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