src/HOL/Tools/refute.ML
author webertj
Fri Jan 19 21:20:10 2007 +0100 (2007-01-19)
changeset 22092 ab3dfcef6489
parent 22055 7c81de75d2c3
child 22093 98e3e9f00192
permissions -rw-r--r--
reformatted to 80 chars/line
webertj@14350
     1
(*  Title:      HOL/Tools/refute.ML
webertj@14350
     2
    ID:         $Id$
webertj@14350
     3
    Author:     Tjark Weber
webertj@21985
     4
    Copyright   2003-2007
webertj@14350
     5
webertj@14965
     6
Finite model generation for HOL formulas, using a SAT solver.
webertj@14350
     7
*)
webertj@14350
     8
webertj@14456
     9
(* ------------------------------------------------------------------------- *)
webertj@14456
    10
(* Declares the 'REFUTE' signature as well as a structure 'Refute'.          *)
webertj@14456
    11
(* Documentation is available in the Isabelle/Isar theory 'HOL/Refute.thy'.  *)
webertj@14350
    12
(* ------------------------------------------------------------------------- *)
webertj@14350
    13
webertj@14350
    14
signature REFUTE =
webertj@14350
    15
sig
webertj@14350
    16
webertj@14456
    17
	exception REFUTE of string * string
webertj@14456
    18
webertj@14456
    19
(* ------------------------------------------------------------------------- *)
webertj@14807
    20
