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