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