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