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