merged
authorwenzelm
Fri Sep 03 12:01:47 2010 +0200 (2010-09-03)
changeset 391053b9e020c3908
parent 39104 7430f17fd80e
parent 39052 b8b075f80a1b
child 39113 91ba394cc525
merged
NEWS
     1.1 --- a/NEWS	Fri Sep 03 08:13:28 2010 +0200
     1.2 +++ b/NEWS	Fri Sep 03 12:01:47 2010 +0200
     1.3 @@ -37,8 +37,9 @@
     1.4    Thy_Output.break          thy_output_break
     1.5  
     1.6    show_question_marks       show_question_marks
     1.7 -
     1.8 -Note that the corresponding "..._default" references may be only
     1.9 +  show_consts               show_consts
    1.10 +
    1.11 +Note that the corresponding "..._default" references in ML may be only
    1.12  changed globally at the ROOT session setup, but *not* within a theory.
    1.13  
    1.14  
     2.1 --- a/doc-src/IsarRef/Thy/Inner_Syntax.thy	Fri Sep 03 08:13:28 2010 +0200
     2.2 +++ b/doc-src/IsarRef/Thy/Inner_Syntax.thy	Fri Sep 03 12:01:47 2010 +0200
     2.3 @@ -98,7 +98,7 @@
     2.4    \begin{mldecls} 
     2.5      @{index_ML show_types: "bool Unsynchronized.ref"} & default @{ML false} \\
     2.6      @{index_ML show_sorts: "bool Unsynchronized.ref"} & default @{ML false} \\
     2.7 -    @{index_ML show_consts: "bool Unsynchronized.ref"} & default @{ML false} \\
     2.8 +    @{index_ML show_consts: "bool Config.T"} & default @{ML false} \\
     2.9      @{index_ML long_names: "bool Unsynchronized.ref"} & default @{ML false} \\
    2.10      @{index_ML short_names: "bool Unsynchronized.ref"} & default @{ML false} \\
    2.11      @{index_ML unique_names: "bool Unsynchronized.ref"} & default @{ML true} \\
     3.1 --- a/doc-src/IsarRef/Thy/document/Inner_Syntax.tex	Fri Sep 03 08:13:28 2010 +0200
     3.2 +++ b/doc-src/IsarRef/Thy/document/Inner_Syntax.tex	Fri Sep 03 12:01:47 2010 +0200
     3.3 @@ -120,7 +120,7 @@
     3.4  \begin{mldecls} 
     3.5      \indexdef{}{ML}{show\_types}\verb|show_types: bool Unsynchronized.ref| & default \verb|false| \\
     3.6      \indexdef{}{ML}{show\_sorts}\verb|show_sorts: bool Unsynchronized.ref| & default \verb|false| \\
     3.7 -    \indexdef{}{ML}{show\_consts}\verb|show_consts: bool Unsynchronized.ref| & default \verb|false| \\
     3.8 +    \indexdef{}{ML}{show\_consts}\verb|show_consts: bool Config.T| & default \verb|false| \\
     3.9      \indexdef{}{ML}{long\_names}\verb|long_names: bool Unsynchronized.ref| & default \verb|false| \\
    3.10      \indexdef{}{ML}{short\_names}\verb|short_names: bool Unsynchronized.ref| & default \verb|false| \\
    3.11      \indexdef{}{ML}{unique\_names}\verb|unique_names: bool Unsynchronized.ref| & default \verb|true| \\
     4.1 --- a/src/HOL/IsaMakefile	Fri Sep 03 08:13:28 2010 +0200
     4.2 +++ b/src/HOL/IsaMakefile	Fri Sep 03 12:01:47 2010 +0200
     4.3 @@ -209,7 +209,6 @@
     4.4    Tools/primrec.ML \
     4.5    Tools/prop_logic.ML \
     4.6    Tools/refute.ML \
     4.7 -  Tools/refute_isar.ML \
     4.8    Tools/rewrite_hol_proof.ML \
     4.9    Tools/sat_funcs.ML \
    4.10    Tools/sat_solver.ML \
     5.1 --- a/src/HOL/Refute.thy	Fri Sep 03 08:13:28 2010 +0200
     5.2 +++ b/src/HOL/Refute.thy	Fri Sep 03 12:01:47 2010 +0200
     5.3 @@ -9,9 +9,7 @@
     5.4  
     5.5  theory Refute
     5.6  imports Hilbert_Choice List
     5.7 -uses
     5.8 -  "Tools/refute.ML"
     5.9 -  "Tools/refute_isar.ML"
    5.10 +uses "Tools/refute.ML"
    5.11  begin
    5.12  
    5.13  setup Refute.setup
    5.14 @@ -92,16 +90,14 @@
    5.15  (* ------------------------------------------------------------------------- *)
    5.16  (* FILES                                                                     *)
    5.17  (*                                                                           *)
    5.18 -(* HOL/Tools/prop_logic.ML    Propositional logic                            *)
    5.19 -(* HOL/Tools/sat_solver.ML    SAT solvers                                    *)
    5.20 -(* HOL/Tools/refute.ML        Translation HOL -> propositional logic and     *)
    5.21 -(*                            Boolean assignment -> HOL model                *)
    5.22 -(* HOL/Tools/refute_isar.ML   Adds 'refute'/'refute_params' to Isabelle's    *)
    5.23 -(*                            syntax                                         *)
    5.24 -(* HOL/Refute.thy             This file: loads the ML files, basic setup,    *)
    5.25 -(*                            documentation                                  *)
    5.26 -(* HOL/SAT.thy                Sets default parameters                        *)
    5.27 -(* HOL/ex/RefuteExamples.thy  Examples                                       *)
    5.28 +(* HOL/Tools/prop_logic.ML     Propositional logic                           *)
    5.29 +(* HOL/Tools/sat_solver.ML     SAT solvers                                   *)
    5.30 +(* HOL/Tools/refute.ML         Translation HOL -> propositional logic and    *)
    5.31 +(*                             Boolean assignment -> HOL model               *)
    5.32 +(* HOL/Refute.thy              This file: loads the ML files, basic setup,   *)
    5.33 +(*                             documentation                                 *)
    5.34 +(* HOL/SAT.thy                 Sets default parameters                       *)
    5.35 +(* HOL/ex/Refute_Examples.thy  Examples                                      *)
    5.36  (* ------------------------------------------------------------------------- *)
    5.37  \end{verbatim}
    5.38  *}
     6.1 --- a/src/HOL/Tools/refute.ML	Fri Sep 03 08:13:28 2010 +0200
     6.2 +++ b/src/HOL/Tools/refute.ML	Fri Sep 03 12:01:47 2010 +0200
     6.3 @@ -25,34 +25,34 @@
     6.4  
     6.5    exception MAXVARS_EXCEEDED
     6.6  
     6.7 -  val add_interpreter : string -> (theory -> model -> arguments -> term ->
     6.8 +  val add_interpreter : string -> (Proof.context -> model -> arguments -> term ->
     6.9      (interpretation * model * arguments) option) -> theory -> theory
    6.10 -  val add_printer     : string -> (theory -> model -> typ ->
    6.11 +  val add_printer : string -> (Proof.context -> model -> typ ->
    6.12      interpretation -> (int -> bool) -> term option) -> theory -> theory
    6.13  
    6.14 -  val interpret : theory -> model -> arguments -> term ->
    6.15 +  val interpret : Proof.context -> model -> arguments -> term ->
    6.16      (interpretation * model * arguments)
    6.17  
    6.18 -  val print       : theory -> model -> typ -> interpretation -> (int -> bool) -> term
    6.19 -  val print_model : theory -> model -> (int -> bool) -> string
    6.20 +  val print : Proof.context -> model -> typ -> interpretation -> (int -> bool) -> term
    6.21 +  val print_model : Proof.context -> model -> (int -> bool) -> string
    6.22  
    6.23  (* ------------------------------------------------------------------------- *)
    6.24  (* Interface                                                                 *)
    6.25  (* ------------------------------------------------------------------------- *)
    6.26  
    6.27    val set_default_param  : (string * string) -> theory -> theory
    6.28 -  val get_default_param  : theory -> string -> string option
    6.29 -  val get_default_params : theory -> (string * string) list
    6.30 -  val actual_params      : theory -> (string * string) list -> params
    6.31 +  val get_default_param  : Proof.context -> string -> string option
    6.32 +  val get_default_params : Proof.context -> (string * string) list
    6.33 +  val actual_params      : Proof.context -> (string * string) list -> params
    6.34  
    6.35 -  val find_model : theory -> params -> term list -> term -> bool -> unit
    6.36 +  val find_model : Proof.context -> params -> term list -> term -> bool -> unit
    6.37  
    6.38    (* tries to find a model for a formula: *)
    6.39    val satisfy_term :
    6.40 -    theory -> (string * string) list -> term list -> term -> unit
    6.41 +    Proof.context -> (string * string) list -> term list -> term -> unit
    6.42    (* tries to find a model that refutes a formula: *)
    6.43    val refute_term :
    6.44 -    theory -> (string * string) list -> term list -> term -> unit
    6.45 +    Proof.context -> (string * string) list -> term list -> term -> unit
    6.46    val refute_goal :
    6.47      Proof.context -> (string * string) list -> thm -> int -> unit
    6.48  
    6.49 @@ -72,22 +72,23 @@
    6.50    val is_const_of_class: theory -> string * typ -> bool
    6.51    val string_of_typ : typ -> string
    6.52    val typ_of_dtyp : Datatype.descr -> (Datatype.dtyp * typ) list -> Datatype.dtyp -> typ
    6.53 -end;  (* signature REFUTE *)
    6.54 +end;
    6.55  
    6.56  structure Refute : REFUTE =
    6.57  struct
    6.58  
    6.59 -  open PropLogic;
    6.60 +open PropLogic;
    6.61  
    6.62 -  (* We use 'REFUTE' only for internal error conditions that should    *)
    6.63 -  (* never occur in the first place (i.e. errors caused by bugs in our *)
    6.64 -  (* code).  Otherwise (e.g. to indicate invalid input data) we use    *)
    6.65 -  (* 'error'.                                                          *)
    6.66 -  exception REFUTE of string * string;  (* ("in function", "cause") *)
    6.67 +(* We use 'REFUTE' only for internal error conditions that should    *)
    6.68 +(* never occur in the first place (i.e. errors caused by bugs in our *)
    6.69 +(* code).  Otherwise (e.g. to indicate invalid input data) we use    *)
    6.70 +(* 'error'.                                                          *)
    6.71 +exception REFUTE of string * string;  (* ("in function", "cause") *)
    6.72  
    6.73 -  (* should be raised by an interpreter when more variables would be *)
    6.74 -  (* required than allowed by 'maxvars'                              *)
    6.75 -  exception MAXVARS_EXCEEDED;
    6.76 +(* should be raised by an interpreter when more variables would be *)
    6.77 +(* required than allowed by 'maxvars'                              *)
    6.78 +exception MAXVARS_EXCEEDED;
    6.79 +
    6.80  
    6.81  (* ------------------------------------------------------------------------- *)
    6.82  (* TREES                                                                     *)
    6.83 @@ -98,20 +99,20 @@
    6.84  (*       of (lists of ...) elements                                          *)
    6.85  (* ------------------------------------------------------------------------- *)
    6.86  
    6.87 -  datatype 'a tree =
    6.88 -      Leaf of 'a
    6.89 -    | Node of ('a tree) list;
    6.90 +datatype 'a tree =
    6.91 +    Leaf of 'a
    6.92 +  | Node of ('a tree) list;
    6.93  
    6.94 -  (* ('a -> 'b) -> 'a tree -> 'b tree *)
    6.95 +(* ('a -> 'b) -> 'a tree -> 'b tree *)
    6.96  
    6.97 -  fun tree_map f tr =
    6.98 -    case tr of
    6.99 -      Leaf x  => Leaf (f x)
   6.100 -    | Node xs => Node (map (tree_map f) xs);
   6.101 +fun tree_map f tr =
   6.102 +  case tr of
   6.103 +    Leaf x  => Leaf (f x)
   6.104 +  | Node xs => Node (map (tree_map f) xs);
   6.105  
   6.106 -  (* ('a * 'b -> 'a) -> 'a * ('b tree) -> 'a *)
   6.107 +(* ('a * 'b -> 'a) -> 'a * ('b tree) -> 'a *)
   6.108  
   6.109 -  fun tree_foldl f =
   6.110 +fun tree_foldl f =
   6.111    let
   6.112      fun itl (e, Leaf x)  = f(e,x)
   6.113        | itl (e, Node xs) = Library.foldl (tree_foldl f) (e,xs)
   6.114 @@ -119,16 +120,16 @@
   6.115      itl
   6.116    end;
   6.117  
   6.118 -  (* 'a tree * 'b tree -> ('a * 'b) tree *)
   6.119 +(* 'a tree * 'b tree -> ('a * 'b) tree *)
   6.120  
   6.121 -  fun tree_pair (t1, t2) =
   6.122 -    case t1 of
   6.123 -      Leaf x =>
   6.124 +fun tree_pair (t1, t2) =
   6.125 +  case t1 of
   6.126 +    Leaf x =>
   6.127        (case t2 of
   6.128            Leaf y => Leaf (x,y)
   6.129          | Node _ => raise REFUTE ("tree_pair",
   6.130              "trees are of different height (second tree is higher)"))
   6.131 -    | Node xs =>
   6.132 +  | Node xs =>
   6.133        (case t2 of
   6.134            (* '~~' will raise an exception if the number of branches in   *)
   6.135            (* both trees is different at the current node                 *)
   6.136 @@ -160,68 +161,70 @@
   6.137  (*                       "unknown").                                         *)
   6.138  (* ------------------------------------------------------------------------- *)
   6.139  
   6.140 -  type params =
   6.141 -    {
   6.142 -      sizes    : (string * int) list,
   6.143 -      minsize  : int,
   6.144 -      maxsize  : int,
   6.145 -      maxvars  : int,
   6.146 -      maxtime  : int,
   6.147 -      satsolver: string,
   6.148 -      no_assms : bool,
   6.149 -      expect   : string
   6.150 -    };
   6.151 +type params =
   6.152 +  {
   6.153 +    sizes    : (string * int) list,
   6.154 +    minsize  : int,
   6.155 +    maxsize  : int,
   6.156 +    maxvars  : int,
   6.157 +    maxtime  : int,
   6.158 +    satsolver: string,
   6.159 +    no_assms : bool,
   6.160 +    expect   : string
   6.161 +  };
   6.162  
   6.163  (* ------------------------------------------------------------------------- *)
   6.164  (* interpretation: a term's interpretation is given by a variable of type    *)
   6.165  (*                 'interpretation'                                          *)
   6.166  (* ------------------------------------------------------------------------- *)
   6.167  
   6.168 -  type interpretation =
   6.169 -    prop_formula list tree;
   6.170 +type interpretation =
   6.171 +  prop_formula list tree;
   6.172  
   6.173  (* ------------------------------------------------------------------------- *)
   6.174  (* model: a model specifies the size of types and the interpretation of      *)
   6.175  (*        terms                                                              *)
   6.176  (* ------------------------------------------------------------------------- *)
   6.177  
   6.178 -  type model =
   6.179 -    (typ * int) list * (term * interpretation) list;
   6.180 +type model =
   6.181 +  (typ * int) list * (term * interpretation) list;
   6.182  
   6.183  (* ------------------------------------------------------------------------- *)
   6.184  (* arguments: additional arguments required during interpretation of terms   *)
   6.185  (* ------------------------------------------------------------------------- *)
   6.186  
   6.187 -  type arguments =
   6.188 -    {
   6.189 -      (* just passed unchanged from 'params': *)
   6.190 -      maxvars   : int,
   6.191 -      (* whether to use 'make_equality' or 'make_def_equality': *)
   6.192 -      def_eq    : bool,
   6.193 -      (* the following may change during the translation: *)
   6.194 -      next_idx  : int,
   6.195 -      bounds    : interpretation list,
   6.196 -      wellformed: prop_formula
   6.197 -    };
   6.198 +type arguments =
   6.199 +  {
   6.200 +    (* just passed unchanged from 'params': *)
   6.201 +    maxvars   : int,
   6.202 +    (* whether to use 'make_equality' or 'make_def_equality': *)
   6.203 +    def_eq    : bool,
   6.204 +    (* the following may change during the translation: *)
   6.205 +    next_idx  : int,
   6.206 +    bounds    : interpretation list,
   6.207 +    wellformed: prop_formula
   6.208 +  };
   6.209  
   6.210  
   6.211 -  structure RefuteData = Theory_Data
   6.212 -  (
   6.213 -    type T =
   6.214 -      {interpreters: (string * (theory -> model -> arguments -> term ->
   6.215 -        (interpretation * model * arguments) option)) list,
   6.216 -       printers: (string * (theory -> model -> typ -> interpretation ->
   6.217 -        (int -> bool) -> term option)) list,
   6.218 -       parameters: string Symtab.table};
   6.219 -    val empty = {interpreters = [], printers = [], parameters = Symtab.empty};
   6.220 -    val extend = I;
   6.221 -    fun merge
   6.222 -      ({interpreters = in1, printers = pr1, parameters = pa1},
   6.223 -       {interpreters = in2, printers = pr2, parameters = pa2}) : T =
   6.224 -      {interpreters = AList.merge (op =) (K true) (in1, in2),
   6.225 -       printers = AList.merge (op =) (K true) (pr1, pr2),
   6.226 -       parameters = Symtab.merge (op=) (pa1, pa2)};
   6.227 -  );
   6.228 +structure Data = Theory_Data
   6.229 +(
   6.230 +  type T =
   6.231 +    {interpreters: (string * (Proof.context -> model -> arguments -> term ->
   6.232 +      (interpretation * model * arguments) option)) list,
   6.233 +     printers: (string * (Proof.context -> model -> typ -> interpretation ->
   6.234 +      (int -> bool) -> term option)) list,
   6.235 +     parameters: string Symtab.table};
   6.236 +  val empty = {interpreters = [], printers = [], parameters = Symtab.empty};
   6.237 +  val extend = I;
   6.238 +  fun merge
   6.239 +    ({interpreters = in1, printers = pr1, parameters = pa1},
   6.240 +     {interpreters = in2, printers = pr2, parameters = pa2}) : T =
   6.241 +    {interpreters = AList.merge (op =) (K true) (in1, in2),
   6.242 +     printers = AList.merge (op =) (K true) (pr1, pr2),
   6.243 +     parameters = Symtab.merge (op=) (pa1, pa2)};
   6.244 +);
   6.245 +
   6.246 +val get_data = Data.get o ProofContext.theory_of;
   6.247  
   6.248  
   6.249  (* ------------------------------------------------------------------------- *)
   6.250 @@ -230,30 +233,24 @@
   6.251  (*            track of the interpretation of subterms                        *)
   6.252  (* ------------------------------------------------------------------------- *)
   6.253  
   6.254 -  (* theory -> model -> arguments -> Term.term ->
   6.255 -    (interpretation * model * arguments) *)
   6.256 -
   6.257 -  fun interpret thy model args t =
   6.258 -    case get_first (fn (_, f) => f thy model args t)
   6.259 -      (#interpreters (RefuteData.get thy)) of
   6.260 -      NONE   => raise REFUTE ("interpret",
   6.261 -        "no interpreter for term " ^ quote (Syntax.string_of_term_global thy t))
   6.262 -    | SOME x => x;
   6.263 +fun interpret ctxt model args t =
   6.264 +  case get_first (fn (_, f) => f ctxt model args t)
   6.265 +      (#interpreters (get_data ctxt)) of
   6.266 +    NONE => raise REFUTE ("interpret",
   6.267 +      "no interpreter for term " ^ quote (Syntax.string_of_term ctxt t))
   6.268 +  | SOME x => x;
   6.269  
   6.270  (* ------------------------------------------------------------------------- *)
   6.271  (* print: converts the interpretation 'intr', which must denote a term of    *)
   6.272  (*        type 'T', into a term using a suitable printer                     *)
   6.273  (* ------------------------------------------------------------------------- *)
   6.274  
   6.275 -  (* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
   6.276 -    Term.term *)
   6.277 -
   6.278 -  fun print thy model T intr assignment =
   6.279 -    case get_first (fn (_, f) => f thy model T intr assignment)
   6.280 -      (#printers (RefuteData.get thy)) of
   6.281 -      NONE   => raise REFUTE ("print",
   6.282 -        "no printer for type " ^ quote (Syntax.string_of_typ_global thy T))
   6.283 -    | SOME x => x;
   6.284 +fun print ctxt model T intr assignment =
   6.285 +  case get_first (fn (_, f) => f ctxt model T intr assignment)
   6.286 +      (#printers (get_data ctxt)) of
   6.287 +    NONE => raise REFUTE ("print",
   6.288 +      "no printer for type " ^ quote (Syntax.string_of_typ ctxt T))
   6.289 +  | SOME x => x;
   6.290  
   6.291  (* ------------------------------------------------------------------------- *)
   6.292  (* print_model: turns the model into a string, using a fixed interpretation  *)
   6.293 @@ -261,9 +258,7 @@
   6.294  (*              printers                                                     *)
   6.295  (* ------------------------------------------------------------------------- *)
   6.296  
   6.297 -  (* theory -> model -> (int -> bool) -> string *)
   6.298 -
   6.299 -  fun print_model thy model assignment =
   6.300 +fun print_model ctxt model assignment =
   6.301    let
   6.302      val (typs, terms) = model
   6.303      val typs_msg =
   6.304 @@ -271,10 +266,10 @@
   6.305          "empty universe (no type variables in term)\n"
   6.306        else
   6.307          "Size of types: " ^ commas (map (fn (T, i) =>
   6.308 -          Syntax.string_of_typ_global thy T ^ ": " ^ string_of_int i) typs) ^ "\n"
   6.309 +          Syntax.string_of_typ ctxt T ^ ": " ^ string_of_int i) typs) ^ "\n"
   6.310      val show_consts_msg =
   6.311 -      if not (!show_consts) andalso Library.exists (is_Const o fst) terms then
   6.312 -        "set \"show_consts\" to show the interpretation of constants\n"
   6.313 +      if not (Config.get ctxt show_consts) andalso Library.exists (is_Const o fst) terms then
   6.314 +        "enable \"show_consts\" to show the interpretation of constants\n"
   6.315        else
   6.316          ""
   6.317      val terms_msg =
   6.318 @@ -283,10 +278,10 @@
   6.319        else
   6.320          cat_lines (map_filter (fn (t, intr) =>
   6.321            (* print constants only if 'show_consts' is true *)
   6.322 -          if (!show_consts) orelse not (is_Const t) then
   6.323 -            SOME (Syntax.string_of_term_global thy t ^ ": " ^
   6.324 -              Syntax.string_of_term_global thy
   6.325 -                (print thy model (Term.type_of t) intr assignment))
   6.326 +          if Config.get ctxt show_consts orelse not (is_Const t) then
   6.327 +            SOME (Syntax.string_of_term ctxt t ^ ": " ^
   6.328 +              Syntax.string_of_term ctxt
   6.329 +                (print ctxt model (Term.type_of t) intr assignment))
   6.330            else
   6.331              NONE) terms) ^ "\n"
   6.332    in
   6.333 @@ -298,71 +293,49 @@
   6.334  (* PARAMETER MANAGEMENT                                                      *)
   6.335  (* ------------------------------------------------------------------------- *)
   6.336  
   6.337 -  (* string -> (theory -> model -> arguments -> Term.term ->
   6.338 -    (interpretation * model * arguments) option) -> theory -> theory *)
   6.339 -
   6.340 -  fun add_interpreter name f thy =
   6.341 -  let
   6.342 -    val {interpreters, printers, parameters} = RefuteData.get thy
   6.343 -  in
   6.344 -    case AList.lookup (op =) interpreters name of
   6.345 -      NONE   => RefuteData.put {interpreters = (name, f) :: interpreters,
   6.346 -      printers = printers, parameters = parameters} thy
   6.347 -    | SOME _ => error ("Interpreter " ^ name ^ " already declared")
   6.348 -  end;
   6.349 +fun add_interpreter name f = Data.map (fn {interpreters, printers, parameters} =>
   6.350 +  case AList.lookup (op =) interpreters name of
   6.351 +    NONE => {interpreters = (name, f) :: interpreters,
   6.352 +      printers = printers, parameters = parameters}
   6.353 +  | SOME _ => error ("Interpreter " ^ name ^ " already declared"));
   6.354  
   6.355 -  (* string -> (theory -> model -> Term.typ -> interpretation ->
   6.356 -    (int -> bool) -> Term.term option) -> theory -> theory *)
   6.357 -
   6.358 -  fun add_printer name f thy =
   6.359 -  let
   6.360 -    val {interpreters, printers, parameters} = RefuteData.get thy
   6.361 -  in
   6.362 -    case AList.lookup (op =) printers name of
   6.363 -      NONE   => RefuteData.put {interpreters = interpreters,
   6.364 -      printers = (name, f) :: printers, parameters = parameters} thy
   6.365 -    | SOME _ => error ("Printer " ^ name ^ " already declared")
   6.366 -  end;
   6.367 +fun add_printer name f = Data.map (fn {interpreters, printers, parameters} =>
   6.368 +  case AList.lookup (op =) printers name of
   6.369 +    NONE => {interpreters = interpreters,
   6.370 +      printers = (name, f) :: printers, parameters = parameters}
   6.371 +  | SOME _ => error ("Printer " ^ name ^ " already declared"));
   6.372  
   6.373  (* ------------------------------------------------------------------------- *)
   6.374 -(* set_default_param: stores the '(name, value)' pair in RefuteData's        *)
   6.375 +(* set_default_param: stores the '(name, value)' pair in Data's              *)
   6.376  (*                    parameter table                                        *)
   6.377  (* ------------------------------------------------------------------------- *)
   6.378  
   6.379 -  (* (string * string) -> theory -> theory *)
   6.380 -
   6.381 -  fun set_default_param (name, value) = RefuteData.map 
   6.382 -    (fn {interpreters, printers, parameters} =>
   6.383 -      {interpreters = interpreters, printers = printers,
   6.384 -        parameters = Symtab.update (name, value) parameters});
   6.385 +fun set_default_param (name, value) = Data.map
   6.386 +  (fn {interpreters, printers, parameters} =>
   6.387 +    {interpreters = interpreters, printers = printers,
   6.388 +      parameters = Symtab.update (name, value) parameters});
   6.389  
   6.390  (* ------------------------------------------------------------------------- *)
   6.391  (* get_default_param: retrieves the value associated with 'name' from        *)
   6.392 -(*                    RefuteData's parameter table                           *)
   6.393 +(*                    Data's parameter table                                 *)
   6.394  (* ------------------------------------------------------------------------- *)
   6.395  
   6.396 -  (* theory -> string -> string option *)
   6.397 -
   6.398 -  val get_default_param = Symtab.lookup o #parameters o RefuteData.get;
   6.399 +val get_default_param = Symtab.lookup o #parameters o get_data;
   6.400  
   6.401  (* ------------------------------------------------------------------------- *)
   6.402  (* get_default_params: returns a list of all '(name, value)' pairs that are  *)
   6.403 -(*                     stored in RefuteData's parameter table                *)
   6.404 +(*                     stored in Data's parameter table                      *)
   6.405  (* ------------------------------------------------------------------------- *)
   6.406  
   6.407 -  (* theory -> (string * string) list *)
   6.408 -
   6.409 -  val get_default_params = Symtab.dest o #parameters o RefuteData.get;
   6.410 +val get_default_params = Symtab.dest o #parameters o get_data;
   6.411  
   6.412  (* ------------------------------------------------------------------------- *)
   6.413  (* actual_params: takes a (possibly empty) list 'params' of parameters that  *)
   6.414 -(*      override the default parameters currently specified in 'thy', and    *)
   6.415 +(*      override the default parameters currently specified, and             *)
   6.416  (*      returns a record that can be passed to 'find_model'.                 *)
   6.417  (* ------------------------------------------------------------------------- *)
   6.418  
   6.419 -  (* theory -> (string * string) list -> params *)
   6.420 -
   6.421 -  fun actual_params thy override =
   6.422 +fun actual_params ctxt override =
   6.423    let
   6.424      (* (string * string) list * string -> bool *)
   6.425      fun read_bool (parms, name) =
   6.426 @@ -370,32 +343,33 @@
   6.427          SOME "true" => true
   6.428        | SOME "false" => false
   6.429        | SOME s => error ("parameter " ^ quote name ^
   6.430 -        " (value is " ^ quote s ^ ") must be \"true\" or \"false\"")
   6.431 +          " (value is " ^ quote s ^ ") must be \"true\" or \"false\"")
   6.432        | NONE   => error ("parameter " ^ quote name ^
   6.433            " must be assigned a value")
   6.434      (* (string * string) list * string -> int *)
   6.435      fun read_int (parms, name) =
   6.436        case AList.lookup (op =) parms name of
   6.437 -        SOME s => (case Int.fromString s of
   6.438 -          SOME i => i
   6.439 -        | NONE   => error ("parameter " ^ quote name ^
   6.440 -          " (value is " ^ quote s ^ ") must be an integer value"))
   6.441 -      | NONE   => error ("parameter " ^ quote name ^
   6.442 +        SOME s =>
   6.443 +          (case Int.fromString s of
   6.444 +            SOME i => i
   6.445 +          | NONE   => error ("parameter " ^ quote name ^
   6.446 +            " (value is " ^ quote s ^ ") must be an integer value"))
   6.447 +      | NONE => error ("parameter " ^ quote name ^
   6.448            " must be assigned a value")
   6.449      (* (string * string) list * string -> string *)
   6.450      fun read_string (parms, name) =
   6.451        case AList.lookup (op =) parms name of
   6.452          SOME s => s
   6.453 -      | NONE   => error ("parameter " ^ quote name ^
   6.454 +      | NONE => error ("parameter " ^ quote name ^
   6.455          " must be assigned a value")
   6.456      (* 'override' first, defaults last: *)
   6.457      (* (string * string) list *)
   6.458 -    val allparams = override @ (get_default_params thy)
   6.459 +    val allparams = override @ get_default_params ctxt
   6.460      (* int *)
   6.461 -    val minsize   = read_int (allparams, "minsize")
   6.462 -    val maxsize   = read_int (allparams, "maxsize")
   6.463 -    val maxvars   = read_int (allparams, "maxvars")
   6.464 -    val maxtime   = read_int (allparams, "maxtime")
   6.465 +    val minsize = read_int (allparams, "minsize")
   6.466 +    val maxsize = read_int (allparams, "maxsize")
   6.467 +    val maxvars = read_int (allparams, "maxvars")
   6.468 +    val maxtime = read_int (allparams, "maxtime")
   6.469      (* string *)
   6.470      val satsolver = read_string (allparams, "satsolver")
   6.471      val no_assms = read_bool (allparams, "no_assms")
   6.472 @@ -405,7 +379,7 @@
   6.473      (* TODO: it is currently not possible to specify a size for a type    *)
   6.474      (*       whose name is one of the other parameters (e.g. 'maxvars')   *)
   6.475      (* (string * int) list *)
   6.476 -    val sizes     = map_filter
   6.477 +    val sizes = map_filter
   6.478        (fn (name, value) => Option.map (pair name) (Int.fromString value))
   6.479        (filter (fn (name, _) => name<>"minsize" andalso name<>"maxsize"
   6.480          andalso name<>"maxvars" andalso name<>"maxtime"
   6.481 @@ -420,25 +394,25 @@
   6.482  (* TRANSLATION HOL -> PROPOSITIONAL LOGIC, BOOLEAN ASSIGNMENT -> MODEL       *)
   6.483  (* ------------------------------------------------------------------------- *)
   6.484  
   6.485 -  fun typ_of_dtyp descr typ_assoc (Datatype_Aux.DtTFree a) =
   6.486 -    (* replace a 'DtTFree' variable by the associated type *)
   6.487 -    the (AList.lookup (op =) typ_assoc (Datatype_Aux.DtTFree a))
   6.488 -    | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtType (s, ds)) =
   6.489 -    Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   6.490 -    | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtRec i) =
   6.491 -    let
   6.492 -      val (s, ds, _) = the (AList.lookup (op =) descr i)
   6.493 -    in
   6.494 +fun typ_of_dtyp descr typ_assoc (Datatype_Aux.DtTFree a) =
   6.495 +      (* replace a 'DtTFree' variable by the associated type *)
   6.496 +      the (AList.lookup (op =) typ_assoc (Datatype_Aux.DtTFree a))
   6.497 +  | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtType (s, ds)) =
   6.498        Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   6.499 -    end;
   6.500 +  | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtRec i) =
   6.501 +      let
   6.502 +        val (s, ds, _) = the (AList.lookup (op =) descr i)
   6.503 +      in
   6.504 +        Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   6.505 +      end;
   6.506  
   6.507  (* ------------------------------------------------------------------------- *)
   6.508  (* close_form: universal closure over schematic variables in 't'             *)
   6.509  (* ------------------------------------------------------------------------- *)
   6.510  
   6.511 -  (* Term.term -> Term.term *)
   6.512 +(* Term.term -> Term.term *)
   6.513  
   6.514 -  fun close_form t =
   6.515 +fun close_form t =
   6.516    let
   6.517      (* (Term.indexname * Term.typ) list *)
   6.518      val vars = sort_wrt (fst o fst) (map dest_Var (OldTerm.term_vars t))
   6.519 @@ -455,9 +429,7 @@
   6.520  (*                    denotes membership to an axiomatic type class          *)
   6.521  (* ------------------------------------------------------------------------- *)
   6.522  
   6.523 -  (* theory -> string * Term.typ -> bool *)
   6.524 -
   6.525 -  fun is_const_of_class thy (s, T) =
   6.526 +fun is_const_of_class thy (s, T) =
   6.527    let
   6.528      val class_const_names = map Logic.const_of_class (Sign.all_classes thy)
   6.529    in
   6.530 @@ -471,28 +443,22 @@
   6.531  (*                     of an inductive datatype in 'thy'                     *)
   6.532  (* ------------------------------------------------------------------------- *)
   6.533  
   6.534 -  (* theory -> string * Term.typ -> bool *)
   6.535 -
   6.536 -  fun is_IDT_constructor thy (s, T) =
   6.537 -    (case body_type T of
   6.538 -      Type (s', _) =>
   6.539 +fun is_IDT_constructor thy (s, T) =
   6.540 +  (case body_type T of
   6.541 +    Type (s', _) =>
   6.542        (case Datatype.get_constrs thy s' of
   6.543          SOME constrs =>
   6.544 -        List.exists (fn (cname, cty) =>
   6.545 -          cname = s andalso Sign.typ_instance thy (T, cty)) constrs
   6.546 -      | NONE =>
   6.547 -        false)
   6.548 -    | _  =>
   6.549 -      false);
   6.550 +          List.exists (fn (cname, cty) =>
   6.551 +            cname = s andalso Sign.typ_instance thy (T, cty)) constrs
   6.552 +      | NONE => false)
   6.553 +  | _  => false);
   6.554  
   6.555  (* ------------------------------------------------------------------------- *)
   6.556  (* is_IDT_recursor: returns 'true' iff 'Const (s, T)' is the recursion       *)
   6.557  (*                  operator of an inductive datatype in 'thy'               *)
   6.558  (* ------------------------------------------------------------------------- *)
   6.559  
   6.560 -  (* theory -> string * Term.typ -> bool *)
   6.561 -
   6.562 -  fun is_IDT_recursor thy (s, T) =
   6.563 +fun is_IDT_recursor thy (s, T) =
   6.564    let
   6.565      val rec_names = Symtab.fold (append o #rec_names o snd)
   6.566        (Datatype.get_all thy) []
   6.567 @@ -506,12 +472,12 @@
   6.568  (* norm_rhs: maps  f ?t1 ... ?tn == rhs  to  %t1...tn. rhs                   *)
   6.569  (* ------------------------------------------------------------------------- *)
   6.570  
   6.571 -  fun norm_rhs eqn =
   6.572 +fun norm_rhs eqn =
   6.573    let
   6.574      fun lambda (v as Var ((x, _), T)) t = Abs (x, T, abstract_over (v, t))
   6.575 -      | lambda v t                      = raise TERM ("lambda", [v, t])
   6.576 +      | lambda v t = raise TERM ("lambda", [v, t])
   6.577      val (lhs, rhs) = Logic.dest_equals eqn
   6.578 -    val (_, args)  = Term.strip_comb lhs
   6.579 +    val (_, args) = Term.strip_comb lhs
   6.580    in
   6.581      fold lambda (rev args) rhs
   6.582    end
   6.583 @@ -520,31 +486,29 @@
   6.584  (* get_def: looks up the definition of a constant                            *)
   6.585  (* ------------------------------------------------------------------------- *)
   6.586  
   6.587 -  (* theory -> string * Term.typ -> (string * Term.term) option *)
   6.588 -
   6.589 -  fun get_def thy (s, T) =
   6.590 +fun get_def thy (s, T) =
   6.591    let
   6.592      (* (string * Term.term) list -> (string * Term.term) option *)
   6.593      fun get_def_ax [] = NONE
   6.594        | get_def_ax ((axname, ax) :: axioms) =
   6.595 -      (let
   6.596 -        val (lhs, _) = Logic.dest_equals ax  (* equations only *)
   6.597 -        val c        = Term.head_of lhs
   6.598 -        val (s', T') = Term.dest_Const c
   6.599 -      in
   6.600 -        if s=s' then
   6.601 -          let
   6.602 -            val typeSubs = Sign.typ_match thy (T', T) Vartab.empty
   6.603 -            val ax'      = monomorphic_term typeSubs ax
   6.604 -            val rhs      = norm_rhs ax'
   6.605 +          (let
   6.606 +            val (lhs, _) = Logic.dest_equals ax  (* equations only *)
   6.607 +            val c        = Term.head_of lhs
   6.608 +            val (s', T') = Term.dest_Const c
   6.609            in
   6.610 -            SOME (axname, rhs)
   6.611 -          end
   6.612 -        else
   6.613 -          get_def_ax axioms
   6.614 -      end handle ERROR _         => get_def_ax axioms
   6.615 -               | TERM _          => get_def_ax axioms
   6.616 -               | Type.TYPE_MATCH => get_def_ax axioms)
   6.617 +            if s=s' then
   6.618 +              let
   6.619 +                val typeSubs = Sign.typ_match thy (T', T) Vartab.empty
   6.620 +                val ax'      = monomorphic_term typeSubs ax
   6.621 +                val rhs      = norm_rhs ax'
   6.622 +              in
   6.623 +                SOME (axname, rhs)
   6.624 +              end
   6.625 +            else
   6.626 +              get_def_ax axioms
   6.627 +          end handle ERROR _         => get_def_ax axioms
   6.628 +                   | TERM _          => get_def_ax axioms
   6.629 +                   | Type.TYPE_MATCH => get_def_ax axioms)
   6.630    in
   6.631      get_def_ax (Theory.all_axioms_of thy)
   6.632    end;
   6.633 @@ -553,43 +517,40 @@
   6.634  (* get_typedef: looks up the definition of a type, as created by "typedef"   *)
   6.635  (* ------------------------------------------------------------------------- *)
   6.636  
   6.637 -  (* theory -> Term.typ -> (string * Term.term) option *)
   6.638 -
   6.639 -  fun get_typedef thy T =
   6.640 +fun get_typedef thy T =
   6.641    let
   6.642      (* (string * Term.term) list -> (string * Term.term) option *)
   6.643      fun get_typedef_ax [] = NONE
   6.644        | get_typedef_ax ((axname, ax) :: axioms) =
   6.645 -      (let
   6.646 -        (* Term.term -> Term.typ option *)
   6.647 -        fun type_of_type_definition (Const (s', T')) =
   6.648 -          if s'= @{const_name type_definition} then
   6.649 -            SOME T'
   6.650 -          else
   6.651 -            NONE
   6.652 -          | type_of_type_definition (Free _)           = NONE
   6.653 -          | type_of_type_definition (Var _)            = NONE
   6.654 -          | type_of_type_definition (Bound _)          = NONE
   6.655 -          | type_of_type_definition (Abs (_, _, body)) =
   6.656 -          type_of_type_definition body
   6.657 -          | type_of_type_definition (t1 $ t2)          =
   6.658 -          (case type_of_type_definition t1 of
   6.659 -            SOME x => SOME x
   6.660 -          | NONE   => type_of_type_definition t2)
   6.661 -      in
   6.662 -        case type_of_type_definition ax of
   6.663 -          SOME T' =>
   6.664 -          let
   6.665 -            val T''      = (domain_type o domain_type) T'
   6.666 -            val typeSubs = Sign.typ_match thy (T'', T) Vartab.empty
   6.667 +          (let
   6.668 +            (* Term.term -> Term.typ option *)
   6.669 +            fun type_of_type_definition (Const (s', T')) =
   6.670 +                  if s'= @{const_name type_definition} then
   6.671 +                    SOME T'
   6.672 +                  else
   6.673 +                    NONE
   6.674 +              | type_of_type_definition (Free _) = NONE
   6.675 +              | type_of_type_definition (Var _) = NONE
   6.676 +              | type_of_type_definition (Bound _) = NONE
   6.677 +              | type_of_type_definition (Abs (_, _, body)) =
   6.678 +                  type_of_type_definition body
   6.679 +              | type_of_type_definition (t1 $ t2) =
   6.680 +                  (case type_of_type_definition t1 of
   6.681 +                    SOME x => SOME x
   6.682 +                  | NONE => type_of_type_definition t2)
   6.683            in
   6.684 -            SOME (axname, monomorphic_term typeSubs ax)
   6.685 -          end
   6.686 -        | NONE =>
   6.687 -          get_typedef_ax axioms
   6.688 -      end handle ERROR _         => get_typedef_ax axioms
   6.689 -               | TERM _          => get_typedef_ax axioms
   6.690 -               | Type.TYPE_MATCH => get_typedef_ax axioms)
   6.691 +            case type_of_type_definition ax of
   6.692 +              SOME T' =>
   6.693 +                let
   6.694 +                  val T'' = domain_type (domain_type T')
   6.695 +                  val typeSubs = Sign.typ_match thy (T'', T) Vartab.empty
   6.696 +                in
   6.697 +                  SOME (axname, monomorphic_term typeSubs ax)
   6.698 +                end
   6.699 +            | NONE => get_typedef_ax axioms
   6.700 +          end handle ERROR _         => get_typedef_ax axioms
   6.701 +                   | TERM _          => get_typedef_ax axioms
   6.702 +                   | Type.TYPE_MATCH => get_typedef_ax axioms)
   6.703    in
   6.704      get_typedef_ax (Theory.all_axioms_of thy)
   6.705    end;
   6.706 @@ -599,9 +560,7 @@
   6.707  (*               created by the "axclass" command                            *)
   6.708  (* ------------------------------------------------------------------------- *)
   6.709  
   6.710 -  (* theory -> string -> (string * Term.term) option *)
   6.711 -
   6.712 -  fun get_classdef thy class =
   6.713 +fun get_classdef thy class =
   6.714    let
   6.715      val axname = class ^ "_class_def"
   6.716    in
   6.717 @@ -617,15 +576,13 @@
   6.718  (*              that definition does not need to be unfolded                 *)
   6.719  (* ------------------------------------------------------------------------- *)
   6.720  
   6.721 -  (* theory -> Term.term -> Term.term *)
   6.722 +(* Note: we could intertwine unfolding of constants and beta-(eta-)       *)
   6.723 +(*       normalization; this would save some unfolding for terms where    *)
   6.724 +(*       constants are eliminated by beta-reduction (e.g. 'K c1 c2').  On *)
   6.725 +(*       the other hand, this would cause additional work for terms where *)
   6.726 +(*       constants are duplicated by beta-reduction (e.g. 'S c1 c2 c3').  *)
   6.727  
   6.728 -  (* Note: we could intertwine unfolding of constants and beta-(eta-)       *)
   6.729 -  (*       normalization; this would save some unfolding for terms where    *)
   6.730 -  (*       constants are eliminated by beta-reduction (e.g. 'K c1 c2').  On *)
   6.731 -  (*       the other hand, this would cause additional work for terms where *)
   6.732 -  (*       constants are duplicated by beta-reduction (e.g. 'S c1 c2 c3').  *)
   6.733 -
   6.734 -  fun unfold_defs thy t =
   6.735 +fun unfold_defs thy t =
   6.736    let
   6.737      (* Term.term -> Term.term *)
   6.738      fun unfold_loop t =
   6.739 @@ -658,13 +615,13 @@
   6.740        | Const (@{const_name Finite_Set.card}, _) => t
   6.741        | Const (@{const_name Finite_Set.finite}, _) => t
   6.742        | Const (@{const_name Orderings.less}, Type ("fun", [@{typ nat},
   6.743 -        Type ("fun", [@{typ nat}, @{typ bool}])])) => t
   6.744 +          Type ("fun", [@{typ nat}, @{typ bool}])])) => t
   6.745        | Const (@{const_name Groups.plus}, Type ("fun", [@{typ nat},
   6.746 -        Type ("fun", [@{typ nat}, @{typ nat}])])) => t
   6.747 +          Type ("fun", [@{typ nat}, @{typ nat}])])) => t
   6.748        | Const (@{const_name Groups.minus}, Type ("fun", [@{typ nat},
   6.749 -        Type ("fun", [@{typ nat}, @{typ nat}])])) => t
   6.750 +          Type ("fun", [@{typ nat}, @{typ nat}])])) => t
   6.751        | Const (@{const_name Groups.times}, Type ("fun", [@{typ nat},
   6.752 -        Type ("fun", [@{typ nat}, @{typ nat}])])) => t
   6.753 +          Type ("fun", [@{typ nat}, @{typ nat}])])) => t
   6.754        | Const (@{const_name List.append}, _) => t
   6.755  (* UNSOUND
   6.756        | Const (@{const_name lfp}, _) => t
   6.757 @@ -674,27 +631,28 @@
   6.758        | Const (@{const_name snd}, _) => t
   6.759        (* simply-typed lambda calculus *)
   6.760        | Const (s, T) =>
   6.761 -        (if is_IDT_constructor thy (s, T)
   6.762 -          orelse is_IDT_recursor thy (s, T) then
   6.763 -          t  (* do not unfold IDT constructors/recursors *)
   6.764 -        (* unfold the constant if there is a defining equation *)
   6.765 -        else case get_def thy (s, T) of
   6.766 -          SOME (axname, rhs) =>
   6.767 -          (* Note: if the term to be unfolded (i.e. 'Const (s, T)')  *)
   6.768 -          (* occurs on the right-hand side of the equation, i.e. in  *)
   6.769 -          (* 'rhs', we must not use this equation to unfold, because *)
   6.770 -          (* that would loop.  Here would be the right place to      *)
   6.771 -          (* check this.  However, getting this really right seems   *)
   6.772 -          (* difficult because the user may state arbitrary axioms,  *)
   6.773 -          (* which could interact with overloading to create loops.  *)
   6.774 -          ((*tracing (" unfolding: " ^ axname);*)
   6.775 -           unfold_loop rhs)
   6.776 -        | NONE => t)
   6.777 -      | Free _           => t
   6.778 -      | Var _            => t
   6.779 -      | Bound _          => t
   6.780 +          (if is_IDT_constructor thy (s, T)
   6.781 +            orelse is_IDT_recursor thy (s, T) then
   6.782 +            t  (* do not unfold IDT constructors/recursors *)
   6.783 +          (* unfold the constant if there is a defining equation *)
   6.784 +          else
   6.785 +            case get_def thy (s, T) of
   6.786 +              SOME (axname, rhs) =>
   6.787 +              (* Note: if the term to be unfolded (i.e. 'Const (s, T)')  *)
   6.788 +              (* occurs on the right-hand side of the equation, i.e. in  *)
   6.789 +              (* 'rhs', we must not use this equation to unfold, because *)
   6.790 +              (* that would loop.  Here would be the right place to      *)
   6.791 +              (* check this.  However, getting this really right seems   *)
   6.792 +              (* difficult because the user may state arbitrary axioms,  *)
   6.793 +              (* which could interact with overloading to create loops.  *)
   6.794 +              ((*tracing (" unfolding: " ^ axname);*)
   6.795 +               unfold_loop rhs)
   6.796 +            | NONE => t)
   6.797 +      | Free _ => t
   6.798 +      | Var _ => t
   6.799 +      | Bound _ => t
   6.800        | Abs (s, T, body) => Abs (s, T, unfold_loop body)
   6.801 -      | t1 $ t2          => (unfold_loop t1) $ (unfold_loop t2)
   6.802 +      | t1 $ t2 => (unfold_loop t1) $ (unfold_loop t2)
   6.803      val result = Envir.beta_eta_contract (unfold_loop t)
   6.804    in
   6.805      result
   6.806 @@ -705,28 +663,27 @@
   6.807  (*                 versions of) all HOL axioms that are relevant w.r.t 't'   *)
   6.808  (* ------------------------------------------------------------------------- *)
   6.809  
   6.810 -  (* Note: to make the collection of axioms more easily extensible, this    *)
   6.811 -  (*       function could be based on user-supplied "axiom collectors",     *)
   6.812 -  (*       similar to 'interpret'/interpreters or 'print'/printers          *)
   6.813 +(* Note: to make the collection of axioms more easily extensible, this    *)
   6.814 +(*       function could be based on user-supplied "axiom collectors",     *)
   6.815 +(*       similar to 'interpret'/interpreters or 'print'/printers          *)
   6.816  
   6.817 -  (* Note: currently we use "inverse" functions to the definitional         *)
   6.818 -  (*       mechanisms provided by Isabelle/HOL, e.g. for "axclass",         *)
   6.819 -  (*       "typedef", "definition".  A more general approach could consider *)
   6.820 -  (*       *every* axiom of the theory and collect it if it has a constant/ *)
   6.821 -  (*       type/typeclass in common with the term 't'.                      *)
   6.822 +(* Note: currently we use "inverse" functions to the definitional         *)
   6.823 +(*       mechanisms provided by Isabelle/HOL, e.g. for "axclass",         *)
   6.824 +(*       "typedef", "definition".  A more general approach could consider *)
   6.825 +(*       *every* axiom of the theory and collect it if it has a constant/ *)
   6.826 +(*       type/typeclass in common with the term 't'.                      *)
   6.827  
   6.828 -  (* theory -> Term.term -> Term.term list *)
   6.829 +(* Which axioms are "relevant" for a particular term/type goes hand in    *)
   6.830 +(* hand with the interpretation of that term/type by its interpreter (see *)
   6.831 +(* way below): if the interpretation respects an axiom anyway, the axiom  *)
   6.832 +(* does not need to be added as a constraint here.                        *)
   6.833  
   6.834 -  (* Which axioms are "relevant" for a particular term/type goes hand in    *)
   6.835 -  (* hand with the interpretation of that term/type by its interpreter (see *)
   6.836 -  (* way below): if the interpretation respects an axiom anyway, the axiom  *)
   6.837 -  (* does not need to be added as a constraint here.                        *)
   6.838 +(* To avoid collecting the same axiom multiple times, we use an           *)
   6.839 +(* accumulator 'axs' which contains all axioms collected so far.          *)
   6.840  
   6.841 -  (* To avoid collecting the same axiom multiple times, we use an           *)
   6.842 -  (* accumulator 'axs' which contains all axioms collected so far.          *)
   6.843 -
   6.844 -  fun collect_axioms thy t =
   6.845 +fun collect_axioms ctxt t =
   6.846    let
   6.847 +    val thy = ProofContext.theory_of ctxt
   6.848      val _ = tracing "Adding axioms..."
   6.849      val axioms = Theory.all_axioms_of thy
   6.850      fun collect_this_axiom (axname, ax) axs =
   6.851 @@ -743,7 +700,7 @@
   6.852              TFree (_, sort) => sort
   6.853            | TVar (_, sort)  => sort
   6.854            | _ => raise REFUTE ("collect_axioms",
   6.855 -              "type " ^ Syntax.string_of_typ_global thy T ^ " is not a variable"))
   6.856 +              "type " ^ Syntax.string_of_typ ctxt T ^ " is not a variable"))
   6.857          (* obtain axioms for all superclasses *)
   6.858          val superclasses = sort @ maps (Sign.super_classes thy) sort
   6.859          (* merely an optimization, because 'collect_this_axiom' disallows *)
   6.860 @@ -761,7 +718,7 @@
   6.861            | [(idx, S)] => (axname, monomorphic_term (Vartab.make [(idx, (S, T))]) ax)
   6.862            | _ =>
   6.863              raise REFUTE ("collect_axioms", "class axiom " ^ axname ^ " (" ^
   6.864 -              Syntax.string_of_term_global thy ax ^
   6.865 +              Syntax.string_of_term ctxt ax ^
   6.866                ") contains more than one type variable")))
   6.867            class_axioms
   6.868        in
   6.869 @@ -782,7 +739,7 @@
   6.870          | NONE =>
   6.871            (case get_typedef thy T of
   6.872              SOME (axname, ax) =>
   6.873 -            collect_this_axiom (axname, ax) axs
   6.874 +              collect_this_axiom (axname, ax) axs
   6.875            | NONE =>
   6.876              (* unspecified type, perhaps introduced with "typedecl" *)
   6.877              (* at least collect relevant type axioms for the argument types *)
   6.878 @@ -808,19 +765,19 @@
   6.879        | Const (@{const_name False}, _) => axs
   6.880        | Const (@{const_name undefined}, T) => collect_type_axioms T axs
   6.881        | Const (@{const_name The}, T) =>
   6.882 -        let
   6.883 -          val ax = specialize_type thy (@{const_name The}, T)
   6.884 -            (the (AList.lookup (op =) axioms "HOL.the_eq_trivial"))
   6.885 -        in
   6.886 -          collect_this_axiom ("HOL.the_eq_trivial", ax) axs
   6.887 -        end
   6.888 +          let
   6.889 +            val ax = specialize_type thy (@{const_name The}, T)
   6.890 +              (the (AList.lookup (op =) axioms "HOL.the_eq_trivial"))
   6.891 +          in
   6.892 +            collect_this_axiom ("HOL.the_eq_trivial", ax) axs
   6.893 +          end
   6.894        | Const (@{const_name Hilbert_Choice.Eps}, T) =>
   6.895 -        let
   6.896 -          val ax = specialize_type thy (@{const_name Hilbert_Choice.Eps}, T)
   6.897 -            (the (AList.lookup (op =) axioms "Hilbert_Choice.someI"))
   6.898 -        in
   6.899 -          collect_this_axiom ("Hilbert_Choice.someI", ax) axs
   6.900 -        end
   6.901 +          let
   6.902 +            val ax = specialize_type thy (@{const_name Hilbert_Choice.Eps}, T)
   6.903 +              (the (AList.lookup (op =) axioms "Hilbert_Choice.someI"))
   6.904 +          in
   6.905 +            collect_this_axiom ("Hilbert_Choice.someI", ax) axs
   6.906 +          end
   6.907        | Const (@{const_name All}, T) => collect_type_axioms T axs
   6.908        | Const (@{const_name Ex}, T) => collect_type_axioms T axs
   6.909        | Const (@{const_name HOL.eq}, T) => collect_type_axioms T axs
   6.910 @@ -864,13 +821,14 @@
   6.911                val ax_in = SOME (specialize_type thy (s, T) of_class)
   6.912                  (* type match may fail due to sort constraints *)
   6.913                  handle Type.TYPE_MATCH => NONE
   6.914 -              val ax_1 = Option.map (fn ax => (Syntax.string_of_term_global thy ax, ax)) ax_in
   6.915 +              val ax_1 = Option.map (fn ax => (Syntax.string_of_term ctxt ax, ax)) ax_in
   6.916                val ax_2 = Option.map (apsnd (specialize_type thy (s, T))) (get_classdef thy class)
   6.917              in
   6.918                collect_type_axioms T (fold collect_this_axiom (map_filter I [ax_1, ax_2]) axs)
   6.919              end
   6.920            else if is_IDT_constructor thy (s, T)
   6.921 -            orelse is_IDT_recursor thy (s, T) then
   6.922 +            orelse is_IDT_recursor thy (s, T)
   6.923 +          then
   6.924              (* only collect relevant type axioms *)
   6.925              collect_type_axioms T axs
   6.926            else
   6.927 @@ -898,70 +856,71 @@
   6.928  (*               and all mutually recursive IDTs are considered.             *)
   6.929  (* ------------------------------------------------------------------------- *)
   6.930  
   6.931 -  fun ground_types thy t =
   6.932 +fun ground_types ctxt t =
   6.933    let
   6.934 +    val thy = ProofContext.theory_of ctxt
   6.935      fun collect_types T acc =
   6.936        (case T of
   6.937          Type ("fun", [T1, T2]) => collect_types T1 (collect_types T2 acc)
   6.938 -      | Type ("prop", [])      => acc
   6.939 -      | Type (s, Ts)           =>
   6.940 -        (case Datatype.get_info thy s of
   6.941 -          SOME info =>  (* inductive datatype *)
   6.942 -          let
   6.943 -            val index        = #index info
   6.944 -            val descr        = #descr info
   6.945 -            val (_, typs, _) = the (AList.lookup (op =) descr index)
   6.946 -            val typ_assoc    = typs ~~ Ts
   6.947 -            (* sanity check: every element in 'dtyps' must be a *)
   6.948 -            (* 'DtTFree'                                        *)
   6.949 -            val _ = if Library.exists (fn d =>
   6.950 -              case d of Datatype_Aux.DtTFree _ => false | _ => true) typs then
   6.951 -              raise REFUTE ("ground_types", "datatype argument (for type "
   6.952 -                ^ Syntax.string_of_typ_global thy T ^ ") is not a variable")
   6.953 -            else ()
   6.954 -            (* required for mutually recursive datatypes; those need to   *)
   6.955 -            (* be added even if they are an instance of an otherwise non- *)
   6.956 -            (* recursive datatype                                         *)
   6.957 -            fun collect_dtyp d acc =
   6.958 -            let
   6.959 -              val dT = typ_of_dtyp descr typ_assoc d
   6.960 -            in
   6.961 -              case d of
   6.962 -                Datatype_Aux.DtTFree _ =>
   6.963 -                collect_types dT acc
   6.964 -              | Datatype_Aux.DtType (_, ds) =>
   6.965 -                collect_types dT (fold_rev collect_dtyp ds acc)
   6.966 -              | Datatype_Aux.DtRec i =>
   6.967 -                if member (op =) acc dT then
   6.968 -                  acc  (* prevent infinite recursion *)
   6.969 -                else
   6.970 +      | Type ("prop", []) => acc
   6.971 +      | Type (s, Ts) =>
   6.972 +          (case Datatype.get_info thy s of
   6.973 +            SOME info =>  (* inductive datatype *)
   6.974 +              let
   6.975 +                val index = #index info
   6.976 +                val descr = #descr info
   6.977 +                val (_, typs, _) = the (AList.lookup (op =) descr index)
   6.978 +                val typ_assoc = typs ~~ Ts
   6.979 +                (* sanity check: every element in 'dtyps' must be a *)
   6.980 +                (* 'DtTFree'                                        *)
   6.981 +                val _ = if Library.exists (fn d =>
   6.982 +                  case d of Datatype_Aux.DtTFree _ => false | _ => true) typs then
   6.983 +                  raise REFUTE ("ground_types", "datatype argument (for type "
   6.984 +                    ^ Syntax.string_of_typ ctxt T ^ ") is not a variable")
   6.985 +                else ()
   6.986 +                (* required for mutually recursive datatypes; those need to   *)
   6.987 +                (* be added even if they are an instance of an otherwise non- *)
   6.988 +                (* recursive datatype                                         *)
   6.989 +                fun collect_dtyp d acc =
   6.990                    let
   6.991 -                    val (_, dtyps, dconstrs) = the (AList.lookup (op =) descr i)
   6.992 -                    (* if the current type is a recursive IDT (i.e. a depth *)
   6.993 -                    (* is required), add it to 'acc'                        *)
   6.994 -                    val acc_dT = if Library.exists (fn (_, ds) =>
   6.995 -                      Library.exists Datatype_Aux.is_rec_type ds) dconstrs then
   6.996 -                        insert (op =) dT acc
   6.997 -                      else acc
   6.998 -                    (* collect argument types *)
   6.999 -                    val acc_dtyps = fold_rev collect_dtyp dtyps acc_dT
  6.1000 -                    (* collect constructor types *)
  6.1001 -                    val acc_dconstrs = fold_rev collect_dtyp (maps snd dconstrs) acc_dtyps
  6.1002 +                    val dT = typ_of_dtyp descr typ_assoc d
  6.1003                    in
  6.1004 -                    acc_dconstrs
  6.1005 +                    case d of
  6.1006 +                      Datatype_Aux.DtTFree _ =>
  6.1007 +                      collect_types dT acc
  6.1008 +                    | Datatype_Aux.DtType (_, ds) =>
  6.1009 +                      collect_types dT (fold_rev collect_dtyp ds acc)
  6.1010 +                    | Datatype_Aux.DtRec i =>
  6.1011 +                      if member (op =) acc dT then
  6.1012 +                        acc  (* prevent infinite recursion *)
  6.1013 +                      else
  6.1014 +                        let
  6.1015 +                          val (_, dtyps, dconstrs) = the (AList.lookup (op =) descr i)
  6.1016 +                          (* if the current type is a recursive IDT (i.e. a depth *)
  6.1017 +                          (* is required), add it to 'acc'                        *)
  6.1018 +                          val acc_dT = if Library.exists (fn (_, ds) =>
  6.1019 +                            Library.exists Datatype_Aux.is_rec_type ds) dconstrs then
  6.1020 +                              insert (op =) dT acc
  6.1021 +                            else acc
  6.1022 +                          (* collect argument types *)
  6.1023 +                          val acc_dtyps = fold_rev collect_dtyp dtyps acc_dT
  6.1024 +                          (* collect constructor types *)
  6.1025 +                          val acc_dconstrs = fold_rev collect_dtyp (maps snd dconstrs) acc_dtyps
  6.1026 +                        in
  6.1027 +                          acc_dconstrs
  6.1028 +                        end
  6.1029                    end
  6.1030 -            end
  6.1031 -          in
  6.1032 -            (* argument types 'Ts' could be added here, but they are also *)
  6.1033 -            (* added by 'collect_dtyp' automatically                      *)
  6.1034 -            collect_dtyp (Datatype_Aux.DtRec index) acc
  6.1035 -          end
  6.1036 -        | NONE =>
  6.1037 -          (* not an inductive datatype, e.g. defined via "typedef" or *)
  6.1038 -          (* "typedecl"                                               *)
  6.1039 -          insert (op =) T (fold collect_types Ts acc))
  6.1040 -      | TFree _                => insert (op =) T acc
  6.1041 -      | TVar _                 => insert (op =) T acc)
  6.1042 +              in
  6.1043 +                (* argument types 'Ts' could be added here, but they are also *)
  6.1044 +                (* added by 'collect_dtyp' automatically                      *)
  6.1045 +                collect_dtyp (Datatype_Aux.DtRec index) acc
  6.1046 +              end
  6.1047 +          | NONE =>
  6.1048 +            (* not an inductive datatype, e.g. defined via "typedef" or *)
  6.1049 +            (* "typedecl"                                               *)
  6.1050 +            insert (op =) T (fold collect_types Ts acc))
  6.1051 +      | TFree _ => insert (op =) T acc
  6.1052 +      | TVar _ => insert (op =) T acc)
  6.1053    in
  6.1054      fold_types collect_types t []
  6.1055    end;
  6.1056 @@ -973,11 +932,11 @@
  6.1057  (*                list") are identified.                                     *)
  6.1058  (* ------------------------------------------------------------------------- *)
  6.1059  
  6.1060 -  (* Term.typ -> string *)
  6.1061 +(* Term.typ -> string *)
  6.1062  
  6.1063 -  fun string_of_typ (Type (s, _))     = s
  6.1064 -    | string_of_typ (TFree (s, _))    = s
  6.1065 -    | string_of_typ (TVar ((s,_), _)) = s;
  6.1066 +fun string_of_typ (Type (s, _))     = s
  6.1067 +  | string_of_typ (TFree (s, _))    = s
  6.1068 +  | string_of_typ (TVar ((s,_), _)) = s;
  6.1069  
  6.1070  (* ------------------------------------------------------------------------- *)
  6.1071  (* first_universe: returns the "first" (i.e. smallest) universe by assigning *)
  6.1072 @@ -985,9 +944,9 @@
  6.1073  (*                 'sizes'                                                   *)
  6.1074  (* ------------------------------------------------------------------------- *)
  6.1075  
  6.1076 -  (* Term.typ list -> (string * int) list -> int -> (Term.typ * int) list *)
  6.1077 +(* Term.typ list -> (string * int) list -> int -> (Term.typ * int) list *)
  6.1078  
  6.1079 -  fun first_universe xs sizes minsize =
  6.1080 +fun first_universe xs sizes minsize =
  6.1081    let
  6.1082      fun size_of_typ T =
  6.1083        case AList.lookup (op =) sizes (string_of_typ T) of
  6.1084 @@ -1004,39 +963,39 @@
  6.1085  (*                type may have a fixed size given in 'sizes'                *)
  6.1086  (* ------------------------------------------------------------------------- *)
  6.1087  
  6.1088 -  (* (Term.typ * int) list -> (string * int) list -> int -> int ->
  6.1089 -    (Term.typ * int) list option *)
  6.1090 +(* (Term.typ * int) list -> (string * int) list -> int -> int ->
  6.1091 +  (Term.typ * int) list option *)
  6.1092  
  6.1093 -  fun next_universe xs sizes minsize maxsize =
  6.1094 +fun next_universe xs sizes minsize maxsize =
  6.1095    let
  6.1096      (* creates the "first" list of length 'len', where the sum of all list *)
  6.1097      (* elements is 'sum', and the length of the list is 'len'              *)
  6.1098      (* int -> int -> int -> int list option *)
  6.1099      fun make_first _ 0 sum =
  6.1100 -      if sum=0 then
  6.1101 -        SOME []
  6.1102 -      else
  6.1103 -        NONE
  6.1104 +          if sum = 0 then
  6.1105 +            SOME []
  6.1106 +          else
  6.1107 +            NONE
  6.1108        | make_first max len sum =
  6.1109 -      if sum<=max orelse max<0 then
  6.1110 -        Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
  6.1111 -      else
  6.1112 -        Option.map (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
  6.1113 +          if sum <= max orelse max < 0 then
  6.1114 +            Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
  6.1115 +          else
  6.1116 +            Option.map (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
  6.1117      (* enumerates all int lists with a fixed length, where 0<=x<='max' for *)
  6.1118      (* all list elements x (unless 'max'<0)                                *)
  6.1119      (* int -> int -> int -> int list -> int list option *)
  6.1120      fun next max len sum [] =
  6.1121 -      NONE
  6.1122 +          NONE
  6.1123        | next max len sum [x] =
  6.1124 -      (* we've reached the last list element, so there's no shift possible *)
  6.1125 -      make_first max (len+1) (sum+x+1)  (* increment 'sum' by 1 *)
  6.1126 +          (* we've reached the last list element, so there's no shift possible *)
  6.1127 +          make_first max (len+1) (sum+x+1)  (* increment 'sum' by 1 *)
  6.1128        | next max len sum (x1::x2::xs) =
  6.1129 -      if x1>0 andalso (x2<max orelse max<0) then
  6.1130 -        (* we can shift *)
  6.1131 -        SOME (the (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
  6.1132 -      else
  6.1133 -        (* continue search *)
  6.1134 -        next max (len+1) (sum+x1) (x2::xs)
  6.1135 +          if x1>0 andalso (x2<max orelse max<0) then
  6.1136 +            (* we can shift *)
  6.1137 +            SOME (the (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
  6.1138 +          else
  6.1139 +            (* continue search *)
  6.1140 +            next max (len+1) (sum+x1) (x2::xs)
  6.1141      (* only consider those types for which the size is not fixed *)
  6.1142      val mutables = filter_out (AList.defined (op =) sizes o string_of_typ o fst) xs
  6.1143      (* subtract 'minsize' from every size (will be added again at the end) *)
  6.1144 @@ -1044,16 +1003,15 @@
  6.1145    in
  6.1146      case next (maxsize-minsize) 0 0 diffs of
  6.1147        SOME diffs' =>
  6.1148 -      (* merge with those types for which the size is fixed *)
  6.1149 -      SOME (fst (fold_map (fn (T, _) => fn ds =>
  6.1150 -        case AList.lookup (op =) sizes (string_of_typ T) of
  6.1151 -        (* return the fixed size *)
  6.1152 -          SOME n => ((T, n), ds)
  6.1153 -        (* consume the head of 'ds', add 'minsize' *)
  6.1154 -        | NONE   => ((T, minsize + hd ds), tl ds))
  6.1155 -        xs diffs'))
  6.1156 -    | NONE =>
  6.1157 -      NONE
  6.1158 +        (* merge with those types for which the size is fixed *)
  6.1159 +        SOME (fst (fold_map (fn (T, _) => fn ds =>
  6.1160 +          case AList.lookup (op =) sizes (string_of_typ T) of
  6.1161 +          (* return the fixed size *)
  6.1162 +            SOME n => ((T, n), ds)
  6.1163 +          (* consume the head of 'ds', add 'minsize' *)
  6.1164 +          | NONE   => ((T, minsize + hd ds), tl ds))
  6.1165 +          xs diffs'))
  6.1166 +    | NONE => NONE
  6.1167    end;
  6.1168  
  6.1169  (* ------------------------------------------------------------------------- *)
  6.1170 @@ -1061,12 +1019,10 @@
  6.1171  (*         formula that is true iff the interpretation denotes "true"        *)
  6.1172  (* ------------------------------------------------------------------------- *)
  6.1173  
  6.1174 -  (* interpretation -> prop_formula *)
  6.1175 +(* interpretation -> prop_formula *)
  6.1176  
  6.1177 -  fun toTrue (Leaf [fm, _]) =
  6.1178 -    fm
  6.1179 -    | toTrue _              =
  6.1180 -    raise REFUTE ("toTrue", "interpretation does not denote a Boolean value");
  6.1181 +fun toTrue (Leaf [fm, _]) = fm
  6.1182 +  | toTrue _ = raise REFUTE ("toTrue", "interpretation does not denote a Boolean value");
  6.1183  
  6.1184  (* ------------------------------------------------------------------------- *)
  6.1185  (* toFalse: converts the interpretation of a Boolean value to a              *)
  6.1186 @@ -1074,170 +1030,168 @@
  6.1187  (*          denotes "false"                                                  *)
  6.1188  (* ------------------------------------------------------------------------- *)
  6.1189  
  6.1190 -  (* interpretation -> prop_formula *)
  6.1191 +(* interpretation -> prop_formula *)
  6.1192  
  6.1193 -  fun toFalse (Leaf [_, fm]) =
  6.1194 -    fm
  6.1195 -    | toFalse _              =
  6.1196 -    raise REFUTE ("toFalse", "interpretation does not denote a Boolean value");
  6.1197 +fun toFalse (Leaf [_, fm]) = fm
  6.1198 +  | toFalse _ = raise REFUTE ("toFalse", "interpretation does not denote a Boolean value");
  6.1199  
  6.1200  (* ------------------------------------------------------------------------- *)
  6.1201  (* find_model: repeatedly calls 'interpret' with appropriate parameters,     *)
  6.1202  (*             applies a SAT solver, and (in case a model is found) displays *)
  6.1203  (*             the model to the user by calling 'print_model'                *)
  6.1204 -(* thy       : the current theory                                            *)
  6.1205  (* {...}     : parameters that control the translation/model generation      *)
  6.1206  (* assm_ts   : assumptions to be considered unless "no_assms" is specified   *)
  6.1207  (* t         : term to be translated into a propositional formula            *)
  6.1208  (* negate    : if true, find a model that makes 't' false (rather than true) *)
  6.1209  (* ------------------------------------------------------------------------- *)
  6.1210  
  6.1211 -  (* theory -> params -> Term.term -> bool -> unit *)
  6.1212 -
  6.1213 -  fun find_model thy {sizes, minsize, maxsize, maxvars, maxtime, satsolver,
  6.1214 -    no_assms, expect} assm_ts t negate =
  6.1215 +fun find_model ctxt
  6.1216 +    {sizes, minsize, maxsize, maxvars, maxtime, satsolver, no_assms, expect}
  6.1217 +    assm_ts t negate =
  6.1218    let
  6.1219 +    val thy = ProofContext.theory_of ctxt
  6.1220      (* string -> unit *)
  6.1221      fun check_expect outcome_code =
  6.1222        if expect = "" orelse outcome_code = expect then ()
  6.1223        else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
  6.1224      (* unit -> unit *)
  6.1225      fun wrapper () =
  6.1226 -    let
  6.1227 -      val timer  = Timer.startRealTimer ()
  6.1228 -      val t = if no_assms then t
  6.1229 -              else if negate then Logic.list_implies (assm_ts, t)
  6.1230 -              else Logic.mk_conjunction_list (t :: assm_ts)
  6.1231 -      val u      = unfold_defs thy t
  6.1232 -      val _      = tracing ("Unfolded term: " ^ Syntax.string_of_term_global thy u)
  6.1233 -      val axioms = collect_axioms thy u
  6.1234 -      (* Term.typ list *)
  6.1235 -      val types = fold (union (op =) o ground_types thy) (u :: axioms) []
  6.1236 -      val _     = tracing ("Ground types: "
  6.1237 -        ^ (if null types then "none."
  6.1238 -           else commas (map (Syntax.string_of_typ_global thy) types)))
  6.1239 -      (* we can only consider fragments of recursive IDTs, so we issue a  *)
  6.1240 -      (* warning if the formula contains a recursive IDT                  *)
  6.1241 -      (* TODO: no warning needed for /positive/ occurrences of IDTs       *)
  6.1242 -      val maybe_spurious = Library.exists (fn
  6.1243 -          Type (s, _) =>
  6.1244 -          (case Datatype.get_info thy s of
  6.1245 -            SOME info =>  (* inductive datatype *)
  6.1246 -            let
  6.1247 -              val index           = #index info
  6.1248 -              val descr           = #descr info
  6.1249 -              val (_, _, constrs) = the (AList.lookup (op =) descr index)
  6.1250 -            in
  6.1251 -              (* recursive datatype? *)
  6.1252 -              Library.exists (fn (_, ds) =>
  6.1253 -                Library.exists Datatype_Aux.is_rec_type ds) constrs
  6.1254 -            end
  6.1255 -          | NONE => false)
  6.1256 -        | _ => false) types
  6.1257 -      val _ = if maybe_spurious then
  6.1258 -          warning ("Term contains a recursive datatype; "
  6.1259 -            ^ "countermodel(s) may be spurious!")
  6.1260 -        else
  6.1261 -          ()
  6.1262 -      (* (Term.typ * int) list -> string *)
  6.1263 -      fun find_model_loop universe =
  6.1264        let
  6.1265 -        val msecs_spent = Time.toMilliseconds (Timer.checkRealTimer timer)
  6.1266 -        val _ = maxtime = 0 orelse msecs_spent < 1000 * maxtime
  6.1267 -                orelse raise TimeLimit.TimeOut
  6.1268 -        val init_model = (universe, [])
  6.1269 -        val init_args  = {maxvars = maxvars, def_eq = false, next_idx = 1,
  6.1270 -          bounds = [], wellformed = True}
  6.1271 -        val _ = tracing ("Translating term (sizes: "
  6.1272 -          ^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
  6.1273 -        (* translate 'u' and all axioms *)
  6.1274 -        val (intrs, (model, args)) = fold_map (fn t' => fn (m, a) =>
  6.1275 +        val timer = Timer.startRealTimer ()
  6.1276 +        val t =
  6.1277 +          if no_assms then t
  6.1278 +          else if negate then Logic.list_implies (assm_ts, t)
  6.1279 +          else Logic.mk_conjunction_list (t :: assm_ts)
  6.1280 +        val u = unfold_defs thy t
  6.1281 +        val _ = tracing ("Unfolded term: " ^ Syntax.string_of_term ctxt u)
  6.1282 +        val axioms = collect_axioms ctxt u
  6.1283 +        (* Term.typ list *)
  6.1284 +        val types = fold (union (op =) o ground_types ctxt) (u :: axioms) []
  6.1285 +        val _ = tracing ("Ground types: "
  6.1286 +          ^ (if null types then "none."
  6.1287 +             else commas (map (Syntax.string_of_typ ctxt) types)))
  6.1288 +        (* we can only consider fragments of recursive IDTs, so we issue a  *)
  6.1289 +        (* warning if the formula contains a recursive IDT                  *)
  6.1290 +        (* TODO: no warning needed for /positive/ occurrences of IDTs       *)
  6.1291 +        val maybe_spurious = Library.exists (fn
  6.1292 +            Type (s, _) =>
  6.1293 +              (case Datatype.get_info thy s of
  6.1294 +                SOME info =>  (* inductive datatype *)
  6.1295 +                  let
  6.1296 +                    val index           = #index info
  6.1297 +                    val descr           = #descr info
  6.1298 +                    val (_, _, constrs) = the (AList.lookup (op =) descr index)
  6.1299 +                  in
  6.1300 +                    (* recursive datatype? *)
  6.1301 +                    Library.exists (fn (_, ds) =>
  6.1302 +                      Library.exists Datatype_Aux.is_rec_type ds) constrs
  6.1303 +                  end
  6.1304 +              | NONE => false)
  6.1305 +          | _ => false) types
  6.1306 +        val _ =
  6.1307 +          if maybe_spurious then
  6.1308 +            warning ("Term contains a recursive datatype; "
  6.1309 +              ^ "countermodel(s) may be spurious!")
  6.1310 +          else
  6.1311 +            ()
  6.1312 +        (* (Term.typ * int) list -> string *)
  6.1313 +        fun find_model_loop universe =
  6.1314            let
  6.1315 -            val (i, m', a') = interpret thy m a t'
  6.1316 +            val msecs_spent = Time.toMilliseconds (Timer.checkRealTimer timer)
  6.1317 +            val _ = maxtime = 0 orelse msecs_spent < 1000 * maxtime
  6.1318 +                    orelse raise TimeLimit.TimeOut
  6.1319 +            val init_model = (universe, [])
  6.1320 +            val init_args  = {maxvars = maxvars, def_eq = false, next_idx = 1,
  6.1321 +              bounds = [], wellformed = True}
  6.1322 +            val _ = tracing ("Translating term (sizes: "
  6.1323 +              ^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
  6.1324 +            (* translate 'u' and all axioms *)
  6.1325 +            val (intrs, (model, args)) = fold_map (fn t' => fn (m, a) =>
  6.1326 +              let
  6.1327 +                val (i, m', a') = interpret ctxt m a t'
  6.1328 +              in
  6.1329 +                (* set 'def_eq' to 'true' *)
  6.1330 +                (i, (m', {maxvars = #maxvars a', def_eq = true,
  6.1331 +                  next_idx = #next_idx a', bounds = #bounds a',
  6.1332 +                  wellformed = #wellformed a'}))
  6.1333 +              end) (u :: axioms) (init_model, init_args)
  6.1334 +            (* make 'u' either true or false, and make all axioms true, and *)
  6.1335 +            (* add the well-formedness side condition                       *)
  6.1336 +            val fm_u = (if negate then toFalse else toTrue) (hd intrs)
  6.1337 +            val fm_ax = PropLogic.all (map toTrue (tl intrs))
  6.1338 +            val fm = PropLogic.all [#wellformed args, fm_ax, fm_u]
  6.1339 +            val _ =
  6.1340 +              (if satsolver = "dpll" orelse satsolver = "enumerate" then
  6.1341 +                warning ("Using SAT solver " ^ quote satsolver ^
  6.1342 +                         "; for better performance, consider installing an \
  6.1343 +                         \external solver.")
  6.1344 +               else ());
  6.1345 +            val solver =
  6.1346 +              SatSolver.invoke_solver satsolver
  6.1347 +              handle Option.Option =>
  6.1348 +                     error ("Unknown SAT solver: " ^ quote satsolver ^
  6.1349 +                            ". Available solvers: " ^
  6.1350 +                            commas (map (quote o fst) (!SatSolver.solvers)) ^ ".")
  6.1351            in
  6.1352 -            (* set 'def_eq' to 'true' *)
  6.1353 -            (i, (m', {maxvars = #maxvars a', def_eq = true,
  6.1354 -              next_idx = #next_idx a', bounds = #bounds a',
  6.1355 -              wellformed = #wellformed a'}))
  6.1356 -          end) (u :: axioms) (init_model, init_args)
  6.1357 -        (* make 'u' either true or false, and make all axioms true, and *)
  6.1358 -        (* add the well-formedness side condition                       *)
  6.1359 -        val fm_u  = (if negate then toFalse else toTrue) (hd intrs)
  6.1360 -        val fm_ax = PropLogic.all (map toTrue (tl intrs))
  6.1361 -        val fm    = PropLogic.all [#wellformed args, fm_ax, fm_u]
  6.1362 -        val _ =
  6.1363 -          (if satsolver = "dpll" orelse satsolver = "enumerate" then
  6.1364 -            warning ("Using SAT solver " ^ quote satsolver ^
  6.1365 -                     "; for better performance, consider installing an \
  6.1366 -                     \external solver.")
  6.1367 -          else
  6.1368 -            ());
  6.1369 -        val solver =
  6.1370 -          SatSolver.invoke_solver satsolver
  6.1371 -          handle Option.Option =>
  6.1372 -                 error ("Unknown SAT solver: " ^ quote satsolver ^
  6.1373 -                        ". Available solvers: " ^
  6.1374 -                        commas (map (quote o fst) (!SatSolver.solvers)) ^ ".")
  6.1375 -      in
  6.1376 -        priority "Invoking SAT solver...";
  6.1377 -        (case solver fm of
  6.1378 -          SatSolver.SATISFIABLE assignment =>
  6.1379 -          (priority ("*** Model found: ***\n" ^ print_model thy model
  6.1380 -            (fn i => case assignment i of SOME b => b | NONE => true));
  6.1381 -           if maybe_spurious then "potential" else "genuine")
  6.1382 -        | SatSolver.UNSATISFIABLE _ =>
  6.1383 -          (priority "No model exists.";
  6.1384 -          case next_universe universe sizes minsize maxsize of
  6.1385 -            SOME universe' => find_model_loop universe'
  6.1386 -          | NONE           => (priority
  6.1387 -            "Search terminated, no larger universe within the given limits.";
  6.1388 -            "none"))
  6.1389 -        | SatSolver.UNKNOWN =>
  6.1390 -          (priority "No model found.";
  6.1391 -          case next_universe universe sizes minsize maxsize of
  6.1392 -            SOME universe' => find_model_loop universe'
  6.1393 -          | NONE           => (priority
  6.1394 -            "Search terminated, no larger universe within the given limits.";
  6.1395 -            "unknown"))
  6.1396 -        ) handle SatSolver.NOT_CONFIGURED =>
  6.1397 -          (error ("SAT solver " ^ quote satsolver ^ " is not configured.");
  6.1398 -           "unknown")
  6.1399 -      end handle MAXVARS_EXCEEDED =>
  6.1400 -        (priority ("Search terminated, number of Boolean variables ("
  6.1401 -          ^ string_of_int maxvars ^ " allowed) exceeded.");
  6.1402 -          "unknown")
  6.1403 +            priority "Invoking SAT solver...";
  6.1404 +            (case solver fm of
  6.1405 +              SatSolver.SATISFIABLE assignment =>
  6.1406 +                (priority ("*** Model found: ***\n" ^ print_model ctxt model
  6.1407 +                  (fn i => case assignment i of SOME b => b | NONE => true));
  6.1408 +                 if maybe_spurious then "potential" else "genuine")
  6.1409 +            | SatSolver.UNSATISFIABLE _ =>
  6.1410 +                (priority "No model exists.";
  6.1411 +                case next_universe universe sizes minsize maxsize of
  6.1412 +                  SOME universe' => find_model_loop universe'
  6.1413 +                | NONE => (priority
  6.1414 +                  "Search terminated, no larger universe within the given limits.";
  6.1415 +                  "none"))
  6.1416 +            | SatSolver.UNKNOWN =>
  6.1417 +                (priority "No model found.";
  6.1418 +                case next_universe universe sizes minsize maxsize of
  6.1419 +                  SOME universe' => find_model_loop universe'
  6.1420 +                | NONE           => (priority
  6.1421 +                  "Search terminated, no larger universe within the given limits.";
  6.1422 +                  "unknown"))) handle SatSolver.NOT_CONFIGURED =>
  6.1423 +              (error ("SAT solver " ^ quote satsolver ^ " is not configured.");
  6.1424 +               "unknown")
  6.1425 +          end
  6.1426 +          handle MAXVARS_EXCEEDED =>
  6.1427 +            (priority ("Search terminated, number of Boolean variables ("
  6.1428 +              ^ string_of_int maxvars ^ " allowed) exceeded.");
  6.1429 +              "unknown")
  6.1430 +
  6.1431          val outcome_code = find_model_loop (first_universe types sizes minsize)
  6.1432        in
  6.1433          check_expect outcome_code
  6.1434        end
  6.1435 -    in
  6.1436 -      (* some parameter sanity checks *)
  6.1437 -      minsize>=1 orelse
  6.1438 -        error ("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
  6.1439 -      maxsize>=1 orelse
  6.1440 -        error ("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
  6.1441 -      maxsize>=minsize orelse
  6.1442 -        error ("\"maxsize\" (=" ^ string_of_int maxsize ^
  6.1443 -        ") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
  6.1444 -      maxvars>=0 orelse
  6.1445 -        error ("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
  6.1446 -      maxtime>=0 orelse
  6.1447 -        error ("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
  6.1448 -      (* enter loop with or without time limit *)
  6.1449 -      priority ("Trying to find a model that "
  6.1450 -        ^ (if negate then "refutes" else "satisfies") ^ ": "
  6.1451 -        ^ Syntax.string_of_term_global thy t);
  6.1452 -      if maxtime>0 then (
  6.1453 -        TimeLimit.timeLimit (Time.fromSeconds maxtime)
  6.1454 -          wrapper ()
  6.1455 -        handle TimeLimit.TimeOut =>
  6.1456 -          (priority ("Search terminated, time limit (" ^
  6.1457 -              string_of_int maxtime
  6.1458 -              ^ (if maxtime=1 then " second" else " seconds") ^ ") exceeded.");
  6.1459 -           check_expect "unknown")
  6.1460 -      ) else
  6.1461 +  in
  6.1462 +    (* some parameter sanity checks *)
  6.1463 +    minsize>=1 orelse
  6.1464 +      error ("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
  6.1465 +    maxsize>=1 orelse
  6.1466 +      error ("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
  6.1467 +    maxsize>=minsize orelse
  6.1468 +      error ("\"maxsize\" (=" ^ string_of_int maxsize ^
  6.1469 +      ") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
  6.1470 +    maxvars>=0 orelse
  6.1471 +      error ("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
  6.1472 +    maxtime>=0 orelse
  6.1473 +      error ("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
  6.1474 +    (* enter loop with or without time limit *)
  6.1475 +    priority ("Trying to find a model that "
  6.1476 +      ^ (if negate then "refutes" else "satisfies") ^ ": "
  6.1477 +      ^ Syntax.string_of_term ctxt t);
  6.1478 +    if maxtime > 0 then (
  6.1479 +      TimeLimit.timeLimit (Time.fromSeconds maxtime)
  6.1480          wrapper ()
  6.1481 -    end;
  6.1482 +      handle TimeLimit.TimeOut =>
  6.1483 +        (priority ("Search terminated, time limit (" ^
  6.1484 +            string_of_int maxtime
  6.1485 +            ^ (if maxtime=1 then " second" else " seconds") ^ ") exceeded.");
  6.1486 +         check_expect "unknown")
  6.1487 +    ) else wrapper ()
  6.1488 +  end;
  6.1489  
  6.1490  
  6.1491  (* ------------------------------------------------------------------------- *)
  6.1492 @@ -1250,10 +1204,8 @@
  6.1493  (*               parameters                                                  *)
  6.1494  (* ------------------------------------------------------------------------- *)
  6.1495  
  6.1496 -  (* theory -> (string * string) list -> Term.term list -> Term.term -> unit *)
  6.1497 -
  6.1498 -  fun satisfy_term thy params assm_ts t =
  6.1499 -    find_model thy (actual_params thy params) assm_ts t false;
  6.1500 +fun satisfy_term ctxt params assm_ts t =
  6.1501 +  find_model ctxt (actual_params ctxt params) assm_ts t false;
  6.1502  
  6.1503  (* ------------------------------------------------------------------------- *)
  6.1504  (* refute_term: calls 'find_model' to find a model that refutes 't'          *)
  6.1505 @@ -1261,9 +1213,7 @@
  6.1506  (*              parameters                                                   *)
  6.1507  (* ------------------------------------------------------------------------- *)
  6.1508  
  6.1509 -  (* theory -> (string * string) list -> Term.term list -> Term.term -> unit *)
  6.1510 -
  6.1511 -  fun refute_term thy params assm_ts t =
  6.1512 +fun refute_term ctxt params assm_ts t =
  6.1513    let
  6.1514      (* disallow schematic type variables, since we cannot properly negate  *)
  6.1515      (* terms containing them (their logical meaning is that there EXISTS a *)
  6.1516 @@ -1293,33 +1243,32 @@
  6.1517      (* quantified variables.                                             *)
  6.1518      (* maps  !!x1...xn. !xk...xm. t   to   t  *)
  6.1519      fun strip_all_body (Const (@{const_name all}, _) $ Abs (_, _, t)) =
  6.1520 -        strip_all_body t
  6.1521 +          strip_all_body t
  6.1522        | strip_all_body (Const (@{const_name Trueprop}, _) $ t) =
  6.1523 -        strip_all_body t
  6.1524 +          strip_all_body t
  6.1525        | strip_all_body (Const (@{const_name All}, _) $ Abs (_, _, t)) =
  6.1526 -        strip_all_body t
  6.1527 +          strip_all_body t
  6.1528        | strip_all_body t = t
  6.1529      (* maps  !!x1...xn. !xk...xm. t   to   [x1, ..., xn, xk, ..., xm]  *)
  6.1530      fun strip_all_vars (Const (@{const_name all}, _) $ Abs (a, T, t)) =
  6.1531 -      (a, T) :: strip_all_vars t
  6.1532 +          (a, T) :: strip_all_vars t
  6.1533        | strip_all_vars (Const (@{const_name Trueprop}, _) $ t) =
  6.1534 -      strip_all_vars t
  6.1535 +          strip_all_vars t
  6.1536        | strip_all_vars (Const (@{const_name All}, _) $ Abs (a, T, t)) =
  6.1537 -      (a, T) :: strip_all_vars t
  6.1538 -      | strip_all_vars t =
  6.1539 -      [] : (string * typ) list
  6.1540 +          (a, T) :: strip_all_vars t
  6.1541 +      | strip_all_vars t = [] : (string * typ) list
  6.1542      val strip_t = strip_all_body ex_closure
  6.1543 -    val frees   = Term.rename_wrt_term strip_t (strip_all_vars ex_closure)
  6.1544 +    val frees = Term.rename_wrt_term strip_t (strip_all_vars ex_closure)
  6.1545      val subst_t = Term.subst_bounds (map Free frees, strip_t)
  6.1546    in
  6.1547 -    find_model thy (actual_params thy params) assm_ts subst_t true
  6.1548 +    find_model ctxt (actual_params ctxt params) assm_ts subst_t true
  6.1549    end;
  6.1550  
  6.1551  (* ------------------------------------------------------------------------- *)
  6.1552  (* refute_goal                                                               *)
  6.1553  (* ------------------------------------------------------------------------- *)
  6.1554  
  6.1555 -  fun refute_goal ctxt params th i =
  6.1556 +fun refute_goal ctxt params th i =
  6.1557    let
  6.1558      val t = th |> prop_of
  6.1559    in
  6.1560 @@ -1330,8 +1279,7 @@
  6.1561          val assms = map term_of (Assumption.all_assms_of ctxt)
  6.1562          val (t, frees) = Logic.goal_params t i
  6.1563        in
  6.1564 -        refute_term (ProofContext.theory_of ctxt) params assms
  6.1565 -        (subst_bounds (frees, t))
  6.1566 +        refute_term ctxt params assms (subst_bounds (frees, t))
  6.1567        end
  6.1568    end
  6.1569  
  6.1570 @@ -1346,81 +1294,64 @@
  6.1571  (*                 variables)                                                *)
  6.1572  (* ------------------------------------------------------------------------- *)
  6.1573  
  6.1574 -  (* theory -> model -> Term.typ -> interpretation list *)
  6.1575 -
  6.1576 -  fun make_constants thy model T =
  6.1577 +fun make_constants ctxt model T =
  6.1578    let
  6.1579      (* returns a list with all unit vectors of length n *)
  6.1580      (* int -> interpretation list *)
  6.1581      fun unit_vectors n =
  6.1582 -    let
  6.1583 -      (* returns the k-th unit vector of length n *)
  6.1584 -      (* int * int -> interpretation *)
  6.1585 -      fun unit_vector (k, n) =
  6.1586 -        Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
  6.1587 -      (* int -> interpretation list *)
  6.1588 -      fun unit_vectors_loop k =
  6.1589 -        if k>n then [] else unit_vector (k,n) :: unit_vectors_loop (k+1)
  6.1590 -    in
  6.1591 -      unit_vectors_loop 1
  6.1592 -    end
  6.1593 +      let
  6.1594 +        (* returns the k-th unit vector of length n *)
  6.1595 +        (* int * int -> interpretation *)
  6.1596 +        fun unit_vector (k, n) =
  6.1597 +          Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
  6.1598 +        (* int -> interpretation list *)
  6.1599 +        fun unit_vectors_loop k =
  6.1600 +          if k>n then [] else unit_vector (k,n) :: unit_vectors_loop (k+1)
  6.1601 +      in
  6.1602 +        unit_vectors_loop 1
  6.1603 +      end
  6.1604      (* returns a list of lists, each one consisting of n (possibly *)
  6.1605      (* identical) elements from 'xs'                               *)
  6.1606      (* int -> 'a list -> 'a list list *)
  6.1607 -    fun pick_all 1 xs =
  6.1608 -      map single xs
  6.1609 +    fun pick_all 1 xs = map single xs
  6.1610        | pick_all n xs =
  6.1611 -      let val rec_pick = pick_all (n-1) xs in
  6.1612 -        maps (fn x => map (cons x) rec_pick) xs
  6.1613 -      end
  6.1614 +          let val rec_pick = pick_all (n - 1) xs in
  6.1615 +            maps (fn x => map (cons x) rec_pick) xs
  6.1616 +          end
  6.1617      (* returns all constant interpretations that have the same tree *)
  6.1618      (* structure as the interpretation argument                     *)
  6.1619      (* interpretation -> interpretation list *)
  6.1620      fun make_constants_intr (Leaf xs) = unit_vectors (length xs)
  6.1621        | make_constants_intr (Node xs) = map Node (pick_all (length xs)
  6.1622 -      (make_constants_intr (hd xs)))
  6.1623 +          (make_constants_intr (hd xs)))
  6.1624      (* obtain the interpretation for a variable of type 'T' *)
  6.1625 -    val (i, _, _) = interpret thy model {maxvars=0, def_eq=false, next_idx=1,
  6.1626 +    val (i, _, _) = interpret ctxt model {maxvars=0, def_eq=false, next_idx=1,
  6.1627        bounds=[], wellformed=True} (Free ("dummy", T))
  6.1628    in
  6.1629      make_constants_intr i
  6.1630    end;
  6.1631  
  6.1632  (* ------------------------------------------------------------------------- *)
  6.1633 -(* power: 'power (a, b)' computes a^b, for a>=0, b>=0                        *)
  6.1634 -(* ------------------------------------------------------------------------- *)
  6.1635 -
  6.1636 -  (* int * int -> int *)
  6.1637 -
  6.1638 -  fun power (a, 0) = 1
  6.1639 -    | power (a, 1) = a
  6.1640 -    | power (a, b) = let val ab = power(a, b div 2) in
  6.1641 -        ab * ab * power(a, b mod 2)
  6.1642 -      end;
  6.1643 -
  6.1644 -(* ------------------------------------------------------------------------- *)
  6.1645  (* size_of_type: returns the number of elements in a type 'T' (i.e. 'length  *)
  6.1646  (*               (make_constants T)', but implemented more efficiently)      *)
  6.1647  (* ------------------------------------------------------------------------- *)
  6.1648  
  6.1649 -  (* theory -> model -> Term.typ -> int *)
  6.1650 +(* returns 0 for an empty ground type or a function type with empty      *)
  6.1651 +(* codomain, but fails for a function type with empty domain --          *)
  6.1652 +(* admissibility of datatype constructor argument types (see "Inductive  *)
  6.1653 +(* datatypes in HOL - lessons learned ...", S. Berghofer, M. Wenzel,     *)
  6.1654 +(* TPHOLs 99) ensures that recursive, possibly empty, datatype fragments *)
  6.1655 +(* never occur as the domain of a function type that is the type of a    *)
  6.1656 +(* constructor argument                                                  *)
  6.1657  
  6.1658 -  (* returns 0 for an empty ground type or a function type with empty      *)
  6.1659 -  (* codomain, but fails for a function type with empty domain --          *)
  6.1660 -  (* admissibility of datatype constructor argument types (see "Inductive  *)
  6.1661 -  (* datatypes in HOL - lessons learned ...", S. Berghofer, M. Wenzel,     *)
  6.1662 -  (* TPHOLs 99) ensures that recursive, possibly empty, datatype fragments *)
  6.1663 -  (* never occur as the domain of a function type that is the type of a    *)
  6.1664 -  (* constructor argument                                                  *)
  6.1665 -
  6.1666 -  fun size_of_type thy model T =
  6.1667 +fun size_of_type ctxt model T =
  6.1668    let
  6.1669      (* returns the number of elements that have the same tree structure as a *)
  6.1670      (* given interpretation                                                  *)
  6.1671      fun size_of_intr (Leaf xs) = length xs
  6.1672 -      | size_of_intr (Node xs) = power (size_of_intr (hd xs), length xs)
  6.1673 +      | size_of_intr (Node xs) = Integer.pow (length xs) (size_of_intr (hd xs))
  6.1674      (* obtain the interpretation for a variable of type 'T' *)
  6.1675 -    val (i, _, _) = interpret thy model {maxvars=0, def_eq=false, next_idx=1,
  6.1676 +    val (i, _, _) = interpret ctxt model {maxvars=0, def_eq=false, next_idx=1,
  6.1677        bounds=[], wellformed=True} (Free ("dummy", T))
  6.1678    in
  6.1679      size_of_intr i
  6.1680 @@ -1430,11 +1361,11 @@
  6.1681  (* TT/FF: interpretations that denote "true" or "false", respectively        *)
  6.1682  (* ------------------------------------------------------------------------- *)
  6.1683  
  6.1684 -  (* interpretation *)
  6.1685 +(* interpretation *)
  6.1686  
  6.1687 -  val TT = Leaf [True, False];
  6.1688 +val TT = Leaf [True, False];
  6.1689  
  6.1690 -  val FF = Leaf [False, True];
  6.1691 +val FF = Leaf [False, True];
  6.1692  
  6.1693  (* ------------------------------------------------------------------------- *)
  6.1694  (* make_equality: returns an interpretation that denotes (extensional)       *)
  6.1695 @@ -1447,46 +1378,46 @@
  6.1696  (*   'not_equal' to another interpretation                                   *)
  6.1697  (* ------------------------------------------------------------------------- *)
  6.1698  
  6.1699 -  (* We could in principle represent '=' on a type T by a particular        *)
  6.1700 -  (* interpretation.  However, the size of that interpretation is quadratic *)
  6.1701 -  (* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
  6.1702 -  (* 'i2' directly is more efficient than constructing the interpretation   *)
  6.1703 -  (* for equality on T first, and "applying" this interpretation to 'i1'    *)
  6.1704 -  (* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
  6.1705 +(* We could in principle represent '=' on a type T by a particular        *)
  6.1706 +(* interpretation.  However, the size of that interpretation is quadratic *)
  6.1707 +(* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
  6.1708 +(* 'i2' directly is more efficient than constructing the interpretation   *)
  6.1709 +(* for equality on T first, and "applying" this interpretation to 'i1'    *)
  6.1710 +(* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
  6.1711  
  6.1712 -  (* interpretation * interpretation -> interpretation *)
  6.1713 +(* interpretation * interpretation -> interpretation *)
  6.1714  
  6.1715 -  fun make_equality (i1, i2) =
  6.1716 +fun make_equality (i1, i2) =
  6.1717    let
  6.1718      (* interpretation * interpretation -> prop_formula *)
  6.1719      fun equal (i1, i2) =
  6.1720        (case i1 of
  6.1721          Leaf xs =>
  6.1722 -        (case i2 of
  6.1723 -          Leaf ys => PropLogic.dot_product (xs, ys)  (* defined and equal *)
  6.1724 -        | Node _  => raise REFUTE ("make_equality",
  6.1725 -          "second interpretation is higher"))
  6.1726 +          (case i2 of
  6.1727 +            Leaf ys => PropLogic.dot_product (xs, ys)  (* defined and equal *)
  6.1728 +          | Node _  => raise REFUTE ("make_equality",
  6.1729 +            "second interpretation is higher"))
  6.1730        | Node xs =>
  6.1731 -        (case i2 of
  6.1732 -          Leaf _  => raise REFUTE ("make_equality",
  6.1733 -          "first interpretation is higher")
  6.1734 -        | Node ys => PropLogic.all (map equal (xs ~~ ys))))
  6.1735 +          (case i2 of
  6.1736 +            Leaf _  => raise REFUTE ("make_equality",
  6.1737 +            "first interpretation is higher")
  6.1738 +          | Node ys => PropLogic.all (map equal (xs ~~ ys))))
  6.1739      (* interpretation * interpretation -> prop_formula *)
  6.1740      fun not_equal (i1, i2) =
  6.1741        (case i1 of
  6.1742          Leaf xs =>
  6.1743 -        (case i2 of
  6.1744 -          (* defined and not equal *)
  6.1745 -          Leaf ys => PropLogic.all ((PropLogic.exists xs)
  6.1746 -          :: (PropLogic.exists ys)
  6.1747 -          :: (map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))
  6.1748 -        | Node _  => raise REFUTE ("make_equality",
  6.1749 -          "second interpretation is higher"))
  6.1750 +          (case i2 of
  6.1751 +            (* defined and not equal *)
  6.1752 +            Leaf ys => PropLogic.all ((PropLogic.exists xs)
  6.1753 +            :: (PropLogic.exists ys)
  6.1754 +            :: (map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))
  6.1755 +          | Node _  => raise REFUTE ("make_equality",
  6.1756 +            "second interpretation is higher"))
  6.1757        | Node xs =>
  6.1758 -        (case i2 of
  6.1759 -          Leaf _  => raise REFUTE ("make_equality",
  6.1760 -          "first interpretation is higher")
  6.1761 -        | Node ys => PropLogic.exists (map not_equal (xs ~~ ys))))
  6.1762 +          (case i2 of
  6.1763 +            Leaf _  => raise REFUTE ("make_equality",
  6.1764 +            "first interpretation is higher")
  6.1765 +          | Node ys => PropLogic.exists (map not_equal (xs ~~ ys))))
  6.1766    in
  6.1767      (* a value may be undefined; therefore 'not_equal' is not just the *)
  6.1768      (* negation of 'equal'                                             *)
  6.1769 @@ -1502,25 +1433,25 @@
  6.1770  (* to an undefined interpretation.                                           *)
  6.1771  (* ------------------------------------------------------------------------- *)
  6.1772  
  6.1773 -  (* interpretation * interpretation -> interpretation *)
  6.1774 +(* interpretation * interpretation -> interpretation *)
  6.1775  
  6.1776 -  fun make_def_equality (i1, i2) =
  6.1777 +fun make_def_equality (i1, i2) =
  6.1778    let
  6.1779      (* interpretation * interpretation -> prop_formula *)
  6.1780      fun equal (i1, i2) =
  6.1781        (case i1 of
  6.1782          Leaf xs =>
  6.1783 -        (case i2 of
  6.1784 -          (* defined and equal, or both undefined *)
  6.1785 -          Leaf ys => SOr (PropLogic.dot_product (xs, ys),
  6.1786 -          SAnd (PropLogic.all (map SNot xs), PropLogic.all (map SNot ys)))
  6.1787 -        | Node _  => raise REFUTE ("make_def_equality",
  6.1788 -          "second interpretation is higher"))
  6.1789 +          (case i2 of
  6.1790 +            (* defined and equal, or both undefined *)
  6.1791 +            Leaf ys => SOr (PropLogic.dot_product (xs, ys),
  6.1792 +            SAnd (PropLogic.all (map SNot xs), PropLogic.all (map SNot ys)))
  6.1793 +          | Node _  => raise REFUTE ("make_def_equality",
  6.1794 +            "second interpretation is higher"))
  6.1795        | Node xs =>
  6.1796 -        (case i2 of
  6.1797 -          Leaf _  => raise REFUTE ("make_def_equality",
  6.1798 -          "first interpretation is higher")
  6.1799 -        | Node ys => PropLogic.all (map equal (xs ~~ ys))))
  6.1800 +          (case i2 of
  6.1801 +            Leaf _  => raise REFUTE ("make_def_equality",
  6.1802 +            "first interpretation is higher")
  6.1803 +          | Node ys => PropLogic.all (map equal (xs ~~ ys))))
  6.1804      (* interpretation *)
  6.1805      val eq = equal (i1, i2)
  6.1806    in
  6.1807 @@ -1533,9 +1464,9 @@
  6.1808  (*                       argument denoted by 'i2'                            *)
  6.1809  (* ------------------------------------------------------------------------- *)
  6.1810  
  6.1811 -  (* interpretation * interpretation -> interpretation *)
  6.1812 +(* interpretation * interpretation -> interpretation *)
  6.1813  
  6.1814 -  fun interpretation_apply (i1, i2) =
  6.1815 +fun interpretation_apply (i1, i2) =
  6.1816    let
  6.1817      (* interpretation * interpretation -> interpretation *)
  6.1818      fun interpretation_disjunction (tr1,tr2) =
  6.1819 @@ -1546,50 +1477,46 @@
  6.1820        tree_map (map (fn x => SAnd (fm,x))) tr
  6.1821      (* prop_formula list * interpretation list -> interpretation *)
  6.1822      fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
  6.1823 -      prop_formula_times_interpretation (fm,tr)
  6.1824 +          prop_formula_times_interpretation (fm,tr)
  6.1825        | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
  6.1826 -      interpretation_disjunction (prop_formula_times_interpretation (fm,tr),
  6.1827 -        prop_formula_list_dot_product_interpretation_list (fms,trees))
  6.1828 +          interpretation_disjunction (prop_formula_times_interpretation (fm,tr),
  6.1829 +            prop_formula_list_dot_product_interpretation_list (fms,trees))
  6.1830        | prop_formula_list_dot_product_interpretation_list (_,_) =
  6.1831 -      raise REFUTE ("interpretation_apply", "empty list (in dot product)")
  6.1832 +          raise REFUTE ("interpretation_apply", "empty list (in dot product)")
  6.1833      (* concatenates 'x' with every list in 'xss', returning a new list of *)
  6.1834      (* lists                                                              *)
  6.1835      (* 'a -> 'a list list -> 'a list list *)
  6.1836 -    fun cons_list x xss =
  6.1837 -      map (cons x) xss
  6.1838 +    fun cons_list x xss = map (cons x) xss
  6.1839      (* returns a list of lists, each one consisting of one element from each *)
  6.1840      (* element of 'xss'                                                      *)
  6.1841      (* 'a list list -> 'a list list *)
  6.1842 -    fun pick_all [xs] =
  6.1843 -      map single xs
  6.1844 +    fun pick_all [xs] = map single xs
  6.1845        | pick_all (xs::xss) =
  6.1846 -      let val rec_pick = pick_all xss in
  6.1847 -        maps (fn x => map (cons x) rec_pick) xs
  6.1848 -      end
  6.1849 -      | pick_all _ =
  6.1850 -      raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
  6.1851 +          let val rec_pick = pick_all xss in
  6.1852 +            maps (fn x => map (cons x) rec_pick) xs
  6.1853 +          end
  6.1854 +      | pick_all _ = raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
  6.1855      (* interpretation -> prop_formula list *)
  6.1856 -    fun interpretation_to_prop_formula_list (Leaf xs) =
  6.1857 -      xs
  6.1858 +    fun interpretation_to_prop_formula_list (Leaf xs) = xs
  6.1859        | interpretation_to_prop_formula_list (Node trees) =
  6.1860 -      map PropLogic.all (pick_all
  6.1861 -        (map interpretation_to_prop_formula_list trees))
  6.1862 +          map PropLogic.all (pick_all
  6.1863 +            (map interpretation_to_prop_formula_list trees))
  6.1864    in
  6.1865      case i1 of
  6.1866        Leaf _ =>
  6.1867 -      raise REFUTE ("interpretation_apply", "first interpretation is a leaf")
  6.1868 +        raise REFUTE ("interpretation_apply", "first interpretation is a leaf")
  6.1869      | Node xs =>
  6.1870 -      prop_formula_list_dot_product_interpretation_list
  6.1871 -        (interpretation_to_prop_formula_list i2, xs)
  6.1872 +        prop_formula_list_dot_product_interpretation_list
  6.1873 +          (interpretation_to_prop_formula_list i2, xs)
  6.1874    end;
  6.1875  
  6.1876  (* ------------------------------------------------------------------------- *)
  6.1877  (* eta_expand: eta-expands a term 't' by adding 'i' lambda abstractions      *)
  6.1878  (* ------------------------------------------------------------------------- *)
  6.1879  
  6.1880 -  (* Term.term -> int -> Term.term *)
  6.1881 +(* Term.term -> int -> Term.term *)
  6.1882  
  6.1883 -  fun eta_expand t i =
  6.1884 +fun eta_expand t i =
  6.1885    let
  6.1886      val Ts = Term.binder_types (Term.fastype_of t)
  6.1887      val t' = Term.incr_boundvars i t
  6.1888 @@ -1605,1056 +1532,1036 @@
  6.1889  (*               their arguments) of the size of the argument types          *)
  6.1890  (* ------------------------------------------------------------------------- *)
  6.1891  
  6.1892 -  fun size_of_dtyp thy typ_sizes descr typ_assoc constructors =
  6.1893 -    Integer.sum (map (fn (_, dtyps) =>
  6.1894 -      Integer.prod (map (size_of_type thy (typ_sizes, []) o
  6.1895 -        (typ_of_dtyp descr typ_assoc)) dtyps))
  6.1896 -          constructors);
  6.1897 +fun size_of_dtyp ctxt typ_sizes descr typ_assoc constructors =
  6.1898 +  Integer.sum (map (fn (_, dtyps) =>
  6.1899 +    Integer.prod (map (size_of_type ctxt (typ_sizes, []) o
  6.1900 +      (typ_of_dtyp descr typ_assoc)) dtyps))
  6.1901 +        constructors);
  6.1902  
  6.1903  
  6.1904  (* ------------------------------------------------------------------------- *)
  6.1905  (* INTERPRETERS: Actual Interpreters                                         *)
  6.1906  (* ------------------------------------------------------------------------- *)
  6.1907  
  6.1908 -  (* theory -> model -> arguments -> Term.term ->
  6.1909 -    (interpretation * model * arguments) option *)
  6.1910 +(* simply typed lambda calculus: Isabelle's basic term syntax, with type *)
  6.1911 +(* variables, function types, and propT                                  *)
  6.1912  
  6.1913 -  (* simply typed lambda calculus: Isabelle's basic term syntax, with type *)
  6.1914 -  (* variables, function types, and propT                                  *)
  6.1915 -
  6.1916 -  fun stlc_interpreter thy model args t =
  6.1917 +fun stlc_interpreter ctxt model args t =
  6.1918    let
  6.1919 -    val (typs, terms)                                   = model
  6.1920 +    val thy = ProofContext.theory_of ctxt
  6.1921 +    val (typs, terms) = model
  6.1922      val {maxvars, def_eq, next_idx, bounds, wellformed} = args
  6.1923      (* Term.typ -> (interpretation * model * arguments) option *)
  6.1924      fun interpret_groundterm T =
  6.1925 -    let
  6.1926 -      (* unit -> (interpretation * model * arguments) option *)
  6.1927 -      fun interpret_groundtype () =
  6.1928        let
  6.1929 -        (* the model must specify a size for ground types *)
  6.1930 -        val size = if T = Term.propT then 2
  6.1931 -          else the (AList.lookup (op =) typs T)
  6.1932 -        val next = next_idx+size
  6.1933 -        (* check if 'maxvars' is large enough *)
  6.1934 -        val _    = (if next-1>maxvars andalso maxvars>0 then
  6.1935 -          raise MAXVARS_EXCEEDED else ())
  6.1936 -        (* prop_formula list *)
  6.1937 -        val fms  = map BoolVar (next_idx upto (next_idx+size-1))
  6.1938 -        (* interpretation *)
  6.1939 -        val intr = Leaf fms
  6.1940 -        (* prop_formula list -> prop_formula *)
  6.1941 -        fun one_of_two_false []      = True
  6.1942 -          | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
  6.1943 -          SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  6.1944 -        (* prop_formula *)
  6.1945 -        val wf   = one_of_two_false fms
  6.1946 +        (* unit -> (interpretation * model * arguments) option *)
  6.1947 +        fun interpret_groundtype () =
  6.1948 +          let
  6.1949 +            (* the model must specify a size for ground types *)
  6.1950 +            val size =
  6.1951 +              if T = Term.propT then 2
  6.1952 +              else the (AList.lookup (op =) typs T)
  6.1953 +            val next = next_idx + size
  6.1954 +            (* check if 'maxvars' is large enough *)
  6.1955 +            val _ = (if next - 1 > maxvars andalso maxvars > 0 then
  6.1956 +              raise MAXVARS_EXCEEDED else ())
  6.1957 +            (* prop_formula list *)
  6.1958 +            val fms  = map BoolVar (next_idx upto (next_idx + size - 1))
  6.1959 +            (* interpretation *)
  6.1960 +            val intr = Leaf fms
  6.1961 +            (* prop_formula list -> prop_formula *)
  6.1962 +            fun one_of_two_false [] = True
  6.1963 +              | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
  6.1964 +                  SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  6.1965 +            (* prop_formula *)
  6.1966 +            val wf = one_of_two_false fms
  6.1967 +          in
  6.1968 +            (* extend the model, increase 'next_idx', add well-formedness *)
  6.1969 +            (* condition                                                  *)
  6.1970 +            SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
  6.1971 +              def_eq = def_eq, next_idx = next, bounds = bounds,
  6.1972 +              wellformed = SAnd (wellformed, wf)})
  6.1973 +          end
  6.1974        in
  6.1975 -        (* extend the model, increase 'next_idx', add well-formedness *)
  6.1976 -        (* condition                                                  *)
  6.1977 -        SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
  6.1978 -          def_eq = def_eq, next_idx = next, bounds = bounds,
  6.1979 -          wellformed = SAnd (wellformed, wf)})
  6.1980 +        case T of
  6.1981 +          Type ("fun", [T1, T2]) =>
  6.1982 +            let
  6.1983 +              (* we create 'size_of_type ... T1' different copies of the        *)
  6.1984 +              (* interpretation for 'T2', which are then combined into a single *)
  6.1985 +              (* new interpretation                                             *)
  6.1986 +              (* make fresh copies, with different variable indices *)
  6.1987 +              (* 'idx': next variable index                         *)
  6.1988 +              (* 'n'  : number of copies                            *)
  6.1989 +              (* int -> int -> (int * interpretation list * prop_formula *)
  6.1990 +              fun make_copies idx 0 = (idx, [], True)
  6.1991 +                | make_copies idx n =
  6.1992 +                    let
  6.1993 +                      val (copy, _, new_args) = interpret ctxt (typs, [])
  6.1994 +                        {maxvars = maxvars, def_eq = false, next_idx = idx,
  6.1995 +                        bounds = [], wellformed = True} (Free ("dummy", T2))
  6.1996 +                      val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
  6.1997 +                    in
  6.1998 +                      (idx', copy :: copies, SAnd (#wellformed new_args, wf'))
  6.1999 +                    end
  6.2000 +              val (next, copies, wf) = make_copies next_idx
  6.2001 +                (size_of_type ctxt model T1)
  6.2002 +              (* combine copies into a single interpretation *)
  6.2003 +              val intr = Node copies
  6.2004 +            in
  6.2005 +              (* extend the model, increase 'next_idx', add well-formedness *)
  6.2006 +              (* condition                                                  *)
  6.2007 +              SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
  6.2008 +                def_eq = def_eq, next_idx = next, bounds = bounds,
  6.2009 +                wellformed = SAnd (wellformed, wf)})
  6.2010 +            end
  6.2011 +        | Type _  => interpret_groundtype ()
  6.2012 +        | TFree _ => interpret_groundtype ()
  6.2013 +        | TVar  _ => interpret_groundtype ()
  6.2014        end
  6.2015 -    in
  6.2016 -      case T of
  6.2017 -        Type ("fun", [T1, T2]) =>
  6.2018 -        let
  6.2019 -          (* we create 'size_of_type ... T1' different copies of the        *)
  6.2020 -          (* interpretation for 'T2', which are then combined into a single *)
  6.2021 -          (* new interpretation                                             *)
  6.2022 -          (* make fresh copies, with different variable indices *)
  6.2023 -          (* 'idx': next variable index                         *)
  6.2024 -          (* 'n'  : number of copies                            *)
  6.2025 -          (* int -> int -> (int * interpretation list * prop_formula *)
  6.2026 -          fun make_copies idx 0 =
  6.2027 -            (idx, [], True)
  6.2028 -            | make_copies idx n =
  6.2029 -            let
  6.2030 -              val (copy, _, new_args) = interpret thy (typs, [])
  6.2031 -                {maxvars = maxvars, def_eq = false, next_idx = idx,
  6.2032 -                bounds = [], wellformed = True} (Free ("dummy", T2))
  6.2033 -              val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
  6.2034 -            in
  6.2035 -              (idx', copy :: copies, SAnd (#wellformed new_args, wf'))
  6.2036 -            end
  6.2037 -          val (next, copies, wf) = make_copies next_idx
  6.2038 -            (size_of_type thy model T1)
  6.2039 -          (* combine copies into a single interpretation *)
  6.2040 -          val intr = Node copies
  6.2041 -        in
  6.2042 -          (* extend the model, increase 'next_idx', add well-formedness *)
  6.2043 -          (* condition                                                  *)
  6.2044 -          SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
  6.2045 -            def_eq = def_eq, next_idx = next, bounds = bounds,
  6.2046 -            wellformed = SAnd (wellformed, wf)})
  6.2047 -        end
  6.2048 -      | Type _  => interpret_groundtype ()
  6.2049 -      | TFree _ => interpret_groundtype ()
  6.2050 -      | TVar  _ => interpret_groundtype ()
  6.2051 -    end
  6.2052    in
  6.2053      case AList.lookup (op =) terms t of
  6.2054        SOME intr =>
  6.2055 -      (* return an existing interpretation *)
  6.2056 -      SOME (intr, model, args)
  6.2057 +        (* return an existing interpretation *)
  6.2058 +        SOME (intr, model, args)
  6.2059      | NONE =>
  6.2060 -      (case t of
  6.2061 -        Const (_, T)     =>
  6.2062 -        interpret_groundterm T
  6.2063 -      | Free (_, T)      =>
  6.2064 -        interpret_groundterm T
  6.2065 -      | Var (_, T)       =>
  6.2066 -        interpret_groundterm T
  6.2067 -      | Bound i          =>
  6.2068 -        SOME (List.nth (#bounds args, i), model, args)
  6.2069 -      | Abs (x, T, body) =>
  6.2070 -        let
  6.2071 -          (* create all constants of type 'T' *)
  6.2072 -          val constants = make_constants thy model T
  6.2073 -          (* interpret the 'body' separately for each constant *)
  6.2074 -          val (bodies, (model', args')) = fold_map
  6.2075 -            (fn c => fn (m, a) =>
  6.2076 -              let
  6.2077 -                (* add 'c' to 'bounds' *)
  6.2078 -                val (i', m', a') = interpret thy m {maxvars = #maxvars a,
  6.2079 -                  def_eq = #def_eq a, next_idx = #next_idx a,
  6.2080 -                  bounds = (c :: #bounds a), wellformed = #wellformed a} body
  6.2081 -              in
  6.2082 -                (* keep the new model m' and 'next_idx' and 'wellformed', *)
  6.2083 -                (* but use old 'bounds'                                   *)
  6.2084 -                (i', (m', {maxvars = maxvars, def_eq = def_eq,
  6.2085 -                  next_idx = #next_idx a', bounds = bounds,
  6.2086 -                  wellformed = #wellformed a'}))
  6.2087 -              end)
  6.2088 -            constants (model, args)
  6.2089 -        in
  6.2090 -          SOME (Node bodies, model', args')
  6.2091 -        end
  6.2092 -      | t1 $ t2 =>
  6.2093 -        let
  6.2094 -          (* interpret 't1' and 't2' separately *)
  6.2095 -          val (intr1, model1, args1) = interpret thy model args t1
  6.2096 -          val (intr2, model2, args2) = interpret thy model1 args1 t2
  6.2097 -        in
  6.2098 -          SOME (interpretation_apply (intr1, intr2), model2, args2)
  6.2099 -        end)
  6.2100 +        (case t of
  6.2101 +          Const (_, T) => interpret_groundterm T
  6.2102 +        | Free (_, T) => interpret_groundterm T
  6.2103 +        | Var (_, T) => interpret_groundterm T
  6.2104 +        | Bound i => SOME (List.nth (#bounds args, i), model, args)
  6.2105 +        | Abs (x, T, body) =>
  6.2106 +            let
  6.2107 +              (* create all constants of type 'T' *)
  6.2108 +              val constants = make_constants ctxt model T
  6.2109 +              (* interpret the 'body' separately for each constant *)
  6.2110 +              val (bodies, (model', args')) = fold_map
  6.2111 +                (fn c => fn (m, a) =>
  6.2112 +                  let
  6.2113 +                    (* add 'c' to 'bounds' *)
  6.2114 +                    val (i', m', a') = interpret ctxt m {maxvars = #maxvars a,
  6.2115 +                      def_eq = #def_eq a, next_idx = #next_idx a,
  6.2116 +                      bounds = (c :: #bounds a), wellformed = #wellformed a} body
  6.2117 +                  in
  6.2118 +                    (* keep the new model m' and 'next_idx' and 'wellformed', *)
  6.2119 +                    (* but use old 'bounds'                                   *)
  6.2120 +                    (i', (m', {maxvars = maxvars, def_eq = def_eq,
  6.2121 +                      next_idx = #next_idx a', bounds = bounds,
  6.2122 +                      wellformed = #wellformed a'}))
  6.2123 +                  end)
  6.2124 +                constants (model, args)
  6.2125 +            in
  6.2126 +              SOME (Node bodies, model', args')
  6.2127 +            end
  6.2128 +        | t1 $ t2 =>
  6.2129 +            let
  6.2130 +              (* interpret 't1' and 't2' separately *)
  6.2131 +              val (intr1, model1, args1) = interpret ctxt model args t1
  6.2132 +              val (intr2, model2, args2) = interpret ctxt model1 args1 t2
  6.2133 +            in
  6.2134 +              SOME (interpretation_apply (intr1, intr2), model2, args2)
  6.2135 +            end)
  6.2136    end;
  6.2137  
  6.2138 -  (* theory -> model -> arguments -> Term.term ->
  6.2139 -    (interpretation * model * arguments) option *)
  6.2140 -
  6.2141 -  fun Pure_interpreter thy model args t =
  6.2142 -    case t of
  6.2143 -      Const (@{const_name all}, _) $ t1 =>
  6.2144 +fun Pure_interpreter ctxt model args t =
  6.2145 +  case t of
  6.2146 +    Const (@{const_name all}, _) $ t1 =>
  6.2147        let
  6.2148 -        val (i, m, a) = interpret thy model args t1
  6.2149 +        val (i, m, a) = interpret ctxt model args t1
  6.2150        in
  6.2151          case i of
  6.2152            Node xs =>
  6.2153 -          (* 3-valued logic *)
  6.2154 -          let
  6.2155 -            val fmTrue  = PropLogic.all (map toTrue xs)
  6.2156 -            val fmFalse = PropLogic.exists (map toFalse xs)
  6.2157 -          in
  6.2158 -            SOME (Leaf [fmTrue, fmFalse], m, a)
  6.2159 -          end
  6.2160 +            (* 3-valued logic *)
  6.2161 +            let
  6.2162 +              val fmTrue  = PropLogic.all (map toTrue xs)
  6.2163 +              val fmFalse = PropLogic.exists (map toFalse xs)
  6.2164 +            in
  6.2165 +              SOME (Leaf [fmTrue, fmFalse], m, a)
  6.2166 +            end
  6.2167          | _ =>
  6.2168            raise REFUTE ("Pure_interpreter",
  6.2169              "\"all\" is followed by a non-function")
  6.2170        end
  6.2171 -    | Const (@{const_name all}, _) =>
  6.2172 -      SOME (interpret thy model args (eta_expand t 1))
  6.2173 -    | Const (@{const_name "=="}, _) $ t1 $ t2 =>
  6.2174 +  | Const (@{const_name all}, _) =>
  6.2175 +      SOME (interpret ctxt model args (eta_expand t 1))
  6.2176 +  | Const (@{const_name "=="}, _) $ t1 $ t2 =>
  6.2177        let
  6.2178 -        val (i1, m1, a1) = interpret thy model args t1
  6.2179 -        val (i2, m2, a2) = interpret thy m1 a1 t2
  6.2180 +        val (i1, m1, a1) = interpret ctxt model args t1
  6.2181 +        val (i2, m2, a2) = interpret ctxt m1 a1 t2
  6.2182        in
  6.2183          (* we use either 'make_def_equality' or 'make_equality' *)
  6.2184          SOME ((if #def_eq args then make_def_equality else make_equality)
  6.2185            (i1, i2), m2, a2)
  6.2186        end
  6.2187 -    | Const (@{const_name "=="}, _) $ t1 =>
  6.2188 -      SOME (interpret thy model args (eta_expand t 1))
  6.2189 -    | Const (@{const_name "=="}, _) =>
  6.2190 -      SOME (interpret thy model args (eta_expand t 2))
  6.2191 -    | Const (@{const_name "==>"}, _) $ t1 $ t2 =>
  6.2192 +  | Const (@{const_name "=="}, _) $ t1 =>
  6.2193 +      SOME (interpret ctxt model args (eta_expand t 1))
  6.2194 +  | Const (@{const_name "=="}, _) =>
  6.2195 +      SOME (interpret ctxt model args (eta_expand t 2))
  6.2196 +  | Const (@{const_name "==>"}, _) $ t1 $ t2 =>
  6.2197        (* 3-valued logic *)
  6.2198        let
  6.2199 -        val (i1, m1, a1) = interpret thy model args t1
  6.2200 -        val (i2, m2, a2) = interpret thy m1 a1 t2
  6.2201 +        val (i1, m1, a1) = interpret ctxt model args t1
  6.2202 +        val (i2, m2, a2) = interpret ctxt m1 a1 t2
  6.2203          val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
  6.2204          val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
  6.2205        in
  6.2206          SOME (Leaf [fmTrue, fmFalse], m2, a2)
  6.2207        end
  6.2208 -    | Const (@{const_name "==>"}, _) $ t1 =>
  6.2209 -      SOME (interpret thy model args (eta_expand t 1))
  6.2210 -    | Const (@{const_name "==>"}, _) =>
  6.2211 -      SOME (interpret thy model args (eta_expand t 2))
  6.2212 -    | _ => NONE;
  6.2213 -
  6.2214 -  (* theory -> model -> arguments -> Term.term ->
  6.2215 -    (interpretation * model * arguments) option *)
  6.2216 +  | Const (@{const_name "==>"}, _) $ t1 =>
  6.2217 +      SOME (interpret ctxt model args (eta_expand t 1))
  6.2218 +  | Const (@{const_name "==>"}, _) =>
  6.2219 +      SOME (interpret ctxt model args (eta_expand t 2))
  6.2220 +  | _ => NONE;
  6.2221  
  6.2222 -  fun HOLogic_interpreter thy model args t =
  6.2223 -  (* Providing interpretations directly is more efficient than unfolding the *)
  6.2224 -  (* logical constants.  In HOL however, logical constants can themselves be *)
  6.2225 -  (* arguments.  They are then translated using eta-expansion.               *)
  6.2226 -    case t of
  6.2227 -      Const (@{const_name Trueprop}, _) =>
  6.2228 +fun HOLogic_interpreter ctxt model args t =
  6.2229 +(* Providing interpretations directly is more efficient than unfolding the *)
  6.2230 +(* logical constants.  In HOL however, logical constants can themselves be *)
  6.2231 +(* arguments.  They are then translated using eta-expansion.               *)
  6.2232 +  case t of
  6.2233 +    Const (@{const_name Trueprop}, _) =>
  6.2234        SOME (Node [TT, FF], model, args)
  6.2235 -    | Const (@{const_name Not}, _) =>
  6.2236 +  | Const (@{const_name Not}, _) =>
  6.2237        SOME (Node [FF, TT], model, args)
  6.2238 -    (* redundant, since 'True' is also an IDT constructor *)
  6.2239 -    | Const (@{const_name True}, _) =>
  6.2240 +  (* redundant, since 'True' is also an IDT constructor *)
  6.2241 +  | Const (@{const_name True}, _) =>
  6.2242        SOME (TT, model, args)
  6.2243 -    (* redundant, since 'False' is also an IDT constructor *)
  6.2244 -    | Const (@{const_name False}, _) =>
  6.2245 +  (* redundant, since 'False' is also an IDT constructor *)
  6.2246 +  | Const (@{const_name False}, _) =>
  6.2247        SOME (FF, model, args)
  6.2248 -    | Const (@{const_name All}, _) $ t1 =>  (* similar to "all" (Pure) *)
  6.2249 +  | Const (@{const_name All}, _) $ t1 =>  (* similar to "all" (Pure) *)
  6.2250        let
  6.2251 -        val (i, m, a) = interpret thy model args t1
  6.2252 +        val (i, m, a) = interpret ctxt model args t1
  6.2253        in
  6.2254          case i of
  6.2255            Node xs =>
  6.2256 -          (* 3-valued logic *)
  6.2257 -          let
  6.2258 -            val fmTrue  = PropLogic.all (map toTrue xs)
  6.2259 -            val fmFalse = PropLogic.exists (map toFalse xs)
  6.2260 -          in
  6.2261 -            SOME (Leaf [fmTrue, fmFalse], m, a)
  6.2262 -          end
  6.2263 +            (* 3-valued logic *)
  6.2264 +            let
  6.2265 +              val fmTrue  = PropLogic.all (map toTrue xs)
  6.2266 +              val fmFalse = PropLogic.exists (map toFalse xs)
  6.2267 +            in
  6.2268 +              SOME (Leaf [fmTrue, fmFalse], m, a)
  6.2269 +            end
  6.2270          | _ =>
  6.2271            raise REFUTE ("HOLogic_interpreter",
  6.2272              "\"All\" is followed by a non-function")
  6.2273        end
  6.2274 -    | Const (@{const_name All}, _) =>
  6.2275 -      SOME (interpret thy model args (eta_expand t 1))
  6.2276 -    | Const (@{const_name Ex}, _) $ t1 =>
  6.2277 +  | Const (@{const_name All}, _) =>
  6.2278 +      SOME (interpret ctxt model args (eta_expand t 1))
  6.2279 +  | Const (@{const_name Ex}, _) $ t1 =>
  6.2280        let
  6.2281 -        val (i, m, a) = interpret thy model args t1
  6.2282 +        val (i, m, a) = interpret ctxt model args t1
  6.2283        in
  6.2284          case i of
  6.2285            Node xs =>
  6.2286 -          (* 3-valued logic *)
  6.2287 -          let
  6.2288 -            val fmTrue  = PropLogic.exists (map toTrue xs)
  6.2289 -            val fmFalse = PropLogic.all (map toFalse xs)
  6.2290 -          in
  6.2291 -            SOME (Leaf [fmTrue, fmFalse], m, a)
  6.2292 -          end
  6.2293 +            (* 3-valued logic *)
  6.2294 +            let
  6.2295 +              val fmTrue  = PropLogic.exists (map toTrue xs)
  6.2296 +              val fmFalse = PropLogic.all (map toFalse xs)
  6.2297 +            in
  6.2298 +              SOME (Leaf [fmTrue, fmFalse], m, a)
  6.2299 +            end
  6.2300          | _ =>
  6.2301            raise REFUTE ("HOLogic_interpreter",
  6.2302              "\"Ex\" is followed by a non-function")
  6.2303        end
  6.2304 -    | Const (@{const_name Ex}, _) =>
  6.2305 -      SOME (interpret thy model args (eta_expand t 1))
  6.2306 -    | Const (@{const_name HOL.eq}, _) $ t1 $ t2 =>  (* similar to "==" (Pure) *)
  6.2307 +  | Const (@{const_name Ex}, _) =>
  6.2308 +      SOME (interpret ctxt model args (eta_expand t 1))
  6.2309 +  | Const (@{const_name HOL.eq}, _) $ t1 $ t2 =>  (* similar to "==" (Pure) *)
  6.2310        let
  6.2311 -        val (i1, m1, a1) = interpret thy model args t1
  6.2312 -        val (i2, m2, a2) = interpret thy m1 a1 t2
  6.2313 +        val (i1, m1, a1) = interpret ctxt model args t1
  6.2314 +        val (i2, m2, a2) = interpret ctxt m1 a1 t2
  6.2315        in
  6.2316          SOME (make_equality (i1, i2), m2, a2)
  6.2317        end
  6.2318 -    | Const (@{const_name HOL.eq}, _) $ t1 =>
  6.2319 -      SOME (interpret thy model args (eta_expand t 1))
  6.2320 -    | Const (@{const_name HOL.eq}, _) =>
  6.2321 -      SOME (interpret thy model args (eta_expand t 2))
  6.2322 -    | Const (@{const_name HOL.conj}, _) $ t1 $ t2 =>
  6.2323 +  | Const (@{const_name HOL.eq}, _) $ t1 =>
  6.2324 +      SOME (interpret ctxt model args (eta_expand t 1))
  6.2325 +  | Const (@{const_name HOL.eq}, _) =>
  6.2326 +      SOME (interpret ctxt model args (eta_expand t 2))
  6.2327 +  | Const (@{const_name HOL.conj}, _) $ t1 $ t2 =>
  6.2328        (* 3-valued logic *)
  6.2329        let
  6.2330 -        val (i1, m1, a1) = interpret thy model args t1
  6.2331 -        val (i2, m2, a2) = interpret thy m1 a1 t2
  6.2332 +        val (i1, m1, a1) = interpret ctxt model args t1
  6.2333 +        val (i2, m2, a2) = interpret ctxt m1 a1 t2
  6.2334          val fmTrue       = PropLogic.SAnd (toTrue i1, toTrue i2)
  6.2335          val fmFalse      = PropLogic.SOr (toFalse i1, toFalse i2)
  6.2336        in
  6.2337          SOME (Leaf [fmTrue, fmFalse], m2, a2)
  6.2338        end
  6.2339 -    | Const (@{const_name HOL.conj}, _) $ t1 =>
  6.2340 -      SOME (interpret thy model args (eta_expand t 1))
  6.2341 -    | Const (@{const_name HOL.conj}, _) =>
  6.2342 -      SOME (interpret thy model args (eta_expand t 2))
  6.2343 +  | Const (@{const_name HOL.conj}, _) $ t1 =>
  6.2344 +      SOME (interpret ctxt model args (eta_expand t 1))
  6.2345 +  | Const (@{const_name HOL.conj}, _) =>
  6.2346 +      SOME (interpret ctxt model args (eta_expand t 2))
  6.2347        (* this would make "undef" propagate, even for formulae like *)
  6.2348        (* "False & undef":                                          *)
  6.2349        (* SOME (Node [Node [TT, FF], Node [FF, FF]], model, args) *)
  6.2350 -    | Const (@{const_name HOL.disj}, _) $ t1 $ t2 =>
  6.2351 +  | Const (@{const_name HOL.disj}, _) $ t1 $ t2 =>
  6.2352        (* 3-valued logic *)
  6.2353        let
  6.2354 -        val (i1, m1, a1) = interpret thy model args t1
  6.2355 -        val (i2, m2, a2) = interpret thy m1 a1 t2
  6.2356 +        val (i1, m1, a1) = interpret ctxt model args t1
  6.2357 +        val (i2, m2, a2) = interpret ctxt m1 a1 t2
  6.2358          val fmTrue       = PropLogic.SOr (toTrue i1, toTrue i2)
  6.2359          val fmFalse      = PropLogic.SAnd (toFalse i1, toFalse i2)
  6.2360        in
  6.2361          SOME (Leaf [fmTrue, fmFalse], m2, a2)
  6.2362        end
  6.2363 -    | Const (@{const_name HOL.disj}, _) $ t1 =>
  6.2364 -      SOME (interpret thy model args (eta_expand t 1))
  6.2365 -    | Const (@{const_name HOL.disj}, _) =>
  6.2366 -      SOME (interpret thy model args (eta_expand t 2))
  6.2367 +  | Const (@{const_name HOL.disj}, _) $ t1 =>
  6.2368 +      SOME (interpret ctxt model args (eta_expand t 1))
  6.2369 +  | Const (@{const_name HOL.disj}, _) =>
  6.2370 +      SOME (interpret ctxt model args (eta_expand t 2))
  6.2371        (* this would make "undef" propagate, even for formulae like *)
  6.2372        (* "True | undef":                                           *)
  6.2373        (* SOME (Node [Node [TT, TT], Node [TT, FF]], model, args) *)
  6.2374 -    | Const (@{const_name HOL.implies}, _) $ t1 $ t2 =>  (* similar to "==>" (Pure) *)
  6.2375 +  | Const (@{const_name HOL.implies}, _) $ t1 $ t2 =>  (* similar to "==>" (Pure) *)
  6.2376        (* 3-valued logic *)
  6.2377        let
  6.2378 -        val (i1, m1, a1) = interpret thy model args t1
  6.2379 -        val (i2, m2, a2) = interpret thy m1 a1 t2
  6.2380 +        val (i1, m1, a1) = interpret ctxt model args t1
  6.2381 +        val (i2, m2, a2) = interpret ctxt m1 a1 t2
  6.2382          val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
  6.2383          val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
  6.2384        in
  6.2385          SOME (Leaf [fmTrue, fmFalse], m2, a2)
  6.2386        end
  6.2387 -    | Const (@{const_name HOL.implies}, _) $ t1 =>
  6.2388 -      SOME (interpret thy model args (eta_expand t 1))
  6.2389 -    | Const (@{const_name HOL.implies}, _) =>
  6.2390 -      SOME (interpret thy model args (eta_expand t 2))
  6.2391 +  | Const (@{const_name HOL.implies}, _) $ t1 =>
  6.2392 +      SOME (interpret ctxt model args (eta_expand t 1))
  6.2393 +  | Const (@{const_name HOL.implies}, _) =>
  6.2394 +      SOME (interpret ctxt model args (eta_expand t 2))
  6.2395        (* this would make "undef" propagate, even for formulae like *)
  6.2396        (* "False --> undef":                                        *)
  6.2397        (* SOME (Node [Node [TT, FF], Node [TT, TT]], model, args) *)
  6.2398 -    | _ => NONE;
  6.2399 -
  6.2400 -  (* theory -> model -> arguments -> Term.term ->
  6.2401 -    (interpretation * model * arguments) option *)
  6.2402 +  | _ => NONE;
  6.2403  
  6.2404 -  (* interprets variables and constants whose type is an IDT (this is        *)
  6.2405 -  (* relatively easy and merely requires us to compute the size of the IDT); *)
  6.2406 -  (* constructors of IDTs however are properly interpreted by                *)
  6.2407 -  (* 'IDT_constructor_interpreter'                                           *)
  6.2408 +(* interprets variables and constants whose type is an IDT (this is        *)
  6.2409 +(* relatively easy and merely requires us to compute the size of the IDT); *)
  6.2410 +(* constructors of IDTs however are properly interpreted by                *)
  6.2411 +(* 'IDT_constructor_interpreter'                                           *)
  6.2412  
  6.2413 -  fun IDT_interpreter thy model args t =
  6.2414 +fun IDT_interpreter ctxt model args t =
  6.2415    let
  6.2416 +    val thy = ProofContext.theory_of ctxt
  6.2417      val (typs, terms) = model
  6.2418      (* Term.typ -> (interpretation * model * arguments) option *)
  6.2419      fun interpret_term (Type (s, Ts)) =
  6.2420 -      (case Datatype.get_info thy s of
  6.2421 -        SOME info =>  (* inductive datatype *)
  6.2422 -        let
  6.2423 -          (* int option -- only recursive IDTs have an associated depth *)
  6.2424 -          val depth = AList.lookup (op =) typs (Type (s, Ts))
  6.2425 -          (* sanity check: depth must be at least 0 *)
  6.2426 -          val _ = (case depth of SOME n =>
  6.2427 -            if n<0 then
  6.2428 -              raise REFUTE ("IDT_interpreter", "negative depth")
  6.2429 -            else ()
  6.2430 -            | _ => ())
  6.2431 -        in
  6.2432 -          (* termination condition to avoid infinite recursion *)
  6.2433 -          if depth = (SOME 0) then
  6.2434 -            (* return a leaf of size 0 *)
  6.2435 -            SOME (Leaf [], model, args)
  6.2436 -          else
  6.2437 -            let
  6.2438 -              val index               = #index info
  6.2439 -              val descr               = #descr info
  6.2440 -              val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  6.2441 -              val typ_assoc           = dtyps ~~ Ts
  6.2442 -              (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  6.2443 -              val _ = if Library.exists (fn d =>
  6.2444 -                  case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  6.2445 -                then
  6.2446 -                  raise REFUTE ("IDT_interpreter",
  6.2447 -                    "datatype argument (for type "
  6.2448 -                    ^ Syntax.string_of_typ_global thy (Type (s, Ts))
  6.2449 -                    ^ ") is not a variable")
  6.2450 -                else ()
  6.2451 -              (* if the model specifies a depth for the current type, *)
  6.2452 -              (* decrement it to avoid infinite recursion             *)
  6.2453 -              val typs'    = case depth of NONE => typs | SOME n =>
  6.2454 -                AList.update (op =) (Type (s, Ts), n-1) typs
  6.2455 -              (* recursively compute the size of the datatype *)
  6.2456 -              val size     = size_of_dtyp thy typs' descr typ_assoc constrs
  6.2457 -              val next_idx = #next_idx args
  6.2458 -              val next     = next_idx+size
  6.2459 -              (* check if 'maxvars' is large enough *)
  6.2460 -              val _        = (if next-1 > #maxvars args andalso
  6.2461 -                #maxvars args > 0 then raise MAXVARS_EXCEEDED else ())
  6.2462 -              (* prop_formula list *)
  6.2463 -              val fms      = map BoolVar (next_idx upto (next_idx+size-1))
  6.2464 -              (* interpretation *)
  6.2465 -              val intr     = Leaf fms
  6.2466 -              (* prop_formula list -> prop_formula *)
  6.2467 -              fun one_of_two_false []      = True
  6.2468 -                | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
  6.2469 -                SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  6.2470 -              (* prop_formula *)
  6.2471 -              val wf       = one_of_two_false fms
  6.2472 -            in
  6.2473 -              (* extend the model, increase 'next_idx', add well-formedness *)
  6.2474 -              (* condition                                                  *)
  6.2475 -              SOME (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args,
  6.2476 -                def_eq = #def_eq args, next_idx = next, bounds = #bounds args,
  6.2477 -                wellformed = SAnd (#wellformed args, wf)})
  6.2478 -            end
  6.2479 -        end
  6.2480 -      | NONE =>  (* not an inductive datatype *)
  6.2481 -        NONE)
  6.2482 +          (case Datatype.get_info thy s of
  6.2483 +            SOME info =>  (* inductive datatype *)
  6.2484 +              let
  6.2485 +                (* int option -- only recursive IDTs have an associated depth *)
  6.2486 +                val depth = AList.lookup (op =) typs (Type (s, Ts))
  6.2487 +                (* sanity check: depth must be at least 0 *)
  6.2488 +                val _ =
  6.2489 +                  (case depth of SOME n =>
  6.2490 +                    if n < 0 then
  6.2491 +                      raise REFUTE ("IDT_interpreter", "negative depth")
  6.2492 +                    else ()
  6.2493 +                  | _ => ())
  6.2494 +              in
  6.2495 +                (* termination condition to avoid infinite recursion *)
  6.2496 +                if depth = (SOME 0) then
  6.2497 +                  (* return a leaf of size 0 *)
  6.2498 +                  SOME (Leaf [], model, args)
  6.2499 +                else
  6.2500 +                  let
  6.2501 +                    val index               = #index info
  6.2502 +                    val descr               = #descr info
  6.2503 +                    val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  6.2504 +                    val typ_assoc           = dtyps ~~ Ts
  6.2505 +                    (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  6.2506 +                    val _ =
  6.2507 +                      if Library.exists (fn d =>
  6.2508 +                        case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  6.2509 +                      then
  6.2510 +                        raise REFUTE ("IDT_interpreter",
  6.2511 +                          "datatype argument (for type "
  6.2512 +                          ^ Syntax.string_of_typ ctxt (Type (s, Ts))
  6.2513 +                          ^ ") is not a variable")
  6.2514 +                      else ()
  6.2515 +                    (* if the model specifies a depth for the current type, *)
  6.2516 +                    (* decrement it to avoid infinite recursion             *)
  6.2517 +                    val typs' = case depth of NONE => typs | SOME n =>
  6.2518 +                      AList.update (op =) (Type (s, Ts), n-1) typs
  6.2519 +                    (* recursively compute the size of the datatype *)
  6.2520 +                    val size     = size_of_dtyp ctxt typs' descr typ_assoc constrs
  6.2521 +                    val next_idx = #next_idx args
  6.2522 +                    val next     = next_idx+size
  6.2523 +                    (* check if 'maxvars' is large enough *)
  6.2524 +                    val _        = (if next-1 > #maxvars args andalso
  6.2525 +                      #maxvars args > 0 then raise MAXVARS_EXCEEDED else ())
  6.2526 +                    (* prop_formula list *)
  6.2527 +                    val fms      = map BoolVar (next_idx upto (next_idx+size-1))
  6.2528 +                    (* interpretation *)
  6.2529 +                    val intr     = Leaf fms
  6.2530 +                    (* prop_formula list -> prop_formula *)
  6.2531 +                    fun one_of_two_false [] = True
  6.2532 +                      | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
  6.2533 +                          SOr (SNot x, SNot x')) xs), one_of_two_false xs)
  6.2534 +                    (* prop_formula *)
  6.2535 +                    val wf = one_of_two_false fms
  6.2536 +                  in
  6.2537 +                    (* extend the model, increase 'next_idx', add well-formedness *)
  6.2538 +                    (* condition                                                  *)
  6.2539 +                    SOME (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args,
  6.2540 +                      def_eq = #def_eq args, next_idx = next, bounds = #bounds args,
  6.2541 +                      wellformed = SAnd (#wellformed args, wf)})
  6.2542 +                  end
  6.2543 +              end
  6.2544 +          | NONE =>  (* not an inductive datatype *)
  6.2545 +              NONE)
  6.2546        | interpret_term _ =  (* a (free or schematic) type variable *)
  6.2547 -      NONE
  6.2548 +          NONE
  6.2549    in
  6.2550      case AList.lookup (op =) terms t of
  6.2551        SOME intr =>
  6.2552 -      (* return an existing interpretation *)
  6.2553 -      SOME (intr, model, args)
  6.2554 +        (* return an existing interpretation *)
  6.2555 +        SOME (intr, model, args)
  6.2556      | NONE =>
  6.2557 -      (case t of
  6.2558 -        Free (_, T)  => interpret_term T
  6.2559 -      | Var (_, T)   => interpret_term T
  6.2560 -      | Const (_, T) => interpret_term T
  6.2561 -      | _            => NONE)
  6.2562 +        (case t of
  6.2563 +          Free (_, T) => interpret_term T
  6.2564 +        | Var (_, T) => interpret_term T
  6.2565 +        | Const (_, T) => interpret_term T
  6.2566 +        | _ => NONE)
  6.2567    end;
  6.2568  
  6.2569 -  (* theory -> model -> arguments -> Term.term ->
  6.2570 -    (interpretation * model * arguments) option *)
  6.2571 +(* This function imposes an order on the elements of a datatype fragment  *)
  6.2572 +(* as follows: C_i x_1 ... x_n < C_j y_1 ... y_m iff i < j or             *)
  6.2573 +(* (x_1, ..., x_n) < (y_1, ..., y_m).  With this order, a constructor is  *)
  6.2574 +(* a function C_i that maps some argument indices x_1, ..., x_n to the    *)
  6.2575 +(* datatype element given by index C_i x_1 ... x_n.  The idea remains the *)
  6.2576 +(* same for recursive datatypes, although the computation of indices gets *)
  6.2577 +(* a little tricky.                                                       *)
  6.2578  
  6.2579 -  (* This function imposes an order on the elements of a datatype fragment  *)
  6.2580 -  (* as follows: C_i x_1 ... x_n < C_j y_1 ... y_m iff i < j or             *)
  6.2581 -  (* (x_1, ..., x_n) < (y_1, ..., y_m).  With this order, a constructor is  *)
  6.2582 -  (* a function C_i that maps some argument indices x_1, ..., x_n to the    *)
  6.2583 -  (* datatype element given by index C_i x_1 ... x_n.  The idea remains the *)
  6.2584 -  (* same for recursive datatypes, although the computation of indices gets *)
  6.2585 -  (* a little tricky.                                                       *)
  6.2586 -
  6.2587 -  fun IDT_constructor_interpreter thy model args t =
  6.2588 +fun IDT_constructor_interpreter ctxt model args t =
  6.2589    let
  6.2590 +    val thy = ProofContext.theory_of ctxt
  6.2591      (* returns a list of canonical representations for terms of the type 'T' *)
  6.2592      (* It would be nice if we could just use 'print' for this, but 'print'   *)
  6.2593      (* for IDTs calls 'IDT_constructor_interpreter' again, and this could    *)
  6.2594      (* lead to infinite recursion when we have (mutually) recursive IDTs.    *)
  6.2595      (* (Term.typ * int) list -> Term.typ -> Term.term list *)
  6.2596      fun canonical_terms typs T =
  6.2597 -      (case T of
  6.2598 -        Type ("fun", [T1, T2]) =>
  6.2599 -        (* 'T2' might contain a recursive IDT, so we cannot use 'print' (at *)
  6.2600 -        (* least not for 'T2'                                               *)
  6.2601 -        let
  6.2602 -          (* returns a list of lists, each one consisting of n (possibly *)
  6.2603 -          (* identical) elements from 'xs'                               *)
  6.2604 -          (* int -> 'a list -> 'a list list *)
  6.2605 -          fun pick_all 1 xs =
  6.2606 -            map single xs
  6.2607 -          | pick_all n xs =
  6.2608 -            let val rec_pick = pick_all (n-1) xs in
  6.2609 -              maps (fn x => map (cons x) rec_pick) xs
  6.2610 -            end
  6.2611 -          (* ["x1", ..., "xn"] *)
  6.2612 -          val terms1 = canonical_terms typs T1
  6.2613 -          (* ["y1", ..., "ym"] *)
  6.2614 -          val terms2 = canonical_terms typs T2
  6.2615 -          (* [[("x1", "y1"), ..., ("xn", "y1")], ..., *)
  6.2616 -          (*   [("x1", "ym"), ..., ("xn", "ym")]]     *)
  6.2617 -          val functions = map (curry (op ~~) terms1)
  6.2618 -            (pick_all (length terms1) terms2)
  6.2619 -          (* [["(x1, y1)", ..., "(xn, y1)"], ..., *)
  6.2620 -          (*   ["(x1, ym)", ..., "(xn, ym)"]]     *)
  6.2621 -          val pairss = map (map HOLogic.mk_prod) functions
  6.2622 -          (* Term.typ *)
  6.2623 -          val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  6.2624 -          val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  6.2625 -          (* Term.term *)
  6.2626 -          val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
  6.2627 -          val HOLogic_insert    =
  6.2628 -            Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  6.2629 -        in
  6.2630 -          (* functions as graphs, i.e. as a (HOL) set of pairs "(x, y)" *)
  6.2631 -          map (fn ps => fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) ps
  6.2632 -            HOLogic_empty_set) pairss
  6.2633 -        end
  6.2634 -      | Type (s, Ts) =>
  6.2635 -        (case Datatype.get_info thy s of
  6.2636 -          SOME info =>
  6.2637 -          (case AList.lookup (op =) typs T of
  6.2638 -            SOME 0 =>
  6.2639 -            (* termination condition to avoid infinite recursion *)
  6.2640 -            []  (* at depth 0, every IDT is empty *)
  6.2641 -          | _ =>
  6.2642 +          (case T of
  6.2643 +            Type ("fun", [T1, T2]) =>
  6.2644 +            (* 'T2' might contain a recursive IDT, so we cannot use 'print' (at *)
  6.2645 +            (* least not for 'T2'                                               *)
  6.2646              let
  6.2647 -              val index               = #index info
  6.2648 -              val descr               = #descr info
  6.2649 -              val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  6.2650 -              val typ_assoc           = dtyps ~~ Ts
  6.2651 -              (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  6.2652 -              val _ = if Library.exists (fn d =>
  6.2653 -                  case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  6.2654 -                then
  6.2655 -                  raise REFUTE ("IDT_constructor_interpreter",
  6.2656 -                    "datatype argument (for type "
  6.2657 -                    ^ Syntax.string_of_typ_global thy T
  6.2658 -                    ^ ") is not a variable")
  6.2659 -                else ()
  6.2660 -              (* decrement depth for the IDT 'T' *)
  6.2661 -              val typs' = (case AList.lookup (op =) typs T of NONE => typs
  6.2662 -                | SOME n => AList.update (op =) (T, n-1) typs)
  6.2663 -              fun constructor_terms terms [] = terms
  6.2664 -                | constructor_terms terms (d::ds) =
  6.2665 +              (* returns a list of lists, each one consisting of n (possibly *)
  6.2666 +              (* identical) elements from 'xs'                               *)
  6.2667 +              (* int -> 'a list -> 'a list list *)
  6.2668 +              fun pick_all 1 xs = map single xs
  6.2669 +                | pick_all n xs =
  6.2670 +                    let val rec_pick = pick_all (n-1) xs in
  6.2671 +                      maps (fn x => map (cons x) rec_pick) xs
  6.2672 +                    end
  6.2673 +              (* ["x1", ..., "xn"] *)
  6.2674 +              val terms1 = canonical_terms typs T1
  6.2675 +              (* ["y1", ..., "ym"] *)
  6.2676 +              val terms2 = canonical_terms typs T2
  6.2677 +              (* [[("x1", "y1"), ..., ("xn", "y1")], ..., *)
  6.2678 +              (*   [("x1", "ym"), ..., ("xn", "ym")]]     *)
  6.2679 +              val functions = map (curry (op ~~) terms1)
  6.2680 +                (pick_all (length terms1) terms2)
  6.2681 +              (* [["(x1, y1)", ..., "(xn, y1)"], ..., *)
  6.2682 +              (*   ["(x1, ym)", ..., "(xn, ym)"]]     *)
  6.2683 +              val pairss = map (map HOLogic.mk_prod) functions
  6.2684 +              (* Term.typ *)
  6.2685 +              val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  6.2686 +              val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  6.2687 +              (* Term.term *)
  6.2688 +              val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
  6.2689 +              val HOLogic_insert    =
  6.2690 +                Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  6.2691 +            in
  6.2692 +              (* functions as graphs, i.e. as a (HOL) set of pairs "(x, y)" *)
  6.2693 +              map (fn ps => fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) ps
  6.2694 +                HOLogic_empty_set) pairss
  6.2695 +            end
  6.2696 +      | Type (s, Ts) =>
  6.2697 +          (case Datatype.get_info thy s of
  6.2698 +            SOME info =>
  6.2699 +              (case AList.lookup (op =) typs T of
  6.2700 +                SOME 0 =>
  6.2701 +                  (* termination condition to avoid infinite recursion *)
  6.2702 +                  []  (* at depth 0, every IDT is empty *)
  6.2703 +              | _ =>
  6.2704                  let
  6.2705 -                  val dT = typ_of_dtyp descr typ_assoc d
  6.2706 -                  val d_terms = canonical_terms typs' dT
  6.2707 +                  val index = #index info
  6.2708 +                  val descr = #descr info
  6.2709 +                  val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  6.2710 +                  val typ_assoc = dtyps ~~ Ts
  6.2711 +                  (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  6.2712 +                  val _ =
  6.2713 +                    if Library.exists (fn d =>
  6.2714 +                      case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  6.2715 +                    then
  6.2716 +                      raise REFUTE ("IDT_constructor_interpreter",
  6.2717 +                        "datatype argument (for type "
  6.2718 +                        ^ Syntax.string_of_typ ctxt T
  6.2719 +                        ^ ") is not a variable")
  6.2720 +                    else ()
  6.2721 +                  (* decrement depth for the IDT 'T' *)
  6.2722 +                  val typs' =
  6.2723 +                    (case AList.lookup (op =) typs T of NONE => typs
  6.2724 +                    | SOME n => AList.update (op =) (T, n-1) typs)
  6.2725 +                  fun constructor_terms terms [] = terms
  6.2726 +                    | constructor_terms terms (d::ds) =
  6.2727 +                        let
  6.2728 +                          val dT = typ_of_dtyp descr typ_assoc d
  6.2729 +                          val d_terms = canonical_terms typs' dT
  6.2730 +                        in
  6.2731 +                          (* C_i x_1 ... x_n < C_i y_1 ... y_n if *)
  6.2732 +                          (* (x_1, ..., x_n) < (y_1, ..., y_n)    *)
  6.2733 +                          constructor_terms
  6.2734 +                            (map_product (curry op $) terms d_terms) ds
  6.2735 +                        end
  6.2736                  in
  6.2737 -                  (* C_i x_1 ... x_n < C_i y_1 ... y_n if *)
  6.2738 -                  (* (x_1, ..., x_n) < (y_1, ..., y_n)    *)
  6.2739 -                  constructor_terms
  6.2740 -                    (map_product (curry op $) terms d_terms) ds
  6.2741 -                end
  6.2742 -            in
  6.2743 -              (* C_i ... < C_j ... if i < j *)
  6.2744 -              maps (fn (cname, ctyps) =>
  6.2745 -                let
  6.2746 -                  val cTerm = Const (cname,
  6.2747 -                    map (typ_of_dtyp descr typ_assoc) ctyps ---> T)
  6.2748 -                in
  6.2749 -                  constructor_terms [cTerm] ctyps
  6.2750 -                end) constrs
  6.2751 -            end)
  6.2752 -        | NONE =>
  6.2753 -          (* not an inductive datatype; in this case the argument types in *)
  6.2754 -          (* 'Ts' may not be IDTs either, so 'print' should be safe        *)
  6.2755 -          map (fn intr => print thy (typs, []) T intr (K false))
  6.2756 -            (make_constants thy (typs, []) T))
  6.2757 +                  (* C_i ... < C_j ... if i < j *)
  6.2758 +                  maps (fn (cname, ctyps) =>
  6.2759 +                    let
  6.2760 +                      val cTerm = Const (cname,
  6.2761 +                        map (typ_of_dtyp descr typ_assoc) ctyps ---> T)
  6.2762 +                    in
  6.2763 +                      constructor_terms [cTerm] ctyps
  6.2764 +                    end) constrs
  6.2765 +                end)
  6.2766 +          | NONE =>
  6.2767 +              (* not an inductive datatype; in this case the argument types in *)
  6.2768 +              (* 'Ts' may not be IDTs either, so 'print' should be safe        *)
  6.2769 +              map (fn intr => print ctxt (typs, []) T intr (K false))
  6.2770 +                (make_constants ctxt (typs, []) T))
  6.2771        | _ =>  (* TFree ..., TVar ... *)
  6.2772 -        map (fn intr => print thy (typs, []) T intr (K false))
  6.2773 -          (make_constants thy (typs, []) T))
  6.2774 +          map (fn intr => print ctxt (typs, []) T intr (K false))
  6.2775 +            (make_constants ctxt (typs, []) T))
  6.2776      val (typs, terms) = model
  6.2777    in
  6.2778      case AList.lookup (op =) terms t of
  6.2779        SOME intr =>
  6.2780 -      (* return an existing interpretation *)
  6.2781 -      SOME (intr, model, args)
  6.2782 +        (* return an existing interpretation *)
  6.2783 +        SOME (intr, model, args)
  6.2784      | NONE =>
  6.2785 -      (case t of
  6.2786 -        Const (s, T) =>
  6.2787 -        (case body_type T of
  6.2788 -          Type (s', Ts') =>
  6.2789 -          (case Datatype.get_info thy s' of
  6.2790 -            SOME info =>  (* body type is an inductive datatype *)
  6.2791 -            let
  6.2792 -              val index               = #index info
  6.2793 -              val descr               = #descr info
  6.2794 -              val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  6.2795 -              val typ_assoc           = dtyps ~~ Ts'
  6.2796 -              (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  6.2797 -              val _ = if Library.exists (fn d =>
  6.2798 -                  case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  6.2799 -                then
  6.2800 -                  raise REFUTE ("IDT_constructor_interpreter",
  6.2801 -                    "datatype argument (for type "
  6.2802 -                    ^ Syntax.string_of_typ_global thy (Type (s', Ts'))
  6.2803 -                    ^ ") is not a variable")
  6.2804 -                else ()
  6.2805 -              (* split the constructors into those occuring before/after *)
  6.2806 -              (* 'Const (s, T)'                                          *)
  6.2807 -              val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
  6.2808 -                not (cname = s andalso Sign.typ_instance thy (T,
  6.2809 -                  map (typ_of_dtyp descr typ_assoc) ctypes
  6.2810 -                    ---> Type (s', Ts')))) constrs
  6.2811 -            in
  6.2812 -              case constrs2 of
  6.2813 -                [] =>
  6.2814 -                (* 'Const (s, T)' is not a constructor of this datatype *)
  6.2815 -                NONE
  6.2816 -              | (_, ctypes)::cs =>
  6.2817 -                let
  6.2818 -                  (* int option -- only /recursive/ IDTs have an associated *)
  6.2819 -                  (*               depth                                    *)
  6.2820 -                  val depth = AList.lookup (op =) typs (Type (s', Ts'))
  6.2821 -                  (* this should never happen: at depth 0, this IDT fragment *)
  6.2822 -                  (* is definitely empty, and in this case we don't need to  *)
  6.2823 -                  (* interpret its constructors                              *)
  6.2824 -                  val _ = (case depth of SOME 0 =>
  6.2825 -                      raise REFUTE ("IDT_constructor_interpreter",
  6.2826 -                        "depth is 0")
  6.2827 -                    | _ => ())
  6.2828 -                  val typs' = (case depth of NONE => typs | SOME n =>
  6.2829 -                    AList.update (op =) (Type (s', Ts'), n-1) typs)
  6.2830 -                  (* elements of the datatype come before elements generated *)
  6.2831 -                  (* by 'Const (s, T)' iff they are generated by a           *)
  6.2832 -                  (* constructor in constrs1                                 *)
  6.2833 -                  val offset = size_of_dtyp thy typs' descr typ_assoc constrs1
  6.2834 -                  (* compute the total (current) size of the datatype *)
  6.2835 -                  val total = offset +
  6.2836 -                    size_of_dtyp thy typs' descr typ_assoc constrs2
  6.2837 -                  (* sanity check *)
  6.2838 -                  val _ = if total <> size_of_type thy (typs, [])
  6.2839 -                    (Type (s', Ts')) then
  6.2840 -                      raise REFUTE ("IDT_constructor_interpreter",
  6.2841 -                        "total is not equal to current size")
  6.2842 -                    else ()
  6.2843 -                  (* returns an interpretation where everything is mapped to *)
  6.2844 -                  (* an "undefined" element of the datatype                  *)
  6.2845 -                  fun make_undef [] =
  6.2846 -                    Leaf (replicate total False)
  6.2847 -                    | make_undef (d::ds) =
  6.2848 +        (case t of
  6.2849 +          Const (s, T) =>
  6.2850 +            (case body_type T of
  6.2851 +              Type (s', Ts') =>
  6.2852 +                (case Datatype.get_info thy s' of
  6.2853 +                  SOME info =>  (* body type is an inductive datatype *)
  6.2854                      let
  6.2855 -                      (* compute the current size of the type 'd' *)
  6.2856 -                      val dT   = typ_of_dtyp descr typ_assoc d
  6.2857 -                      val size = size_of_type thy (typs, []) dT
  6.2858 -                    in
  6.2859 -                      Node (replicate size (make_undef ds))
  6.2860 -                    end
  6.2861 -                  (* returns the interpretation for a constructor *)
  6.2862 -                  fun make_constr [] offset =
  6.2863 -                    if offset < total then
  6.2864 -                      (Leaf (replicate offset False @ True ::
  6.2865 -                        (replicate (total - offset - 1) False)), offset + 1)
  6.2866 -                    else
  6.2867 -                      raise REFUTE ("IDT_constructor_interpreter",
  6.2868 -                        "offset >= total")
  6.2869 -                    | make_constr (d::ds) offset =
  6.2870 -                    let
  6.2871 -                      (* Term.typ *)
  6.2872 -                      val dT = typ_of_dtyp descr typ_assoc d
  6.2873 -                      (* compute canonical term representations for all   *)
  6.2874 -                      (* elements of the type 'd' (with the reduced depth *)
  6.2875 -                      (* for the IDT)                                     *)
  6.2876 -                      val terms' = canonical_terms typs' dT
  6.2877 -                      (* sanity check *)
  6.2878 -                      val _ =
  6.2879 -                        if length terms' <> size_of_type thy (typs', []) dT
  6.2880 +                      val index               = #index info
  6.2881 +                      val descr               = #descr info
  6.2882 +                      val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  6.2883 +                      val typ_assoc           = dtyps ~~ Ts'
  6.2884 +                      (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  6.2885 +                      val _ = if Library.exists (fn d =>
  6.2886 +                          case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  6.2887                          then
  6.2888                            raise REFUTE ("IDT_constructor_interpreter",
  6.2889 -                            "length of terms' is not equal to old size")
  6.2890 -                        else ()
  6.2891 -                      (* compute canonical term representations for all   *)
  6.2892 -                      (* elements of the type 'd' (with the current depth *)
  6.2893 -                      (* for the IDT)                                     *)
  6.2894 -                      val terms = canonical_terms typs dT
  6.2895 -                      (* sanity check *)
  6.2896 -                      val _ =
  6.2897 -                        if length terms <> size_of_type thy (typs, []) dT
  6.2898 -                        then
  6.2899 -                          raise REFUTE ("IDT_constructor_interpreter",
  6.2900 -                            "length of terms is not equal to current size")
  6.2901 -                        else ()
  6.2902 -                      (* sanity check *)
  6.2903 -                      val _ =
  6.2904 -                        if length terms < length terms' then
  6.2905 -                          raise REFUTE ("IDT_constructor_interpreter",
  6.2906 -                            "current size is less than old size")
  6.2907 +                            "datatype argument (for type "
  6.2908 +                            ^ Syntax.string_of_typ ctxt (Type (s', Ts'))
  6.2909 +                            ^ ") is not a variable")
  6.2910                          else ()
  6.2911 -                      (* sanity check: every element of terms' must also be *)
  6.2912 -                      (*               present in terms                     *)
  6.2913 -                      val _ =
  6.2914 -                        if forall (member (op =) terms) terms' then ()
  6.2915 -                        else
  6.2916 -                          raise REFUTE ("IDT_constructor_interpreter",
  6.2917 -                            "element has disappeared")
  6.2918 -                      (* sanity check: the order on elements of terms' is    *)
  6.2919 -                      (*               the same in terms, for those elements *)
  6.2920 -                      val _ =
  6.2921 -                        let
  6.2922 -                          fun search (x::xs) (y::ys) =
  6.2923 -                                if x = y then search xs ys else search (x::xs) ys
  6.2924 -                            | search (x::xs) [] =
  6.2925 +                      (* split the constructors into those occuring before/after *)
  6.2926 +                      (* 'Const (s, T)'                                          *)
  6.2927 +                      val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
  6.2928 +                        not (cname = s andalso Sign.typ_instance thy (T,
  6.2929 +                          map (typ_of_dtyp descr typ_assoc) ctypes
  6.2930 +                            ---> Type (s', Ts')))) constrs
  6.2931 +                    in
  6.2932 +                      case constrs2 of
  6.2933 +                        [] =>
  6.2934 +                          (* 'Const (s, T)' is not a constructor of this datatype *)
  6.2935 +                          NONE
  6.2936 +                      | (_, ctypes)::cs =>
  6.2937 +                          let
  6.2938 +                            (* int option -- only /recursive/ IDTs have an associated *)
  6.2939 +                            (*               depth                                    *)
  6.2940 +                            val depth = AList.lookup (op =) typs (Type (s', Ts'))
  6.2941 +                            (* this should never happen: at depth 0, this IDT fragment *)
  6.2942 +                            (* is definitely empty, and in this case we don't need to  *)
  6.2943 +                            (* interpret its constructors                              *)
  6.2944 +                            val _ = (case depth of SOME 0 =>
  6.2945 +                                raise REFUTE ("IDT_constructor_interpreter",
  6.2946 +                                  "depth is 0")
  6.2947 +                              | _ => ())
  6.2948 +                            val typs' = (case depth of NONE => typs | SOME n =>
  6.2949 +                              AList.update (op =) (Type (s', Ts'), n-1) typs)
  6.2950 +                            (* elements of the datatype come before elements generated *)
  6.2951 +                            (* by 'Const (s, T)' iff they are generated by a           *)
  6.2952 +                            (* constructor in constrs1                                 *)
  6.2953 +                            val offset = size_of_dtyp ctxt typs' descr typ_assoc constrs1
  6.2954 +                            (* compute the total (current) size of the datatype *)
  6.2955 +                            val total = offset +
  6.2956 +                              size_of_dtyp ctxt typs' descr typ_assoc constrs2
  6.2957 +                            (* sanity check *)
  6.2958 +                            val _ = if total <> size_of_type ctxt (typs, [])
  6.2959 +                              (Type (s', Ts')) then
  6.2960                                  raise REFUTE ("IDT_constructor_interpreter",
  6.2961 -                                  "element order not preserved")
  6.2962 -                            | search [] _ = ()
  6.2963 -                        in  search terms' terms  end
  6.2964 -                      (* int * interpretation list *)
  6.2965 -                      val (intrs, new_offset) =
  6.2966 -                        fold_map (fn t_elem => fn off =>
  6.2967 -                          (* if 't_elem' existed at the previous depth,    *)
  6.2968 -                          (* proceed recursively, otherwise map the entire *)
  6.2969 -                          (* subtree to "undefined"                        *)
  6.2970 -                          if member (op =) terms' t_elem then
  6.2971 -                            make_constr ds off
  6.2972 -                          else
  6.2973 -                            (make_undef ds, off))
  6.2974 -                        terms offset
  6.2975 -                    in
  6.2976 -                      (Node intrs, new_offset)
  6.2977 +                                  "total is not equal to current size")
  6.2978 +                              else ()
  6.2979 +                            (* returns an interpretation where everything is mapped to *)
  6.2980 +                            (* an "undefined" element of the datatype                  *)
  6.2981 +                            fun make_undef [] = Leaf (replicate total False)
  6.2982 +                              | make_undef (d::ds) =
  6.2983 +                                  let
  6.2984 +                                    (* compute the current size of the type 'd' *)
  6.2985 +                                    val dT   = typ_of_dtyp descr typ_assoc d
  6.2986 +                                    val size = size_of_type ctxt (typs, []) dT
  6.2987 +                                  in
  6.2988 +                                    Node (replicate size (make_undef ds))
  6.2989 +                                  end
  6.2990 +                            (* returns the interpretation for a constructor *)
  6.2991 +                            fun make_constr [] offset =
  6.2992 +                                  if offset < total then
  6.2993 +                                    (Leaf (replicate offset False @ True ::
  6.2994 +                                      (replicate (total - offset - 1) False)), offset + 1)
  6.2995 +                                  else
  6.2996 +                                    raise REFUTE ("IDT_constructor_interpreter",
  6.2997 +                                      "offset >= total")
  6.2998 +                              | make_constr (d::ds) offset =
  6.2999 +                                  let
  6.3000 +                                    (* Term.typ *)
  6.3001 +                                    val dT = typ_of_dtyp descr typ_assoc d
  6.3002 +                                    (* compute canonical term representations for all   *)
  6.3003 +                                    (* elements of the type 'd' (with the reduced depth *)
  6.3004 +                                    (* for the IDT)                                     *)
  6.3005 +                                    val terms' = canonical_terms typs' dT
  6.3006 +                                    (* sanity check *)
  6.3007 +                                    val _ =
  6.3008 +                                      if length terms' <> size_of_type ctxt (typs', []) dT
  6.3009 +                                      then
  6.3010 +                                        raise REFUTE ("IDT_constructor_interpreter",
  6.3011 +                                          "length of terms' is not equal to old size")
  6.3012 +                                      else ()
  6.3013 +                                    (* compute canonical term representations for all   *)
  6.3014 +                                    (* elements of the type 'd' (with the current depth *)
  6.3015 +                                    (* for the IDT)                                     *)
  6.3016 +                                    val terms = canonical_terms typs dT
  6.3017 +                                    (* sanity check *)
  6.3018 +                                    val _ =
  6.3019 +                                      if length terms <> size_of_type ctxt (typs, []) dT
  6.3020 +                                      then
  6.3021 +                                        raise REFUTE ("IDT_constructor_interpreter",
  6.3022 +                                          "length of terms is not equal to current size")
  6.3023 +                                      else ()
  6.3024 +                                    (* sanity check *)
  6.3025 +                                    val _ =
  6.3026 +                                      if length terms < length terms' then
  6.3027 +                                        raise REFUTE ("IDT_constructor_interpreter",
  6.3028 +                                          "current size is less than old size")
  6.3029 +                                      else ()
  6.3030 +                                    (* sanity check: every element of terms' must also be *)
  6.3031 +                                    (*               present in terms                     *)
  6.3032 +                                    val _ =
  6.3033 +                                      if forall (member (op =) terms) terms' then ()
  6.3034 +                                      else
  6.3035 +                                        raise REFUTE ("IDT_constructor_interpreter",
  6.3036 +                                          "element has disappeared")
  6.3037 +                                    (* sanity check: the order on elements of terms' is    *)
  6.3038 +                                    (*               the same in terms, for those elements *)
  6.3039 +                                    val _ =
  6.3040 +                                      let
  6.3041 +                                        fun search (x::xs) (y::ys) =
  6.3042 +                                              if x = y then search xs ys else search (x::xs) ys
  6.3043 +                                          | search (x::xs) [] =
  6.3044 +                                              raise REFUTE ("IDT_constructor_interpreter",
  6.3045 +                                                "element order not preserved")
  6.3046 +                                          | search [] _ = ()
  6.3047 +                                      in search terms' terms end
  6.3048 +                                    (* int * interpretation list *)
  6.3049 +                                    val (intrs, new_offset) =
  6.3050 +                                      fold_map (fn t_elem => fn off =>
  6.3051 +                                        (* if 't_elem' existed at the previous depth,    *)
  6.3052 +                                        (* proceed recursively, otherwise map the entire *)
  6.3053 +                                        (* subtree to "undefined"                        *)
  6.3054 +                                        if member (op =) terms' t_elem then
  6.3055 +                                          make_constr ds off
  6.3056 +                                        else
  6.3057 +                                          (make_undef ds, off))
  6.3058 +                                      terms offset
  6.3059 +                                  in
  6.3060 +                                    (Node intrs, new_offset)
  6.3061 +                                  end
  6.3062 +                          in
  6.3063 +                            SOME (fst (make_constr ctypes offset), model, args)
  6.3064 +                          end
  6.3065                      end
  6.3066 -                in
  6.3067 -                  SOME (fst (make_constr ctypes offset), model, args)
  6.3068 -                end
  6.3069 -            end
  6.3070 -          | NONE =>  (* body type is not an inductive datatype *)
  6.3071 -            NONE)
  6.3072 -        | _ =>  (* body type is a (free or schematic) type variable *)
  6.3073 +                | NONE =>  (* body type is not an inductive datatype *)
  6.3074 +                    NONE)
  6.3075 +            | _ =>  (* body type is a (free or schematic) type variable *)
  6.3076 +              NONE)
  6.3077 +        | _ =>  (* term is not a constant *)
  6.3078            NONE)
  6.3079 -      | _ =>  (* term is not a constant *)
  6.3080 -        NONE)
  6.3081    end;
  6.3082  
  6.3083 -  (* theory -> model -> arguments -> Term.term ->
  6.3084 -    (interpretation * model * arguments) option *)
  6.3085 +(* Difficult code ahead.  Make sure you understand the                *)
  6.3086 +(* 'IDT_constructor_interpreter' and the order in which it enumerates *)
  6.3087 +(* elements of an IDT before you try to understand this function.     *)
  6.3088  
  6.3089 -  (* Difficult code ahead.  Make sure you understand the                *)
  6.3090 -  (* 'IDT_constructor_interpreter' and the order in which it enumerates *)
  6.3091 -  (* elements of an IDT before you try to understand this function.     *)
  6.3092 -
  6.3093 -  fun IDT_recursion_interpreter thy model args t =
  6.3094 +fun IDT_recursion_interpreter ctxt model args t =
  6.3095 +  let
  6.3096 +    val thy = ProofContext.theory_of ctxt
  6.3097 +  in
  6.3098      (* careful: here we descend arbitrarily deep into 't', possibly before *)
  6.3099      (* any other interpreter for atomic terms has had a chance to look at  *)
  6.3100      (* 't'                                                                 *)
  6.3101      case strip_comb t of
  6.3102        (Const (s, T), params) =>
  6.3103 -      (* iterate over all datatypes in 'thy' *)
  6.3104 -      Symtab.fold (fn (_, info) => fn result =>
  6.3105 -        case result of
  6.3106 -          SOME _ =>
  6.3107 -          result  (* just keep 'result' *)
  6.3108 -        | NONE =>
  6.3109 -          if member (op =) (#rec_names info) s then
  6.3110 -            (* we do have a recursion operator of one of the (mutually *)
  6.3111 -            (* recursive) datatypes given by 'info'                    *)
  6.3112 -            let
  6.3113 -              (* number of all constructors, including those of different  *)
  6.3114 -              (* (mutually recursive) datatypes within the same descriptor *)
  6.3115 -              val mconstrs_count =
  6.3116 -                Integer.sum (map (fn (_, (_, _, cs)) => length cs) (#descr info))
  6.3117 -            in
  6.3118 -              if mconstrs_count < length params then
  6.3119 -                (* too many actual parameters; for now we'll use the *)
  6.3120 -                (* 'stlc_interpreter' to strip off one application   *)
  6.3121 -                NONE
  6.3122 -              else if mconstrs_count > length params then
  6.3123 -                (* too few actual parameters; we use eta expansion          *)
  6.3124 -                (* Note that the resulting expansion of lambda abstractions *)
  6.3125 -                (* by the 'stlc_interpreter' may be rather slow (depending  *)
  6.3126 -                (* on the argument types and the size of the IDT, of        *)
  6.3127 -                (* course).                                                 *)
  6.3128 -                SOME (interpret thy model args (eta_expand t
  6.3129 -                  (mconstrs_count - length params)))
  6.3130 -              else  (* mconstrs_count = length params *)
  6.3131 +        (* iterate over all datatypes in 'thy' *)
  6.3132 +        Symtab.fold (fn (_, info) => fn result =>
  6.3133 +          case result of
  6.3134 +            SOME _ =>
  6.3135 +              result  (* just keep 'result' *)
  6.3136 +          | NONE =>
  6.3137 +              if member (op =) (#rec_names info) s then
  6.3138 +                (* we do have a recursion operator of one of the (mutually *)
  6.3139 +                (* recursive) datatypes given by 'info'                    *)
  6.3140                  let
  6.3141 -                  (* interpret each parameter separately *)
  6.3142 -                  val (p_intrs, (model', args')) = fold_map (fn p => fn (m, a) =>
  6.3143 +                  (* number of all constructors, including those of different  *)
  6.3144 +                  (* (mutually recursive) datatypes within the same descriptor *)
  6.3145 +                  val mconstrs_count =
  6.3146 +                    Integer.sum (map (fn (_, (_, _, cs)) => length cs) (#descr info))
  6.3147 +                in
  6.3148 +                  if mconstrs_count < length params then
  6.3149 +                    (* too many actual parameters; for now we'll use the *)
  6.3150 +                    (* 'stlc_interpreter' to strip off one application   *)
  6.3151 +                    NONE
  6.3152 +                  else if mconstrs_count > length params then
  6.3153 +                    (* too few actual parameters; we use eta expansion          *)
  6.3154 +                    (* Note that the resulting expansion of lambda abstractions *)
  6.3155 +                    (* by the 'stlc_interpreter' may be rather slow (depending  *)
  6.3156 +                    (* on the argument types and the size of the IDT, of        *)
  6.3157 +                    (* course).                                                 *)
  6.3158 +                    SOME (interpret ctxt model args (eta_expand t
  6.3159 +                      (mconstrs_count - length params)))
  6.3160 +                  else  (* mconstrs_count = length params *)
  6.3161                      let
  6.3162 -                      val (i, m', a') = interpret thy m a p
  6.3163 -                    in
  6.3164 -                      (i, (m', a'))
  6.3165 -                    end) params (model, args)
  6.3166 -                  val (typs, _) = model'
  6.3167 -                  (* 'index' is /not/ necessarily the index of the IDT that *)
  6.3168 -                  (* the recursion operator is associated with, but merely  *)
  6.3169 -                  (* the index of some mutually recursive IDT               *)
  6.3170 -                  val index         = #index info
  6.3171 -                  val descr         = #descr info
  6.3172 -                  val (_, dtyps, _) = the (AList.lookup (op =) descr index)
  6.3173 -                  (* sanity check: we assume that the order of constructors *)
  6.3174 -                  (*               in 'descr' is the same as the order of   *)
  6.3175 -                  (*               corresponding parameters, otherwise the  *)
  6.3176 -                  (*               association code below won't match the   *)
  6.3177 -                  (*               right constructors/parameters; we also   *)
  6.3178 -                  (*               assume that the order of recursion       *)
  6.3179 -                  (*               operators in '#rec_names info' is the    *)
  6.3180 -                  (*               same as the order of corresponding       *)
  6.3181 -                  (*               datatypes in 'descr'                     *)
  6.3182 -                  val _ = if map fst descr <> (0 upto (length descr - 1)) then
  6.3183 -                      raise REFUTE ("IDT_recursion_interpreter",
  6.3184 -                        "order of constructors and corresponding parameters/" ^
  6.3185 -                          "recursion operators and corresponding datatypes " ^
  6.3186 -                          "different?")
  6.3187 -                    else ()
  6.3188 -                  (* sanity check: every element in 'dtyps' must be a *)
  6.3189 -                  (*               'DtTFree'                          *)
  6.3190 -                  val _ = if Library.exists (fn d =>
  6.3191 -                    case d of Datatype_Aux.DtTFree _ => false
  6.3192 -                            | _ => true) dtyps
  6.3193 -                    then
  6.3194 -                      raise REFUTE ("IDT_recursion_interpreter",
  6.3195 -                        "datatype argument is not a variable")
  6.3196 -                    else ()
  6.3197 -                  (* the type of a recursion operator is *)
  6.3198 -                  (* [T1, ..., Tn, IDT] ---> Tresult     *)
  6.3199 -                  val IDT = List.nth (binder_types T, mconstrs_count)
  6.3200 -                  (* by our assumption on the order of recursion operators *)
  6.3201 -                  (* and datatypes, this is the index of the datatype      *)
  6.3202 -                  (* corresponding to the given recursion operator         *)
  6.3203 -                  val idt_index = find_index (fn s' => s' = s) (#rec_names info)
  6.3204 -                  (* mutually recursive types must have the same type   *)
  6.3205 -                  (* parameters, unless the mutual recursion comes from *)
  6.3206 -                  (* indirect recursion                                 *)
  6.3207 -                  fun rec_typ_assoc acc [] =
  6.3208 -                    acc
  6.3209 -                    | rec_typ_assoc acc ((d, T)::xs) =
  6.3210 -                    (case AList.lookup op= acc d of
  6.3211 -                      NONE =>
  6.3212 -                      (case d of
  6.3213 -                        Datatype_Aux.DtTFree _ =>
  6.3214 -                        (* add the association, proceed *)
  6.3215 -                        rec_typ_assoc ((d, T)::acc) xs
  6.3216 -                      | Datatype_Aux.DtType (s, ds) =>
  6.3217 +                      (* interpret each parameter separately *)
  6.3218 +                      val (p_intrs, (model', args')) = fold_map (fn p => fn (m, a) =>
  6.3219 +                        let
  6.3220 +                          val (i, m', a') = interpret ctxt m a p
  6.3221 +                        in
  6.3222 +                          (i, (m', a'))
  6.3223 +                        end) params (model, args)
  6.3224 +                      val (typs, _) = model'
  6.3225 +                      (* 'index' is /not/ necessarily the index of the IDT that *)
  6.3226 +                      (* the recursion operator is associated with, but merely  *)
  6.3227 +                      (* the index of some mutually recursive IDT               *)
  6.3228 +                      val index         = #index info
  6.3229 +                      val descr         = #descr info
  6.3230 +                      val (_, dtyps, _) = the (AList.lookup (op =) descr index)
  6.3231 +                      (* sanity check: we assume that the order of constructors *)
  6.3232 +                      (*               in 'descr' is the same as the order of   *)
  6.3233 +                      (*               corresponding parameters, otherwise the  *)
  6.3234 +                      (*               association code below won't match the   *)
  6.3235 +                      (*               right constructors/parameters; we also   *)
  6.3236 +                      (*               assume that the order of recursion       *)
  6.3237 +                      (*               operators in '#rec_names info' is the    *)
  6.3238 +                      (*               same as the order of corresponding       *)
  6.3239 +                      (*               datatypes in 'descr'                     *)
  6.3240 +                      val _ = if map fst descr <> (0 upto (length descr - 1)) then
  6.3241 +                          raise REFUTE ("IDT_recursion_interpreter",
  6.3242 +                            "order of constructors and corresponding parameters/" ^
  6.3243 +                              "recursion operators and corresponding datatypes " ^
  6.3244 +                              "different?")
  6.3245 +                        else ()
  6.3246 +                      (* sanity check: every element in 'dtyps' must be a *)
  6.3247 +                      (*               'DtTFree'                          *)
  6.3248 +                      val _ =
  6.3249 +                        if Library.exists (fn d =>
  6.3250 +                          case d of Datatype_Aux.DtTFree _ => false
  6.3251 +                                  | _ => true) dtyps
  6.3252 +                        then
  6.3253 +                          raise REFUTE ("IDT_recursion_interpreter",
  6.3254 +                            "datatype argument is not a variable")
  6.3255 +                        else ()
  6.3256 +                      (* the type of a recursion operator is *)
  6.3257 +                      (* [T1, ..., Tn, IDT] ---> Tresult     *)
  6.3258 +                      val IDT = List.nth (binder_types T, mconstrs_count)
  6.3259 +                      (* by our assumption on the order of recursion operators *)
  6.3260 +                      (* and datatypes, this is the index of the datatype      *)
  6.3261 +                      (* corresponding to the given recursion operator         *)
  6.3262 +                      val idt_index = find_index (fn s' => s' = s) (#rec_names info)
  6.3263 +                      (* mutually recursive types must have the same type   *)
  6.3264 +                      (* parameters, unless the mutual recursion comes from *)
  6.3265 +                      (* indirect recursion                                 *)
  6.3266 +                      fun rec_typ_assoc acc [] = acc
  6.3267 +                        | rec_typ_assoc acc ((d, T)::xs) =
  6.3268 +                            (case AList.lookup op= acc d of
  6.3269 +                              NONE =>
  6.3270 +                                (case d of
  6.3271 +                                  Datatype_Aux.DtTFree _ =>
  6.3272 +                                  (* add the association, proceed *)
  6.3273 +                                  rec_typ_assoc ((d, T)::acc) xs
  6.3274 +                                | Datatype_Aux.DtType (s, ds) =>
  6.3275 +                                    let
  6.3276 +                                      val (s', Ts) = dest_Type T
  6.3277 +                                    in
  6.3278 +                                      if s=s' then
  6.3279 +                                        rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
  6.3280 +                                      else
  6.3281 +                                        raise REFUTE ("IDT_recursion_interpreter",
  6.3282 +                                          "DtType/Type mismatch")
  6.3283 +                                    end
  6.3284 +                                | Datatype_Aux.DtRec i =>
  6.3285 +                                    let
  6.3286 +                                      val (_, ds, _) = the (AList.lookup (op =) descr i)
  6.3287 +                                      val (_, Ts)    = dest_Type T
  6.3288 +                                    in
  6.3289 +                                      rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
  6.3290 +                                    end)
  6.3291 +                            | SOME T' =>
  6.3292 +                                if T=T' then
  6.3293 +                                  (* ignore the association since it's already *)
  6.3294 +                                  (* present, proceed                          *)
  6.3295 +                                  rec_typ_assoc acc xs
  6.3296 +                                else
  6.3297 +                                  raise REFUTE ("IDT_recursion_interpreter",
  6.3298 +                                    "different type associations for the same dtyp"))
  6.3299 +                      val typ_assoc = filter
  6.3300 +                        (fn (Datatype_Aux.DtTFree _, _) => true | (_, _) => false)
  6.3301 +                        (rec_typ_assoc []
  6.3302 +                          (#2 (the (AList.lookup (op =) descr idt_index)) ~~ (snd o dest_Type) IDT))
  6.3303 +                      (* sanity check: typ_assoc must associate types to the   *)
  6.3304 +                      (*               elements of 'dtyps' (and only to those) *)
  6.3305 +                      val _ =
  6.3306 +                        if not (eq_set (op =) (dtyps, map fst typ_assoc))
  6.3307 +                        then
  6.3308 +                          raise REFUTE ("IDT_recursion_interpreter",
  6.3309 +                            "type association has extra/missing elements")
  6.3310 +                        else ()
  6.3311 +                      (* interpret each constructor in the descriptor (including *)
  6.3312 +                      (* those of mutually recursive datatypes)                  *)
  6.3313 +                      (* (int * interpretation list) list *)
  6.3314 +                      val mc_intrs = map (fn (idx, (_, _, cs)) =>
  6.3315                          let
  6.3316 -                          val (s', Ts) = dest_Type T
  6.3317 +                          val c_return_typ = typ_of_dtyp descr typ_assoc
  6.3318 +                            (Datatype_Aux.DtRec idx)
  6.3319                          in
  6.3320 -                          if s=s' then
  6.3321 -                            rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
  6.3322 -                          else
  6.3323 +                          (idx, map (fn (cname, cargs) =>
  6.3324 +                            (#1 o interpret ctxt (typs, []) {maxvars=0,
  6.3325 +                              def_eq=false, next_idx=1, bounds=[],
  6.3326 +                              wellformed=True}) (Const (cname, map (typ_of_dtyp
  6.3327 +                              descr typ_assoc) cargs ---> c_return_typ))) cs)
  6.3328 +                        end) descr
  6.3329 +                      (* associate constructors with corresponding parameters *)
  6.3330 +                      (* (int * (interpretation * interpretation) list) list *)
  6.3331 +                      val (mc_p_intrs, p_intrs') = fold_map
  6.3332 +                        (fn (idx, c_intrs) => fn p_intrs' =>
  6.3333 +                          let
  6.3334 +                            val len = length c_intrs
  6.3335 +                          in
  6.3336 +                            ((idx, c_intrs ~~ List.take (p_intrs', len)),
  6.3337 +                              List.drop (p_intrs', len))
  6.3338 +                          end) mc_intrs p_intrs
  6.3339 +                      (* sanity check: no 'p_intr' may be left afterwards *)
  6.3340 +                      val _ =
  6.3341 +                        if p_intrs' <> [] then
  6.3342 +                          raise REFUTE ("IDT_recursion_interpreter",
  6.3343 +                            "more parameter than constructor interpretations")
  6.3344 +                        else ()
  6.3345 +                      (* The recursion operator, applied to 'mconstrs_count'     *)
  6.3346 +                      (* arguments, is a function that maps every element of the *)
  6.3347 +                      (* inductive datatype to an element of some result type.   *)
  6.3348 +                      (* Recursion operators for mutually recursive IDTs are     *)
  6.3349 +                      (* translated simultaneously.                              *)
  6.3350 +                      (* Since the order on datatype elements is given by an     *)
  6.3351 +                      (* order on constructors (and then by the order on         *)
  6.3352 +                      (* argument tuples), we can simply copy corresponding      *)
  6.3353 +                      (* subtrees from 'p_intrs', in the order in which they are *)
  6.3354 +                      (* given.                                                  *)
  6.3355 +                      (* interpretation * interpretation -> interpretation list *)
  6.3356 +                      fun ci_pi (Leaf xs, pi) =
  6.3357 +                            (* if the constructor does not match the arguments to a *)
  6.3358 +                            (* defined element of the IDT, the corresponding value  *)
  6.3359 +                            (* of the parameter must be ignored                     *)
  6.3360 +                            if List.exists (equal True) xs then [pi] else []
  6.3361 +                        | ci_pi (Node xs, Node ys) = maps ci_pi (xs ~~ ys)
  6.3362 +                        | ci_pi (Node _, Leaf _) =
  6.3363                              raise REFUTE ("IDT_recursion_interpreter",
  6.3364 -                              "DtType/Type mismatch")
  6.3365 -                        end
  6.3366 -                      | Datatype_Aux.DtRec i =>
  6.3367 +                              "constructor takes more arguments than the " ^
  6.3368 +                                "associated parameter")
  6.3369 +                      (* (int * interpretation list) list *)
  6.3370 +                      val rec_operators = map (fn (idx, c_p_intrs) =>
  6.3371 +                        (idx, maps ci_pi c_p_intrs)) mc_p_intrs
  6.3372 +                      (* sanity check: every recursion operator must provide as  *)
  6.3373 +                      (*               many values as the corresponding datatype *)
  6.3374 +                      (*               has elements                              *)
  6.3375 +                      val _ = map (fn (idx, intrs) =>
  6.3376                          let
  6.3377 -                          val (_, ds, _) = the (AList.lookup (op =) descr i)
  6.3378 -                          val (_, Ts)    = dest_Type T
  6.3379 +                          val T = typ_of_dtyp descr typ_assoc
  6.3380 +                            (Datatype_Aux.DtRec idx)
  6.3381                          in
  6.3382 -                          rec_typ_assoc ((d, T)::acc) ((ds ~~ Ts) @ xs)
  6.3383 -                        end)
  6.3384 -                    | SOME T' =>
  6.3385 -                      if T=T' then
  6.3386 -                        (* ignore the association since it's already *)
  6.3387 -                        (* present, proceed                          *)
  6.3388 -                        rec_typ_assoc acc xs
  6.3389 -                      else
  6.3390 -                        raise REFUTE ("IDT_recursion_interpreter",
  6.3391 -                          "different type associations for the same dtyp"))
  6.3392 -                  val typ_assoc = filter
  6.3393 -                    (fn (Datatype_Aux.DtTFree _, _) => true | (_, _) => false)
  6.3394 -                    (rec_typ_assoc []
  6.3395 -                      (#2 (the (AList.lookup (op =) descr idt_index)) ~~ (snd o dest_Type) IDT))
  6.3396 -                  (* sanity check: typ_assoc must associate types to the   *)
  6.3397 -                  (*               elements of 'dtyps' (and only to those) *)
  6.3398 -                  val _ = if not (eq_set (op =) (dtyps, map fst typ_assoc))
  6.3399 -                    then
  6.3400 -                      raise REFUTE ("IDT_recursion_interpreter",
  6.3401 -                        "type association has extra/missing elements")
  6.3402 -                    else ()
  6.3403 -                  (* interpret each constructor in the descriptor (including *)
  6.3404 -                  (* those of mutually recursive datatypes)                  *)
  6.3405 -                  (* (int * interpretation list) list *)
  6.3406 -                  val mc_intrs = map (fn (idx, (_, _, cs)) =>
  6.3407 -                    let
  6.3408 -                      val c_return_typ = typ_of_dtyp descr typ_assoc
  6.3409 -                        (Datatype_Aux.DtRec idx)
  6.3410 +                          if length intrs <> size_of_type ctxt (typs, []) T then
  6.3411 +                            raise REFUTE ("IDT_recursion_interpreter",
  6.3412 +                              "wrong number of interpretations for rec. operator")
  6.3413 +                          else ()
  6.3414 +                        end) rec_operators
  6.3415 +                      (* For non-recursive datatypes, we are pretty much done at *)
  6.3416 +                      (* this point.  For recursive datatypes however, we still  *)
  6.3417 +                      (* need to apply the interpretations in 'rec_operators' to *)
  6.3418 +                      (* (recursively obtained) interpretations for recursive    *)
  6.3419 +                      (* constructor arguments.  To do so more efficiently, we   *)
  6.3420 +                      (* copy 'rec_operators' into arrays first.  Each Boolean   *)
  6.3421 +                      (* indicates whether the recursive arguments have been     *)
  6.3422 +                      (* considered already.                                     *)
  6.3423 +                      (* (int * (bool * interpretation) Array.array) list *)
  6.3424 +                      val REC_OPERATORS = map (fn (idx, intrs) =>
  6.3425 +                        (idx, Array.fromList (map (pair false) intrs)))
  6.3426 +                        rec_operators
  6.3427 +                      (* takes an interpretation, and if some leaf of this     *)
  6.3428 +                      (* interpretation is the 'elem'-th element of the type,  *)
  6.3429 +                      (* the indices of the arguments leading to this leaf are *)
  6.3430 +                      (* returned                                              *)
  6.3431 +                      (* interpretation -> int -> int list option *)
  6.3432 +                      fun get_args (Leaf xs) elem =
  6.3433 +                            if find_index (fn x => x = True) xs = elem then
  6.3434 +                              SOME []
  6.3435 +                            else
  6.3436 +                              NONE
  6.3437 +                        | get_args (Node xs) elem =
  6.3438 +                            let
  6.3439 +                              (* interpretation list * int -> int list option *)
  6.3440 +                              fun search ([], _) =
  6.3441 +                                NONE
  6.3442 +                                | search (x::xs, n) =
  6.3443 +                                (case get_args x elem of
  6.3444 +                                  SOME result => SOME (n::result)
  6.3445 +                                | NONE        => search (xs, n+1))
  6.3446 +                            in
  6.3447 +                              search (xs, 0)
  6.3448 +                            end
  6.3449 +                      (* returns the index of the constructor and indices for *)
  6.3450 +                      (* its arguments that generate the 'elem'-th element of *)
  6.3451 +                      (* the datatype given by 'idx'                          *)
  6.3452 +                      (* int -> int -> int * int list *)
  6.3453 +                      fun get_cargs idx elem =
  6.3454 +                        let
  6.3455 +                          (* int * interpretation list -> int * int list *)
  6.3456 +                          fun get_cargs_rec (_, []) =
  6.3457 +                                raise REFUTE ("IDT_recursion_interpreter",
  6.3458 +                                  "no matching constructor found for datatype element")
  6.3459 +                            | get_cargs_rec (n, x::xs) =
  6.3460 +                                (case get_args x elem of
  6.3461 +                                  SOME args => (n, args)
  6.3462 +                                | NONE => get_cargs_rec (n+1, xs))
  6.3463 +                        in
  6.3464 +                          get_cargs_rec (0, the (AList.lookup (op =) mc_intrs idx))
  6.3465 +                        end
  6.3466 +                      (* computes one entry in 'REC_OPERATORS', and recursively *)
  6.3467 +                      (* all entries needed for it, where 'idx' gives the       *)
  6.3468 +                      (* datatype and 'elem' the element of it                  *)
  6.3469 +                      (* int -> int -> interpretation *)
  6.3470 +                      fun compute_array_entry idx elem =
  6.3471 +                        let
  6.3472 +                          val arr = the (AList.lookup (op =) REC_OPERATORS idx)
  6.3473 +                          val (flag, intr) = Array.sub (arr, elem)
  6.3474 +                        in
  6.3475 +                          if flag then
  6.3476 +                            (* simply return the previously computed result *)
  6.3477 +                            intr
  6.3478 +                          else
  6.3479 +                            (* we have to apply 'intr' to interpretations for all *)
  6.3480 +                            (* recursive arguments                                *)
  6.3481 +                            let
  6.3482 +                              (* int * int list *)
  6.3483 +                              val (c, args) = get_cargs idx elem
  6.3484 +                              (* find the indices of the constructor's /recursive/ *)
  6.3485 +                              (* arguments                                         *)
  6.3486 +                              val (_, _, constrs) = the (AList.lookup (op =) descr idx)
  6.3487 +                              val (_, dtyps)      = List.nth (constrs, c)
  6.3488 +                              val rec_dtyps_args  = filter
  6.3489 +                                (Datatype_Aux.is_rec_type o fst) (dtyps ~~ args)
  6.3490 +                              (* map those indices to interpretations *)
  6.3491 +                              val rec_dtyps_intrs = map (fn (dtyp, arg) =>
  6.3492 +                                let
  6.3493 +                                  val dT     = typ_of_dtyp descr typ_assoc dtyp
  6.3494 +                                  val consts = make_constants ctxt (typs, []) dT
  6.3495 +                                  val arg_i  = List.nth (consts, arg)
  6.3496 +                                in
  6.3497 +                                  (dtyp, arg_i)
  6.3498 +                                end) rec_dtyps_args
  6.3499 +                              (* takes the dtyp and interpretation of an element, *)
  6.3500 +                              (* and computes the interpretation for the          *)
  6.3501 +                              (* corresponding recursive argument                 *)
  6.3502 +                              fun rec_intr (Datatype_Aux.DtRec i) (Leaf xs) =
  6.3503 +                                    (* recursive argument is "rec_i params elem" *)
  6.3504 +                                    compute_array_entry i (find_index (fn x => x = True) xs)
  6.3505 +                                | rec_intr (Datatype_Aux.DtRec _) (Node _) =
  6.3506 +                                    raise REFUTE ("IDT_recursion_interpreter",
  6.3507 +                                      "interpretation for IDT is a node")
  6.3508 +                                | rec_intr (Datatype_Aux.DtType ("fun", [dt1, dt2])) (Node xs) =
  6.3509 +                                    (* recursive argument is something like     *)
  6.3510 +                                    (* "\<lambda>x::dt1. rec_? params (elem x)" *)
  6.3511 +                                    Node (map (rec_intr dt2) xs)
  6.3512 +                                | rec_intr (Datatype_Aux.DtType ("fun", [_, _])) (Leaf _) =
  6.3513 +                                    raise REFUTE ("IDT_recursion_interpreter",
  6.3514 +                                      "interpretation for function dtyp is a leaf")
  6.3515 +                                | rec_intr _ _ =
  6.3516 +                                    (* admissibility ensures that every recursive type *)
  6.3517 +                                    (* is of the form 'Dt_1 -> ... -> Dt_k ->          *)
  6.3518 +                                    (* (DtRec i)'                                      *)
  6.3519 +                                    raise REFUTE ("IDT_recursion_interpreter",
  6.3520 +                                      "non-recursive codomain in recursive dtyp")
  6.3521 +                              (* obtain interpretations for recursive arguments *)
  6.3522 +                              (* interpretation list *)
  6.3523 +                              val arg_intrs = map (uncurry rec_intr) rec_dtyps_intrs
  6.3524 +                              (* apply 'intr' to all recursive arguments *)
  6.3525 +                              val result = fold (fn arg_i => fn i =>
  6.3526 +                                interpretation_apply (i, arg_i)) arg_intrs intr
  6.3527 +                              (* update 'REC_OPERATORS' *)
  6.3528 +                              val _ = Array.update (arr, elem, (true, result))
  6.3529 +                            in
  6.3530 +                              result
  6.3531 +                            end
  6.3532 +                        end
  6.3533 +                      val idt_size = Array.length (the (AList.lookup (op =) REC_OPERATORS idt_index))
  6.3534 +                      (* sanity check: the size of 'IDT' should be 'idt_size' *)
  6.3535 +                      val _ =
  6.3536 +                          if idt_size <> size_of_type ctxt (typs, []) IDT then
  6.3537 +                            raise REFUTE ("IDT_recursion_interpreter",
  6.3538 +                              "unexpected size of IDT (wrong type associated?)")
  6.3539 +                          else ()
  6.3540 +                      (* interpretation *)
  6.3541 +                      val rec_op = Node (map_range (compute_array_entry idt_index) idt_size)
  6.3542                      in
  6.3543 -                      (idx, map (fn (cname, cargs) =>
  6.3544 -                        (#1 o interpret thy (typs, []) {maxvars=0,
  6.3545 -                          def_eq=false, next_idx=1, bounds=[],
  6.3546 -                          wellformed=True}) (Const (cname, map (typ_of_dtyp
  6.3547 -                          descr typ_assoc) cargs ---> c_return_typ))) cs)
  6.3548 -                    end) descr
  6.3549 -                  (* associate constructors with corresponding parameters *)
  6.3550 -                  (* (int * (interpretation * interpretation) list) list *)
  6.3551 -                  val (mc_p_intrs, p_intrs') = fold_map
  6.3552 -                    (fn (idx, c_intrs) => fn p_intrs' =>
  6.3553 -                      let
  6.3554 -                        val len = length c_intrs
  6.3555 -                      in
  6.3556 -                        ((idx, c_intrs ~~ List.take (p_intrs', len)),
  6.3557 -                          List.drop (p_intrs', len))
  6.3558 -                      end) mc_intrs p_intrs
  6.3559 -                  (* sanity check: no 'p_intr' may be left afterwards *)
  6.3560 -                  val _ = if p_intrs' <> [] then
  6.3561 -                      raise REFUTE ("IDT_recursion_interpreter",
  6.3562 -                        "more parameter than constructor interpretations")
  6.3563 -                    else ()
  6.3564 -                  (* The recursion operator, applied to 'mconstrs_count'     *)
  6.3565 -                  (* arguments, is a function that maps every element of the *)
  6.3566 -                  (* inductive datatype to an element of some result type.   *)
  6.3567 -                  (* Recursion operators for mutually recursive IDTs are     *)
  6.3568 -                  (* translated simultaneously.                              *)
  6.3569 -                  (* Since the order on datatype elements is given by an     *)
  6.3570 -                  (* order on constructors (and then by the order on         *)
  6.3571 -                  (* argument tuples), we can simply copy corresponding      *)
  6.3572 -                  (* subtrees from 'p_intrs', in the order in which they are *)
  6.3573 -                  (* given.                                                  *)
  6.3574 -                  (* interpretation * interpretation -> interpretation list *)
  6.3575 -                  fun ci_pi (Leaf xs, pi) =
  6.3576 -                    (* if the constructor does not match the arguments to a *)
  6.3577 -                    (* defined element of the IDT, the corresponding value  *)
  6.3578 -                    (* of the parameter must be ignored                     *)
  6.3579 -                    if List.exists (equal True) xs then [pi] else []
  6.3580 -                    | ci_pi (Node xs, Node ys) =
  6.3581 -                    maps ci_pi (xs ~~ ys)
  6.3582 -                    | ci_pi (Node _, Leaf _) =
  6.3583 -                    raise REFUTE ("IDT_recursion_interpreter",
  6.3584 -                      "constructor takes more arguments than the " ^
  6.3585 -                        "associated parameter")
  6.3586 -                  (* (int * interpretation list) list *)
  6.3587 -                  val rec_operators = map (fn (idx, c_p_intrs) =>
  6.3588 -                    (idx, maps ci_pi c_p_intrs)) mc_p_intrs
  6.3589 -                  (* sanity check: every recursion operator must provide as  *)
  6.3590 -                  (*               many values as the corresponding datatype *)
  6.3591 -                  (*               has elements                              *)
  6.3592 -                  val _ = map (fn (idx, intrs) =>
  6.3593 -                    let
  6.3594 -                      val T = typ_of_dtyp descr typ_assoc
  6.3595 -                        (Datatype_Aux.DtRec idx)
  6.3596 -                    in
  6.3597 -                      if length intrs <> size_of_type thy (typs, []) T then
  6.3598 -                        raise REFUTE ("IDT_recursion_interpreter",
  6.3599 -                          "wrong number of interpretations for rec. operator")
  6.3600 -                      else ()
  6.3601 -                    end) rec_operators
  6.3602 -                  (* For non-recursive datatypes, we are pretty much done at *)
  6.3603 -                  (* this point.  For recursive datatypes however, we still  *)
  6.3604 -                  (* need to apply the interpretations in 'rec_operators' to *)
  6.3605 -                  (* (recursively obtained) interpretations for recursive    *)
  6.3606 -                  (* constructor arguments.  To do so more efficiently, we   *)
  6.3607 -                  (* copy 'rec_operators' into arrays first.  Each Boolean   *)
  6.3608 -                  (* indicates whether the recursive arguments have been     *)
  6.3609 -                  (* considered already.                                     *)
  6.3610 -                  (* (int * (bool * interpretation) Array.array) list *)
  6.3611 -                  val REC_OPERATORS = map (fn (idx, intrs) =>
  6.3612 -                    (idx, Array.fromList (map (pair false) intrs)))
  6.3613 -                    rec_operators
  6.3614 -                  (* takes an interpretation, and if some leaf of this     *)
  6.3615 -                  (* interpretation is the 'elem'-th element of the type,  *)
  6.3616 -                  (* the indices of the arguments leading to this leaf are *)
  6.3617 -                  (* returned                                              *)
  6.3618 -                  (* interpretation -> int -> int list option *)
  6.3619 -                  fun get_args (Leaf xs) elem =
  6.3620 -                    if find_index (fn x => x = True) xs = elem then
  6.3621 -                      SOME []
  6.3622 -                    else
  6.3623 -                      NONE
  6.3624 -                    | get_args (Node xs) elem =
  6.3625 -                    let
  6.3626 -                      (* interpretation list * int -> int list option *)
  6.3627 -                      fun search ([], _) =
  6.3628 -                        NONE
  6.3629 -                        | search (x::xs, n) =
  6.3630 -                        (case get_args x elem of
  6.3631 -                          SOME result => SOME (n::result)
  6.3632 -                        | NONE        => search (xs, n+1))
  6.3633 -                    in
  6.3634 -                      search (xs, 0)
  6.3635 +                      SOME (rec_op, model', args')
  6.3636                      end
  6.3637 -                  (* returns the index of the constructor and indices for *)
  6.3638 -                  (* its arguments that generate the 'elem'-th element of *)
  6.3639 -                  (* the datatype given by 'idx'                          *)
  6.3640 -                  (* int -> int -> int * int list *)
  6.3641 -                  fun get_cargs idx elem =
  6.3642 -                  let
  6.3643 -                    (* int * interpretation list -> int * int list *)
  6.3644 -                    fun get_cargs_rec (_, []) =
  6.3645 -                      raise REFUTE ("IDT_recursion_interpreter",
  6.3646 -                        "no matching constructor found for datatype element")
  6.3647 -                      | get_cargs_rec (n, x::xs) =
  6.3648 -                        (case get_args x elem of
  6.3649 -                          SOME args => (n, args)
  6.3650 -                        | NONE      => get_cargs_rec (n+1, xs))
  6.3651 -                    in
  6.3652 -                      get_cargs_rec (0, the (AList.lookup (op =) mc_intrs idx))
  6.3653 -                    end
  6.3654 -                  (* computes one entry in 'REC_OPERATORS', and recursively *)
  6.3655 -                  (* all entries needed for it, where 'idx' gives the       *)
  6.3656 -                  (* datatype and 'elem' the element of it                  *)
  6.3657 -                  (* int -> int -> interpretation *)
  6.3658 -                  fun compute_array_entry idx elem =
  6.3659 -                  let
  6.3660 -                    val arr          = the (AList.lookup (op =) REC_OPERATORS idx)
  6.3661 -                    val (flag, intr) = Array.sub (arr, elem)
  6.3662 -                  in
  6.3663 -                    if flag then
  6.3664 -                      (* simply return the previously computed result *)
  6.3665 -                      intr
  6.3666 -                    else
  6.3667 -                      (* we have to apply 'intr' to interpretations for all *)
  6.3668 -                      (* recursive arguments                                *)
  6.3669 -                      let
  6.3670 -                        (* int * int list *)
  6.3671 -                        val (c, args) = get_cargs idx elem
  6.3672 -                        (* find the indices of the constructor's /recursive/ *)
  6.3673 -                        (* arguments                                         *)
  6.3674 -                        val (_, _, constrs) = the (AList.lookup (op =) descr idx)
  6.3675 -                        val (_, dtyps)      = List.nth (constrs, c)
  6.3676 -                        val rec_dtyps_args  = filter
  6.3677 -                          (Datatype_Aux.is_rec_type o fst) (dtyps ~~ args)
  6.3678 -                        (* map those indices to interpretations *)
  6.3679 -                        val rec_dtyps_intrs = map (fn (dtyp, arg) =>
  6.3680 -                          let
  6.3681 -                            val dT     = typ_of_dtyp descr typ_assoc dtyp
  6.3682 -                            val consts = make_constants thy (typs, []) dT
  6.3683 -                            val arg_i  = List.nth (consts, arg)
  6.3684 -                          in
  6.3685 -                            (dtyp, arg_i)
  6.3686 -                          end) rec_dtyps_args
  6.3687 -                        (* takes the dtyp and interpretation of an element, *)
  6.3688 -                        (* and computes the interpretation for the          *)
  6.3689 -                        (* corresponding recursive argument                 *)
  6.3690 -                        fun rec_intr (Datatype_Aux.DtRec i) (Leaf xs) =
  6.3691 -                          (* recursive argument is "rec_i params elem" *)
  6.3692 -                          compute_array_entry i (find_index (fn x => x = True) xs)
  6.3693 -                          | rec_intr (Datatype_Aux.DtRec _) (Node _) =
  6.3694 -                          raise REFUTE ("IDT_recursion_interpreter",
  6.3695 -                            "interpretation for IDT is a node")
  6.3696 -                          | rec_intr (Datatype_Aux.DtType ("fun", [dt1, dt2]))
  6.3697 -                            (Node xs) =
  6.3698 -                          (* recursive argument is something like     *)
  6.3699 -                          (* "\<lambda>x::dt1. rec_? params (elem x)" *)
  6.3700 -                          Node (map (rec_intr dt2) xs)
  6.3701 -                          | rec_intr (Datatype_Aux.DtType ("fun", [_, _]))
  6.3702 -                            (Leaf _) =
  6.3703 -                          raise REFUTE ("IDT_recursion_interpreter",
  6.3704 -                            "interpretation for function dtyp is a leaf")
  6.3705 -                          | rec_intr _ _ =
  6.3706 -                          (* admissibility ensures that every recursive type *)
  6.3707 -                          (* is of the form 'Dt_1 -> ... -> Dt_k ->          *)
  6.3708 -                          (* (DtRec i)'                                      *)
  6.3709 -                          raise REFUTE ("IDT_recursion_interpreter",
  6.3710 -                            "non-recursive codomain in recursive dtyp")
  6.3711 -                        (* obtain interpretations for recursive arguments *)
  6.3712 -                        (* interpretation list *)
  6.3713 -                        val arg_intrs = map (uncurry rec_intr) rec_dtyps_intrs
  6.3714 -                        (* apply 'intr' to all recursive arguments *)
  6.3715 -                        val result = fold (fn arg_i => fn i =>
  6.3716 -                          interpretation_apply (i, arg_i)) arg_intrs intr
  6.3717 -                        (* update 'REC_OPERATORS' *)
  6.3718 -                        val _ = Array.update (arr, elem, (true, result))
  6.3719 -                      in
  6.3720 -                        result
  6.3721 -                      end
  6.3722 -                  end
  6.3723 -                  val idt_size = Array.length (the (AList.lookup (op =) REC_OPERATORS idt_index))
  6.3724 -                  (* sanity check: the size of 'IDT' should be 'idt_size' *)
  6.3725 -                  val _ = if idt_size <> size_of_type thy (typs, []) IDT then
  6.3726 -                        raise REFUTE ("IDT_recursion_interpreter",
  6.3727 -                          "unexpected size of IDT (wrong type associated?)")
  6.3728 -                      else ()
  6.3729 -                  (* interpretation *)
  6.3730 -                  val rec_op = Node (map_range (compute_array_entry idt_index) idt_size)
  6.3731 -                in
  6.3732 -                  SOME (rec_op, model', args')
  6.3733                  end
  6.3734 -            end
  6.3735 -          else
  6.3736 -            NONE  (* not a recursion operator of this datatype *)
  6.3737 -        ) (Datatype.get_all thy) NONE
  6.3738 +              else
  6.3739 +                NONE  (* not a recursion operator of this datatype *)
  6.3740 +          ) (Datatype.get_all thy) NONE
  6.3741      | _ =>  (* head of term is not a constant *)
  6.3742 -      NONE;
  6.3743 +      NONE
  6.3744 +  end;
  6.3745  
  6.3746 -  (* theory -> model -> arguments -> Term.term ->
  6.3747 -    (interpretation * model * arguments) option *)
  6.3748 -
  6.3749 -  fun set_interpreter thy model args t =
  6.3750 +fun set_interpreter ctxt model args t =
  6.3751    let
  6.3752      val (typs, terms) = model
  6.3753    in
  6.3754      case AList.lookup (op =) terms t of
  6.3755        SOME intr =>
  6.3756 -      (* return an existing interpretation *)
  6.3757 -      SOME (intr, model, args)
  6.3758 +        (* return an existing interpretation *)
  6.3759 +        SOME (intr, model, args)
  6.3760      | NONE =>
  6.3761 -      (case t of
  6.3762 -      (* 'Collect' == identity *)
  6.3763 -        Const (@{const_name Collect}, _) $ t1 =>
  6.3764 -        SOME (interpret thy model args t1)
  6.3765 -      | Const (@{const_name Collect}, _) =>
  6.3766 -        SOME (interpret thy model args (eta_expand t 1))
  6.3767 -      (* 'op :' == application *)
  6.3768 -      | Const (@{const_name Set.member}, _) $ t1 $ t2 =>
  6.3769 -        SOME (interpret thy model args (t2 $ t1))
  6.3770 -      | Const (@{const_name Set.member}, _) $ t1 =>
  6.3771 -        SOME (interpret thy model args (eta_expand t 1))
  6.3772 -      | Const (@{const_name Set.member}, _) =>
  6.3773 -        SOME (interpret thy model args (eta_expand t 2))
  6.3774 -      | _ => NONE)
  6.3775 +        (case t of
  6.3776 +        (* 'Collect' == identity *)
  6.3777 +          Const (@{const_name Collect}, _) $ t1 =>
  6.3778 +            SOME (interpret ctxt model args t1)
  6.3779 +        | Const (@{const_name Collect}, _) =>
  6.3780 +            SOME (interpret ctxt model args (eta_expand t 1))
  6.3781 +        (* 'op :' == application *)
  6.3782 +        | Const (@{const_name Set.member}, _) $ t1 $ t2 =>
  6.3783 +            SOME (interpret ctxt model args (t2 $ t1))
  6.3784 +        | Const (@{const_name Set.member}, _) $ t1 =>
  6.3785 +            SOME (interpret ctxt model args (eta_expand t 1))
  6.3786 +        | Const (@{const_name Set.member}, _) =>
  6.3787 +            SOME (interpret ctxt model args (eta_expand t 2))
  6.3788 +        | _ => NONE)
  6.3789    end;
  6.3790  
  6.3791 -  (* theory -> model -> arguments -> Term.term ->
  6.3792 -    (interpretation * model * arguments) option *)
  6.3793 +(* only an optimization: 'card' could in principle be interpreted with *)
  6.3794 +(* interpreters available already (using its definition), but the code *)
  6.3795 +(* below is more efficient                                             *)
  6.3796  
  6.3797 -  (* only an optimization: 'card' could in principle be interpreted with *)
  6.3798 -  (* interpreters available already (using its definition), but the code *)
  6.3799 -  (* below is more efficient                                             *)
  6.3800 -
  6.3801 -  fun Finite_Set_card_interpreter thy model args t =
  6.3802 -    case t of
  6.3803 -      Const (@{const_name Finite_Set.card},
  6.3804 -        Type ("fun", [Type ("fun", [T, @{typ bool}]),
  6.3805 -                      @{typ nat}])) =>
  6.3806 +fun Finite_Set_card_interpreter ctxt model args t =
  6.3807 +  case t of
  6.3808 +    Const (@{const_name Finite_Set.card},
  6.3809 +        Type ("fun", [Type ("fun", [T, @{typ bool}]), @{typ nat}])) =>
  6.3810        let
  6.3811          (* interpretation -> int *)
  6.3812          fun number_of_elements (Node xs) =
  6.3813 @@ -2668,9 +2575,9 @@
  6.3814                    "interpretation for set type does not yield a Boolean"))
  6.3815                xs 0
  6.3816            | number_of_elements (Leaf _) =
  6.3817 -          raise REFUTE ("Finite_Set_card_interpreter",
  6.3818 -            "interpretation for set type is a leaf")
  6.3819 -        val size_of_nat = size_of_type thy model (@{typ nat})
  6.3820 +              raise REFUTE ("Finite_Set_card_interpreter",
  6.3821 +                "interpretation for set type is a leaf")
  6.3822 +        val size_of_nat = size_of_type ctxt model (@{typ nat})
  6.3823          (* takes an interpretation for a set and returns an interpretation *)
  6.3824          (* for a 'nat' denoting the set's cardinality                      *)
  6.3825          (* interpretation -> interpretation *)
  6.3826 @@ -2678,62 +2585,54 @@
  6.3827            let
  6.3828              val n = number_of_elements i
  6.3829            in
  6.3830 -            if n<size_of_nat then
  6.3831 +            if n < size_of_nat then
  6.3832                Leaf ((replicate n False) @ True ::
  6.3833                  (replicate (size_of_nat-n-1) False))
  6.3834              else
  6.3835                Leaf (replicate size_of_nat False)
  6.3836            end
  6.3837          val set_constants =
  6.3838 -          make_constants thy model (Type ("fun", [T, HOLogic.boolT]))
  6.3839 +          make_constants ctxt model (Type ("fun", [T, HOLogic.boolT]))
  6.3840        in
  6.3841          SOME (Node (map card set_constants), model, args)
  6.3842        end
  6.3843 -    | _ =>
  6.3844 -      NONE;
  6.3845 +  | _ => NONE;
  6.3846  
  6.3847 -  (* theory -> model -> arguments -> Term.term ->
  6.3848 -    (interpretation * model * arguments) option *)
  6.3849 +(* only an optimization: 'finite' could in principle be interpreted with  *)
  6.3850 +(* interpreters available already (using its definition), but the code    *)
  6.3851 +(* below is more efficient                                                *)
  6.3852  
  6.3853 -  (* only an optimization: 'finite' could in principle be interpreted with  *)
  6.3854 -  (* interpreters available already (using its definition), but the code    *)
  6.3855 -  (* below is more efficient                                                *)
  6.3856 -
  6.3857 -  fun Finite_Set_finite_interpreter thy model args t =
  6.3858 -    case t of
  6.3859 -      Const (@{const_name Finite_Set.finite},
  6.3860 -        Type ("fun", [Type ("fun", [T, @{typ bool}]),
  6.3861 -                      @{typ bool}])) $ _ =>
  6.3862 +fun Finite_Set_finite_interpreter ctxt model args t =
  6.3863 +  case t of
  6.3864 +    Const (@{const_name Finite_Set.finite},
  6.3865 +      Type ("fun", [Type ("fun", [T, @{typ bool}]),
  6.3866 +                    @{typ bool}])) $ _ =>
  6.3867          (* we only consider finite models anyway, hence EVERY set is *)
  6.3868          (* "finite"                                                  *)
  6.3869          SOME (TT, model, args)
  6.3870 -    | Const (@{const_name Finite_Set.finite},
  6.3871 -        Type ("fun", [Type ("fun", [T, @{typ bool}]),
  6.3872 -                      @{typ bool}])) =>
  6.3873 +  | Const (@{const_name Finite_Set.finite},
  6.3874 +      Type ("fun", [Type ("fun", [T, @{typ bool}]),
  6.3875 +                    @{typ bool}])) =>
  6.3876        let
  6.3877          val size_of_set =
  6.3878 -          size_of_type thy model (Type ("fun", [T, HOLogic.boolT]))
  6.3879 +          size_of_type ctxt model (Type ("fun", [T, HOLogic.boolT]))
  6.3880        in
  6.3881          (* we only consider finite models anyway, hence EVERY set is *)
  6.3882          (* "finite"                                                  *)
  6.3883          SOME (Node (replicate size_of_set TT), model, args)
  6.3884        end
  6.3885 -    | _ =>
  6.3886 -      NONE;
  6.3887 -
  6.3888 -  (* theory -> model -> arguments -> Term.term ->
  6.3889 -    (interpretation * model * arguments) option *)
  6.3890 +  | _ => NONE;
  6.3891  
  6.3892 -  (* only an optimization: 'less' could in principle be interpreted with *)
  6.3893 -  (* interpreters available already (using its definition), but the code     *)
  6.3894 -  (* below is more efficient                                                 *)
  6.3895 +(* only an optimization: 'less' could in principle be interpreted with *)
  6.3896 +(* interpreters available already (using its definition), but the code     *)
  6.3897 +(* below is more efficient                                                 *)
  6.3898  
  6.3899 -  fun Nat_less_interpreter thy model args t =
  6.3900 -    case t of
  6.3901 -      Const (@{const_name Orderings.less}, Type ("fun", [@{typ nat},
  6.3902 +fun Nat_less_interpreter ctxt model args t =
  6.3903 +  case t of
  6.3904 +    Const (@{const_name Orderings.less}, Type ("fun", [@{typ nat},
  6.3905          Type ("fun", [@{typ nat}, @{typ bool}])])) =>
  6.3906        let
  6.3907 -        val size_of_nat = size_of_type thy model (@{typ nat})
  6.3908 +        val size_of_nat = size_of_type ctxt model (@{typ nat})
  6.3909          (* the 'n'-th nat is not less than the first 'n' nats, while it *)
  6.3910          (* is less than the remaining 'size_of_nat - n' nats            *)
  6.3911          (* int -> interpretation *)
  6.3912 @@ -2741,22 +2640,18 @@
  6.3913        in
  6.3914          SOME (Node (map less (1 upto size_of_nat)), model, args)
  6.3915        end
  6.3916 -    | _ =>
  6.3917 -      NONE;
  6.3918 -
  6.3919 -  (* theory -> model -> arguments -> Term.term ->
  6.3920 -    (interpretation * model * arguments) option *)
  6.3921 +  | _ => NONE;
  6.3922  
  6.3923 -  (* only an optimization: 'plus' could in principle be interpreted with *)
  6.3924 -  (* interpreters available already (using its definition), but the code     *)
  6.3925 -  (* below is more efficient                                                 *)
  6.3926 +(* only an optimization: 'plus' could in principle be interpreted with *)
  6.3927 +(* interpreters available already (using its definition), but the code     *)
  6.3928 +(* below is more efficient                                                 *)
  6.3929  
  6.3930 -  fun Nat_plus_interpreter thy model args t =
  6.3931 -    case t of
  6.3932 -      Const (@{const_name Groups.plus}, Type ("fun", [@{typ nat},
  6.3933 +fun Nat_plus_interpreter ctxt model args t =
  6.3934 +  case t of
  6.3935 +    Const (@{const_name Groups.plus}, Type ("fun", [@{typ nat},
  6.3936          Type ("fun", [@{typ nat}, @{typ nat}])])) =>
  6.3937        let
  6.3938 -        val size_of_nat = size_of_type thy model (@{typ nat})
  6.3939 +        val size_of_nat = size_of_type ctxt model (@{typ nat})
  6.3940          (* int -> int -> interpretation *)
  6.3941          fun plus m n =
  6.3942            let
  6.3943 @@ -2772,22 +2667,18 @@
  6.3944          SOME (Node (map_range (fn m => Node (map_range (plus m) size_of_nat)) size_of_nat),
  6.3945            model, args)
  6.3946        end
  6.3947 -    | _ =>
  6.3948 -      NONE;
  6.3949 -
  6.3950 -  (* theory -> model -> arguments -> Term.term ->
  6.3951 -    (interpretation * model * arguments) option *)
  6.3952 +  | _ => NONE;
  6.3953  
  6.3954 -  (* only an optimization: 'minus' could in principle be interpreted *)
  6.3955 -  (* with interpreters available already (using its definition), but the *)
  6.3956 -  (* code below is more efficient                                        *)
  6.3957 +(* only an optimization: 'minus' could in principle be interpreted *)
  6.3958 +(* with interpreters available already (using its definition), but the *)
  6.3959 +(* code below is more efficient                                        *)
  6.3960  
  6.3961 -  fun Nat_minus_interpreter thy model args t =
  6.3962 -    case t of
  6.3963 -      Const (@{const_name Groups.minus}, Type ("fun", [@{typ nat},
  6.3964 +fun Nat_minus_interpreter ctxt model args t =
  6.3965 +  case t of
  6.3966 +    Const (@{const_name Groups.minus}, Type ("fun", [@{typ nat},
  6.3967          Type ("fun", [@{typ nat}, @{typ nat}])])) =>
  6.3968        let
  6.3969 -        val size_of_nat = size_of_type thy model (@{typ nat})
  6.3970 +        val size_of_nat = size_of_type ctxt model (@{typ nat})
  6.3971          (* int -> int -> interpretation *)
  6.3972          fun minus m n =
  6.3973            let
  6.3974 @@ -2800,22 +2691,18 @@
  6.3975          SOME (Node (map_range (fn m => Node (map_range (minus m) size_of_nat)) size_of_nat),
  6.3976            model, args)
  6.3977        end
  6.3978 -    | _ =>
  6.3979 -      NONE;
  6.3980 -
  6.3981 -  (* theory -> model -> arguments -> Term.term ->
  6.3982 -    (interpretation * model * arguments) option *)
  6.3983 +  | _ => NONE;
  6.3984  
  6.3985 -  (* only an optimization: 'times' could in principle be interpreted *)
  6.3986 -  (* with interpreters available already (using its definition), but the *)
  6.3987 -  (* code below is more efficient                                        *)
  6.3988 +(* only an optimization: 'times' could in principle be interpreted *)
  6.3989 +(* with interpreters available already (using its definition), but the *)
  6.3990 +(* code below is more efficient                                        *)
  6.3991  
  6.3992 -  fun Nat_times_interpreter thy model args t =
  6.3993 -    case t of
  6.3994 -      Const (@{const_name Groups.times}, Type ("fun", [@{typ nat},
  6.3995 +fun Nat_times_interpreter ctxt model args t =
  6.3996 +  case t of
  6.3997 +    Const (@{const_name Groups.times}, Type ("fun", [@{typ nat},
  6.3998          Type ("fun", [@{typ nat}, @{typ nat}])])) =>
  6.3999        let
  6.4000 -        val size_of_nat = size_of_type thy model (@{typ nat})
  6.4001 +        val size_of_nat = size_of_type ctxt model (@{typ nat})
  6.4002          (* nat -> nat -> interpretation *)
  6.4003          fun mult m n =
  6.4004            let
  6.4005 @@ -2831,25 +2718,22 @@
  6.4006          SOME (Node (map_range (fn m => Node (map_range (mult m) size_of_nat)) size_of_nat),
  6.4007            model, args)
  6.4008        end
  6.4009 -    | _ =>
  6.4010 -      NONE;
  6.4011 -
  6.4012 -  (* theory -> model -> arguments -> Term.term ->
  6.4013 -    (interpretation * model * arguments) option *)
  6.4014 +  | _ => NONE;
  6.4015  
  6.4016 -  (* only an optimization: 'append' could in principle be interpreted with *)
  6.4017 -  (* interpreters available already (using its definition), but the code   *)
  6.4018 -  (* below is more efficient                                               *)
  6.4019 +(* only an optimization: 'append' could in principle be interpreted with *)
  6.4020 +(* interpreters available already (using its definition), but the code   *)
  6.4021 +(* below is more efficient                                               *)
  6.4022  
  6.4023 -  fun List_append_interpreter thy model args t =
  6.4024 -    case t of
  6.4025 -      Const (@{const_name List.append}, Type ("fun", [Type ("List.list", [T]), Type ("fun",
  6.4026 +fun List_append_interpreter ctxt model args t =
  6.4027 +  case t of
  6.4028 +    Const (@{const_name List.append}, Type ("fun", [Type ("List.list", [T]), Type ("fun",
  6.4029          [Type ("List.list", [_]), Type ("List.list", [_])])])) =>
  6.4030        let
  6.4031 -        val size_elem   = size_of_type thy model T
  6.4032 -        val size_list   = size_of_type thy model (Type ("List.list", [T]))
  6.4033 +        val size_elem = size_of_type ctxt model T
  6.4034 +        val size_list = size_of_type ctxt model (Type ("List.list", [T]))
  6.4035          (* maximal length of lists; 0 if we only consider the empty list *)
  6.4036 -        val list_length = let
  6.4037 +        val list_length =
  6.4038 +          let
  6.4039              (* int -> int -> int -> int *)
  6.4040              fun list_length_acc len lists total =
  6.4041                if lists = total then
  6.4042 @@ -2893,12 +2777,12 @@
  6.4043                in
  6.4044                  case offsets' of
  6.4045                    [] =>
  6.4046 -                  (* we're at the last node in the tree; the next value *)
  6.4047 -                  (* won't be used anyway                               *)
  6.4048 -                  (assoc, ([], 0))
  6.4049 +                    (* we're at the last node in the tree; the next value *)
  6.4050 +                    (* won't be used anyway                               *)
  6.4051 +                    (assoc, ([], 0))
  6.4052                  | off'::offs' =>
  6.4053 -                  (* go to next sibling node *)
  6.4054 -                  (assoc, (offs', off' + 1))
  6.4055 +                    (* go to next sibling node *)
  6.4056 +                    (assoc, (offs', off' + 1))
  6.4057                end
  6.4058            end) elements ([], 0)
  6.4059          (* we also need the reverse association (from length/offset to *)
  6.4060 @@ -2911,341 +2795,328 @@
  6.4061              val (len_m, off_m) = the (AList.lookup (op =) lenoff_lists m)
  6.4062              val (len_n, off_n) = the (AList.lookup (op =) lenoff_lists n)
  6.4063              val len_elem = len_m + len_n
  6.4064 -            val off_elem = off_m * power (size_elem, len_n) + off_n
  6.4065 +            val off_elem = off_m * Integer.pow len_n size_elem + off_n
  6.4066            in
  6.4067 -            case AList.lookup op= lenoff'_lists (len_elem, off_elem)  of
  6.4068 +            case AList.lookup op= lenoff'_lists (len_elem, off_elem) of
  6.4069                NONE =>
  6.4070 -              (* undefined *)
  6.4071 -              Leaf (replicate size_list False)
  6.4072 +                (* undefined *)
  6.4073 +                Leaf (replicate size_list False)
  6.4074              | SOME element =>
  6.4075 -              Leaf ((replicate element False) @ True ::
  6.4076 -                (replicate (size_list - element - 1) False))
  6.4077 +                Leaf ((replicate element False) @ True ::
  6.4078 +                  (replicate (size_list - element - 1) False))
  6.4079            end
  6.4080        in
  6.4081          SOME (Node (map (fn m => Node (map (append m) elements)) elements),
  6.4082            model, args)
  6.4083        end
  6.4084 -    | _ =>
  6.4085 -      NONE;
  6.4086 +  | _ => NONE;
  6.4087  
  6.4088  (* UNSOUND
  6.4089  
  6.4090 -  (* theory -> model -> arguments -> Term.term ->
  6.4091 -    (interpretation * model * arguments) option *)
  6.4092 -
  6.4093 -  (* only an optimization: 'lfp' could in principle be interpreted with  *)
  6.4094 -  (* interpreters available already (using its definition), but the code *)
  6.4095 -  (* below is more efficient                                             *)
  6.4096 +(* only an optimization: 'lfp' could in principle be interpreted with  *)
  6.4097 +(* interpreters available already (using its definition), but the code *)
  6.4098 +(* below is more efficient                                             *)
  6.4099  
  6.4100 -  fun lfp_interpreter thy model args t =
  6.4101 -    case t of
  6.4102 -      Const (@{const_name lfp}, Type ("fun", [Type ("fun",
  6.4103 -        [Type ("fun", [T, @{typ bool}]),
  6.4104 -         Type ("fun", [_, @{typ bool}])]),
  6.4105 -         Type ("fun", [_, @{typ bool}])])) =>
  6.4106 +fun lfp_interpreter ctxt model args t =
  6.4107 +  case t of
  6.4108 +    Const (@{const_name lfp}, Type ("fun", [Type ("fun",
  6.4109 +      [Type ("fun", [T, @{typ bool}]),
  6.4110 +       Type ("fun", [_, @{typ bool}])]),
  6.4111 +       Type ("fun", [_, @{typ bool}])])) =>
  6.4112        let
  6.4113 -        val size_elem = size_of_type thy model T
  6.4114 +        val size_elem = size_of_type ctxt model T
  6.4115          (* the universe (i.e. the set that contains every element) *)
  6.4116          val i_univ = Node (replicate size_elem TT)
  6.4117          (* all sets with elements from type 'T' *)
  6.4118          val i_sets =
  6.4119 -          make_constants thy model (Type ("fun", [T, HOLogic.boolT]))
  6.4120 +          make_constants ctxt model (Type ("fun", [T, HOLogic.boolT]))
  6.4121          (* all functions that map sets to sets *)
  6.4122 -        val i_funs = make_constants thy model (Type ("fun",
  6.4123 +        val i_funs = make_constants ctxt model (Type ("fun",
  6.4124            [Type ("fun", [T, @{typ bool}]),
  6.4125             Type ("fun", [T, @{typ bool}])]))
  6.4126          (* "lfp(f) == Inter({u. f(u) <= u})" *)
  6.4127          (* interpretation * interpretation -> bool *)
  6.4128          fun is_subset (Node subs, Node sups) =
  6.4129 -          forall (fn (sub, sup) => (sub = FF) orelse (sup = TT))
  6.4130 -            (subs ~~ sups)
  6.4131 +              forall (fn (sub, sup) => (sub = FF) orelse (sup = TT)) (subs ~~ sups)
  6.4132            | is_subset (_, _) =
  6.4133 -          raise REFUTE ("lfp_interpreter",
  6.4134 -            "is_subset: interpretation for set is not a node")
  6.4135 +              raise REFUTE ("lfp_interpreter",
  6.4136 +                "is_subset: interpretation for set is not a node")
  6.4137          (* interpretation * interpretation -> interpretation *)
  6.4138          fun intersection (Node xs, Node ys) =
  6.4139 -          Node (map (fn (x, y) => if x=TT andalso y=TT then TT else FF)
  6.4140 -            (xs ~~ ys))
  6.4141 +              Node (map (fn (x, y) => if x=TT andalso y=TT then TT else FF)
  6.4142 +                (xs ~~ ys))
  6.4143            | intersection (_, _) =
  6.4144 -          raise REFUTE ("lfp_interpreter",
  6.4145 -            "intersection: interpretation for set is not a node")
  6.4146 +              raise REFUTE ("lfp_interpreter",
  6.4147 +                "intersection: interpretation for set is not a node")
  6.4148          (* interpretation -> interpretaion *)
  6.4149          fun lfp (Node resultsets) =
  6.4150 -          fold (fn (set, resultset) => fn acc =>
  6.4151 -            if is_subset (resultset, set) then
  6.4152 -              intersection (acc, set)
  6.4153 -            else
  6.4154 -              acc) (i_sets ~~ resultsets) i_univ
  6.4155 +              fold (fn (set, resultset) => fn acc =>
  6.4156 +                if is_subset (resultset, set) then
  6.4157 +                  intersection (acc, set)
  6.4158 +                else
  6.4159 +                  acc) (i_sets ~~ resultsets) i_univ
  6.4160            | lfp _ =
  6.4161 -            raise REFUTE ("lfp_interpreter",
  6.4162 -              "lfp: interpretation for function is not a node")
  6.4163 +              raise REFUTE ("lfp_interpreter",
  6.4164 +                "lfp: interpretation for function is not a node")
  6.4165        in
  6.4166          SOME (Node (map lfp i_funs), model, args)
  6.4167        end
  6.4168 -    | _ =>
  6.4169 -      NONE;
  6.4170 +  | _ => NONE;
  6.4171  
  6.4172 -  (* theory -> model -> arguments -> Term.term ->
  6.4173 -    (interpretation * model * arguments) option *)
  6.4174 -
  6.4175 -  (* only an optimization: 'gfp' could in principle be interpreted with  *)
  6.4176 -  (* interpreters available already (using its definition), but the code *)
  6.4177 -  (* below is more efficient                                             *)
  6.4178 +(* only an optimization: 'gfp' could in principle be interpreted with  *)
  6.4179 +(* interpreters available already (using its definition), but the code *)
  6.4180 +(* below is more efficient                                             *)
  6.4181  
  6.4182 -  fun gfp_interpreter thy model args t =
  6.4183 -    case t of
  6.4184 -      Const (@{const_name gfp}, Type ("fun", [Type ("fun",
  6.4185 -        [Type ("fun", [T, @{typ bool}]),
  6.4186 -         Type ("fun", [_, @{typ bool}])]),
  6.4187 -         Type ("fun", [_, @{typ bool}])])) =>
  6.4188 -      let
  6.4189 -        val size_elem = size_of_type thy model T
  6.4190 -        (* the universe (i.e. the set that contains every element) *)
  6.4191 -        val i_univ = Node (replicate size_elem TT)
  6.4192 -        (* all sets with elements from type 'T' *)
  6.4193 -        val i_sets =
  6.4194 -          make_constants thy model (Type ("fun", [T, HOLogic.boolT]))
  6.4195 -        (* all functions that map sets to sets *)
  6.4196 -        val i_funs = make_constants thy model (Type ("fun",
  6.4197 -          [Type ("fun", [T, HOLogic.boolT]),
  6.4198 -           Type ("fun", [T, HOLogic.boolT])]))
  6.4199 -        (* "gfp(f) == Union({u. u <= f(u)})" *)
  6.4200 -        (* interpretation * interpretation -> bool *)
  6.4201 -        fun is_subset (Node subs, Node sups) =
  6.4202 -          forall (fn (sub, sup) => (sub = FF) orelse (sup = TT))
  6.4203 -            (subs ~~ sups)
  6.4204 -          | is_subset (_, _) =
  6.4205 -          raise REFUTE ("gfp_interpreter",
  6.4206 -            "is_subset: interpretation for set is not a node")
  6.4207 -        (* interpretation * interpretation -> interpretation *)
  6.4208 -        fun union (Node xs, Node ys) =
  6.4209 +fun gfp_interpreter ctxt model args t =
  6.4210 +  case t of
  6.4211 +    Const (@{const_name gfp}, Type ("fun", [Type ("fun",
  6.4212 +      [Type ("fun", [T, @{typ bool}]),
  6.4213 +       Type ("fun", [_, @{typ bool}])]),
  6.4214 +       Type ("fun", [_, @{typ bool}])])) =>
  6.4215 +    let
  6.4216 +      val size_elem = size_of_type ctxt model T
  6.4217 +      (* the universe (i.e. the set that contains every element) *)
  6.4218 +      val i_univ = Node (replicate size_elem TT)
  6.4219 +      (* all sets with elements from type 'T' *)
  6.4220 +      val i_sets =
  6.4221 +        make_constants ctxt model (Type ("fun", [T, HOLogic.boolT]))
  6.4222 +      (* all functions that map sets to sets *)
  6.4223 +      val i_funs = make_constants ctxt model (Type ("fun",
  6.4224 +        [Type ("fun", [T, HOLogic.boolT]),
  6.4225 +         Type ("fun", [T, HOLogic.boolT])]))
  6.4226 +      (* "gfp(f) == Union({u. u <= f(u)})" *)
  6.4227 +      (* interpretation * interpretation -> bool *)
  6.4228 +      fun is_subset (Node subs, Node sups) =
  6.4229 +            forall (fn (sub, sup) => (sub = FF) orelse (sup = TT))
  6.4230 +              (subs ~~ sups)
  6.4231 +        | is_subset (_, _) =
  6.4232 +            raise REFUTE ("gfp_interpreter",
  6.4233 +              "is_subset: interpretation for set is not a node")
  6.4234 +      (* interpretation * interpretation -> interpretation *)
  6.4235 +      fun union (Node xs, Node ys) =
  6.4236              Node (map (fn (x,y) => if x=TT orelse y=TT then TT else FF)
  6.4237                   (xs ~~ ys))
  6.4238 -          | union (_, _) =
  6.4239 -          raise REFUTE ("gfp_interpreter",
  6.4240 -            "union: interpretation for set is not a node")
  6.4241 -        (* interpretation -> interpretaion *)
  6.4242 -        fun gfp (Node resultsets) =
  6.4243 -          fold (fn (set, resultset) => fn acc =>
  6.4244 -            if is_subset (set, resultset) then
  6.4245 -              union (acc, set)
  6.4246 -            else
  6.4247 -              acc) (i_sets ~~ resultsets) i_univ
  6.4248 -          | gfp _ =
  6.4249 +        | union (_, _) =
  6.4250 +            raise REFUTE ("gfp_interpreter",
  6.4251 +              "union: interpretation for set is not a node")
  6.4252 +      (* interpretation -> interpretaion *)
  6.4253 +      fun gfp (Node resultsets) =
  6.4254 +            fold (fn (set, resultset) => fn acc =>
  6.4255 +              if is_subset (set, resultset) then
  6.4256 +                union (acc, set)
  6.4257 +              else
  6.4258 +                acc) (i_sets ~~ resultsets) i_univ
  6.4259 +        | gfp _ =
  6.4260              raise REFUTE ("gfp_interpreter",
  6.4261                "gfp: interpretation for function is not a node")
  6.4262 -      in
  6.4263 -        SOME (Node (map gfp i_funs), model, args)
  6.4264 -      end
  6.4265 -    | _ =>
  6.4266 -      NONE;
  6.4267 +    in
  6.4268 +      SOME (Node (map gfp i_funs), model, args)
  6.4269 +    end
  6.4270 +  | _ => NONE;
  6.4271  *)
  6.4272  
  6.4273 -  (* theory -> model -> arguments -> Term.term ->
  6.4274 -    (interpretation * model * arguments) option *)
  6.4275 -
  6.4276 -  (* only an optimization: 'fst' could in principle be interpreted with  *)
  6.4277 -  (* interpreters available already (using its definition), but the code *)
  6.4278 -  (* below is more efficient                                             *)
  6.4279 +(* only an optimization: 'fst' could in principle be interpreted with  *)
  6.4280 +(* interpreters available already (using its definition), but the code *)
  6.4281 +(* below is more efficient                                             *)
  6.4282  
  6.4283 -  fun Product_Type_fst_interpreter thy model args t =
  6.4284 -    case t of
  6.4285 -      Const (@{const_name fst}, Type ("fun", [Type (@{type_name Product_Type.prod}, [T, U]), _])) =>
  6.4286 +fun Product_Type_fst_interpreter ctxt model args t =
  6.4287 +  case t of
  6.4288 +    Const (@{const_name fst}, Type ("fun", [Type (@{type_name Product_Type.prod}, [T, U]), _])) =>
  6.4289        let
  6.4290 -        val constants_T = make_constants thy model T
  6.4291 -        val size_U      = size_of_type thy model U
  6.4292 +        val constants_T = make_constants ctxt model T
  6.4293 +        val size_U = size_of_type ctxt model U
  6.4294        in
  6.4295          SOME (Node (maps (replicate size_U) constants_T), model, args)
  6.4296        end
  6.4297 -    | _ =>
  6.4298 -      NONE;
  6.4299 +  | _ => NONE;
  6.4300  
  6.4301 -  (* theory -> model -> arguments -> Term.term ->
  6.4302 -    (interpretation * model * arguments) option *)
  6.4303 +(* only an optimization: 'snd' could in principle be interpreted with  *)
  6.4304 +(* interpreters available already (using its definition), but the code *)
  6.4305 +(* below is more efficient                                             *)
  6.4306  
  6.4307 -  (* only an optimization: 'snd' could in principle be interpreted with  *)
  6.4308 -  (* interpreters available already (using its definition), but the code *)
  6.4309 -  (* below is more efficient                                             *)
  6.4310 -
  6.4311 -  fun Product_Type_snd_interpreter thy model args t =
  6.4312 -    case t of
  6.4313 -      Const (@{const_name snd}, Type ("fun", [Type (@{type_name Product_Type.prod}, [T, U]), _])) =>
  6.4314 +fun Product_Type_snd_interpreter ctxt model args t =
  6.4315 +  case t of
  6.4316 +    Const (@{const_name snd}, Type ("fun", [Type (@{type_name Product_Type.prod}, [T, U]), _])) =>
  6.4317        let
  6.4318 -        val size_T      = size_of_type thy model T
  6.4319 -        val constants_U = make_constants thy model U
  6.4320 +        val size_T = size_of_type ctxt model T
  6.4321 +        val constants_U = make_constants ctxt model U
  6.4322        in
  6.4323          SOME (Node (flat (replicate size_T constants_U)), model, args)
  6.4324        end
  6.4325 -    | _ =>
  6.4326 -      NONE;
  6.4327 +  | _ => NONE;
  6.4328  
  6.4329  
  6.4330  (* ------------------------------------------------------------------------- *)
  6.4331  (* PRINTERS                                                                  *)
  6.4332  (* ------------------------------------------------------------------------- *)
  6.4333  
  6.4334 -  (* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
  6.4335 -    Term.term option *)
  6.4336 -
  6.4337 -  fun stlc_printer thy model T intr assignment =
  6.4338 +fun stlc_printer ctxt model T intr assignment =
  6.4339    let
  6.4340      (* string -> string *)
  6.4341      fun strip_leading_quote s =
  6.4342        (implode o (fn [] => [] | x::xs => if x="'" then xs else x::xs)
  6.4343          o explode) s
  6.4344      (* Term.typ -> string *)
  6.4345 -    fun string_of_typ (Type (s, _))     = s
  6.4346 -      | string_of_typ (TFree (x, _))    = strip_leading_quote x
  6.4347 +    fun string_of_typ (Type (s, _)) = s
  6.4348 +      | string_of_typ (TFree (x, _)) = strip_leading_quote x
  6.4349        | string_of_typ (TVar ((x,i), _)) =
  6.4350 -      strip_leading_quote x ^ string_of_int i
  6.4351 +          strip_leading_quote x ^ string_of_int i
  6.4352      (* interpretation -> int *)
  6.4353      fun index_from_interpretation (Leaf xs) =
  6.4354 -      find_index (PropLogic.eval assignment) xs
  6.4355 +          find_index (PropLogic.eval assignment) xs
  6.4356        | index_from_interpretation _ =
  6.4357 -      raise REFUTE ("stlc_printer",
  6.4358 -        "interpretation for ground type is not a leaf")
  6.4359 +          raise REFUTE ("stlc_printer",
  6.4360 +            "interpretation for ground type is not a leaf")
  6.4361    in
  6.4362      case T of
  6.4363        Type ("fun", [T1, T2]) =>
  6.4364 -      let
  6.4365 -        (* create all constants of type 'T1' *)
  6.4366 -        val constants = make_constants thy model T1
  6.4367 -        (* interpretation list *)
  6.4368 -        val results = (case intr of
  6.4369 -            Node xs => xs
  6.4370 -          | _       => raise REFUTE ("stlc_printer",
  6.4371 -            "interpretation for function type is a leaf"))
  6.4372 -        (* Term.term list *)
  6.4373 -        val pairs = map (fn (arg, result) =>
  6.4374 -          HOLogic.mk_prod
  6.4375 -            (print thy model T1 arg assignment,
  6.4376 -             print thy model T2 result assignment))
  6.4377 -          (constants ~~ results)
  6.4378 -        (* Term.typ *)
  6.4379 -        val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  6.4380 -        val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  6.4381 -        (* Term.term *)
  6.4382 -        val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
  6.4383 -        val HOLogic_insert    =
  6.4384 -          Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  6.4385 -      in
  6.4386 -        SOME (fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) pairs HOLogic_empty_set)
  6.4387 -      end
  6.4388 -    | Type ("prop", [])      =>
  6.4389 -      (case index_from_interpretation intr of
  6.4390 -        ~1 => SOME (HOLogic.mk_Trueprop (Const (@{const_name undefined}, HOLogic.boolT)))
  6.4391 -      | 0  => SOME (HOLogic.mk_Trueprop HOLogic.true_const)
  6.4392 -      | 1  => SOME (HOLogic.mk_Trueprop HOLogic.false_const)
  6.4393 -      | _  => raise REFUTE ("stlc_interpreter",
  6.4394 -        "illegal interpretation for a propositional value"))
  6.4395 -    | Type _  => if index_from_interpretation intr = (~1) then
  6.4396 -        SOME (Const (@{const_name undefined}, T))
  6.4397 -      else
  6.4398 -        SOME (Const (string_of_typ T ^
  6.4399 -          string_of_int (index_from_interpretation intr), T))
  6.4400 -    | TFree _ => if index_from_interpretation intr = (~1) then
  6.4401 -        SOME (Const (@{const_name undefined}, T))
  6.4402 -      else
  6.4403 -        SOME (Const (string_of_typ T ^
  6.4404 -          string_of_int (index_from_interpretation intr), T))
  6.4405 -    | TVar _  => if index_from_interpretation intr = (~1) then
  6.4406 -        SOME (Const (@{const_name undefined}, T))
  6.4407 -      else
  6.4408 -        SOME (Const (string_of_typ T ^
  6.4409 -          string_of_int (index_from_interpretation intr), T))
  6.4410 +        let
  6.4411 +          (* create all constants of type 'T1' *)
  6.4412 +          val constants = make_constants ctxt model T1
  6.4413 +          (* interpretation list *)
  6.4414 +          val results =
  6.4415 +            (case intr of
  6.4416 +              Node xs => xs
  6.4417 +            | _ => raise REFUTE ("stlc_printer",
  6.4418 +              "interpretation for function type is a leaf"))
  6.4419 +          (* Term.term list *)
  6.4420 +          val pairs = map (fn (arg, result) =>
  6.4421 +            HOLogic.mk_prod
  6.4422 +              (print ctxt model T1 arg assignment,
  6.4423 +               print ctxt model T2 result assignment))
  6.4424 +            (constants ~~ results)
  6.4425 +          (* Term.typ *)
  6.4426 +          val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
  6.4427 +          val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
  6.4428 +          (* Term.term *)
  6.4429 +          val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
  6.4430 +          val HOLogic_insert    =
  6.4431 +            Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
  6.4432 +        in
  6.4433 +          SOME (fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) pairs HOLogic_empty_set)
  6.4434 +        end
  6.4435 +    | Type ("prop", []) =>
  6.4436 +        (case index_from_interpretation intr of
  6.4437 +          ~1 => SOME (HOLogic.mk_Trueprop (Const (@{const_name undefined}, HOLogic.boolT)))
  6.4438 +        | 0  => SOME (HOLogic.mk_Trueprop HOLogic.true_const)
  6.4439 +        | 1  => SOME (HOLogic.mk_Trueprop HOLogic.false_const)
  6.4440 +        | _  => raise REFUTE ("stlc_interpreter",
  6.4441 +          "illegal interpretation for a propositional value"))
  6.4442 +    | Type _  =>
  6.4443 +        if index_from_interpretation intr = (~1) then
  6.4444 +          SOME (Const (@{const_name undefined}, T))
  6.4445 +        else
  6.4446 +          SOME (Const (string_of_typ T ^
  6.4447 +            string_of_int (index_from_interpretation intr), T))
  6.4448 +    | TFree _ =>
  6.4449 +        if index_from_interpretation intr = (~1) then
  6.4450 +          SOME (Const (@{const_name undefined}, T))
  6.4451 +        else
  6.4452 +          SOME (Const (string_of_typ T ^
  6.4453 +            string_of_int (index_from_interpretation intr), T))
  6.4454 +    | TVar _  =>
  6.4455 +        if index_from_interpretation intr = (~1) then
  6.4456 +          SOME (Const (@{const_name undefined}, T))
  6.4457 +        else
  6.4458 +          SOME (Const (string_of_typ T ^
  6.4459 +            string_of_int (index_from_interpretation intr), T))
  6.4460    end;
  6.4461  
  6.4462 -  (* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
  6.4463 -    Term.term option *)
  6.4464 -
  6.4465 -  fun IDT_printer thy model T intr assignment =
  6.4466 +fun IDT_printer ctxt model T intr assignment =
  6.4467 +  let
  6.4468 +    val thy = ProofContext.theory_of ctxt
  6.4469 +  in
  6.4470      (case T of
  6.4471        Type (s, Ts) =>
  6.4472 -      (case Datatype.get_info thy s of
  6.4473 -        SOME info =>  (* inductive datatype *)
  6.4474 -        let
  6.4475 -          val (typs, _)           = model
  6.4476 -          val index               = #index info
  6.4477 -          val descr               = #descr info
  6.4478 -          val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  6.4479 -          val typ_assoc           = dtyps ~~ Ts
  6.4480 -          (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  6.4481 -          val _ = if Library.exists (fn d =>
  6.4482 -              case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  6.4483 -            then
  6.4484 -              raise REFUTE ("IDT_printer", "datatype argument (for type " ^
  6.4485 -                Syntax.string_of_typ_global thy (Type (s, Ts)) ^ ") is not a variable")
  6.4486 -            else ()
  6.4487 -          (* the index of the element in the datatype *)
  6.4488 -          val element = (case intr of
  6.4489 -              Leaf xs => find_index (PropLogic.eval assignment) xs
  6.4490 -            | Node _  => raise REFUTE ("IDT_printer",
  6.4491 -              "interpretation is not a leaf"))
  6.4492 -        in
  6.4493 -          if element < 0 then
  6.4494 -            SOME (Const (@{const_name undefined}, Type (s, Ts)))
  6.4495 -          else let
  6.4496 -            (* takes a datatype constructor, and if for some arguments this  *)
  6.4497 -            (* constructor generates the datatype's element that is given by *)
  6.4498 -            (* 'element', returns the constructor (as a term) as well as the *)
  6.4499 -            (* indices of the arguments                                      *)
  6.4500 -            fun get_constr_args (cname, cargs) =
  6.4501 -              let
  6.4502 -                val cTerm      = Const (cname,
  6.4503 -                  map (typ_of_dtyp descr typ_assoc) cargs ---> Type (s, Ts))
  6.4504 -                val (iC, _, _) = interpret thy (typs, []) {maxvars=0,
  6.4505 -                  def_eq=false, next_idx=1, bounds=[], wellformed=True} cTerm
  6.4506 -                (* interpretation -> int list option *)
  6.4507 -                fun get_args (Leaf xs) =
  6.4508 -                  if find_index (fn x => x = True) xs = element then
  6.4509 -                    SOME []
  6.4510 -                  else
  6.4511 -                    NONE
  6.4512 -                  | get_args (Node xs) =
  6.4513 -                  let
  6.4514 -                    (* interpretation * int -> int list option *)
  6.4515 -                    fun search ([], _) =
  6.4516 -                      NONE
  6.4517 -                      | search (x::xs, n) =
  6.4518 -                      (case get_args x of
  6.4519 -                        SOME result => SOME (n::result)
  6.4520 -                      | NONE        => search (xs, n+1))
  6.4521 -                  in
  6.4522 -                    search (xs, 0)
  6.4523 -                  end
  6.4524 -              in
  6.4525 -                Option.map (fn args => (cTerm, cargs, args)) (get_args iC)
  6.4526 -              end
  6.4527 -            val (cTerm, cargs, args) =
  6.4528 -              (* we could speed things up by computing the correct          *)
  6.4529 -              (* constructor directly (rather than testing all              *)
  6.4530 -              (* constructors), based on the order in which constructors    *)
  6.4531 -              (* generate elements of datatypes; the current implementation *)
  6.4532 -              (* of 'IDT_printer' however is independent of the internals   *)
  6.4533 -              (* of 'IDT_constructor_interpreter'                           *)
  6.4534 -              (case get_first get_constr_args constrs of
  6.4535 -                SOME x => x
  6.4536 -              | NONE   => raise REFUTE ("IDT_printer",
  6.4537 -                "no matching constructor found for element " ^
  6.4538 -                string_of_int element))
  6.4539 -            val argsTerms = map (fn (d, n) =>
  6.4540 -              let
  6.4541 -                val dT     = typ_of_dtyp descr typ_assoc d
  6.4542 -                (* we only need the n-th element of this list, so there   *)
  6.4543 -                (* might be a more efficient implementation that does not *)
  6.4544 -                (* generate all constants                                 *)
  6.4545 -                val consts = make_constants thy (typs, []) dT
  6.4546 -              in
  6.4547 -                print thy (typs, []) dT (List.nth (consts, n)) assignment
  6.4548 -              end) (cargs ~~ args)
  6.4549 -          in
  6.4550 -            SOME (list_comb (cTerm, argsTerms))
  6.4551 -          end
  6.4552 -        end
  6.4553 -      | NONE =>  (* not an inductive datatype *)
  6.4554 +        (case Datatype.get_info thy s of
  6.4555 +          SOME info =>  (* inductive datatype *)
  6.4556 +            let
  6.4557 +              val (typs, _)           = model
  6.4558 +              val index               = #index info
  6.4559 +              val descr               = #descr info
  6.4560 +              val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
  6.4561 +              val typ_assoc           = dtyps ~~ Ts
  6.4562 +              (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
  6.4563 +              val _ =
  6.4564 +                if Library.exists (fn d =>
  6.4565 +                  case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
  6.4566 +                then
  6.4567 +                  raise REFUTE ("IDT_printer", "datatype argument (for type " ^
  6.4568 +                    Syntax.string_of_typ ctxt (Type (s, Ts)) ^ ") is not a variable")
  6.4569 +                else ()
  6.4570 +              (* the index of the element in the datatype *)
  6.4571 +              val element =
  6.4572 +                (case intr of
  6.4573 +                  Leaf xs => find_index (PropLogic.eval assignment) xs
  6.4574 +                | Node _  => raise REFUTE ("IDT_printer",
  6.4575 +                  "interpretation is not a leaf"))
  6.4576 +            in
  6.4577 +              if element < 0 then
  6.4578 +                SOME (Const (@{const_name undefined}, Type (s, Ts)))
  6.4579 +              else
  6.4580 +                let
  6.4581 +                  (* takes a datatype constructor, and if for some arguments this  *)
  6.4582 +                  (* constructor generates the datatype's element that is given by *)
  6.4583 +                  (* 'element', returns the constructor (as a term) as well as the *)
  6.4584 +                  (* indices of the arguments                                      *)
  6.4585 +                  fun get_constr_args (cname, cargs) =
  6.4586 +                    let
  6.4587 +                      val cTerm      = Const (cname,
  6.4588 +                        map (typ_of_dtyp descr typ_assoc) cargs ---> Type (s, Ts))
  6.4589 +                      val (iC, _, _) = interpret ctxt (typs, []) {maxvars=0,
  6.4590 +                        def_eq=false, next_idx=1, bounds=[], wellformed=True} cTerm
  6.4591 +                      (* interpretation -> int list option *)
  6.4592 +                      fun get_args (Leaf xs) =
  6.4593 +                            if find_index (fn x => x = True) xs = element then
  6.4594 +                              SOME []
  6.4595 +                            else
  6.4596 +                              NONE
  6.4597 +                        | get_args (Node xs) =
  6.4598 +                            let
  6.4599 +                              (* interpretation * int -> int list option *)
  6.4600 +                              fun search ([], _) =
  6.4601 +                                NONE
  6.4602 +                                | search (x::xs, n) =
  6.4603 +                                (case get_args x of
  6.4604 +                                  SOME result => SOME (n::result)
  6.4605 +                                | NONE        => search (xs, n+1))
  6.4606 +                            in
  6.4607 +                              search (xs, 0)
  6.4608 +                            end
  6.4609 +                    in
  6.4610 +                      Option.map (fn args => (cTerm, cargs, args)) (get_args iC)
  6.4611 +                    end
  6.4612 +                  val (cTerm, cargs, args) =
  6.4613 +                    (* we could speed things up by computing the correct          *)
  6.4614 +                    (* constructor directly (rather than testing all              *)
  6.4615 +                    (* constructors), based on the order in which constructors    *)
  6.4616 +                    (* generate elements of datatypes; the current implementation *)
  6.4617 +                    (* of 'IDT_printer' however is independent of the internals   *)
  6.4618 +                    (* of 'IDT_constructor_interpreter'                           *)
  6.4619 +                    (case get_first get_constr_args constrs of
  6.4620 +                      SOME x => x
  6.4621 +                    | NONE   => raise REFUTE ("IDT_printer",
  6.4622 +                      "no matching constructor found for element " ^
  6.4623 +                      string_of_int element))
  6.4624 +                  val argsTerms = map (fn (d, n) =>
  6.4625 +                    let
  6.4626 +                      val dT = typ_of_dtyp descr typ_assoc d
  6.4627 +                      (* we only need the n-th element of this list, so there   *)
  6.4628 +                      (* might be a more efficient implementation that does not *)
  6.4629 +                      (* generate all constants                                 *)
  6.4630 +                      val consts = make_constants ctxt (typs, []) dT
  6.4631 +                    in
  6.4632 +                      print ctxt (typs, []) dT (List.nth (consts, n)) assignment
  6.4633 +                    end) (cargs ~~ args)
  6.4634 +                in
  6.4635 +                  SOME (list_comb (cTerm, argsTerms))
  6.4636 +                end
  6.4637 +            end
  6.4638 +        | NONE =>  (* not an inductive datatype *)
  6.4639 +            NONE)
  6.4640 +    | _ =>  (* a (free or schematic) type variable *)
  6.4641          NONE)
  6.4642 -    | _ =>  (* a (free or schematic) type variable *)
  6.4643 -      NONE);
  6.4644 +  end;
  6.4645  
  6.4646  
  6.4647  (* ------------------------------------------------------------------------- *)
  6.4648 @@ -3260,28 +3131,71 @@
  6.4649  (*       subterms that are then passed to other interpreters!                *)
  6.4650  (* ------------------------------------------------------------------------- *)
  6.4651  
  6.4652 -  val setup =
  6.4653 -     add_interpreter "stlc"    stlc_interpreter #>
  6.4654 -     add_interpreter "Pure"    Pure_interpreter #>
  6.4655 -     add_interpreter "HOLogic" HOLogic_interpreter #>
  6.4656 -     add_interpreter "set"     set_interpreter #>
  6.4657 -     add_interpreter "IDT"             IDT_interpreter #>
  6.4658 -     add_interpreter "IDT_constructor" IDT_constructor_interpreter #>
  6.4659 -     add_interpreter "IDT_recursion"   IDT_recursion_interpreter #>
  6.4660 -     add_interpreter "Finite_Set.card"    Finite_Set_card_interpreter #>
  6.4661 -     add_interpreter "Finite_Set.finite"  Finite_Set_finite_interpreter #>
  6.4662 -     add_interpreter "Nat_Orderings.less" Nat_less_interpreter #>
  6.4663 -     add_interpreter "Nat_HOL.plus"       Nat_plus_interpreter #>
  6.4664 -     add_interpreter "Nat_HOL.minus"      Nat_minus_interpreter #>
  6.4665 -     add_interpreter "Nat_HOL.times"      Nat_times_interpreter #>
  6.4666 -     add_interpreter "List.append" List_append_interpreter #>
  6.4667 +val setup =
  6.4668 +   add_interpreter "stlc"    stlc_interpreter #>
  6.4669 +   add_interpreter "Pure"    Pure_interpreter #>
  6.4670 +   add_interpreter "HOLogic" HOLogic_interpreter #>
  6.4671 +   add_interpreter "set"     set_interpreter #>
  6.4672 +   add_interpreter "IDT"             IDT_interpreter #>
  6.4673 +   add_interpreter "IDT_constructor" IDT_constructor_interpreter #>
  6.4674 +   add_interpreter "IDT_recursion"   IDT_recursion_interpreter #>
  6.4675 +   add_interpreter "Finite_Set.card"    Finite_Set_card_interpreter #>
  6.4676 +   add_interpreter "Finite_Set.finite"  Finite_Set_finite_interpreter #>
  6.4677 +   add_interpreter "Nat_Orderings.less" Nat_less_interpreter #>
  6.4678 +   add_interpreter "Nat_HOL.plus"       Nat_plus_interpreter #>
  6.4679 +   add_interpreter "Nat_HOL.minus"      Nat_minus_interpreter #>
  6.4680 +   add_interpreter "Nat_HOL.times"      Nat_times_interpreter #>
  6.4681 +   add_interpreter "List.append" List_append_interpreter #>
  6.4682  (* UNSOUND
  6.4683 -     add_interpreter "lfp" lfp_interpreter #>
  6.4684 -     add_interpreter "gfp" gfp_interpreter #>
  6.4685 +   add_interpreter "lfp" lfp_interpreter #>
  6.4686 +   add_interpreter "gfp" gfp_interpreter #>
  6.4687  *)
  6.4688 -     add_interpreter "Product_Type.fst" Product_Type_fst_interpreter #>
  6.4689 -     add_interpreter "Product_Type.snd" Product_Type_snd_interpreter #>
  6.4690 -     add_printer "stlc" stlc_printer #>
  6.4691 -     add_printer "IDT"  IDT_printer;
  6.4692 +   add_interpreter "Product_Type.fst" Product_Type_fst_interpreter #>
  6.4693 +   add_interpreter "Product_Type.snd" Product_Type_snd_interpreter #>
  6.4694 +   add_printer "stlc" stlc_printer #>
  6.4695 +   add_printer "IDT"  IDT_printer;
  6.4696 +
  6.4697 +
  6.4698 +
  6.4699 +(** outer syntax commands 'refute' and 'refute_params' **)
  6.4700 +
  6.4701 +(* argument parsing *)
  6.4702 +
  6.4703 +(*optional list of arguments of the form [name1=value1, name2=value2, ...]*)
  6.4704 +
  6.4705 +val scan_parm = Parse.name -- (Scan.optional (Parse.$$$ "=" |-- Parse.name) "true")
  6.4706 +val scan_parms = Scan.optional (Parse.$$$ "[" |-- Parse.list scan_parm --| Parse.$$$ "]") [];
  6.4707 +
  6.4708 +
  6.4709 +(* 'refute' command *)
  6.4710  
  6.4711 -end  (* structure Refute *)
  6.4712 +val _ =
  6.4713 +  Outer_Syntax.improper_command "refute"
  6.4714 +    "try to find a model that refutes a given subgoal" Keyword.diag
  6.4715 +    (scan_parms -- Scan.optional Parse.nat 1 >>
  6.4716 +      (fn (parms, i) =>
  6.4717 +        Toplevel.keep (fn state =>
  6.4718 +          let
  6.4719 +            val ctxt = Toplevel.context_of state;
  6.4720 +            val {goal = st, ...} = Proof.raw_goal (Toplevel.proof_of state);
  6.4721 +          in refute_goal ctxt parms st i end)));
  6.4722 +
  6.4723 +
  6.4724 +(* 'refute_params' command *)
  6.4725 +
  6.4726 +val _ =
  6.4727 +  Outer_Syntax.command "refute_params"
  6.4728 +    "show/store default parameters for the 'refute' command" Keyword.thy_decl
  6.4729 +    (scan_parms >> (fn parms =>
  6.4730 +      Toplevel.theory (fn thy =>
  6.4731 +        let
  6.4732 +          val thy' = fold set_default_param parms thy;
  6.4733 +          val output =
  6.4734 +            (case get_default_params (ProofContext.init_global thy') of
  6.4735 +              [] => "none"
  6.4736 +            | new_defaults => cat_lines (map (fn (x, y) => x ^ "=" ^ y) new_defaults));
  6.4737 +          val _ = writeln ("Default parameters for 'refute':\n" ^ output);
  6.4738 +        in thy' end)));
  6.4739 +
  6.4740 +end;
  6.4741 +
     7.1 --- a/src/HOL/Tools/refute_isar.ML	Fri Sep 03 08:13:28 2010 +0200
     7.2 +++ b/src/HOL/Tools/refute_isar.ML	Fri Sep 03 12:01:47 2010 +0200
     7.3 @@ -2,49 +2,6 @@
     7.4      Author:     Tjark Weber
     7.5      Copyright   2003-2007
     7.6  
     7.7 -Outer syntax commands 'refute' and 'refute_params'.
     7.8 -*)
     7.9 -
    7.10 -structure Refute_Isar: sig end =
    7.11 -struct
    7.12 -
    7.13 -(* argument parsing *)
    7.14 -
    7.15 -(*optional list of arguments of the form [name1=value1, name2=value2, ...]*)
    7.16 -
    7.17 -val scan_parm = Parse.name -- (Scan.optional (Parse.$$$ "=" |-- Parse.name) "true")
    7.18 -val scan_parms = Scan.optional (Parse.$$$ "[" |-- Parse.list scan_parm --| Parse.$$$ "]") [];
    7.19 -
    7.20 -
    7.21 -(* 'refute' command *)
    7.22 -
    7.23 -val _ =
    7.24 -  Outer_Syntax.improper_command "refute"
    7.25 -    "try to find a model that refutes a given subgoal" Keyword.diag
    7.26 -    (scan_parms -- Scan.optional Parse.nat 1 >>
    7.27 -      (fn (parms, i) =>
    7.28 -        Toplevel.keep (fn state =>
    7.29 -          let
    7.30 -            val ctxt = Toplevel.context_of state;
    7.31 -            val {goal = st, ...} = Proof.raw_goal (Toplevel.proof_of state);
    7.32 -          in Refute.refute_goal ctxt parms st i end)));
    7.33 -
    7.34 -
    7.35 -(* 'refute_params' command *)
    7.36 -
    7.37 -val _ =
    7.38 -  Outer_Syntax.command "refute_params"
    7.39 -    "show/store default parameters for the 'refute' command" Keyword.thy_decl
    7.40 -    (scan_parms >> (fn parms =>
    7.41 -      Toplevel.theory (fn thy =>
    7.42 -        let
    7.43 -          val thy' = fold Refute.set_default_param parms thy;
    7.44 -          val output =
    7.45 -            (case Refute.get_default_params thy' of
    7.46 -              [] => "none"
    7.47 -            | new_defaults => cat_lines (map (fn (x, y) => x ^ "=" ^ y) new_defaults));
    7.48 -          val _ = writeln ("Default parameters for 'refute':\n" ^ output);
    7.49 -        in thy' end)));
    7.50  
    7.51  end;
    7.52  
     8.1 --- a/src/Pure/General/position.scala	Fri Sep 03 08:13:28 2010 +0200
     8.2 +++ b/src/Pure/General/position.scala	Fri Sep 03 12:01:47 2010 +0200
     8.3 @@ -24,7 +24,7 @@
     8.4      def unapply(pos: T): Option[Text.Range] =
     8.5        (Offset.unapply(pos), End_Offset.unapply(pos)) match {
     8.6          case (Some(start), Some(stop)) if start <= stop => Some(Text.Range(start, stop))
     8.7 -        case (Some(start), None) => Some(Text.Range(start))
     8.8 +        case (Some(start), None) => Some(Text.Range(start, start + 1))
     8.9          case _ => None
    8.10        }
    8.11    }
     9.1 --- a/src/Pure/Isar/attrib.ML	Fri Sep 03 08:13:28 2010 +0200
     9.2 +++ b/src/Pure/Isar/attrib.ML	Fri Sep 03 12:01:47 2010 +0200
     9.3 @@ -392,7 +392,8 @@
     9.4  (* theory setup *)
     9.5  
     9.6  val _ = Context.>> (Context.map_theory
     9.7 - (register_config show_question_marks_value #>
     9.8 + (register_config Syntax.show_question_marks_value #>
     9.9 +  register_config Goal_Display.show_consts_value #>
    9.10    register_config Unify.trace_bound_value #>
    9.11    register_config Unify.search_bound_value #>
    9.12    register_config Unify.trace_simp_value #>
    10.1 --- a/src/Pure/Isar/proof.ML	Fri Sep 03 08:13:28 2010 +0200
    10.2 +++ b/src/Pure/Isar/proof.ML	Fri Sep 03 12:01:47 2010 +0200
    10.3 @@ -331,7 +331,7 @@
    10.4  
    10.5  fun pretty_state nr state =
    10.6    let
    10.7 -    val {context, facts, mode, goal = _} = current state;
    10.8 +    val {context = ctxt, facts, mode, goal = _} = current state;
    10.9  
   10.10      fun levels_up 0 = ""
   10.11        | levels_up 1 = "1 level up"
   10.12 @@ -345,7 +345,7 @@
   10.13        (case filter_out (fn s => s = "") strs of [] => ""
   10.14        | strs' => enclose " (" ")" (commas strs'));
   10.15  
   10.16 -    fun prt_goal (SOME (ctxt, (i,
   10.17 +    fun prt_goal (SOME (_, (i,
   10.18        {statement = ((_, pos), _, _), messages, using, goal, before_qed = _, after_qed = _}))) =
   10.19            pretty_facts "using " ctxt
   10.20              (if mode <> Backward orelse null using then NONE else SOME using) @
   10.21 @@ -357,8 +357,8 @@
   10.22        | prt_goal NONE = [];
   10.23  
   10.24      val prt_ctxt =
   10.25 -      if ! verbose orelse mode = Forward then ProofContext.pretty_context context
   10.26 -      else if mode = Backward then ProofContext.pretty_ctxt context
   10.27 +      if ! verbose orelse mode = Forward then ProofContext.pretty_context ctxt
   10.28 +      else if mode = Backward then ProofContext.pretty_ctxt ctxt
   10.29        else [];
   10.30    in
   10.31      [Pretty.str ("proof (" ^ mode_name mode ^ "): step " ^ string_of_int nr ^
   10.32 @@ -366,8 +366,8 @@
   10.33        Pretty.str ""] @
   10.34      (if null prt_ctxt then [] else prt_ctxt @ [Pretty.str ""]) @
   10.35      (if ! verbose orelse mode = Forward then
   10.36 -       pretty_facts "" context facts @ prt_goal (try find_goal state)
   10.37 -     else if mode = Chain then pretty_facts "picking " context facts
   10.38 +       pretty_facts "" ctxt facts @ prt_goal (try find_goal state)
   10.39 +     else if mode = Chain then pretty_facts "picking " ctxt facts
   10.40       else prt_goal (try find_goal state))
   10.41    end;
   10.42  
    11.1 --- a/src/Pure/Isar/proof_context.ML	Fri Sep 03 08:13:28 2010 +0200
    11.2 +++ b/src/Pure/Isar/proof_context.ML	Fri Sep 03 12:01:47 2010 +0200
    11.3 @@ -741,14 +741,14 @@
    11.4    let
    11.5      val (syms, pos) = Syntax.parse_token ctxt Markup.sort text;
    11.6      val S = Syntax.standard_parse_sort ctxt (syn_of ctxt) (syms, pos)
    11.7 -      handle ERROR msg => cat_error msg ("Failed to parse sort" ^ Position.str_of pos)
    11.8 +      handle ERROR msg => cat_error msg "Failed to parse sort";
    11.9    in Type.minimize_sort (tsig_of ctxt) S end;
   11.10  
   11.11  fun parse_typ ctxt text =
   11.12    let
   11.13      val (syms, pos) = Syntax.parse_token ctxt Markup.typ text;
   11.14      val T = Syntax.standard_parse_typ ctxt (syn_of ctxt) (get_sort ctxt) (syms, pos)
   11.15 -      handle ERROR msg => cat_error msg ("Failed to parse type" ^ Position.str_of pos);
   11.16 +      handle ERROR msg => cat_error msg "Failed to parse type";
   11.17    in T end;
   11.18  
   11.19  fun parse_term T ctxt text =
   11.20 @@ -756,7 +756,8 @@
   11.21      val {get_sort, map_const, map_free} = term_context ctxt;
   11.22  
   11.23      val (T', _) = Type_Infer.paramify_dummies T 0;
   11.24 -    val (markup, kind) = if T' = propT then (Markup.prop, "proposition") else (Markup.term, "term");
   11.25 +    val (markup, kind) =
   11.26 +      if T' = propT then (Markup.prop, "proposition") else (Markup.term, "term");
   11.27      val (syms, pos) = Syntax.parse_token ctxt markup text;
   11.28  
   11.29      fun check t = (Syntax.check_term ctxt (Type_Infer.constrain T' t); NONE)
   11.30 @@ -764,7 +765,7 @@
   11.31      val t =
   11.32        Syntax.standard_parse_term (Syntax.pp ctxt) check get_sort map_const map_free
   11.33          ctxt (Type.is_logtype (tsig_of ctxt)) (syn_of ctxt) T' (syms, pos)
   11.34 -      handle ERROR msg => cat_error msg ("Failed to parse " ^ kind ^ Position.str_of pos);
   11.35 +      handle ERROR msg => cat_error msg ("Failed to parse " ^ kind);
   11.36    in t end;
   11.37  
   11.38  
    12.1 --- a/src/Pure/PIDE/isar_document.scala	Fri Sep 03 08:13:28 2010 +0200
    12.2 +++ b/src/Pure/PIDE/isar_document.scala	Fri Sep 03 12:01:47 2010 +0200
    12.3 @@ -58,17 +58,23 @@
    12.4  
    12.5    /* reported positions */
    12.6  
    12.7 +  private val include_pos = Set(Markup.BINDING, Markup.ENTITY, Markup.REPORT, Markup.POSITION)
    12.8 +  private val exclude_pos = Set(Markup.LOCATION)
    12.9 +
   12.10    def reported_positions(command_id: Document.Command_ID, message: XML.Elem): Set[Text.Range] =
   12.11    {
   12.12      def reported(set: Set[Text.Range], tree: XML.Tree): Set[Text.Range] =
   12.13        tree match {
   12.14          case XML.Elem(Markup(name, Position.Id_Range(id, range)), body)
   12.15 -        if (name == Markup.BINDING || name == Markup.ENTITY || name == Markup.REPORT) &&
   12.16 -          id == command_id => body.foldLeft(set + range)(reported)
   12.17 -        case XML.Elem(_, body) => body.foldLeft(set)(reported)
   12.18 -        case XML.Text(_) => set
   12.19 +        if include_pos(name) && id == command_id =>
   12.20 +          body.foldLeft(set + range)(reported)
   12.21 +        case XML.Elem(Markup(name, _), body) if !exclude_pos(name) =>
   12.22 +          body.foldLeft(set)(reported)
   12.23 +        case _ => set
   12.24        }
   12.25 -    reported(Set.empty, message) ++ Position.Range.unapply(message.markup.properties)
   12.26 +    val set = reported(Set.empty, message)
   12.27 +    if (set.isEmpty) set ++ Position.Range.unapply(message.markup.properties)
   12.28 +    else set
   12.29    }
   12.30  }
   12.31  
    13.1 --- a/src/Pure/ProofGeneral/preferences.ML	Fri Sep 03 08:13:28 2010 +0200
    13.2 +++ b/src/Pure/ProofGeneral/preferences.ML	Fri Sep 03 12:01:47 2010 +0200
    13.3 @@ -117,7 +117,7 @@
    13.4    bool_pref show_sorts
    13.5      "show-sorts"
    13.6      "Include sorts in display of Isabelle terms",
    13.7 -  bool_pref show_consts
    13.8 +  bool_pref show_consts_default
    13.9      "show-consts"
   13.10      "Show types of consts in Isabelle goal display",
   13.11    bool_pref long_names
    14.1 --- a/src/Pure/display.ML	Fri Sep 03 08:13:28 2010 +0200
    14.2 +++ b/src/Pure/display.ML	Fri Sep 03 12:01:47 2010 +0200
    14.3 @@ -8,7 +8,8 @@
    14.4  signature BASIC_DISPLAY =
    14.5  sig
    14.6    val goals_limit: int Unsynchronized.ref
    14.7 -  val show_consts: bool Unsynchronized.ref
    14.8 +  val show_consts_default: bool Unsynchronized.ref
    14.9 +  val show_consts: bool Config.T
   14.10    val show_hyps: bool Unsynchronized.ref
   14.11    val show_tags: bool Unsynchronized.ref
   14.12  end;
   14.13 @@ -37,6 +38,7 @@
   14.14  (** options **)
   14.15  
   14.16  val goals_limit = Goal_Display.goals_limit;
   14.17 +val show_consts_default = Goal_Display.show_consts_default;
   14.18  val show_consts = Goal_Display.show_consts;
   14.19  
   14.20  val show_hyps = Unsynchronized.ref false;    (*false: print meta-hypotheses as dots*)
    15.1 --- a/src/Pure/goal_display.ML	Fri Sep 03 08:13:28 2010 +0200
    15.2 +++ b/src/Pure/goal_display.ML	Fri Sep 03 12:01:47 2010 +0200
    15.3 @@ -8,7 +8,9 @@
    15.4  signature GOAL_DISPLAY =
    15.5  sig
    15.6    val goals_limit: int Unsynchronized.ref
    15.7 -  val show_consts: bool Unsynchronized.ref
    15.8 +  val show_consts_default: bool Unsynchronized.ref
    15.9 +  val show_consts_value: Config.value Config.T
   15.10 +  val show_consts: bool Config.T
   15.11    val pretty_flexpair: Proof.context -> term * term -> Pretty.T
   15.12    val pretty_goals: Proof.context -> {total: bool, main: bool, maxgoals: int} ->
   15.13      thm -> Pretty.T list
   15.14 @@ -19,7 +21,12 @@
   15.15  struct
   15.16  
   15.17  val goals_limit = Unsynchronized.ref 10;     (*max number of goals to print*)
   15.18 -val show_consts = Unsynchronized.ref false;  (*true: show consts with types in proof state output*)
   15.19 +
   15.20 +(*true: show consts with types in proof state output*)
   15.21 +val show_consts_default = Unsynchronized.ref false;
   15.22 +val show_consts_value =
   15.23 +  Config.declare false "show_consts" (fn _ => Config.Bool (! show_consts_default));
   15.24 +val show_consts = Config.bool show_consts_value;
   15.25  
   15.26  fun pretty_flexpair ctxt (t, u) = Pretty.block
   15.27    [Syntax.pretty_term ctxt t, Pretty.str " =?=", Pretty.brk 1, Syntax.pretty_term ctxt u];
   15.28 @@ -104,7 +111,7 @@
   15.29             else [])
   15.30          else pretty_subgoals As) @
   15.31        pretty_ffpairs tpairs @
   15.32 -      (if ! show_consts then pretty_consts prop else []) @
   15.33 +      (if Config.get ctxt show_consts then pretty_consts prop else []) @
   15.34        (if types then pretty_vars prop else []) @
   15.35        (if sorts then pretty_varsT prop else []);
   15.36    in
    16.1 --- a/src/Tools/jEdit/src/jedit/document_view.scala	Fri Sep 03 08:13:28 2010 +0200
    16.2 +++ b/src/Tools/jEdit/src/jedit/document_view.scala	Fri Sep 03 12:01:47 2010 +0200
    16.3 @@ -24,7 +24,9 @@
    16.4  
    16.5  object Document_View
    16.6  {
    16.7 -  def choose_color(snapshot: Document.Snapshot, command: Command): Color =
    16.8 +  /* physical rendering */
    16.9 +
   16.10 +  def status_color(snapshot: Document.Snapshot, command: Command): Color =
   16.11    {
   16.12      val state = snapshot.state(command)
   16.13      if (snapshot.is_outdated) new Color(240, 240, 240)
   16.14 @@ -38,6 +40,13 @@
   16.15        }
   16.16    }
   16.17  
   16.18 +  val message_markup: PartialFunction[Text.Info[Any], Color] =
   16.19 +  {
   16.20 +    case Text.Info(_, XML.Elem(Markup(Markup.WRITELN, _), _)) => new Color(220, 220, 220)
   16.21 +    case Text.Info(_, XML.Elem(Markup(Markup.WARNING, _), _)) => new Color(255, 165, 0)
   16.22 +    case Text.Info(_, XML.Elem(Markup(Markup.ERROR, _), _)) => new Color(255, 106, 106)
   16.23 +  }
   16.24 +
   16.25  
   16.26    /* document view of text area */
   16.27  
   16.28 @@ -163,18 +172,36 @@
   16.29        Isabelle.swing_buffer_lock(model.buffer) {
   16.30          val snapshot = model.snapshot()
   16.31          val saved_color = gfx.getColor
   16.32 +        val ascent = text_area.getPainter.getFontMetrics.getAscent
   16.33          try {
   16.34            for (i <- 0 until physical_lines.length) {
   16.35              if (physical_lines(i) != -1) {
   16.36                val line_range = proper_line_range(start(i), end(i))
   16.37 +
   16.38 +              // background color
   16.39                val cmds = snapshot.node.command_range(snapshot.revert(line_range))
   16.40 -              for ((command, command_start) <- cmds if !command.is_ignored) {
   16.41 +              for {
   16.42 +                (command, command_start) <- cmds if !command.is_ignored
   16.43                  val range = line_range.restrict(snapshot.convert(command.range + command_start))
   16.44 -                val p = text_area.offsetToXY(range.start)
   16.45 -                val q = text_area.offsetToXY(range.stop)
   16.46 -                if (p != null && q != null) {
   16.47 -                  gfx.setColor(Document_View.choose_color(snapshot, command))
   16.48 -                  gfx.fillRect(p.x, y + i * line_height, q.x - p.x, line_height)
   16.49 +                r <- Isabelle.gfx_range(text_area, range)
   16.50 +              } {
   16.51 +                gfx.setColor(Document_View.status_color(snapshot, command))
   16.52 +                gfx.fillRect(r.x, y + i * line_height, r.length, line_height)
   16.53 +              }
   16.54 +
   16.55 +              // squiggly underline
   16.56 +              for {
   16.57 +                Text.Info(range, color) <-
   16.58 +                  snapshot.select_markup(line_range)(Document_View.message_markup)(null)
   16.59 +                if color != null
   16.60 +                r <- Isabelle.gfx_range(text_area, range)
   16.61 +              } {
   16.62 +                gfx.setColor(color)
   16.63 +                val x0 = (r.x / 2) * 2
   16.64 +                val y0 = r.y + ascent + 1
   16.65 +                for (x1 <- Range(x0, x0 + r.length, 2)) {
   16.66 +                  val y1 = if (x1 % 4 < 2) y0 else y0 + 1
   16.67 +                  gfx.drawLine(x1, y1, x1 + 1, y1)
   16.68                  }
   16.69                }
   16.70              }
   16.71 @@ -266,7 +293,7 @@
   16.72              val line2 = buffer.getLineOfOffset(snapshot.convert(start + command.length)) + 1
   16.73              val y = line_to_y(line1)
   16.74              val height = HEIGHT * (line2 - line1)
   16.75 -            gfx.setColor(Document_View.choose_color(snapshot, command))
   16.76 +            gfx.setColor(Document_View.status_color(snapshot, command))
   16.77              gfx.fillRect(0, y, getWidth - 1, height)
   16.78            }
   16.79          }
    17.1 --- a/src/Tools/jEdit/src/jedit/plugin.scala	Fri Sep 03 08:13:28 2010 +0200
    17.2 +++ b/src/Tools/jEdit/src/jedit/plugin.scala	Fri Sep 03 12:01:47 2010 +0200
    17.3 @@ -17,7 +17,7 @@
    17.4  
    17.5  import org.gjt.sp.jedit.{jEdit, EBMessage, EBPlugin, Buffer, EditPane, ServiceManager, View}
    17.6  import org.gjt.sp.jedit.buffer.JEditBuffer
    17.7 -import org.gjt.sp.jedit.textarea.JEditTextArea
    17.8 +import org.gjt.sp.jedit.textarea.{JEditTextArea, TextArea}
    17.9  import org.gjt.sp.jedit.msg.{BufferUpdate, EditPaneUpdate, PropertiesChanged}
   17.10  import org.gjt.sp.jedit.gui.DockableWindowManager
   17.11  
   17.12 @@ -74,6 +74,19 @@
   17.13        Int_Property("relative-font-size", 100)).toFloat / 100
   17.14  
   17.15  
   17.16 +  /* text area ranges */
   17.17 +
   17.18 +  case class Gfx_Range(val x: Int, val y: Int, val length: Int)
   17.19 +
   17.20 +  def gfx_range(text_area: TextArea, range: Text.Range): Option[Gfx_Range] =
   17.21 +  {
   17.22 +    val p = text_area.offsetToXY(range.start)
   17.23 +    val q = text_area.offsetToXY(range.stop)
   17.24 +    if (p != null && q != null && p.y == q.y) Some(new Gfx_Range(p.x, p.y, q.x - p.x))
   17.25 +    else None
   17.26 +  }
   17.27 +
   17.28 +
   17.29    /* tooltip markup */
   17.30  
   17.31    def tooltip(text: String): String =