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