src/HOL/Tools/refute.ML
author haftmann
Wed May 05 18:25:34 2010 +0200 (2010-05-05)
changeset 36692 54b64d4ad524
parent 36555 8ff45c2076da
child 37117 59cee8807c29
permissions -rw-r--r--
farewell to old-style mem infixes -- type inference in situations with mem_int and mem_string should provide enough information to resolve the type of (op =)
     1 (*  Title:      HOL/Tools/refute.ML
     2     Author:     Tjark Weber, TU Muenchen
     3 
     4 Finite model generation for HOL formulas, using a SAT solver.
     5 *)
     6 
     7 (* ------------------------------------------------------------------------- *)
     8 (* Declares the 'REFUTE' signature as well as a structure 'Refute'.          *)
     9 (* Documentation is available in the Isabelle/Isar theory 'HOL/Refute.thy'.  *)
    10 (* ------------------------------------------------------------------------- *)
    11 
    12 signature REFUTE =
    13 sig
    14 
    15   exception REFUTE of string * string
    16 
    17 (* ------------------------------------------------------------------------- *)
    18 (* Model/interpretation related code (translation HOL -> propositional logic *)
    19 (* ------------------------------------------------------------------------- *)
    20 
    21   type params
    22   type interpretation
    23   type model
    24   type arguments
    25 
    26   exception MAXVARS_EXCEEDED
    27 
    28   val add_interpreter : string -> (theory -> model -> arguments -> term ->
    29     (interpretation * model * arguments) option) -> theory -> theory
    30   val add_printer     : string -> (theory -> model -> typ ->
    31     interpretation -> (int -> bool) -> term option) -> theory -> theory
    32 
    33   val interpret : theory -> model -> arguments -> term ->
    34     (interpretation * model * arguments)
    35 
    36   val print       : theory -> model -> typ -> interpretation -> (int -> bool) -> term
    37   val print_model : theory -> model -> (int -> bool) -> string
    38 
    39 (* ------------------------------------------------------------------------- *)
    40 (* Interface                                                                 *)
    41 (* ------------------------------------------------------------------------- *)
    42 
    43   val set_default_param  : (string * string) -> theory -> theory
    44   val get_default_param  : theory -> string -> string option
    45   val get_default_params : theory -> (string * string) list
    46   val actual_params      : theory -> (string * string) list -> params
    47 
    48   val find_model : theory -> params -> term list -> term -> bool -> unit
    49 
    50   (* tries to find a model for a formula: *)
    51   val satisfy_term :
    52     theory -> (string * string) list -> term list -> term -> unit
    53   (* tries to find a model that refutes a formula: *)
    54   val refute_term :
    55     theory -> (string * string) list -> term list -> term -> unit
    56   val refute_goal :
    57     Proof.context -> (string * string) list -> thm -> int -> unit
    58 
    59   val setup : theory -> theory
    60 
    61 (* ------------------------------------------------------------------------- *)
    62 (* Additional functions used by Nitpick (to be factored out)                 *)
    63 (* ------------------------------------------------------------------------- *)
    64 
    65   val close_form : term -> term
    66   val get_classdef : theory -> string -> (string * term) option
    67   val norm_rhs : term -> term
    68   val get_def : theory -> string * typ -> (string * term) option
    69   val get_typedef : theory -> typ -> (string * term) option
    70   val is_IDT_constructor : theory -> string * typ -> bool
    71   val is_IDT_recursor : theory -> string * typ -> bool
    72   val is_const_of_class: theory -> string * typ -> bool
    73   val string_of_typ : typ -> string
    74   val typ_of_dtyp : Datatype.descr -> (Datatype.dtyp * typ) list -> Datatype.dtyp -> typ
    75 end;  (* signature REFUTE *)
    76 
    77 structure Refute : REFUTE =
    78 struct
    79 
    80   open PropLogic;
    81 
    82   (* We use 'REFUTE' only for internal error conditions that should    *)
    83   (* never occur in the first place (i.e. errors caused by bugs in our *)
    84   (* code).  Otherwise (e.g. to indicate invalid input data) we use    *)
    85   (* 'error'.                                                          *)
    86   exception REFUTE of string * string;  (* ("in function", "cause") *)
    87 
    88   (* should be raised by an interpreter when more variables would be *)
    89   (* required than allowed by 'maxvars'                              *)
    90   exception MAXVARS_EXCEEDED;
    91 
    92 (* ------------------------------------------------------------------------- *)
    93 (* TREES                                                                     *)
    94 (* ------------------------------------------------------------------------- *)
    95 
    96 (* ------------------------------------------------------------------------- *)
    97 (* tree: implements an arbitrarily (but finitely) branching tree as a list   *)
    98 (*       of (lists of ...) elements                                          *)
    99 (* ------------------------------------------------------------------------- *)
   100 
   101   datatype 'a tree =
   102       Leaf of 'a
   103     | Node of ('a tree) list;
   104 
   105   (* ('a -> 'b) -> 'a tree -> 'b tree *)
   106 
   107   fun tree_map f tr =
   108     case tr of
   109       Leaf x  => Leaf (f x)
   110     | Node xs => Node (map (tree_map f) xs);
   111 
   112   (* ('a * 'b -> 'a) -> 'a * ('b tree) -> 'a *)
   113 
   114   fun tree_foldl f =
   115   let
   116     fun itl (e, Leaf x)  = f(e,x)
   117       | itl (e, Node xs) = Library.foldl (tree_foldl f) (e,xs)
   118   in
   119     itl
   120   end;
   121 
   122   (* 'a tree * 'b tree -> ('a * 'b) tree *)
   123 
   124   fun tree_pair (t1, t2) =
   125     case t1 of
   126       Leaf x =>
   127       (case t2 of
   128           Leaf y => Leaf (x,y)
   129         | Node _ => raise REFUTE ("tree_pair",
   130             "trees are of different height (second tree is higher)"))
   131     | Node xs =>
   132       (case t2 of
   133           (* '~~' will raise an exception if the number of branches in   *)
   134           (* both trees is different at the current node                 *)
   135           Node ys => Node (map tree_pair (xs ~~ ys))
   136         | Leaf _  => raise REFUTE ("tree_pair",
   137             "trees are of different height (first tree is higher)"));
   138 
   139 (* ------------------------------------------------------------------------- *)
   140 (* params: parameters that control the translation into a propositional      *)
   141 (*         formula/model generation                                          *)
   142 (*                                                                           *)
   143 (* The following parameters are supported (and required (!), except for      *)
   144 (* "sizes" and "expect"):                                                    *)
   145 (*                                                                           *)
   146 (* Name          Type    Description                                         *)
   147 (*                                                                           *)
   148 (* "sizes"       (string * int) list                                         *)
   149 (*                       Size of ground types (e.g. 'a=2), or depth of IDTs. *)
   150 (* "minsize"     int     If >0, minimal size of each ground type/IDT depth.  *)
   151 (* "maxsize"     int     If >0, maximal size of each ground type/IDT depth.  *)
   152 (* "maxvars"     int     If >0, use at most 'maxvars' Boolean variables      *)
   153 (*                       when transforming the term into a propositional     *)
   154 (*                       formula.                                            *)
   155 (* "maxtime"     int     If >0, terminate after at most 'maxtime' seconds.   *)
   156 (* "satsolver"   string  SAT solver to be used.                              *)
   157 (* "no_assms"    bool    If "true", assumptions in structured proofs are     *)
   158 (*                       not considered.                                     *)
   159 (* "expect"      string  Expected result ("genuine", "potential", "none", or *)
   160 (*                       "unknown").                                         *)
   161 (* ------------------------------------------------------------------------- *)
   162 
   163   type params =
   164     {
   165       sizes    : (string * int) list,
   166       minsize  : int,
   167       maxsize  : int,
   168       maxvars  : int,
   169       maxtime  : int,
   170       satsolver: string,
   171       no_assms : bool,
   172       expect   : string
   173     };
   174 
   175 (* ------------------------------------------------------------------------- *)
   176 (* interpretation: a term's interpretation is given by a variable of type    *)
   177 (*                 'interpretation'                                          *)
   178 (* ------------------------------------------------------------------------- *)
   179 
   180   type interpretation =
   181     prop_formula list tree;
   182 
   183 (* ------------------------------------------------------------------------- *)
   184 (* model: a model specifies the size of types and the interpretation of      *)
   185 (*        terms                                                              *)
   186 (* ------------------------------------------------------------------------- *)
   187 
   188   type model =
   189     (typ * int) list * (term * interpretation) list;
   190 
   191 (* ------------------------------------------------------------------------- *)
   192 (* arguments: additional arguments required during interpretation of terms   *)
   193 (* ------------------------------------------------------------------------- *)
   194 
   195   type arguments =
   196     {
   197       (* just passed unchanged from 'params': *)
   198       maxvars   : int,
   199       (* whether to use 'make_equality' or 'make_def_equality': *)
   200       def_eq    : bool,
   201       (* the following may change during the translation: *)
   202       next_idx  : int,
   203       bounds    : interpretation list,
   204       wellformed: prop_formula
   205     };
   206 
   207 
   208   structure RefuteData = Theory_Data
   209   (
   210     type T =
   211       {interpreters: (string * (theory -> model -> arguments -> term ->
   212         (interpretation * model * arguments) option)) list,
   213        printers: (string * (theory -> model -> typ -> interpretation ->
   214         (int -> bool) -> term option)) list,
   215        parameters: string Symtab.table};
   216     val empty = {interpreters = [], printers = [], parameters = Symtab.empty};
   217     val extend = I;
   218     fun merge
   219       ({interpreters = in1, printers = pr1, parameters = pa1},
   220        {interpreters = in2, printers = pr2, parameters = pa2}) : T =
   221       {interpreters = AList.merge (op =) (K true) (in1, in2),
   222        printers = AList.merge (op =) (K true) (pr1, pr2),
   223        parameters = Symtab.merge (op=) (pa1, pa2)};
   224   );
   225 
   226 
   227 (* ------------------------------------------------------------------------- *)
   228 (* interpret: interprets the term 't' using a suitable interpreter; returns  *)
   229 (*            the interpretation and a (possibly extended) model that keeps  *)
   230 (*            track of the interpretation of subterms                        *)
   231 (* ------------------------------------------------------------------------- *)
   232 
   233   (* theory -> model -> arguments -> Term.term ->
   234     (interpretation * model * arguments) *)
   235 
   236   fun interpret thy model args t =
   237     case get_first (fn (_, f) => f thy model args t)
   238       (#interpreters (RefuteData.get thy)) of
   239       NONE   => raise REFUTE ("interpret",
   240         "no interpreter for term " ^ quote (Syntax.string_of_term_global thy t))
   241     | SOME x => x;
   242 
   243 (* ------------------------------------------------------------------------- *)
   244 (* print: converts the interpretation 'intr', which must denote a term of    *)
   245 (*        type 'T', into a term using a suitable printer                     *)
   246 (* ------------------------------------------------------------------------- *)
   247 
   248   (* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
   249     Term.term *)
   250 
   251   fun print thy model T intr assignment =
   252     case get_first (fn (_, f) => f thy model T intr assignment)
   253       (#printers (RefuteData.get thy)) of
   254       NONE   => raise REFUTE ("print",
   255         "no printer for type " ^ quote (Syntax.string_of_typ_global thy T))
   256     | SOME x => x;
   257 
   258 (* ------------------------------------------------------------------------- *)
   259 (* print_model: turns the model into a string, using a fixed interpretation  *)
   260 (*              (given by an assignment for Boolean variables) and suitable  *)
   261 (*              printers                                                     *)
   262 (* ------------------------------------------------------------------------- *)
   263 
   264   (* theory -> model -> (int -> bool) -> string *)
   265 
   266   fun print_model thy model assignment =
   267   let
   268     val (typs, terms) = model
   269     val typs_msg =
   270       if null typs then
   271         "empty universe (no type variables in term)\n"
   272       else
   273         "Size of types: " ^ commas (map (fn (T, i) =>
   274           Syntax.string_of_typ_global thy T ^ ": " ^ string_of_int i) typs) ^ "\n"
   275     val show_consts_msg =
   276       if not (!show_consts) andalso Library.exists (is_Const o fst) terms then
   277         "set \"show_consts\" to show the interpretation of constants\n"
   278       else
   279         ""
   280     val terms_msg =
   281       if null terms then
   282         "empty interpretation (no free variables in term)\n"
   283       else
   284         cat_lines (map_filter (fn (t, intr) =>
   285           (* print constants only if 'show_consts' is true *)
   286           if (!show_consts) orelse not (is_Const t) then
   287             SOME (Syntax.string_of_term_global thy t ^ ": " ^
   288               Syntax.string_of_term_global thy
   289                 (print thy model (Term.type_of t) intr assignment))
   290           else
   291             NONE) terms) ^ "\n"
   292   in
   293     typs_msg ^ show_consts_msg ^ terms_msg
   294   end;
   295 
   296 
   297 (* ------------------------------------------------------------------------- *)
   298 (* PARAMETER MANAGEMENT                                                      *)
   299 (* ------------------------------------------------------------------------- *)
   300 
   301   (* string -> (theory -> model -> arguments -> Term.term ->
   302     (interpretation * model * arguments) option) -> theory -> theory *)
   303 
   304   fun add_interpreter name f thy =
   305   let
   306     val {interpreters, printers, parameters} = RefuteData.get thy
   307   in
   308     case AList.lookup (op =) interpreters name of
   309       NONE   => RefuteData.put {interpreters = (name, f) :: interpreters,
   310       printers = printers, parameters = parameters} thy
   311     | SOME _ => error ("Interpreter " ^ name ^ " already declared")
   312   end;
   313 
   314   (* string -> (theory -> model -> Term.typ -> interpretation ->
   315     (int -> bool) -> Term.term option) -> theory -> theory *)
   316 
   317   fun add_printer name f thy =
   318   let
   319     val {interpreters, printers, parameters} = RefuteData.get thy
   320   in
   321     case AList.lookup (op =) printers name of
   322       NONE   => RefuteData.put {interpreters = interpreters,
   323       printers = (name, f) :: printers, parameters = parameters} thy
   324     | SOME _ => error ("Printer " ^ name ^ " already declared")
   325   end;
   326 
   327 (* ------------------------------------------------------------------------- *)
   328 (* set_default_param: stores the '(name, value)' pair in RefuteData's        *)
   329 (*                    parameter table                                        *)
   330 (* ------------------------------------------------------------------------- *)
   331 
   332   (* (string * string) -> theory -> theory *)
   333 
   334   fun set_default_param (name, value) = RefuteData.map 
   335     (fn {interpreters, printers, parameters} =>
   336       {interpreters = interpreters, printers = printers,
   337         parameters = Symtab.update (name, value) parameters});
   338 
   339 (* ------------------------------------------------------------------------- *)
   340 (* get_default_param: retrieves the value associated with 'name' from        *)
   341 (*                    RefuteData's parameter table                           *)
   342 (* ------------------------------------------------------------------------- *)
   343 
   344   (* theory -> string -> string option *)
   345 
   346   val get_default_param = Symtab.lookup o #parameters o RefuteData.get;
   347 
   348 (* ------------------------------------------------------------------------- *)
   349 (* get_default_params: returns a list of all '(name, value)' pairs that are  *)
   350 (*                     stored in RefuteData's parameter table                *)
   351 (* ------------------------------------------------------------------------- *)
   352 
   353   (* theory -> (string * string) list *)
   354 
   355   val get_default_params = Symtab.dest o #parameters o RefuteData.get;
   356 
   357 (* ------------------------------------------------------------------------- *)
   358 (* actual_params: takes a (possibly empty) list 'params' of parameters that  *)
   359 (*      override the default parameters currently specified in 'thy', and    *)
   360 (*      returns a record that can be passed to 'find_model'.                 *)
   361 (* ------------------------------------------------------------------------- *)
   362 
   363   (* theory -> (string * string) list -> params *)
   364 
   365   fun actual_params thy override =
   366   let
   367     (* (string * string) list * string -> bool *)
   368     fun read_bool (parms, name) =
   369       case AList.lookup (op =) parms name of
   370         SOME "true" => true
   371       | SOME "false" => false
   372       | SOME s => error ("parameter " ^ quote name ^
   373         " (value is " ^ quote s ^ ") must be \"true\" or \"false\"")
   374       | NONE   => error ("parameter " ^ quote name ^
   375           " must be assigned a value")
   376     (* (string * string) list * string -> int *)
   377     fun read_int (parms, name) =
   378       case AList.lookup (op =) parms name of
   379         SOME s => (case Int.fromString s of
   380           SOME i => i
   381         | NONE   => error ("parameter " ^ quote name ^
   382           " (value is " ^ quote s ^ ") must be an integer value"))
   383       | NONE   => error ("parameter " ^ quote name ^
   384           " must be assigned a value")
   385     (* (string * string) list * string -> string *)
   386     fun read_string (parms, name) =
   387       case AList.lookup (op =) parms name of
   388         SOME s => s
   389       | NONE   => error ("parameter " ^ quote name ^
   390         " must be assigned a value")
   391     (* 'override' first, defaults last: *)
   392     (* (string * string) list *)
   393     val allparams = override @ (get_default_params thy)
   394     (* int *)
   395     val minsize   = read_int (allparams, "minsize")
   396     val maxsize   = read_int (allparams, "maxsize")
   397     val maxvars   = read_int (allparams, "maxvars")
   398     val maxtime   = read_int (allparams, "maxtime")
   399     (* string *)
   400     val satsolver = read_string (allparams, "satsolver")
   401     val no_assms = read_bool (allparams, "no_assms")
   402     val expect = the_default "" (AList.lookup (op =) allparams "expect")
   403     (* all remaining parameters of the form "string=int" are collected in *)
   404     (* 'sizes'                                                            *)
   405     (* TODO: it is currently not possible to specify a size for a type    *)
   406     (*       whose name is one of the other parameters (e.g. 'maxvars')   *)
   407     (* (string * int) list *)
   408     val sizes     = map_filter
   409       (fn (name, value) => Option.map (pair name) (Int.fromString value))
   410       (filter (fn (name, _) => name<>"minsize" andalso name<>"maxsize"
   411         andalso name<>"maxvars" andalso name<>"maxtime"
   412         andalso name<>"satsolver" andalso name<>"no_assms") allparams)
   413   in
   414     {sizes=sizes, minsize=minsize, maxsize=maxsize, maxvars=maxvars,
   415       maxtime=maxtime, satsolver=satsolver, no_assms=no_assms, expect=expect}
   416   end;
   417 
   418 
   419 (* ------------------------------------------------------------------------- *)
   420 (* TRANSLATION HOL -> PROPOSITIONAL LOGIC, BOOLEAN ASSIGNMENT -> MODEL       *)
   421 (* ------------------------------------------------------------------------- *)
   422 
   423   fun typ_of_dtyp descr typ_assoc (Datatype_Aux.DtTFree a) =
   424     (* replace a 'DtTFree' variable by the associated type *)
   425     the (AList.lookup (op =) typ_assoc (Datatype_Aux.DtTFree a))
   426     | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtType (s, ds)) =
   427     Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   428     | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtRec i) =
   429     let
   430       val (s, ds, _) = the (AList.lookup (op =) descr i)
   431     in
   432       Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   433     end;
   434 
   435 (* ------------------------------------------------------------------------- *)
   436 (* close_form: universal closure over schematic variables in 't'             *)
   437 (* ------------------------------------------------------------------------- *)
   438 
   439   (* Term.term -> Term.term *)
   440 
   441   fun close_form t =
   442   let
   443     (* (Term.indexname * Term.typ) list *)
   444     val vars = sort_wrt (fst o fst) (map dest_Var (OldTerm.term_vars t))
   445   in
   446     fold (fn ((x, i), T) => fn t' =>
   447       Term.all T $ Abs (x, T, abstract_over (Var ((x, i), T), t'))) vars t
   448   end;
   449 
   450 val monomorphic_term = Sledgehammer_Util.monomorphic_term
   451 val specialize_type = Sledgehammer_Util.specialize_type
   452 
   453 (* ------------------------------------------------------------------------- *)
   454 (* is_const_of_class: returns 'true' iff 'Const (s, T)' is a constant that   *)
   455 (*                    denotes membership to an axiomatic type class          *)
   456 (* ------------------------------------------------------------------------- *)
   457 
   458   (* theory -> string * Term.typ -> bool *)
   459 
   460   fun is_const_of_class thy (s, T) =
   461   let
   462     val class_const_names = map Logic.const_of_class (Sign.all_classes thy)
   463   in
   464     (* I'm not quite sure if checking the name 's' is sufficient, *)
   465     (* or if we should also check the type 'T'.                   *)
   466     member (op =) class_const_names s
   467   end;
   468 
   469 (* ------------------------------------------------------------------------- *)
   470 (* is_IDT_constructor: returns 'true' iff 'Const (s, T)' is the constructor  *)
   471 (*                     of an inductive datatype in 'thy'                     *)
   472 (* ------------------------------------------------------------------------- *)
   473 
   474   (* theory -> string * Term.typ -> bool *)
   475 
   476   fun is_IDT_constructor thy (s, T) =
   477     (case body_type T of
   478       Type (s', _) =>
   479       (case Datatype.get_constrs thy s' of
   480         SOME constrs =>
   481         List.exists (fn (cname, cty) =>
   482           cname = s andalso Sign.typ_instance thy (T, cty)) constrs
   483       | NONE =>
   484         false)
   485     | _  =>
   486       false);
   487 
   488 (* ------------------------------------------------------------------------- *)
   489 (* is_IDT_recursor: returns 'true' iff 'Const (s, T)' is the recursion       *)
   490 (*                  operator of an inductive datatype in 'thy'               *)
   491 (* ------------------------------------------------------------------------- *)
   492 
   493   (* theory -> string * Term.typ -> bool *)
   494 
   495   fun is_IDT_recursor thy (s, T) =
   496   let
   497     val rec_names = Symtab.fold (append o #rec_names o snd)
   498       (Datatype.get_all thy) []
   499   in
   500     (* I'm not quite sure if checking the name 's' is sufficient, *)
   501     (* or if we should also check the type 'T'.                   *)
   502     member (op =) rec_names s
   503   end;
   504 
   505 (* ------------------------------------------------------------------------- *)
   506 (* norm_rhs: maps  f ?t1 ... ?tn == rhs  to  %t1...tn. rhs                   *)
   507 (* ------------------------------------------------------------------------- *)
   508 
   509   fun norm_rhs eqn =
   510   let
   511     fun lambda (v as Var ((x, _), T)) t = Abs (x, T, abstract_over (v, t))
   512       | lambda v t                      = raise TERM ("lambda", [v, t])
   513     val (lhs, rhs) = Logic.dest_equals eqn
   514     val (_, args)  = Term.strip_comb lhs
   515   in
   516     fold lambda (rev args) rhs
   517   end
   518 
   519 (* ------------------------------------------------------------------------- *)
   520 (* get_def: looks up the definition of a constant, as created by "constdefs" *)
   521 (* ------------------------------------------------------------------------- *)
   522 
   523   (* theory -> string * Term.typ -> (string * Term.term) option *)
   524 
   525   fun get_def thy (s, T) =
   526   let
   527     (* (string * Term.term) list -> (string * Term.term) option *)
   528     fun get_def_ax [] = NONE
   529       | get_def_ax ((axname, ax) :: axioms) =
   530       (let
   531         val (lhs, _) = Logic.dest_equals ax  (* equations only *)
   532         val c        = Term.head_of lhs
   533         val (s', T') = Term.dest_Const c
   534       in
   535         if s=s' then
   536           let
   537             val typeSubs = Sign.typ_match thy (T', T) Vartab.empty
   538             val ax'      = monomorphic_term typeSubs ax
   539             val rhs      = norm_rhs ax'
   540           in
   541             SOME (axname, rhs)
   542           end
   543         else
   544           get_def_ax axioms
   545       end handle ERROR _         => get_def_ax axioms
   546                | TERM _          => get_def_ax axioms
   547                | Type.TYPE_MATCH => get_def_ax axioms)
   548   in
   549     get_def_ax (Theory.all_axioms_of thy)
   550   end;
   551 
   552 (* ------------------------------------------------------------------------- *)
   553 (* get_typedef: looks up the definition of a type, as created by "typedef"   *)
   554 (* ------------------------------------------------------------------------- *)
   555 
   556   (* theory -> Term.typ -> (string * Term.term) option *)
   557 
   558   fun get_typedef thy T =
   559   let
   560     (* (string * Term.term) list -> (string * Term.term) option *)
   561     fun get_typedef_ax [] = NONE
   562       | get_typedef_ax ((axname, ax) :: axioms) =
   563       (let
   564         (* Term.term -> Term.typ option *)
   565         fun type_of_type_definition (Const (s', T')) =
   566           if s'= @{const_name type_definition} then
   567             SOME T'
   568           else
   569             NONE
   570           | type_of_type_definition (Free _)           = NONE
   571           | type_of_type_definition (Var _)            = NONE
   572           | type_of_type_definition (Bound _)          = NONE
   573           | type_of_type_definition (Abs (_, _, body)) =
   574           type_of_type_definition body
   575           | type_of_type_definition (t1 $ t2)          =
   576           (case type_of_type_definition t1 of
   577             SOME x => SOME x
   578           | NONE   => type_of_type_definition t2)
   579       in
   580         case type_of_type_definition ax of
   581           SOME T' =>
   582           let
   583             val T''      = (domain_type o domain_type) T'
   584             val typeSubs = Sign.typ_match thy (T'', T) Vartab.empty
   585           in
   586             SOME (axname, monomorphic_term typeSubs ax)
   587           end
   588         | NONE =>
   589           get_typedef_ax axioms
   590       end handle ERROR _         => get_typedef_ax axioms
   591                | MATCH           => get_typedef_ax axioms
   592                | Type.TYPE_MATCH => get_typedef_ax axioms)
   593   in
   594     get_typedef_ax (Theory.all_axioms_of thy)
   595   end;
   596 
   597 (* ------------------------------------------------------------------------- *)
   598 (* get_classdef: looks up the defining axiom for an axiomatic type class, as *)
   599 (*               created by the "axclass" command                            *)
   600 (* ------------------------------------------------------------------------- *)
   601 
   602   (* theory -> string -> (string * Term.term) option *)
   603 
   604   fun get_classdef thy class =
   605   let
   606     val axname = class ^ "_class_def"
   607   in
   608     Option.map (pair axname)
   609       (AList.lookup (op =) (Theory.all_axioms_of thy) axname)
   610   end;
   611 
   612 (* ------------------------------------------------------------------------- *)
   613 (* unfold_defs: unfolds all defined constants in a term 't', beta-eta        *)
   614 (*              normalizes the result term; certain constants are not        *)
   615 (*              unfolded (cf. 'collect_axioms' and the various interpreters  *)
   616 (*              below): if the interpretation respects a definition anyway,  *)
   617 (*              that definition does not need to be unfolded                 *)
   618 (* ------------------------------------------------------------------------- *)
   619 
   620   (* theory -> Term.term -> Term.term *)
   621 
   622   (* Note: we could intertwine unfolding of constants and beta-(eta-)       *)
   623   (*       normalization; this would save some unfolding for terms where    *)
   624   (*       constants are eliminated by beta-reduction (e.g. 'K c1 c2').  On *)
   625   (*       the other hand, this would cause additional work for terms where *)
   626   (*       constants are duplicated by beta-reduction (e.g. 'S c1 c2 c3').  *)
   627 
   628   fun unfold_defs thy t =
   629   let
   630     (* Term.term -> Term.term *)
   631     fun unfold_loop t =
   632       case t of
   633       (* Pure *)
   634         Const (@{const_name all}, _) => t
   635       | Const (@{const_name "=="}, _) => t
   636       | Const (@{const_name "==>"}, _) => t
   637       | Const (@{const_name TYPE}, _) => t  (* axiomatic type classes *)
   638       (* HOL *)
   639       | Const (@{const_name Trueprop}, _) => t
   640       | Const (@{const_name Not}, _) => t
   641       | (* redundant, since 'True' is also an IDT constructor *)
   642         Const (@{const_name True}, _) => t
   643       | (* redundant, since 'False' is also an IDT constructor *)
   644         Const (@{const_name False}, _) => t
   645       | Const (@{const_name undefined}, _) => t
   646       | Const (@{const_name The}, _) => t
   647       | Const (@{const_name Hilbert_Choice.Eps}, _) => t
   648       | Const (@{const_name All}, _) => t
   649       | Const (@{const_name Ex}, _) => t
   650       | Const (@{const_name "op ="}, _) => t
   651       | Const (@{const_name "op &"}, _) => t
   652       | Const (@{const_name "op |"}, _) => t
   653       | Const (@{const_name "op -->"}, _) => t
   654       (* sets *)
   655       | Const (@{const_name Collect}, _) => t
   656       | Const (@{const_name "op :"}, _) => t
   657       (* other optimizations *)
   658       | Const (@{const_name Finite_Set.card}, _) => t
   659       | Const (@{const_name Finite_Set.finite}, _) => t
   660       | Const (@{const_name Orderings.less}, Type ("fun", [Type ("nat", []),
   661         Type ("fun", [Type ("nat", []), Type ("bool", [])])])) => t
   662       | Const (@{const_name Groups.plus}, Type ("fun", [Type ("nat", []),
   663         Type ("fun", [Type ("nat", []), Type ("nat", [])])])) => t
   664       | Const (@{const_name Groups.minus}, Type ("fun", [Type ("nat", []),
   665         Type ("fun", [Type ("nat", []), Type ("nat", [])])])) => t
   666       | Const (@{const_name Groups.times}, Type ("fun", [Type ("nat", []),
   667         Type ("fun", [Type ("nat", []), Type ("nat", [])])])) => t
   668       | Const (@{const_name List.append}, _) => t
   669 (* UNSOUND
   670       | Const (@{const_name lfp}, _) => t
   671       | Const (@{const_name gfp}, _) => t
   672 *)
   673       | Const (@{const_name fst}, _) => t
   674       | Const (@{const_name snd}, _) => t
   675       (* simply-typed lambda calculus *)
   676       | Const (s, T) =>
   677         (if is_IDT_constructor thy (s, T)
   678           orelse is_IDT_recursor thy (s, T) then
   679           t  (* do not unfold IDT constructors/recursors *)
   680         (* unfold the constant if there is a defining equation *)
   681         else case get_def thy (s, T) of
   682           SOME (axname, rhs) =>
   683           (* Note: if the term to be unfolded (i.e. 'Const (s, T)')  *)
   684           (* occurs on the right-hand side of the equation, i.e. in  *)
   685           (* 'rhs', we must not use this equation to unfold, because *)
   686           (* that would loop.  Here would be the right place to      *)
   687           (* check this.  However, getting this really right seems   *)
   688           (* difficult because the user may state arbitrary axioms,  *)
   689           (* which could interact with overloading to create loops.  *)
   690           ((*tracing (" unfolding: " ^ axname);*)
   691            unfold_loop rhs)
   692         | NONE => t)
   693       | Free _           => t
   694       | Var _            => t
   695       | Bound _          => t
   696       | Abs (s, T, body) => Abs (s, T, unfold_loop body)
   697       | t1 $ t2          => (unfold_loop t1) $ (unfold_loop t2)
   698     val result = Envir.beta_eta_contract (unfold_loop t)
   699   in
   700     result
   701   end;
   702 
   703 (* ------------------------------------------------------------------------- *)
   704 (* collect_axioms: collects (monomorphic, universally quantified, unfolded   *)
   705 (*                 versions of) all HOL axioms that are relevant w.r.t 't'   *)
   706 (* ------------------------------------------------------------------------- *)
   707 
   708   (* Note: to make the collection of axioms more easily extensible, this    *)
   709   (*       function could be based on user-supplied "axiom collectors",     *)
   710   (*       similar to 'interpret'/interpreters or 'print'/printers          *)
   711 
   712   (* Note: currently we use "inverse" functions to the definitional         *)
   713   (*       mechanisms provided by Isabelle/HOL, e.g. for "axclass",         *)
   714   (*       "typedef", "constdefs".  A more general approach could consider  *)
   715   (*       *every* axiom of the theory and collect it if it has a constant/ *)
   716   (*       type/typeclass in common with the term 't'.                      *)
   717 
   718   (* theory -> Term.term -> Term.term list *)
   719 
   720   (* Which axioms are "relevant" for a particular term/type goes hand in    *)
   721   (* hand with the interpretation of that term/type by its interpreter (see *)
   722   (* way below): if the interpretation respects an axiom anyway, the axiom  *)
   723   (* does not need to be added as a constraint here.                        *)
   724 
   725   (* To avoid collecting the same axiom multiple times, we use an           *)
   726   (* accumulator 'axs' which contains all axioms collected so far.          *)
   727 
   728   fun collect_axioms thy t =
   729   let
   730     val _ = tracing "Adding axioms..."
   731     val axioms = Theory.all_axioms_of thy
   732     fun collect_this_axiom (axname, ax) axs =
   733       let
   734         val ax' = unfold_defs thy ax
   735       in
   736         if member (op aconv) axs ax' then axs
   737         else (tracing axname; collect_term_axioms ax' (ax' :: axs))
   738       end
   739     and collect_sort_axioms T axs =
   740       let
   741         val sort =
   742           (case T of
   743             TFree (_, sort) => sort
   744           | TVar (_, sort)  => sort
   745           | _ => raise REFUTE ("collect_axioms",
   746               "type " ^ Syntax.string_of_typ_global thy T ^ " is not a variable"))
   747         (* obtain axioms for all superclasses *)
   748         val superclasses = sort @ maps (Sign.super_classes thy) sort
   749         (* merely an optimization, because 'collect_this_axiom' disallows *)
   750         (* duplicate axioms anyway:                                       *)
   751         val superclasses = distinct (op =) superclasses
   752         val class_axioms = maps (fn class => map (fn ax =>
   753           ("<" ^ class ^ ">", Thm.prop_of ax))
   754           (#axioms (AxClass.get_info thy class) handle ERROR _ => []))
   755           superclasses
   756         (* replace the (at most one) schematic type variable in each axiom *)
   757         (* by the actual type 'T'                                          *)
   758         val monomorphic_class_axioms = map (fn (axname, ax) =>
   759           (case Term.add_tvars ax [] of
   760             [] => (axname, ax)
   761           | [(idx, S)] => (axname, monomorphic_term (Vartab.make [(idx, (S, T))]) ax)
   762           | _ =>
   763             raise REFUTE ("collect_axioms", "class axiom " ^ axname ^ " (" ^
   764               Syntax.string_of_term_global thy ax ^
   765               ") contains more than one type variable")))
   766           class_axioms
   767       in
   768         fold collect_this_axiom monomorphic_class_axioms axs
   769       end
   770     and collect_type_axioms T axs =
   771       case T of
   772       (* simple types *)
   773         Type ("prop", []) => axs
   774       | Type ("fun", [T1, T2]) => collect_type_axioms T2 (collect_type_axioms T1 axs)
   775       (* axiomatic type classes *)
   776       | Type ("itself", [T1]) => collect_type_axioms T1 axs
   777       | Type (s, Ts) =>
   778         (case Datatype.get_info thy s of
   779           SOME info =>  (* inductive datatype *)
   780             (* only collect relevant type axioms for the argument types *)
   781             fold collect_type_axioms Ts axs
   782         | NONE =>
   783           (case get_typedef thy T of
   784             SOME (axname, ax) =>
   785             collect_this_axiom (axname, ax) axs
   786           | NONE =>
   787             (* unspecified type, perhaps introduced with "typedecl" *)
   788             (* at least collect relevant type axioms for the argument types *)
   789             fold collect_type_axioms Ts axs))
   790       (* axiomatic type classes *)
   791       | TFree _ => collect_sort_axioms T axs
   792       (* axiomatic type classes *)
   793       | TVar _ => collect_sort_axioms T axs
   794     and collect_term_axioms t axs =
   795       case t of
   796       (* Pure *)
   797         Const (@{const_name all}, _) => axs
   798       | Const (@{const_name "=="}, _) => axs
   799       | Const (@{const_name "==>"}, _) => axs
   800       (* axiomatic type classes *)
   801       | Const (@{const_name TYPE}, T) => collect_type_axioms T axs
   802       (* HOL *)
   803       | Const (@{const_name Trueprop}, _) => axs
   804       | Const (@{const_name Not}, _) => axs
   805       (* redundant, since 'True' is also an IDT constructor *)
   806       | Const (@{const_name True}, _) => axs
   807       (* redundant, since 'False' is also an IDT constructor *)
   808       | Const (@{const_name False}, _) => axs
   809       | Const (@{const_name undefined}, T) => collect_type_axioms T axs
   810       | Const (@{const_name The}, T) =>
   811         let
   812           val ax = specialize_type thy (@{const_name The}, T)
   813             (the (AList.lookup (op =) axioms "HOL.the_eq_trivial"))
   814         in
   815           collect_this_axiom ("HOL.the_eq_trivial", ax) axs
   816         end
   817       | Const (@{const_name Hilbert_Choice.Eps}, T) =>
   818         let
   819           val ax = specialize_type thy (@{const_name Hilbert_Choice.Eps}, T)
   820             (the (AList.lookup (op =) axioms "Hilbert_Choice.someI"))
   821         in
   822           collect_this_axiom ("Hilbert_Choice.someI", ax) axs
   823         end
   824       | Const (@{const_name All}, T) => collect_type_axioms T axs
   825       | Const (@{const_name Ex}, T) => collect_type_axioms T axs
   826       | Const (@{const_name "op ="}, T) => collect_type_axioms T axs
   827       | Const (@{const_name "op &"}, _) => axs
   828       | Const (@{const_name "op |"}, _) => axs
   829       | Const (@{const_name "op -->"}, _) => axs
   830       (* sets *)
   831       | Const (@{const_name Collect}, T) => collect_type_axioms T axs
   832       | Const (@{const_name "op :"}, T) => collect_type_axioms T axs
   833       (* other optimizations *)
   834       | Const (@{const_name Finite_Set.card}, T) => collect_type_axioms T axs
   835       | Const (@{const_name Finite_Set.finite}, T) =>
   836         collect_type_axioms T axs
   837       | Const (@{const_name Orderings.less}, T as Type ("fun", [Type ("nat", []),
   838         Type ("fun", [Type ("nat", []), Type ("bool", [])])])) =>
   839           collect_type_axioms T axs
   840       | Const (@{const_name Groups.plus}, T as Type ("fun", [Type ("nat", []),
   841         Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
   842           collect_type_axioms T axs
   843       | Const (@{const_name Groups.minus}, T as Type ("fun", [Type ("nat", []),
   844         Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
   845           collect_type_axioms T axs
   846       | Const (@{const_name Groups.times}, T as Type ("fun", [Type ("nat", []),
   847         Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
   848           collect_type_axioms T axs
   849       | Const (@{const_name List.append}, T) => collect_type_axioms T axs
   850 (* UNSOUND
   851       | Const (@{const_name lfp}, T) => collect_type_axioms T axs
   852       | Const (@{const_name gfp}, T) => collect_type_axioms T axs
   853 *)
   854       | Const (@{const_name fst}, T) => collect_type_axioms T axs
   855       | Const (@{const_name snd}, T) => collect_type_axioms T axs
   856       (* simply-typed lambda calculus *)
   857       | Const (s, T) =>
   858           if is_const_of_class thy (s, T) then
   859             (* axiomatic type classes: add "OFCLASS(?'a::c, c_class)" *)
   860             (* and the class definition                               *)
   861             let
   862               val class = Logic.class_of_const s
   863               val of_class = Logic.mk_of_class (TVar (("'a", 0), [class]), class)
   864               val ax_in = SOME (specialize_type thy (s, T) of_class)
   865                 (* type match may fail due to sort constraints *)
   866                 handle Type.TYPE_MATCH => NONE
   867               val ax_1 = Option.map (fn ax => (Syntax.string_of_term_global thy ax, ax)) ax_in
   868               val ax_2 = Option.map (apsnd (specialize_type thy (s, T))) (get_classdef thy class)
   869             in
   870               collect_type_axioms T (fold collect_this_axiom (map_filter I [ax_1, ax_2]) axs)
   871             end
   872           else if is_IDT_constructor thy (s, T)
   873             orelse is_IDT_recursor thy (s, T) then
   874             (* only collect relevant type axioms *)
   875             collect_type_axioms T axs
   876           else
   877             (* other constants should have been unfolded, with some *)
   878             (* exceptions: e.g. Abs_xxx/Rep_xxx functions for       *)
   879             (* typedefs, or type-class related constants            *)
   880             (* only collect relevant type axioms *)
   881             collect_type_axioms T axs
   882       | Free (_, T) => collect_type_axioms T axs
   883       | Var (_, T) => collect_type_axioms T axs
   884       | Bound _ => axs
   885       | Abs (_, T, body) => collect_term_axioms body (collect_type_axioms T axs)
   886       | t1 $ t2 => collect_term_axioms t2 (collect_term_axioms t1 axs)
   887     val result = map close_form (collect_term_axioms t [])
   888     val _ = tracing " ...done."
   889   in
   890     result
   891   end;
   892 
   893 (* ------------------------------------------------------------------------- *)
   894 (* ground_types: collects all ground types in a term (including argument     *)
   895 (*               types of other types), suppressing duplicates.  Does not    *)
   896 (*               return function types, set types, non-recursive IDTs, or    *)
   897 (*               'propT'.  For IDTs, also the argument types of constructors *)
   898 (*               and all mutually recursive IDTs are considered.             *)
   899 (* ------------------------------------------------------------------------- *)
   900 
   901   fun ground_types thy t =
   902   let
   903     fun collect_types T acc =
   904       (case T of
   905         Type ("fun", [T1, T2]) => collect_types T1 (collect_types T2 acc)
   906       | Type ("prop", [])      => acc
   907       | Type (s, Ts)           =>
   908         (case Datatype.get_info thy s of
   909           SOME info =>  (* inductive datatype *)
   910           let
   911             val index        = #index info
   912             val descr        = #descr info
   913             val (_, typs, _) = the (AList.lookup (op =) descr index)
   914             val typ_assoc    = typs ~~ Ts
   915             (* sanity check: every element in 'dtyps' must be a *)
   916             (* 'DtTFree'                                        *)
   917             val _ = if Library.exists (fn d =>
   918               case d of Datatype_Aux.DtTFree _ => false | _ => true) typs then
   919               raise REFUTE ("ground_types", "datatype argument (for type "
   920                 ^ Syntax.string_of_typ_global thy T ^ ") is not a variable")
   921             else ()
   922             (* required for mutually recursive datatypes; those need to   *)
   923             (* be added even if they are an instance of an otherwise non- *)
   924             (* recursive datatype                                         *)
   925             fun collect_dtyp d acc =
   926             let
   927               val dT = typ_of_dtyp descr typ_assoc d
   928             in
   929               case d of
   930                 Datatype_Aux.DtTFree _ =>
   931                 collect_types dT acc
   932               | Datatype_Aux.DtType (_, ds) =>
   933                 collect_types dT (fold_rev collect_dtyp ds acc)
   934               | Datatype_Aux.DtRec i =>
   935                 if member (op =) acc dT then
   936                   acc  (* prevent infinite recursion *)
   937                 else
   938                   let
   939                     val (_, dtyps, dconstrs) = the (AList.lookup (op =) descr i)
   940                     (* if the current type is a recursive IDT (i.e. a depth *)
   941                     (* is required), add it to 'acc'                        *)
   942                     val acc_dT = if Library.exists (fn (_, ds) =>
   943                       Library.exists Datatype_Aux.is_rec_type ds) dconstrs then
   944                         insert (op =) dT acc
   945                       else acc
   946                     (* collect argument types *)
   947                     val acc_dtyps = fold_rev collect_dtyp dtyps acc_dT
   948                     (* collect constructor types *)
   949                     val acc_dconstrs = fold_rev collect_dtyp (maps snd dconstrs) acc_dtyps
   950                   in
   951                     acc_dconstrs
   952                   end
   953             end
   954           in
   955             (* argument types 'Ts' could be added here, but they are also *)
   956             (* added by 'collect_dtyp' automatically                      *)
   957             collect_dtyp (Datatype_Aux.DtRec index) acc
   958           end
   959         | NONE =>
   960           (* not an inductive datatype, e.g. defined via "typedef" or *)
   961           (* "typedecl"                                               *)
   962           insert (op =) T (fold collect_types Ts acc))
   963       | TFree _                => insert (op =) T acc
   964       | TVar _                 => insert (op =) T acc)
   965   in
   966     fold_types collect_types t []
   967   end;
   968 
   969 (* ------------------------------------------------------------------------- *)
   970 (* string_of_typ: (rather naive) conversion from types to strings, used to   *)
   971 (*                look up the size of a type in 'sizes'.  Parameterized      *)
   972 (*                types with different parameters (e.g. "'a list" vs. "bool  *)
   973 (*                list") are identified.                                     *)
   974 (* ------------------------------------------------------------------------- *)
   975 
   976   (* Term.typ -> string *)
   977 
   978   fun string_of_typ (Type (s, _))     = s
   979     | string_of_typ (TFree (s, _))    = s
   980     | string_of_typ (TVar ((s,_), _)) = s;
   981 
   982 (* ------------------------------------------------------------------------- *)
   983 (* first_universe: returns the "first" (i.e. smallest) universe by assigning *)
   984 (*                 'minsize' to every type for which no size is specified in *)
   985 (*                 'sizes'                                                   *)
   986 (* ------------------------------------------------------------------------- *)
   987 
   988   (* Term.typ list -> (string * int) list -> int -> (Term.typ * int) list *)
   989 
   990   fun first_universe xs sizes minsize =
   991   let
   992     fun size_of_typ T =
   993       case AList.lookup (op =) sizes (string_of_typ T) of
   994         SOME n => n
   995       | NONE => minsize
   996   in
   997     map (fn T => (T, size_of_typ T)) xs
   998   end;
   999 
  1000 (* ------------------------------------------------------------------------- *)
  1001 (* next_universe: enumerates all universes (i.e. assignments of sizes to     *)
  1002 (*                types), where the minimal size of a type is given by       *)
  1003 (*                'minsize', the maximal size is given by 'maxsize', and a   *)
  1004 (*                type may have a fixed size given in 'sizes'                *)
  1005 (* ------------------------------------------------------------------------- *)
  1006 
  1007   (* (Term.typ * int) list -> (string * int) list -> int -> int ->
  1008     (Term.typ * int) list option *)
  1009 
  1010   fun next_universe xs sizes minsize maxsize =
  1011   let
  1012     (* creates the "first" list of length 'len', where the sum of all list *)
  1013     (* elements is 'sum', and the length of the list is 'len'              *)
  1014     (* int -> int -> int -> int list option *)
  1015     fun make_first _ 0 sum =
  1016       if sum=0 then
  1017         SOME []
  1018       else
  1019         NONE
  1020       | make_first max len sum =
  1021       if sum<=max orelse max<0 then
  1022         Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
  1023       else
  1024         Option.map (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
  1025     (* enumerates all int lists with a fixed length, where 0<=x<='max' for *)
  1026     (* all list elements x (unless 'max'<0)                                *)
  1027     (* int -> int -> int -> int list -> int list option *)
  1028     fun next max len sum [] =
  1029       NONE
  1030       | next max len sum [x] =
  1031       (* we've reached the last list element, so there's no shift possible *)
  1032       make_first max (len+1) (sum+x+1)  (* increment 'sum' by 1 *)
  1033       | next max len sum (x1::x2::xs) =
  1034       if x1>0 andalso (x2<max orelse max<0) then
  1035         (* we can shift *)
  1036         SOME (the (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
  1037       else
  1038         (* continue search *)
  1039         next max (len+1) (sum+x1) (x2::xs)
  1040     (* only consider those types for which the size is not fixed *)
  1041     val mutables = filter_out (AList.defined (op =) sizes o string_of_typ o fst) xs
  1042     (* subtract 'minsize' from every size (will be added again at the end) *)
  1043     val diffs = map (fn (_, n) => n-minsize) mutables
  1044   in
  1045     case next (maxsize-minsize) 0 0 diffs of
  1046       SOME diffs' =>
  1047       (* merge with those types for which the size is fixed *)
  1048       SOME (fst (fold_map (fn (T, _) => fn ds =>
  1049         case AList.lookup (op =) sizes (string_of_typ T) of
  1050         (* return the fixed size *)
  1051           SOME n => ((T, n), ds)
  1052         (* consume the head of 'ds', add 'minsize' *)
  1053         | NONE   => ((T, minsize + hd ds), tl ds))
  1054         xs diffs'))
  1055     | NONE =>
  1056       NONE
  1057   end;
  1058 
  1059 (* ------------------------------------------------------------------------- *)
  1060 (* toTrue: converts the interpretation of a Boolean value to a propositional *)
  1061 (*         formula that is true iff the interpretation denotes "true"        *)
  1062 (* ------------------------------------------------------------------------- *)
  1063 
  1064   (* interpretation -> prop_formula *)
  1065 
  1066   fun toTrue (Leaf [fm, _]) =
  1067     fm
  1068     | toTrue _              =
  1069     raise REFUTE ("toTrue", "interpretation does not denote a Boolean value");
  1070 
  1071 (* ------------------------------------------------------------------------- *)
  1072 (* toFalse: converts the interpretation of a Boolean value to a              *)
  1073 (*          propositional formula that is true iff the interpretation        *)
  1074 (*          denotes "false"                                                  *)
  1075 (* ------------------------------------------------------------------------- *)
  1076 
  1077   (* interpretation -> prop_formula *)
  1078 
  1079   fun toFalse (Leaf [_, fm]) =
  1080     fm
  1081     | toFalse _              =
  1082     raise REFUTE ("toFalse", "interpretation does not denote a Boolean value");
  1083 
  1084 (* ------------------------------------------------------------------------- *)
  1085 (* find_model: repeatedly calls 'interpret' with appropriate parameters,     *)
  1086 (*             applies a SAT solver, and (in case a model is found) displays *)
  1087 (*             the model to the user by calling 'print_model'                *)
  1088 (* thy       : the current theory                                            *)
  1089 (* {...}     : parameters that control the translation/model generation      *)
  1090 (* assm_ts   : assumptions to be considered unless "no_assms" is specified   *)
  1091 (* t         : term to be translated into a propositional formula            *)
  1092 (* negate    : if true, find a model that makes 't' false (rather than true) *)
  1093 (* ------------------------------------------------------------------------- *)
  1094 
  1095   (* theory -> params -> Term.term -> bool -> unit *)
  1096 
  1097   fun find_model thy {sizes, minsize, maxsize, maxvars, maxtime, satsolver,
  1098     no_assms, expect} assm_ts t negate =
  1099   let
  1100     (* string -> unit *)
  1101     fun check_expect outcome_code =
  1102       if expect = "" orelse outcome_code = expect then ()
  1103       else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
  1104     (* unit -> unit *)
  1105     fun wrapper () =
  1106     let
  1107       val timer  = Timer.startRealTimer ()
  1108       val t = if no_assms then t
  1109               else if negate then Logic.list_implies (assm_ts, t)
  1110               else Logic.mk_conjunction_list (t :: assm_ts)
  1111       val u      = unfold_defs thy t
  1112       val _      = tracing ("Unfolded term: " ^ Syntax.string_of_term_global thy u)
  1113       val axioms = collect_axioms thy u
  1114       (* Term.typ list *)
  1115       val types = fold (union (op =) o ground_types thy) (u :: axioms) []
  1116       val _     = tracing ("Ground types: "
  1117         ^ (if null types then "none."
  1118            else commas (map (Syntax.string_of_typ_global thy) types)))
  1119       (* we can only consider fragments of recursive IDTs, so we issue a  *)
  1120       (* warning if the formula contains a recursive IDT                  *)
  1121       (* TODO: no warning needed for /positive/ occurrences of IDTs       *)
  1122       val maybe_spurious = Library.exists (fn
  1123           Type (s, _) =>
  1124           (case Datatype.get_info thy s of
  1125             SOME info =>  (* inductive datatype *)
  1126             let
  1127               val index           = #index info
  1128               val descr           = #descr info
  1129               val (_, _, constrs) = the (AList.lookup (op =) descr index)
  1130             in
  1131               (* recursive datatype? *)
  1132               Library.exists (fn (_, ds) =>
  1133                 Library.exists Datatype_Aux.is_rec_type ds) constrs
  1134             end
  1135           | NONE => false)
  1136         | _ => false) types
  1137       val _ = if maybe_spurious then
  1138           warning ("Term contains a recursive datatype; "
  1139             ^ "countermodel(s) may be spurious!")
  1140         else
  1141           ()
  1142       (* (Term.typ * int) list -> string *)
  1143       fun find_model_loop universe =
  1144       let
  1145         val msecs_spent = Time.toMilliseconds (Timer.checkRealTimer timer)
  1146         val _ = maxtime = 0 orelse msecs_spent < 1000 * maxtime
  1147                 orelse raise TimeLimit.TimeOut
  1148         val init_model = (universe, [])
  1149         val init_args  = {maxvars = maxvars, def_eq = false, next_idx = 1,
  1150           bounds = [], wellformed = True}
  1151         val _ = tracing ("Translating term (sizes: "
  1152           ^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
  1153         (* translate 'u' and all axioms *)
  1154         val (intrs, (model, args)) = fold_map (fn t' => fn (m, a) =>
  1155           let
  1156             val (i, m', a') = interpret thy m a t'
  1157           in
  1158             (* set 'def_eq' to 'true' *)
  1159             (i, (m', {maxvars = #maxvars a', def_eq = true,
  1160               next_idx = #next_idx a', bounds = #bounds a',
  1161               wellformed = #wellformed a'}))
  1162           end) (u :: axioms) (init_model, init_args)
  1163         (* make 'u' either true or false, and make all axioms true, and *)
  1164         (* add the well-formedness side condition                       *)
  1165         val fm_u  = (if negate then toFalse else toTrue) (hd intrs)
  1166         val fm_ax = PropLogic.all (map toTrue (tl intrs))
  1167         val fm    = PropLogic.all [#wellformed args, fm_ax, fm_u]
  1168         val solver =
  1169           SatSolver.invoke_solver satsolver
  1170           handle Option.Option =>
  1171                  error ("Unknown SAT solver: " ^ quote satsolver ^
  1172                         ". Available solvers: " ^
  1173                         commas (map (quote o fst) (!SatSolver.solvers)) ^ ".")
  1174       in
  1175         priority "Invoking SAT solver...";
  1176         (case solver fm of
  1177           SatSolver.SATISFIABLE assignment =>
  1178           (priority ("*** Model found: ***\n" ^ print_model thy model
  1179             (fn i => case assignment i of SOME b => b | NONE => true));
  1180            if maybe_spurious then "potential" else "genuine")
  1181         | SatSolver.UNSATISFIABLE _ =>
  1182           (priority "No model exists.";
  1183           case next_universe universe sizes minsize maxsize of
  1184             SOME universe' => find_model_loop universe'
  1185           | NONE           => (priority
  1186             "Search terminated, no larger universe within the given limits.";
  1187             "none"))
  1188         | SatSolver.UNKNOWN =>
  1189           (priority "No model found.";
  1190           case next_universe universe sizes minsize maxsize of
  1191             SOME universe' => find_model_loop universe'
  1192           | NONE           => (priority
  1193             "Search terminated, no larger universe within the given limits.";
  1194             "unknown"))
  1195         ) handle SatSolver.NOT_CONFIGURED =>
  1196           (error ("SAT solver " ^ quote satsolver ^ " is not configured.");
  1197            "unknown")
  1198       end handle MAXVARS_EXCEEDED =>
  1199         (priority ("Search terminated, number of Boolean variables ("
  1200           ^ string_of_int maxvars ^ " allowed) exceeded.");
  1201           "unknown")
  1202         val outcome_code = find_model_loop (first_universe types sizes minsize)
  1203       in
  1204         check_expect outcome_code
  1205       end
  1206     in
  1207       (* some parameter sanity checks *)
  1208       minsize>=1 orelse
  1209         error ("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
  1210       maxsize>=1 orelse
  1211         error ("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
  1212       maxsize>=minsize orelse
  1213         error ("\"maxsize\" (=" ^ string_of_int maxsize ^
  1214         ") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
  1215       maxvars>=0 orelse
  1216         error ("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
  1217       maxtime>=0 orelse
  1218         error ("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
  1219       (* enter loop with or without time limit *)
  1220       priority ("Trying to find a model that "
  1221         ^ (if negate then "refutes" else "satisfies") ^ ": "
  1222         ^ Syntax.string_of_term_global thy t);
  1223       if maxtime>0 then (
  1224         TimeLimit.timeLimit (Time.fromSeconds maxtime)
  1225           wrapper ()
  1226         handle TimeLimit.TimeOut =>
  1227           (priority ("Search terminated, time limit (" ^
  1228               string_of_int maxtime
  1229               ^ (if maxtime=1 then " second" else " seconds") ^ ") exceeded.");
  1230            check_expect "unknown")
  1231       ) else
  1232         wrapper ()
  1233     end;
  1234 
  1235 
  1236 (* ------------------------------------------------------------------------- *)
  1237 (* INTERFACE, PART 2: FINDING A MODEL                                        *)
  1238 (* ------------------------------------------------------------------------- *)
  1239 
  1240 (* ------------------------------------------------------------------------- *)
  1241 (* satisfy_term: calls 'find_model' to find a model that satisfies 't'       *)
  1242 (* params      : list of '(name, value)' pairs used to override default      *)
  1243 (*               parameters                                                  *)
  1244 (* ------------------------------------------------------------------------- *)
  1245 
  1246   (* theory -> (string * string) list -> Term.term list -> Term.term -> unit *)
  1247 
  1248   fun satisfy_term thy params assm_ts t =
  1249     find_model thy (actual_params thy params) assm_ts t false;
  1250 
  1251 (* ------------------------------------------------------------------------- *)
  1252 (* refute_term: calls 'find_model' to find a model that refutes 't'          *)
  1253 (* params     : list of '(name, value)' pairs used to override default       *)
  1254 (*              parameters                                                   *)
  1255 (* ------------------------------------------------------------------------- *)
  1256 
  1257   (* theory -> (string * string) list -> Term.term list -> Term.term -> unit *)
  1258 
  1259   fun refute_term thy params assm_ts t =
  1260   let
  1261     (* disallow schematic type variables, since we cannot properly negate  *)
  1262     (* terms containing them (their logical meaning is that there EXISTS a *)
  1263     (* type s.t. ...; to refute such a formula, we would have to show that *)
  1264     (* for ALL types, not ...)                                             *)
  1265     val _ = null (Term.add_tvars t []) orelse
  1266       error "Term to be refuted contains schematic type variables"
  1267 
  1268     (* existential closure over schematic variables *)
  1269     (* (Term.indexname * Term.typ) list *)
  1270     val vars = sort_wrt (fst o fst) (map dest_Var (OldTerm.term_vars t))
  1271     (* Term.term *)
  1272     val ex_closure = fold (fn ((x, i), T) => fn t' =>
  1273       HOLogic.exists_const T $
  1274         Abs (x, T, abstract_over (Var ((x, i), T), t'))) vars t
  1275     (* Note: If 't' is of type 'propT' (rather than 'boolT'), applying   *)
  1276     (* 'HOLogic.exists_const' is not type-correct.  However, this is not *)
  1277     (* really a problem as long as 'find_model' still interprets the     *)
  1278     (* resulting term correctly, without checking its type.              *)
  1279 
  1280     (* replace outermost universally quantified variables by Free's:     *)
  1281     (* refuting a term with Free's is generally faster than refuting a   *)
  1282     (* term with (nested) quantifiers, because quantifiers are expanded, *)
  1283     (* while the SAT solver searches for an interpretation for Free's.   *)
  1284     (* Also we get more information back that way, namely an             *)
  1285     (* interpretation which includes values for the (formerly)           *)
  1286     (* quantified variables.                                             *)
  1287     (* maps  !!x1...xn. !xk...xm. t   to   t  *)
  1288     fun strip_all_body (Const (@{const_name all}, _) $ Abs (_, _, t)) =
  1289         strip_all_body t
  1290       | strip_all_body (Const (@{const_name Trueprop}, _) $ t) =
  1291         strip_all_body t
  1292       | strip_all_body (Const (@{const_name All}, _) $ Abs (_, _, t)) =
  1293         strip_all_body t
  1294       | strip_all_body t = t
  1295     (* maps  !!x1...xn. !xk...xm. t   to   [x1, ..., xn, xk, ..., xm]  *)
  1296     fun strip_all_vars (Const (@{const_name all}, _) $ Abs (a, T, t)) =
  1297       (a, T) :: strip_all_vars t
  1298       | strip_all_vars (Const (@{const_name Trueprop}, _) $ t) =
  1299       strip_all_vars t
  1300       | strip_all_vars (Const (@{const_name All}, _) $ Abs (a, T, t)) =
  1301       (a, T) :: strip_all_vars t
  1302       | strip_all_vars t =
  1303       [] : (string * typ) list
  1304     val strip_t = strip_all_body ex_closure
  1305     val frees   = Term.rename_wrt_term strip_t (strip_all_vars ex_closure)
  1306     val subst_t = Term.subst_bounds (map Free frees, strip_t)
  1307   in
  1308     find_model thy (actual_params thy params) assm_ts subst_t true
  1309   end;
  1310 
  1311 (* ------------------------------------------------------------------------- *)
  1312 (* refute_goal                                                               *)
  1313 (* ------------------------------------------------------------------------- *)
  1314 
  1315   fun refute_goal ctxt params th i =
  1316   let
  1317     val t = th |> prop_of
  1318   in
  1319     if Logic.count_prems t = 0 then
  1320       priority "No subgoal!"
  1321     else
  1322       let
  1323         val assms = map term_of (Assumption.all_assms_of ctxt)
  1324         val (t, frees) = Logic.goal_params t i
  1325       in
  1326         refute_term (ProofContext.theory_of ctxt) params assms
  1327         (subst_bounds (frees, t))
  1328       end
  1329   end
  1330 
  1331 
  1332 (* ------------------------------------------------------------------------- *)
  1333 (* INTERPRETERS: Auxiliary Functions                                         *)
  1334 (* ------------------------------------------------------------------------- *)
  1335 
  1336 (* ------------------------------------------------------------------------- *)
  1337 (* make_constants: returns all interpretations for type 'T' that consist of  *)
  1338 (*                 unit vectors with 'True'/'False' only (no Boolean         *)
  1339 (*                 variables)                                                *)
  1340 (* ------------------------------------------------------------------------- *)
  1341 
  1342   (* theory -> model -> Term.typ -> interpretation list *)
  1343 
  1344   fun make_constants thy model T =
  1345   let
  1346     (* returns a list with all unit vectors of length n *)
  1347     (* int -> interpretation list *)
  1348     fun unit_vectors n =
  1349     let
  1350       (* returns the k-th unit vector of length n *)
  1351       (* int * int -> interpretation *)
  1352       fun unit_vector (k, n) =
  1353         Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
  1354       (* int -> interpretation list *)
  1355       fun unit_vectors_loop k =
  1356         if k>n then [] else unit_vector (k,n) :: unit_vectors_loop (k+1)
  1357     in
  1358       unit_vectors_loop 1
  1359     end
  1360     (* returns a list of lists, each one consisting of n (possibly *)
  1361     (* identical) elements from 'xs'                               *)
  1362     (* int -> 'a list -> 'a list list *)
  1363     fun pick_all 1 xs =
  1364       map single xs
  1365       | pick_all n xs =
  1366       let val rec_pick = pick_all (n-1) xs in
  1367         maps (fn x => map (cons x) rec_pick) xs
  1368       end
  1369     (* returns all constant interpretations that have the same tree *)
  1370     (* structure as the interpretation argument                     *)
  1371     (* interpretation -> interpretation list *)
  1372     fun make_constants_intr (Leaf xs) = unit_vectors (length xs)
  1373       | make_constants_intr (Node xs) = map Node (pick_all (length xs)
  1374       (make_constants_intr (hd xs)))
  1375     (* obtain the interpretation for a variable of type 'T' *)
  1376     val (i, _, _) = interpret thy model {maxvars=0, def_eq=false, next_idx=1,
  1377       bounds=[], wellformed=True} (Free ("dummy", T))
  1378   in
  1379     make_constants_intr i
  1380   end;
  1381 
  1382 (* ------------------------------------------------------------------------- *)
  1383 (* power: 'power (a, b)' computes a^b, for a>=0, b>=0                        *)
  1384 (* ------------------------------------------------------------------------- *)
  1385 
  1386   (* int * int -> int *)
  1387 
  1388   fun power (a, 0) = 1
  1389     | power (a, 1) = a
  1390     | power (a, b) = let val ab = power(a, b div 2) in
  1391         ab * ab * power(a, b mod 2)
  1392       end;
  1393 
  1394 (* ------------------------------------------------------------------------- *)
  1395 (* size_of_type: returns the number of elements in a type 'T' (i.e. 'length  *)
  1396 (*               (make_constants T)', but implemented more efficiently)      *)
  1397 (* ------------------------------------------------------------------------- *)
  1398 
  1399   (* theory -> model -> Term.typ -> int *)
  1400 
  1401   (* returns 0 for an empty ground type or a function type with empty      *)
  1402   (* codomain, but fails for a function type with empty domain --          *)
  1403   (* admissibility of datatype constructor argument types (see "Inductive  *)
  1404   (* datatypes in HOL - lessons learned ...", S. Berghofer, M. Wenzel,     *)
  1405   (* TPHOLs 99) ensures that recursive, possibly empty, datatype fragments *)
  1406   (* never occur as the domain of a function type that is the type of a    *)
  1407   (* constructor argument                                                  *)
  1408 
  1409   fun size_of_type thy model T =
  1410   let
  1411     (* returns the number of elements that have the same tree structure as a *)
  1412     (* given interpretation                                                  *)
  1413     fun size_of_intr (Leaf xs) = length xs
  1414       | size_of_intr (Node xs) = power (size_of_intr (hd xs), length xs)
  1415     (* obtain the interpretation for a variable of type 'T' *)
  1416     val (i, _, _) = interpret thy model {maxvars=0, def_eq=false, next_idx=1,
  1417       bounds=[], wellformed=True} (Free ("dummy", T))
  1418   in
  1419     size_of_intr i
  1420   end;
  1421 
  1422 (* ------------------------------------------------------------------------- *)
  1423 (* TT/FF: interpretations that denote "true" or "false", respectively        *)
  1424 (* ------------------------------------------------------------------------- *)
  1425 
  1426   (* interpretation *)
  1427 
  1428   val TT = Leaf [True, False];
  1429 
  1430   val FF = Leaf [False, True];
  1431 
  1432 (* ------------------------------------------------------------------------- *)
  1433 (* make_equality: returns an interpretation that denotes (extensional)       *)
  1434 (*                equality of two interpretations                            *)
  1435 (* - two interpretations are 'equal' iff they are both defined and denote    *)
  1436 (*   the same value                                                          *)
  1437 (* - two interpretations are 'not_equal' iff they are both defined at least  *)
  1438 (*   partially, and a defined part denotes different values                  *)
  1439 (* - a completely undefined interpretation is neither 'equal' nor            *)
  1440 (*   'not_equal' to another interpretation                                   *)
  1441 (* ------------------------------------------------------------------------- *)
  1442 
  1443   (* We could in principle represent '=' on a type T by a particular        *)
  1444   (* interpretation.  However, the size of that interpretation is quadratic *)
  1445   (* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
  1446   (* 'i2' directly is more efficient than constructing the interpretation   *)
  1447   (* for equality on T first, and "applying" this interpretation to 'i1'    *)
  1448   (* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
  1449 
  1450   (* interpretation * interpretation -> interpretation *)
  1451 
  1452   fun make_equality (i1, i2) =
  1453   let
  1454     (* interpretation * interpretation -> prop_formula *)
  1455     fun equal (i1, i2) =
  1456       (case i1 of
  1457         Leaf xs =>
  1458         (case i2 of
  1459           Leaf ys => PropLogic.dot_product (xs, ys)  (* defined and equal *)
  1460         | Node _  => raise REFUTE ("make_equality",
  1461           "second interpretation is higher"))
  1462       | Node xs =>
  1463         (case i2 of
  1464           Leaf _  => raise REFUTE ("make_equality",
  1465           "first interpretation is higher")
  1466         | Node ys => PropLogic.all (map equal (xs ~~ ys))))
  1467     (* interpretation * interpretation -> prop_formula *)
  1468     fun not_equal (i1, i2) =
  1469       (case i1 of
  1470         Leaf xs =>
  1471         (case i2 of
  1472           (* defined and not equal *)
  1473           Leaf ys => PropLogic.all ((PropLogic.exists xs)
  1474           :: (PropLogic.exists ys)
  1475           :: (map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))
  1476         | Node _  => raise REFUTE ("make_equality",
  1477           "second interpretation is higher"))
  1478       | Node xs =>
  1479         (case i2 of
  1480           Leaf _  => raise REFUTE ("make_equality",
  1481           "first interpretation is higher")
  1482         | Node ys => PropLogic.exists (map not_equal (xs ~~ ys))))
  1483   in
  1484     (* a value may be undefined; therefore 'not_equal' is not just the *)
  1485     (* negation of 'equal'                                             *)
  1486     Leaf [equal (i1, i2), not_equal (i1, i2)]
  1487   end;
  1488 
  1489 (* ------------------------------------------------------------------------- *)
  1490 (* make_def_equality: returns an interpretation that denotes (extensional)   *)
  1491 (*                    equality of two interpretations                        *)
  1492 (* This function treats undefined/partially defined interpretations          *)
  1493 (* different from 'make_equality': two undefined interpretations are         *)
  1494 (* considered equal, while a defined interpretation is considered not equal  *)
  1495 (* to an undefined interpretation.                                           *)
  1496 (* ------------------------------------------------------------------------- *)
  1497 
  1498   (* interpretation * interpretation -> interpretation *)
  1499 
  1500   fun make_def_equality (i1, i2) =
  1501   let
  1502     (* interpretation * interpretation -> prop_formula *)
  1503     fun equal (i1, i2) =
  1504       (case i1 of
  1505         Leaf xs =>
  1506         (case i2 of
  1507           (* defined and equal, or both undefined *)
  1508           Leaf ys => SOr (PropLogic.dot_product (xs, ys),
  1509           SAnd (PropLogic.all (map SNot xs), PropLogic.all (map SNot ys)))
  1510         | Node _  => raise REFUTE ("make_def_equality",
  1511           "second interpretation is higher"))
  1512       | Node xs =>
  1513         (case i2 of
  1514           Leaf _  => raise REFUTE ("make_def_equality",
  1515           "first interpretation is higher")
  1516         | Node ys => PropLogic.all (map equal (xs ~~ ys))))
  1517     (* interpretation *)
  1518     val eq = equal (i1, i2)
  1519   in
  1520     Leaf [eq, SNot eq]
  1521   end;
  1522 
  1523 (* ------------------------------------------------------------------------- *)
  1524 (* interpretation_apply: returns an interpretation that denotes the result   *)
  1525 (*                       of applying the function denoted by 'i1' to the     *)
  1526 (*                       argument denoted by 'i2'                            *)
  1527 (* ------------------------------------------------------------------------- *)
  1528 
  1529   (* interpretation * interpretation -> interpretation *)
  1530 
  1531   fun interpretation_apply (i1, i2) =
  1532   let
  1533     (* interpretation * interpretation -> interpretation *)
  1534     fun interpretation_disjunction (tr1,tr2) =
  1535       tree_map (fn (xs,ys) => map (fn (x,y) => SOr(x,y)) (xs ~~ ys))
  1536         (tree_pair (tr1,tr2))
  1537     (* prop_formula * interpretation -> interpretation *)
  1538     fun prop_formula_times_interpretation (fm,tr) =
  1539       tree_map (map (fn x => SAnd (fm,x))) tr
  1540     (* prop_formula list * interpretation list -> interpretation *)
  1541     fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
  1542       prop_formula_times_interpretation (fm,tr)
  1543       | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
  1544       interpretation_disjunction (prop_formula_times_interpretation (fm,tr),
  1545         prop_formula_list_dot_product_interpretation_list (fms,trees))
  1546       | prop_formula_list_dot_product_interpretation_list (_,_) =
  1547       raise REFUTE ("interpretation_apply", "empty list (in dot product)")
  1548     (* concatenates 'x' with every list in 'xss', returning a new list of *)
  1549     (* lists                                                              *)
  1550     (* 'a -> 'a list list -> 'a list list *)
  1551     fun cons_list x xss =
  1552       map (cons x) xss
  1553     (* returns a list of lists, each one consisting of one element from each *)
  1554     (* element of 'xss'                                                      *)
  1555     (* 'a list list -> 'a list list *)
  1556     fun pick_all [xs] =
  1557       map single xs
  1558       | pick_all (xs::xss) =
  1559       let val rec_pick = pick_all xss in
  1560         maps (fn x => map (cons x) rec_pick) xs
  1561       end
  1562       | pick_all _ =
  1563       raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
  1564     (* interpretation -> prop_formula list *)
  1565     fun interpretation_to_prop_formula_list (Leaf xs) =
  1566       xs
  1567       | interpretation_to_prop_formula_list (Node trees) =
  1568       map PropLogic.all (pick_all
  1569         (map interpretation_to_prop_formula_list trees))
  1570   in
  1571     case i1 of
  1572       Leaf _ =>
  1573       raise REFUTE ("interpretation_apply", "first interpretation is a leaf")
  1574     | Node xs =>
  1575       prop_formula_list_dot_product_interpretation_list
  1576         (interpretation_to_prop_formula_list i2, xs)
  1577   end;
  1578 
  1579 (* ------------------------------------------------------------------------- *)
  1580 (* eta_expand: eta-expands a term 't' by adding 'i' lambda abstractions      *)
  1581 (* ------------------------------------------------------------------------- *)
  1582 
  1583   (* Term.term -> int -> Term.term *)
  1584 
  1585   fun eta_expand t i =
  1586   let
  1587     val Ts = Term.binder_types (Term.fastype_of t)
  1588     val t' = Term.incr_boundvars i t
  1589   in
  1590     fold_rev (fn T => fn term => Abs ("<eta_expand>", T, term))
  1591       (List.take (Ts, i))
  1592       (Term.list_comb (t', map Bound (i-1 downto 0)))
  1593   end;
  1594 
  1595 (* ------------------------------------------------------------------------- *)
  1596 (* size_of_dtyp: the size of (an initial fragment of) an inductive data type *)
  1597 (*               is the sum (over its constructors) of the product (over     *)
  1598 (*               their arguments) of the size of the argument types          *)
  1599 (* ------------------------------------------------------------------------- *)
  1600 
  1601   fun size_of_dtyp thy typ_sizes descr typ_assoc constructors =
  1602     Integer.sum (map (fn (_, dtyps) =>
  1603       Integer.prod (map (size_of_type thy (typ_sizes, []) o
  1604         (typ_of_dtyp descr typ_assoc)) dtyps))
  1605           constructors);
  1606 
  1607 
  1608 (* ------------------------------------------------------------------------- *)
  1609 (* INTERPRETERS: Actual Interpreters                                         *)
  1610 (* ------------------------------------------------------------------------- *)
  1611 
  1612   (* theory -> model -> arguments -> Term.term ->
  1613     (interpretation * model * arguments) option *)
  1614 
  1615   (* simply typed lambda calculus: Isabelle's basic term syntax, with type *)
  1616   (* variables, function types, and propT                                  *)
  1617 
  1618   fun stlc_interpreter thy model args t =
  1619   let
  1620     val (typs, terms)                                   = model
  1621     val {maxvars, def_eq, next_idx, bounds, wellformed} = args
  1622     (* Term.typ -> (interpretation * model * arguments) option *)
  1623     fun interpret_groundterm T =
  1624     let
  1625       (* unit -> (interpretation * model * arguments) option *)
  1626       fun interpret_groundtype () =
  1627       let
  1628         (* the model must specify a size for ground types *)
  1629         val size = if T = Term.propT then 2
  1630           else the (AList.lookup (op =) typs T)
  1631         val next = next_idx+size
  1632         (* check if 'maxvars' is large enough *)
  1633         val _    = (if next-1>maxvars andalso maxvars>0 then
  1634           raise MAXVARS_EXCEEDED else ())
  1635         (* prop_formula list *)
  1636         val fms  = map BoolVar (next_idx upto (next_idx+size-1))
  1637         (* interpretation *)
  1638         val intr = Leaf fms
  1639         (* prop_formula list -> prop_formula *)
  1640         fun one_of_two_false []      = True
  1641           | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
  1642           SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  1643         (* prop_formula *)
  1644         val wf   = one_of_two_false fms
  1645       in
  1646         (* extend the model, increase 'next_idx', add well-formedness *)
  1647         (* condition                                                  *)
  1648         SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
  1649           def_eq = def_eq, next_idx = next, bounds = bounds,
  1650           wellformed = SAnd (wellformed, wf)})
  1651       end
  1652     in
  1653       case T of
  1654         Type ("fun", [T1, T2]) =>
  1655         let
  1656           (* we create 'size_of_type ... T1' different copies of the        *)
  1657           (* interpretation for 'T2', which are then combined into a single *)
  1658           (* new interpretation                                             *)
  1659           (* make fresh copies, with different variable indices *)
  1660           (* 'idx': next variable index                         *)
  1661           (* 'n'  : number of copies                            *)
  1662           (* int -> int -> (int * interpretation list * prop_formula *)
  1663           fun make_copies idx 0 =
  1664             (idx, [], True)
  1665             | make_copies idx n =
  1666             let
  1667               val (copy, _, new_args) = interpret thy (typs, [])
  1668                 {maxvars = maxvars, def_eq = false, next_idx = idx,
  1669                 bounds = [], wellformed = True} (Free ("dummy", T2))
  1670               val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
  1671             in
  1672               (idx', copy :: copies, SAnd (#wellformed new_args, wf'))
  1673             end
  1674           val (next, copies, wf) = make_copies next_idx
  1675             (size_of_type thy model T1)
  1676           (* combine copies into a single interpretation *)
  1677           val intr = Node copies
  1678         in
  1679           (* extend the model, increase 'next_idx', add well-formedness *)
  1680           (* condition                                                  *)
  1681           SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
  1682             def_eq = def_eq, next_idx = next, bounds = bounds,
  1683             wellformed = SAnd (wellformed, wf)})
  1684         end
  1685       | Type _  => interpret_groundtype ()
  1686       | TFree _ => interpret_groundtype ()
  1687       | TVar  _ => interpret_groundtype ()
  1688     end
  1689   in
  1690     case AList.lookup (op =) terms t of
  1691       SOME intr =>
  1692       (* return an existing interpretation *)
  1693       SOME (intr, model, args)
  1694     | NONE =>
  1695       (case t of
  1696         Const (_, T)     =>
  1697         interpret_groundterm T
  1698       | Free (_, T)      =>
  1699         interpret_groundterm T
  1700       | Var (_, T)       =>
  1701         interpret_groundterm T
  1702       | Bound i          =>
  1703         SOME (List.nth (#bounds args, i), model, args)
  1704       | Abs (x, T, body) =>
  1705         let
  1706           (* create all constants of type 'T' *)
  1707           val constants = make_constants thy model T
  1708           (* interpret the 'body' separately for each constant *)
  1709           val (bodies, (model', args')) = fold_map
  1710             (fn c => fn (m, a) =>
  1711               let
  1712                 (* add 'c' to 'bounds' *)
  1713                 val (i', m', a') = interpret thy m {maxvars = #maxvars a,
  1714                   def_eq = #def_eq a, next_idx = #next_idx a,
  1715                   bounds = (c :: #bounds a), wellformed = #wellformed a} body
  1716               in
  1717                 (* keep the new model m' and 'next_idx' and 'wellformed', *)
  1718                 (* but use old 'bounds'                                   *)
  1719                 (i', (m', {maxvars = maxvars, def_eq = def_eq,
  1720                   next_idx = #next_idx a', bounds = bounds,
  1721                   wellformed = #wellformed a'}))
  1722               end)
  1723             constants (model, args)
  1724         in
  1725           SOME (Node bodies, model', args')
  1726         end
  1727       | t1 $ t2 =>
  1728         let
  1729           (* interpret 't1' and 't2' separately *)
  1730           val (intr1, model1, args1) = interpret thy model args t1
  1731           val (intr2, model2, args2) = interpret thy model1 args1 t2
  1732         in
  1733           SOME (interpretation_apply (intr1, intr2), model2, args2)
  1734         end)
  1735   end;
  1736 
  1737   (* theory -> model -> arguments -> Term.term ->
  1738     (interpretation * model * arguments) option *)
  1739 
  1740   fun Pure_interpreter thy model args t =
  1741     case t of
  1742       Const (@{const_name all}, _) $ t1 =>
  1743       let
  1744         val (i, m, a) = interpret thy model args t1
  1745       in
  1746         case i of
  1747           Node xs =>
  1748           (* 3-valued logic *)
  1749           let
  1750             val fmTrue  = PropLogic.all (map toTrue xs)
  1751             val fmFalse = PropLogic.exists (map toFalse xs)
  1752           in
  1753             SOME (Leaf [fmTrue, fmFalse], m, a)
  1754           end
  1755         | _ =>
  1756           raise REFUTE ("Pure_interpreter",
  1757             "\"all\" is followed by a non-function")
  1758       end
  1759     | Const (@{const_name all}, _) =>
  1760       SOME (interpret thy model args (eta_expand t 1))
  1761     | Const (@{const_name "=="}, _) $ t1 $ t2 =>
  1762       let
  1763         val (i1, m1, a1) = interpret thy model args t1
  1764         val (i2, m2, a2) = interpret thy m1 a1 t2
  1765       in
  1766         (* we use either 'make_def_equality' or 'make_equality' *)
  1767         SOME ((if #def_eq args then make_def_equality else make_equality)
  1768           (i1, i2), m2, a2)
  1769       end
  1770     | Const (@{const_name "=="}, _) $ t1 =>
  1771       SOME (interpret thy model args (eta_expand t 1))
  1772     | Const (@{const_name "=="}, _) =>
  1773       SOME (interpret thy model args (eta_expand t 2))
  1774     | Const (@{const_name "==>"}, _) $ t1 $ t2 =>
  1775       (* 3-valued logic *)
  1776       let
  1777         val (i1, m1, a1) = interpret thy model args t1
  1778         val (i2, m2, a2) = interpret thy m1 a1 t2
  1779         val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
  1780         val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
  1781       in
  1782         SOME (Leaf [fmTrue, fmFalse], m2, a2)
  1783       end
  1784     | Const (@{const_name "==>"}, _) $ t1 =>
  1785       SOME (interpret thy model args (eta_expand t 1))
  1786     | Const (@{const_name "==>"}, _) =>
  1787       SOME (interpret thy model args (eta_expand t 2))
  1788     | _ => NONE;
  1789 
  1790   (* theory -> model -> arguments -> Term.term ->
  1791     (interpretation * model * arguments) option *)
  1792 
  1793   fun HOLogic_interpreter thy model args t =
  1794   (* Providing interpretations directly is more efficient than unfolding the *)
  1795   (* logical constants.  In HOL however, logical constants can themselves be *)
  1796   (* arguments.  They are then translated using eta-expansion.               *)
  1797     case t of
  1798       Const (@{const_name Trueprop}, _) =>
  1799       SOME (Node [TT, FF], model, args)
  1800     | Const (@{const_name Not}, _) =>
  1801       SOME (Node [FF, TT], model, args)
  1802     (* redundant, since 'True' is also an IDT constructor *)
  1803     | Const (@{const_name True}, _) =>
  1804       SOME (TT, model, args)
  1805     (* redundant, since 'False' is also an IDT constructor *)
  1806     | Const (@{const_name False}, _) =>
  1807       SOME (FF, model, args)
  1808     | Const (@{const_name All}, _) $ t1 =>  (* similar to "all" (Pure) *)
  1809       let
  1810         val (i, m, a) = interpret thy model args t1
  1811       in
  1812         case i of
  1813           Node xs =>
  1814           (* 3-valued logic *)
  1815           let
  1816             val fmTrue  = PropLogic.all (map toTrue xs)
  1817             val fmFalse = PropLogic.exists (map toFalse xs)
  1818           in
  1819             SOME (Leaf [fmTrue, fmFalse], m, a)
  1820           end
  1821         | _ =>
  1822           raise REFUTE ("HOLogic_interpreter",
  1823             "\"All\" is followed by a non-function")
  1824       end
  1825     | Const (@{const_name All}, _) =>
  1826       SOME (interpret thy model args (eta_expand t 1))
  1827     | Const (@{const_name Ex}, _) $ t1 =>
  1828       let
  1829         val (i, m, a) = interpret thy model args t1
  1830       in
  1831         case i of
  1832           Node xs =>
  1833           (* 3-valued logic *)
  1834           let
  1835             val fmTrue  = PropLogic.exists (map toTrue xs)
  1836             val fmFalse = PropLogic.all (map toFalse xs)
  1837           in
  1838             SOME (Leaf [fmTrue, fmFalse], m, a)
  1839           end
  1840         | _ =>
  1841           raise REFUTE ("HOLogic_interpreter",
  1842             "\"Ex\" is followed by a non-function")
  1843       end
  1844     | Const (@{const_name Ex}, _) =>
  1845       SOME (interpret thy model args (eta_expand t 1))
  1846     | Const (@{const_name "op ="}, _) $ t1 $ t2 =>  (* similar to "==" (Pure) *)
  1847       let
  1848         val (i1, m1, a1) = interpret thy model args t1
  1849         val (i2, m2, a2) = interpret thy m1 a1 t2
  1850       in
  1851         SOME (make_equality (i1, i2), m2, a2)
  1852       end
  1853     | Const (@{const_name "op ="}, _) $ t1 =>
  1854       SOME (interpret thy model args (eta_expand t 1))
  1855     | Const (@{const_name "op ="}, _) =>
  1856       SOME (interpret thy model args (eta_expand t 2))
  1857     | Const (@{const_name "op &"}, _) $ t1 $ t2 =>
  1858       (* 3-valued logic *)
  1859       let
  1860         val (i1, m1, a1) = interpret thy model args t1
  1861         val (i2, m2, a2) = interpret thy m1 a1 t2
  1862         val fmTrue       = PropLogic.SAnd (toTrue i1, toTrue i2)
  1863         val fmFalse      = PropLogic.SOr (toFalse i1, toFalse i2)
  1864       in
  1865         SOME (Leaf [fmTrue, fmFalse], m2, a2)
  1866       end
  1867     | Const (@{const_name "op &"}, _) $ t1 =>
  1868       SOME (interpret thy model args (eta_expand t 1))
  1869     | Const (@{const_name "op &"}, _) =>
  1870       SOME (interpret thy model args (eta_expand t 2))
  1871       (* this would make "undef" propagate, even for formulae like *)
  1872       (* "False & undef":                                          *)
  1873       (* SOME (Node [Node [TT, FF], Node [FF, FF]], model, args) *)
  1874     | Const (@{const_name "op |"}, _) $ t1 $ t2 =>
  1875       (* 3-valued logic *)
  1876       let
  1877         val (i1, m1, a1) = interpret thy model args t1
  1878         val (i2, m2, a2) = interpret thy m1 a1 t2
  1879         val fmTrue       = PropLogic.SOr (toTrue i1, toTrue i2)
  1880         val fmFalse      = PropLogic.SAnd (toFalse i1, toFalse i2)
  1881       in
  1882         SOME (Leaf [fmTrue, fmFalse], m2, a2)
  1883       end
  1884     | Const (@{const_name "op |"}, _) $ t1 =>
  1885       SOME (interpret thy model args (eta_expand t 1))
  1886     | Const (@{const_name "op |"}, _) =>
  1887       SOME (interpret thy model args (eta_expand t 2))
  1888       (* this would make "undef" propagate, even for formulae like *)
  1889       (* "True | undef":                                           *)
  1890       (* SOME (Node [Node [TT, TT], Node [TT, FF]], model, args) *)
  1891     | Const (@{const_name "op -->"}, _) $ t1 $ t2 =>  (* similar to "==>" (Pure) *)
  1892       (* 3-valued logic *)
  1893       let
  1894         val (i1, m1, a1) = interpret thy model args t1
  1895         val (i2, m2, a2) = interpret thy m1 a1 t2
  1896         val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
  1897         val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
  1898       in
  1899         SOME (Leaf [fmTrue, fmFalse], m2, a2)
  1900       end
  1901     | Const (@{const_name "op -->"}, _) $ t1 =>
  1902       SOME (interpret thy model args (eta_expand t 1))
  1903     | Const (@{const_name "op -->"}, _) =>
  1904       SOME (interpret thy model args (eta_expand t 2))
  1905       (* this would make "undef" propagate, even for formulae like *)
  1906       (* "False --> undef":                                        *)
  1907       (* SOME (Node [Node [TT, FF], Node [TT, TT]], model, args) *)
  1908     | _ => NONE;
  1909 
  1910   (* theory -> model -> arguments -> Term.term ->
  1911     (interpretation * model * arguments) option *)
  1912 
  1913   (* interprets variables and constants whose type is an IDT (this is        *)
  1914   (* relatively easy and merely requires us to compute the size of the IDT); *)
  1915   (* constructors of IDTs however are properly interpreted by                *)
  1916   (* 'IDT_constructor_interpreter'                                           *)
  1917 
  1918   fun IDT_interpreter thy model args t =
  1919   let
  1920     val (typs, terms) = model
  1921     (* Term.typ -> (interpretation * model * arguments) option *)
  1922     fun interpret_term (Type (s, Ts)) =
  1923       (case Datatype.get_info thy s of
  1924         SOME info =>  (* inductive datatype *)
  1925         let
  1926           (* int option -- only recursive IDTs have an associated depth *)
  1927           val depth = AList.lookup (op =) typs (Type (s, Ts))
  1928           (* sanity check: depth must be at least 0 *)
  1929           val _ = (case depth of SOME n =>
  1930             if n<0 then
  1931               raise REFUTE ("IDT_interpreter", "negative depth")
  1932             else ()
  1933             | _ => ())
  1934         in
  1935           (* termination condition to avoid infinite recursion *)
  1936           if depth = (SOME 0) then
  1937             (* return a leaf of size 0 *)
  1938             SOME (Leaf [], model, args)
  1939           else
  1940             let
  1941               val index               = #index info
  1942               val descr               = #descr info
  1943               val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  1944               val typ_assoc           = dtyps ~~ Ts
  1945               (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  1946               val _ = if Library.exists (fn d =>
  1947                   case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  1948                 then
  1949                   raise REFUTE ("IDT_interpreter",
  1950                     "datatype argument (for type "
  1951                     ^ Syntax.string_of_typ_global thy (Type (s, Ts))
  1952                     ^ ") is not a variable")
  1953                 else ()
  1954               (* if the model specifies a depth for the current type, *)
  1955               (* decrement it to avoid infinite recursion             *)
  1956               val typs'    = case depth of NONE => typs | SOME n =>
  1957                 AList.update (op =) (Type (s, Ts), n-1) typs
  1958               (* recursively compute the size of the datatype *)
  1959               val size     = size_of_dtyp thy typs' descr typ_assoc constrs
  1960               val next_idx = #next_idx args
  1961               val next     = next_idx+size
  1962               (* check if 'maxvars' is large enough *)
  1963               val _        = (if next-1 > #maxvars args andalso
  1964                 #maxvars args > 0 then raise MAXVARS_EXCEEDED else ())
  1965               (* prop_formula list *)
  1966               val fms      = map BoolVar (next_idx upto (next_idx+size-1))
  1967               (* interpretation *)
  1968               val intr     = Leaf fms
  1969               (* prop_formula list -> prop_formula *)
  1970               fun one_of_two_false []      = True
  1971                 | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
  1972                 SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  1973               (* prop_formula *)
  1974               val wf       = one_of_two_false fms
  1975             in
  1976               (* extend the model, increase 'next_idx', add well-formedness *)
  1977               (* condition                                                  *)
  1978               SOME (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args,
  1979                 def_eq = #def_eq args, next_idx = next, bounds = #bounds args,
  1980                 wellformed = SAnd (#wellformed args, wf)})
  1981             end
  1982         end
  1983       | NONE =>  (* not an inductive datatype *)
  1984         NONE)
  1985       | interpret_term _ =  (* a (free or schematic) type variable *)
  1986       NONE
  1987   in
  1988     case AList.lookup (op =) terms t of
  1989       SOME intr =>
  1990       (* return an existing interpretation *)
  1991       SOME (intr, model, args)
  1992     | NONE =>
  1993       (case t of
  1994         Free (_, T)  => interpret_term T
  1995       | Var (_, T)   => interpret_term T
  1996       | Const (_, T) => interpret_term T
  1997       | _            => NONE)
  1998   end;
  1999 
  2000   (* theory -> model -> arguments -> Term.term ->
  2001     (interpretation * model * arguments) option *)
  2002 
  2003   (* This function imposes an order on the elements of a datatype fragment  *)
  2004   (* as follows: C_i x_1 ... x_n < C_j y_1 ... y_m iff i < j or             *)
  2005   (* (x_1, ..., x_n) < (y_1, ..., y_m).  With this order, a constructor is  *)
  2006   (* a function C_i that maps some argument indices x_1, ..., x_n to the    *)
  2007   (* datatype element given by index C_i x_1 ... x_n.  The idea remains the *)
  2008   (* same for recursive datatypes, although the computation of indices gets *)
  2009   (* a little tricky.                                                       *)
  2010 
  2011   fun IDT_constructor_interpreter thy model args t =
  2012   let
  2013     (* returns a list of canonical representations for terms of the type 'T' *)
  2014     (* It would be nice if we could just use 'print' for this, but 'print'   *)
  2015     (* for IDTs calls 'IDT_constructor_interpreter' again, and this could    *)
  2016     (* lead to infinite recursion when we have (mutually) recursive IDTs.    *)
  2017     (* (Term.typ * int) list -> Term.typ -> Term.term list *)
  2018     fun canonical_terms typs T =
  2019       (case T of
  2020         Type ("fun", [T1, T2]) =>
  2021         (* 'T2' might contain a recursive IDT, so we cannot use 'print' (at *)
  2022         (* least not for 'T2'                                               *)
  2023         let
  2024           (* returns a list of lists, each one consisting of n (possibly *)
  2025           (* identical) elements from 'xs'                               *)
  2026           (* int -> 'a list -> 'a list list *)
  2027           fun pick_all 1 xs =
  2028             map single xs
  2029           | pick_all n xs =
  2030             let val rec_pick = pick_all (n-1) xs in
  2031               maps (fn x => map (cons x) rec_pick) xs
  2032             end
  2033           (* ["x1", ..., "xn"] *)
  2034           val terms1 = canonical_terms typs T1
  2035           (* ["y1", ..., "ym"] *)
  2036           val terms2 = canonical_terms typs T2
  2037           (* [[("x1", "y1"), ..., ("xn", "y1")], ..., *)
  2038           (*   [("x1", "ym"), ..., ("xn", "ym")]]     *)
  2039           val functions = map (curry (op ~~) terms1)
  2040             (pick_all (length terms1) terms2)
  2041           (* [["(x1, y1)", ..., "(xn, y1)"], ..., *)
  2042           (*   ["(x1, ym)", ..., "(xn, ym)"]]     *)
  2043           val pairss = map (map HOLogic.mk_prod) functions
  2044           (* Term.typ *)
  2045           val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  2046           val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  2047           (* Term.term *)
  2048           val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
  2049           val HOLogic_insert    =
  2050             Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  2051         in
  2052           (* functions as graphs, i.e. as a (HOL) set of pairs "(x, y)" *)
  2053           map (fn ps => fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) ps
  2054             HOLogic_empty_set) pairss
  2055         end
  2056       | Type (s, Ts) =>
  2057         (case Datatype.get_info thy s of
  2058           SOME info =>
  2059           (case AList.lookup (op =) typs T of
  2060             SOME 0 =>
  2061             (* termination condition to avoid infinite recursion *)
  2062             []  (* at depth 0, every IDT is empty *)
  2063           | _ =>
  2064             let
  2065               val index               = #index info
  2066               val descr               = #descr info
  2067               val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  2068               val typ_assoc           = dtyps ~~ Ts
  2069               (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  2070               val _ = if Library.exists (fn d =>
  2071                   case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  2072                 then
  2073                   raise REFUTE ("IDT_constructor_interpreter",
  2074                     "datatype argument (for type "
  2075                     ^ Syntax.string_of_typ_global thy T
  2076                     ^ ") is not a variable")
  2077                 else ()
  2078               (* decrement depth for the IDT 'T' *)
  2079               val typs' = (case AList.lookup (op =) typs T of NONE => typs
  2080                 | SOME n => AList.update (op =) (T, n-1) typs)
  2081               fun constructor_terms terms [] = terms
  2082                 | constructor_terms terms (d::ds) =
  2083                 let
  2084                   val dT = typ_of_dtyp descr typ_assoc d
  2085                   val d_terms = canonical_terms typs' dT
  2086                 in
  2087                   (* C_i x_1 ... x_n < C_i y_1 ... y_n if *)
  2088                   (* (x_1, ..., x_n) < (y_1, ..., y_n)    *)
  2089                   constructor_terms
  2090                     (map_product (curry op $) terms d_terms) ds
  2091                 end
  2092             in
  2093               (* C_i ... < C_j ... if i < j *)
  2094               maps (fn (cname, ctyps) =>
  2095                 let
  2096                   val cTerm = Const (cname,
  2097                     map (typ_of_dtyp descr typ_assoc) ctyps ---> T)
  2098                 in
  2099                   constructor_terms [cTerm] ctyps
  2100                 end) constrs
  2101             end)
  2102         | NONE =>
  2103           (* not an inductive datatype; in this case the argument types in *)
  2104           (* 'Ts' may not be IDTs either, so 'print' should be safe        *)
  2105           map (fn intr => print thy (typs, []) T intr (K false))
  2106             (make_constants thy (typs, []) T))
  2107       | _ =>  (* TFree ..., TVar ... *)
  2108         map (fn intr => print thy (typs, []) T intr (K false))
  2109           (make_constants thy (typs, []) T))
  2110     val (typs, terms) = model
  2111   in
  2112     case AList.lookup (op =) terms t of
  2113       SOME intr =>
  2114       (* return an existing interpretation *)
  2115       SOME (intr, model, args)
  2116     | NONE =>
  2117       (case t of
  2118         Const (s, T) =>
  2119         (case body_type T of
  2120           Type (s', Ts') =>
  2121           (case Datatype.get_info thy s' of
  2122             SOME info =>  (* body type is an inductive datatype *)
  2123             let
  2124               val index               = #index info
  2125               val descr               = #descr info
  2126               val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  2127               val typ_assoc           = dtyps ~~ Ts'
  2128               (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  2129               val _ = if Library.exists (fn d =>
  2130                   case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  2131                 then
  2132                   raise REFUTE ("IDT_constructor_interpreter",
  2133                     "datatype argument (for type "
  2134                     ^ Syntax.string_of_typ_global thy (Type (s', Ts'))
  2135                     ^ ") is not a variable")
  2136                 else ()
  2137               (* split the constructors into those occuring before/after *)
  2138               (* 'Const (s, T)'                                          *)
  2139               val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
  2140                 not (cname = s andalso Sign.typ_instance thy (T,
  2141                   map (typ_of_dtyp descr typ_assoc) ctypes
  2142                     ---> Type (s', Ts')))) constrs
  2143             in
  2144               case constrs2 of
  2145                 [] =>
  2146                 (* 'Const (s, T)' is not a constructor of this datatype *)
  2147                 NONE
  2148               | (_, ctypes)::cs =>
  2149                 let
  2150                   (* int option -- only /recursive/ IDTs have an associated *)
  2151                   (*               depth                                    *)
  2152                   val depth = AList.lookup (op =) typs (Type (s', Ts'))
  2153                   (* this should never happen: at depth 0, this IDT fragment *)
  2154                   (* is definitely empty, and in this case we don't need to  *)
  2155                   (* interpret its constructors                              *)
  2156                   val _ = (case depth of SOME 0 =>
  2157                       raise REFUTE ("IDT_constructor_interpreter",
  2158                         "depth is 0")
  2159                     | _ => ())
  2160                   val typs' = (case depth of NONE => typs | SOME n =>
  2161                     AList.update (op =) (Type (s', Ts'), n-1) typs)
  2162                   (* elements of the datatype come before elements generated *)
  2163                   (* by 'Const (s, T)' iff they are generated by a           *)
  2164                   (* constructor in constrs1                                 *)
  2165                   val offset = size_of_dtyp thy typs' descr typ_assoc constrs1
  2166                   (* compute the total (current) size of the datatype *)
  2167                   val total = offset +
  2168                     size_of_dtyp thy typs' descr typ_assoc constrs2
  2169                   (* sanity check *)
  2170                   val _ = if total <> size_of_type thy (typs, [])
  2171                     (Type (s', Ts')) then
  2172                       raise REFUTE ("IDT_constructor_interpreter",
  2173                         "total is not equal to current size")
  2174                     else ()
  2175                   (* returns an interpretation where everything is mapped to *)
  2176                   (* an "undefined" element of the datatype                  *)
  2177                   fun make_undef [] =
  2178                     Leaf (replicate total False)
  2179                     | make_undef (d::ds) =
  2180                     let
  2181                       (* compute the current size of the type 'd' *)
  2182                       val dT   = typ_of_dtyp descr typ_assoc d
  2183                       val size = size_of_type thy (typs, []) dT
  2184                     in
  2185                       Node (replicate size (make_undef ds))
  2186                     end
  2187                   (* returns the interpretation for a constructor *)
  2188                   fun make_constr [] offset =
  2189                     if offset < total then
  2190                       (Leaf (replicate offset False @ True ::
  2191                         (replicate (total - offset - 1) False)), offset + 1)
  2192                     else
  2193                       raise REFUTE ("IDT_constructor_interpreter",
  2194                         "offset >= total")
  2195                     | make_constr (d::ds) offset =
  2196                     let
  2197                       (* Term.typ *)
  2198                       val dT = typ_of_dtyp descr typ_assoc d
  2199                       (* compute canonical term representations for all   *)
  2200                       (* elements of the type 'd' (with the reduced depth *)
  2201                       (* for the IDT)                                     *)
  2202                       val terms' = canonical_terms typs' dT
  2203                       (* sanity check *)
  2204                       val _ =
  2205                         if length terms' <> size_of_type thy (typs', []) dT
  2206                         then
  2207                           raise REFUTE ("IDT_constructor_interpreter",
  2208                             "length of terms' is not equal to old size")
  2209                         else ()
  2210                       (* compute canonical term representations for all   *)
  2211                       (* elements of the type 'd' (with the current depth *)
  2212                       (* for the IDT)                                     *)
  2213                       val terms = canonical_terms typs dT
  2214                       (* sanity check *)
  2215                       val _ =
  2216                         if length terms <> size_of_type thy (typs, []) dT
  2217                         then
  2218                           raise REFUTE ("IDT_constructor_interpreter",
  2219                             "length of terms is not equal to current size")
  2220                         else ()
  2221                       (* sanity check *)
  2222                       val _ =
  2223                         if length terms < length terms' then
  2224                           raise REFUTE ("IDT_constructor_interpreter",
  2225                             "current size is less than old size")
  2226                         else ()
  2227                       (* sanity check: every element of terms' must also be *)
  2228                       (*               present in terms                     *)
  2229                       val _ =
  2230                         if List.all (member (op =) terms) terms' then ()
  2231                         else
  2232                           raise REFUTE ("IDT_constructor_interpreter",
  2233                             "element has disappeared")
  2234                       (* sanity check: the order on elements of terms' is    *)
  2235                       (*               the same in terms, for those elements *)
  2236                       val _ =
  2237                         let
  2238                           fun search (x::xs) (y::ys) =
  2239                                 if x = y then search xs ys else search (x::xs) ys
  2240                             | search (x::xs) [] =
  2241                                 raise REFUTE ("IDT_constructor_interpreter",
  2242                                   "element order not preserved")
  2243                             | search [] _ = ()
  2244                         in  search terms' terms  end
  2245                       (* int * interpretation list *)
  2246                       val (intrs, new_offset) =
  2247                         fold_map (fn t_elem => fn off =>
  2248                           (* if 't_elem' existed at the previous depth,    *)
  2249                           (* proceed recursively, otherwise map the entire *)
  2250                           (* subtree to "undefined"                        *)
  2251                           if member (op =) terms' t_elem then
  2252                             make_constr ds off
  2253                           else
  2254                             (make_undef ds, off))
  2255                         terms offset
  2256                     in
  2257                       (Node intrs, new_offset)
  2258                     end
  2259                 in
  2260                   SOME (fst (make_constr ctypes offset), model, args)
  2261                 end
  2262             end
  2263           | NONE =>  (* body type is not an inductive datatype *)
  2264             NONE)
  2265         | _ =>  (* body type is a (free or schematic) type variable *)
  2266           NONE)
  2267       | _ =>  (* term is not a constant *)
  2268         NONE)
  2269   end;
  2270 
  2271   (* theory -> model -> arguments -> Term.term ->
  2272     (interpretation * model * arguments) option *)
  2273 
  2274   (* Difficult code ahead.  Make sure you understand the                *)
  2275   (* 'IDT_constructor_interpreter' and the order in which it enumerates *)
  2276   (* elements of an IDT before you try to understand this function.     *)
  2277 
  2278   fun IDT_recursion_interpreter thy model args t =
  2279     (* careful: here we descend arbitrarily deep into 't', possibly before *)
  2280     (* any other interpreter for atomic terms has had a chance to look at  *)
  2281     (* 't'                                                                 *)
  2282     case strip_comb t of
  2283       (Const (s, T), params) =>
  2284       (* iterate over all datatypes in 'thy' *)
  2285       Symtab.fold (fn (_, info) => fn result =>
  2286         case result of
  2287           SOME _ =>
  2288           result  (* just keep 'result' *)
  2289         | NONE =>
  2290           if member (op =) (#rec_names info) s then
  2291             (* we do have a recursion operator of one of the (mutually *)
  2292             (* recursive) datatypes given by 'info'                    *)
  2293             let
  2294               (* number of all constructors, including those of different  *)
  2295               (* (mutually recursive) datatypes within the same descriptor *)
  2296               val mconstrs_count =
  2297                 Integer.sum (map (fn (_, (_, _, cs)) => length cs) (#descr info))
  2298             in
  2299               if mconstrs_count < length params then
  2300                 (* too many actual parameters; for now we'll use the *)
  2301                 (* 'stlc_interpreter' to strip off one application   *)
  2302                 NONE
  2303               else if mconstrs_count > length params then
  2304                 (* too few actual parameters; we use eta expansion          *)
  2305                 (* Note that the resulting expansion of lambda abstractions *)
  2306                 (* by the 'stlc_interpreter' may be rather slow (depending  *)
  2307                 (* on the argument types and the size of the IDT, of        *)
  2308                 (* course).                                                 *)
  2309                 SOME (interpret thy model args (eta_expand t
  2310                   (mconstrs_count - length params)))
  2311               else  (* mconstrs_count = length params *)
  2312                 let
  2313                   (* interpret each parameter separately *)
  2314                   val (p_intrs, (model', args')) = fold_map (fn p => fn (m, a) =>
  2315                     let
  2316                       val (i, m', a') = interpret thy m a p
  2317                     in
  2318                       (i, (m', a'))
  2319                     end) params (model, args)
  2320                   val (typs, _) = model'
  2321                   (* 'index' is /not/ necessarily the index of the IDT that *)
  2322                   (* the recursion operator is associated with, but merely  *)
  2323                   (* the index of some mutually recursive IDT               *)
  2324                   val index         = #index info
  2325                   val descr         = #descr info
  2326                   val (_, dtyps, _) = the (AList.lookup (op =) descr index)
  2327                   (* sanity check: we assume that the order of constructors *)
  2328                   (*               in 'descr' is the same as the order of   *)
  2329                   (*               corresponding parameters, otherwise the  *)
  2330                   (*               association code below won't match the   *)
  2331                   (*               right constructors/parameters; we also   *)
  2332                   (*               assume that the order of recursion       *)
  2333                   (*               operators in '#rec_names info' is the    *)
  2334                   (*               same as the order of corresponding       *)
  2335                   (*               datatypes in 'descr'                     *)
  2336                   val _ = if map fst descr <> (0 upto (length descr - 1)) then
  2337                       raise REFUTE ("IDT_recursion_interpreter",
  2338                         "order of constructors and corresponding parameters/" ^
  2339                           "recursion operators and corresponding datatypes " ^
  2340                           "different?")
  2341                     else ()
  2342                   (* sanity check: every element in 'dtyps' must be a *)
  2343                   (*               'DtTFree'                          *)
  2344                   val _ = if Library.exists (fn d =>
  2345                     case d of Datatype_Aux.DtTFree _ => false
  2346                             | _ => true) dtyps
  2347                     then
  2348                       raise REFUTE ("IDT_recursion_interpreter",
  2349                         "datatype argument is not a variable")
  2350                     else ()
  2351                   (* the type of a recursion operator is *)
  2352                   (* [T1, ..., Tn, IDT] ---> Tresult     *)
  2353                   val IDT = List.nth (binder_types T, mconstrs_count)
  2354                   (* by our assumption on the order of recursion operators *)
  2355                   (* and datatypes, this is the index of the datatype      *)
  2356                   (* corresponding to the given recursion operator         *)
  2357                   val idt_index = find_index (fn s' => s' = s) (#rec_names info)
  2358                   (* mutually recursive types must have the same type   *)
  2359                   (* parameters, unless the mutual recursion comes from *)
  2360                   (* indirect recursion                                 *)
  2361                   fun rec_typ_assoc acc [] =
  2362                     acc
  2363                     | rec_typ_assoc acc ((d, T)::xs) =
  2364                     (case AList.lookup op= acc d of
  2365                       NONE =>
  2366                       (case d of
  2367                         Datatype_Aux.DtTFree _ =>
  2368                         (* add the association, proceed *)
  2369                         rec_typ_assoc ((d, T)::acc) xs
  2370                       | Datatype_Aux.DtType (s, ds) =>
  2371                         let
  2372                           val (s', Ts) = dest_Type T
  2373                         in
  2374                           if s=s' then
  2375                             rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
  2376                           else
  2377                             raise REFUTE ("IDT_recursion_interpreter",
  2378                               "DtType/Type mismatch")
  2379                         end
  2380                       | Datatype_Aux.DtRec i =>
  2381                         let
  2382                           val (_, ds, _) = the (AList.lookup (op =) descr i)
  2383                           val (_, Ts)    = dest_Type T
  2384                         in
  2385                           rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
  2386                         end)
  2387                     | SOME T' =>
  2388                       if T=T' then
  2389                         (* ignore the association since it's already *)
  2390                         (* present, proceed                          *)
  2391                         rec_typ_assoc acc xs
  2392                       else
  2393                         raise REFUTE ("IDT_recursion_interpreter",
  2394                           "different type associations for the same dtyp"))
  2395                   val typ_assoc = filter
  2396                     (fn (Datatype_Aux.DtTFree _, _) => true | (_, _) => false)
  2397                     (rec_typ_assoc []
  2398                       (#2 (the (AList.lookup (op =) descr idt_index)) ~~ (snd o dest_Type) IDT))
  2399                   (* sanity check: typ_assoc must associate types to the   *)
  2400                   (*               elements of 'dtyps' (and only to those) *)
  2401                   val _ = if not (eq_set (op =) (dtyps, map fst typ_assoc))
  2402                     then
  2403                       raise REFUTE ("IDT_recursion_interpreter",
  2404                         "type association has extra/missing elements")
  2405                     else ()
  2406                   (* interpret each constructor in the descriptor (including *)
  2407                   (* those of mutually recursive datatypes)                  *)
  2408                   (* (int * interpretation list) list *)
  2409                   val mc_intrs = map (fn (idx, (_, _, cs)) =>
  2410                     let
  2411                       val c_return_typ = typ_of_dtyp descr typ_assoc
  2412                         (Datatype_Aux.DtRec idx)
  2413                     in
  2414                       (idx, map (fn (cname, cargs) =>
  2415                         (#1 o interpret thy (typs, []) {maxvars=0,
  2416                           def_eq=false, next_idx=1, bounds=[],
  2417                           wellformed=True}) (Const (cname, map (typ_of_dtyp
  2418                           descr typ_assoc) cargs ---> c_return_typ))) cs)
  2419                     end) descr
  2420                   (* associate constructors with corresponding parameters *)
  2421                   (* (int * (interpretation * interpretation) list) list *)
  2422                   val (mc_p_intrs, p_intrs') = fold_map
  2423                     (fn (idx, c_intrs) => fn p_intrs' =>
  2424                       let
  2425                         val len = length c_intrs
  2426                       in
  2427                         ((idx, c_intrs ~~ List.take (p_intrs', len)),
  2428                           List.drop (p_intrs', len))
  2429                       end) mc_intrs p_intrs
  2430                   (* sanity check: no 'p_intr' may be left afterwards *)
  2431                   val _ = if p_intrs' <> [] then
  2432                       raise REFUTE ("IDT_recursion_interpreter",
  2433                         "more parameter than constructor interpretations")
  2434                     else ()
  2435                   (* The recursion operator, applied to 'mconstrs_count'     *)
  2436                   (* arguments, is a function that maps every element of the *)
  2437                   (* inductive datatype to an element of some result type.   *)
  2438                   (* Recursion operators for mutually recursive IDTs are     *)
  2439                   (* translated simultaneously.                              *)
  2440                   (* Since the order on datatype elements is given by an     *)
  2441                   (* order on constructors (and then by the order on         *)
  2442                   (* argument tuples), we can simply copy corresponding      *)
  2443                   (* subtrees from 'p_intrs', in the order in which they are *)
  2444                   (* given.                                                  *)
  2445                   (* interpretation * interpretation -> interpretation list *)
  2446                   fun ci_pi (Leaf xs, pi) =
  2447                     (* if the constructor does not match the arguments to a *)
  2448                     (* defined element of the IDT, the corresponding value  *)
  2449                     (* of the parameter must be ignored                     *)
  2450                     if List.exists (equal True) xs then [pi] else []
  2451                     | ci_pi (Node xs, Node ys) =
  2452                     maps ci_pi (xs ~~ ys)
  2453                     | ci_pi (Node _, Leaf _) =
  2454                     raise REFUTE ("IDT_recursion_interpreter",
  2455                       "constructor takes more arguments than the " ^
  2456                         "associated parameter")
  2457                   (* (int * interpretation list) list *)
  2458                   val rec_operators = map (fn (idx, c_p_intrs) =>
  2459                     (idx, maps ci_pi c_p_intrs)) mc_p_intrs
  2460                   (* sanity check: every recursion operator must provide as  *)
  2461                   (*               many values as the corresponding datatype *)
  2462                   (*               has elements                              *)
  2463                   val _ = map (fn (idx, intrs) =>
  2464                     let
  2465                       val T = typ_of_dtyp descr typ_assoc
  2466                         (Datatype_Aux.DtRec idx)
  2467                     in
  2468                       if length intrs <> size_of_type thy (typs, []) T then
  2469                         raise REFUTE ("IDT_recursion_interpreter",
  2470                           "wrong number of interpretations for rec. operator")
  2471                       else ()
  2472                     end) rec_operators
  2473                   (* For non-recursive datatypes, we are pretty much done at *)
  2474                   (* this point.  For recursive datatypes however, we still  *)
  2475                   (* need to apply the interpretations in 'rec_operators' to *)
  2476                   (* (recursively obtained) interpretations for recursive    *)
  2477                   (* constructor arguments.  To do so more efficiently, we   *)
  2478                   (* copy 'rec_operators' into arrays first.  Each Boolean   *)
  2479                   (* indicates whether the recursive arguments have been     *)
  2480                   (* considered already.                                     *)
  2481                   (* (int * (bool * interpretation) Array.array) list *)
  2482                   val REC_OPERATORS = map (fn (idx, intrs) =>
  2483                     (idx, Array.fromList (map (pair false) intrs)))
  2484                     rec_operators
  2485                   (* takes an interpretation, and if some leaf of this     *)
  2486                   (* interpretation is the 'elem'-th element of the type,  *)
  2487                   (* the indices of the arguments leading to this leaf are *)
  2488                   (* returned                                              *)
  2489                   (* interpretation -> int -> int list option *)
  2490                   fun get_args (Leaf xs) elem =
  2491                     if find_index (fn x => x = True) xs = elem then
  2492                       SOME []
  2493                     else
  2494                       NONE
  2495                     | get_args (Node xs) elem =
  2496                     let
  2497                       (* interpretation list * int -> int list option *)
  2498                       fun search ([], _) =
  2499                         NONE
  2500                         | search (x::xs, n) =
  2501                         (case get_args x elem of
  2502                           SOME result => SOME (n::result)
  2503                         | NONE        => search (xs, n+1))
  2504                     in
  2505                       search (xs, 0)
  2506                     end
  2507                   (* returns the index of the constructor and indices for *)
  2508                   (* its arguments that generate the 'elem'-th element of *)
  2509                   (* the datatype given by 'idx'                          *)
  2510                   (* int -> int -> int * int list *)
  2511                   fun get_cargs idx elem =
  2512                   let
  2513                     (* int * interpretation list -> int * int list *)
  2514                     fun get_cargs_rec (_, []) =
  2515                       raise REFUTE ("IDT_recursion_interpreter",
  2516                         "no matching constructor found for datatype element")
  2517                       | get_cargs_rec (n, x::xs) =
  2518                         (case get_args x elem of
  2519                           SOME args => (n, args)
  2520                         | NONE      => get_cargs_rec (n+1, xs))
  2521                     in
  2522                       get_cargs_rec (0, the (AList.lookup (op =) mc_intrs idx))
  2523                     end
  2524                   (* computes one entry in 'REC_OPERATORS', and recursively *)
  2525                   (* all entries needed for it, where 'idx' gives the       *)
  2526                   (* datatype and 'elem' the element of it                  *)
  2527                   (* int -> int -> interpretation *)
  2528                   fun compute_array_entry idx elem =
  2529                   let
  2530                     val arr          = the (AList.lookup (op =) REC_OPERATORS idx)
  2531                     val (flag, intr) = Array.sub (arr, elem)
  2532                   in
  2533                     if flag then
  2534                       (* simply return the previously computed result *)
  2535                       intr
  2536                     else
  2537                       (* we have to apply 'intr' to interpretations for all *)
  2538                       (* recursive arguments                                *)
  2539                       let
  2540                         (* int * int list *)
  2541                         val (c, args) = get_cargs idx elem
  2542                         (* find the indices of the constructor's /recursive/ *)
  2543                         (* arguments                                         *)
  2544                         val (_, _, constrs) = the (AList.lookup (op =) descr idx)
  2545                         val (_, dtyps)      = List.nth (constrs, c)
  2546                         val rec_dtyps_args  = filter
  2547                           (Datatype_Aux.is_rec_type o fst) (dtyps ~~ args)
  2548                         (* map those indices to interpretations *)
  2549                         val rec_dtyps_intrs = map (fn (dtyp, arg) =>
  2550                           let
  2551                             val dT     = typ_of_dtyp descr typ_assoc dtyp
  2552                             val consts = make_constants thy (typs, []) dT
  2553                             val arg_i  = List.nth (consts, arg)
  2554                           in
  2555                             (dtyp, arg_i)
  2556                           end) rec_dtyps_args
  2557                         (* takes the dtyp and interpretation of an element, *)
  2558                         (* and computes the interpretation for the          *)
  2559                         (* corresponding recursive argument                 *)
  2560                         fun rec_intr (Datatype_Aux.DtRec i) (Leaf xs) =
  2561                           (* recursive argument is "rec_i params elem" *)
  2562                           compute_array_entry i (find_index (fn x => x = True) xs)
  2563                           | rec_intr (Datatype_Aux.DtRec _) (Node _) =
  2564                           raise REFUTE ("IDT_recursion_interpreter",
  2565                             "interpretation for IDT is a node")
  2566                           | rec_intr (Datatype_Aux.DtType ("fun", [dt1, dt2]))
  2567                             (Node xs) =
  2568                           (* recursive argument is something like     *)
  2569                           (* "\<lambda>x::dt1. rec_? params (elem x)" *)
  2570                           Node (map (rec_intr dt2) xs)
  2571                           | rec_intr (Datatype_Aux.DtType ("fun", [_, _]))
  2572                             (Leaf _) =
  2573                           raise REFUTE ("IDT_recursion_interpreter",
  2574                             "interpretation for function dtyp is a leaf")
  2575                           | rec_intr _ _ =
  2576                           (* admissibility ensures that every recursive type *)
  2577                           (* is of the form 'Dt_1 -> ... -> Dt_k ->          *)
  2578                           (* (DtRec i)'                                      *)
  2579                           raise REFUTE ("IDT_recursion_interpreter",
  2580                             "non-recursive codomain in recursive dtyp")
  2581                         (* obtain interpretations for recursive arguments *)
  2582                         (* interpretation list *)
  2583                         val arg_intrs = map (uncurry rec_intr) rec_dtyps_intrs
  2584                         (* apply 'intr' to all recursive arguments *)
  2585                         val result = fold (fn arg_i => fn i =>
  2586                           interpretation_apply (i, arg_i)) arg_intrs intr
  2587                         (* update 'REC_OPERATORS' *)
  2588                         val _ = Array.update (arr, elem, (true, result))
  2589                       in
  2590                         result
  2591                       end
  2592                   end
  2593                   val idt_size = Array.length (the (AList.lookup (op =) REC_OPERATORS idt_index))
  2594                   (* sanity check: the size of 'IDT' should be 'idt_size' *)
  2595                   val _ = if idt_size <> size_of_type thy (typs, []) IDT then
  2596                         raise REFUTE ("IDT_recursion_interpreter",
  2597                           "unexpected size of IDT (wrong type associated?)")
  2598                       else ()
  2599                   (* interpretation *)
  2600                   val rec_op = Node (map_range (compute_array_entry idt_index) idt_size)
  2601                 in
  2602                   SOME (rec_op, model', args')
  2603                 end
  2604             end
  2605           else
  2606             NONE  (* not a recursion operator of this datatype *)
  2607         ) (Datatype.get_all thy) NONE
  2608     | _ =>  (* head of term is not a constant *)
  2609       NONE;
  2610 
  2611   (* theory -> model -> arguments -> Term.term ->
  2612     (interpretation * model * arguments) option *)
  2613 
  2614   fun set_interpreter thy model args t =
  2615   let
  2616     val (typs, terms) = model
  2617   in
  2618     case AList.lookup (op =) terms t of
  2619       SOME intr =>
  2620       (* return an existing interpretation *)
  2621       SOME (intr, model, args)
  2622     | NONE =>
  2623       (case t of
  2624       (* 'Collect' == identity *)
  2625         Const (@{const_name Collect}, _) $ t1 =>
  2626         SOME (interpret thy model args t1)
  2627       | Const (@{const_name Collect}, _) =>
  2628         SOME (interpret thy model args (eta_expand t 1))
  2629       (* 'op :' == application *)
  2630       | Const (@{const_name "op :"}, _) $ t1 $ t2 =>
  2631         SOME (interpret thy model args (t2 $ t1))
  2632       | Const (@{const_name "op :"}, _) $ t1 =>
  2633         SOME (interpret thy model args (eta_expand t 1))
  2634       | Const (@{const_name "op :"}, _) =>
  2635         SOME (interpret thy model args (eta_expand t 2))
  2636       | _ => NONE)
  2637   end;
  2638 
  2639   (* theory -> model -> arguments -> Term.term ->
  2640     (interpretation * model * arguments) option *)
  2641 
  2642   (* only an optimization: 'card' could in principle be interpreted with *)
  2643   (* interpreters available already (using its definition), but the code *)
  2644   (* below is more efficient                                             *)
  2645 
  2646   fun Finite_Set_card_interpreter thy model args t =
  2647     case t of
  2648       Const (@{const_name Finite_Set.card},
  2649         Type ("fun", [Type ("fun", [T, Type ("bool", [])]),
  2650                       Type ("nat", [])])) =>
  2651       let
  2652         (* interpretation -> int *)
  2653         fun number_of_elements (Node xs) =
  2654             fold (fn x => fn n =>
  2655               if x = TT then
  2656                 n + 1
  2657               else if x = FF then
  2658                 n
  2659               else
  2660                 raise REFUTE ("Finite_Set_card_interpreter",
  2661                   "interpretation for set type does not yield a Boolean"))
  2662               xs 0
  2663           | number_of_elements (Leaf _) =
  2664           raise REFUTE ("Finite_Set_card_interpreter",
  2665             "interpretation for set type is a leaf")
  2666         val size_of_nat = size_of_type thy model (Type ("nat", []))
  2667         (* takes an interpretation for a set and returns an interpretation *)
  2668         (* for a 'nat' denoting the set's cardinality                      *)
  2669         (* interpretation -> interpretation *)
  2670         fun card i =
  2671           let
  2672             val n = number_of_elements i
  2673           in
  2674             if n<size_of_nat then
  2675               Leaf ((replicate n False) @ True ::
  2676                 (replicate (size_of_nat-n-1) False))
  2677             else
  2678               Leaf (replicate size_of_nat False)
  2679           end
  2680         val set_constants =
  2681           make_constants thy model (Type ("fun", [T, Type ("bool", [])]))
  2682       in
  2683         SOME (Node (map card set_constants), model, args)
  2684       end
  2685     | _ =>
  2686       NONE;
  2687 
  2688   (* theory -> model -> arguments -> Term.term ->
  2689     (interpretation * model * arguments) option *)
  2690 
  2691   (* only an optimization: 'finite' could in principle be interpreted with  *)
  2692   (* interpreters available already (using its definition), but the code    *)
  2693   (* below is more efficient                                                *)
  2694 
  2695   fun Finite_Set_finite_interpreter thy model args t =
  2696     case t of
  2697       Const (@{const_name Finite_Set.finite},
  2698         Type ("fun", [Type ("fun", [T, Type ("bool", [])]),
  2699                       Type ("bool", [])])) $ _ =>
  2700         (* we only consider finite models anyway, hence EVERY set is *)
  2701         (* "finite"                                                  *)
  2702         SOME (TT, model, args)
  2703     | Const (@{const_name Finite_Set.finite},
  2704         Type ("fun", [Type ("fun", [T, Type ("bool", [])]),
  2705                       Type ("bool", [])])) =>
  2706       let
  2707         val size_of_set =
  2708           size_of_type thy model (Type ("fun", [T, Type ("bool", [])]))
  2709       in
  2710         (* we only consider finite models anyway, hence EVERY set is *)
  2711         (* "finite"                                                  *)
  2712         SOME (Node (replicate size_of_set TT), model, args)
  2713       end
  2714     | _ =>
  2715       NONE;
  2716 
  2717   (* theory -> model -> arguments -> Term.term ->
  2718     (interpretation * model * arguments) option *)
  2719 
  2720   (* only an optimization: 'less' could in principle be interpreted with *)
  2721   (* interpreters available already (using its definition), but the code     *)
  2722   (* below is more efficient                                                 *)
  2723 
  2724   fun Nat_less_interpreter thy model args t =
  2725     case t of
  2726       Const (@{const_name Orderings.less}, Type ("fun", [Type ("nat", []),
  2727         Type ("fun", [Type ("nat", []), Type ("bool", [])])])) =>
  2728       let
  2729         val size_of_nat = size_of_type thy model (Type ("nat", []))
  2730         (* the 'n'-th nat is not less than the first 'n' nats, while it *)
  2731         (* is less than the remaining 'size_of_nat - n' nats            *)
  2732         (* int -> interpretation *)
  2733         fun less n = Node ((replicate n FF) @ (replicate (size_of_nat - n) TT))
  2734       in
  2735         SOME (Node (map less (1 upto size_of_nat)), model, args)
  2736       end
  2737     | _ =>
  2738       NONE;
  2739 
  2740   (* theory -> model -> arguments -> Term.term ->
  2741     (interpretation * model * arguments) option *)
  2742 
  2743   (* only an optimization: 'plus' could in principle be interpreted with *)
  2744   (* interpreters available already (using its definition), but the code     *)
  2745   (* below is more efficient                                                 *)
  2746 
  2747   fun Nat_plus_interpreter thy model args t =
  2748     case t of
  2749       Const (@{const_name Groups.plus}, Type ("fun", [Type ("nat", []),
  2750         Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
  2751       let
  2752         val size_of_nat = size_of_type thy model (Type ("nat", []))
  2753         (* int -> int -> interpretation *)
  2754         fun plus m n =
  2755           let
  2756             val element = m + n
  2757           in
  2758             if element > size_of_nat - 1 then
  2759               Leaf (replicate size_of_nat False)
  2760             else
  2761               Leaf ((replicate element False) @ True ::
  2762                 (replicate (size_of_nat - element - 1) False))
  2763           end
  2764       in
  2765         SOME (Node (map_range (fn m => Node (map_range (plus m) size_of_nat)) size_of_nat),
  2766           model, args)
  2767       end
  2768     | _ =>
  2769       NONE;
  2770 
  2771   (* theory -> model -> arguments -> Term.term ->
  2772     (interpretation * model * arguments) option *)
  2773 
  2774   (* only an optimization: 'minus' could in principle be interpreted *)
  2775   (* with interpreters available already (using its definition), but the *)
  2776   (* code below is more efficient                                        *)
  2777 
  2778   fun Nat_minus_interpreter thy model args t =
  2779     case t of
  2780       Const (@{const_name Groups.minus}, Type ("fun", [Type ("nat", []),
  2781         Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
  2782       let
  2783         val size_of_nat = size_of_type thy model (Type ("nat", []))
  2784         (* int -> int -> interpretation *)
  2785         fun minus m n =
  2786           let
  2787             val element = Int.max (m-n, 0)
  2788           in
  2789             Leaf ((replicate element False) @ True ::
  2790               (replicate (size_of_nat - element - 1) False))
  2791           end
  2792       in
  2793         SOME (Node (map_range (fn m => Node (map_range (minus m) size_of_nat)) size_of_nat),
  2794           model, args)
  2795       end
  2796     | _ =>
  2797       NONE;
  2798 
  2799   (* theory -> model -> arguments -> Term.term ->
  2800     (interpretation * model * arguments) option *)
  2801 
  2802   (* only an optimization: 'times' could in principle be interpreted *)
  2803   (* with interpreters available already (using its definition), but the *)
  2804   (* code below is more efficient                                        *)
  2805 
  2806   fun Nat_times_interpreter thy model args t =
  2807     case t of
  2808       Const (@{const_name Groups.times}, Type ("fun", [Type ("nat", []),
  2809         Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
  2810       let
  2811         val size_of_nat = size_of_type thy model (Type ("nat", []))
  2812         (* nat -> nat -> interpretation *)
  2813         fun mult m n =
  2814           let
  2815             val element = m * n
  2816           in
  2817             if element > size_of_nat - 1 then
  2818               Leaf (replicate size_of_nat False)
  2819             else
  2820               Leaf ((replicate element False) @ True ::
  2821                 (replicate (size_of_nat - element - 1) False))
  2822           end
  2823       in
  2824         SOME (Node (map_range (fn m => Node (map_range (mult m) size_of_nat)) size_of_nat),
  2825           model, args)
  2826       end
  2827     | _ =>
  2828       NONE;
  2829 
  2830   (* theory -> model -> arguments -> Term.term ->
  2831     (interpretation * model * arguments) option *)
  2832 
  2833   (* only an optimization: 'append' could in principle be interpreted with *)
  2834   (* interpreters available already (using its definition), but the code   *)
  2835   (* below is more efficient                                               *)
  2836 
  2837   fun List_append_interpreter thy model args t =
  2838     case t of
  2839       Const (@{const_name List.append}, Type ("fun", [Type ("List.list", [T]), Type ("fun",
  2840         [Type ("List.list", [_]), Type ("List.list", [_])])])) =>
  2841       let
  2842         val size_elem   = size_of_type thy model T
  2843         val size_list   = size_of_type thy model (Type ("List.list", [T]))
  2844         (* maximal length of lists; 0 if we only consider the empty list *)
  2845         val list_length = let
  2846             (* int -> int -> int -> int *)
  2847             fun list_length_acc len lists total =
  2848               if lists = total then
  2849                 len
  2850               else if lists < total then
  2851                 list_length_acc (len+1) (lists*size_elem) (total-lists)
  2852               else
  2853                 raise REFUTE ("List_append_interpreter",
  2854                   "size_list not equal to 1 + size_elem + ... + " ^
  2855                     "size_elem^len, for some len")
  2856           in
  2857             list_length_acc 0 1 size_list
  2858           end
  2859         val elements = 0 upto (size_list-1)
  2860         (* FIXME: there should be a nice formula, which computes the same as *)
  2861         (*        the following, but without all this intermediate tree      *)
  2862         (*        length/offset stuff                                        *)
  2863         (* associate each list with its length and offset in a complete tree *)
  2864         (* of width 'size_elem' and depth 'length_list' (with 'size_list'    *)
  2865         (* nodes total)                                                      *)
  2866         (* (int * (int * int)) list *)
  2867         val (lenoff_lists, _) = fold_map (fn elem => fn (offsets, off) =>
  2868           (* corresponds to a pre-order traversal of the tree *)
  2869           let
  2870             val len = length offsets
  2871             (* associate the given element with len/off *)
  2872             val assoc = (elem, (len, off))
  2873           in
  2874             if len < list_length then
  2875               (* go to first child node *)
  2876               (assoc, (off :: offsets, off * size_elem))
  2877             else if off mod size_elem < size_elem - 1 then
  2878               (* go to next sibling node *)
  2879               (assoc, (offsets, off + 1))
  2880             else
  2881               (* go back up the stack until we find a level where we can go *)
  2882               (* to the next sibling node                                   *)
  2883               let
  2884                 val offsets' = dropwhile
  2885                   (fn off' => off' mod size_elem = size_elem - 1) offsets
  2886               in
  2887                 case offsets' of
  2888                   [] =>
  2889                   (* we're at the last node in the tree; the next value *)
  2890                   (* won't be used anyway                               *)
  2891                   (assoc, ([], 0))
  2892                 | off'::offs' =>
  2893                   (* go to next sibling node *)
  2894                   (assoc, (offs', off' + 1))
  2895               end
  2896           end) elements ([], 0)
  2897         (* we also need the reverse association (from length/offset to *)
  2898         (* index)                                                      *)
  2899         val lenoff'_lists = map Library.swap lenoff_lists
  2900         (* returns the interpretation for "(list no. m) @ (list no. n)" *)
  2901         (* nat -> nat -> interpretation *)
  2902         fun append m n =
  2903           let
  2904             val (len_m, off_m) = the (AList.lookup (op =) lenoff_lists m)
  2905             val (len_n, off_n) = the (AList.lookup (op =) lenoff_lists n)
  2906             val len_elem = len_m + len_n
  2907             val off_elem = off_m * power (size_elem, len_n) + off_n
  2908           in
  2909             case AList.lookup op= lenoff'_lists (len_elem, off_elem)  of
  2910               NONE =>
  2911               (* undefined *)
  2912               Leaf (replicate size_list False)
  2913             | SOME element =>
  2914               Leaf ((replicate element False) @ True ::
  2915                 (replicate (size_list - element - 1) False))
  2916           end
  2917       in
  2918         SOME (Node (map (fn m => Node (map (append m) elements)) elements),
  2919           model, args)
  2920       end
  2921     | _ =>
  2922       NONE;
  2923 
  2924 (* UNSOUND
  2925 
  2926   (* theory -> model -> arguments -> Term.term ->
  2927     (interpretation * model * arguments) option *)
  2928 
  2929   (* only an optimization: 'lfp' could in principle be interpreted with  *)
  2930   (* interpreters available already (using its definition), but the code *)
  2931   (* below is more efficient                                             *)
  2932 
  2933   fun lfp_interpreter thy model args t =
  2934     case t of
  2935       Const (@{const_name lfp}, Type ("fun", [Type ("fun",
  2936         [Type ("fun", [T, Type ("bool", [])]),
  2937          Type ("fun", [_, Type ("bool", [])])]),
  2938          Type ("fun", [_, Type ("bool", [])])])) =>
  2939       let
  2940         val size_elem = size_of_type thy model T
  2941         (* the universe (i.e. the set that contains every element) *)
  2942         val i_univ = Node (replicate size_elem TT)
  2943         (* all sets with elements from type 'T' *)
  2944         val i_sets =
  2945           make_constants thy model (Type ("fun", [T, Type ("bool", [])]))
  2946         (* all functions that map sets to sets *)
  2947         val i_funs = make_constants thy model (Type ("fun",
  2948           [Type ("fun", [T, Type ("bool", [])]),
  2949            Type ("fun", [T, Type ("bool", [])])]))
  2950         (* "lfp(f) == Inter({u. f(u) <= u})" *)
  2951         (* interpretation * interpretation -> bool *)
  2952         fun is_subset (Node subs, Node sups) =
  2953           List.all (fn (sub, sup) => (sub = FF) orelse (sup = TT))
  2954             (subs ~~ sups)
  2955           | is_subset (_, _) =
  2956           raise REFUTE ("lfp_interpreter",
  2957             "is_subset: interpretation for set is not a node")
  2958         (* interpretation * interpretation -> interpretation *)
  2959         fun intersection (Node xs, Node ys) =
  2960           Node (map (fn (x, y) => if x=TT andalso y=TT then TT else FF)
  2961             (xs ~~ ys))
  2962           | intersection (_, _) =
  2963           raise REFUTE ("lfp_interpreter",
  2964             "intersection: interpretation for set is not a node")
  2965         (* interpretation -> interpretaion *)
  2966         fun lfp (Node resultsets) =
  2967           fold (fn (set, resultset) => fn acc =>
  2968             if is_subset (resultset, set) then
  2969               intersection (acc, set)
  2970             else
  2971               acc) (i_sets ~~ resultsets) i_univ
  2972           | lfp _ =
  2973             raise REFUTE ("lfp_interpreter",
  2974               "lfp: interpretation for function is not a node")
  2975       in
  2976         SOME (Node (map lfp i_funs), model, args)
  2977       end
  2978     | _ =>
  2979       NONE;
  2980 
  2981   (* theory -> model -> arguments -> Term.term ->
  2982     (interpretation * model * arguments) option *)
  2983 
  2984   (* only an optimization: 'gfp' could in principle be interpreted with  *)
  2985   (* interpreters available already (using its definition), but the code *)
  2986   (* below is more efficient                                             *)
  2987 
  2988   fun gfp_interpreter thy model args t =
  2989     case t of
  2990       Const (@{const_name gfp}, Type ("fun", [Type ("fun",
  2991         [Type ("fun", [T, Type ("bool", [])]),
  2992          Type ("fun", [_, Type ("bool", [])])]),
  2993          Type ("fun", [_, Type ("bool", [])])])) =>
  2994       let
  2995         val size_elem = size_of_type thy model T
  2996         (* the universe (i.e. the set that contains every element) *)
  2997         val i_univ = Node (replicate size_elem TT)
  2998         (* all sets with elements from type 'T' *)
  2999         val i_sets =
  3000           make_constants thy model (Type ("fun", [T, Type ("bool", [])]))
  3001         (* all functions that map sets to sets *)
  3002         val i_funs = make_constants thy model (Type ("fun",
  3003           [Type ("fun", [T, Type ("bool", [])]),
  3004            Type ("fun", [T, Type ("bool", [])])]))
  3005         (* "gfp(f) == Union({u. u <= f(u)})" *)
  3006         (* interpretation * interpretation -> bool *)
  3007         fun is_subset (Node subs, Node sups) =
  3008           List.all (fn (sub, sup) => (sub = FF) orelse (sup = TT))
  3009             (subs ~~ sups)
  3010           | is_subset (_, _) =
  3011           raise REFUTE ("gfp_interpreter",
  3012             "is_subset: interpretation for set is not a node")
  3013         (* interpretation * interpretation -> interpretation *)
  3014         fun union (Node xs, Node ys) =
  3015             Node (map (fn (x,y) => if x=TT orelse y=TT then TT else FF)
  3016                  (xs ~~ ys))
  3017           | union (_, _) =
  3018           raise REFUTE ("gfp_interpreter",
  3019             "union: interpretation for set is not a node")
  3020         (* interpretation -> interpretaion *)
  3021         fun gfp (Node resultsets) =
  3022           fold (fn (set, resultset) => fn acc =>
  3023             if is_subset (set, resultset) then
  3024               union (acc, set)
  3025             else
  3026               acc) (i_sets ~~ resultsets) i_univ
  3027           | gfp _ =
  3028             raise REFUTE ("gfp_interpreter",
  3029               "gfp: interpretation for function is not a node")
  3030       in
  3031         SOME (Node (map gfp i_funs), model, args)
  3032       end
  3033     | _ =>
  3034       NONE;
  3035 *)
  3036 
  3037   (* theory -> model -> arguments -> Term.term ->
  3038     (interpretation * model * arguments) option *)
  3039 
  3040   (* only an optimization: 'fst' could in principle be interpreted with  *)
  3041   (* interpreters available already (using its definition), but the code *)
  3042   (* below is more efficient                                             *)
  3043 
  3044   fun Product_Type_fst_interpreter thy model args t =
  3045     case t of
  3046       Const (@{const_name fst}, Type ("fun", [Type ("*", [T, U]), _])) =>
  3047       let
  3048         val constants_T = make_constants thy model T
  3049         val size_U      = size_of_type thy model U
  3050       in
  3051         SOME (Node (maps (replicate size_U) constants_T), model, args)
  3052       end
  3053     | _ =>
  3054       NONE;
  3055 
  3056   (* theory -> model -> arguments -> Term.term ->
  3057     (interpretation * model * arguments) option *)
  3058 
  3059   (* only an optimization: 'snd' could in principle be interpreted with  *)
  3060   (* interpreters available already (using its definition), but the code *)
  3061   (* below is more efficient                                             *)
  3062 
  3063   fun Product_Type_snd_interpreter thy model args t =
  3064     case t of
  3065       Const (@{const_name snd}, Type ("fun", [Type ("*", [T, U]), _])) =>
  3066       let
  3067         val size_T      = size_of_type thy model T
  3068         val constants_U = make_constants thy model U
  3069       in
  3070         SOME (Node (flat (replicate size_T constants_U)), model, args)
  3071       end
  3072     | _ =>
  3073       NONE;
  3074 
  3075 
  3076 (* ------------------------------------------------------------------------- *)
  3077 (* PRINTERS                                                                  *)
  3078 (* ------------------------------------------------------------------------- *)
  3079 
  3080   (* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
  3081     Term.term option *)
  3082 
  3083   fun stlc_printer thy model T intr assignment =
  3084   let
  3085     (* string -> string *)
  3086     fun strip_leading_quote s =
  3087       (implode o (fn [] => [] | x::xs => if x="'" then xs else x::xs)
  3088         o explode) s
  3089     (* Term.typ -> string *)
  3090     fun string_of_typ (Type (s, _))     = s
  3091       | string_of_typ (TFree (x, _))    = strip_leading_quote x
  3092       | string_of_typ (TVar ((x,i), _)) =
  3093       strip_leading_quote x ^ string_of_int i
  3094     (* interpretation -> int *)
  3095     fun index_from_interpretation (Leaf xs) =
  3096       find_index (PropLogic.eval assignment) xs
  3097       | index_from_interpretation _ =
  3098       raise REFUTE ("stlc_printer",
  3099         "interpretation for ground type is not a leaf")
  3100   in
  3101     case T of
  3102       Type ("fun", [T1, T2]) =>
  3103       let
  3104         (* create all constants of type 'T1' *)
  3105         val constants = make_constants thy model T1
  3106         (* interpretation list *)
  3107         val results = (case intr of
  3108             Node xs => xs
  3109           | _       => raise REFUTE ("stlc_printer",
  3110             "interpretation for function type is a leaf"))
  3111         (* Term.term list *)
  3112         val pairs = map (fn (arg, result) =>
  3113           HOLogic.mk_prod
  3114             (print thy model T1 arg assignment,
  3115              print thy model T2 result assignment))
  3116           (constants ~~ results)
  3117         (* Term.typ *)
  3118         val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  3119         val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  3120         (* Term.term *)
  3121         val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
  3122         val HOLogic_insert    =
  3123           Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  3124       in
  3125         SOME (fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) pairs HOLogic_empty_set)
  3126       end
  3127     | Type ("prop", [])      =>
  3128       (case index_from_interpretation intr of
  3129         ~1 => SOME (HOLogic.mk_Trueprop (Const (@{const_name undefined}, HOLogic.boolT)))
  3130       | 0  => SOME (HOLogic.mk_Trueprop HOLogic.true_const)
  3131       | 1  => SOME (HOLogic.mk_Trueprop HOLogic.false_const)
  3132       | _  => raise REFUTE ("stlc_interpreter",
  3133         "illegal interpretation for a propositional value"))
  3134     | Type _  => if index_from_interpretation intr = (~1) then
  3135         SOME (Const (@{const_name undefined}, T))
  3136       else
  3137         SOME (Const (string_of_typ T ^
  3138           string_of_int (index_from_interpretation intr), T))
  3139     | TFree _ => if index_from_interpretation intr = (~1) then
  3140         SOME (Const (@{const_name undefined}, T))
  3141       else
  3142         SOME (Const (string_of_typ T ^
  3143           string_of_int (index_from_interpretation intr), T))
  3144     | TVar _  => if index_from_interpretation intr = (~1) then
  3145         SOME (Const (@{const_name undefined}, T))
  3146       else
  3147         SOME (Const (string_of_typ T ^
  3148           string_of_int (index_from_interpretation intr), T))
  3149   end;
  3150 
  3151   (* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
  3152     Term.term option *)
  3153 
  3154   fun IDT_printer thy model T intr assignment =
  3155     (case T of
  3156       Type (s, Ts) =>
  3157       (case Datatype.get_info thy s of
  3158         SOME info =>  (* inductive datatype *)
  3159         let
  3160           val (typs, _)           = model
  3161           val index               = #index info
  3162           val descr               = #descr info
  3163           val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  3164           val typ_assoc           = dtyps ~~ Ts
  3165           (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  3166           val _ = if Library.exists (fn d =>
  3167               case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  3168             then
  3169               raise REFUTE ("IDT_printer", "datatype argument (for type " ^
  3170                 Syntax.string_of_typ_global thy (Type (s, Ts)) ^ ") is not a variable")
  3171             else ()
  3172           (* the index of the element in the datatype *)
  3173           val element = (case intr of
  3174               Leaf xs => find_index (PropLogic.eval assignment) xs
  3175             | Node _  => raise REFUTE ("IDT_printer",
  3176               "interpretation is not a leaf"))
  3177         in
  3178           if element < 0 then
  3179             SOME (Const (@{const_name undefined}, Type (s, Ts)))
  3180           else let
  3181             (* takes a datatype constructor, and if for some arguments this  *)
  3182             (* constructor generates the datatype's element that is given by *)
  3183             (* 'element', returns the constructor (as a term) as well as the *)
  3184             (* indices of the arguments                                      *)
  3185             fun get_constr_args (cname, cargs) =
  3186               let
  3187                 val cTerm      = Const (cname,
  3188                   map (typ_of_dtyp descr typ_assoc) cargs ---> Type (s, Ts))
  3189                 val (iC, _, _) = interpret thy (typs, []) {maxvars=0,
  3190                   def_eq=false, next_idx=1, bounds=[], wellformed=True} cTerm
  3191                 (* interpretation -> int list option *)
  3192                 fun get_args (Leaf xs) =
  3193                   if find_index (fn x => x = True) xs = element then
  3194                     SOME []
  3195                   else
  3196                     NONE
  3197                   | get_args (Node xs) =
  3198                   let
  3199                     (* interpretation * int -> int list option *)
  3200                     fun search ([], _) =
  3201                       NONE
  3202                       | search (x::xs, n) =
  3203                       (case get_args x of
  3204                         SOME result => SOME (n::result)
  3205                       | NONE        => search (xs, n+1))
  3206                   in
  3207                     search (xs, 0)
  3208                   end
  3209               in
  3210                 Option.map (fn args => (cTerm, cargs, args)) (get_args iC)
  3211               end
  3212             val (cTerm, cargs, args) =
  3213               (* we could speed things up by computing the correct          *)
  3214               (* constructor directly (rather than testing all              *)
  3215               (* constructors), based on the order in which constructors    *)
  3216               (* generate elements of datatypes; the current implementation *)
  3217               (* of 'IDT_printer' however is independent of the internals   *)
  3218               (* of 'IDT_constructor_interpreter'                           *)
  3219               (case get_first get_constr_args constrs of
  3220                 SOME x => x
  3221               | NONE   => raise REFUTE ("IDT_printer",
  3222                 "no matching constructor found for element " ^
  3223                 string_of_int element))
  3224             val argsTerms = map (fn (d, n) =>
  3225               let
  3226                 val dT     = typ_of_dtyp descr typ_assoc d
  3227                 (* we only need the n-th element of this list, so there   *)
  3228                 (* might be a more efficient implementation that does not *)
  3229                 (* generate all constants                                 *)
  3230                 val consts = make_constants thy (typs, []) dT
  3231               in
  3232                 print thy (typs, []) dT (List.nth (consts, n)) assignment
  3233               end) (cargs ~~ args)
  3234           in
  3235             SOME (list_comb (cTerm, argsTerms))
  3236           end
  3237         end
  3238       | NONE =>  (* not an inductive datatype *)
  3239         NONE)
  3240     | _ =>  (* a (free or schematic) type variable *)
  3241       NONE);
  3242 
  3243 
  3244 (* ------------------------------------------------------------------------- *)
  3245 (* use 'setup Refute.setup' in an Isabelle theory to initialize the 'Refute' *)
  3246 (* structure                                                                 *)
  3247 (* ------------------------------------------------------------------------- *)
  3248 
  3249 (* ------------------------------------------------------------------------- *)
  3250 (* Note: the interpreters and printers are used in reverse order; however,   *)
  3251 (*       an interpreter that can handle non-atomic terms ends up being       *)
  3252 (*       applied before the 'stlc_interpreter' breaks the term apart into    *)
  3253 (*       subterms that are then passed to other interpreters!                *)
  3254 (* ------------------------------------------------------------------------- *)
  3255 
  3256   val setup =
  3257      add_interpreter "stlc"    stlc_interpreter #>
  3258      add_interpreter "Pure"    Pure_interpreter #>
  3259      add_interpreter "HOLogic" HOLogic_interpreter #>
  3260      add_interpreter "set"     set_interpreter #>
  3261      add_interpreter "IDT"             IDT_interpreter #>
  3262      add_interpreter "IDT_constructor" IDT_constructor_interpreter #>
  3263      add_interpreter "IDT_recursion"   IDT_recursion_interpreter #>
  3264      add_interpreter "Finite_Set.card"    Finite_Set_card_interpreter #>
  3265      add_interpreter "Finite_Set.finite"  Finite_Set_finite_interpreter #>
  3266      add_interpreter "Nat_Orderings.less" Nat_less_interpreter #>
  3267      add_interpreter "Nat_HOL.plus"       Nat_plus_interpreter #>
  3268      add_interpreter "Nat_HOL.minus"      Nat_minus_interpreter #>
  3269      add_interpreter "Nat_HOL.times"      Nat_times_interpreter #>
  3270      add_interpreter "List.append" List_append_interpreter #>
  3271 (* UNSOUND
  3272      add_interpreter "lfp" lfp_interpreter #>
  3273      add_interpreter "gfp" gfp_interpreter #>
  3274 *)
  3275      add_interpreter "fst" Product_Type_fst_interpreter #>
  3276      add_interpreter "snd" Product_Type_snd_interpreter #>
  3277      add_printer "stlc" stlc_printer #>
  3278      add_printer "IDT"  IDT_printer;
  3279 
  3280 end  (* structure Refute *)