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