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