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