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