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