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