src/HOL/Tools/refute.ML
author webertj
Wed May 26 18:52:18 2004 +0200 (2004-05-26)
changeset 14810 4b4b97d29370
parent 14807 e8ccb13d7774
child 14818 ad83019a66a4
permissions -rw-r--r--
adjusted for different signature of Type.typ_instance
     1 (*  Title:      HOL/Tools/refute.ML
     2     ID:         $Id$
     3     Author:     Tjark Weber
     4     Copyright   2003-2004
     5 
     6 Finite model generation for HOL formulae, using a SAT solver.
     7 *)
     8 
     9 (* TODO: case, rec, size for IDTs are not supported yet      *)
    10 
    11 (* ------------------------------------------------------------------------- *)
    12 (* Declares the 'REFUTE' signature as well as a structure 'Refute'.          *)
    13 (* Documentation is available in the Isabelle/Isar theory 'HOL/Refute.thy'.  *)
    14 (* ------------------------------------------------------------------------- *)
    15 
    16 signature REFUTE =
    17 sig
    18 
    19 	exception REFUTE of string * string
    20 
    21 (* ------------------------------------------------------------------------- *)
    22 (* Model/interpretation related code (translation HOL -> propositional logic *)
    23 (* ------------------------------------------------------------------------- *)
    24 
    25 	type params
    26 	type interpretation
    27 	type model
    28 	type arguments
    29 
    30 	exception CANNOT_INTERPRET of Term.term
    31 	exception MAXVARS_EXCEEDED
    32 
    33 	val add_interpreter : string -> (theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option) -> theory -> theory
    34 	val add_printer     : string -> (theory -> model -> Term.term -> interpretation -> (int -> bool) -> Term.term option) -> theory -> theory
    35 
    36 	val interpret : theory -> model -> arguments -> Term.term -> (interpretation * model * arguments)  (* exception CANNOT_INTERPRET *)
    37 
    38 	val print       : theory -> model -> Term.term -> interpretation -> (int -> bool) -> Term.term
    39 	val print_model : theory -> model -> (int -> bool) -> string
    40 
    41 (* ------------------------------------------------------------------------- *)
    42 (* Interface                                                                 *)
    43 (* ------------------------------------------------------------------------- *)
    44 
    45 	val set_default_param  : (string * string) -> theory -> theory
    46 	val get_default_param  : theory -> string -> string option
    47 	val get_default_params : theory -> (string * string) list
    48 	val actual_params      : theory -> (string * string) list -> params
    49 
    50 	val find_model : theory -> params -> Term.term -> bool -> unit
    51 
    52 	val satisfy_term   : theory -> (string * string) list -> Term.term -> unit  (* tries to find a model for a formula *)
    53 	val refute_term    : theory -> (string * string) list -> Term.term -> unit  (* tries to find a model that refutes a formula *)
    54 	val refute_subgoal : theory -> (string * string) list -> Thm.thm -> int -> unit
    55 
    56 	val setup : (theory -> theory) list
    57 end;
    58 
    59 structure Refute : REFUTE =
    60 struct
    61 
    62 	open PropLogic;
    63 
    64 	(* We use 'REFUTE' only for internal error conditions that should    *)
    65 	(* never occur in the first place (i.e. errors caused by bugs in our *)
    66 	(* code).  Otherwise (e.g. to indicate invalid input data) we use    *)
    67 	(* 'error'.                                                          *)
    68 	exception REFUTE of string * string;  (* ("in function", "cause") *)
    69 
    70 	exception CANNOT_INTERPRET of Term.term;
    71 
    72 	(* should be raised by an interpreter when more variables would be *)
    73 	(* required than allowed by 'maxvars'                              *)
    74 	exception MAXVARS_EXCEEDED;
    75 
    76 (* ------------------------------------------------------------------------- *)
    77 (* TREES                                                                     *)
    78 (* ------------------------------------------------------------------------- *)
    79 
    80 (* ------------------------------------------------------------------------- *)
    81 (* tree: implements an arbitrarily (but finitely) branching tree as a list   *)
    82 (*       of (lists of ...) elements                                          *)
    83 (* ------------------------------------------------------------------------- *)
    84 
    85 	datatype 'a tree =
    86 		  Leaf of 'a
    87 		| Node of ('a tree) list;
    88 
    89 	(* ('a -> 'b) -> 'a tree -> 'b tree *)
    90 
    91 	fun tree_map f tr =
    92 		case tr of
    93 		  Leaf x  => Leaf (f x)
    94 		| Node xs => Node (map (tree_map f) xs);
    95 
    96 	(* ('a * 'b -> 'a) -> 'a * ('b tree) -> 'a *)
    97 
    98 	fun tree_foldl f =
    99 	let
   100 		fun itl (e, Leaf x)  = f(e,x)
   101 		  | itl (e, Node xs) = foldl (tree_foldl f) (e,xs)
   102 	in
   103 		itl
   104 	end;
   105 
   106 	(* 'a tree * 'b tree -> ('a * 'b) tree *)
   107 
   108 	fun tree_pair (t1,t2) =
   109 		case t1 of
   110 		  Leaf x =>
   111 			(case t2 of
   112 				  Leaf y => Leaf (x,y)
   113 				| Node _ => raise REFUTE ("tree_pair", "trees are of different height (second tree is higher)"))
   114 		| Node xs =>
   115 			(case t2 of
   116 				  (* '~~' will raise an exception if the number of branches in   *)
   117 				  (* both trees is different at the current node                 *)
   118 				  Node ys => Node (map tree_pair (xs ~~ ys))
   119 				| Leaf _  => raise REFUTE ("tree_pair", "trees are of different height (first tree is higher)"));
   120 
   121 
   122 (* ------------------------------------------------------------------------- *)
   123 (* params: parameters that control the translation into a propositional      *)
   124 (*         formula/model generation                                          *)
   125 (*                                                                           *)
   126 (* The following parameters are supported (and required (!), except for      *)
   127 (* "sizes"):                                                                 *)
   128 (*                                                                           *)
   129 (* Name          Type    Description                                         *)
   130 (*                                                                           *)
   131 (* "sizes"       (string * int) list                                         *)
   132 (*                       Size of ground types (e.g. 'a=2), or depth of IDTs. *)
   133 (* "minsize"     int     If >0, minimal size of each ground type/IDT depth.  *)
   134 (* "maxsize"     int     If >0, maximal size of each ground type/IDT depth.  *)
   135 (* "maxvars"     int     If >0, use at most 'maxvars' Boolean variables      *)
   136 (*                       when transforming the term into a propositional     *)
   137 (*                       formula.                                            *)
   138 (* "maxtime"     int     If >0, terminate after at most 'maxtime' seconds.   *)
   139 (* "satsolver"   string  SAT solver to be used.                              *)
   140 (* ------------------------------------------------------------------------- *)
   141 
   142 	type params =
   143 		{
   144 			sizes    : (string * int) list,
   145 			minsize  : int,
   146 			maxsize  : int,
   147 			maxvars  : int,
   148 			maxtime  : int,
   149 			satsolver: string
   150 		};
   151 
   152 (* ------------------------------------------------------------------------- *)
   153 (* interpretation: a term's interpretation is given by a variable of type    *)
   154 (*                 'interpretation'                                          *)
   155 (* ------------------------------------------------------------------------- *)
   156 
   157 	type interpretation =
   158 		prop_formula list tree;
   159 
   160 (* ------------------------------------------------------------------------- *)
   161 (* model: a model specifies the size of types and the interpretation of      *)
   162 (*        terms                                                              *)
   163 (* ------------------------------------------------------------------------- *)
   164 
   165 	type model =
   166 		(Term.typ * int) list * (Term.term * interpretation) list;
   167 
   168 (* ------------------------------------------------------------------------- *)
   169 (* arguments: additional arguments required during interpretation of terms   *)
   170 (* ------------------------------------------------------------------------- *)
   171 
   172 	type arguments =
   173 		{
   174 			(* just passed unchanged from 'params' *)
   175 			maxvars   : int,
   176 			(* these may change during the translation *)
   177 			next_idx  : int,
   178 			bounds    : interpretation list,
   179 			wellformed: prop_formula
   180 		};
   181 
   182 
   183 	structure RefuteDataArgs =
   184 	struct
   185 		val name = "HOL/refute";
   186 		type T =
   187 			{interpreters: (string * (theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option)) list,
   188 			 printers: (string * (theory -> model -> Term.term -> interpretation -> (int -> bool) -> Term.term option)) list,
   189 			 parameters: string Symtab.table};
   190 		val empty = {interpreters = [], printers = [], parameters = Symtab.empty};
   191 		val copy = I;
   192 		val prep_ext = I;
   193 		fun merge
   194 			({interpreters = in1, printers = pr1, parameters = pa1},
   195 			 {interpreters = in2, printers = pr2, parameters = pa2}) =
   196 			{interpreters = rev (merge_alists (rev in1) (rev in2)),
   197 			 printers = rev (merge_alists (rev pr1) (rev pr2)),
   198 			 parameters = Symtab.merge (op=) (pa1, pa2)};
   199 		fun print sg {interpreters, printers, parameters} =
   200 			Pretty.writeln (Pretty.chunks
   201 				[Pretty.strs ("default parameters:" :: flat (map (fn (name,value) => [name, "=", value]) (Symtab.dest parameters))),
   202 				 Pretty.strs ("interpreters:" :: map fst interpreters),
   203 				 Pretty.strs ("printers:" :: map fst printers)]);
   204 	end;
   205 
   206 	structure RefuteData = TheoryDataFun(RefuteDataArgs);
   207 
   208 
   209 (* ------------------------------------------------------------------------- *)
   210 (* interpret: tries to interpret the term 't' using a suitable interpreter;  *)
   211 (*            returns the interpretation and a (possibly extended) model     *)
   212 (*            that keeps track of the interpretation of subterms             *)
   213 (* Note: exception 'CANNOT_INTERPRET t' is raised if the term cannot be      *)
   214 (*       interpreted by any interpreter                                      *)
   215 (* ------------------------------------------------------------------------- *)
   216 
   217 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) *)
   218 
   219 	fun interpret thy model args t =
   220 		(case get_first (fn (_, f) => f thy model args t) (#interpreters (RefuteData.get thy)) of
   221 		  None   => raise (CANNOT_INTERPRET t)
   222 		| Some x => x);
   223 
   224 (* ------------------------------------------------------------------------- *)
   225 (* print: tries to convert the constant denoted by the term 't' into a term  *)
   226 (*        using a suitable printer                                           *)
   227 (* ------------------------------------------------------------------------- *)
   228 
   229 	(* theory -> model -> Term.term -> interpretation -> (int -> bool) -> Term.term *)
   230 
   231 	fun print thy model t intr assignment =
   232 		(case get_first (fn (_, f) => f thy model t intr assignment) (#printers (RefuteData.get thy)) of
   233 		  None   => Const ("<<no printer available>>", fastype_of t)
   234 		| Some x => x);
   235 
   236 (* ------------------------------------------------------------------------- *)
   237 (* print_model: turns the model into a string, using a fixed interpretation  *)
   238 (*              (given by an assignment for Boolean variables) and suitable  *)
   239 (*              printers                                                     *)
   240 (* ------------------------------------------------------------------------- *)
   241 
   242 	(* theory -> model -> (int -> bool) -> string *)
   243 
   244 	fun print_model thy model assignment =
   245 	let
   246 		val (typs, terms) = model
   247 		val typs_msg =
   248 			if null typs then
   249 				"empty universe (no type variables in term)\n"
   250 			else
   251 				"Size of types: " ^ commas (map (fn (T,i) => Sign.string_of_typ (sign_of thy) T ^ ": " ^ string_of_int i) typs) ^ "\n"
   252 		val show_consts_msg =
   253 			if not (!show_consts) andalso Library.exists (is_Const o fst) terms then
   254 				"set \"show_consts\" to show the interpretation of constants\n"
   255 			else
   256 				""
   257 		val terms_msg =
   258 			if null terms then
   259 				"empty interpretation (no free variables in term)\n"
   260 			else
   261 				space_implode "\n" (mapfilter (fn (t,intr) =>
   262 					(* print constants only if 'show_consts' is true *)
   263 					if (!show_consts) orelse not (is_Const t) then
   264 						Some (Sign.string_of_term (sign_of thy) t ^ ": " ^ Sign.string_of_term (sign_of thy) (print thy model t intr assignment))
   265 					else
   266 						None) terms) ^ "\n"
   267 	in
   268 		typs_msg ^ show_consts_msg ^ terms_msg
   269 	end;
   270 
   271 
   272 (* ------------------------------------------------------------------------- *)
   273 (* PARAMETER MANAGEMENT                                                      *)
   274 (* ------------------------------------------------------------------------- *)
   275 
   276 	(* string -> (theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option) -> theory -> theory *)
   277 
   278 	fun add_interpreter name f thy =
   279 	let
   280 		val {interpreters, printers, parameters} = RefuteData.get thy
   281 	in
   282 		case assoc (interpreters, name) of
   283 		  None   => RefuteData.put {interpreters = (name, f) :: interpreters, printers = printers, parameters = parameters} thy
   284 		| Some _ => error ("Interpreter " ^ name ^ " already declared")
   285 	end;
   286 
   287 	(* string -> (theory -> model -> Term.term -> interpretation -> (int -> bool) -> Term.term option) -> theory -> theory *)
   288 
   289 	fun add_printer name f thy =
   290 	let
   291 		val {interpreters, printers, parameters} = RefuteData.get thy
   292 	in
   293 		case assoc (printers, name) of
   294 		  None   => RefuteData.put {interpreters = interpreters, printers = (name, f) :: printers, parameters = parameters} thy
   295 		| Some _ => error ("Printer " ^ name ^ " already declared")
   296 	end;
   297 
   298 (* ------------------------------------------------------------------------- *)
   299 (* set_default_param: stores the '(name, value)' pair in RefuteData's        *)
   300 (*                    parameter table                                        *)
   301 (* ------------------------------------------------------------------------- *)
   302 
   303 	(* (string * string) -> theory -> theory *)
   304 
   305 	fun set_default_param (name, value) thy =
   306 	let
   307 		val {interpreters, printers, parameters} = RefuteData.get thy
   308 	in
   309 		case Symtab.lookup (parameters, name) of
   310 		  None   => RefuteData.put
   311 			{interpreters = interpreters, printers = printers, parameters = Symtab.extend (parameters, [(name, value)])} thy
   312 		| Some _ => RefuteData.put
   313 			{interpreters = interpreters, printers = printers, parameters = Symtab.update ((name, value), parameters)} thy
   314 	end;
   315 
   316 (* ------------------------------------------------------------------------- *)
   317 (* get_default_param: retrieves the value associated with 'name' from        *)
   318 (*                    RefuteData's parameter table                           *)
   319 (* ------------------------------------------------------------------------- *)
   320 
   321 	(* theory -> string -> string option *)
   322 
   323 	fun get_default_param thy name = Symtab.lookup ((#parameters o RefuteData.get) thy, name);
   324 
   325 (* ------------------------------------------------------------------------- *)
   326 (* get_default_params: returns a list of all '(name, value)' pairs that are  *)
   327 (*                     stored in RefuteData's parameter table                *)
   328 (* ------------------------------------------------------------------------- *)
   329 
   330 	(* theory -> (string * string) list *)
   331 
   332 	fun get_default_params thy = (Symtab.dest o #parameters o RefuteData.get) thy;
   333 
   334 (* ------------------------------------------------------------------------- *)
   335 (* actual_params: takes a (possibly empty) list 'params' of parameters that  *)
   336 (*      override the default parameters currently specified in 'thy', and    *)
   337 (*      returns a record that can be passed to 'find_model'.                 *)
   338 (* ------------------------------------------------------------------------- *)
   339 
   340 	(* theory -> (string * string) list -> params *)
   341 
   342 	fun actual_params thy override =
   343 	let
   344 		(* (string * string) list * string -> int *)
   345 		fun read_int (parms, name) =
   346 			case assoc_string (parms, name) of
   347 			  Some s => (case Int.fromString s of
   348 				  SOME i => i
   349 				| NONE   => error ("parameter " ^ quote name ^ " (value is " ^ quote s ^ ") must be an integer value"))
   350 			| None   => error ("parameter " ^ quote name ^ " must be assigned a value")
   351 		(* (string * string) list * string -> string *)
   352 		fun read_string (parms, name) =
   353 			case assoc_string (parms, name) of
   354 			  Some s => s
   355 			| None   => error ("parameter " ^ quote name ^ " must be assigned a value")
   356 		(* (string * string) list *)
   357 		val allparams = override @ (get_default_params thy)  (* 'override' first, defaults last *)
   358 		(* int *)
   359 		val minsize   = read_int (allparams, "minsize")
   360 		val maxsize   = read_int (allparams, "maxsize")
   361 		val maxvars   = read_int (allparams, "maxvars")
   362       val maxtime   = read_int (allparams, "maxtime")
   363 		(* string *)
   364 		val satsolver = read_string (allparams, "satsolver")
   365 		(* all remaining parameters of the form "string=int" are collected in  *)
   366 		(* 'sizes'                                                             *)
   367 		(* TODO: it is currently not possible to specify a size for a type     *)
   368 		(*       whose name is one of the other parameters (e.g. 'maxvars')    *)
   369 		(* (string * int) list *)
   370 		val sizes     = mapfilter
   371 			(fn (name,value) => (case Int.fromString value of SOME i => Some (name, i) | NONE => None))
   372 			(filter (fn (name,_) => name<>"minsize" andalso name<>"maxsize" andalso name<>"maxvars" andalso name<>"maxtime" andalso name<>"satsolver")
   373 				allparams)
   374 	in
   375 		{sizes=sizes, minsize=minsize, maxsize=maxsize, maxvars=maxvars, maxtime=maxtime, satsolver=satsolver}
   376 	end;
   377 
   378 
   379 (* ------------------------------------------------------------------------- *)
   380 (* TRANSLATION HOL -> PROPOSITIONAL LOGIC, BOOLEAN ASSIGNMENT -> MODEL       *)
   381 (* ------------------------------------------------------------------------- *)
   382 
   383 (* ------------------------------------------------------------------------- *)
   384 (* collect_axioms: collects (monomorphic, universally quantified versions    *)
   385 (*                 of) all HOL axioms that are relevant w.r.t 't'            *)
   386 (* ------------------------------------------------------------------------- *)
   387 
   388 	(* TODO: to make the collection of axioms more easily extensible, this    *)
   389 	(*       function could be based on user-supplied "axiom collectors",     *)
   390 	(*       similar to 'interpret'/interpreters or 'print'/printers          *)
   391 
   392 	(* theory -> Term.term -> Term.term list *)
   393 
   394 	(* Which axioms are "relevant" for a particular term/type goes hand in    *)
   395 	(* hand with the interpretation of that term/type by its interpreter (see *)
   396 	(* way below): if the interpretation respects an axiom anyway, the axiom  *)
   397 	(* does not need to be added as a constraint here.                        *)
   398 
   399 	(* When an axiom is added as relevant, further axioms may need to be      *)
   400 	(* added as well (e.g. when a constant is defined in terms of other       *)
   401 	(* constants).  To avoid infinite recursion (which should not happen for  *)
   402 	(* constants anyway, but it could happen for "typedef"-related axioms,    *)
   403 	(* since they contain the type again), we use an accumulator 'axs' and    *)
   404 	(* add a relevant axiom only if it is not in 'axs' yet.                   *)
   405 
   406 	fun collect_axioms thy t =
   407 	let
   408 		val _ = std_output "Adding axioms..."
   409 		(* (string * Term.term) list *)
   410 		val axioms = flat (map (Symtab.dest o #axioms o Theory.rep_theory) (thy :: Theory.ancestors_of thy))
   411 		(* given a constant 's' of type 'T', which is a subterm of 't', where  *)
   412 		(* 't' has a (possibly) more general type, the schematic type          *)
   413 		(* variables in 't' are instantiated to match the type 'T'             *)
   414 		(* (string * Term.typ) * Term.term -> Term.term *)
   415 		fun specialize_type ((s, T), t) =
   416 		let
   417 			fun find_typeSubs (Const (s', T')) =
   418 				(if s=s' then
   419 					Some (Type.typ_match (Sign.tsig_of (sign_of thy)) (Vartab.empty, (T', T)))
   420 				else
   421 					None
   422 				handle Type.TYPE_MATCH => None)
   423 			  | find_typeSubs (Free _)           = None
   424 			  | find_typeSubs (Var _)            = None
   425 			  | find_typeSubs (Bound _)          = None
   426 			  | find_typeSubs (Abs (_, _, body)) = find_typeSubs body
   427 			  | find_typeSubs (t1 $ t2)          = (case find_typeSubs t1 of Some x => Some x | None => find_typeSubs t2)
   428 			val typeSubs = (case find_typeSubs t of
   429 				  Some x => x
   430 				| None   => raise REFUTE ("collect_axioms", "no type instantiation found for " ^ quote s ^ " in " ^ Sign.string_of_term (sign_of thy) t))
   431 		in
   432 			map_term_types
   433 				(map_type_tvar
   434 					(fn (v,_) =>
   435 						case Vartab.lookup (typeSubs, v) of
   436 						  None =>
   437 							(* schematic type variable not instantiated *)
   438 							raise REFUTE ("collect_axioms", "term " ^ Sign.string_of_term (sign_of thy) t ^ " still has a polymorphic type (after instantiating type of " ^ quote s ^ ")")
   439 						| Some typ =>
   440 							typ))
   441 					t
   442 		end
   443 		(* Term.term list * Term.typ -> Term.term list *)
   444 		fun collect_type_axioms (axs, T) =
   445 			case T of
   446 			(* simple types *)
   447 			  Type ("prop", [])      => axs
   448 			| Type ("fun", [T1, T2]) => collect_type_axioms (collect_type_axioms (axs, T1), T2)
   449 			| Type ("set", [T1])     => collect_type_axioms (axs, T1)
   450 			| Type (s, Ts)           =>
   451 				let
   452 					(* look up the definition of a type, as created by "typedef" *)
   453 					(* (string * Term.term) list -> (string * Term.term) option *)
   454 					fun get_typedefn [] =
   455 						None
   456 					  | get_typedefn ((axname,ax)::axms) =
   457 						(let
   458 							(* Term.term -> Term.typ option *)
   459 							fun type_of_type_definition (Const (s', T')) =
   460 								if s'="Typedef.type_definition" then
   461 									Some T'
   462 								else
   463 									None
   464 							  | type_of_type_definition (Free _)           = None
   465 							  | type_of_type_definition (Var _)            = None
   466 							  | type_of_type_definition (Bound _)          = None
   467 							  | type_of_type_definition (Abs (_, _, body)) = type_of_type_definition body
   468 							  | type_of_type_definition (t1 $ t2)          = (case type_of_type_definition t1 of Some x => Some x | None => type_of_type_definition t2)
   469 						in
   470 							case type_of_type_definition ax of
   471 							  Some T' =>
   472 								let
   473 									val T''      = (domain_type o domain_type) T'
   474 									val typeSubs = Type.typ_match (Sign.tsig_of (sign_of thy)) (Vartab.empty, (T'', T))
   475 									val unvar_ax = map_term_types
   476 										(map_type_tvar
   477 											(fn (v,_) =>
   478 												case Vartab.lookup (typeSubs, v) of
   479 												  None =>
   480 													(* schematic type variable not instantiated *)
   481 													raise ERROR
   482 												| Some typ =>
   483 													typ))
   484 										ax
   485 								in
   486 									Some (axname, unvar_ax)
   487 								end
   488 							| None =>
   489 								get_typedefn axms
   490 						end
   491 						handle ERROR           => get_typedefn axms
   492 						     | MATCH           => get_typedefn axms
   493 						     | Type.TYPE_MATCH => get_typedefn axms)
   494 				in
   495 					case DatatypePackage.datatype_info thy s of
   496 					  Some info =>  (* inductive datatype *)
   497 							(* only collect relevant type axioms for the argument types *)
   498 							foldl collect_type_axioms (axs, Ts)
   499 					| None =>
   500 						(case get_typedefn axioms of
   501 						  Some (axname, ax) => 
   502 							if mem_term (ax, axs) then
   503 								(* collect relevant type axioms for the argument types *)
   504 								foldl collect_type_axioms (axs, Ts)
   505 							else
   506 								(std_output (" " ^ axname);
   507 								collect_term_axioms (ax :: axs, ax))
   508 						| None =>
   509 							(* at least collect relevant type axioms for the argument types *)
   510 							foldl collect_type_axioms (axs, Ts))
   511 				end
   512 			(* TODO: include sort axioms *)
   513 			| TFree (_, sorts)       => ((*if not (null sorts) then std_output " *ignoring sorts*" else ();*) axs)
   514 			| TVar  (_, sorts)       => ((*if not (null sorts) then std_output " *ignoring sorts*" else ();*) axs)
   515 		(* Term.term list * Term.term -> Term.term list *)
   516 		and collect_term_axioms (axs, t) =
   517 			case t of
   518 			(* Pure *)
   519 			  Const ("all", _)                => axs
   520 			| Const ("==", _)                 => axs
   521 			| Const ("==>", _)                => axs
   522 			(* HOL *)
   523 			| Const ("Trueprop", _)           => axs
   524 			| Const ("Not", _)                => axs
   525 			| Const ("True", _)               => axs  (* redundant, since 'True' is also an IDT constructor *)
   526 			| Const ("False", _)              => axs  (* redundant, since 'False' is also an IDT constructor *)
   527 			| Const ("arbitrary", T)          => collect_type_axioms (axs, T)
   528 			| Const ("The", T)                =>
   529 				let
   530 					val ax = specialize_type (("The", T), (the o assoc) (axioms, "HOL.the_eq_trivial"))
   531 				in
   532 					if mem_term (ax, axs) then
   533 						collect_type_axioms (axs, T)
   534 					else
   535 						(std_output " HOL.the_eq_trivial";
   536 						collect_term_axioms (ax :: axs, ax))
   537 				end
   538 			| Const ("Hilbert_Choice.Eps", T) =>
   539 				let
   540 					val ax = specialize_type (("Hilbert_Choice.Eps", T), (the o assoc) (axioms, "Hilbert_Choice.someI"))
   541 				in
   542 					if mem_term (ax, axs) then
   543 						collect_type_axioms (axs, T)
   544 					else
   545 						(std_output " Hilbert_Choice.someI";
   546 						collect_term_axioms (ax :: axs, ax))
   547 				end
   548 			| Const ("All", _) $ t1           => collect_term_axioms (axs, t1)
   549 			| Const ("Ex", _) $ t1            => collect_term_axioms (axs, t1)
   550 			| Const ("op =", T)               => collect_type_axioms (axs, T)
   551 			| Const ("op &", _)               => axs
   552 			| Const ("op |", _)               => axs
   553 			| Const ("op -->", _)             => axs
   554 			(* sets *)
   555 			| Const ("Collect", T)            => collect_type_axioms (axs, T)
   556 			| Const ("op :", T)               => collect_type_axioms (axs, T)
   557 			(* other optimizations *)
   558 			| Const ("Finite_Set.card", T)    => collect_type_axioms (axs, T)
   559 			(* simply-typed lambda calculus *)
   560 			| Const (s, T)                    =>
   561 				let
   562 					(* look up the definition of a constant, as created by "constdefs" *)
   563 					(* string -> Term.typ -> (string * Term.term) list -> (string * Term.term) option *)
   564 					fun get_defn [] =
   565 						None
   566 					  | get_defn ((axname,ax)::axms) =
   567 						(let
   568 							val (lhs, _) = Logic.dest_equals ax  (* equations only *)
   569 							val c        = head_of lhs
   570 							val (s', T') = dest_Const c
   571 						in
   572 							if s=s' then
   573 								let
   574 									val typeSubs = Type.typ_match (Sign.tsig_of (sign_of thy)) (Vartab.empty, (T', T))
   575 									val unvar_ax = map_term_types
   576 										(map_type_tvar
   577 											(fn (v,_) =>
   578 												case Vartab.lookup (typeSubs, v) of
   579 												  None =>
   580 													(* schematic type variable not instantiated *)
   581 													raise ERROR
   582 												| Some typ =>
   583 													typ))
   584 										ax
   585 								in
   586 									Some (axname, unvar_ax)
   587 								end
   588 							else
   589 								get_defn axms
   590 						end
   591 						handle ERROR           => get_defn axms
   592 						     | TERM _          => get_defn axms
   593 						     | Type.TYPE_MATCH => get_defn axms)
   594 						(* unit -> bool *)
   595 						fun is_IDT_constructor () =
   596 							(case body_type T of
   597 							  Type (s', _) =>
   598 								(case DatatypePackage.constrs_of thy s' of
   599 								  Some constrs =>
   600 									Library.exists (fn c =>
   601 										(case c of
   602 										  Const (cname, ctype) =>
   603 											cname = s andalso Type.typ_instance (Sign.tsig_of (sign_of thy)) (T, ctype)
   604 										| _ =>
   605 											raise REFUTE ("collect_axioms", "IDT constructor is not a constant")))
   606 										constrs
   607 								| None =>
   608 									false)
   609 							| _  =>
   610 								false)
   611 						(* unit -> bool *)
   612 						fun is_IDT_recursor () =
   613 							(* the type of a recursion operator: [T1,...,Tn,IDT]--->TResult (where *)
   614 							(* the T1,...,Tn depend on the types of the datatype's constructors)   *)
   615 							((case last_elem (binder_types T) of
   616 							  Type (s', _) =>
   617 								(case DatatypePackage.datatype_info thy s' of
   618 								  Some info =>
   619 									(* TODO: I'm not quite sute if comparing the names is sufficient, or if *)
   620 									(*       we should also check the type                                  *)
   621 									s mem (#rec_names info)
   622 								| None =>  (* not an inductive datatype *)
   623 									false)
   624 							| _ =>  (* a (free or schematic) type variable *)
   625 								false)
   626 							handle LIST "last_elem" => false)  (* not even a function type *)
   627 				in
   628 					if is_IDT_constructor () orelse is_IDT_recursor () then
   629 						(* only collect relevant type axioms *)
   630 						collect_type_axioms (axs, T)
   631 					else
   632 						(case get_defn axioms of
   633 						  Some (axname, ax) => 
   634 							if mem_term (ax, axs) then
   635 								(* collect relevant type axioms *)
   636 								collect_type_axioms (axs, T)
   637 							else
   638 								(std_output (" " ^ axname);
   639 								collect_term_axioms (ax :: axs, ax))
   640 						| None =>
   641 							(* collect relevant type axioms *)
   642 							collect_type_axioms (axs, T))
   643 				end
   644 			| Free (_, T)                     => collect_type_axioms (axs, T)
   645 			| Var (_, T)                      => collect_type_axioms (axs, T)
   646 			| Bound i                         => axs
   647 			| Abs (_, T, body)                => collect_term_axioms (collect_type_axioms (axs, T), body)
   648 			| t1 $ t2                         => collect_term_axioms (collect_term_axioms (axs, t1), t2)
   649 		(* universal closure over schematic variables *)
   650 		(* Term.term -> Term.term *)
   651 		fun close_form t =
   652 		let
   653 			(* (Term.indexname * Term.typ) list *)
   654 			val vars = sort_wrt (fst o fst) (map dest_Var (term_vars t))
   655 		in
   656 			foldl
   657 				(fn (t', ((x,i),T)) => (Term.all T) $ Abs (x, T, abstract_over (Var((x,i),T), t')))
   658 				(t, vars)
   659 		end
   660 		(* Term.term list *)
   661 		val result = map close_form (collect_term_axioms ([], t))
   662 		val _ = writeln " ...done."
   663 	in
   664 		result
   665 	end;
   666 
   667 (* ------------------------------------------------------------------------- *)
   668 (* ground_types: collects all ground types in a term (including argument     *)
   669 (*               types of other types), suppressing duplicates.  Does not    *)
   670 (*               return function types, set types, non-recursive IDTs, or    *)
   671 (*               'propT'.  For IDTs, also the argument types of constructors *)
   672 (*               are considered.                                             *)
   673 (* ------------------------------------------------------------------------- *)
   674 
   675 	(* theory -> Term.term -> Term.typ list *)
   676 
   677 	fun ground_types thy t =
   678 	let
   679 		(* Term.typ * Term.typ list -> Term.typ list *)
   680 		fun collect_types (T, acc) =
   681 			if T mem acc then
   682 				acc  (* prevent infinite recursion (for IDTs) *)
   683 			else
   684 				(case T of
   685 				  Type ("fun", [T1, T2]) => collect_types (T1, collect_types (T2, acc))
   686 				| Type ("prop", [])      => acc
   687 				| Type ("set", [T1])     => collect_types (T1, acc)
   688 				| Type (s, Ts)           =>
   689 					(case DatatypePackage.datatype_info thy s of
   690 					  Some info =>  (* inductive datatype *)
   691 						let
   692 							val index               = #index info
   693 							val descr               = #descr info
   694 							val (_, dtyps, constrs) = (the o assoc) (descr, index)
   695 							val typ_assoc           = dtyps ~~ Ts
   696 							(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
   697 							val _ = (if Library.exists (fn d =>
   698 									case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
   699 								then
   700 									raise REFUTE ("ground_types", "datatype argument (for type " ^ Sign.string_of_typ (sign_of thy) (Type (s, Ts)) ^ ") is not a variable")
   701 								else
   702 									())
   703 							(* DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list -> DatatypeAux.dtyp -> Term.typ *)
   704 							fun typ_of_dtyp descr typ_assoc (DatatypeAux.DtTFree a) =
   705 								(* replace a 'DtTFree' variable by the associated type *)
   706 								(the o assoc) (typ_assoc, DatatypeAux.DtTFree a)
   707 							  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtRec i) =
   708 								let
   709 									val (s, ds, _) = (the o assoc) (descr, i)
   710 								in
   711 									Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   712 								end
   713 							  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtType (s, ds)) =
   714 								Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   715 							(* if the current type is a recursive IDT (i.e. a depth is required), add it to 'acc' *)
   716 							val acc' = (if Library.exists (fn (_, ds) => Library.exists DatatypeAux.is_rec_type ds) constrs then
   717 									T ins acc
   718 								else
   719 									acc)
   720 							(* collect argument types *)
   721 							val acc_args = foldr collect_types (Ts, acc')
   722 							(* collect constructor types *)
   723 							val acc_constrs = foldr collect_types (flat (map (fn (_, ds) => map (typ_of_dtyp descr typ_assoc) ds) constrs), acc_args)
   724 						in
   725 							acc_constrs
   726 						end
   727 					| None =>  (* not an inductive datatype, e.g. defined via "typedef" or "typedecl" *)
   728 						T ins (foldr collect_types (Ts, acc)))
   729 				| TFree _                => T ins acc
   730 				| TVar _                 => T ins acc)
   731 	in
   732 		it_term_types collect_types (t, [])
   733 	end;
   734 
   735 (* ------------------------------------------------------------------------- *)
   736 (* string_of_typ: (rather naive) conversion from types to strings, used to   *)
   737 (*                look up the size of a type in 'sizes'.  Parameterized      *)
   738 (*                types with different parameters (e.g. "'a list" vs. "bool  *)
   739 (*                list") are identified.                                     *)
   740 (* ------------------------------------------------------------------------- *)
   741 
   742 	(* Term.typ -> string *)
   743 
   744 	fun string_of_typ (Type (s, _))     = s
   745 	  | string_of_typ (TFree (s, _))    = s
   746 	  | string_of_typ (TVar ((s,_), _)) = s;
   747 
   748 (* ------------------------------------------------------------------------- *)
   749 (* first_universe: returns the "first" (i.e. smallest) universe by assigning *)
   750 (*                 'minsize' to every type for which no size is specified in *)
   751 (*                 'sizes'                                                   *)
   752 (* ------------------------------------------------------------------------- *)
   753 
   754 	(* Term.typ list -> (string * int) list -> int -> (Term.typ * int) list *)
   755 
   756 	fun first_universe xs sizes minsize =
   757 	let
   758 		fun size_of_typ T =
   759 			case assoc (sizes, string_of_typ T) of
   760 			  Some n => n
   761 			| None   => minsize
   762 	in
   763 		map (fn T => (T, size_of_typ T)) xs
   764 	end;
   765 
   766 (* ------------------------------------------------------------------------- *)
   767 (* next_universe: enumerates all universes (i.e. assignments of sizes to     *)
   768 (*                types), where the minimal size of a type is given by       *)
   769 (*                'minsize', the maximal size is given by 'maxsize', and a   *)
   770 (*                type may have a fixed size given in 'sizes'                *)
   771 (* ------------------------------------------------------------------------- *)
   772 
   773 	(* (Term.typ * int) list -> (string * int) list -> int -> int -> (Term.typ * int) list option *)
   774 
   775 	fun next_universe xs sizes minsize maxsize =
   776 	let
   777 		(* int -> int list -> int list option *)
   778 		fun add1 _ [] =
   779 			None  (* overflow *)
   780 		  | add1 max (x::xs) =
   781 		 	if x<max orelse max<0 then
   782 				Some ((x+1)::xs)  (* add 1 to the head *)
   783 			else
   784 				apsome (fn xs' => 0 :: xs') (add1 max xs)  (* carry-over *)
   785 		(* int -> int list * int list -> int list option *)
   786 		fun shift _ (_, []) =
   787 			None
   788 		  | shift max (zeros, x::xs) =
   789 			if x=0 then
   790 				shift max (0::zeros, xs)
   791 			else
   792 				apsome (fn xs' => (x-1) :: (zeros @ xs')) (add1 max xs)
   793 		(* creates the "first" list of length 'len', where the sum of all list *)
   794 		(* elements is 'sum', and the length of the list is 'len'              *)
   795 		(* int -> int -> int -> int list option *)
   796 		fun make_first 0 sum _ =
   797 			if sum=0 then
   798 				Some []
   799 			else
   800 				None
   801 		  | make_first len sum max =
   802 			if sum<=max orelse max<0 then
   803 				apsome (fn xs' => sum :: xs') (make_first (len-1) 0 max)
   804 			else
   805 				apsome (fn xs' => max :: xs') (make_first (len-1) (sum-max) max)
   806 		(* enumerates all int lists with a fixed length, where 0<=x<='max' for *)
   807 		(* all list elements x (unless 'max'<0)                                *)
   808 		(* int -> int list -> int list option *)
   809 		fun next max xs =
   810 			(case shift max ([], xs) of
   811 			  Some xs' =>
   812 				Some xs'
   813 			| None =>
   814 				let
   815 					val (len, sum) = foldl (fn ((l, s), x) => (l+1, s+x)) ((0, 0), xs)
   816 				in
   817 					make_first len (sum+1) max  (* increment 'sum' by 1 *)
   818 				end)
   819 		(* only consider those types for which the size is not fixed *)
   820 		val mutables = filter (fn (T, _) => assoc (sizes, string_of_typ T) = None) xs
   821 		(* subtract 'minsize' from every size (will be added again at the end) *)
   822 		val diffs = map (fn (_, n) => n-minsize) mutables
   823 	in
   824 		case next (maxsize-minsize) diffs of
   825 		  Some diffs' =>
   826 			(* merge with those types for which the size is fixed *)
   827 			Some (snd (foldl_map (fn (ds, (T, _)) =>
   828 				case assoc (sizes, string_of_typ T) of
   829 				  Some n => (ds, (T, n))                      (* return the fixed size *)
   830 				| None   => (tl ds, (T, minsize + (hd ds))))  (* consume the head of 'ds', add 'minsize' *)
   831 				(diffs', xs)))
   832 		| None =>
   833 			None
   834 	end;
   835 
   836 (* ------------------------------------------------------------------------- *)
   837 (* toTrue: converts the interpretation of a Boolean value to a propositional *)
   838 (*         formula that is true iff the interpretation denotes "true"        *)
   839 (* ------------------------------------------------------------------------- *)
   840 
   841 	(* interpretation -> prop_formula *)
   842 
   843 	fun toTrue (Leaf [fm,_]) = fm
   844 	  | toTrue _             = raise REFUTE ("toTrue", "interpretation does not denote a Boolean value");
   845 
   846 (* ------------------------------------------------------------------------- *)
   847 (* toFalse: converts the interpretation of a Boolean value to a              *)
   848 (*          propositional formula that is true iff the interpretation        *)
   849 (*          denotes "false"                                                  *)
   850 (* ------------------------------------------------------------------------- *)
   851 
   852 	(* interpretation -> prop_formula *)
   853 
   854 	fun toFalse (Leaf [_,fm]) = fm
   855 	  | toFalse _             = raise REFUTE ("toFalse", "interpretation does not denote a Boolean value");
   856 
   857 (* ------------------------------------------------------------------------- *)
   858 (* find_model: repeatedly calls 'interpret' with appropriate parameters,     *)
   859 (*             applies a SAT solver, and (in case a model is found) displays *)
   860 (*             the model to the user by calling 'print_model'                *)
   861 (* thy       : the current theory                                            *)
   862 (* {...}     : parameters that control the translation/model generation      *)
   863 (* t         : term to be translated into a propositional formula            *)
   864 (* negate    : if true, find a model that makes 't' false (rather than true) *)
   865 (* Note: exception 'TimeOut' is raised if the algorithm does not terminate   *)
   866 (*       within 'maxtime' seconds (if 'maxtime' >0)                          *)
   867 (* ------------------------------------------------------------------------- *)
   868 
   869 	(* theory -> params -> Term.term -> bool -> unit *)
   870 
   871 	fun find_model thy {sizes, minsize, maxsize, maxvars, maxtime, satsolver} t negate =
   872 	let
   873 		(* unit -> unit *)
   874 		fun wrapper () =
   875 		let
   876 			(* Term.term list *)
   877 			val axioms = collect_axioms thy t
   878 			(* Term.typ list *)
   879 			val types  = foldl (fn (acc, t') => acc union (ground_types thy t')) ([], t :: axioms)
   880 			val _      = writeln ("Ground types: "
   881 				^ (if null types then "none."
   882 				   else commas (map (Sign.string_of_typ (sign_of thy)) types)))
   883 			(* (Term.typ * int) list -> unit *)
   884 			fun find_model_loop universe =
   885 			(let
   886 				val init_model             = (universe, [])
   887 				val init_args              = {maxvars = maxvars, next_idx = 1, bounds = [], wellformed = True}
   888 				val _                      = std_output ("Translating term (sizes: " ^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
   889 				(* translate 't' and all axioms *)
   890 				val ((model, args), intrs) = foldl_map (fn ((m, a), t') =>
   891 					let
   892 						val (i, m', a') = interpret thy m a t'
   893 					in
   894 						((m', a'), i)
   895 					end) ((init_model, init_args), t :: axioms)
   896 				(* make 't' either true or false, and make all axioms true, and *)
   897 				(* add the well-formedness side condition                       *)
   898 				val fm_t  = (if negate then toFalse else toTrue) (hd intrs)
   899 				val fm_ax = PropLogic.all (map toTrue (tl intrs))
   900 				val fm    = PropLogic.all [#wellformed args, fm_ax, fm_t]
   901 			in
   902 				std_output " invoking SAT solver...";
   903 				case SatSolver.invoke_solver satsolver fm of
   904 				  None =>
   905 					error ("SAT solver " ^ quote satsolver ^ " not configured.")
   906 				| Some None =>
   907 					(std_output " no model found.\n";
   908 					case next_universe universe sizes minsize maxsize of
   909 					  Some universe' => find_model_loop universe'
   910 					| None           => writeln "Search terminated, no larger universe within the given limits.")
   911 				| Some (Some assignment) =>
   912 					writeln ("\n*** Model found: ***\n" ^ print_model thy model assignment)
   913 			end handle MAXVARS_EXCEEDED =>
   914 				writeln ("\nSearch terminated, number of Boolean variables (" ^ string_of_int maxvars ^ " allowed) exceeded.")
   915 			| CANNOT_INTERPRET t' =>
   916 				error ("Unable to interpret term " ^ Sign.string_of_term (sign_of thy) t'))
   917 			in
   918 				find_model_loop (first_universe types sizes minsize)
   919 			end
   920 		in
   921 			(* some parameter sanity checks *)
   922 			assert (minsize>=1) ("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
   923 			assert (maxsize>=1) ("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
   924 			assert (maxsize>=minsize) ("\"maxsize\" (=" ^ string_of_int maxsize ^ ") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
   925 			assert (maxvars>=0) ("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
   926 			assert (maxtime>=0) ("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
   927 			(* enter loop with/without time limit *)
   928 			writeln ("Trying to find a model that " ^ (if negate then "refutes" else "satisfies") ^ ": "
   929 				^ Sign.string_of_term (sign_of thy) t);
   930 			if maxtime>0 then
   931 				(* TODO: this only works with SML/NJ *)
   932 				((*TimeLimit.timeLimit (Time.fromSeconds (Int32.fromInt maxtime))*)
   933 					wrapper ()
   934 				(*handle TimeLimit.TimeOut =>
   935 					writeln ("\nSearch terminated, time limit ("
   936 						^ string_of_int maxtime ^ " second"
   937 						^ (if maxtime=1 then "" else "s")
   938 						^ ") exceeded.")*))
   939 			else
   940 				wrapper ()
   941 		end;
   942 
   943 
   944 (* ------------------------------------------------------------------------- *)
   945 (* INTERFACE, PART 2: FINDING A MODEL                                        *)
   946 (* ------------------------------------------------------------------------- *)
   947 
   948 (* ------------------------------------------------------------------------- *)
   949 (* satisfy_term: calls 'find_model' to find a model that satisfies 't'       *)
   950 (* params      : list of '(name, value)' pairs used to override default      *)
   951 (*               parameters                                                  *)
   952 (* ------------------------------------------------------------------------- *)
   953 
   954 	(* theory -> (string * string) list -> Term.term -> unit *)
   955 
   956 	fun satisfy_term thy params t =
   957 		find_model thy (actual_params thy params) t false;
   958 
   959 (* ------------------------------------------------------------------------- *)
   960 (* refute_term: calls 'find_model' to find a model that refutes 't'          *)
   961 (* params     : list of '(name, value)' pairs used to override default       *)
   962 (*              parameters                                                   *)
   963 (* ------------------------------------------------------------------------- *)
   964 
   965 	(* theory -> (string * string) list -> Term.term -> unit *)
   966 
   967 	fun refute_term thy params t =
   968 	let
   969 		(* disallow schematic type variables, since we cannot properly negate  *)
   970 		(* terms containing them (their logical meaning is that there EXISTS a *)
   971 		(* type s.t. ...; to refute such a formula, we would have to show that *)
   972 		(* for ALL types, not ...)                                             *)
   973 		val _ = assert (null (term_tvars t)) "Term to be refuted contains schematic type variables"
   974 		(* existential closure over schematic variables *)
   975 		(* (Term.indexname * Term.typ) list *)
   976 		val vars = sort_wrt (fst o fst) (map dest_Var (term_vars t))
   977 		(* Term.term *)
   978 		val ex_closure = foldl
   979 			(fn (t', ((x,i),T)) => (HOLogic.exists_const T) $ Abs (x, T, abstract_over (Var((x,i),T), t')))
   980 			(t, vars)
   981 		(* If 't' is of type 'propT' (rather than 'boolT'), applying  *)
   982 		(* 'HOLogic.exists_const' is not type-correct.  However, this *)
   983 		(* is not really a problem as long as 'find_model' still      *)
   984 		(* interprets the resulting term correctly, without checking  *)
   985 		(* its type.                                                  *)
   986 	in
   987 		find_model thy (actual_params thy params) ex_closure true
   988 	end;
   989 
   990 (* ------------------------------------------------------------------------- *)
   991 (* refute_subgoal: calls 'refute_term' on a specific subgoal                 *)
   992 (* params        : list of '(name, value)' pairs used to override default    *)
   993 (*                 parameters                                                *)
   994 (* subgoal       : 0-based index specifying the subgoal number               *)
   995 (* ------------------------------------------------------------------------- *)
   996 
   997 	(* theory -> (string * string) list -> Thm.thm -> int -> unit *)
   998 
   999 	fun refute_subgoal thy params thm subgoal =
  1000 		refute_term thy params (nth_elem (subgoal, prems_of thm));
  1001 
  1002 
  1003 (* ------------------------------------------------------------------------- *)
  1004 (* INTERPRETERS                                                              *)
  1005 (* ------------------------------------------------------------------------- *)
  1006 
  1007 (* ------------------------------------------------------------------------- *)
  1008 (* make_constants: returns all interpretations that have the same tree       *)
  1009 (*                 structure as 'intr', but consist of unit vectors with     *)
  1010 (*                 'True'/'False' only (no Boolean variables)                *)
  1011 (* ------------------------------------------------------------------------- *)
  1012 
  1013 	(* interpretation -> interpretation list *)
  1014 
  1015 	fun make_constants intr =
  1016 	let
  1017 		(* returns a list with all unit vectors of length n *)
  1018 		(* int -> interpretation list *)
  1019 		fun unit_vectors n =
  1020 		let
  1021 			(* returns the k-th unit vector of length n *)
  1022 			(* int * int -> interpretation *)
  1023 			fun unit_vector (k,n) =
  1024 				Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
  1025 			(* int -> interpretation list -> interpretation list *)
  1026 			fun unit_vectors_acc k vs =
  1027 				if k>n then [] else (unit_vector (k,n))::(unit_vectors_acc (k+1) vs)
  1028 		in
  1029 			unit_vectors_acc 1 []
  1030 		end
  1031 		(* concatenates 'x' with every list in 'xss', returning a new list of lists *)
  1032 		(* 'a -> 'a list list -> 'a list list *)
  1033 		fun cons_list x xss =
  1034 			map (fn xs => x::xs) xss
  1035 		(* returns a list of lists, each one consisting of n (possibly identical) elements from 'xs' *)
  1036 		(* int -> 'a list -> 'a list list *)
  1037 		fun pick_all 1 xs =
  1038 			map (fn x => [x]) xs
  1039 		  | pick_all n xs =
  1040 			let val rec_pick = pick_all (n-1) xs in
  1041 				foldl (fn (acc,x) => (cons_list x rec_pick) @ acc) ([],xs)
  1042 			end
  1043 	in
  1044 		case intr of
  1045 		  Leaf xs => unit_vectors (length xs)
  1046 		| Node xs => map (fn xs' => Node xs') (pick_all (length xs) (make_constants (hd xs)))
  1047 	end;
  1048 
  1049 (* ------------------------------------------------------------------------- *)
  1050 (* size_of_type: returns the number of constants in a type (i.e. 'length     *)
  1051 (*               (make_constants intr)', but implemented more efficiently)   *)
  1052 (* ------------------------------------------------------------------------- *)
  1053 
  1054 	(* interpretation -> int *)
  1055 
  1056 	fun size_of_type intr =
  1057 	let
  1058 		(* power(a,b) computes a^b, for a>=0, b>=0 *)
  1059 		(* int * int -> int *)
  1060 		fun power (a,0) = 1
  1061 		  | power (a,1) = a
  1062 		  | power (a,b) = let val ab = power(a,b div 2) in ab * ab * power(a,b mod 2) end
  1063 	in
  1064 		case intr of
  1065 		  Leaf xs => length xs
  1066 		| Node xs => power (size_of_type (hd xs), length xs)
  1067 	end;
  1068 
  1069 (* ------------------------------------------------------------------------- *)
  1070 (* TT/FF: interpretations that denote "true" or "false", respectively        *)
  1071 (* ------------------------------------------------------------------------- *)
  1072 
  1073 	(* interpretation *)
  1074 
  1075 	val TT = Leaf [True, False];
  1076 
  1077 	val FF = Leaf [False, True];
  1078 
  1079 (* ------------------------------------------------------------------------- *)
  1080 (* make_equality: returns an interpretation that denotes (extensional)       *)
  1081 (*                equality of two interpretations                            *)
  1082 (* ------------------------------------------------------------------------- *)
  1083 
  1084 	(* We could in principle represent '=' on a type T by a particular        *)
  1085 	(* interpretation.  However, the size of that interpretation is quadratic *)
  1086 	(* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
  1087 	(* 'i2' directly is more efficient than constructing the interpretation   *)
  1088 	(* for equality on T first, and "applying" this interpretation to 'i1'    *)
  1089 	(* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
  1090 
  1091 	(* interpretation * interpretation -> interpretation *)
  1092 
  1093 	fun make_equality (i1, i2) =
  1094 	let
  1095 		(* interpretation * interpretation -> prop_formula *)
  1096 		fun equal (i1, i2) =
  1097 			(case i1 of
  1098 			  Leaf xs =>
  1099 				(case i2 of
  1100 				  Leaf ys => PropLogic.dot_product (xs, ys)
  1101 				| Node _  => raise REFUTE ("make_equality", "second interpretation is higher"))
  1102 			| Node xs =>
  1103 				(case i2 of
  1104 				  Leaf _  => raise REFUTE ("make_equality", "first interpretation is higher")
  1105 				| Node ys => PropLogic.all (map equal (xs ~~ ys))))
  1106 		(* interpretation * interpretation -> prop_formula *)
  1107 		fun not_equal (i1, i2) =
  1108 			(case i1 of
  1109 			  Leaf xs =>
  1110 				(case i2 of
  1111 				  Leaf ys => PropLogic.all ((PropLogic.exists xs) :: (PropLogic.exists ys) ::
  1112 					(map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))  (* defined and not equal *)
  1113 				| Node _  => raise REFUTE ("make_equality", "second interpretation is higher"))
  1114 			| Node xs =>
  1115 				(case i2 of
  1116 				  Leaf _  => raise REFUTE ("make_equality", "first interpretation is higher")
  1117 				| Node ys => PropLogic.exists (map not_equal (xs ~~ ys))))
  1118 	in
  1119 		(* a value may be undefined; therefore 'not_equal' is not just the     *)
  1120 		(* negation of 'equal':                                                *)
  1121 		(* - two interpretations are 'equal' iff they are both defined and     *)
  1122 		(*   denote the same value                                             *)
  1123 		(* - two interpretations are 'not_equal' iff they are both defined at  *)
  1124 		(*   least partially, and a defined part denotes different values      *)
  1125 		(* - an undefined interpretation is neither 'equal' nor 'not_equal' to *)
  1126 		(*   another value                                                     *)
  1127 		Leaf [equal (i1, i2), not_equal (i1, i2)]
  1128 	end;
  1129 
  1130 
  1131 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1132 
  1133 	(* simply typed lambda calculus: Isabelle's basic term syntax, with type  *)
  1134 	(* variables, function types, and propT                                   *)
  1135 
  1136 	fun stlc_interpreter thy model args t =
  1137 	let
  1138 		val (typs, terms)                           = model
  1139 		val {maxvars, next_idx, bounds, wellformed} = args
  1140 		(* Term.typ -> (interpretation * model * arguments) option *)
  1141 		fun interpret_groundterm T =
  1142 		let
  1143 			(* unit -> (interpretation * model * arguments) option *)
  1144 			fun interpret_groundtype () =
  1145 			let
  1146 				val size = (if T = Term.propT then 2 else (the o assoc) (typs, T))  (* the model MUST specify a size for ground types *)
  1147 				val next = (if size=2 then next_idx+1 else next_idx+size)  (* optimization for types with size 2 *)
  1148 				val _    = (if next-1>maxvars andalso maxvars>0 then raise MAXVARS_EXCEEDED else ())  (* check if 'maxvars' is large enough *)
  1149 				(* prop_formula list *)
  1150 				val fms  = (if size=2 then [BoolVar next_idx, Not (BoolVar next_idx)]
  1151 					else (map BoolVar (next_idx upto (next_idx+size-1))))
  1152 				(* interpretation *)
  1153 				val intr = Leaf fms
  1154 				(* prop_formula list -> prop_formula *)
  1155 				fun one_of_two_false []      = True
  1156 				  | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' => SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  1157 				(* prop_formula list -> prop_formula *)
  1158 				fun exactly_one_true xs = SAnd (PropLogic.exists xs, one_of_two_false xs)
  1159 				(* prop_formula *)
  1160 				val wf   = (if size=2 then True else exactly_one_true fms)
  1161 			in
  1162 				(* extend the model, increase 'next_idx', add well-formedness condition *)
  1163 				Some (intr, (typs, (t, intr)::terms), {maxvars = maxvars, next_idx = next, bounds = bounds, wellformed = SAnd (wellformed, wf)})
  1164 			end
  1165 		in
  1166 			case T of
  1167 			  Type ("fun", [T1, T2]) =>
  1168 				let
  1169 					(* we create 'size_of_type (interpret (... T1))' different copies *)
  1170 					(* of the interpretation for 'T2', which are then combined into a *)
  1171 					(* single new interpretation                                      *)
  1172 					val (i1, _, _) =
  1173 						(interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T1))
  1174 						handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1175 					(* make fresh copies, with different variable indices *)
  1176 					(* 'idx': next variable index                         *)
  1177 					(* 'n'  : number of copies                            *)
  1178 					(* int -> int -> (int * interpretation list * prop_formula *)
  1179 					fun make_copies idx 0 =
  1180 						(idx, [], True)
  1181 					  | make_copies idx n =
  1182 						let
  1183 							val (copy, _, new_args) =
  1184 								(interpret thy (typs, []) {maxvars = maxvars, next_idx = idx, bounds = [], wellformed = True} (Free ("dummy", T2))
  1185 								handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1186 							val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
  1187 						in
  1188 							(idx', copy :: copies, SAnd (#wellformed new_args, wf'))
  1189 						end
  1190 					val (next, copies, wf) = make_copies next_idx (size_of_type i1)
  1191 					(* combine copies into a single interpretation *)
  1192 					val intr = Node copies
  1193 				in
  1194 					(* extend the model, increase 'next_idx', add well-formedness condition *)
  1195 					Some (intr, (typs, (t, intr)::terms), {maxvars = maxvars, next_idx = next, bounds = bounds, wellformed = SAnd (wellformed, wf)})
  1196 				end
  1197 			| Type _  => interpret_groundtype ()
  1198 			| TFree _ => interpret_groundtype ()
  1199 			| TVar  _ => interpret_groundtype ()
  1200 		end
  1201 	in
  1202 		case assoc (terms, t) of
  1203 		  Some intr =>
  1204 			(* return an existing interpretation *)
  1205 			Some (intr, model, args)
  1206 		| None =>
  1207 			(case t of
  1208 			  Const (_, T)     =>
  1209 				interpret_groundterm T
  1210 			| Free (_, T)      =>
  1211 				interpret_groundterm T
  1212 			| Var (_, T)       =>
  1213 				interpret_groundterm T
  1214 			| Bound i          =>
  1215 				Some (nth_elem (i, #bounds args), model, args)
  1216 			| Abs (x, T, body) =>
  1217 				let
  1218 					(* create all constants of type 'T' *)
  1219 					val (i, _, _) =
  1220 						(interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1221 						handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1222 					val constants = make_constants i
  1223 					(* interpret the 'body' separately for each constant *)
  1224 					val ((model', args'), bodies) = foldl_map
  1225 						(fn ((m,a), c) =>
  1226 							let
  1227 								(* add 'c' to 'bounds' *)
  1228 								val (i', m', a') = interpret thy m {maxvars = #maxvars a, next_idx = #next_idx a, bounds = (c :: #bounds a), wellformed = #wellformed a} body
  1229 							in
  1230 								(* keep the new model m' and 'next_idx' and 'wellformed', but use old 'bounds' *)
  1231 								((m', {maxvars = maxvars, next_idx = #next_idx a', bounds = bounds, wellformed = #wellformed a'}), i')
  1232 							end)
  1233 						((model, args), constants)
  1234 				in
  1235 					Some (Node bodies, model', args')
  1236 				end
  1237 			| t1 $ t2          =>
  1238 				let
  1239 					(* auxiliary functions *)
  1240 					(* interpretation * interpretation -> interpretation *)
  1241 					fun interpretation_disjunction (tr1,tr2) =
  1242 						tree_map (fn (xs,ys) => map (fn (x,y) => SOr(x,y)) (xs ~~ ys)) (tree_pair (tr1,tr2))
  1243 					(* prop_formula * interpretation -> interpretation *)
  1244 					fun prop_formula_times_interpretation (fm,tr) =
  1245 						tree_map (map (fn x => SAnd (fm,x))) tr
  1246 					(* prop_formula list * interpretation list -> interpretation *)
  1247 					fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
  1248 						prop_formula_times_interpretation (fm,tr)
  1249 					  | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
  1250 						interpretation_disjunction (prop_formula_times_interpretation (fm,tr), prop_formula_list_dot_product_interpretation_list (fms,trees))
  1251 					  | prop_formula_list_dot_product_interpretation_list (_,_) =
  1252 						raise REFUTE ("stlc_interpreter", "empty list (in dot product)")
  1253 					(* concatenates 'x' with every list in 'xss', returning a new list of lists *)
  1254 					(* 'a -> 'a list list -> 'a list list *)
  1255 					fun cons_list x xss =
  1256 						map (fn xs => x::xs) xss
  1257 					(* returns a list of lists, each one consisting of one element from each element of 'xss' *)
  1258 					(* 'a list list -> 'a list list *)
  1259 					fun pick_all [xs] =
  1260 						map (fn x => [x]) xs
  1261 					  | pick_all (xs::xss) =
  1262 						let val rec_pick = pick_all xss in
  1263 							foldl (fn (acc,x) => (cons_list x rec_pick) @ acc) ([],xs)
  1264 						end
  1265 					  | pick_all _ =
  1266 						raise REFUTE ("stlc_interpreter", "empty list (in pick_all)")
  1267 					(* interpretation -> prop_formula list *)
  1268 					fun interpretation_to_prop_formula_list (Leaf xs) =
  1269 						xs
  1270 					  | interpretation_to_prop_formula_list (Node trees) =
  1271 						map PropLogic.all (pick_all (map interpretation_to_prop_formula_list trees))
  1272 					(* interpretation * interpretation -> interpretation *)
  1273 					fun interpretation_apply (tr1,tr2) =
  1274 						(case tr1 of
  1275 						  Leaf _ =>
  1276 							raise REFUTE ("stlc_interpreter", "first interpretation is a leaf")
  1277 						| Node xs =>
  1278 							prop_formula_list_dot_product_interpretation_list (interpretation_to_prop_formula_list tr2, xs))
  1279 					(* interpret 't1' and 't2' separately *)
  1280 					val (intr1, model1, args1) = interpret thy model args t1
  1281 					val (intr2, model2, args2) = interpret thy model1 args1 t2
  1282 				in
  1283 					Some (interpretation_apply (intr1,intr2), model2, args2)
  1284 				end)
  1285 	end;
  1286 
  1287 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1288 
  1289 	fun Pure_interpreter thy model args t =
  1290 		case t of
  1291 		  Const ("all", _) $ t1 =>  (* in the meta-logic, 'all' MUST be followed by an argument term *)
  1292 			let
  1293 				val (i, m, a) = interpret thy model args t1
  1294 			in
  1295 				case i of
  1296 				  Node xs =>
  1297 					let
  1298 						val fmTrue  = PropLogic.all (map toTrue xs)
  1299 						val fmFalse = PropLogic.exists (map toFalse xs)
  1300 					in
  1301 						Some (Leaf [fmTrue, fmFalse], m, a)
  1302 					end
  1303 				| _ =>
  1304 					raise REFUTE ("Pure_interpreter", "\"all\" is not followed by a function")
  1305 			end
  1306 		| Const ("==", _) $ t1 $ t2 =>
  1307 			let
  1308 				val (i1, m1, a1) = interpret thy model args t1
  1309 				val (i2, m2, a2) = interpret thy m1 a1 t2
  1310 			in
  1311 				Some (make_equality (i1, i2), m2, a2)
  1312 			end
  1313 		| Const ("==>", _) =>  (* simpler than translating 'Const ("==>", _) $ t1 $ t2' *)
  1314 			Some (Node [Node [TT, FF], Node [TT, TT]], model, args)
  1315 		| _ => None;
  1316 
  1317 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1318 
  1319 	fun HOLogic_interpreter thy model args t =
  1320 	let
  1321 		(* Term.term -> int -> Term.term *)
  1322 		fun eta_expand t i =
  1323 		let
  1324 			val Ts = binder_types (fastype_of t)
  1325 		in
  1326 			foldr (fn (T, t) => Abs ("<eta_expand>", T, t))
  1327 				(take (i, Ts), list_comb (t, map Bound (i-1 downto 0)))
  1328 		end
  1329 	in
  1330 	(* ------------------------------------------------------------------------- *)
  1331 	(* Providing interpretations directly is more efficient than unfolding the   *)
  1332 	(* logical constants.  IN HOL however, logical constants can themselves be   *)
  1333 	(* arguments.  "All" and "Ex" are then translated just like any other        *)
  1334 	(* constant, with the relevant axiom being added by 'collect_axioms'.        *)
  1335 	(* ------------------------------------------------------------------------- *)
  1336 		case t of
  1337 		  Const ("Trueprop", _) =>
  1338 			Some (Node [TT, FF], model, args)
  1339 		| Const ("Not", _) =>
  1340 			Some (Node [FF, TT], model, args)
  1341 		| Const ("True", _) =>  (* redundant, since 'True' is also an IDT constructor *)
  1342 			Some (TT, model, args)
  1343 		| Const ("False", _) =>  (* redundant, since 'False' is also an IDT constructor *)
  1344 			Some (FF, model, args)
  1345 		| Const ("All", _) $ t1 =>
  1346 			let
  1347 				val (i, m, a) = interpret thy model args t1
  1348 			in
  1349 				case i of
  1350 				  Node xs =>
  1351 					let
  1352 						val fmTrue  = PropLogic.all (map toTrue xs)
  1353 						val fmFalse = PropLogic.exists (map toFalse xs)
  1354 					in
  1355 						Some (Leaf [fmTrue, fmFalse], m, a)
  1356 					end
  1357 				| _ =>
  1358 					raise REFUTE ("HOLogic_interpreter", "\"All\" is not followed by a function")
  1359 			end
  1360 		| Const ("Ex", _) $ t1 =>
  1361 			let
  1362 				val (i, m, a) = interpret thy model args t1
  1363 			in
  1364 				case i of
  1365 				  Node xs =>
  1366 					let
  1367 						val fmTrue  = PropLogic.exists (map toTrue xs)
  1368 						val fmFalse = PropLogic.all (map toFalse xs)
  1369 					in
  1370 						Some (Leaf [fmTrue, fmFalse], m, a)
  1371 					end
  1372 				| _ =>
  1373 					raise REFUTE ("HOLogic_interpreter", "\"Ex\" is not followed by a function")
  1374 			end
  1375 		| Const ("op =", _) $ t1 $ t2 =>
  1376 			let
  1377 				val (i1, m1, a1) = interpret thy model args t1
  1378 				val (i2, m2, a2) = interpret thy m1 a1 t2
  1379 			in
  1380 				Some (make_equality (i1, i2), m2, a2)
  1381 			end
  1382 		| Const ("op =", _) $ t1 =>
  1383 			(Some (interpret thy model args (eta_expand t 1)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1384 		| Const ("op =", _) =>
  1385 			(Some (interpret thy model args (eta_expand t 2)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1386 		| Const ("op &", _) =>
  1387 			Some (Node [Node [TT, FF], Node [FF, FF]], model, args)
  1388 		| Const ("op |", _) =>
  1389 			Some (Node [Node [TT, TT], Node [TT, FF]], model, args)
  1390 		| Const ("op -->", _) =>
  1391 			Some (Node [Node [TT, FF], Node [TT, TT]], model, args)
  1392 		| _ => None
  1393 	end;
  1394 
  1395 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1396 
  1397 	fun set_interpreter thy model args t =
  1398 	(* "T set" is isomorphic to "T --> bool" *)
  1399 	let
  1400 		val (typs, terms) = model
  1401 		(* Term.term -> int -> Term.term *)
  1402 		fun eta_expand t i =
  1403 		let
  1404 			val Ts = binder_types (fastype_of t)
  1405 		in
  1406 			foldr (fn (T, t) => Abs ("<eta_expand>", T, t))
  1407 				(take (i, Ts), list_comb (t, map Bound (i-1 downto 0)))
  1408 		end
  1409 	in
  1410 		case assoc (terms, t) of
  1411 		  Some intr =>
  1412 			(* return an existing interpretation *)
  1413 			Some (intr, model, args)
  1414 		| None =>
  1415 			(case t of
  1416 			  Free (x, Type ("set", [T])) =>
  1417 				(let
  1418 					val (intr, _, args') = interpret thy (typs, []) args (Free (x, T --> HOLogic.boolT))
  1419 				in
  1420 					Some (intr, (typs, (t, intr)::terms), args')
  1421 				end handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1422 			| Var ((x,i), Type ("set", [T])) =>
  1423 				(let
  1424 					val (intr, _, args') = interpret thy (typs, []) args (Var ((x,i), T --> HOLogic.boolT))
  1425 				in
  1426 					Some (intr, (typs, (t, intr)::terms), args')
  1427 				end handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1428 			| Const (s, Type ("set", [T])) =>
  1429 				(let
  1430 					val (intr, _, args') = interpret thy (typs, []) args (Const (s, T --> HOLogic.boolT))
  1431 				in
  1432 					Some (intr, (typs, (t, intr)::terms), args')
  1433 				end handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1434 			(* 'Collect' == identity *)
  1435 			| Const ("Collect", _) $ t1 =>
  1436 				Some (interpret thy model args t1)
  1437 			| Const ("Collect", _) =>
  1438 				(Some (interpret thy model args (eta_expand t 1)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1439 			(* 'op :' == application *)
  1440 			| Const ("op :", _) $ t1 $ t2 =>
  1441 				Some (interpret thy model args (t2 $ t1))
  1442 			| Const ("op :", _) $ t1 =>
  1443 				(Some (interpret thy model args (eta_expand t 1)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1444 			| Const ("op :", _) =>
  1445 				(Some (interpret thy model args (eta_expand t 2)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1446 			| _ => None)
  1447 	end;
  1448 
  1449 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1450 
  1451 	fun IDT_interpreter thy model args t =
  1452 	let
  1453 		val (typs, terms) = model
  1454 		(* DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list -> DatatypeAux.dtyp -> Term.typ *)
  1455 		fun typ_of_dtyp descr typ_assoc (DatatypeAux.DtTFree a) =
  1456 			(* replace a 'DtTFree' variable by the associated type *)
  1457 			(the o assoc) (typ_assoc, DatatypeAux.DtTFree a)
  1458 		  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtRec i) =
  1459 			let
  1460 				val (s, ds, _) = (the o assoc) (descr, i)
  1461 			in
  1462 				Type (s, map (typ_of_dtyp descr typ_assoc) ds)
  1463 			end
  1464 		  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtType (s, ds)) =
  1465 			Type (s, map (typ_of_dtyp descr typ_assoc) ds)
  1466 		(* int list -> int *)
  1467 		fun sum xs = foldl op+ (0, xs)
  1468 		(* int list -> int *)
  1469 		fun product xs = foldl op* (1, xs)
  1470 		(* the size of an IDT is the sum (over its constructors) of the        *)
  1471 		(* product (over their arguments) of the size of the argument type     *)
  1472 		(* (Term.typ * int) list -> DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list -> (string * DatatypeAux.dtyp list) list -> int *)
  1473 		fun size_of_dtyp typs descr typ_assoc constrs =
  1474 			sum (map (fn (_, ds) =>
  1475 				product (map (fn d =>
  1476 					let
  1477 						val T         = typ_of_dtyp descr typ_assoc d
  1478 						val (i, _, _) =
  1479 							(interpret thy (typs, []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1480 							handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1481 					in
  1482 						size_of_type i
  1483 					end) ds)) constrs)
  1484 		(* Term.typ -> (interpretation * model * arguments) option *)
  1485 		fun interpret_variable (Type (s, Ts)) =
  1486 			(case DatatypePackage.datatype_info thy s of
  1487 			  Some info =>  (* inductive datatype *)
  1488 				let
  1489 					val (typs, terms) = model
  1490 					(* int option -- only recursive IDTs have an associated depth *)
  1491 					val depth         = assoc (typs, Type (s, Ts))
  1492 				in
  1493 					if depth = (Some 0) then  (* termination condition to avoid infinite recursion *)
  1494 						(* return a leaf of size 0 *)
  1495 						Some (Leaf [], model, args)
  1496 					else
  1497 						let
  1498 							val index               = #index info
  1499 							val descr               = #descr info
  1500 							val (_, dtyps, constrs) = (the o assoc) (descr, index)
  1501 							val typ_assoc           = dtyps ~~ Ts
  1502 							(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1503 							val _ = (if Library.exists (fn d =>
  1504 									case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
  1505 								then
  1506 									raise REFUTE ("IDT_interpreter", "datatype argument (for type " ^ Sign.string_of_typ (sign_of thy) (Type (s, Ts)) ^ ") is not a variable")
  1507 								else
  1508 									())
  1509 							(* if the model specifies a depth for the current type, decrement it to avoid infinite recursion *)
  1510 							val typs'    = (case depth of None => typs | Some n => overwrite (typs, (Type (s, Ts), n-1)))
  1511 							(* recursively compute the size of the datatype *)
  1512 							val size     = size_of_dtyp typs' descr typ_assoc constrs
  1513 							val next_idx = #next_idx args
  1514 							val next     = (if size=2 then next_idx+1 else next_idx+size)  (* optimization for types with size 2 *)
  1515 							val _        = (if next-1>(#maxvars args) andalso (#maxvars args)>0 then raise MAXVARS_EXCEEDED else ())  (* check if 'maxvars' is large enough *)
  1516 							(* prop_formula list *)
  1517 							val fms      = (if size=2 then [BoolVar next_idx, Not (BoolVar next_idx)]
  1518 								else (map BoolVar (next_idx upto (next_idx+size-1))))
  1519 							(* interpretation *)
  1520 							val intr     = Leaf fms
  1521 							(* prop_formula list -> prop_formula *)
  1522 							fun one_of_two_false []      = True
  1523 							  | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' => SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  1524 							(* prop_formula list -> prop_formula *)
  1525 							fun exactly_one_true xs = SAnd (PropLogic.exists xs, one_of_two_false xs)
  1526 							(* prop_formula *)
  1527 							val wf       = (if size=2 then True else exactly_one_true fms)
  1528 						in
  1529 							(* extend the model, increase 'next_idx', add well-formedness condition *)
  1530 							Some (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args, next_idx = next, bounds = #bounds args, wellformed = SAnd (#wellformed args, wf)})
  1531 						end
  1532 				end
  1533 			| None =>  (* not an inductive datatype *)
  1534 				None)
  1535 		  | interpret_variable _ =  (* a (free or schematic) type variable *)
  1536 			None
  1537 	in
  1538 		case assoc (terms, t) of
  1539 		  Some intr =>
  1540 			(* return an existing interpretation *)
  1541 			Some (intr, model, args)
  1542 		| None =>
  1543 			(case t of
  1544 			  Free (_, T)  => interpret_variable T
  1545 			| Var (_, T)   => interpret_variable T
  1546 			| Const (s, T) =>
  1547 				(* TODO: case, recursion, size *)
  1548 				let
  1549 					(* unit -> (interpretation * model * arguments) option *)
  1550 					fun interpret_constructor () =
  1551 						(case body_type T of
  1552 						  Type (s', Ts') =>
  1553 							(case DatatypePackage.datatype_info thy s' of
  1554 							  Some info =>  (* body type is an inductive datatype *)
  1555 								let
  1556 									val index               = #index info
  1557 									val descr               = #descr info
  1558 									val (_, dtyps, constrs) = (the o assoc) (descr, index)
  1559 									val typ_assoc           = dtyps ~~ Ts'
  1560 									(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1561 									val _ = (if Library.exists (fn d =>
  1562 											case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
  1563 										then
  1564 											raise REFUTE ("IDT_interpreter", "datatype argument (for type " ^ Sign.string_of_typ (sign_of thy) (Type (s', Ts')) ^ ") is not a variable")
  1565 										else
  1566 											())
  1567 									(* split the constructors into those occuring before/after 'Const (s, T)' *)
  1568 									val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
  1569 										not (cname = s andalso Type.typ_instance (Sign.tsig_of (sign_of thy)) (T,
  1570 											map (typ_of_dtyp descr typ_assoc) ctypes ---> Type (s', Ts')))) constrs
  1571 								in
  1572 									case constrs2 of
  1573 									  [] =>
  1574 										(* 'Const (s, T)' is not a constructor of this datatype *)
  1575 										None
  1576 									| c::cs =>
  1577 										let
  1578 											(* int option -- only recursive IDTs have an associated depth *)
  1579 											val depth = assoc (typs, Type (s', Ts'))
  1580 											val typs' = (case depth of None => typs | Some n => overwrite (typs, (Type (s', Ts'), n-1)))
  1581 											(* constructors before 'Const (s, T)' generate elements of the datatype *)
  1582 											val offset  = size_of_dtyp typs' descr typ_assoc constrs1
  1583 											(* 'Const (s, T)' and constructors after it generate elements of the datatype *)
  1584 											val total   = offset + (size_of_dtyp typs' descr typ_assoc constrs2)
  1585 											(* create an interpretation that corresponds to the constructor 'Const (s, T)' *)
  1586 											(* by recursion over its argument types                                        *)
  1587 											(* DatatypeAux.dtyp list -> interpretation *)
  1588 											fun make_partial [] =
  1589 												(* all entries of the leaf are 'False' *)
  1590 												Leaf (replicate total False)
  1591 											  | make_partial (d::ds) =
  1592 												let
  1593 													(* compute the "new" size of the type 'd' *)
  1594 													val T         = typ_of_dtyp descr typ_assoc d
  1595 													val (i, _, _) =
  1596 														(interpret thy (typs, []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1597 														handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1598 												in
  1599 													(* all entries of the whole subtree are 'False' *)
  1600 													Node (replicate (size_of_type i) (make_partial ds))
  1601 												end
  1602 											(* int * DatatypeAux.dtyp list -> int * interpretation *)
  1603 											fun make_constr (offset, []) =
  1604 												if offset<total then
  1605 													(offset+1, Leaf ((replicate offset False) @ True :: (replicate (total-offset-1) False)))
  1606 												else
  1607 													raise REFUTE ("IDT_interpreter", "internal error: offset >= total")
  1608 											  | make_constr (offset, d::ds) =
  1609 												let
  1610 													(* compute the "new" and "old" size of the type 'd' *)
  1611 													val T         = typ_of_dtyp descr typ_assoc d
  1612 													val (i, _, _) =
  1613 														(interpret thy (typs, []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1614 														handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1615 													val (i', _, _) =
  1616 														(interpret thy (typs', []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1617 														handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1618 													val size  = size_of_type i
  1619 													val size' = size_of_type i'
  1620 													val _ = if size<size' then
  1621 															raise REFUTE ("IDT_interpreter", "internal error: new size < old size")
  1622 														else
  1623 															()
  1624 													val (new_offset, intrs) = foldl_map make_constr (offset, replicate size' ds)
  1625 												in
  1626 													(* the first size' elements of the type actually yield a result *)
  1627 													(* element, while the remaining size-size' elements don't       *)
  1628 													(new_offset, Node (intrs @ (replicate (size-size') (make_partial ds))))
  1629 												end
  1630 										in
  1631 											Some ((snd o make_constr) (offset, snd c), model, args)
  1632 										end
  1633 								end
  1634 							| None =>  (* body type is not an inductive datatype *)
  1635 								None)
  1636 						| _ =>  (* body type is a (free or schematic) type variable *)
  1637 							None)
  1638 				in
  1639 					case interpret_constructor () of
  1640 					  Some x => Some x
  1641 					| None   => interpret_variable T
  1642 				end
  1643 			| _ => None)
  1644 	end;
  1645 
  1646 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1647 
  1648 	(* only an optimization: 'card' could in principle be interpreted with    *)
  1649 	(* interpreters available already (using its definition), but the code    *)
  1650 	(* below is much more efficient                                           *)
  1651 
  1652 	fun Finite_Set_card_interpreter thy model args t =
  1653 		case t of
  1654 		  Const ("Finite_Set.card", Type ("fun", [Type ("set", [T]), Type ("nat", [])])) =>
  1655 			let
  1656 				val (i_nat, _, _) =
  1657 					(interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", Type ("nat", [])))
  1658 						handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1659 				val size_nat      = size_of_type i_nat
  1660 				val (i_set, _, _) =
  1661 					(interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", Type ("set", [T])))
  1662 						handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1663 				val constants     = make_constants i_set
  1664 				(* interpretation -> int *)
  1665 				fun number_of_elements (Node xs) =
  1666 					foldl (fn (n, x) =>
  1667 						if x=TT then n+1 else if x=FF then n else raise REFUTE ("Finite_Set_card_interpreter", "interpretation for set type does not yield a Boolean")) (0, xs)
  1668 				  | number_of_elements (Leaf _) =
  1669 					raise REFUTE ("Finite_Set_card_interpreter", "interpretation for set type is a leaf")
  1670 				(* takes an interpretation for a set and returns an interpretation for a 'nat' *)
  1671 				(* interpretation -> interpretation *)
  1672 				fun card i =
  1673 					let
  1674 						val n = number_of_elements i
  1675 					in
  1676 						if n<size_nat then
  1677 							Leaf ((replicate n False) @ True :: (replicate (size_nat-n-1) False))
  1678 						else
  1679 							Leaf (replicate size_nat False)
  1680 					end
  1681 			in
  1682 				Some (Node (map card constants), model, args)
  1683 			end
  1684 		| _ =>
  1685 			None;
  1686 
  1687 
  1688 (* ------------------------------------------------------------------------- *)
  1689 (* PRINTERS                                                                  *)
  1690 (* ------------------------------------------------------------------------- *)
  1691 
  1692 	(* theory -> model -> Term.term -> interpretation -> (int -> bool) -> Term.term option *)
  1693 
  1694 	fun stlc_printer thy model t intr assignment =
  1695 	let
  1696 		(* Term.term -> Term.typ option *)
  1697 		fun typeof (Free (_, T))  = Some T
  1698 		  | typeof (Var (_, T))   = Some T
  1699 		  | typeof (Const (_, T)) = Some T
  1700 		  | typeof _              = None
  1701 		(* string -> string *)
  1702 		fun strip_leading_quote s =
  1703 			(implode o (fn ss => case ss of [] => [] | x::xs => if x="'" then xs else ss) o explode) s
  1704 		(* Term.typ -> string *)
  1705 		fun string_of_typ (Type (s, _))     = s
  1706 		  | string_of_typ (TFree (x, _))    = strip_leading_quote x
  1707 		  | string_of_typ (TVar ((x,i), _)) = strip_leading_quote x ^ string_of_int i
  1708 		(* interpretation -> int *)
  1709 		fun index_from_interpretation (Leaf xs) =
  1710 			let
  1711 				val idx = find_index (PropLogic.eval assignment) xs
  1712 			in
  1713 				if idx<0 then
  1714 					raise REFUTE ("stlc_printer", "illegal interpretation: no value assigned (SAT solver unsound?)")
  1715 				else
  1716 					idx
  1717 			end
  1718 		  | index_from_interpretation _ =
  1719 			raise REFUTE ("stlc_printer", "interpretation for ground type is not a leaf")
  1720 	in
  1721 		case typeof t of
  1722 		  Some T =>
  1723 			(case T of
  1724 			  Type ("fun", [T1, T2]) =>
  1725 				(let
  1726 					(* create all constants of type 'T1' *)
  1727 					val (i, _, _) = interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T1))
  1728 					val constants = make_constants i
  1729 					(* interpretation list *)
  1730 					val results = (case intr of
  1731 						  Node xs => xs
  1732 						| _       => raise REFUTE ("stlc_printer", "interpretation for function type is a leaf"))
  1733 					(* Term.term list *)
  1734 					val pairs = map (fn (arg, result) =>
  1735 						HOLogic.mk_prod
  1736 							(print thy model (Free ("dummy", T1)) arg assignment,
  1737 							 print thy model (Free ("dummy", T2)) result assignment))
  1738 						(constants ~~ results)
  1739 					(* Term.typ *)
  1740 					val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  1741 					val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  1742 					(* Term.term *)
  1743 					val HOLogic_empty_set = Const ("{}", HOLogic_setT)
  1744 					val HOLogic_insert    = Const ("insert", HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  1745 				in
  1746 					Some (foldr (fn (pair, acc) => HOLogic_insert $ pair $ acc) (pairs, HOLogic_empty_set))
  1747 				end handle CANNOT_INTERPRET _ => None)
  1748 			| Type ("prop", [])      =>
  1749 				(case index_from_interpretation intr of
  1750 				  0 => Some (HOLogic.mk_Trueprop HOLogic.true_const)
  1751 				| 1 => Some (HOLogic.mk_Trueprop HOLogic.false_const)
  1752 				| _ => raise REFUTE ("stlc_interpreter", "illegal interpretation for a propositional value"))
  1753 			| Type _  => Some (Const (string_of_typ T ^ string_of_int (index_from_interpretation intr), T))
  1754 			| TFree _ => Some (Const (string_of_typ T ^ string_of_int (index_from_interpretation intr), T))
  1755 			| TVar _  => Some (Const (string_of_typ T ^ string_of_int (index_from_interpretation intr), T)))
  1756 		| None =>
  1757 			None
  1758 	end;
  1759 
  1760 	(* theory -> model -> Term.term -> interpretation -> (int -> bool) -> string option *)
  1761 
  1762 	fun set_printer thy model t intr assignment =
  1763 	let
  1764 		(* Term.term -> Term.typ option *)
  1765 		fun typeof (Free (_, T))  = Some T
  1766 		  | typeof (Var (_, T))   = Some T
  1767 		  | typeof (Const (_, T)) = Some T
  1768 		  | typeof _              = None
  1769 	in
  1770 		case typeof t of
  1771 		  Some (Type ("set", [T])) =>
  1772 			(let
  1773 				(* create all constants of type 'T' *)
  1774 				val (i, _, _) = interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1775 				val constants = make_constants i
  1776 				(* interpretation list *)
  1777 				val results = (case intr of
  1778 					  Node xs => xs
  1779 					| _       => raise REFUTE ("set_printer", "interpretation for set type is a leaf"))
  1780 				(* Term.term list *)
  1781 				val elements = mapfilter (fn (arg, result) =>
  1782 					case result of
  1783 					  Leaf [fmTrue, fmFalse] =>
  1784 						if PropLogic.eval assignment fmTrue then
  1785 							Some (print thy model (Free ("dummy", T)) arg assignment)
  1786 						else if PropLogic.eval assignment fmFalse then
  1787 							None
  1788 						else
  1789 							raise REFUTE ("set_printer", "illegal interpretation: no value assigned (SAT solver unsound?)")
  1790 					| _ =>
  1791 						raise REFUTE ("set_printer", "illegal interpretation for a Boolean value"))
  1792 					(constants ~~ results)
  1793 				(* Term.typ *)
  1794 				val HOLogic_setT  = HOLogic.mk_setT T
  1795 				(* Term.term *)
  1796 				val HOLogic_empty_set = Const ("{}", HOLogic_setT)
  1797 				val HOLogic_insert    = Const ("insert", T --> HOLogic_setT --> HOLogic_setT)
  1798 			in
  1799 				Some (foldl (fn (acc, elem) => HOLogic_insert $ elem $ acc) (HOLogic_empty_set, elements))
  1800 			end handle CANNOT_INTERPRET _ => None)
  1801 		| _ =>
  1802 			None
  1803 	end;
  1804 
  1805 	(* theory -> model -> Term.term -> interpretation -> (int -> bool) -> Term.term option *)
  1806 
  1807 	fun IDT_printer thy model t intr assignment =
  1808 	let
  1809 		(* Term.term -> Term.typ option *)
  1810 		fun typeof (Free (_, T))  = Some T
  1811 		  | typeof (Var (_, T))   = Some T
  1812 		  | typeof (Const (_, T)) = Some T
  1813 		  | typeof _              = None
  1814 	in
  1815 		case typeof t of
  1816 		  Some (Type (s, Ts)) =>
  1817 			(case DatatypePackage.datatype_info thy s of
  1818 			  Some info =>  (* inductive datatype *)
  1819 				let
  1820 					val (typs, _)           = model
  1821 					val index               = #index info
  1822 					val descr               = #descr info
  1823 					val (_, dtyps, constrs) = (the o assoc) (descr, index)
  1824 					val typ_assoc           = dtyps ~~ Ts
  1825 					(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1826 					val _ = (if Library.exists (fn d =>
  1827 							case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
  1828 						then
  1829 							raise REFUTE ("IDT_printer", "datatype argument (for type " ^ Sign.string_of_typ (sign_of thy) (Type (s, Ts)) ^ ") is not a variable")
  1830 						else
  1831 							())
  1832 					(* the index of the element in the datatype *)
  1833 					val element = (case intr of
  1834 						  Leaf xs => find_index (PropLogic.eval assignment) xs
  1835 						| Node _  => raise REFUTE ("IDT_printer", "interpretation is not a leaf"))
  1836 					val _ = (if element<0 then raise REFUTE ("IDT_printer", "invalid interpretation (no value assigned)") else ())
  1837 					(* int option -- only recursive IDTs have an associated depth *)
  1838 					val depth = assoc (typs, Type (s, Ts))
  1839 					val typs' = (case depth of None => typs | Some n => overwrite (typs, (Type (s, Ts), n-1)))
  1840 					(* DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list -> DatatypeAux.dtyp -> Term.typ *)
  1841 					fun typ_of_dtyp descr typ_assoc (DatatypeAux.DtTFree a) =
  1842 						(* replace a 'DtTFree' variable by the associated type *)
  1843 						(the o assoc) (typ_assoc, DatatypeAux.DtTFree a)
  1844 					  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtRec i) =
  1845 						let
  1846 							val (s, ds, _) = (the o assoc) (descr, i)
  1847 						in
  1848 							Type (s, map (typ_of_dtyp descr typ_assoc) ds)
  1849 						end
  1850 					  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtType (s, ds)) =
  1851 						Type (s, map (typ_of_dtyp descr typ_assoc) ds)
  1852 					(* int list -> int *)
  1853 					fun sum xs = foldl op+ (0, xs)
  1854 					(* int list -> int *)
  1855 					fun product xs = foldl op* (1, xs)
  1856 					(* the size of an IDT is the sum (over its constructors) of the        *)
  1857 					(* product (over their arguments) of the size of the argument type     *)
  1858 					(* (Term.typ * int) list -> DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list -> (string * DatatypeAux.dtyp list) list -> int *)
  1859 					fun size_of_dtyp typs descr typ_assoc xs =
  1860 						sum (map (fn (_, ds) =>
  1861 							product (map (fn d =>
  1862 								let
  1863 									val T         = typ_of_dtyp descr typ_assoc d
  1864 									val (i, _, _) =
  1865 										(interpret thy (typs, []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1866 										handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1867 					in
  1868 						size_of_type i
  1869 					end) ds)) xs)
  1870 					(* int -> DatatypeAux.dtyp list -> Term.term list *)
  1871 					fun make_args n [] =
  1872 						if n<>0 then
  1873 							raise REFUTE ("IDT_printer", "error computing the element: remainder is not 0")
  1874 						else
  1875 							[]
  1876 					  | make_args n (d::ds) =
  1877 						let
  1878 							val dT        = typ_of_dtyp descr typ_assoc d
  1879 							val (i, _, _) =
  1880 								(interpret thy (typs', []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", dT))
  1881 								handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1882 							val size      = size_of_type i
  1883 							val consts    = make_constants i  (* we only need the (n mod size)-th element of *)
  1884 								(* this list, so there might be a more efficient implementation that does not *)
  1885 								(* generate all constants                                                     *)
  1886 						in
  1887 							(print thy (typs', []) (Free ("dummy", dT)) (nth_elem (n mod size, consts)) assignment)::(make_args (n div size) ds)
  1888 						end
  1889 					(* int -> (string * DatatypeAux.dtyp list) list -> Term.term *)
  1890 					fun make_term _ [] =
  1891 						raise REFUTE ("IDT_printer", "invalid interpretation (value too large - not enough constructors)")
  1892 					  | make_term n (c::cs) =
  1893 						let
  1894 							val c_size = size_of_dtyp typs' descr typ_assoc [c]
  1895 						in
  1896 							if n<c_size then
  1897 								let
  1898 									val (cname, cargs) = c
  1899 									val c_term = Const (cname, (map (typ_of_dtyp descr typ_assoc) cargs) ---> Type (s, Ts))
  1900 								in
  1901 									foldl op$ (c_term, rev (make_args n (rev cargs)))
  1902 								end
  1903 							else
  1904 								make_term (n-c_size) cs
  1905 						end
  1906 				in
  1907 					Some (make_term element constrs)
  1908 				end
  1909 			| None =>  (* not an inductive datatype *)
  1910 				None)
  1911 		| _ =>  (* a (free or schematic) type variable *)
  1912 			None
  1913 	end;
  1914 
  1915 
  1916 (* ------------------------------------------------------------------------- *)
  1917 (* use 'setup Refute.setup' in an Isabelle theory to initialize the 'Refute' *)
  1918 (* structure                                                                 *)
  1919 (* ------------------------------------------------------------------------- *)
  1920 
  1921 (* ------------------------------------------------------------------------- *)
  1922 (* Note: the interpreters and printers are used in reverse order; however,   *)
  1923 (*       an interpreter that can handle non-atomic terms ends up being       *)
  1924 (*       applied before the 'stlc_interpreter' breaks the term apart into    *)
  1925 (*       subterms that are then passed to other interpreters!                *)
  1926 (* ------------------------------------------------------------------------- *)
  1927 
  1928 	(* (theory -> theory) list *)
  1929 
  1930 	val setup =
  1931 		[RefuteData.init,
  1932 		 add_interpreter "stlc"            stlc_interpreter,
  1933 		 add_interpreter "Pure"            Pure_interpreter,
  1934 		 add_interpreter "HOLogic"         HOLogic_interpreter,
  1935 		 add_interpreter "set"             set_interpreter,
  1936 		 add_interpreter "IDT"             IDT_interpreter,
  1937 		 add_interpreter "Finite_Set.card" Finite_Set_card_interpreter,
  1938 		 add_printer "stlc" stlc_printer,
  1939 		 add_printer "set"  set_printer,
  1940 		 add_printer "IDT"  IDT_printer];
  1941 
  1942 end