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