(* Model/interpretation related code (translation HOL -> propositional logic *)
webertj@14456
    21
(* ------------------------------------------------------------------------- *)
webertj@14456
    22
webertj@14807
    23
	type params
webertj@14456
    24
	type interpretation
webertj@14456
    25
	type model
webertj@14456
    26
	type arguments
webertj@14456
    27
webertj@14807
    28
	exception MAXVARS_EXCEEDED
webertj@14456
    29
webertj@22092
    30
	val add_interpreter : string -> (theory -> model -> arguments -> Term.term ->
webertj@22092
    31
		(interpretation * model * arguments) option) -> theory -> theory
webertj@22092
    32
	val add_printer     : string -> (theory -> model -> Term.term ->
webertj@22092
    33
		interpretation -> (int -> bool) -> Term.term option) -> theory -> theory
webertj@14456
    34
webertj@22092
    35
	val interpret : theory -> model -> arguments -> Term.term ->
webertj@22092
    36
		(interpretation * model * arguments)
webertj@14807
    37
webertj@22092
    38
	val print       : theory -> model -> Term.term -> interpretation ->
webertj@22092
    39
		(int -> bool) -> Term.term
webertj@14456
    40
	val print_model : theory -> model -> (int -> bool) -> string
webertj@14456
    41
webertj@14456
    42
(* ------------------------------------------------------------------------- *)
webertj@14456
    43
(* Interface                                                                 *)
webertj@14456
    44
(* ------------------------------------------------------------------------- *)
webertj@14456
    45
webertj@14456
    46
	val set_default_param  : (string * string) -> theory -> theory
webertj@14456
    47
	val get_default_param  : theory -> string -> string option
webertj@14456
    48
	val get_default_params : theory -> (string * string) list
webertj@14807
    49
	val actual_params      : theory -> (string * string) list -> params
webertj@14456
    50
webertj@14807
    51
	val find_model : theory -> params -> Term.term -> bool -> unit
webertj@14456
    52
webertj@22092
    53
	(* tries to find a model for a formula: *)
webertj@22092
    54
	val satisfy_term   : theory -> (string * string) list -> Term.term -> unit
webertj@22092
    55
	(* tries to find a model that refutes a formula: *)
webertj@22092
    56
	val refute_term    : theory -> (string * string) list -> Term.term -> unit
webertj@22092
    57
	val refute_subgoal :
webertj@22092
    58
		theory -> (string * string) list -> Thm.thm -> int -> unit
webertj@14456
    59
wenzelm@18708
    60
	val setup : theory -> theory
webertj@22092
    61
webertj@22092
    62
end;  (* signature REFUTE *)
webertj@14456
    63
webertj@14456
    64
structure Refute : REFUTE =
webertj@14456
    65
struct
webertj@14456
    66
webertj@14456
    67
	open PropLogic;
webertj@14456
    68
webertj@14350
    69
	(* We use 'REFUTE' only for internal error conditions that should    *)
webertj@14350
    70
	(* never occur in the first place (i.e. errors caused by bugs in our *)
webertj@14350
    71
	(* code).  Otherwise (e.g. to indicate invalid input data) we use    *)
webertj@14350
    72
	(* 'error'.                                                          *)
webertj@14456
    73
	exception REFUTE of string * string;  (* ("in function", "cause") *)
webertj@14350
    74
webertj@14807
    75
	(* should be raised by an interpreter when more variables would be *)
webertj@14807
    76
	(* required than allowed by 'maxvars'                              *)
webertj@14807
    77
	exception MAXVARS_EXCEEDED;
webertj@14350
    78
webertj@14350
    79
(* ------------------------------------------------------------------------- *)
webertj@14350
    80
(* TREES                                                                     *)
webertj@14350
    81
(* ------------------------------------------------------------------------- *)
webertj@14350
    82
webertj@14350
    83
(* ------------------------------------------------------------------------- *)
webertj@14350
    84
(* tree: implements an arbitrarily (but finitely) branching tree as a list   *)
webertj@14350
    85
(*       of (lists of ...) elements                                          *)
webertj@14350
    86
(* ------------------------------------------------------------------------- *)
webertj@14350
    87
webertj@14350
    88
	datatype 'a tree =
webertj@14350
    89
		  Leaf of 'a
webertj@14350
    90
		| Node of ('a tree) list;
webertj@14350
    91
webertj@14350
    92
	(* ('a -> 'b) -> 'a tree -> 'b tree *)
webertj@14350
    93
webertj@14350
    94
	fun tree_map f tr =
webertj@14350
    95
		case tr of
webertj@14350
    96
		  Leaf x  => Leaf (f x)
webertj@14350
    97
		| Node xs => Node (map (tree_map f) xs);
webertj@14350
    98
webertj@14350
    99
	(* ('a * 'b -> 'a) -> 'a * ('b tree) -> 'a *)
webertj@14350
   100
webertj@14350
   101
	fun tree_foldl f =
webertj@14350
   102
	let
webertj@14350
   103
		fun itl (e, Leaf x)  = f(e,x)
skalberg@15570
   104
		  | itl (e, Node xs) = Library.foldl (tree_foldl f) (e,xs)
webertj@14350
   105
	in
webertj@14350
   106
		itl
webertj@14350
   107
	end;
webertj@14350
   108
webertj@14350
   109
	(* 'a tree * 'b tree -> ('a * 'b) tree *)
webertj@14350
   110
webertj@15611
   111
	fun tree_pair (t1, t2) =
webertj@14350
   112
		case t1 of
webertj@14350
   113
		  Leaf x =>
webertj@14350
   114
			(case t2 of
webertj@14350
   115
				  Leaf y => Leaf (x,y)
webertj@22092
   116
				| Node _ => raise REFUTE ("tree_pair",
webertj@22092
   117
						"trees are of different height (second tree is higher)"))
webertj@14350
   118
		| Node xs =>
webertj@14350
   119
			(case t2 of
webertj@14807
   120
				  (* '~~' will raise an exception if the number of branches in   *)
webertj@14807
   121
				  (* both trees is different at the current node                 *)
webertj@14350
   122
				  Node ys => Node (map tree_pair (xs ~~ ys))
webertj@22092
   123
				| Leaf _  => raise REFUTE ("tree_pair",
webertj@22092
   124
						"trees are of different height (first tree is higher)"));
webertj@14350
   125
webertj@14350
   126
(* ------------------------------------------------------------------------- *)
webertj@14807
   127
(* params: parameters that control the translation into a propositional      *)
webertj@14807
   128
(*         formula/model generation                                          *)
webertj@14807
   129
(*                                                                           *)
webertj@14807
   130
(* The following parameters are supported (and required (!), except for      *)
webertj@14807
   131
(* "sizes"):                                                                 *)
webertj@14807
   132
(*                                                                           *)
webertj@14807
   133
(* Name          Type    Description                                         *)
webertj@14807
   134
(*                                                                           *)
webertj@14807
   135
(* "sizes"       (string * int) list                                         *)
webertj@14807
   136
(*                       Size of ground types (e.g. 'a=2), or depth of IDTs. *)
webertj@14807
   137
(* "minsize"     int     If >0, minimal size of each ground type/IDT depth.  *)
webertj@14807
   138
(* "maxsize"     int     If >0, maximal size of each ground type/IDT depth.  *)
webertj@14807
   139
(* "maxvars"     int     If >0, use at most 'maxvars' Boolean variables      *)
webertj@14807
   140
(*                       when transforming the term into a propositional     *)
webertj@14807
   141
(*                       formula.                                            *)
webertj@14807
   142
(* "maxtime"     int     If >0, terminate after at most 'maxtime' seconds.   *)
webertj@14807
   143
(* "satsolver"   string  SAT solver to be used.                              *)
webertj@14807
   144
(* ------------------------------------------------------------------------- *)
webertj@14807
   145
webertj@14807
   146
	type params =
webertj@14807
   147
		{
webertj@14807
   148
			sizes    : (string * int) list,
webertj@14807
   149
			minsize  : int,
webertj@14807
   150
			maxsize  : int,
webertj@14807
   151
			maxvars  : int,
webertj@14807
   152
			maxtime  : int,
webertj@14807
   153
			satsolver: string
webertj@14807
   154
		};
webertj@14807
   155
webertj@14807
   156
(* ------------------------------------------------------------------------- *)
webertj@14456
   157
(* interpretation: a term's interpretation is given by a variable of type    *)
webertj@14456
   158
(*                 'interpretation'                                          *)
webertj@14350
   159
(* ------------------------------------------------------------------------- *)
webertj@14350
   160
webertj@14456
   161
	type interpretation =
webertj@14456
   162
		prop_formula list tree;
webertj@14350
   163
webertj@14350
   164
(* ------------------------------------------------------------------------- *)
webertj@14456
   165
(* model: a model specifies the size of types and the interpretation of      *)
webertj@14456
   166
(*        terms                                                              *)
webertj@14350
   167
(* ------------------------------------------------------------------------- *)
webertj@14350
   168
webertj@14456
   169
	type model =
webertj@14456
   170
		(Term.typ * int) list * (Term.term * interpretation) list;
webertj@14350
   171
webertj@14456
   172
(* ------------------------------------------------------------------------- *)
webertj@14456
   173
(* arguments: additional arguments required during interpretation of terms   *)
webertj@14456
   174
(* ------------------------------------------------------------------------- *)
webertj@14807
   175
webertj@14456
   176
	type arguments =
webertj@14807
   177
		{
webertj@22092
   178
			(* just passed unchanged from 'params': *)
webertj@22092
   179
			maxvars   : int,
webertj@22092
   180
			(* whether to use 'make_equality' or 'make_def_equality': *)
webertj@22092
   181
			def_eq    : bool,
webertj@22092
   182
			(* the following may change during the translation: *)
webertj@14807
   183
			next_idx  : int,
webertj@14807
   184
			bounds    : interpretation list,
webertj@14807
   185
			wellformed: prop_formula
webertj@14807
   186
		};
webertj@14456
   187
webertj@14350
   188
webertj@14456
   189
	structure RefuteDataArgs =
webertj@14456
   190
	struct
webertj@14456
   191
		val name = "HOL/refute";
webertj@14456
   192
		type T =
webertj@22092
   193
			{interpreters: (string * (theory -> model -> arguments -> Term.term ->
webertj@22092
   194
				(interpretation * model * arguments) option)) list,
webertj@22092
   195
			 printers: (string * (theory -> model -> Term.term -> interpretation ->
webertj@22092
   196
				(int -> bool) -> Term.term option)) list,
webertj@14456
   197
			 parameters: string Symtab.table};
webertj@14456
   198
		val empty = {interpreters = [], printers = [], parameters = Symtab.empty};
webertj@14456
   199
		val copy = I;
wenzelm@16424
   200
		val extend = I;
wenzelm@16424
   201
		fun merge _
webertj@14456
   202
			({interpreters = in1, printers = pr1, parameters = pa1},
webertj@14456
   203
			 {interpreters = in2, printers = pr2, parameters = pa2}) =
haftmann@21098
   204
			{interpreters = AList.merge (op =) (K true) (in1, in2),
haftmann@21098
   205
			 printers = AList.merge (op =) (K true) (pr1, pr2),
webertj@14456
   206
			 parameters = Symtab.merge (op=) (pa1, pa2)};
webertj@14456
   207
		fun print sg {interpreters, printers, parameters} =
webertj@14456
   208
			Pretty.writeln (Pretty.chunks
webertj@22092
   209
				[Pretty.strs ("default parameters:" :: List.concat (map
webertj@22092
   210
					(fn (name, value) => [name, "=", value]) (Symtab.dest parameters))),
webertj@14456
   211
				 Pretty.strs ("interpreters:" :: map fst interpreters),
webertj@14456
   212
				 Pretty.strs ("printers:" :: map fst printers)]);
webertj@14456
   213
	end;
webertj@14456
   214
webertj@14456
   215
	structure RefuteData = TheoryDataFun(RefuteDataArgs);
webertj@14456
   216
webertj@14350
   217
webertj@14350
   218
(* ------------------------------------------------------------------------- *)
webertj@15334
   219
(* interpret: interprets the term 't' using a suitable interpreter; returns  *)
webertj@15334
   220
(*            the interpretation and a (possibly extended) model that keeps  *)
webertj@15334
   221
(*            track of the interpretation of subterms                        *)
webertj@14350
   222
(* ------------------------------------------------------------------------- *)
webertj@14350
   223
webertj@22092
   224
	(* theory -> model -> arguments -> Term.term ->
webertj@22092
   225
		(interpretation * model * arguments) *)
webertj@14456
   226
webertj@14456
   227
	fun interpret thy model args t =
webertj@22092
   228
		case get_first (fn (_, f) => f thy model args t)
webertj@22092
   229
			(#interpreters (RefuteData.get thy)) of
webertj@22092
   230
		  NONE   => raise REFUTE ("interpret",
webertj@22092
   231
				"no interpreter for term " ^ quote (Sign.string_of_term thy t))
webertj@22092
   232
		| SOME x => x;
webertj@14456
   233
webertj@14456
   234
(* ------------------------------------------------------------------------- *)
webertj@15547
   235
(* print: converts the constant denoted by the term 't' into a term using a  *)
webertj@15547
   236
(*        suitable printer                                                   *)
webertj@14456
   237
(* ------------------------------------------------------------------------- *)
webertj@14350
   238
webertj@22092
   239
	(* theory -> model -> Term.term -> interpretation -> (int -> bool) ->
webertj@22092
   240
		Term.term *)
webertj@14456
   241
webertj@14456
   242
	fun print thy model t intr assignment =
webertj@22092
   243
		case get_first (fn (_, f) => f thy model t intr assignment)
webertj@22092
   244
			(#printers (RefuteData.get thy)) of
webertj@22092
   245
		  NONE   => raise REFUTE ("print",
webertj@22092
   246
				"no printer for term " ^ quote (Sign.string_of_term thy t))
webertj@22092
   247
		| SOME x => x;
webertj@14456
   248
webertj@14456
   249
(* ------------------------------------------------------------------------- *)
webertj@14456
   250
(* print_model: turns the model into a string, using a fixed interpretation  *)
webertj@14807
   251
(*              (given by an assignment for Boolean variables) and suitable  *)
webertj@14456
   252
(*              printers                                                     *)
webertj@14456
   253
(* ------------------------------------------------------------------------- *)
webertj@14456
   254
webertj@14807
   255
	(* theory -> model -> (int -> bool) -> string *)
webertj@14807
   256
webertj@14456
   257
	fun print_model thy model assignment =
webertj@14456
   258
	let
webertj@14456
   259
		val (typs, terms) = model
webertj@14807
   260
		val typs_msg =
webertj@14807
   261
			if null typs then
webertj@14807
   262
				"empty universe (no type variables in term)\n"
webertj@14807
   263
			else
webertj@22092
   264
				"Size of types: " ^ commas (map (fn (T, i) =>
webertj@22092
   265
					Sign.string_of_typ thy T ^ ": " ^ string_of_int i) typs) ^ "\n"
webertj@14807
   266
		val show_consts_msg =
webertj@14807
   267
			if not (!show_consts) andalso Library.exists (is_Const o fst) terms then
webertj@14807
   268
				"set \"show_consts\" to show the interpretation of constants\n"
webertj@14807
   269
			else
webertj@14807
   270
				""
webertj@14807
   271
		val terms_msg =
webertj@14807
   272
			if null terms then
webertj@14807
   273
				"empty interpretation (no free variables in term)\n"
webertj@14807
   274
			else
webertj@15611
   275
				space_implode "\n" (List.mapPartial (fn (t, intr) =>
webertj@14807
   276
					(* print constants only if 'show_consts' is true *)
webertj@14807
   277
					if (!show_consts) orelse not (is_Const t) then
webertj@22092
   278
						SOME (Sign.string_of_term thy t ^ ": " ^
webertj@22092
   279
							Sign.string_of_term thy (print thy model t intr assignment))
webertj@14807
   280
					else
skalberg@15531
   281
						NONE) terms) ^ "\n"
webertj@14456
   282
	in
webertj@14807
   283
		typs_msg ^ show_consts_msg ^ terms_msg
webertj@14456
   284
	end;
webertj@14456
   285
webertj@14456
   286
webertj@14456
   287
(* ------------------------------------------------------------------------- *)
webertj@14456
   288
(* PARAMETER MANAGEMENT                                                      *)
webertj@14456
   289
(* ------------------------------------------------------------------------- *)
webertj@14456
   290
webertj@22092
   291
	(* string -> (theory -> model -> arguments -> Term.term ->
webertj@22092
   292
		(interpretation * model * arguments) option) -> theory -> theory *)
webertj@14456
   293
webertj@14456
   294
	fun add_interpreter name f thy =
webertj@14456
   295
	let
webertj@14456
   296
		val {interpreters, printers, parameters} = RefuteData.get thy
webertj@14456
   297
	in
haftmann@17314
   298
		case AList.lookup (op =) interpreters name of
webertj@22092
   299
		  NONE   => RefuteData.put {interpreters = (name, f) :: interpreters,
webertj@22092
   300
			printers = printers, parameters = parameters} thy
skalberg@15531
   301
		| SOME _ => error ("Interpreter " ^ name ^ " already declared")
webertj@14456
   302
	end;
webertj@14456
   303
webertj@22092
   304
	(* string -> (theory -> model -> Term.term -> interpretation ->
webertj@22092
   305
		(int -> bool) -> Term.term option) -> theory -> theory *)
webertj@14456
   306
webertj@14456
   307
	fun add_printer name f thy =
webertj@14456
   308
	let
webertj@14456
   309
		val {interpreters, printers, parameters} = RefuteData.get thy
webertj@14456
   310
	in
haftmann@17314
   311
		case AList.lookup (op =) printers name of
webertj@22092
   312
		  NONE   => RefuteData.put {interpreters = interpreters,
webertj@22092
   313
			printers = (name, f) :: printers, parameters = parameters} thy
skalberg@15531
   314
		| SOME _ => error ("Printer " ^ name ^ " already declared")
webertj@14456
   315
	end;
webertj@14456
   316
webertj@14456
   317
(* ------------------------------------------------------------------------- *)
webertj@14456
   318
(* set_default_param: stores the '(name, value)' pair in RefuteData's        *)
webertj@14456
   319
(*                    parameter table                                        *)
webertj@14456
   320
(* ------------------------------------------------------------------------- *)
webertj@14456
   321
webertj@14456
   322
	(* (string * string) -> theory -> theory *)
webertj@14456
   323
webertj@14456
   324
	fun set_default_param (name, value) thy =
webertj@14456
   325
	let
webertj@14456
   326
		val {interpreters, printers, parameters} = RefuteData.get thy
webertj@14456
   327
	in
webertj@22092
   328
		RefuteData.put (case Symtab.lookup parameters name of
webertj@22092
   329
		  NONE   =>
webertj@22092
   330
			{interpreters = interpreters, printers = printers,
webertj@22092
   331
				parameters = Symtab.extend (parameters, [(name, value)])}
webertj@22092
   332
		| SOME _ =>
webertj@22092
   333
			{interpreters = interpreters, printers = printers,
webertj@22092
   334
				parameters = Symtab.update (name, value) parameters}) thy
webertj@14350
   335
	end;
webertj@14350
   336
webertj@14350
   337
(* ------------------------------------------------------------------------- *)
webertj@14456
   338
(* get_default_param: retrieves the value associated with 'name' from        *)
webertj@14456
   339
(*                    RefuteData's parameter table                           *)
webertj@14456
   340
(* ------------------------------------------------------------------------- *)
webertj@14456
   341
webertj@14456
   342
	(* theory -> string -> string option *)
webertj@14456
   343
wenzelm@17412
   344
	val get_default_param = Symtab.lookup o #parameters o RefuteData.get;
webertj@14456
   345
webertj@14456
   346
(* ------------------------------------------------------------------------- *)
webertj@14456
   347
(* get_default_params: returns a list of all '(name, value)' pairs that are  *)
webertj@14456
   348
(*                     stored in RefuteData's parameter table                *)
webertj@14456
   349
(* ------------------------------------------------------------------------- *)
webertj@14456
   350
webertj@14456
   351
	(* theory -> (string * string) list *)
webertj@14456
   352
wenzelm@17261
   353
	val get_default_params = Symtab.dest o #parameters o RefuteData.get;
webertj@14456
   354
webertj@14456
   355
(* ------------------------------------------------------------------------- *)
webertj@14456
   356
(* actual_params: takes a (possibly empty) list 'params' of parameters that  *)
webertj@14456
   357
(*      override the default parameters currently specified in 'thy', and    *)
webertj@14807
   358
(*      returns a record that can be passed to 'find_model'.                 *)
webertj@14456
   359
(* ------------------------------------------------------------------------- *)
webertj@14456
   360
webertj@14807
   361
	(* theory -> (string * string) list -> params *)
webertj@14456
   362
webertj@14807
   363
	fun actual_params thy override =
webertj@14456
   364
	let
webertj@14456
   365
		(* (string * string) list * string -> int *)
webertj@14456
   366
		fun read_int (parms, name) =
haftmann@17314
   367
			case AList.lookup (op =) parms name of
skalberg@15531
   368
			  SOME s => (case Int.fromString s of
webertj@14456
   369
				  SOME i => i
webertj@22092
   370
				| NONE   => error ("parameter " ^ quote name ^
webertj@22092
   371
					" (value is " ^ quote s ^ ") must be an integer value"))
webertj@22092
   372
			| NONE   => error ("parameter " ^ quote name ^
webertj@22092
   373
					" must be assigned a value")
webertj@14456
   374
		(* (string * string) list * string -> string *)
webertj@14456
   375
		fun read_string (parms, name) =
haftmann@17314
   376
			case AList.lookup (op =) parms name of
skalberg@15531
   377
			  SOME s => s
webertj@22092
   378
			| NONE   => error ("parameter " ^ quote name ^
webertj@22092
   379
				" must be assigned a value")
webertj@22092
   380
		(* 'override' first, defaults last: *)
webertj@14456
   381
		(* (string * string) list *)
webertj@22092
   382
		val allparams = override @ (get_default_params thy)
webertj@14456
   383
		(* int *)
webertj@14456
   384
		val minsize   = read_int (allparams, "minsize")
webertj@14456
   385
		val maxsize   = read_int (allparams, "maxsize")
webertj@14456
   386
		val maxvars   = read_int (allparams, "maxvars")
webertj@20544
   387
		val maxtime   = read_int (allparams, "maxtime")
webertj@14456
   388
		(* string *)
webertj@14456
   389
		val satsolver = read_string (allparams, "satsolver")
webertj@22092
   390
		(* all remaining parameters of the form "string=int" are collected in *)
webertj@22092
   391
		(* 'sizes'                                                            *)
webertj@22092
   392
		(* TODO: it is currently not possible to specify a size for a type    *)
webertj@22092
   393
		(*       whose name is one of the other parameters (e.g. 'maxvars')   *)
webertj@14807
   394
		(* (string * int) list *)
skalberg@15570
   395
		val sizes     = List.mapPartial
webertj@22092
   396
			(fn (name, value) => Option.map (pair name) (Int.fromString value))
webertj@22092
   397
			(List.filter (fn (name, _) => name<>"minsize" andalso name<>"maxsize"
webertj@22092
   398
				andalso name<>"maxvars" andalso name<>"maxtime"
webertj@22092
   399
				andalso name<>"satsolver") allparams)
webertj@14456
   400
	in
webertj@22092
   401
		{sizes=sizes, minsize=minsize, maxsize=maxsize, maxvars=maxvars,
webertj@22092
   402
			maxtime=maxtime, satsolver=satsolver}
webertj@14807
   403
	end;
webertj@14807
   404
webertj@14807
   405
webertj@14807
   406
(* ------------------------------------------------------------------------- *)
webertj@14807
   407
(* TRANSLATION HOL -> PROPOSITIONAL LOGIC, BOOLEAN ASSIGNMENT -> MODEL       *)
webertj@14807
   408
(* ------------------------------------------------------------------------- *)
webertj@14807
   409
webertj@22092
   410
	(* (''a * 'b) list -> ''a -> 'b *)
webertj@22092
   411
webertj@22092
   412
	fun lookup xs key =
webertj@22092
   413
		Option.valOf (AList.lookup (op =) xs key);
webertj@22092
   414
webertj@14807
   415
(* ------------------------------------------------------------------------- *)
webertj@15335
   416
(* typ_of_dtyp: converts a data type ('DatatypeAux.dtyp') into a type        *)
webertj@15335
   417
(*              ('Term.typ'), given type parameters for the data type's type *)
webertj@15335
   418
(*              arguments                                                    *)
webertj@15335
   419
(* ------------------------------------------------------------------------- *)
webertj@15335
   420
webertj@22092
   421
	(* DatatypeAux.descr -> (DatatypeAux.dtyp * Term.typ) list ->
webertj@22092
   422
		DatatypeAux.dtyp -> Term.typ *)
webertj@15335
   423
webertj@15335
   424
	fun typ_of_dtyp descr typ_assoc (DatatypeAux.DtTFree a) =
webertj@15335
   425
		(* replace a 'DtTFree' variable by the associated type *)
webertj@22092
   426
		lookup typ_assoc (DatatypeAux.DtTFree a)
webertj@15547
   427
	  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtType (s, ds)) =
webertj@15547
   428
		Type (s, map (typ_of_dtyp descr typ_assoc) ds)
webertj@15335
   429
	  | typ_of_dtyp descr typ_assoc (DatatypeAux.DtRec i) =
webertj@15335
   430
		let
webertj@22092
   431
			val (s, ds, _) = lookup descr i
webertj@15335
   432
		in
webertj@15335
   433
			Type (s, map (typ_of_dtyp descr typ_assoc) ds)
webertj@15547
   434
		end;
webertj@15335
   435
webertj@15335
   436
(* ------------------------------------------------------------------------- *)
webertj@21985
   437
(* close_form: universal closure over schematic variables in 't'             *)
webertj@21985
   438
(* ------------------------------------------------------------------------- *)
webertj@21985
   439
webertj@21985
   440
	(* Term.term -> Term.term *)
webertj@21985
   441
webertj@21985
   442
	fun close_form t =
webertj@21985
   443
	let
webertj@21985
   444
		(* (Term.indexname * Term.typ) list *)
webertj@21985
   445
		val vars = sort_wrt (fst o fst) (map dest_Var (term_vars t))
webertj@21985
   446
	in
webertj@22092
   447
		Library.foldl (fn (t', ((x, i), T)) =>
webertj@22092
   448
			(Term.all T) $ Abs (x, T, abstract_over (Var ((x, i), T), t')))
webertj@21985
   449
			(t, vars)
webertj@21985
   450
	end;
webertj@21985
   451
webertj@21985
   452
(* ------------------------------------------------------------------------- *)
webertj@21985
   453
(* monomorphic_term: applies a type substitution 'typeSubs' for all type     *)
webertj@21985
   454
(*                   variables in a term 't'                                 *)
webertj@21985
   455
(* ------------------------------------------------------------------------- *)
webertj@21985
   456
webertj@21985
   457
	(* Type.tyenv -> Term.term -> Term.term *)
webertj@21985
   458
webertj@21985
   459
	fun monomorphic_term typeSubs t =
webertj@21985
   460
		map_types (map_type_tvar
webertj@21985
   461
			(fn v =>
webertj@21985
   462
				case Type.lookup (typeSubs, v) of
webertj@21985
   463
				  NONE =>
webertj@21985
   464
					(* schematic type variable not instantiated *)
webertj@21985
   465
					raise REFUTE ("monomorphic_term",
webertj@21985
   466
						"no substitution for type variable " ^ fst (fst v) ^
webertj@21985
   467
						" in term " ^ Display.raw_string_of_term t)
webertj@21985
   468
				| SOME typ =>
webertj@21985
   469
					typ)) t;
webertj@21985
   470
webertj@21985
   471
(* ------------------------------------------------------------------------- *)
webertj@21985
   472
(* specialize_type: given a constant 's' of type 'T', which is a subterm of  *)
webertj@21985
   473
(*                  't', where 't' has a (possibly) more general type, the   *)
webertj@21985
   474
(*                  schematic type variables in 't' are instantiated to      *)
webertj@21985
   475
(*                  match the type 'T' (may raise Type.TYPE_MATCH)           *)
webertj@21985
   476
(* ------------------------------------------------------------------------- *)
webertj@21985
   477
webertj@21985
   478
	(* theory -> (string * Term.typ) -> Term.term -> Term.term *)
webertj@21985
   479
webertj@21985
   480
	fun specialize_type thy (s, T) t =
webertj@21985
   481
	let
webertj@21985
   482
		fun find_typeSubs (Const (s', T')) =
webertj@21985
   483
			if s=s' then
webertj@21985
   484
				SOME (Sign.typ_match thy (T', T) Vartab.empty)
webertj@21985
   485
					handle Type.TYPE_MATCH => NONE
webertj@21985
   486
			else
webertj@21985
   487
				NONE
webertj@21985
   488
		  | find_typeSubs (Free _)           = NONE
webertj@21985
   489
		  | find_typeSubs (Var _)            = NONE
webertj@21985
   490
		  | find_typeSubs (Bound _)          = NONE
webertj@21985
   491
		  | find_typeSubs (Abs (_, _, body)) = find_typeSubs body
webertj@21985
   492
		  | find_typeSubs (t1 $ t2)          =
webertj@21985
   493
			(case find_typeSubs t1 of SOME x => SOME x
webertj@21985
   494
			                        | NONE   => find_typeSubs t2)
webertj@21985
   495
	in
webertj@21985
   496
		case find_typeSubs t of
webertj@21985
   497
		  SOME typeSubs =>
webertj@21985
   498
			monomorphic_term typeSubs t
webertj@21985
   499
		| NONE =>
webertj@21985
   500
			(* no match found - perhaps due to sort constraints *)
webertj@21985
   501
			raise Type.TYPE_MATCH
webertj@21985
   502
	end;
webertj@21985
   503
webertj@21985
   504
(* ------------------------------------------------------------------------- *)
webertj@21985
   505
(* is_const_of_class: returns 'true' iff 'Const (s, T)' is a constant that   *)
webertj@21985
   506
(*                    denotes membership to an axiomatic type class          *)
webertj@21985
   507
(* ------------------------------------------------------------------------- *)
webertj@21985
   508
webertj@21985
   509
	(* theory -> string * Term.typ -> bool *)
webertj@21985
   510
webertj@21985
   511
	fun is_const_of_class thy (s, T) =
webertj@21985
   512
	let
webertj@21985
   513
		val class_const_names = map Logic.const_of_class (Sign.all_classes thy)
webertj@21985
   514
	in
webertj@21985
   515
		(* I'm not quite sure if checking the name 's' is sufficient, *)
webertj@21985
   516
		(* or if we should also check the type 'T'.                   *)
webertj@21985
   517
		s mem_string class_const_names
webertj@21985
   518
	end;
webertj@21985
   519
webertj@21985
   520
(* ------------------------------------------------------------------------- *)
webertj@21985
   521
(* is_IDT_constructor: returns 'true' iff 'Const (s, T)' is the constructor  *)
webertj@21985
   522
(*                     of an inductive datatype in 'thy'                     *)
webertj@21985
   523
(* ------------------------------------------------------------------------- *)
webertj@21985
   524
webertj@21985
   525
	(* theory -> string * Term.typ -> bool *)
webertj@21985
   526
webertj@21985
   527
	fun is_IDT_constructor thy (s, T) =
webertj@21985
   528
		(case body_type T of
webertj@21985
   529
		  Type (s', _) =>
webertj@21985
   530
			(case DatatypePackage.get_datatype_constrs thy s' of
webertj@21985
   531
			  SOME constrs =>
webertj@21985
   532
				List.exists (fn (cname, cty) =>
webertj@21985
   533
					cname = s andalso Sign.typ_instance thy (T, cty)) constrs
webertj@21985
   534
			| NONE =>
webertj@21985
   535
				false)
webertj@21985
   536
		| _  =>
webertj@21985
   537
			false);
webertj@21985
   538
webertj@21985
   539
(* ------------------------------------------------------------------------- *)
webertj@21985
   540
(* is_IDT_recursor: returns 'true' iff 'Const (s, T)' is the recursion       *)
webertj@21985
   541
(*                  operator of an inductive datatype in 'thy'               *)
webertj@21985
   542
(* ------------------------------------------------------------------------- *)
webertj@21985
   543
webertj@21985
   544
	(* theory -> string * Term.typ -> bool *)
webertj@21985
   545
webertj@21985
   546
	fun is_IDT_recursor thy (s, T) =
webertj@21985
   547
	let
webertj@21985
   548
		val rec_names = Symtab.fold (append o #rec_names o snd)
webertj@21985
   549
			(DatatypePackage.get_datatypes thy) []
webertj@21985
   550
	in
webertj@21985
   551
		(* I'm not quite sure if checking the name 's' is sufficient, *)
webertj@21985
   552
		(* or if we should also check the type 'T'.                   *)
webertj@21985
   553
		s mem_string rec_names
webertj@21985
   554
	end;
webertj@21985
   555
webertj@21985
   556
(* ------------------------------------------------------------------------- *)
webertj@21985
   557
(* get_def: looks up the definition of a constant, as created by "constdefs" *)
webertj@21985
   558
(* ------------------------------------------------------------------------- *)
webertj@21985
   559
webertj@21985
   560
	(* theory -> string * Term.typ -> (string * Term.term) option *)
webertj@21985
   561
webertj@21985
   562
	fun get_def thy (s, T) =
webertj@21985
   563
	let
webertj@21985
   564
		(* maps  f ?t1 ... ?tn == rhs  to  %t1...tn. rhs *)
webertj@21985
   565
		fun norm_rhs eqn =
webertj@21985
   566
		let
webertj@21985
   567
			fun lambda (v as Var ((x, _), T)) t = Abs (x, T, abstract_over (v, t))
webertj@21985
   568
			  | lambda v t                      = raise TERM ("lambda", [v, t])
webertj@21985
   569
			val (lhs, rhs) = Logic.dest_equals eqn
webertj@21985
   570
			val (_, args)  = Term.strip_comb lhs
webertj@21985
   571
		in
webertj@21985
   572
			fold lambda (rev args) rhs
webertj@21985
   573
		end
webertj@21985
   574
		(* (string * Term.term) list -> (string * Term.term) option *)
webertj@21985
   575
		fun get_def_ax [] = NONE
webertj@21985
   576
		  | get_def_ax ((axname, ax) :: axioms) =
webertj@21985
   577
			(let
webertj@21985
   578
				val (lhs, _) = Logic.dest_equals ax  (* equations only *)
webertj@21985
   579
				val c        = Term.head_of lhs
webertj@21985
   580
				val (s', T') = Term.dest_Const c
webertj@21985
   581
			in
webertj@21985
   582
				if s=s' then
webertj@21985
   583
					let
webertj@21985
   584
						val typeSubs = Sign.typ_match thy (T', T) Vartab.empty
webertj@21985
   585
						val ax'      = monomorphic_term typeSubs ax
webertj@21985
   586
						val rhs      = norm_rhs ax'
webertj@21985
   587
					in
webertj@21985
   588
						SOME (axname, rhs)
webertj@21985
   589
					end
webertj@21985
   590
				else
webertj@21985
   591
					get_def_ax axioms
webertj@21985
   592
			end handle ERROR _         => get_def_ax axioms
webertj@21985
   593
			         | TERM _          => get_def_ax axioms
webertj@21985
   594
			         | Type.TYPE_MATCH => get_def_ax axioms)
webertj@21985
   595
	in
webertj@21985
   596
		get_def_ax (Theory.all_axioms_of thy)
webertj@21985
   597
	end;
webertj@21985
   598
webertj@21985
   599
(* ------------------------------------------------------------------------- *)
webertj@21985
   600
(* get_typedef: looks up the definition of a type, as created by "typedef"   *)
webertj@21985
   601
(* ------------------------------------------------------------------------- *)
webertj@21985
   602
webertj@21985
   603
	(* theory -> (string * Term.typ) -> (string * Term.term) option *)
webertj@21985
   604
webertj@21985
   605
	fun get_typedef thy T =
webertj@21985
   606
	let
webertj@21985
   607
		(* (string * Term.term) list -> (string * Term.term) option *)
webertj@21985
   608
		fun get_typedef_ax [] = NONE
webertj@21985
   609
		  | get_typedef_ax ((axname, ax) :: axioms) =
webertj@21985
   610
			(let
webertj@21985
   611
				(* Term.term -> Term.typ option *)
webertj@21985
   612
				fun type_of_type_definition (Const (s', T')) =
webertj@21985
   613
					if s'="Typedef.type_definition" then
webertj@21985
   614
						SOME T'
webertj@21985
   615
					else
webertj@21985
   616
						NONE
webertj@21985
   617
				  | type_of_type_definition (Free _)           = NONE
webertj@21985
   618
				  | type_of_type_definition (Var _)            = NONE
webertj@21985
   619
				  | type_of_type_definition (Bound _)          = NONE
webertj@21985
   620
				  | type_of_type_definition (Abs (_, _, body)) =
webertj@21985
   621
					type_of_type_definition body
webertj@21985
   622
				  | type_of_type_definition (t1 $ t2)          =
webertj@21985
   623
					(case type_of_type_definition t1 of
webertj@21985
   624
					  SOME x => SOME x
webertj@21985
   625
					| NONE   => type_of_type_definition t2)
webertj@21985
   626
			in
webertj@21985
   627
				case type_of_type_definition ax of
webertj@21985
   628
				  SOME T' =>
webertj@21985
   629
					let
webertj@21985
   630
						val T''      = (domain_type o domain_type) T'
webertj@21985
   631
						val typeSubs = Sign.typ_match thy (T'', T) Vartab.empty
webertj@21985
   632
					in
webertj@21985
   633
						SOME (axname, monomorphic_term typeSubs ax)
webertj@21985
   634
					end
webertj@21985
   635
				| NONE =>
webertj@21985
   636
					get_typedef_ax axioms
webertj@21985
   637
			end handle ERROR _         => get_typedef_ax axioms
webertj@21985
   638
			         | MATCH           => get_typedef_ax axioms
webertj@21985
   639
			         | Type.TYPE_MATCH => get_typedef_ax axioms)
webertj@21985
   640
	in
webertj@21985
   641
		get_typedef_ax (Theory.all_axioms_of thy)
webertj@21985
   642
	end;
webertj@21985
   643
webertj@21985
   644
(* ------------------------------------------------------------------------- *)
webertj@21985
   645
(* get_classdef: looks up the defining axiom for an axiomatic type class, as *)
webertj@21985
   646
(*               created by the "axclass" command                            *)
webertj@21985
   647
(* ------------------------------------------------------------------------- *)
webertj@21985
   648
webertj@21985
   649
	(* theory -> string -> (string * Term.term) option *)
webertj@21985
   650
webertj@21985
   651
	fun get_classdef thy class =
webertj@21985
   652
	let
webertj@21985
   653
		val axname = class ^ "_class_def"
webertj@21985
   654
	in
webertj@21985
   655
		Option.map (pair axname)
webertj@21985
   656
			(AList.lookup (op =) (Theory.all_axioms_of thy) axname)
webertj@21985
   657
	end;
webertj@21985
   658
webertj@21985
   659
(* ------------------------------------------------------------------------- *)
webertj@21985
   660
(* unfold_defs: unfolds all defined constants in a term 't', beta-eta        *)
webertj@21985
   661
(*              normalizes the result term; certain constants are not        *)
webertj@21985
   662
(*              unfolded (cf. 'collect_axioms' and the various interpreters  *)
webertj@21985
   663
(*              below): if the interpretation respects a definition anyway,  *)
webertj@21985
   664
(*              that definition does not need to be unfolded                 *)
webertj@21985
   665
(* ------------------------------------------------------------------------- *)
webertj@21985
   666
webertj@21985
   667
	(* theory -> Term.term -> Term.term *)
webertj@21985
   668
webertj@21985
   669
	(* Note: we could intertwine unfolding of constants and beta-(eta-)       *)
webertj@21985
   670
	(*       normalization; this would save some unfolding for terms where    *)
webertj@21985
   671
	(*       constants are eliminated by beta-reduction (e.g. 'K c1 c2').  On *)
webertj@21985
   672
	(*       the other hand, this would cause additional work for terms where *)
webertj@21985
   673
	(*       constants are duplicated by beta-reduction (e.g. 'S c1 c2 c3').  *)
webertj@21985
   674
webertj@21985
   675
	fun unfold_defs thy t =
webertj@21985
   676
	let
webertj@21985
   677
		(* Term.term -> Term.term *)
webertj@21985
   678
		fun unfold_loop t =
webertj@21985
   679
			case t of
webertj@21985
   680
			(* Pure *)
webertj@21985
   681
			  Const ("all", _)                => t
webertj@21985
   682
			| Const ("==", _)                 => t
webertj@21985
   683
			| Const ("==>", _)                => t
webertj@21985
   684
			| Const ("TYPE", _)               => t  (* axiomatic type classes *)
webertj@21985
   685
			(* HOL *)
webertj@21985
   686
			| Const ("Trueprop", _)           => t
webertj@21985
   687
			| Const ("Not", _)                => t
webertj@21985
   688
			| (* redundant, since 'True' is also an IDT constructor *)
webertj@21985
   689
			  Const ("True", _)               => t
webertj@21985
   690
			| (* redundant, since 'False' is also an IDT constructor *)
webertj@21985
   691
			  Const ("False", _)              => t
webertj@21985
   692
			| Const ("arbitrary", _)          => t
webertj@21985
   693
			| Const ("The", _)                => t
webertj@21985
   694
			| Const ("Hilbert_Choice.Eps", _) => t
webertj@21985
   695
			| Const ("All", _)                => t
webertj@21985
   696
			| Const ("Ex", _)                 => t
webertj@21985
   697
			| Const ("op =", _)               => t
webertj@21985
   698
			| Const ("op &", _)               => t
webertj@21985
   699
			| Const ("op |", _)               => t
webertj@21985
   700
			| Const ("op -->", _)             => t
webertj@21985
   701
			(* sets *)
webertj@21985
   702
			| Const ("Collect", _)            => t
webertj@21985
   703
			| Const ("op :", _)               => t
webertj@21985
   704
			(* other optimizations *)
webertj@21985
   705
			| Const ("Finite_Set.card", _)    => t
webertj@21985
   706
			| Const ("Finite_Set.Finites", _) => t
webertj@22092
   707
			| Const ("Orderings.less", Type ("fun", [Type ("nat", []),
webertj@22092
   708
				Type ("fun", [Type ("nat", []), Type ("bool", [])])])) => t
webertj@22092
   709
			| Const ("HOL.plus", Type ("fun", [Type ("nat", []),
webertj@22092
   710
				Type ("fun", [Type ("nat", []), Type ("nat", [])])])) => t
webertj@22092
   711
			| Const ("HOL.minus", Type ("fun", [Type ("nat", []),
webertj@22092
   712
				Type ("fun", [Type ("nat", []), Type ("nat", [])])])) => t
webertj@22092
   713
			| Const ("HOL.times", Type ("fun", [Type ("nat", []),
webertj@22092
   714
				Type ("fun", [Type ("nat", []), Type ("nat", [])])])) => t
webertj@21985
   715
			| Const ("List.op @", _)          => t
webertj@21985
   716
			| Const ("Lfp.lfp", _)            => t
webertj@21985
   717
			| Const ("Gfp.gfp", _)            => t
webertj@21985
   718
			| Const ("fst", _)                => t
webertj@21985
   719
			| Const ("snd", _)                => t
webertj@21985
   720
			(* simply-typed lambda calculus *)
webertj@21985
   721
			| Const (s, T) =>
webertj@22092
   722
				(if is_IDT_constructor thy (s, T)
webertj@22092
   723
					orelse is_IDT_recursor thy (s, T) then
webertj@21985
   724
					t  (* do not unfold IDT constructors/recursors *)
webertj@21985
   725
				(* unfold the constant if there is a defining equation *)
webertj@21985
   726
				else case get_def thy (s, T) of
webertj@21985
   727
				  SOME (axname, rhs) =>
webertj@21985
   728
					(* Note: if the term to be unfolded (i.e. 'Const (s, T)')  *)
webertj@21985
   729
					(* occurs on the right-hand side of the equation, i.e. in  *)
webertj@21985
   730
					(* 'rhs', we must not use this equation to unfold, because *)
webertj@21985
   731
					(* that would loop.  Here would be the right place to      *)
webertj@21985
   732
					(* check this.  However, getting this really right seems   *)
webertj@21985
   733
					(* difficult because the user may state arbitrary axioms,  *)
webertj@21985
   734
					(* which could interact with overloading to create loops.  *)
webertj@21985
   735
					((*immediate_output (" unfolding: " ^ axname);*)unfold_loop rhs)
webertj@21985
   736
				| NONE => t)
webertj@21985
   737
			| Free _           => t
webertj@21985
   738
			| Var _            => t
webertj@21985
   739
			| Bound _          => t
webertj@21985
   740
			| Abs (s, T, body) => Abs (s, T, unfold_loop body)
webertj@21985
   741
			| t1 $ t2          => (unfold_loop t1) $ (unfold_loop t2)
webertj@21985
   742
		val result = Envir.beta_eta_contract (unfold_loop t)
webertj@21985
   743
	in
webertj@21985
   744
		result
webertj@21985
   745
	end;
webertj@21985
   746
webertj@21985
   747
(* ------------------------------------------------------------------------- *)
webertj@21985
   748
(* collect_axioms: collects (monomorphic, universally quantified, unfolded   *)
webertj@21985
   749
(*                 versions of) all HOL axioms that are relevant w.r.t 't'   *)
webertj@14807
   750
(* ------------------------------------------------------------------------- *)
webertj@14807
   751
webertj@15547
   752
	(* Note: to make the collection of axioms more easily extensible, this    *)
webertj@14807
   753
	(*       function could be based on user-supplied "axiom collectors",     *)
webertj@14807
   754
	(*       similar to 'interpret'/interpreters or 'print'/printers          *)
webertj@14807
   755
webertj@21985
   756
	(* Note: currently we use "inverse" functions to the definitional         *)
webertj@21985
   757
	(*       mechanisms provided by Isabelle/HOL, e.g. for "axclass",         *)
webertj@21985
   758
	(*       "typedef", "constdefs".  A more general approach could consider  *)
webertj@21985
   759
	(*       *every* axiom of the theory and collect it if it has a constant/ *)
webertj@21985
   760
	(*       type/typeclass in common with the term 't'.                      *)
webertj@21985
   761
webertj@14807
   762
	(* theory -> Term.term -> Term.term list *)
webertj@14807
   763
webertj@14807
   764
	(* Which axioms are "relevant" for a particular term/type goes hand in    *)
webertj@14807
   765
	(* hand with the interpretation of that term/type by its interpreter (see *)
webertj@14807
   766
	(* way below): if the interpretation respects an axiom anyway, the axiom  *)
webertj@14807
   767
	(* does not need to be added as a constraint here.                        *)
webertj@14807
   768
webertj@21985
   769
	(* To avoid collecting the same axiom multiple times, we use an           *)
webertj@21985
   770
	(* accumulator 'axs' which contains all axioms collected so far.          *)
webertj@14807
   771
webertj@14807
   772
	fun collect_axioms thy t =
webertj@14807
   773
	let
wenzelm@14984
   774
		val _ = immediate_output "Adding axioms..."
webertj@14807
   775
		(* (string * Term.term) list *)
webertj@21985
   776
		val axioms = Theory.all_axioms_of thy
webertj@21985
   777
		(* string * Term.term -> Term.term list -> Term.term list *)
webertj@21985
   778
		fun collect_this_axiom (axname, ax) axs =
webertj@14807
   779
		let
webertj@21985
   780
			val ax' = unfold_defs thy ax
webertj@14807
   781
		in
webertj@21985
   782
			if member (op aconv) axs ax' then
webertj@21985
   783
				axs
webertj@21985
   784
			else (
webertj@21985
   785
				immediate_output (" " ^ axname);
webertj@21985
   786
				collect_term_axioms (ax' :: axs, ax')
webertj@21985
   787
			)
webertj@14807
   788
		end
webertj@14807
   789
		(* Term.term list * Term.typ -> Term.term list *)
webertj@21985
   790
		and collect_sort_axioms (axs, T) =
webertj@21985
   791
		let
webertj@21985
   792
			(* string list *)
webertj@21985
   793
			val sort = (case T of
webertj@21985
   794
				  TFree (_, sort) => sort
webertj@21985
   795
				| TVar (_, sort)  => sort
webertj@21985
   796
				| _               => raise REFUTE ("collect_axioms", "type " ^
webertj@21985
   797
					Sign.string_of_typ thy T ^ " is not a variable"))
webertj@21985
   798
			(* obtain axioms for all superclasses *)
webertj@21985
   799
			val superclasses = sort @ (maps (Sign.super_classes thy) sort)
webertj@21985
   800
			(* merely an optimization, because 'collect_this_axiom' disallows *)
webertj@21985
   801
			(* duplicate axioms anyway:                                       *)
webertj@21985
   802
			val superclasses = distinct (op =) superclasses
webertj@21985
   803
			val class_axioms = maps (fn class => map (fn ax =>
webertj@21985
   804
				("<" ^ class ^ ">", Thm.prop_of ax))
webertj@21985
   805
				(#axioms (AxClass.get_definition thy class) handle ERROR _ => []))
webertj@21985
   806
				superclasses
webertj@21985
   807
			(* replace the (at most one) schematic type variable in each axiom *)
webertj@21985
   808
			(* by the actual type 'T'                                          *)
webertj@21985
   809
			val monomorphic_class_axioms = map (fn (axname, ax) =>
webertj@21985
   810
				(case Term.term_tvars ax of
webertj@21985
   811
				  [] =>
webertj@21985
   812
					(axname, ax)
webertj@21985
   813
				| [(idx, S)] =>
webertj@21985
   814
					(axname, monomorphic_term (Vartab.make [(idx, (S, T))]) ax)
webertj@21985
   815
				| _ =>
webertj@21985
   816
					raise REFUTE ("collect_axioms", "class axiom " ^ axname ^ " (" ^
webertj@21985
   817
						Sign.string_of_term thy ax ^
webertj@21985
   818
						") contains more than one type variable")))
webertj@21985
   819
				class_axioms
webertj@21985
   820
		in
webertj@21985
   821
			fold collect_this_axiom monomorphic_class_axioms axs
webertj@21985
   822
		end
webertj@15547
   823
		(* Term.term list * Term.typ -> Term.term list *)
webertj@15547
   824
		and collect_type_axioms (axs, T) =
webertj@14807
   825
			case T of
webertj@14807
   826
			(* simple types *)
webertj@14807
   827
			  Type ("prop", [])      => axs
webertj@22092
   828
			| Type ("fun", [T1, T2]) => collect_type_axioms
webertj@22092
   829
				(collect_type_axioms (axs, T1), T2)
webertj@14807
   830
			| Type ("set", [T1])     => collect_type_axioms (axs, T1)
webertj@22092
   831
			(* axiomatic type classes *)
webertj@22092
   832
			| Type ("itself", [T1])  => collect_type_axioms (axs, T1)
webertj@14807
   833
			| Type (s, Ts)           =>
webertj@21985
   834
				(case DatatypePackage.get_datatype thy s of
webertj@21985
   835
				  SOME info =>  (* inductive datatype *)
webertj@21985
   836
						(* only collect relevant type axioms for the argument types *)
webertj@21985
   837
						Library.foldl collect_type_axioms (axs, Ts)
webertj@21985
   838
				| NONE =>
webertj@21985
   839
					(case get_typedef thy T of
webertj@21985
   840
					  SOME (axname, ax) =>
webertj@21985
   841
						collect_this_axiom (axname, ax) axs
skalberg@15531
   842
					| NONE =>
webertj@21985
   843
						(* unspecified type, perhaps introduced with "typedecl" *)
webertj@21985
   844
						(* at least collect relevant type axioms for the argument types *)
webertj@21985
   845
						Library.foldl collect_type_axioms (axs, Ts)))
webertj@22092
   846
			(* axiomatic type classes *)
webertj@22092
   847
			| TFree _                => collect_sort_axioms (axs, T)
webertj@22092
   848
			(* axiomatic type classes *)
webertj@22092
   849
			| TVar _                 => collect_sort_axioms (axs, T)
webertj@14807
   850
		(* Term.term list * Term.term -> Term.term list *)
webertj@14807
   851
		and collect_term_axioms (axs, t) =
webertj@14807
   852
			case t of
webertj@14807
   853
			(* Pure *)
webertj@14807
   854
			  Const ("all", _)                => axs
webertj@14807
   855
			| Const ("==", _)                 => axs
webertj@14807
   856
			| Const ("==>", _)                => axs
webertj@22092
   857
			(* axiomatic type classes *)
webertj@22092
   858
			| Const ("TYPE", T)               => collect_type_axioms (axs, T)
webertj@14807
   859
			(* HOL *)
webertj@14807
   860
			| Const ("Trueprop", _)           => axs
webertj@14807
   861
			| Const ("Not", _)                => axs
webertj@22092
   862
			(* redundant, since 'True' is also an IDT constructor *)
webertj@22092
   863
			| Const ("True", _)               => axs
webertj@22092
   864
			(* redundant, since 'False' is also an IDT constructor *)
webertj@22092
   865
			| Const ("False", _)              => axs
webertj@14807
   866
			| Const ("arbitrary", T)          => collect_type_axioms (axs, T)
webertj@14807
   867
			| Const ("The", T)                =>
webertj@14807
   868
				let
webertj@22092
   869
					val ax = specialize_type thy ("The", T)
webertj@22092
   870
						(lookup axioms "HOL.the_eq_trivial")
webertj@14807
   871
				in
webertj@21985
   872
					collect_this_axiom ("HOL.the_eq_trivial", ax) axs
webertj@14807
   873
				end
webertj@14807
   874
			| Const ("Hilbert_Choice.Eps", T) =>
webertj@14807
   875
				let
webertj@22092
   876
					val ax = specialize_type thy ("Hilbert_Choice.Eps", T)
webertj@22092
   877
						(lookup axioms "Hilbert_Choice.someI")
webertj@14807
   878
				in
webertj@21985
   879
					collect_this_axiom ("Hilbert_Choice.someI", ax) axs
webertj@14807
   880
				end
webertj@21985
   881
			| Const ("All", T)                => collect_type_axioms (axs, T)
webertj@21985
   882
			| Const ("Ex", T)                 => collect_type_axioms (axs, T)
webertj@14807
   883
			| Const ("op =", T)               => collect_type_axioms (axs, T)
webertj@14807
   884
			| Const ("op &", _)               => axs
webertj@14807
   885
			| Const ("op |", _)               => axs
webertj@14807
   886
			| Const ("op -->", _)             => axs
webertj@14807
   887
			(* sets *)
webertj@14807
   888
			| Const ("Collect", T)            => collect_type_axioms (axs, T)
webertj@14807
   889
			| Const ("op :", T)               => collect_type_axioms (axs, T)
webertj@14807
   890
			(* other optimizations *)
webertj@14807
   891
			| Const ("Finite_Set.card", T)    => collect_type_axioms (axs, T)
webertj@15571
   892
			| Const ("Finite_Set.Finites", T) => collect_type_axioms (axs, T)
webertj@22092
   893
			| Const ("Orderings.less", T as Type ("fun", [Type ("nat", []),
webertj@22092
   894
				Type ("fun", [Type ("nat", []), Type ("bool", [])])])) =>
webertj@22092
   895
					collect_type_axioms (axs, T)
webertj@22092
   896
			| Const ("HOL.plus", T as Type ("fun", [Type ("nat", []),
webertj@22092
   897
				Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
webertj@22092
   898
					collect_type_axioms (axs, T)
webertj@22092
   899
			| Const ("HOL.minus", T as Type ("fun", [Type ("nat", []),
webertj@22092
   900
				Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
webertj@22092
   901
					collect_type_axioms (axs, T)
webertj@22092
   902
			| Const ("HOL.times", T as Type ("fun", [Type ("nat", []),
webertj@22092
   903
				Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
webertj@22092
   904
					collect_type_axioms (axs, T)
webertj@15767
   905
			| Const ("List.op @", T)          => collect_type_axioms (axs, T)
webertj@16050
   906
			| Const ("Lfp.lfp", T)            => collect_type_axioms (axs, T)
webertj@16050
   907
			| Const ("Gfp.gfp", T)            => collect_type_axioms (axs, T)
webertj@21267
   908
			| Const ("fst", T)                => collect_type_axioms (axs, T)
webertj@21267
   909
			| Const ("snd", T)                => collect_type_axioms (axs, T)
webertj@14807
   910
			(* simply-typed lambda calculus *)
webertj@14807
   911
			| Const (s, T)                    =>
webertj@21985
   912
					if is_const_of_class thy (s, T) then
webertj@21985
   913
						(* axiomatic type classes: add "OFCLASS(?'a::c, c_class)" *)
webertj@21985
   914
						(* and the class definition                               *)
webertj@15547
   915
						let
wenzelm@18932
   916
							val class   = Logic.class_of_const s
webertj@15547
   917
							val inclass = Logic.mk_inclass (TVar (("'a", 0), [class]), class)
webertj@21985
   918
							val ax_in   = SOME (specialize_type thy (s, T) inclass)
webertj@21985
   919
								(* type match may fail due to sort constraints *)
webertj@21985
   920
								handle Type.TYPE_MATCH => NONE
webertj@22092
   921
							val ax_1 = Option.map (fn ax => (Sign.string_of_term thy ax, ax))
webertj@22092
   922
								ax_in
webertj@22092
   923
							val ax_2 = Option.map (apsnd (specialize_type thy (s, T)))
webertj@22092
   924
								(get_classdef thy class)
webertj@15547
   925
						in
webertj@21985
   926
							collect_type_axioms (fold collect_this_axiom
webertj@21985
   927
								(map_filter I [ax_1, ax_2]) axs, T)
webertj@15547
   928
						end
webertj@21985
   929
					else if is_IDT_constructor thy (s, T)
webertj@21985
   930
						orelse is_IDT_recursor thy (s, T) then
webertj@15125
   931
						(* only collect relevant type axioms *)
webertj@15125
   932
						collect_type_axioms (axs, T)
webertj@21985
   933
					else
webertj@21985
   934
						(* other constants should have been unfolded, with some *)
webertj@21985
   935
						(* exceptions: e.g. Abs_xxx/Rep_xxx functions for       *)
webertj@21985
   936
						(* typedefs, or type-class related constants            *)
webertj@21985
   937
						(* only collect relevant type axioms *)
webertj@21985
   938
						collect_type_axioms (axs, T)
webertj@21985
   939
			| Free (_, T)      => collect_type_axioms (axs, T)
webertj@21985
   940
			| Var (_, T)       => collect_type_axioms (axs, T)
webertj@21985
   941
			| Bound i          => axs
webertj@22092
   942
			| Abs (_, T, body) => collect_term_axioms
webertj@22092
   943
				(collect_type_axioms (axs, T), body)
webertj@22092
   944
			| t1 $ t2          => collect_term_axioms
webertj@22092
   945
				(collect_term_axioms (axs, t1), t2)
webertj@14807
   946
		(* Term.term list *)
webertj@14807
   947
		val result = map close_form (collect_term_axioms ([], t))
webertj@14807
   948
		val _ = writeln " ...done."
webertj@14807
   949
	in
webertj@14807
   950
		result
webertj@14456
   951
	end;
webertj@14456
   952
webertj@14456
   953
(* ------------------------------------------------------------------------- *)
webertj@14807
   954
(* ground_types: collects all ground types in a term (including argument     *)
webertj@14807
   955
(*               types of other types), suppressing duplicates.  Does not    *)
webertj@14807
   956
(*               return function types, set types, non-recursive IDTs, or    *)
webertj@14807
   957
(*               'propT'.  For IDTs, also the argument types of constructors *)
webertj@14807
   958
(*               are considered.                                             *)
webertj@14807
   959
(* ------------------------------------------------------------------------- *)
webertj@14807
   960
webertj@14807
   961
	(* theory -> Term.term -> Term.typ list *)
webertj@14807
   962
webertj@14807
   963
	fun ground_types thy t =
webertj@14807
   964
	let
webertj@14807
   965
		(* Term.typ * Term.typ list -> Term.typ list *)
webertj@14807
   966
		fun collect_types (T, acc) =
webertj@14807
   967
			if T mem acc then
webertj@14807
   968
				acc  (* prevent infinite recursion (for IDTs) *)
webertj@14807
   969
			else
webertj@14807
   970
				(case T of
webertj@14807
   971
				  Type ("fun", [T1, T2]) => collect_types (T1, collect_types (T2, acc))
webertj@14807
   972
				| Type ("prop", [])      => acc
webertj@14807
   973
				| Type ("set", [T1])     => collect_types (T1, acc)
webertj@14807
   974
				| Type (s, Ts)           =>
haftmann@19346
   975
					(case DatatypePackage.get_datatype thy s of
skalberg@15531
   976
					  SOME info =>  (* inductive datatype *)
webertj@14807
   977
						let
webertj@14807
   978
							val index               = #index info
webertj@14807
   979
							val descr               = #descr info
webertj@22092
   980
							val (_, dtyps, constrs) = lookup descr index
webertj@14807
   981
							val typ_assoc           = dtyps ~~ Ts
webertj@14807
   982
							(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
webertj@14807
   983
							val _ = (if Library.exists (fn d =>
webertj@14807
   984
									case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
webertj@14807
   985
								then
webertj@22092
   986
									raise REFUTE ("ground_types", "datatype argument (for type "
webertj@22092
   987
										^ Sign.string_of_typ thy (Type (s, Ts))
webertj@22092
   988
										^ ") is not a variable")
webertj@14807
   989
								else
webertj@14807
   990
									())
webertj@22092
   991
							(* if the current type is a recursive IDT (i.e. a depth is *)
webertj@22092
   992
							(* required), add it to 'acc'                              *)
webertj@22092
   993
							val acc' = (if Library.exists (fn (_, ds) => Library.exists
webertj@22092
   994
								DatatypeAux.is_rec_type ds) constrs then
haftmann@20854
   995
									insert (op =) T acc
webertj@14807
   996
								else
webertj@14807
   997
									acc)
webertj@14807
   998
							(* collect argument types *)
skalberg@15574
   999
							val acc_args = foldr collect_types acc' Ts
webertj@14807
  1000
							(* collect constructor types *)
webertj@22092
  1001
							val acc_constrs = foldr collect_types acc_args (List.concat
webertj@22092
  1002
								(map (fn (_, ds) => map (typ_of_dtyp descr typ_assoc) ds)
webertj@22092
  1003
									constrs))
webertj@14807
  1004
						in
webertj@14807
  1005
							acc_constrs
webertj@14807
  1006
						end
webertj@22092
  1007
					| NONE =>
webertj@22092
  1008
						(* not an inductive datatype, e.g. defined via "typedef" or *)
webertj@22092
  1009
						(* "typedecl"                                               *)
haftmann@20854
  1010
						insert (op =) T (foldr collect_types acc Ts))
haftmann@20854
  1011
				| TFree _                => insert (op =) T acc
haftmann@20854
  1012
				| TVar _                 => insert (op =) T acc)
webertj@14807
  1013
	in
webertj@14807
  1014
		it_term_types collect_types (t, [])
webertj@14807
  1015
	end;
webertj@14807
  1016
webertj@14807
  1017
(* ------------------------------------------------------------------------- *)
webertj@14807
  1018
(* string_of_typ: (rather naive) conversion from types to strings, used to   *)
webertj@14807
  1019
(*                look up the size of a type in 'sizes'.  Parameterized      *)
webertj@14807
  1020
(*                types with different parameters (e.g. "'a list" vs. "bool  *)
webertj@14807
  1021
(*                list") are identified.                                     *)
webertj@14807
  1022
(* ------------------------------------------------------------------------- *)
webertj@14807
  1023
webertj@14807
  1024
	(* Term.typ -> string *)
webertj@14807
  1025
webertj@14807
  1026
	fun string_of_typ (Type (s, _))     = s
webertj@14807
  1027
	  | string_of_typ (TFree (s, _))    = s
webertj@14807
  1028
	  | string_of_typ (TVar ((s,_), _)) = s;
webertj@14807
  1029
webertj@14807
  1030
(* ------------------------------------------------------------------------- *)
webertj@14807
  1031
(* first_universe: returns the "first" (i.e. smallest) universe by assigning *)
webertj@14807
  1032
(*                 'minsize' to every type for which no size is specified in *)
webertj@14807
  1033
(*                 'sizes'                                                   *)
webertj@14807
  1034
(* ------------------------------------------------------------------------- *)
webertj@14807
  1035
webertj@14807
  1036
	(* Term.typ list -> (string * int) list -> int -> (Term.typ * int) list *)
webertj@14807
  1037
webertj@14807
  1038
	fun first_universe xs sizes minsize =
webertj@14807
  1039
	let
webertj@14807
  1040
		fun size_of_typ T =
haftmann@17314
  1041
			case AList.lookup (op =) sizes (string_of_typ T) of
skalberg@15531
  1042
			  SOME n => n
skalberg@15531
  1043
			| NONE   => minsize
webertj@14807
  1044
	in
webertj@14807
  1045
		map (fn T => (T, size_of_typ T)) xs
webertj@14807
  1046
	end;
webertj@14807
  1047
webertj@14807
  1048
(* ------------------------------------------------------------------------- *)
webertj@14807
  1049
(* next_universe: enumerates all universes (i.e. assignments of sizes to     *)
webertj@14807
  1050
(*                types), where the minimal size of a type is given by       *)
webertj@14807
  1051
(*                'minsize', the maximal size is given by 'maxsize', and a   *)
webertj@14807
  1052
(*                type may have a fixed size given in 'sizes'                *)
webertj@14456
  1053
(* ------------------------------------------------------------------------- *)
webertj@14456
  1054
webertj@22092
  1055
	(* (Term.typ * int) list -> (string * int) list -> int -> int ->
webertj@22092
  1056
		(Term.typ * int) list option *)
webertj@14456
  1057
webertj@14807
  1058
	fun next_universe xs sizes minsize maxsize =
webertj@14456
  1059
	let
webertj@14807
  1060
		(* creates the "first" list of length 'len', where the sum of all list *)
webertj@14807
  1061
		(* elements is 'sum', and the length of the list is 'len'              *)
webertj@14807
  1062
		(* int -> int -> int -> int list option *)
webertj@15547
  1063
		fun make_first _ 0 sum =
webertj@14807
  1064
			if sum=0 then
skalberg@15531
  1065
				SOME []
webertj@14807
  1066
			else
skalberg@15531
  1067
				NONE
webertj@15547
  1068
		  | make_first max len sum =
webertj@14807
  1069
			if sum<=max orelse max<0 then
skalberg@15570
  1070
				Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
webertj@14807
  1071
			else
skalberg@15570
  1072
				Option.map (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
webertj@14807
  1073
		(* enumerates all int lists with a fixed length, where 0<=x<='max' for *)
webertj@14807
  1074
		(* all list elements x (unless 'max'<0)                                *)
webertj@15547
  1075
		(* int -> int -> int -> int list -> int list option *)
webertj@15547
  1076
		fun next max len sum [] =
webertj@15547
  1077
			NONE
webertj@15547
  1078
		  | next max len sum [x] =
webertj@15547
  1079
			(* we've reached the last list element, so there's no shift possible *)
webertj@15547
  1080
			make_first max (len+1) (sum+x+1)  (* increment 'sum' by 1 *)
webertj@15547
  1081
		  | next max len sum (x1::x2::xs) =
webertj@15547
  1082
			if x1>0 andalso (x2<max orelse max<0) then
webertj@15547
  1083
				(* we can shift *)
skalberg@15570
  1084
				SOME (valOf (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
webertj@15547
  1085
			else
webertj@15547
  1086
				(* continue search *)
webertj@15547
  1087
				next max (len+1) (sum+x1) (x2::xs)
webertj@14807
  1088
		(* only consider those types for which the size is not fixed *)
webertj@22092
  1089
		val mutables = List.filter
webertj@22092
  1090
			(not o (AList.defined (op =) sizes) o string_of_typ o fst) xs
webertj@14807
  1091
		(* subtract 'minsize' from every size (will be added again at the end) *)
webertj@14807
  1092
		val diffs = map (fn (_, n) => n-minsize) mutables
webertj@14807
  1093
	in
webertj@15547
  1094
		case next (maxsize-minsize) 0 0 diffs of
skalberg@15531
  1095
		  SOME diffs' =>
webertj@14807
  1096
			(* merge with those types for which the size is fixed *)
skalberg@15531
  1097
			SOME (snd (foldl_map (fn (ds, (T, _)) =>
haftmann@17314
  1098
				case AList.lookup (op =) sizes (string_of_typ T) of
webertj@22092
  1099
				(* return the fixed size *)
webertj@22092
  1100
				  SOME n => (ds, (T, n))
webertj@22092
  1101
				(* consume the head of 'ds', add 'minsize' *)
webertj@22092
  1102
				| NONE   => (tl ds, (T, minsize + hd ds)))
webertj@14807
  1103
				(diffs', xs)))
skalberg@15531
  1104
		| NONE =>
skalberg@15531
  1105
			NONE
webertj@14807
  1106
	end;
webertj@14807
  1107
webertj@14807
  1108
(* ------------------------------------------------------------------------- *)
webertj@14807
  1109
(* toTrue: converts the interpretation of a Boolean value to a propositional *)
webertj@14807
  1110
(*         formula that is true iff the interpretation denotes "true"        *)
webertj@14807
  1111
(* ------------------------------------------------------------------------- *)
webertj@14807
  1112
webertj@14807
  1113
	(* interpretation -> prop_formula *)
webertj@14807
  1114
webertj@22092
  1115
	fun toTrue (Leaf [fm, _]) =
webertj@22092
  1116
		fm
webertj@22092
  1117
	  | toTrue _              =
webertj@22092
  1118
		raise REFUTE ("toTrue", "interpretation does not denote a Boolean value");
webertj@14807
  1119
webertj@14807
  1120
(* ------------------------------------------------------------------------- *)
webertj@14807
  1121
(* toFalse: converts the interpretation of a Boolean value to a              *)
webertj@14807
  1122
(*          propositional formula that is true iff the interpretation        *)
webertj@14807
  1123
(*          denotes "false"                                                  *)
webertj@14807
  1124
(* ------------------------------------------------------------------------- *)
webertj@14807
  1125
webertj@14807
  1126
	(* interpretation -> prop_formula *)
webertj@14807
  1127
webertj@22092
  1128
	fun toFalse (Leaf [_, fm]) =
webertj@22092
  1129
		fm
webertj@22092
  1130
	  | toFalse _              =
webertj@22092
  1131
		raise REFUTE ("toFalse", "interpretation does not denote a Boolean value");
webertj@14807
  1132
webertj@14807
  1133
(* ------------------------------------------------------------------------- *)
webertj@14807
  1134
(* find_model: repeatedly calls 'interpret' with appropriate parameters,     *)
webertj@14807
  1135
(*             applies a SAT solver, and (in case a model is found) displays *)
webertj@14807
  1136
(*             the model to the user by calling 'print_model'                *)
webertj@14807
  1137
(* thy       : the current theory                                            *)
webertj@14807
  1138
(* {...}     : parameters that control the translation/model generation      *)
webertj@14807
  1139
(* t         : term to be translated into a propositional formula            *)
webertj@14807
  1140
(* negate    : if true, find a model that makes 't' false (rather than true) *)
webertj@14807
  1141
(* ------------------------------------------------------------------------- *)
webertj@14807
  1142
webertj@14807
  1143
	(* theory -> params -> Term.term -> bool -> unit *)
webertj@14807
  1144
webertj@22092
  1145
	fun find_model thy {sizes, minsize, maxsize, maxvars, maxtime, satsolver} t
webertj@22092
  1146
		negate =
webertj@14807
  1147
	let
webertj@14807
  1148
		(* unit -> unit *)
webertj@14807
  1149
		fun wrapper () =
webertj@14807
  1150
		let
webertj@21985
  1151
			val u      = unfold_defs thy t
webertj@21992
  1152
			val _      = writeln ("Unfolded term: " ^ Sign.string_of_term thy u)
webertj@21985
  1153
			val axioms = collect_axioms thy u
webertj@14807
  1154
			(* Term.typ list *)
webertj@22092
  1155
			val types = Library.foldl (fn (acc, t') =>
webertj@22092
  1156
				acc union (ground_types thy t')) ([], u :: axioms)
webertj@21985
  1157
			val _     = writeln ("Ground types: "
webertj@14807
  1158
				^ (if null types then "none."
webertj@21992
  1159
				   else commas (map (Sign.string_of_typ thy) types)))
webertj@15547
  1160
			(* we can only consider fragments of recursive IDTs, so we issue a  *)
webertj@15547
  1161
			(* warning if the formula contains a recursive IDT                  *)
webertj@15547
  1162
			(* TODO: no warning needed for /positive/ occurrences of IDTs       *)
webertj@15547
  1163
			val _ = if Library.exists (fn
webertj@15547
  1164
				  Type (s, _) =>
haftmann@19346
  1165
					(case DatatypePackage.get_datatype thy s of
webertj@15547
  1166
					  SOME info =>  (* inductive datatype *)
webertj@15547
  1167
						let
webertj@15547
  1168
							val index           = #index info
webertj@15547
  1169
							val descr           = #descr info
webertj@22092
  1170
							val (_, _, constrs) = lookup descr index
webertj@15547
  1171
						in
webertj@15547
  1172
							(* recursive datatype? *)
webertj@22092
  1173
							Library.exists (fn (_, ds) =>
webertj@22092
  1174
								Library.exists DatatypeAux.is_rec_type ds) constrs
webertj@15547
  1175
						end
webertj@15547
  1176
					| NONE => false)
webertj@15547
  1177
				| _ => false) types then
webertj@22092
  1178
					warning ("Term contains a recursive datatype; "
webertj@22092
  1179
						^ "countermodel(s) may be spurious!")
webertj@15547
  1180
				else
webertj@15547
  1181
					()
webertj@14807
  1182
			(* (Term.typ * int) list -> unit *)
webertj@14807
  1183
			fun find_model_loop universe =
webertj@15334
  1184
			let
webertj@22092
  1185
				val init_model = (universe, [])
webertj@22092
  1186
				val init_args  = {maxvars = maxvars, def_eq = false, next_idx = 1,
webertj@22092
  1187
					bounds = [], wellformed = True}
webertj@22092
  1188
				val _          = immediate_output ("Translating term (sizes: "
webertj@22092
  1189
					^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
webertj@21985
  1190
				(* translate 'u' and all axioms *)
webertj@14807
  1191
				val ((model, args), intrs) = foldl_map (fn ((m, a), t') =>
webertj@14807
  1192
					let
webertj@14807
  1193
						val (i, m', a') = interpret thy m a t'
webertj@14807
  1194
					in
webertj@15547
  1195
						(* set 'def_eq' to 'true' *)
webertj@22092
  1196
						((m', {maxvars = #maxvars a', def_eq = true,
webertj@22092
  1197
							next_idx = #next_idx a', bounds = #bounds a',
webertj@22092
  1198
							wellformed = #wellformed a'}), i)
webertj@21985
  1199
					end) ((init_model, init_args), u :: axioms)
webertj@21985
  1200
				(* make 'u' either true or false, and make all axioms true, and *)
webertj@14807
  1201
				(* add the well-formedness side condition                       *)
webertj@21985
  1202
				val fm_u  = (if negate then toFalse else toTrue) (hd intrs)
webertj@14807
  1203
				val fm_ax = PropLogic.all (map toTrue (tl intrs))
webertj@21985
  1204
				val fm    = PropLogic.all [#wellformed args, fm_ax, fm_u]
webertj@14456
  1205
			in
wenzelm@14984
  1206
				immediate_output " invoking SAT solver...";
webertj@14965
  1207
				(case SatSolver.invoke_solver satsolver fm of
webertj@14965
  1208
				  SatSolver.SATISFIABLE assignment =>
webertj@15547
  1209
					(writeln " model found!";
webertj@22092
  1210
					writeln ("*** Model found: ***\n" ^ print_model thy model
webertj@22092
  1211
						(fn i => case assignment i of SOME b => b | NONE => true)))
webertj@17493
  1212
				| SatSolver.UNSATISFIABLE _ =>
webertj@15547
  1213
					(immediate_output " no model exists.\n";
webertj@15547
  1214
					case next_universe universe sizes minsize maxsize of
webertj@15547
  1215
					  SOME universe' => find_model_loop universe'
webertj@22092
  1216
					| NONE           => writeln
webertj@22092
  1217
						"Search terminated, no larger universe within the given limits.")
webertj@15547
  1218
				| SatSolver.UNKNOWN =>
wenzelm@14984
  1219
					(immediate_output " no model found.\n";
webertj@14807
  1220
					case next_universe universe sizes minsize maxsize of
skalberg@15531
  1221
					  SOME universe' => find_model_loop universe'
webertj@22092
  1222
					| NONE           => writeln
webertj@22092
  1223
						"Search terminated, no larger universe within the given limits.")
webertj@15547
  1224
				) handle SatSolver.NOT_CONFIGURED =>
webertj@14965
  1225
					error ("SAT solver " ^ quote satsolver ^ " is not configured.")
webertj@14807
  1226
			end handle MAXVARS_EXCEEDED =>
webertj@22092
  1227
				writeln ("\nSearch terminated, number of Boolean variables ("
webertj@22092
  1228
					^ string_of_int maxvars ^ " allowed) exceeded.")
webertj@14807
  1229
			in
webertj@14807
  1230
				find_model_loop (first_universe types sizes minsize)
webertj@14456
  1231
			end
webertj@14807
  1232
		in
webertj@14807
  1233
			(* some parameter sanity checks *)
webertj@22092
  1234
			assert (minsize>=1)
webertj@22092
  1235
				("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
webertj@22092
  1236
			assert (maxsize>=1)
webertj@22092
  1237
				("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
webertj@22092
  1238
			assert (maxsize>=minsize)
webertj@22092
  1239
				("\"maxsize\" (=" ^ string_of_int maxsize ^
webertj@22092
  1240
				") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
webertj@22092
  1241
			assert (maxvars>=0)
webertj@22092
  1242
				("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
webertj@22092
  1243
			assert (maxtime>=0)
webertj@22092
  1244
				("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
webertj@15547
  1245
			(* enter loop with or without time limit *)
webertj@22092
  1246
			writeln ("Trying to find a model that "
webertj@22092
  1247
				^ (if negate then "refutes" else "satisfies") ^ ": "
webertj@21992
  1248
				^ Sign.string_of_term thy t);
webertj@15547
  1249
			if maxtime>0 then (
webertj@18760
  1250
				interrupt_timeout (Time.fromSeconds (Int.toLarge maxtime))
webertj@14807
  1251
					wrapper ()
webertj@18760
  1252
				handle Interrupt =>
webertj@22092
  1253
					writeln ("\nSearch terminated, time limit (" ^ string_of_int maxtime
webertj@22092
  1254
						^ (if maxtime=1 then " second" else " seconds") ^ ") exceeded.")
webertj@15547
  1255
			) else
webertj@14807
  1256
				wrapper ()
webertj@14807
  1257
		end;
webertj@14456
  1258
webertj@14456
  1259
webertj@14456
  1260
(* ------------------------------------------------------------------------- *)
webertj@14456
  1261
(* INTERFACE, PART 2: FINDING A MODEL                                        *)
webertj@14350
  1262
(* ------------------------------------------------------------------------- *)
webertj@14350
  1263
webertj@14350
  1264
(* ------------------------------------------------------------------------- *)
webertj@14456
  1265
(* satisfy_term: calls 'find_model' to find a model that satisfies 't'       *)
webertj@14456
  1266
(* params      : list of '(name, value)' pairs used to override default      *)
webertj@14456
  1267
(*               parameters                                                  *)
webertj@14350
  1268
(* ------------------------------------------------------------------------- *)
webertj@14350
  1269
webertj@14456
  1270
	(* theory -> (string * string) list -> Term.term -> unit *)
webertj@14350
  1271
webertj@14456
  1272
	fun satisfy_term thy params t =
webertj@14807
  1273
		find_model thy (actual_params thy params) t false;
webertj@14350
  1274
webertj@14350
  1275
(* ------------------------------------------------------------------------- *)
webertj@14456
  1276
(* refute_term: calls 'find_model' to find a model that refutes 't'          *)
webertj@14456
  1277
(* params     : list of '(name, value)' pairs used to override default       *)
webertj@14456
  1278
(*              parameters                                                   *)
webertj@14350
  1279
(* ------------------------------------------------------------------------- *)
webertj@14350
  1280
webertj@14456
  1281
	(* theory -> (string * string) list -> Term.term -> unit *)
webertj@14350
  1282
webertj@14456
  1283
	fun refute_term thy params t =
webertj@14350
  1284
	let
webertj@14807
  1285
		(* disallow schematic type variables, since we cannot properly negate  *)
webertj@14807
  1286
		(* terms containing them (their logical meaning is that there EXISTS a *)
webertj@14807
  1287
		(* type s.t. ...; to refute such a formula, we would have to show that *)
webertj@14807
  1288
		(* for ALL types, not ...)                                             *)
webertj@22092
  1289
		val _ = assert (null (term_tvars t))
webertj@22092
  1290
			"Term to be refuted contains schematic type variables"
webertj@21556
  1291
webertj@14456
  1292
		(* existential closure over schematic variables *)
webertj@14456
  1293
		(* (Term.indexname * Term.typ) list *)
webertj@14456
  1294
		val vars = sort_wrt (fst o fst) (map dest_Var (term_vars t))
webertj@14456
  1295
		(* Term.term *)
webertj@22092
  1296
		val ex_closure = Library.foldl (fn (t', ((x, i), T)) =>
webertj@22092
  1297
			(HOLogic.exists_const T) $
webertj@22092
  1298
				Abs (x, T, abstract_over (Var ((x, i), T), t')))
webertj@14456
  1299
			(t, vars)
webertj@21556
  1300
		(* Note: If 't' is of type 'propT' (rather than 'boolT'), applying   *)
webertj@21556
  1301
		(* 'HOLogic.exists_const' is not type-correct.  However, this is not *)
webertj@21556
  1302
		(* really a problem as long as 'find_model' still interprets the     *)
webertj@21556
  1303
		(* resulting term correctly, without checking its type.              *)
webertj@21556
  1304
webertj@21556
  1305
		(* replace outermost universally quantified variables by Free's:     *)
webertj@21556
  1306
		(* refuting a term with Free's is generally faster than refuting a   *)
webertj@21556
  1307
		(* term with (nested) quantifiers, because quantifiers are expanded, *)
webertj@21556
  1308
		(* while the SAT solver searches for an interpretation for Free's.   *)
webertj@21556
  1309
		(* Also we get more information back that way, namely an             *)
webertj@21556
  1310
		(* interpretation which includes values for the (formerly)           *)
webertj@21556
  1311
		(* quantified variables.                                             *)
webertj@21556
  1312
		(* maps  !!x1...xn. !xk...xm. t   to   t  *)
webertj@21556
  1313
		fun strip_all_body (Const ("all", _) $ Abs (_, _, t)) = strip_all_body t
webertj@21556
  1314
		  | strip_all_body (Const ("Trueprop", _) $ t)        = strip_all_body t
webertj@21556
  1315
		  | strip_all_body (Const ("All", _) $ Abs (_, _, t)) = strip_all_body t
webertj@21556
  1316
		  | strip_all_body t                                  = t
webertj@21556
  1317
		(* maps  !!x1...xn. !xk...xm. t   to   [x1, ..., xn, xk, ..., xm]  *)
webertj@22092
  1318
		fun strip_all_vars (Const ("all", _) $ Abs (a, T, t)) =
webertj@22092
  1319
			(a, T) :: strip_all_vars t
webertj@22092
  1320
		  | strip_all_vars (Const ("Trueprop", _) $ t)        =
webertj@22092
  1321
			strip_all_vars t
webertj@22092
  1322
		  | strip_all_vars (Const ("All", _) $ Abs (a, T, t)) =
webertj@22092
  1323
			(a, T) :: strip_all_vars t
webertj@22092
  1324
		  | strip_all_vars t                                  =
webertj@22092
  1325
			[] : (string * typ) list
webertj@21556
  1326
		val strip_t = strip_all_body ex_closure
webertj@21556
  1327
		val frees   = Term.rename_wrt_term strip_t (strip_all_vars ex_closure)
webertj@21556
  1328
		val subst_t = Term.subst_bounds (map Free frees, strip_t)
webertj@14350
  1329
	in
webertj@21556
  1330
		find_model thy (actual_params thy params) subst_t true
webertj@14350
  1331
	end;
webertj@14350
  1332
webertj@14350
  1333
(* ------------------------------------------------------------------------- *)
webertj@14456
  1334
(* refute_subgoal: calls 'refute_term' on a specific subgoal                 *)
webertj@14456
  1335
(* params        : list of '(name, value)' pairs used to override default    *)
webertj@14456
  1336
(*                 parameters                                                *)
webertj@14456
  1337
(* subgoal       : 0-based index specifying the subgoal number               *)
webertj@14350
  1338
(* ------------------------------------------------------------------------- *)
webertj@14350
  1339
webertj@14456
  1340
	(* theory -> (string * string) list -> Thm.thm -> int -> unit *)
webertj@14350
  1341
webertj@14456
  1342
	fun refute_subgoal thy params thm subgoal =
webertj@22055
  1343
		refute_term thy params (List.nth (Thm.prems_of thm, subgoal));
webertj@14350
  1344
webertj@14350
  1345
webertj@14350
  1346
(* ------------------------------------------------------------------------- *)
webertj@15292
  1347
(* INTERPRETERS: Auxiliary Functions                                         *)
webertj@14350
  1348
(* ------------------------------------------------------------------------- *)
webertj@14350
  1349
webertj@14350
  1350
(* ------------------------------------------------------------------------- *)
webertj@14807
  1351
(* make_constants: returns all interpretations that have the same tree       *)
webertj@14807
  1352
(*                 structure as 'intr', but consist of unit vectors with     *)
webertj@14807
  1353
(*                 'True'/'False' only (no Boolean variables)                *)
webertj@14350
  1354
(* ------------------------------------------------------------------------- *)
webertj@14350
  1355
webertj@14807
  1356
	(* interpretation -> interpretation list *)
webertj@14350
  1357
webertj@14807
  1358
	fun make_constants intr =
webertj@14456
  1359
	let
webertj@14350
  1360
		(* returns a list with all unit vectors of length n *)
webertj@14456
  1361
		(* int -> interpretation list *)
webertj@14350
  1362
		fun unit_vectors n =
webertj@14350
  1363
		let
webertj@14350
  1364
			(* returns the k-th unit vector of length n *)
webertj@14456
  1365
			(* int * int -> interpretation *)
webertj@14350
  1366
			fun unit_vector (k,n) =
webertj@14350
  1367
				Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
webertj@14456
  1368
			(* int -> interpretation list -> interpretation list *)
webertj@14350
  1369
			fun unit_vectors_acc k vs =
webertj@14350
  1370
				if k>n then [] else (unit_vector (k,n))::(unit_vectors_acc (k+1) vs)
webertj@14350
  1371
		in
webertj@14350
  1372
			unit_vectors_acc 1 []
webertj@14350
  1373
		end
webertj@22092
  1374
		(* returns a list of lists, each one consisting of n (possibly *)
webertj@22092
  1375
		(* identical) elements from 'xs'                               *)
webertj@14350
  1376
		(* int -> 'a list -> 'a list list *)
webertj@14350
  1377
		fun pick_all 1 xs =
webertj@22092
  1378
			map single xs
webertj@14350
  1379
		  | pick_all n xs =
webertj@14350
  1380
			let val rec_pick = pick_all (n-1) xs in
webertj@22092
  1381
				Library.foldl (fn (acc, x) => map (cons x) rec_pick @ acc) ([], xs)
webertj@14350
  1382
			end
webertj@14807
  1383
	in
webertj@14807
  1384
		case intr of
webertj@14807
  1385
		  Leaf xs => unit_vectors (length xs)
webertj@22092
  1386
		| Node xs => map (fn xs' => Node xs') (pick_all (length xs)
webertj@22092
  1387
			(make_constants (hd xs)))
webertj@14807
  1388
	end;
webertj@14807
  1389
webertj@14807
  1390
(* ------------------------------------------------------------------------- *)
webertj@14807
  1391
(* size_of_type: returns the number of constants in a type (i.e. 'length     *)
webertj@14807
  1392
(*               (make_constants intr)', but implemented more efficiently)   *)
webertj@14807
  1393
(* ------------------------------------------------------------------------- *)
webertj@14807
  1394
webertj@14807
  1395
	(* interpretation -> int *)
webertj@14807
  1396
webertj@14807
  1397
	fun size_of_type intr =
webertj@14807
  1398
	let
webertj@15611
  1399
		(* power (a, b) computes a^b, for a>=0, b>=0 *)
webertj@14807
  1400
		(* int * int -> int *)
webertj@15611
  1401
		fun power (a, 0) = 1
webertj@15611
  1402
		  | power (a, 1) = a
webertj@22092
  1403
		  | power (a, b) = let val ab = power(a, b div 2) in
webertj@22092
  1404
				ab * ab * power(a, b mod 2)
webertj@22092
  1405
			end
webertj@14807
  1406
	in
webertj@14807
  1407
		case intr of
webertj@14807
  1408
		  Leaf xs => length xs
webertj@14807
  1409
		| Node xs => power (size_of_type (hd xs), length xs)
webertj@14807
  1410
	end;
webertj@14807
  1411
webertj@14807
  1412
(* ------------------------------------------------------------------------- *)
webertj@14807
  1413
(* TT/FF: interpretations that denote "true" or "false", respectively        *)
webertj@14807
  1414
(* ------------------------------------------------------------------------- *)
webertj@14807
  1415
webertj@14807
  1416
	(* interpretation *)
webertj@14807
  1417
webertj@14807
  1418
	val TT = Leaf [True, False];
webertj@14807
  1419
webertj@14807
  1420
	val FF = Leaf [False, True];
webertj@14807
  1421
webertj@14807
  1422
(* ------------------------------------------------------------------------- *)
webertj@14807
  1423
(* make_equality: returns an interpretation that denotes (extensional)       *)
webertj@14807
  1424
(*                equality of two interpretations                            *)
webertj@15547
  1425
(* - two interpretations are 'equal' iff they are both defined and denote    *)
webertj@15547
  1426
(*   the same value                                                          *)
webertj@15547
  1427
(* - two interpretations are 'not_equal' iff they are both defined at least  *)
webertj@15547
  1428
(*   partially, and a defined part denotes different values                  *)
webertj@15547
  1429
(* - a completely undefined interpretation is neither 'equal' nor            *)
webertj@15547
  1430
(*   'not_equal' to another interpretation                                   *)
webertj@14807
  1431
(* ------------------------------------------------------------------------- *)
webertj@14807
  1432
webertj@14807
  1433
	(* We could in principle represent '=' on a type T by a particular        *)
webertj@14807
  1434
	(* interpretation.  However, the size of that interpretation is quadratic *)
webertj@14807
  1435
	(* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
webertj@14807
  1436
	(* 'i2' directly is more efficient than constructing the interpretation   *)
webertj@14807
  1437
	(* for equality on T first, and "applying" this interpretation to 'i1'    *)
webertj@14807
  1438
	(* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
webertj@14807
  1439
webertj@14807
  1440
	(* interpretation * interpretation -> interpretation *)
webertj@14807
  1441
webertj@14807
  1442
	fun make_equality (i1, i2) =
webertj@14807
  1443
	let
webertj@14807
  1444
		(* interpretation * interpretation -> prop_formula *)
webertj@14807
  1445
		fun equal (i1, i2) =
webertj@14807
  1446
			(case i1 of
webertj@14807
  1447
			  Leaf xs =>
webertj@14807
  1448
				(case i2 of
webertj@15547
  1449
				  Leaf ys => PropLogic.dot_product (xs, ys)  (* defined and equal *)
webertj@22092
  1450
				| Node _  => raise REFUTE ("make_equality",
webertj@22092
  1451
					"second interpretation is higher"))
webertj@14807
  1452
			| Node xs =>
webertj@14807
  1453
				(case i2 of
webertj@22092
  1454
				  Leaf _  => raise REFUTE ("make_equality",
webertj@22092
  1455
					"first interpretation is higher")
webertj@14807
  1456
				| Node ys => PropLogic.all (map equal (xs ~~ ys))))
webertj@14807
  1457
		(* interpretation * interpretation -> prop_formula *)
webertj@14807
  1458
		fun not_equal (i1, i2) =
webertj@14807
  1459
			(case i1 of
webertj@14807
  1460
			  Leaf xs =>
webertj@14807
  1461
				(case i2 of
webertj@22092
  1462
				  (* defined and not equal *)
webertj@22092
  1463
				  Leaf ys => PropLogic.all ((PropLogic.exists xs)
webertj@22092
  1464
					:: (PropLogic.exists ys)
webertj@22092
  1465
					:: (map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))
webertj@22092
  1466
				| Node _  => raise REFUTE ("make_equality",
webertj@22092
  1467
					"second interpretation is higher"))
webertj@14807
  1468
			| Node xs =>
webertj@14807
  1469
				(case i2 of
webertj@22092
  1470
				  Leaf _  => raise REFUTE ("make_equality",
webertj@22092
  1471
					"first interpretation is higher")
webertj@14807
  1472
				| Node ys => PropLogic.exists (map not_equal (xs ~~ ys))))
webertj@14350
  1473
	in
webertj@22092
  1474
		(* a value may be undefined; therefore 'not_equal' is not just the *)
webertj@22092
  1475
		(* negation of 'equal'                                             *)
webertj@14807
  1476
		Leaf [equal (i1, i2), not_equal (i1, i2)]
webertj@14807
  1477
	end;
webertj@14807
  1478
webertj@15292
  1479
(* ------------------------------------------------------------------------- *)
webertj@15547
  1480
(* make_def_equality: returns an interpretation that denotes (extensional)   *)
webertj@15547
  1481
(*                    equality of two interpretations                        *)
webertj@15547
  1482
(* This function treats undefined/partially defined interpretations          *)
webertj@15547
  1483
(* different from 'make_equality': two undefined interpretations are         *)
webertj@15547
  1484
(* considered equal, while a defined interpretation is considered not equal  *)
webertj@15547
  1485
(* to an undefined interpretation.                                           *)
webertj@15547
  1486
(* ------------------------------------------------------------------------- *)
webertj@15547
  1487
webertj@15547
  1488
	(* interpretation * interpretation -> interpretation *)
webertj@15547
  1489
webertj@15547
  1490
	fun make_def_equality (i1, i2) =
webertj@15547
  1491
	let
webertj@15547
  1492
		(* interpretation * interpretation -> prop_formula *)
webertj@15547
  1493
		fun equal (i1, i2) =
webertj@15547
  1494
			(case i1 of
webertj@15547
  1495
			  Leaf xs =>
webertj@15547
  1496
				(case i2 of
webertj@22092
  1497
				  (* defined and equal, or both undefined *)
webertj@22092
  1498
				  Leaf ys => SOr (PropLogic.dot_product (xs, ys),
webertj@15547
  1499
					SAnd (PropLogic.all (map SNot xs), PropLogic.all (map SNot ys)))
webertj@22092
  1500
				| Node _  => raise REFUTE ("make_def_equality",
webertj@22092
  1501
					"second interpretation is higher"))
webertj@15547
  1502
			| Node xs =>
webertj@15547
  1503
				(case i2 of
webertj@22092
  1504
				  Leaf _  => raise REFUTE ("make_def_equality",
webertj@22092
  1505
					"first interpretation is higher")
webertj@15547
  1506
				| Node ys => PropLogic.all (map equal (xs ~~ ys))))
webertj@15547
  1507
		(* interpretation *)
webertj@15547
  1508
		val eq = equal (i1, i2)
webertj@15547
  1509
	in
webertj@15547
  1510
		Leaf [eq, SNot eq]
webertj@15547
  1511
	end;
webertj@15547
  1512
webertj@15547
  1513
(* ------------------------------------------------------------------------- *)
webertj@15547
  1514
(* interpretation_apply: returns an interpretation that denotes the result   *)
webertj@22092
  1515
(*                       of applying the function denoted by 'i1' to the     *)
webertj@15547
  1516
(*                       argument denoted by 'i2'                            *)
webertj@15547
  1517
(* ------------------------------------------------------------------------- *)
webertj@15547
  1518
webertj@15547
  1519
	(* interpretation * interpretation -> interpretation *)
webertj@15547
  1520
webertj@15547
  1521
	fun interpretation_apply (i1, i2) =
webertj@15547
  1522
	let
webertj@15547
  1523
		(* interpretation * interpretation -> interpretation *)
webertj@15547
  1524
		fun interpretation_disjunction (tr1,tr2) =
webertj@22092
  1525
			tree_map (fn (xs,ys) => map (fn (x,y) => SOr(x,y)) (xs ~~ ys))
webertj@22092
  1526
				(tree_pair (tr1,tr2))
webertj@15547
  1527
		(* prop_formula * interpretation -> interpretation *)
webertj@15547
  1528
		fun prop_formula_times_interpretation (fm,tr) =
webertj@15547
  1529
			tree_map (map (fn x => SAnd (fm,x))) tr
webertj@15547
  1530
		(* prop_formula list * interpretation list -> interpretation *)
webertj@15547
  1531
		fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
webertj@15547
  1532
			prop_formula_times_interpretation (fm,tr)
webertj@15547
  1533
		  | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
webertj@22092
  1534
			interpretation_disjunction (prop_formula_times_interpretation (fm,tr),
webertj@22092
  1535
				prop_formula_list_dot_product_interpretation_list (fms,trees))
webertj@15547
  1536
		  | prop_formula_list_dot_product_interpretation_list (_,_) =
webertj@15547
  1537
			raise REFUTE ("interpretation_apply", "empty list (in dot product)")
webertj@22092
  1538
		(* concatenates 'x' with every list in 'xss', returning a new list of *)
webertj@22092
  1539
		(* lists                                                              *)
webertj@15547
  1540
		(* 'a -> 'a list list -> 'a list list *)
webertj@15547
  1541
		fun cons_list x xss =
webertj@22092
  1542
			map (cons x) xss
webertj@22092
  1543
		(* returns a list of lists, each one consisting of one element from each *)
webertj@22092
  1544
		(* element of 'xss'                                                      *)
webertj@15547
  1545
		(* 'a list list -> 'a list list *)
webertj@15547
  1546
		fun pick_all [xs] =
webertj@22092
  1547
			map single xs
webertj@15547
  1548
		  | pick_all (xs::xss) =
webertj@15547
  1549
			let val rec_pick = pick_all xss in
webertj@15611
  1550
				Library.foldl (fn (acc, x) => (cons_list x rec_pick) @ acc) ([], xs)
webertj@15547
  1551
			end
webertj@15547
  1552
		  | pick_all _ =
webertj@15547
  1553
			raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
webertj@15547
  1554
		(* interpretation -> prop_formula list *)
webertj@15547
  1555
		fun interpretation_to_prop_formula_list (Leaf xs) =
webertj@15547
  1556
			xs
webertj@15547
  1557
		  | interpretation_to_prop_formula_list (Node trees) =
webertj@22092
  1558
			map PropLogic.all (pick_all
webertj@22092
  1559
				(map interpretation_to_prop_formula_list trees))
webertj@15547
  1560
	in
webertj@15547
  1561
		case i1 of
webertj@15547
  1562
		  Leaf _ =>
webertj@15547
  1563
			raise REFUTE ("interpretation_apply", "first interpretation is a leaf")
webertj@15547
  1564
		| Node xs =>
webertj@22092
  1565
			prop_formula_list_dot_product_interpretation_list
webertj@22092
  1566
				(interpretation_to_prop_formula_list i2, xs)
webertj@15547
  1567
	end;
webertj@15547
  1568
webertj@15547
  1569
(* ------------------------------------------------------------------------- *)
webertj@15292
  1570
(* eta_expand: eta-expands a term 't' by adding 'i' lambda abstractions      *)
webertj@15292
  1571
(* ------------------------------------------------------------------------- *)
webertj@15292
  1572
webertj@15292
  1573
	(* Term.term -> int -> Term.term *)
webertj@15292
  1574
webertj@15292
  1575
	fun eta_expand t i =
webertj@15292
  1576
	let
webertj@21985
  1577
		val Ts = Term.binder_types (Term.fastype_of t)
webertj@21985
  1578
		val t' = Term.incr_boundvars i t
webertj@15292
  1579
	in
webertj@21985
  1580
		foldr (fn (T, term) => Abs ("<eta_expand>", T, term))
webertj@21985
  1581
			(Term.list_comb (t', map Bound (i-1 downto 0))) (List.take (Ts, i))
webertj@15292
  1582
	end;
webertj@15292
  1583
webertj@15335
  1584
(* ------------------------------------------------------------------------- *)
webertj@15335
  1585
(* sum: returns the sum of a list 'xs' of integers                           *)
webertj@15335
  1586
(* ------------------------------------------------------------------------- *)
webertj@15335
  1587
webertj@15335
  1588
	(* int list -> int *)
webertj@15335
  1589
webertj@15611
  1590
	fun sum xs = foldl op+ 0 xs;
webertj@15335
  1591
webertj@15335
  1592
(* ------------------------------------------------------------------------- *)
webertj@15335
  1593
(* product: returns the product of a list 'xs' of integers                   *)
webertj@15335
  1594
(* ------------------------------------------------------------------------- *)
webertj@15335
  1595
webertj@15335
  1596
	(* int list -> int *)
webertj@15335
  1597
webertj@15611
  1598
	fun product xs = foldl op* 1 xs;
webertj@15335
  1599
webertj@15335
  1600
(* ------------------------------------------------------------------------- *)
webertj@15547
  1601
(* size_of_dtyp: the size of (an initial fragment of) an inductive data type *)
webertj@15547
  1602
(*               is the sum (over its constructors) of the product (over     *)
webertj@15547
  1603
(*               their arguments) of the size of the argument types          *)
webertj@15335
  1604
(* ------------------------------------------------------------------------- *)
webertj@15335
  1605
webertj@22092
  1606
	(* theory -> (Term.typ * int) list -> DatatypeAux.descr ->
webertj@22092
  1607
		(DatatypeAux.dtyp * Term.typ) list ->
webertj@22092
  1608
		(string * DatatypeAux.dtyp list) list -> int *)
webertj@15335
  1609
webertj@15335
  1610
	fun size_of_dtyp thy typ_sizes descr typ_assoc constructors =
webertj@15335
  1611
		sum (map (fn (_, dtyps) =>
webertj@15335
  1612
			product (map (fn dtyp =>
webertj@15335
  1613
				let
webertj@15335
  1614
					val T         = typ_of_dtyp descr typ_assoc dtyp
webertj@22092
  1615
					val (i, _, _) = interpret thy (typ_sizes, [])
webertj@22092
  1616
						{maxvars=0, def_eq=false, next_idx=1, bounds=[], wellformed=True}
webertj@22092
  1617
						(Free ("dummy", T))
webertj@15335
  1618
				in
webertj@15335
  1619
					size_of_type i
webertj@15335
  1620
				end) dtyps)) constructors);
webertj@15335
  1621
webertj@15292
  1622
webertj@15292
  1623
(* ------------------------------------------------------------------------- *)
webertj@15292
  1624
(* INTERPRETERS: Actual Interpreters                                         *)
webertj@15292
  1625
(* ------------------------------------------------------------------------- *)
webertj@14807
  1626
webertj@22092
  1627
	(* theory -> model -> arguments -> Term.term ->
webertj@22092
  1628
		(interpretation * model * arguments) option *)
webertj@14807
  1629
webertj@22092
  1630
	(* simply typed lambda calculus: Isabelle's basic term syntax, with type *)
webertj@22092
  1631
	(* variables, function types, and propT                                  *)
webertj@14807
  1632
webertj@14807
  1633
	fun stlc_interpreter thy model args t =
webertj@14807
  1634
	let
webertj@15547
  1635
		val (typs, terms)                                   = model
webertj@15547
  1636
		val {maxvars, def_eq, next_idx, bounds, wellformed} = args
webertj@14807
  1637
		(* Term.typ -> (interpretation * model * arguments) option *)
webertj@14807
  1638
		fun interpret_groundterm T =
webertj@14807
  1639
		let
webertj@14807
  1640
			(* unit -> (interpretation * model * arguments) option *)
webertj@14807
  1641
			fun interpret_groundtype () =
webertj@14807
  1642
			let
webertj@22092
  1643
				(* the model must specify a size for ground types *)
webertj@22092
  1644
				val size = (if T = Term.propT then 2 else lookup typs T)
webertj@15547
  1645
				val next = next_idx+size
webertj@22092
  1646
				(* check if 'maxvars' is large enough *)
webertj@22092
  1647
				val _    = (if next-1>maxvars andalso maxvars>0 then
webertj@22092
  1648
					raise MAXVARS_EXCEEDED else ())
webertj@14807
  1649
				(* prop_formula list *)
webertj@15547
  1650
				val fms  = map BoolVar (next_idx upto (next_idx+size-1))
webertj@14807
  1651
				(* interpretation *)
webertj@14807
  1652
				val intr = Leaf fms
webertj@14807
  1653
				(* prop_formula list -> prop_formula *)
webertj@14807
  1654
				fun one_of_two_false []      = True
webertj@22092
  1655
				  | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
webertj@22092
  1656
					SOr (SNot x, SNot x')) xs), one_of_two_false xs)
webertj@14807
  1657
				(* prop_formula *)
webertj@15547
  1658
				val wf   = one_of_two_false fms
webertj@14807
  1659
			in
webertj@22092
  1660
				(* extend the model, increase 'next_idx', add well-formedness *)
webertj@22092
  1661
				(* condition                                                  *)
webertj@22092
  1662
				SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
webertj@22092
  1663
					def_eq = def_eq, next_idx = next, bounds = bounds,
webertj@22092
  1664
					wellformed = SAnd (wellformed, wf)})
webertj@14807
  1665
			end
webertj@14807
  1666
		in
webertj@14807
  1667
			case T of
webertj@14807
  1668
			  Type ("fun", [T1, T2]) =>
webertj@14807
  1669
				let
webertj@14807
  1670
					(* we create 'size_of_type (interpret (... T1))' different copies *)
webertj@14807
  1671
					(* of the interpretation for 'T2', which are then combined into a *)
webertj@14807
  1672
					(* single new interpretation                                      *)
webertj@22092
  1673
					val (i1, _, _) = interpret thy model {maxvars=0, def_eq=false,
webertj@22092
  1674
						next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T1))
webertj@14807
  1675
					(* make fresh copies, with different variable indices *)
webertj@14807
  1676
					(* 'idx': next variable index                         *)
webertj@14807
  1677
					(* 'n'  : number of copies                            *)
webertj@14807
  1678
					(* int -> int -> (int * interpretation list * prop_formula *)
webertj@14807
  1679
					fun make_copies idx 0 =
webertj@14807
  1680
						(idx, [], True)
webertj@14807
  1681
					  | make_copies idx n =
webertj@14807
  1682
						let
webertj@22092
  1683
							val (copy, _, new_args) = interpret thy (typs, [])
webertj@22092
  1684
								{maxvars = maxvars, def_eq = false, next_idx = idx,
webertj@22092
  1685
								bounds = [], wellformed = True} (Free ("dummy", T2))
webertj@14807
  1686
							val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
webertj@14807
  1687
						in
webertj@14807
  1688
							(idx', copy :: copies, SAnd (#wellformed new_args, wf'))
webertj@14807
  1689
						end
webertj@14807
  1690
					val (next, copies, wf) = make_copies next_idx (size_of_type i1)
webertj@14807
  1691
					(* combine copies into a single interpretation *)
webertj@14807
  1692
					val intr = Node copies
webertj@14807
  1693
				in
webertj@22092
  1694
					(* extend the model, increase 'next_idx', add well-formedness *)
webertj@22092
  1695
					(* condition                                                  *)
webertj@22092
  1696
					SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
webertj@22092
  1697
						def_eq = def_eq, next_idx = next, bounds = bounds,
webertj@22092
  1698
						wellformed = SAnd (wellformed, wf)})
webertj@14807
  1699
				end
webertj@14807
  1700
			| Type _  => interpret_groundtype ()
webertj@14807
  1701
			| TFree _ => interpret_groundtype ()
webertj@14807
  1702
			| TVar  _ => interpret_groundtype ()
webertj@14807
  1703
		end
webertj@14807
  1704
	in
haftmann@17314
  1705
		case AList.lookup (op =) terms t of
skalberg@15531
  1706
		  SOME intr =>
webertj@14807
  1707
			(* return an existing interpretation *)
skalberg@15531
  1708
			SOME (intr, model, args)
skalberg@15531
  1709
		| NONE =>
webertj@14807
  1710
			(case t of
webertj@14807
  1711
			  Const (_, T)     =>
webertj@14807
  1712
				interpret_groundterm T
webertj@14807
  1713
			| Free (_, T)      =>
webertj@14807
  1714
				interpret_groundterm T
webertj@14807
  1715
			| Var (_, T)       =>
webertj@14807
  1716
				interpret_groundterm T
webertj@14807
  1717
			| Bound i          =>
skalberg@15570
  1718
				SOME (List.nth (#bounds args, i), model, args)
webertj@14807
  1719
			| Abs (x, T, body) =>
webertj@14807
  1720
				let
webertj@14807
  1721
					(* create all constants of type 'T' *)
webertj@22092
  1722
					val (i, _, _) = interpret thy model {maxvars=0, def_eq=false,
webertj@22092
  1723
						next_idx=1, bounds=[], wellformed=True} (Free ("dummy", T))
webertj@14807
  1724
					val constants = make_constants i
webertj@14807
  1725
					(* interpret the 'body' separately for each constant *)
webertj@14807
  1726
					val ((model', args'), bodies) = foldl_map
webertj@15547
  1727
						(fn ((m, a), c) =>
webertj@14807
  1728
							let
webertj@14807
  1729
								(* add 'c' to 'bounds' *)
webertj@22092
  1730
								val (i', m', a') = interpret thy m {maxvars = #maxvars a,
webertj@22092
  1731
									def_eq = #def_eq a, next_idx = #next_idx a,
webertj@22092
  1732
									bounds = (c :: #bounds a), wellformed = #wellformed a} body
webertj@14807
  1733
							in
webertj@22092
  1734
								(* keep the new model m' and 'next_idx' and 'wellformed', *)
webertj@22092
  1735
								(* but use old 'bounds'                                   *)
webertj@22092
  1736
								((m', {maxvars = maxvars, def_eq = def_eq,
webertj@22092
  1737
									next_idx = #next_idx a', bounds = bounds,
webertj@22092
  1738
									wellformed = #wellformed a'}), i')
webertj@14807
  1739
							end)
webertj@14807
  1740
						((model, args), constants)
webertj@14807
  1741
				in
skalberg@15531
  1742
					SOME (Node bodies, model', args')
webertj@14807
  1743
				end
webertj@14807
  1744
			| t1 $ t2          =>
webertj@14807
  1745
				let
webertj@14807
  1746
					(* interpret 't1' and 't2' separately *)
webertj@14807
  1747
					val (intr1, model1, args1) = interpret thy model args t1
webertj@14807
  1748
					val (intr2, model2, args2) = interpret thy model1 args1 t2
webertj@14807
  1749
				in
webertj@15547
  1750
					SOME (interpretation_apply (intr1, intr2), model2, args2)
webertj@14807
  1751
				end)
webertj@14807
  1752
	end;
webertj@14807
  1753
webertj@22092
  1754
	(* theory -> model -> arguments -> Term.term ->
webertj@22092
  1755
		(interpretation * model * arguments) option *)
webertj@14807
  1756
webertj@14807
  1757
	fun Pure_interpreter thy model args t =
webertj@14456
  1758
		case t of
webertj@21985
  1759
		  Const ("all", _) $ t1 =>
webertj@14807
  1760
			let
webertj@14807
  1761
				val (i, m, a) = interpret thy model args t1
webertj@14807
  1762
			in
webertj@14807
  1763
				case i of
webertj@14807
  1764
				  Node xs =>
webertj@21985
  1765
					(* 3-valued logic *)
webertj@14807
  1766
					let
webertj@14807
  1767
						val fmTrue  = PropLogic.all (map toTrue xs)
webertj@14807
  1768
						val fmFalse = PropLogic.exists (map toFalse xs)
webertj@14807
  1769
					in
skalberg@15531
  1770
						SOME (Leaf [fmTrue, fmFalse], m, a)
webertj@14807
  1771
					end
webertj@14807
  1772
				| _ =>
webertj@22092
  1773
					raise REFUTE ("Pure_interpreter",
webertj@22092
  1774
						"\"all\" is followed by a non-function")
webertj@14807
  1775
			end
webertj@21985
  1776
		| Const ("all", _) =>
webertj@21985
  1777
			SOME (interpret thy model args (eta_expand t 1))
webertj@14807
  1778
		| Const ("==", _) $ t1 $ t2 =>
webertj@14807
  1779
			let
webertj@14807
  1780
				val (i1, m1, a1) = interpret thy model args t1
webertj@14807
  1781
				val (i2, m2, a2) = interpret thy m1 a1 t2
webertj@14807
  1782
			in
webertj@15547
  1783
				(* we use either 'make_def_equality' or 'make_equality' *)
webertj@22092
  1784
				SOME ((if #def_eq args then make_def_equality else make_equality)
webertj@22092
  1785
					(i1, i2), m2, a2)
webertj@14807
  1786
			end
webertj@21985
  1787
		| Const ("==", _) $ t1 =>
webertj@21985
  1788
			SOME (interpret thy model args (eta_expand t 1))
webertj@21985
  1789
		| Const ("==", _) =>
webertj@21985
  1790
			SOME (interpret thy model args (eta_expand t 2))
webertj@21985
  1791
		| Const ("==>", _) $ t1 $ t2 =>
webertj@21985
  1792
			(* 3-valued logic *)
webertj@21985
  1793
			let
webertj@21985
  1794
				val (i1, m1, a1) = interpret thy model args t1
webertj@21985
  1795
				val (i2, m2, a2) = interpret thy m1 a1 t2
webertj@21985
  1796
				val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
webertj@21985
  1797
				val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
webertj@21985
  1798
			in
webertj@21985
  1799
				SOME (Leaf [fmTrue, fmFalse], m2, a2)
webertj@21985
  1800
			end
webertj@21985
  1801
		| Const ("==>", _) $ t1 =>
webertj@21985
  1802
			SOME (interpret thy model args (eta_expand t 1))
webertj@21985
  1803
		| Const ("==>", _) =>
webertj@21985
  1804
			SOME (interpret thy model args (eta_expand t 2))
skalberg@15531
  1805
		| _ => NONE;
webertj@14807
  1806
webertj@22092
  1807
	(* theory -> model -> arguments -> Term.term ->
webertj@22092
  1808
		(interpretation * model * arguments) option *)
webertj@14807
  1809
webertj@14807
  1810
	fun HOLogic_interpreter thy model args t =
webertj@22092
  1811
	(* Providing interpretations directly is more efficient than unfolding the *)
webertj@22092
  1812
	(* logical constants.  In HOL however, logical constants can themselves be *)
webertj@22092
  1813
	(* arguments.  They are then translated using eta-expansion.               *)
webertj@14807
  1814
		case t of
webertj@14807
  1815
		  Const ("Trueprop", _) =>
skalberg@15531
  1816
			SOME (Node [TT, FF], model, args)
webertj@14807
  1817
		| Const ("Not", _) =>
skalberg@15531
  1818
			SOME (Node [FF, TT], model, args)
webertj@22092
  1819
		(* redundant, since 'True' is also an IDT constructor *)
webertj@22092
  1820
		| Const ("True", _) =>
skalberg@15531
  1821
			SOME (TT, model, args)
webertj@22092
  1822
		(* redundant, since 'False' is also an IDT constructor *)
webertj@22092
  1823
		| Const ("False", _) =>
skalberg@15531
  1824
			SOME (FF, model, args)
webertj@21985
  1825
		| Const ("All", _) $ t1 =>  (* similar to "all" (Pure) *)
webertj@14350
  1826
			let
webertj@14807
  1827
				val (i, m, a) = interpret thy model args t1
webertj@14807
  1828
			in
webertj@14807
  1829
				case i of
webertj@14807
  1830
				  Node xs =>
webertj@21985
  1831
					(* 3-valued logic *)
webertj@14807
  1832
					let
webertj@14807
  1833
						val fmTrue  = PropLogic.all (map toTrue xs)
webertj@14807
  1834
						val fmFalse = PropLogic.exists (map toFalse xs)
webertj@14807
  1835
					in
skalberg@15531
  1836
						SOME (Leaf [fmTrue, fmFalse], m, a)
webertj@14807
  1837
					end
webertj@14807
  1838
				| _ =>
webertj@22092
  1839
					raise REFUTE ("HOLogic_interpreter",
webertj@22092
  1840
						"\"All\" is followed by a non-function")
webertj@14807
  1841
			end
webertj@21985
  1842
		| Const ("All", _) =>
webertj@21985
  1843
			SOME (interpret thy model args (eta_expand t 1))
webertj@15333
  1844
		| Const ("Ex", _) $ t1 =>
webertj@14807
  1845
			let
webertj@14807
  1846
				val (i, m, a) = interpret thy model args t1
webertj@14807
  1847
			in
webertj@14807
  1848
				case i of
webertj@14807
  1849
				  Node xs =>
webertj@21985
  1850
					(* 3-valued logic *)
webertj@14807
  1851
					let
webertj@14807
  1852
						val fmTrue  = PropLogic.exists (map toTrue xs)
webertj@14807
  1853
						val fmFalse = PropLogic.all (map toFalse xs)
webertj@14807
  1854
					in
skalberg@15531
  1855
						SOME (Leaf [fmTrue, fmFalse], m, a)
webertj@14807
  1856
					end
webertj@14807
  1857
				| _ =>
webertj@22092
  1858
					raise REFUTE ("HOLogic_interpreter",
webertj@22092
  1859
						"\"Ex\" is followed by a non-function")
webertj@14807
  1860
			end
webertj@21985
  1861
		| Const ("Ex", _) =>
webertj@21985
  1862
			SOME (interpret thy model args (eta_expand t 1))
webertj@21985
  1863
		| Const ("op =", _) $ t1 $ t2 =>  (* similar to "==" (Pure) *)
webertj@14807
  1864
			let
webertj@14807
  1865
				val (i1, m1, a1) = interpret thy model args t1
webertj@14807
  1866
				val (i2, m2, a2) = interpret thy m1 a1 t2
webertj@14807
  1867
			in
skalberg@15531
  1868
				SOME (make_equality (i1, i2), m2, a2)
webertj@14807
  1869
			end
webertj@14807
  1870
		| Const ("op =", _) $ t1 =>
skalberg@15531
  1871
			SOME (interpret thy model args (eta_expand t 1))
webertj@14807
  1872
		| Const ("op =", _) =>
skalberg@15531
  1873
			SOME (interpret thy model args (eta_expand t 2))
webertj@15547
  1874
		| Const ("op &", _) $ t1 $ t2 =>
webertj@15547
  1875
			(* 3-valued logic *)
webertj@15547
  1876
			let
webertj@15547
  1877
				val (i1, m1, a1) = interpret thy model args t1
webertj@15547
  1878
				val (i2, m2, a2) = interpret thy m1 a1 t2
webertj@15547
  1879
				val fmTrue       = PropLogic.SAnd (toTrue i1, toTrue i2)
webertj@15547
  1880
				val fmFalse      = PropLogic.SOr (toFalse i1, toFalse i2)
webertj@15547
  1881
			in
webertj@15547
  1882
				SOME (Leaf [fmTrue, fmFalse], m2, a2)
webertj@15547
  1883
			end
webertj@15547
  1884
		| Const ("op &", _) $ t1 =>
webertj@15547
  1885
			SOME (interpret thy model args (eta_expand t 1))
webertj@14807
  1886
		| Const ("op &", _) =>
webertj@15547
  1887
			SOME (interpret thy model args (eta_expand t 2))
webertj@21985
  1888
			(* this would make "undef" propagate, even for formulae like *)
webertj@21985
  1889
			(* "False & undef":                                          *)
webertj@15547
  1890
			(* SOME (Node [Node [TT, FF], Node [FF, FF]], model, args) *)
webertj@15547
  1891
		| Const ("op |", _) $ t1 $ t2 =>
webertj@15547
  1892
			(* 3-valued logic *)
webertj@15547
  1893
			let
webertj@15547
  1894
				val (i1, m1, a1) = interpret thy model args t1
webertj@15547
  1895
				val (i2, m2, a2) = interpret thy m1 a1 t2
webertj@15547
  1896
				val fmTrue       = PropLogic.SOr (toTrue i1, toTrue i2)
webertj@15547
  1897
				val fmFalse      = PropLogic.SAnd (toFalse i1, toFalse i2)
webertj@15547
  1898
			in
webertj@15547
  1899
				SOME (Leaf [fmTrue, fmFalse], m2, a2)
webertj@15547
  1900
			end
webertj@15547
  1901
		| Const ("op |", _) $ t1 =>
webertj@15547
  1902
			SOME (interpret thy model args (eta_expand t 1))
webertj@14807
  1903
		| Const ("op |", _) =>
webertj@15547
  1904
			SOME (interpret thy model args (eta_expand t 2))
webertj@21985
  1905
			(* this would make "undef" propagate, even for formulae like *)
webertj@21985
  1906
			(* "True | undef":                                           *)
webertj@15547
  1907
			(* SOME (Node [Node [TT, TT], Node [TT, FF]], model, args) *)
webertj@21985
  1908
		| Const ("op -->", _) $ t1 $ t2 =>  (* similar to "==>" (Pure) *)
webertj@15547
  1909
			(* 3-valued logic *)
webertj@15547
  1910
			let
webertj@15547
  1911
				val (i1, m1, a1) = interpret thy model args t1
webertj@15547
  1912
				val (i2, m2, a2) = interpret thy m1 a1 t2
webertj@15547
  1913
				val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
webertj@15547
  1914
				val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
webertj@15547
  1915
			in
webertj@15547
  1916
				SOME (Leaf [fmTrue, fmFalse], m2, a2)
webertj@15547
  1917
			end
webertj@21985
  1918
		| Const ("op -->", _) $ t1 =>
webertj@21985
  1919
			SOME (interpret thy model args (eta_expand t 1))
webertj@14807
  1920
		| Const ("op -->", _) =>
webertj@21985
  1921
			SOME (interpret thy model args (eta_expand t 2))
webertj@21985
  1922
			(* this would make "undef" propagate, even for formulae like *)
webertj@21985
  1923
			(* "False --> undef":                                        *)
webertj@15547
  1924
			(* SOME (Node [Node [TT, FF], Node [TT, TT]], model, args) *)
skalberg@15531
  1925
		| _ => NONE;
webertj@14807
  1926
webertj@22092
  1927
	(* theory -> model -> arguments -> Term.term ->
webertj@22092
  1928
		(interpretation * model * arguments) option *)
webertj@14807
  1929
webertj@14807
  1930
	fun set_interpreter thy model args t =
webertj@14807
  1931
	(* "T set" is isomorphic to "T --> bool" *)
webertj@14807
  1932
	let
webertj@14807
  1933
		val (typs, terms) = model
webertj@14807
  1934
	in
haftmann@17314
  1935
		case AList.lookup (op =) terms t of
skalberg@15531
  1936
		  SOME intr =>
webertj@14807
  1937
			(* return an existing interpretation *)
skalberg@15531
  1938
			SOME (intr, model, args)
skalberg@15531
  1939
		| NONE =>
webertj@14807
  1940
			(case t of
webertj@14807
  1941
			  Free (x, Type ("set", [T])) =>
webertj@15334
  1942
				let
webertj@22092
  1943
					val (intr, _, args') =
webertj@22092
  1944
						interpret thy (typs, []) args (Free (x, T --> HOLogic.boolT))
webertj@14807
  1945
				in
skalberg@15531
  1946
					SOME (intr, (typs, (t, intr)::terms), args')
webertj@15334
  1947
				end
webertj@15767
  1948
			| Var ((x, i), Type ("set", [T])) =>
webertj@15334
  1949
				let
webertj@22092
  1950
					val (intr, _, args') =
webertj@22092
  1951
						interpret thy (typs, []) args (Var ((x,i), T --> HOLogic.boolT))
webertj@14807
  1952
				in
skalberg@15531
  1953
					SOME (intr, (typs, (t, intr)::terms), args')
webertj@15334
  1954
				end
webertj@14807
  1955
			| Const (s, Type ("set", [T])) =>
webertj@15334
  1956
				let
webertj@22092
  1957
					val (intr, _, args') =
webertj@22092
  1958
						interpret thy (typs, []) args (Const (s, T --> HOLogic.boolT))
webertj@14807
  1959
				in
skalberg@15531
  1960
					SOME (intr, (typs, (t, intr)::terms), args')
webertj@15334
  1961
				end
webertj@14807
  1962
			(* 'Collect' == identity *)
webertj@14807
  1963
			| Const ("Collect", _) $ t1 =>
skalberg@15531
  1964
				SOME (interpret thy model args t1)
webertj@14807
  1965
			| Const ("Collect", _) =>
skalberg@15531
  1966
				SOME (interpret thy model args (eta_expand t 1))
webertj@14807
  1967
			(* 'op :' == application *)
webertj@14807
  1968
			| Const ("op :", _) $ t1 $ t2 =>
skalberg@15531
  1969
				SOME (interpret thy model args (t2 $ t1))
webertj@14807
  1970
			| Const ("op :", _) $ t1 =>
skalberg@15531
  1971
				SOME (interpret thy model args (eta_expand t 1))
webertj@14807
  1972
			| Const ("op :", _) =>
skalberg@15531
  1973
				SOME (interpret thy model args (eta_expand t 2))
skalberg@15531
  1974
			| _ => NONE)
webertj@14807
  1975
	end;
webertj@14807
  1976
webertj@22092
  1977
	(* theory -> model -> arguments -> Term.term ->
webertj@22092
  1978
		(interpretation * model * arguments) option *)
webertj@14807
  1979
webertj@22092
  1980
	(* interprets variables and constants whose type is an IDT; *)
webertj@22092
  1981
	(* constructors of IDTs however are properly interpreted by *)
webertj@22092
  1982
	(* 'IDT_constructor_interpreter'                            *)
webertj@15547
  1983
webertj@14807
  1984
	fun IDT_interpreter thy model args t =
webertj@14807
  1985
	let
webertj@14807
  1986
		val (typs, terms) = model
webertj@14807
  1987
		(* Term.typ -> (interpretation * model * arguments) option *)
webertj@15547
  1988
		fun interpret_term (Type (s, Ts)) =
haftmann@19346
  1989
			(case DatatypePackage.get_datatype thy s of
skalberg@15531
  1990
			  SOME info =>  (* inductive datatype *)
webertj@14807
  1991
				let
webertj@14807
  1992
					(* int option -- only recursive IDTs have an associated depth *)
haftmann@17314
  1993
					val depth = AList.lookup (op =) typs (Type (s, Ts))
webertj@14807
  1994
				in
webertj@22092
  1995
					(* termination condition to avoid infinite recursion *)
webertj@22092
  1996
					if depth = (SOME 0) then
webertj@14807
  1997
						(* return a leaf of size 0 *)
skalberg@15531
  1998
						SOME (Leaf [], model, args)
webertj@14807
  1999
					else
webertj@14807
  2000
						let
webertj@14807
  2001
							val index               = #index info
webertj@14807
  2002
							val descr               = #descr info
webertj@22092
  2003
							val (_, dtyps, constrs) = lookup descr index
webertj@14807
  2004
							val typ_assoc           = dtyps ~~ Ts
webertj@14807
  2005
							(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
webertj@14807
  2006
							val _ = (if Library.exists (fn d =>
webertj@14807
  2007
									case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
webertj@14807
  2008
								then
webertj@22092
  2009
									raise REFUTE ("IDT_interpreter",
webertj@22092
  2010
										"datatype argument (for type "
webertj@22092
  2011
										^ Sign.string_of_typ thy (Type (s, Ts))
webertj@22092
  2012
										^ ") is not a variable")
webertj@14807
  2013
								else
webertj@14807
  2014
									())
webertj@22092
  2015
							(* if the model specifies a depth for the current type, *)
webertj@22092
  2016
							(* decrement it to avoid infinite recursion             *)
haftmann@17314
  2017
							val typs'    = case depth of NONE => typs | SOME n =>
haftmann@17314
  2018
								AList.update (op =) (Type (s, Ts), n-1) typs
webertj@14807
  2019
							(* recursively compute the size of the datatype *)
webertj@15335
  2020
							val size     = size_of_dtyp thy typs' descr typ_assoc constrs
webertj@14807
  2021
							val next_idx = #next_idx args
webertj@15547
  2022
							val next     = next_idx+size
webertj@22092
  2023
							(* check if 'maxvars' is large enough *)
webertj@22092
  2024
							val _        = (if next-1 > #maxvars args andalso
webertj@22092
  2025
								#maxvars args > 0 then raise MAXVARS_EXCEEDED else ())
webertj@14807
  2026
							(* prop_formula list *)
webertj@15547
  2027
							val fms      = map BoolVar (next_idx upto (next_idx+size-1))
webertj@14807
  2028
							(* interpretation *)
webertj@14807
  2029
							val intr     = Leaf fms
webertj@14807
  2030
							(* prop_formula list -> prop_formula *)
webertj@14807
  2031
							fun one_of_two_false []      = True
webertj@22092
  2032
							  | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
webertj@22092
  2033
								SOr (SNot x, SNot x')) xs), one_of_two_false xs)
webertj@14807
  2034
							(* prop_formula *)
webertj@15547
  2035
							val wf       = one_of_two_false fms
webertj@14807
  2036
						in
webertj@22092
  2037
							(* extend the model, increase 'next_idx', add well-formedness *)
webertj@22092
  2038
							(* condition                                                  *)
webertj@22092
  2039
							SOME (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args,
webertj@22092
  2040
								def_eq = #def_eq args, next_idx = next, bounds = #bounds args,
webertj@22092
  2041
								wellformed = SAnd (#wellformed args, wf)})
webertj@14807
  2042
						end
webertj@14807
  2043
				end
skalberg@15531
  2044
			| NONE =>  (* not an inductive datatype *)
skalberg@15531
  2045
				NONE)
webertj@15547
  2046
		  | interpret_term _ =  (* a (free or schematic) type variable *)
skalberg@15531
  2047
			NONE
webertj@14807
  2048
	in
haftmann@17314
  2049
		case AList.lookup (op =) terms t of
skalberg@15531
  2050
		  SOME intr =>
webertj@14807
  2051
			(* return an existing interpretation *)
skalberg@15531
  2052
			SOME (intr, model, args)
skalberg@15531
  2053
		| NONE =>
webertj@14807
  2054
			(case t of
webertj@15547
  2055
			  Free (_, T)  => interpret_term T
webertj@15547
  2056
			| Var (_, T)   => interpret_term T
webertj@15547
  2057
			| Const (_, T) => interpret_term T
webertj@15547
  2058
			| _            => NONE)
webertj@15547
  2059
	end;
webertj@15547
  2060
webertj@22092
  2061
	(* theory -> model -> arguments -> Term.term ->
webertj@22092
  2062
		(interpretation * model * arguments) option *)
webertj@15547
  2063
webertj@15547
  2064
	fun IDT_constructor_interpreter thy model args t =
webertj@15547
  2065
	let
webertj@15547
  2066
		val (typs, terms) = model
webertj@15547
  2067
	in
haftmann@17314
  2068
		case AList.lookup (op =) terms t of
webertj@15547
  2069
		  SOME intr =>
webertj@15547
  2070
			(* return an existing interpretation *)
webertj@15547
  2071
			SOME (intr, model, args)
webertj@15547
  2072
		| NONE =>
webertj@15547
  2073
			(case t of
webertj@15547
  2074
			  Const (s, T) =>
webertj@15547
  2075
				(case body_type T of
webertj@15547
  2076
				  Type (s', Ts') =>
haftmann@19346
  2077
					(case DatatypePackage.get_datatype thy s' of
webertj@15547
  2078
					  SOME info =>  (* body type is an inductive datatype *)
webertj@15547
  2079
						let
webertj@15547
  2080
							val index               = #index info
webertj@15547
  2081
							val descr               = #descr info
webertj@22092
  2082
							val (_, dtyps, constrs) = lookup descr index
webertj@15547
  2083
							val typ_assoc           = dtyps ~~ Ts'
webertj@15547
  2084
							(* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
webertj@15547
  2085
							val _ = (if Library.exists (fn d =>
webertj@15547
  2086
									case d of DatatypeAux.DtTFree _ => false | _ => true) dtyps
webertj@15547
  2087
								then
webertj@22092
  2088
									raise REFUTE ("IDT_constructor_interpreter",
webertj@22092
  2089
										"datatype argument (for type "
webertj@22092
  2090
										^ Sign.string_of_typ thy (Type (s', Ts'))
webertj@22092
  2091
										^ ") is not a variable")
webertj@15547
  2092
								else
webertj@15547
  2093
									())
webertj@22092
  2094
							(* split the constructors into those occuring before/after *)
webertj@22092
  2095
							(* 'Const (s, T)'                                          *)
webertj@15547
  2096
							val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
wenzelm@16935
  2097
								not (cname = s andalso Sign.typ_instance thy (T,
webertj@22092
  2098
									map (typ_of_dtyp descr typ_assoc) ctypes
webertj@22092
  2099
										---> Type (s', Ts')))) constrs
webertj@15547
  2100
						in
webertj@15547
  2101
							case constrs2 of
webertj@15547
  2102
							  [] =>
webertj@15547
  2103
								(* 'Const (s, T)' is not a constructor of this datatype *)
webertj@15547
  2104
								NONE
webertj@15547
  2105
							| (_, ctypes)::cs =>
webertj@14807
  2106
								let
webertj@22092
  2107
									(* compute the total size of the datatype (with the *)
webertj@22092
  2108
									(* current depth)                                   *)
webertj@22092
  2109
									val (i, _, _) = interpret thy (typs, []) {maxvars=0,
webertj@22092
  2110
										def_eq=false, next_idx=1, bounds=[], wellformed=True}
webertj@22092
  2111
										(Free ("dummy", Type (s', Ts')))
webertj@15547
  2112
									val total     = size_of_type i
webertj@22092
  2113
									(* int option -- only /recursive/ IDTs have an associated *)
webertj@22092
  2114
									(*               depth                                    *)
haftmann@17314
  2115
									val depth = AList.lookup (op =) typs (Type (s', Ts'))
haftmann@17314
  2116
									val typs' = (case depth of NONE => typs | SOME n =>
haftmann@17314
  2117
										AList.update (op =) (Type (s', Ts'), n-1) typs)
webertj@22092
  2118
									(* returns an interpretation where everything is mapped to *)
webertj@22092
  2119
									(* "undefined"                                             *)
webertj@15547
  2120
									(* DatatypeAux.dtyp list -> interpretation *)
webertj@15547
  2121
									fun make_undef [] =
webertj@15547
  2122
										Leaf (replicate total False)
webertj@15547
  2123
									  | make_undef (d::ds) =
webertj@15547
  2124
										let
webertj@15547
  2125
											(* compute the current size of the type 'd' *)
webertj@15547
  2126
											val T           = typ_of_dtyp descr typ_assoc d
webertj@22092
  2127
											val (i, _, _)   = interpret thy (typs, []) {maxvars=0,
webertj@22092
  2128
												def_eq=false, next_idx=1, bounds=[], wellformed=True}
webertj@22092
  2129
												(Free ("dummy", T))
webertj@15547
  2130
											val size        = size_of_type i
webertj@15547
  2131
										in
webertj@15547
  2132
											Node (replicate size (make_undef ds))
webertj@15547
  2133
										end
webertj@15547
  2134
									(* returns the interpretation for a constructor at depth 1 *)
webertj@15547
  2135
									(* int * DatatypeAux.dtyp list -> int * interpretation *)
webertj@15547
  2136
									fun make_constr (offset, []) =
webertj@15547
  2137
										if offset<total then
webertj@22092
  2138
											(offset+1, Leaf ((replicate offset False) @ True ::
webertj@22092
  2139
												(replicate (total-offset-1) False)))
webertj@14807
  2140
										else
webertj@22092
  2141
											raise REFUTE ("IDT_constructor_interpreter",
webertj@22092
  2142
												"offset >= total")
webertj@15547
  2143
									  | make_constr (offset, d::ds) =
webertj@14807
  2144
										let
webertj@15547
  2145
											(* compute the current and the old size of the type 'd' *)
webertj@15547
  2146
											val T           = typ_of_dtyp descr typ_assoc d
webertj@22092
  2147
											val (i, _, _)   = interpret thy (typs, []) {maxvars=0,
webertj@22092
  2148
												def_eq=false, next_idx=1, bounds=[], wellformed=True}
webertj@22092
  2149
												(Free ("dummy", T))
webertj@15547
  2150
											val size        = size_of_type i
webertj@22092
  2151
											val (i', _, _)  = interpret thy (typs', []) {maxvars=0,
webertj@22092
  2152
												def_eq=false, next_idx=1, bounds=[], wellformed=True}
webertj@22092
  2153
												(Free ("dummy", T))
webertj@15547
  2154
											val size'       = size_of_type i'
webertj@15547
  2155
											(* sanity check *)
webertj@15547
  2156
											val _           = if size < size' then
webertj@22092
  2157
													raise REFUTE ("IDT_constructor_interpreter",
webertj@22092
  2158
														"current size is less than old size")
webertj@22092
  2159
												else ()
webertj@15547
  2160
											(* int * interpretation list *)
webertj@22092
  2161
											val (new_offset, intrs) = foldl_map make_constr
webertj@22092
  2162
												(offset, replicate size' ds)
webertj@15547
  2163
											(* interpretation list *)
webertj@22092
  2164
											val undefs = replicate (size - size') (make_undef ds)
webertj@15547
  2165
										in
webertj@22092
  2166
											(* elements that exist at the previous depth are      *)
webertj@22092
  2167
											(* mapped to a defined value, while new elements are  *)
webertj@22092
  2168
											(* mapped to "undefined" by the recursive constructor *)
webertj@15547
  2169
											(new_offset, Node (intrs @ undefs))
webertj@15547
  2170
										end
webertj@22092
  2171
									(* extends the interpretation for a constructor (both      *)
webertj@22092
  2172
									(* recursive and non-recursive) obtained at depth n (n>=1) *)
webertj@22092
  2173
									(* to depth n+1                                            *)
webertj@22092
  2174
									(* int * DatatypeAux.dtyp list * interpretation
webertj@22092
  2175
										-> int * interpretation *)
webertj@15547
  2176
									fun extend_constr (offset, [], Leaf xs) =
webertj@15547
  2177
										let
webertj@15547
  2178
											(* returns the k-th unit vector of length n *)
webertj@15547
  2179
											(* int * int -> interpretation *)
webertj@15611
  2180
											fun unit_vector (k, n) =
webertj@22092
  2181
												Leaf ((replicate (k-1) False) @ True ::
webertj@22092
  2182
													(replicate (n-k) False))
webertj@15547
  2183
											(* int *)
webertj@15547
  2184
											val k = find_index_eq True xs
webertj@14807
  2185
										in
webertj@15547
  2186
											if k=(~1) then
webertj@22092
  2187
												(* if the element was mapped to "undefined" before, *)
webertj@22092
  2188
												(* map it to the value given by 'offset' now (and   *)
webertj@22092
  2189
												(* extend the length of the leaf)                   *)
webertj@15547
  2190
												(offset+1, unit_vector (offset+1, total))
webertj@15547
  2191
											else
webertj@22092
  2192
												(* if the element was already mapped to a defined  *)
webertj@22092
  2193
												(* value, map it to the same value again, just     *)
webertj@22092
  2194
												(* extend the length of the leaf, do not increment *)
webertj@22092
  2195
												(* the 'offset'                                    *)
webertj@15547
  2196
												(offset, unit_vector (k+1, total))
webertj@15547
  2197
										end
webertj@15547
  2198
									  | extend_constr (_, [], Node _) =
webertj@22092
  2199
										raise REFUTE ("IDT_constructor_interpreter",
webertj@22092
  2200
											"interpretation for constructor (with no arguments left)"
webertj@22092
  2201
											^ " is a node")
webertj@15547
  2202
									  | extend_constr (offset, d::ds, Node xs) =
webertj@15547
  2203
										let
webertj@15547
  2204
											(* compute the size of the type 'd' *)
webertj@15547
  2205
											val T          = typ_of_dtyp descr typ_assoc d
webertj@22092
  2206
											val (i, _, _)  = interpret thy (typs, []) {maxvars=0,
webertj@22092
  2207
												def_eq=false, next_idx=1, bounds=[], wellformed=True}
webertj@22092
  2208
												(Free ("dummy", T))
webertj@15547
  2209
											val size       = size_of_type i
webertj@15547
  2210
											(* sanity check *)
webertj@15547
  2211
											val _          = if size < length xs then
webertj@22092
  2212
													raise REFUTE ("IDT_constructor_interpreter",
webertj@22092
  2213
														"new size of type is less than old size")
webertj@22092
  2214
												else ()
webertj@15547
  2215
											(* extend the existing interpretations *)
webertj@15547
  2216
											(* int * interpretation list *)
webertj@22092
  2217
											val (new_offset, intrs) = foldl_map (fn (off, i) =>
webertj@22092
  2218
												extend_constr (off, ds, i)) (offset, xs)
webertj@22092
  2219
											(* new elements of the type 'd' are mapped to *)
webertj@22092
  2220
											(* "undefined"                                *)
webertj@15547
  2221
											val undefs = replicate (size - length xs) (make_undef ds)
webertj@15547
  2222
										in
webertj@15547
  2223
											(new_offset, Node (intrs @ undefs))
webertj@15547
  2224
										end
webertj@15547
  2225
									  | extend_constr (_, d::ds, Leaf _) =
webertj@22092
  2226
										raise REFUTE ("IDT_constructor_interpreter",
webertj@22092
  2227
											"interpretation for constructor (with arguments left)"
webertj@22092
  2228
											^ " is a leaf")
webertj@22092
  2229
									(* returns 'true' iff the constructor has a recursive *)
webertj@22092
  2230
									(* argument                                           *)
webertj@15547
  2231
									(* DatatypeAux.dtyp list -> bool *)
webertj@15547
  2232
									fun is_rec_constr ds =
webertj@15547
  2233
										Library.exists DatatypeAux.is_rec_type ds
webertj@22092
  2234
									(* constructors before 'Const (s, T)' generate elements of *)
webertj@22092
  2235
									(* the datatype                                            *)
webertj@15611
  2236
									val offset = size_of_dtyp thy typs' descr typ_assoc constrs1
webertj@15547
  2237
								in
webertj@15547
  2238
									case depth of
webertj@15547
  2239
									  NONE =>  (* equivalent to a depth of 1 *)
webertj@15547
  2240
										SOME (snd (make_constr (offset, ctypes)), model, args)
webertj@15547
  2241
									| SOME 0 =>
webertj@15547
  2242
										raise REFUTE ("IDT_constructor_interpreter", "depth is 0")
webertj@15547
  2243
									| SOME 1 =>
webertj@15547
  2244
										SOME (snd (make_constr (offset, ctypes)), model, args)
webertj@15547
  2245
									| SOME n =>  (* n > 1 *)
webertj@15547
  2246
										let
webertj@15547
  2247
											(* interpret the constructor at depth-1 *)
webertj@22092
  2248
											val (iC, _, _) = interpret thy (typs', []) {maxvars=0,
webertj@22092
  2249
												def_eq=false, next_idx=1, bounds=[], wellformed=True}
webertj@22092
  2250
												(Const (s, T))
webertj@22092
  2251
											(* elements generated by the constructor at depth-1 *)
webertj@22092
  2252
											(* must be added to 'offset'                        *)
webertj@15547
  2253
											(* interpretation -> int *)
webertj@15547
  2254
											fun number_of_defined_elements (Leaf xs) =
webertj@15547
  2255
												if find_index_eq True xs = (~1) then 0 else 1
webertj@15547
  2256
											  | number_of_defined_elements (Node xs) =
webertj@15547
  2257
												sum (map number_of_defined_elements xs)
webertj@15547
  2258
											(* int *)
webertj@15547
  2259
											val offset' = offset + number_of_defined_elements iC
webertj@15547
  2260
										in
webertj@22092
  2261
											SOME (snd (extend_constr (offset', ctypes, iC)), model,
webertj@22092
  2262
												args)
webertj@14807
  2263
										end
webertj@14807
  2264
								end
webertj@15547
  2265
						end
webertj@15547
  2266
					| NONE =>  (* body type is not an inductive datatype *)
webertj@15547
  2267
						NONE)
webertj@15547
  2268
				| _ =>  (* body type is a (free or schematic) type variable *)
webertj@15547
  2269
					NONE)
webertj@15547
  2270
			| _ =>  (* term is not a constant *)
webertj@15547
  2271
				NONE)
webertj@14807
  2272
	end;
webertj@14807
  2273
webertj@22092
  2274
	(* theory -> model -> arguments -> Term.term ->
webertj@22092
  2275
		(interpretation * model * arguments) option *)
webertj@14807
  2276
webertj@22092
  2277
	(* Difficult code ahead.  Make sure you understand the                *)
webertj@22092
  2278
	(* 'IDT_constructor_interpreter' and the order in which it enumerates *)
webertj@22092
  2279
	(* elements of an IDT before you try to understand this function.     *)
webertj@15547
  2280
webertj@15547
  2281
	fun IDT_recursion_interpreter thy model args t =
webertj@22092
  2282
		(* careful: here we descend arbitrarily deep into 't', possibly before *)
webertj@22092
  2283
		(* any other interpreter for atomic terms has had a chance to look at  *)
webertj@22092
  2284
		(* 't'                                                                 *)
webertj@22092
  2285
		case strip_comb t of
webertj@15547
  2286
		  (Const (s, T), params) =>
webertj@15547
  2287
			(* iterate over all datatypes in 'thy' *)
haftmann@21056
  2288
			Symtab.fold (fn (_, info) => fn result =>
webertj@15547
  2289
				case result of
webertj@15547
  2290
				  SOME _ =>
webertj@15547
  2291
					result  (* just keep 'result' *)
webertj@15547
  2292
				| NONE =>
haftmann@21056
  2293
					if member (op =) (#rec_names info) s then
webertj@22092
  2294
						(* we do have a recursion operator of the datatype given by *)
webertj@22092
  2295
						(* 'info', or of a mutually recursive datatype              *)
webertj@15547
  2296
						let