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