src/HOL/Tools/refute.ML
author wenzelm
Mon Jun 21 16:39:39 2004 +0200 (2004-06-21)
changeset 14984 edbc81e60809
parent 14965 7155b319eafa
child 15125 5224130bc0d6
permissions -rw-r--r--
immediate_output;
     1 (*  Title:      HOL/Tools/refute.ML
     2     ID:         $Id$
     3     Author:     Tjark Weber
     4     Copyright   2003-2004
     5 
     6 Finite model generation for HOL formulas, using a SAT solver.
     7 *)
     8 
     9 (* TODO: case, recursion, 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 _ = immediate_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 								(immediate_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 immediate_output " *ignoring sorts*" else ();*) axs)
   514 			| TVar  (_, sorts)       => ((*if not (null sorts) then immediate_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 						(immediate_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 						(immediate_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 								(immediate_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 _                      = immediate_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 				immediate_output " invoking SAT solver...";
   903 				(case SatSolver.invoke_solver satsolver fm of
   904 				  SatSolver.SATISFIABLE assignment =>
   905 					writeln ("\n*** Model found: ***\n" ^ print_model thy model (fn i => case assignment i of Some b => b | None => true))
   906 				| _ =>  (* SatSolver.UNSATISFIABLE, SatSolver.UNKNOWN *)
   907 					(immediate_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 				handle SatSolver.NOT_CONFIGURED =>
   912 					error ("SAT solver " ^ quote satsolver ^ " is not configured.")
   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 				(TimeLimit.timeLimit (Time.fromSeconds (Int.toLarge maxtime))
   932 					wrapper ()
   933 				handle TimeLimit.TimeOut =>
   934 					writeln ("\nSearch terminated, time limit ("
   935 						^ string_of_int maxtime ^ (if maxtime=1 then " second" else " seconds")
   936 						^ ") exceeded."))
   937 			else
   938 				wrapper ()
   939 		end;
   940 
   941 
   942 (* ------------------------------------------------------------------------- *)
   943 (* INTERFACE, PART 2: FINDING A MODEL                                        *)
   944 (* ------------------------------------------------------------------------- *)
   945 
   946 (* ------------------------------------------------------------------------- *)
   947 (* satisfy_term: calls 'find_model' to find a model that satisfies 't'       *)
   948 (* params      : list of '(name, value)' pairs used to override default      *)
   949 (*               parameters                                                  *)
   950 (* ------------------------------------------------------------------------- *)
   951 
   952 	(* theory -> (string * string) list -> Term.term -> unit *)
   953 
   954 	fun satisfy_term thy params t =
   955 		find_model thy (actual_params thy params) t false;
   956 
   957 (* ------------------------------------------------------------------------- *)
   958 (* refute_term: calls 'find_model' to find a model that refutes 't'          *)
   959 (* params     : list of '(name, value)' pairs used to override default       *)
   960 (*              parameters                                                   *)
   961 (* ------------------------------------------------------------------------- *)
   962 
   963 	(* theory -> (string * string) list -> Term.term -> unit *)
   964 
   965 	fun refute_term thy params t =
   966 	let
   967 		(* disallow schematic type variables, since we cannot properly negate  *)
   968 		(* terms containing them (their logical meaning is that there EXISTS a *)
   969 		(* type s.t. ...; to refute such a formula, we would have to show that *)
   970 		(* for ALL types, not ...)                                             *)
   971 		val _ = assert (null (term_tvars t)) "Term to be refuted contains schematic type variables"
   972 		(* existential closure over schematic variables *)
   973 		(* (Term.indexname * Term.typ) list *)
   974 		val vars = sort_wrt (fst o fst) (map dest_Var (term_vars t))
   975 		(* Term.term *)
   976 		val ex_closure = foldl
   977 			(fn (t', ((x,i),T)) => (HOLogic.exists_const T) $ Abs (x, T, abstract_over (Var((x,i),T), t')))
   978 			(t, vars)
   979 		(* If 't' is of type 'propT' (rather than 'boolT'), applying  *)
   980 		(* 'HOLogic.exists_const' is not type-correct.  However, this *)
   981 		(* is not really a problem as long as 'find_model' still      *)
   982 		(* interprets the resulting term correctly, without checking  *)
   983 		(* its type.                                                  *)
   984 	in
   985 		find_model thy (actual_params thy params) ex_closure true
   986 	end;
   987 
   988 (* ------------------------------------------------------------------------- *)
   989 (* refute_subgoal: calls 'refute_term' on a specific subgoal                 *)
   990 (* params        : list of '(name, value)' pairs used to override default    *)
   991 (*                 parameters                                                *)
   992 (* subgoal       : 0-based index specifying the subgoal number               *)
   993 (* ------------------------------------------------------------------------- *)
   994 
   995 	(* theory -> (string * string) list -> Thm.thm -> int -> unit *)
   996 
   997 	fun refute_subgoal thy params thm subgoal =
   998 		refute_term thy params (nth_elem (subgoal, prems_of thm));
   999 
  1000 
  1001 (* ------------------------------------------------------------------------- *)
  1002 (* INTERPRETERS                                                              *)
  1003 (* ------------------------------------------------------------------------- *)
  1004 
  1005 (* ------------------------------------------------------------------------- *)
  1006 (* make_constants: returns all interpretations that have the same tree       *)
  1007 (*                 structure as 'intr', but consist of unit vectors with     *)
  1008 (*                 'True'/'False' only (no Boolean variables)                *)
  1009 (* ------------------------------------------------------------------------- *)
  1010 
  1011 	(* interpretation -> interpretation list *)
  1012 
  1013 	fun make_constants intr =
  1014 	let
  1015 		(* returns a list with all unit vectors of length n *)
  1016 		(* int -> interpretation list *)
  1017 		fun unit_vectors n =
  1018 		let
  1019 			(* returns the k-th unit vector of length n *)
  1020 			(* int * int -> interpretation *)
  1021 			fun unit_vector (k,n) =
  1022 				Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
  1023 			(* int -> interpretation list -> interpretation list *)
  1024 			fun unit_vectors_acc k vs =
  1025 				if k>n then [] else (unit_vector (k,n))::(unit_vectors_acc (k+1) vs)
  1026 		in
  1027 			unit_vectors_acc 1 []
  1028 		end
  1029 		(* concatenates 'x' with every list in 'xss', returning a new list of lists *)
  1030 		(* 'a -> 'a list list -> 'a list list *)
  1031 		fun cons_list x xss =
  1032 			map (fn xs => x::xs) xss
  1033 		(* returns a list of lists, each one consisting of n (possibly identical) elements from 'xs' *)
  1034 		(* int -> 'a list -> 'a list list *)
  1035 		fun pick_all 1 xs =
  1036 			map (fn x => [x]) xs
  1037 		  | pick_all n xs =
  1038 			let val rec_pick = pick_all (n-1) xs in
  1039 				foldl (fn (acc,x) => (cons_list x rec_pick) @ acc) ([],xs)
  1040 			end
  1041 	in
  1042 		case intr of
  1043 		  Leaf xs => unit_vectors (length xs)
  1044 		| Node xs => map (fn xs' => Node xs') (pick_all (length xs) (make_constants (hd xs)))
  1045 	end;
  1046 
  1047 (* ------------------------------------------------------------------------- *)
  1048 (* size_of_type: returns the number of constants in a type (i.e. 'length     *)
  1049 (*               (make_constants intr)', but implemented more efficiently)   *)
  1050 (* ------------------------------------------------------------------------- *)
  1051 
  1052 	(* interpretation -> int *)
  1053 
  1054 	fun size_of_type intr =
  1055 	let
  1056 		(* power(a,b) computes a^b, for a>=0, b>=0 *)
  1057 		(* int * int -> int *)
  1058 		fun power (a,0) = 1
  1059 		  | power (a,1) = a
  1060 		  | power (a,b) = let val ab = power(a,b div 2) in ab * ab * power(a,b mod 2) end
  1061 	in
  1062 		case intr of
  1063 		  Leaf xs => length xs
  1064 		| Node xs => power (size_of_type (hd xs), length xs)
  1065 	end;
  1066 
  1067 (* ------------------------------------------------------------------------- *)
  1068 (* TT/FF: interpretations that denote "true" or "false", respectively        *)
  1069 (* ------------------------------------------------------------------------- *)
  1070 
  1071 	(* interpretation *)
  1072 
  1073 	val TT = Leaf [True, False];
  1074 
  1075 	val FF = Leaf [False, True];
  1076 
  1077 (* ------------------------------------------------------------------------- *)
  1078 (* make_equality: returns an interpretation that denotes (extensional)       *)
  1079 (*                equality of two interpretations                            *)
  1080 (* ------------------------------------------------------------------------- *)
  1081 
  1082 	(* We could in principle represent '=' on a type T by a particular        *)
  1083 	(* interpretation.  However, the size of that interpretation is quadratic *)
  1084 	(* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
  1085 	(* 'i2' directly is more efficient than constructing the interpretation   *)
  1086 	(* for equality on T first, and "applying" this interpretation to 'i1'    *)
  1087 	(* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
  1088 
  1089 	(* interpretation * interpretation -> interpretation *)
  1090 
  1091 	fun make_equality (i1, i2) =
  1092 	let
  1093 		(* interpretation * interpretation -> prop_formula *)
  1094 		fun equal (i1, i2) =
  1095 			(case i1 of
  1096 			  Leaf xs =>
  1097 				(case i2 of
  1098 				  Leaf ys => PropLogic.dot_product (xs, ys)
  1099 				| Node _  => raise REFUTE ("make_equality", "second interpretation is higher"))
  1100 			| Node xs =>
  1101 				(case i2 of
  1102 				  Leaf _  => raise REFUTE ("make_equality", "first interpretation is higher")
  1103 				| Node ys => PropLogic.all (map equal (xs ~~ ys))))
  1104 		(* interpretation * interpretation -> prop_formula *)
  1105 		fun not_equal (i1, i2) =
  1106 			(case i1 of
  1107 			  Leaf xs =>
  1108 				(case i2 of
  1109 				  Leaf ys => PropLogic.all ((PropLogic.exists xs) :: (PropLogic.exists ys) ::
  1110 					(map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))  (* defined and not equal *)
  1111 				| Node _  => raise REFUTE ("make_equality", "second interpretation is higher"))
  1112 			| Node xs =>
  1113 				(case i2 of
  1114 				  Leaf _  => raise REFUTE ("make_equality", "first interpretation is higher")
  1115 				| Node ys => PropLogic.exists (map not_equal (xs ~~ ys))))
  1116 	in
  1117 		(* a value may be undefined; therefore 'not_equal' is not just the     *)
  1118 		(* negation of 'equal':                                                *)
  1119 		(* - two interpretations are 'equal' iff they are both defined and     *)
  1120 		(*   denote the same value                                             *)
  1121 		(* - two interpretations are 'not_equal' iff they are both defined at  *)
  1122 		(*   least partially, and a defined part denotes different values      *)
  1123 		(* - an undefined interpretation is neither 'equal' nor 'not_equal' to *)
  1124 		(*   another value                                                     *)
  1125 		Leaf [equal (i1, i2), not_equal (i1, i2)]
  1126 	end;
  1127 
  1128 
  1129 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1130 
  1131 	(* simply typed lambda calculus: Isabelle's basic term syntax, with type  *)
  1132 	(* variables, function types, and propT                                   *)
  1133 
  1134 	fun stlc_interpreter thy model args t =
  1135 	let
  1136 		val (typs, terms)                           = model
  1137 		val {maxvars, next_idx, bounds, wellformed} = args
  1138 		(* Term.typ -> (interpretation * model * arguments) option *)
  1139 		fun interpret_groundterm T =
  1140 		let
  1141 			(* unit -> (interpretation * model * arguments) option *)
  1142 			fun interpret_groundtype () =
  1143 			let
  1144 				val size = (if T = Term.propT then 2 else (the o assoc) (typs, T))  (* the model MUST specify a size for ground types *)
  1145 				val next = (if size=2 then next_idx+1 else next_idx+size)  (* optimization for types with size 2 *)
  1146 				val _    = (if next-1>maxvars andalso maxvars>0 then raise MAXVARS_EXCEEDED else ())  (* check if 'maxvars' is large enough *)
  1147 				(* prop_formula list *)
  1148 				val fms  = (if size=2 then [BoolVar next_idx, Not (BoolVar next_idx)]
  1149 					else (map BoolVar (next_idx upto (next_idx+size-1))))
  1150 				(* interpretation *)
  1151 				val intr = Leaf fms
  1152 				(* prop_formula list -> prop_formula *)
  1153 				fun one_of_two_false []      = True
  1154 				  | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' => SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  1155 				(* prop_formula list -> prop_formula *)
  1156 				fun exactly_one_true xs = SAnd (PropLogic.exists xs, one_of_two_false xs)
  1157 				(* prop_formula *)
  1158 				val wf   = (if size=2 then True else exactly_one_true fms)
  1159 			in
  1160 				(* extend the model, increase 'next_idx', add well-formedness condition *)
  1161 				Some (intr, (typs, (t, intr)::terms), {maxvars = maxvars, next_idx = next, bounds = bounds, wellformed = SAnd (wellformed, wf)})
  1162 			end
  1163 		in
  1164 			case T of
  1165 			  Type ("fun", [T1, T2]) =>
  1166 				let
  1167 					(* we create 'size_of_type (interpret (... T1))' different copies *)
  1168 					(* of the interpretation for 'T2', which are then combined into a *)
  1169 					(* single new interpretation                                      *)
  1170 					val (i1, _, _) =
  1171 						(interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T1))
  1172 						handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1173 					(* make fresh copies, with different variable indices *)
  1174 					(* 'idx': next variable index                         *)
  1175 					(* 'n'  : number of copies                            *)
  1176 					(* int -> int -> (int * interpretation list * prop_formula *)
  1177 					fun make_copies idx 0 =
  1178 						(idx, [], True)
  1179 					  | make_copies idx n =
  1180 						let
  1181 							val (copy, _, new_args) =
  1182 								(interpret thy (typs, []) {maxvars = maxvars, next_idx = idx, bounds = [], wellformed = True} (Free ("dummy", T2))
  1183 								handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1184 							val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
  1185 						in
  1186 							(idx', copy :: copies, SAnd (#wellformed new_args, wf'))
  1187 						end
  1188 					val (next, copies, wf) = make_copies next_idx (size_of_type i1)
  1189 					(* combine copies into a single interpretation *)
  1190 					val intr = Node copies
  1191 				in
  1192 					(* extend the model, increase 'next_idx', add well-formedness condition *)
  1193 					Some (intr, (typs, (t, intr)::terms), {maxvars = maxvars, next_idx = next, bounds = bounds, wellformed = SAnd (wellformed, wf)})
  1194 				end
  1195 			| Type _  => interpret_groundtype ()
  1196 			| TFree _ => interpret_groundtype ()
  1197 			| TVar  _ => interpret_groundtype ()
  1198 		end
  1199 	in
  1200 		case assoc (terms, t) of
  1201 		  Some intr =>
  1202 			(* return an existing interpretation *)
  1203 			Some (intr, model, args)
  1204 		| None =>
  1205 			(case t of
  1206 			  Const (_, T)     =>
  1207 				interpret_groundterm T
  1208 			| Free (_, T)      =>
  1209 				interpret_groundterm T
  1210 			| Var (_, T)       =>
  1211 				interpret_groundterm T
  1212 			| Bound i          =>
  1213 				Some (nth_elem (i, #bounds args), model, args)
  1214 			| Abs (x, T, body) =>
  1215 				let
  1216 					(* create all constants of type 'T' *)
  1217 					val (i, _, _) =
  1218 						(interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1219 						handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1220 					val constants = make_constants i
  1221 					(* interpret the 'body' separately for each constant *)
  1222 					val ((model', args'), bodies) = foldl_map
  1223 						(fn ((m,a), c) =>
  1224 							let
  1225 								(* add 'c' to 'bounds' *)
  1226 								val (i', m', a') = interpret thy m {maxvars = #maxvars a, next_idx = #next_idx a, bounds = (c :: #bounds a), wellformed = #wellformed a} body
  1227 							in
  1228 								(* keep the new model m' and 'next_idx' and 'wellformed', but use old 'bounds' *)
  1229 								((m', {maxvars = maxvars, next_idx = #next_idx a', bounds = bounds, wellformed = #wellformed a'}), i')
  1230 							end)
  1231 						((model, args), constants)
  1232 				in
  1233 					Some (Node bodies, model', args')
  1234 				end
  1235 			| t1 $ t2          =>
  1236 				let
  1237 					(* auxiliary functions *)
  1238 					(* interpretation * interpretation -> interpretation *)
  1239 					fun interpretation_disjunction (tr1,tr2) =
  1240 						tree_map (fn (xs,ys) => map (fn (x,y) => SOr(x,y)) (xs ~~ ys)) (tree_pair (tr1,tr2))
  1241 					(* prop_formula * interpretation -> interpretation *)
  1242 					fun prop_formula_times_interpretation (fm,tr) =
  1243 						tree_map (map (fn x => SAnd (fm,x))) tr
  1244 					(* prop_formula list * interpretation list -> interpretation *)
  1245 					fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
  1246 						prop_formula_times_interpretation (fm,tr)
  1247 					  | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
  1248 						interpretation_disjunction (prop_formula_times_interpretation (fm,tr), prop_formula_list_dot_product_interpretation_list (fms,trees))
  1249 					  | prop_formula_list_dot_product_interpretation_list (_,_) =
  1250 						raise REFUTE ("stlc_interpreter", "empty list (in dot product)")
  1251 					(* concatenates 'x' with every list in 'xss', returning a new list of lists *)
  1252 					(* 'a -> 'a list list -> 'a list list *)
  1253 					fun cons_list x xss =
  1254 						map (fn xs => x::xs) xss
  1255 					(* returns a list of lists, each one consisting of one element from each element of 'xss' *)
  1256 					(* 'a list list -> 'a list list *)
  1257 					fun pick_all [xs] =
  1258 						map (fn x => [x]) xs
  1259 					  | pick_all (xs::xss) =
  1260 						let val rec_pick = pick_all xss in
  1261 							foldl (fn (acc,x) => (cons_list x rec_pick) @ acc) ([],xs)
  1262 						end
  1263 					  | pick_all _ =
  1264 						raise REFUTE ("stlc_interpreter", "empty list (in pick_all)")
  1265 					(* interpretation -> prop_formula list *)
  1266 					fun interpretation_to_prop_formula_list (Leaf xs) =
  1267 						xs
  1268 					  | interpretation_to_prop_formula_list (Node trees) =
  1269 						map PropLogic.all (pick_all (map interpretation_to_prop_formula_list trees))
  1270 					(* interpretation * interpretation -> interpretation *)
  1271 					fun interpretation_apply (tr1,tr2) =
  1272 						(case tr1 of
  1273 						  Leaf _ =>
  1274 							raise REFUTE ("stlc_interpreter", "first interpretation is a leaf")
  1275 						| Node xs =>
  1276 							prop_formula_list_dot_product_interpretation_list (interpretation_to_prop_formula_list tr2, xs))
  1277 					(* interpret 't1' and 't2' separately *)
  1278 					val (intr1, model1, args1) = interpret thy model args t1
  1279 					val (intr2, model2, args2) = interpret thy model1 args1 t2
  1280 				in
  1281 					Some (interpretation_apply (intr1,intr2), model2, args2)
  1282 				end)
  1283 	end;
  1284 
  1285 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1286 
  1287 	fun Pure_interpreter thy model args t =
  1288 		case t of
  1289 		  Const ("all", _) $ t1 =>  (* in the meta-logic, 'all' MUST be followed by an argument term *)
  1290 			let
  1291 				val (i, m, a) = interpret thy model args t1
  1292 			in
  1293 				case i of
  1294 				  Node xs =>
  1295 					let
  1296 						val fmTrue  = PropLogic.all (map toTrue xs)
  1297 						val fmFalse = PropLogic.exists (map toFalse xs)
  1298 					in
  1299 						Some (Leaf [fmTrue, fmFalse], m, a)
  1300 					end
  1301 				| _ =>
  1302 					raise REFUTE ("Pure_interpreter", "\"all\" is not followed by a function")
  1303 			end
  1304 		| Const ("==", _) $ t1 $ t2 =>
  1305 			let
  1306 				val (i1, m1, a1) = interpret thy model args t1
  1307 				val (i2, m2, a2) = interpret thy m1 a1 t2
  1308 			in
  1309 				Some (make_equality (i1, i2), m2, a2)
  1310 			end
  1311 		| Const ("==>", _) =>  (* simpler than translating 'Const ("==>", _) $ t1 $ t2' *)
  1312 			Some (Node [Node [TT, FF], Node [TT, TT]], model, args)
  1313 		| _ => None;
  1314 
  1315 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1316 
  1317 	fun HOLogic_interpreter thy model args t =
  1318 	let
  1319 		(* Term.term -> int -> Term.term *)
  1320 		fun eta_expand t i =
  1321 		let
  1322 			val Ts = binder_types (fastype_of t)
  1323 		in
  1324 			foldr (fn (T, t) => Abs ("<eta_expand>", T, t))
  1325 				(take (i, Ts), list_comb (t, map Bound (i-1 downto 0)))
  1326 		end
  1327 	in
  1328 	(* ------------------------------------------------------------------------- *)
  1329 	(* Providing interpretations directly is more efficient than unfolding the   *)
  1330 	(* logical constants.  IN HOL however, logical constants can themselves be   *)
  1331 	(* arguments.  "All" and "Ex" are then translated just like any other        *)
  1332 	(* constant, with the relevant axiom being added by 'collect_axioms'.        *)
  1333 	(* ------------------------------------------------------------------------- *)
  1334 		case t of
  1335 		  Const ("Trueprop", _) =>
  1336 			Some (Node [TT, FF], model, args)
  1337 		| Const ("Not", _) =>
  1338 			Some (Node [FF, TT], model, args)
  1339 		| Const ("True", _) =>  (* redundant, since 'True' is also an IDT constructor *)
  1340 			Some (TT, model, args)
  1341 		| Const ("False", _) =>  (* redundant, since 'False' is also an IDT constructor *)
  1342 			Some (FF, model, args)
  1343 		| Const ("All", _) $ t1 =>
  1344 			let
  1345 				val (i, m, a) = interpret thy model args t1
  1346 			in
  1347 				case i of
  1348 				  Node xs =>
  1349 					let
  1350 						val fmTrue  = PropLogic.all (map toTrue xs)
  1351 						val fmFalse = PropLogic.exists (map toFalse xs)
  1352 					in
  1353 						Some (Leaf [fmTrue, fmFalse], m, a)
  1354 					end
  1355 				| _ =>
  1356 					raise REFUTE ("HOLogic_interpreter", "\"All\" is not followed by a function")
  1357 			end
  1358 		| Const ("Ex", _) $ t1 =>
  1359 			let
  1360 				val (i, m, a) = interpret thy model args t1
  1361 			in
  1362 				case i of
  1363 				  Node xs =>
  1364 					let
  1365 						val fmTrue  = PropLogic.exists (map toTrue xs)
  1366 						val fmFalse = PropLogic.all (map toFalse xs)
  1367 					in
  1368 						Some (Leaf [fmTrue, fmFalse], m, a)
  1369 					end
  1370 				| _ =>
  1371 					raise REFUTE ("HOLogic_interpreter", "\"Ex\" is not followed by a function")
  1372 			end
  1373 		| Const ("op =", _) $ t1 $ t2 =>
  1374 			let
  1375 				val (i1, m1, a1) = interpret thy model args t1
  1376 				val (i2, m2, a2) = interpret thy m1 a1 t2
  1377 			in
  1378 				Some (make_equality (i1, i2), m2, a2)
  1379 			end
  1380 		| Const ("op =", _) $ t1 =>
  1381 			(Some (interpret thy model args (eta_expand t 1)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1382 		| Const ("op =", _) =>
  1383 			(Some (interpret thy model args (eta_expand t 2)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1384 		| Const ("op &", _) =>
  1385 			Some (Node [Node [TT, FF], Node [FF, FF]], model, args)
  1386 		| Const ("op |", _) =>
  1387 			Some (Node [Node [TT, TT], Node [TT, FF]], model, args)
  1388 		| Const ("op -->", _) =>
  1389 			Some (Node [Node [TT, FF], Node [TT, TT]], model, args)
  1390 		| _ => None
  1391 	end;
  1392 
  1393 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1394 
  1395 	fun set_interpreter thy model args t =
  1396 	(* "T set" is isomorphic to "T --> bool" *)
  1397 	let
  1398 		val (typs, terms) = model
  1399 		(* Term.term -> int -> Term.term *)
  1400 		fun eta_expand t i =
  1401 		let
  1402 			val Ts = binder_types (fastype_of t)
  1403 		in
  1404 			foldr (fn (T, t) => Abs ("<eta_expand>", T, t))
  1405 				(take (i, Ts), list_comb (t, map Bound (i-1 downto 0)))
  1406 		end
  1407 	in
  1408 		case assoc (terms, t) of
  1409 		  Some intr =>
  1410 			(* return an existing interpretation *)
  1411 			Some (intr, model, args)
  1412 		| None =>
  1413 			(case t of
  1414 			  Free (x, Type ("set", [T])) =>
  1415 				(let
  1416 					val (intr, _, args') = interpret thy (typs, []) args (Free (x, T --> HOLogic.boolT))
  1417 				in
  1418 					Some (intr, (typs, (t, intr)::terms), args')
  1419 				end handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1420 			| Var ((x,i), Type ("set", [T])) =>
  1421 				(let
  1422 					val (intr, _, args') = interpret thy (typs, []) args (Var ((x,i), T --> HOLogic.boolT))
  1423 				in
  1424 					Some (intr, (typs, (t, intr)::terms), args')
  1425 				end handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1426 			| Const (s, Type ("set", [T])) =>
  1427 				(let
  1428 					val (intr, _, args') = interpret thy (typs, []) args (Const (s, T --> HOLogic.boolT))
  1429 				in
  1430 					Some (intr, (typs, (t, intr)::terms), args')
  1431 				end handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1432 			(* 'Collect' == identity *)
  1433 			| Const ("Collect", _) $ t1 =>
  1434 				Some (interpret thy model args t1)
  1435 			| Const ("Collect", _) =>
  1436 				(Some (interpret thy model args (eta_expand t 1)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1437 			(* 'op :' == application *)
  1438 			| Const ("op :", _) $ t1 $ t2 =>
  1439 				Some (interpret thy model args (t2 $ t1))
  1440 			| Const ("op :", _) $ t1 =>
  1441 				(Some (interpret thy model args (eta_expand t 1)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1442 			| Const ("op :", _) =>
  1443 				(Some (interpret thy model args (eta_expand t 2)) handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1444 			| _ => None)
  1445 	end;
  1446 
  1447 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1448 
  1449 	fun IDT_interpreter thy model args t =
  1450 	let
  1451 		val (typs, terms) = model
  1452 		(* DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list -> DatatypeAux.dtyp -> Term.typ *)
  1453 		fun typ_of_dtyp descr typ_assoc (DatatypeAux.DtTFree a) =
  1454 			(* replace a 'DtTFree' variable by the associated type *)
  1455 			(the o assoc) (typ_assoc, DatatypeAux.DtTFree a)
  1456 		  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtRec i) =
  1457 			let
  1458 				val (s, ds, _) = (the o assoc) (descr, i)
  1459 			in
  1460 				Type (s, map (typ_of_dtyp descr typ_assoc) ds)
  1461 			end
  1462 		  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtType (s, ds)) =
  1463 			Type (s, map (typ_of_dtyp descr typ_assoc) ds)
  1464 		(* int list -> int *)
  1465 		fun sum xs = foldl op+ (0, xs)
  1466 		(* int list -> int *)
  1467 		fun product xs = foldl op* (1, xs)
  1468 		(* the size of an IDT is the sum (over its constructors) of the        *)
  1469 		(* product (over their arguments) of the size of the argument type     *)
  1470 		(* (Term.typ * int) list -> DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list -> (string * DatatypeAux.dtyp list) list -> int *)
  1471 		fun size_of_dtyp typs descr typ_assoc constrs =
  1472 			sum (map (fn (_, ds) =>
  1473 				product (map (fn d =>
  1474 					let
  1475 						val T         = typ_of_dtyp descr typ_assoc d
  1476 						val (i, _, _) =
  1477 							(interpret thy (typs, []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1478 							handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1479 					in
  1480 						size_of_type i
  1481 					end) ds)) constrs)
  1482 		(* Term.typ -> (interpretation * model * arguments) option *)
  1483 		fun interpret_variable (Type (s, Ts)) =
  1484 			(case DatatypePackage.datatype_info thy s of
  1485 			  Some info =>  (* inductive datatype *)
  1486 				let
  1487 					val (typs, terms) = model
  1488 					(* int option -- only recursive IDTs have an associated depth *)
  1489 					val depth         = assoc (typs, Type (s, Ts))
  1490 				in
  1491 					if depth = (Some 0) then  (* termination condition to avoid infinite recursion *)
  1492 						(* return a leaf of size 0 *)
  1493 						Some (Leaf [], model, args)
  1494 					else
  1495 						let
  1496 							val index               = #index info
  1497 							val descr               = #descr info
  1498 							val (_, dtyps, constrs) = (the o assoc) (descr, index)
  1499 							val typ_assoc           = dtyps ~~ Ts
  1500 							(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1501 							val _ = (if Library.exists (fn d =>
  1502 									case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
  1503 								then
  1504 									raise REFUTE ("IDT_interpreter", "datatype argument (for type " ^ Sign.string_of_typ (sign_of thy) (Type (s, Ts)) ^ ") is not a variable")
  1505 								else
  1506 									())
  1507 							(* if the model specifies a depth for the current type, decrement it to avoid infinite recursion *)
  1508 							val typs'    = (case depth of None => typs | Some n => overwrite (typs, (Type (s, Ts), n-1)))
  1509 							(* recursively compute the size of the datatype *)
  1510 							val size     = size_of_dtyp typs' descr typ_assoc constrs
  1511 							val next_idx = #next_idx args
  1512 							val next     = (if size=2 then next_idx+1 else next_idx+size)  (* optimization for types with size 2 *)
  1513 							val _        = (if next-1>(#maxvars args) andalso (#maxvars args)>0 then raise MAXVARS_EXCEEDED else ())  (* check if 'maxvars' is large enough *)
  1514 							(* prop_formula list *)
  1515 							val fms      = (if size=2 then [BoolVar next_idx, Not (BoolVar next_idx)]
  1516 								else (map BoolVar (next_idx upto (next_idx+size-1))))
  1517 							(* interpretation *)
  1518 							val intr     = Leaf fms
  1519 							(* prop_formula list -> prop_formula *)
  1520 							fun one_of_two_false []      = True
  1521 							  | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' => SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  1522 							(* prop_formula list -> prop_formula *)
  1523 							fun exactly_one_true xs = SAnd (PropLogic.exists xs, one_of_two_false xs)
  1524 							(* prop_formula *)
  1525 							val wf       = (if size=2 then True else exactly_one_true fms)
  1526 						in
  1527 							(* extend the model, increase 'next_idx', add well-formedness condition *)
  1528 							Some (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args, next_idx = next, bounds = #bounds args, wellformed = SAnd (#wellformed args, wf)})
  1529 						end
  1530 				end
  1531 			| None =>  (* not an inductive datatype *)
  1532 				None)
  1533 		  | interpret_variable _ =  (* a (free or schematic) type variable *)
  1534 			None
  1535 	in
  1536 		case assoc (terms, t) of
  1537 		  Some intr =>
  1538 			(* return an existing interpretation *)
  1539 			Some (intr, model, args)
  1540 		| None =>
  1541 			(case t of
  1542 			  Free (_, T)  => interpret_variable T
  1543 			| Var (_, T)   => interpret_variable T
  1544 			| Const (s, T) =>
  1545 				(* TODO: case, recursion, size *)
  1546 				let
  1547 					(* unit -> (interpretation * model * arguments) option *)
  1548 					fun interpret_constructor () =
  1549 						(case body_type T of
  1550 						  Type (s', Ts') =>
  1551 							(case DatatypePackage.datatype_info thy s' of
  1552 							  Some info =>  (* body type is an inductive datatype *)
  1553 								let
  1554 									val index               = #index info
  1555 									val descr               = #descr info
  1556 									val (_, dtyps, constrs) = (the o assoc) (descr, index)
  1557 									val typ_assoc           = dtyps ~~ Ts'
  1558 									(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1559 									val _ = (if Library.exists (fn d =>
  1560 											case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
  1561 										then
  1562 											raise REFUTE ("IDT_interpreter", "datatype argument (for type " ^ Sign.string_of_typ (sign_of thy) (Type (s', Ts')) ^ ") is not a variable")
  1563 										else
  1564 											())
  1565 									(* split the constructors into those occuring before/after 'Const (s, T)' *)
  1566 									val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
  1567 										not (cname = s andalso Type.typ_instance (Sign.tsig_of (sign_of thy)) (T,
  1568 											map (typ_of_dtyp descr typ_assoc) ctypes ---> Type (s', Ts')))) constrs
  1569 								in
  1570 									case constrs2 of
  1571 									  [] =>
  1572 										(* 'Const (s, T)' is not a constructor of this datatype *)
  1573 										None
  1574 									| c::cs =>
  1575 										let
  1576 											(* int option -- only recursive IDTs have an associated depth *)
  1577 											val depth = assoc (typs, Type (s', Ts'))
  1578 											val typs' = (case depth of None => typs | Some n => overwrite (typs, (Type (s', Ts'), n-1)))
  1579 											(* constructors before 'Const (s, T)' generate elements of the datatype *)
  1580 											val offset  = size_of_dtyp typs' descr typ_assoc constrs1
  1581 											(* 'Const (s, T)' and constructors after it generate elements of the datatype *)
  1582 											val total   = offset + (size_of_dtyp typs' descr typ_assoc constrs2)
  1583 											(* create an interpretation that corresponds to the constructor 'Const (s, T)' *)
  1584 											(* by recursion over its argument types                                        *)
  1585 											(* DatatypeAux.dtyp list -> interpretation *)
  1586 											fun make_partial [] =
  1587 												(* all entries of the leaf are 'False' *)
  1588 												Leaf (replicate total False)
  1589 											  | make_partial (d::ds) =
  1590 												let
  1591 													(* compute the "new" size of the type 'd' *)
  1592 													val T         = typ_of_dtyp descr typ_assoc d
  1593 													val (i, _, _) =
  1594 														(interpret thy (typs, []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1595 														handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1596 												in
  1597 													(* all entries of the whole subtree are 'False' *)
  1598 													Node (replicate (size_of_type i) (make_partial ds))
  1599 												end
  1600 											(* int * DatatypeAux.dtyp list -> int * interpretation *)
  1601 											fun make_constr (offset, []) =
  1602 												if offset<total then
  1603 													(offset+1, Leaf ((replicate offset False) @ True :: (replicate (total-offset-1) False)))
  1604 												else
  1605 													raise REFUTE ("IDT_interpreter", "internal error: offset >= total")
  1606 											  | make_constr (offset, d::ds) =
  1607 												let
  1608 													(* compute the "new" and "old" size of the type 'd' *)
  1609 													val T         = typ_of_dtyp descr typ_assoc d
  1610 													val (i, _, _) =
  1611 														(interpret thy (typs, []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1612 														handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1613 													val (i', _, _) =
  1614 														(interpret thy (typs', []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1615 														handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1616 													val size  = size_of_type i
  1617 													val size' = size_of_type i'
  1618 													val _ = if size<size' then
  1619 															raise REFUTE ("IDT_interpreter", "internal error: new size < old size")
  1620 														else
  1621 															()
  1622 													val (new_offset, intrs) = foldl_map make_constr (offset, replicate size' ds)
  1623 												in
  1624 													(* the first size' elements of the type actually yield a result *)
  1625 													(* element, while the remaining size-size' elements don't       *)
  1626 													(new_offset, Node (intrs @ (replicate (size-size') (make_partial ds))))
  1627 												end
  1628 										in
  1629 											Some ((snd o make_constr) (offset, snd c), model, args)
  1630 										end
  1631 								end
  1632 							| None =>  (* body type is not an inductive datatype *)
  1633 								None)
  1634 						| _ =>  (* body type is a (free or schematic) type variable *)
  1635 							None)
  1636 				in
  1637 					case interpret_constructor () of
  1638 					  Some x => Some x
  1639 					| None   => interpret_variable T
  1640 				end
  1641 			| _ => None)
  1642 	end;
  1643 
  1644 	(* theory -> model -> arguments -> Term.term -> (interpretation * model * arguments) option *)
  1645 
  1646 	(* only an optimization: 'card' could in principle be interpreted with    *)
  1647 	(* interpreters available already (using its definition), but the code    *)
  1648 	(* below is much more efficient                                           *)
  1649 
  1650 	fun Finite_Set_card_interpreter thy model args t =
  1651 		case t of
  1652 		  Const ("Finite_Set.card", Type ("fun", [Type ("set", [T]), Type ("nat", [])])) =>
  1653 			let
  1654 				val (i_nat, _, _) =
  1655 					(interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", Type ("nat", [])))
  1656 						handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1657 				val size_nat      = size_of_type i_nat
  1658 				val (i_set, _, _) =
  1659 					(interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", Type ("set", [T])))
  1660 						handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1661 				val constants     = make_constants i_set
  1662 				(* interpretation -> int *)
  1663 				fun number_of_elements (Node xs) =
  1664 					foldl (fn (n, x) =>
  1665 						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)
  1666 				  | number_of_elements (Leaf _) =
  1667 					raise REFUTE ("Finite_Set_card_interpreter", "interpretation for set type is a leaf")
  1668 				(* takes an interpretation for a set and returns an interpretation for a 'nat' *)
  1669 				(* interpretation -> interpretation *)
  1670 				fun card i =
  1671 					let
  1672 						val n = number_of_elements i
  1673 					in
  1674 						if n<size_nat then
  1675 							Leaf ((replicate n False) @ True :: (replicate (size_nat-n-1) False))
  1676 						else
  1677 							Leaf (replicate size_nat False)
  1678 					end
  1679 			in
  1680 				Some (Node (map card constants), model, args)
  1681 			end
  1682 		| _ =>
  1683 			None;
  1684 
  1685 
  1686 (* ------------------------------------------------------------------------- *)
  1687 (* PRINTERS                                                                  *)
  1688 (* ------------------------------------------------------------------------- *)
  1689 
  1690 	(* theory -> model -> Term.term -> interpretation -> (int -> bool) -> Term.term option *)
  1691 
  1692 	fun stlc_printer thy model t intr assignment =
  1693 	let
  1694 		(* Term.term -> Term.typ option *)
  1695 		fun typeof (Free (_, T))  = Some T
  1696 		  | typeof (Var (_, T))   = Some T
  1697 		  | typeof (Const (_, T)) = Some T
  1698 		  | typeof _              = None
  1699 		(* string -> string *)
  1700 		fun strip_leading_quote s =
  1701 			(implode o (fn ss => case ss of [] => [] | x::xs => if x="'" then xs else ss) o explode) s
  1702 		(* Term.typ -> string *)
  1703 		fun string_of_typ (Type (s, _))     = s
  1704 		  | string_of_typ (TFree (x, _))    = strip_leading_quote x
  1705 		  | string_of_typ (TVar ((x,i), _)) = strip_leading_quote x ^ string_of_int i
  1706 		(* interpretation -> int *)
  1707 		fun index_from_interpretation (Leaf xs) =
  1708 			let
  1709 				val idx = find_index (PropLogic.eval assignment) xs
  1710 			in
  1711 				if idx<0 then
  1712 					raise REFUTE ("stlc_printer", "illegal interpretation: no value assigned (SAT solver unsound?)")
  1713 				else
  1714 					idx
  1715 			end
  1716 		  | index_from_interpretation _ =
  1717 			raise REFUTE ("stlc_printer", "interpretation for ground type is not a leaf")
  1718 	in
  1719 		case typeof t of
  1720 		  Some T =>
  1721 			(case T of
  1722 			  Type ("fun", [T1, T2]) =>
  1723 				(let
  1724 					(* create all constants of type 'T1' *)
  1725 					val (i, _, _) = interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T1))
  1726 					val constants = make_constants i
  1727 					(* interpretation list *)
  1728 					val results = (case intr of
  1729 						  Node xs => xs
  1730 						| _       => raise REFUTE ("stlc_printer", "interpretation for function type is a leaf"))
  1731 					(* Term.term list *)
  1732 					val pairs = map (fn (arg, result) =>
  1733 						HOLogic.mk_prod
  1734 							(print thy model (Free ("dummy", T1)) arg assignment,
  1735 							 print thy model (Free ("dummy", T2)) result assignment))
  1736 						(constants ~~ results)
  1737 					(* Term.typ *)
  1738 					val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  1739 					val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  1740 					(* Term.term *)
  1741 					val HOLogic_empty_set = Const ("{}", HOLogic_setT)
  1742 					val HOLogic_insert    = Const ("insert", HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  1743 				in
  1744 					Some (foldr (fn (pair, acc) => HOLogic_insert $ pair $ acc) (pairs, HOLogic_empty_set))
  1745 				end handle CANNOT_INTERPRET _ => None)
  1746 			| Type ("prop", [])      =>
  1747 				(case index_from_interpretation intr of
  1748 				  0 => Some (HOLogic.mk_Trueprop HOLogic.true_const)
  1749 				| 1 => Some (HOLogic.mk_Trueprop HOLogic.false_const)
  1750 				| _ => raise REFUTE ("stlc_interpreter", "illegal interpretation for a propositional value"))
  1751 			| Type _  => Some (Const (string_of_typ T ^ string_of_int (index_from_interpretation intr), T))
  1752 			| TFree _ => Some (Const (string_of_typ T ^ string_of_int (index_from_interpretation intr), T))
  1753 			| TVar _  => Some (Const (string_of_typ T ^ string_of_int (index_from_interpretation intr), T)))
  1754 		| None =>
  1755 			None
  1756 	end;
  1757 
  1758 	(* theory -> model -> Term.term -> interpretation -> (int -> bool) -> string option *)
  1759 
  1760 	fun set_printer thy model t intr assignment =
  1761 	let
  1762 		(* Term.term -> Term.typ option *)
  1763 		fun typeof (Free (_, T))  = Some T
  1764 		  | typeof (Var (_, T))   = Some T
  1765 		  | typeof (Const (_, T)) = Some T
  1766 		  | typeof _              = None
  1767 	in
  1768 		case typeof t of
  1769 		  Some (Type ("set", [T])) =>
  1770 			(let
  1771 				(* create all constants of type 'T' *)
  1772 				val (i, _, _) = interpret thy model {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1773 				val constants = make_constants i
  1774 				(* interpretation list *)
  1775 				val results = (case intr of
  1776 					  Node xs => xs
  1777 					| _       => raise REFUTE ("set_printer", "interpretation for set type is a leaf"))
  1778 				(* Term.term list *)
  1779 				val elements = mapfilter (fn (arg, result) =>
  1780 					case result of
  1781 					  Leaf [fmTrue, fmFalse] =>
  1782 						if PropLogic.eval assignment fmTrue then
  1783 							Some (print thy model (Free ("dummy", T)) arg assignment)
  1784 						else if PropLogic.eval assignment fmFalse then
  1785 							None
  1786 						else
  1787 							raise REFUTE ("set_printer", "illegal interpretation: no value assigned (SAT solver unsound?)")
  1788 					| _ =>
  1789 						raise REFUTE ("set_printer", "illegal interpretation for a Boolean value"))
  1790 					(constants ~~ results)
  1791 				(* Term.typ *)
  1792 				val HOLogic_setT  = HOLogic.mk_setT T
  1793 				(* Term.term *)
  1794 				val HOLogic_empty_set = Const ("{}", HOLogic_setT)
  1795 				val HOLogic_insert    = Const ("insert", T --> HOLogic_setT --> HOLogic_setT)
  1796 			in
  1797 				Some (foldl (fn (acc, elem) => HOLogic_insert $ elem $ acc) (HOLogic_empty_set, elements))
  1798 			end handle CANNOT_INTERPRET _ => None)
  1799 		| _ =>
  1800 			None
  1801 	end;
  1802 
  1803 	(* theory -> model -> Term.term -> interpretation -> (int -> bool) -> Term.term option *)
  1804 
  1805 	fun IDT_printer thy model t intr assignment =
  1806 	let
  1807 		(* Term.term -> Term.typ option *)
  1808 		fun typeof (Free (_, T))  = Some T
  1809 		  | typeof (Var (_, T))   = Some T
  1810 		  | typeof (Const (_, T)) = Some T
  1811 		  | typeof _              = None
  1812 	in
  1813 		case typeof t of
  1814 		  Some (Type (s, Ts)) =>
  1815 			(case DatatypePackage.datatype_info thy s of
  1816 			  Some info =>  (* inductive datatype *)
  1817 				let
  1818 					val (typs, _)           = model
  1819 					val index               = #index info
  1820 					val descr               = #descr info
  1821 					val (_, dtyps, constrs) = (the o assoc) (descr, index)
  1822 					val typ_assoc           = dtyps ~~ Ts
  1823 					(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1824 					val _ = (if Library.exists (fn d =>
  1825 							case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
  1826 						then
  1827 							raise REFUTE ("IDT_printer", "datatype argument (for type " ^ Sign.string_of_typ (sign_of thy) (Type (s, Ts)) ^ ") is not a variable")
  1828 						else
  1829 							())
  1830 					(* the index of the element in the datatype *)
  1831 					val element = (case intr of
  1832 						  Leaf xs => find_index (PropLogic.eval assignment) xs
  1833 						| Node _  => raise REFUTE ("IDT_printer", "interpretation is not a leaf"))
  1834 					val _ = (if element<0 then raise REFUTE ("IDT_printer", "invalid interpretation (no value assigned)") else ())
  1835 					(* int option -- only recursive IDTs have an associated depth *)
  1836 					val depth = assoc (typs, Type (s, Ts))
  1837 					val typs' = (case depth of None => typs | Some n => overwrite (typs, (Type (s, Ts), n-1)))
  1838 					(* DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list -> DatatypeAux.dtyp -> Term.typ *)
  1839 					fun typ_of_dtyp descr typ_assoc (DatatypeAux.DtTFree a) =
  1840 						(* replace a 'DtTFree' variable by the associated type *)
  1841 						(the o assoc) (typ_assoc, DatatypeAux.DtTFree a)
  1842 					  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtRec i) =
  1843 						let
  1844 							val (s, ds, _) = (the o assoc) (descr, i)
  1845 						in
  1846 							Type (s, map (typ_of_dtyp descr typ_assoc) ds)
  1847 						end
  1848 					  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtType (s, ds)) =
  1849 						Type (s, map (typ_of_dtyp descr typ_assoc) ds)
  1850 					(* int list -> int *)
  1851 					fun sum xs = foldl op+ (0, xs)
  1852 					(* int list -> int *)
  1853 					fun product xs = foldl op* (1, xs)
  1854 					(* the size of an IDT is the sum (over its constructors) of the        *)
  1855 					(* product (over their arguments) of the size of the argument type     *)
  1856 					(* (Term.typ * int) list -> DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list -> (string * DatatypeAux.dtyp list) list -> int *)
  1857 					fun size_of_dtyp typs descr typ_assoc xs =
  1858 						sum (map (fn (_, ds) =>
  1859 							product (map (fn d =>
  1860 								let
  1861 									val T         = typ_of_dtyp descr typ_assoc d
  1862 									val (i, _, _) =
  1863 										(interpret thy (typs, []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
  1864 										handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1865 					in
  1866 						size_of_type i
  1867 					end) ds)) xs)
  1868 					(* int -> DatatypeAux.dtyp list -> Term.term list *)
  1869 					fun make_args n [] =
  1870 						if n<>0 then
  1871 							raise REFUTE ("IDT_printer", "error computing the element: remainder is not 0")
  1872 						else
  1873 							[]
  1874 					  | make_args n (d::ds) =
  1875 						let
  1876 							val dT        = typ_of_dtyp descr typ_assoc d
  1877 							val (i, _, _) =
  1878 								(interpret thy (typs', []) {maxvars=0, next_idx=1, bounds=[], wellformed=True} (Free ("dummy", dT))
  1879 								handle CANNOT_INTERPRET _ => raise CANNOT_INTERPRET t)
  1880 							val size      = size_of_type i
  1881 							val consts    = make_constants i  (* we only need the (n mod size)-th element of *)
  1882 								(* this list, so there might be a more efficient implementation that does not *)
  1883 								(* generate all constants                                                     *)
  1884 						in
  1885 							(print thy (typs', []) (Free ("dummy", dT)) (nth_elem (n mod size, consts)) assignment)::(make_args (n div size) ds)
  1886 						end
  1887 					(* int -> (string * DatatypeAux.dtyp list) list -> Term.term *)
  1888 					fun make_term _ [] =
  1889 						raise REFUTE ("IDT_printer", "invalid interpretation (value too large - not enough constructors)")
  1890 					  | make_term n (c::cs) =
  1891 						let
  1892 							val c_size = size_of_dtyp typs' descr typ_assoc [c]
  1893 						in
  1894 							if n<c_size then
  1895 								let
  1896 									val (cname, cargs) = c
  1897 									val c_term = Const (cname, (map (typ_of_dtyp descr typ_assoc) cargs) ---> Type (s, Ts))
  1898 								in
  1899 									foldl op$ (c_term, rev (make_args n (rev cargs)))
  1900 								end
  1901 							else
  1902 								make_term (n-c_size) cs
  1903 						end
  1904 				in
  1905 					Some (make_term element constrs)
  1906 				end
  1907 			| None =>  (* not an inductive datatype *)
  1908 				None)
  1909 		| _ =>  (* a (free or schematic) type variable *)
  1910 			None
  1911 	end;
  1912 
  1913 
  1914 (* ------------------------------------------------------------------------- *)
  1915 (* use 'setup Refute.setup' in an Isabelle theory to initialize the 'Refute' *)
  1916 (* structure                                                                 *)
  1917 (* ------------------------------------------------------------------------- *)
  1918 
  1919 (* ------------------------------------------------------------------------- *)
  1920 (* Note: the interpreters and printers are used in reverse order; however,   *)
  1921 (*       an interpreter that can handle non-atomic terms ends up being       *)
  1922 (*       applied before the 'stlc_interpreter' breaks the term apart into    *)
  1923 (*       subterms that are then passed to other interpreters!                *)
  1924 (* ------------------------------------------------------------------------- *)
  1925 
  1926 	(* (theory -> theory) list *)
  1927 
  1928 	val setup =
  1929 		[RefuteData.init,
  1930 		 add_interpreter "stlc"            stlc_interpreter,
  1931 		 add_interpreter "Pure"            Pure_interpreter,
  1932 		 add_interpreter "HOLogic"         HOLogic_interpreter,
  1933 		 add_interpreter "set"             set_interpreter,
  1934 		 add_interpreter "IDT"             IDT_interpreter,
  1935 		 add_interpreter "Finite_Set.card" Finite_Set_card_interpreter,
  1936 		 add_printer "stlc" stlc_printer,
  1937 		 add_printer "set"  set_printer,
  1938 		 add_printer "IDT"  IDT_printer];
  1939 
  1940 end