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