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