src/HOL/Tools/refute.ML
author blanchet
Fri Apr 23 16:59:48 2010 +0200 (2010-04-23)
changeset 36374 19c0c4b8b445
parent 36130 9a672f7d488d
child 36555 8ff45c2076da
permissions -rw-r--r--
remove debugging code
webertj@14350
     1
(*  Title:      HOL/Tools/refute.ML
wenzelm@29265
     2
    Author:     Tjark Weber, TU Muenchen
webertj@14350
     3
webertj@14965
     4
Finite model generation for HOL formulas, using a SAT solver.
webertj@14350
     5
*)
webertj@14350
     6
webertj@14456
     7
(* ------------------------------------------------------------------------- *)
webertj@14456
     8
(* Declares the 'REFUTE' signature as well as a structure 'Refute'.          *)
webertj@14456
     9
(* Documentation is available in the Isabelle/Isar theory 'HOL/Refute.thy'.  *)
webertj@14350
    10
(* ------------------------------------------------------------------------- *)
webertj@14350
    11
webertj@14350
    12
signature REFUTE =
webertj@14350
    13
sig
webertj@14350
    14
wenzelm@22567
    15
  exception REFUTE of string * string
webertj@14456
    16
webertj@14456
    17
(* ------------------------------------------------------------------------- *)
webertj@14807
    18
(* Model/interpretation related code (translation HOL -> propositional logic *)
webertj@14456
    19
(* ------------------------------------------------------------------------- *)
webertj@14456
    20
wenzelm@22567
    21
  type params
wenzelm@22567
    22
  type interpretation
wenzelm@22567
    23
  type model
wenzelm@22567
    24
  type arguments
webertj@14456
    25
wenzelm@22567
    26
  exception MAXVARS_EXCEEDED
webertj@14456
    27
wenzelm@33243
    28
  val add_interpreter : string -> (theory -> model -> arguments -> term ->
wenzelm@22567
    29
    (interpretation * model * arguments) option) -> theory -> theory
wenzelm@33243
    30
  val add_printer     : string -> (theory -> model -> typ ->
wenzelm@33243
    31
    interpretation -> (int -> bool) -> term option) -> theory -> theory
webertj@14456
    32
wenzelm@33243
    33
  val interpret : theory -> model -> arguments -> term ->
wenzelm@22567
    34
    (interpretation * model * arguments)
webertj@14807
    35
wenzelm@33243
    36
  val print       : theory -> model -> typ -> interpretation -> (int -> bool) -> term
wenzelm@22567
    37
  val print_model : theory -> model -> (int -> bool) -> string
webertj@14456
    38
webertj@14456
    39
(* ------------------------------------------------------------------------- *)
webertj@14456
    40
(* Interface                                                                 *)
webertj@14456
    41
(* ------------------------------------------------------------------------- *)
webertj@14456
    42
wenzelm@22567
    43
  val set_default_param  : (string * string) -> theory -> theory
wenzelm@22567
    44
  val get_default_param  : theory -> string -> string option
wenzelm@22567
    45
  val get_default_params : theory -> (string * string) list
wenzelm@22567
    46
  val actual_params      : theory -> (string * string) list -> params
webertj@14456
    47
blanchet@34120
    48
  val find_model : theory -> params -> term list -> term -> bool -> unit
webertj@14456
    49
wenzelm@22567
    50
  (* tries to find a model for a formula: *)
blanchet@34120
    51
  val satisfy_term :
blanchet@34120
    52
    theory -> (string * string) list -> term list -> term -> unit
wenzelm@22567
    53
  (* tries to find a model that refutes a formula: *)
blanchet@34120
    54
  val refute_term :
blanchet@34120
    55
    theory -> (string * string) list -> term list -> term -> unit
blanchet@34120
    56
  val refute_goal :
blanchet@34120
    57
    Proof.context -> (string * string) list -> thm -> int -> unit
webertj@14456
    58
wenzelm@22567
    59
  val setup : theory -> theory
webertj@22092
    60
blanchet@29802
    61
(* ------------------------------------------------------------------------- *)
blanchet@29802
    62
(* Additional functions used by Nitpick (to be factored out)                 *)
blanchet@29802
    63
(* ------------------------------------------------------------------------- *)
blanchet@29802
    64
wenzelm@33243
    65
  val close_form : term -> term
wenzelm@33243
    66
  val get_classdef : theory -> string -> (string * term) option
wenzelm@33243
    67
  val norm_rhs : term -> term
wenzelm@33243
    68
  val get_def : theory -> string * typ -> (string * term) option
wenzelm@33243
    69
  val get_typedef : theory -> typ -> (string * term) option
wenzelm@33243
    70
  val is_IDT_constructor : theory -> string * typ -> bool
wenzelm@33243
    71
  val is_IDT_recursor : theory -> string * typ -> bool
wenzelm@33243
    72
  val is_const_of_class: theory -> string * typ -> bool
wenzelm@33243
    73
  val monomorphic_term : Type.tyenv -> term -> term
wenzelm@33243
    74
  val specialize_type : theory -> (string * typ) -> term -> term
wenzelm@33243
    75
  val string_of_typ : typ -> string
wenzelm@33243
    76
  val typ_of_dtyp : Datatype.descr -> (Datatype.dtyp * typ) list -> Datatype.dtyp -> typ
webertj@22092
    77
end;  (* signature REFUTE *)
webertj@14456
    78
webertj@14456
    79
structure Refute : REFUTE =
webertj@14456
    80
struct
webertj@14456
    81
wenzelm@22567
    82
  open PropLogic;
webertj@14456
    83
wenzelm@22567
    84
  (* We use 'REFUTE' only for internal error conditions that should    *)
wenzelm@22567
    85
  (* never occur in the first place (i.e. errors caused by bugs in our *)
wenzelm@22567
    86
  (* code).  Otherwise (e.g. to indicate invalid input data) we use    *)
wenzelm@22567
    87
  (* 'error'.                                                          *)
wenzelm@22567
    88
  exception REFUTE of string * string;  (* ("in function", "cause") *)
webertj@14350
    89
wenzelm@22567
    90
  (* should be raised by an interpreter when more variables would be *)
wenzelm@22567
    91
  (* required than allowed by 'maxvars'                              *)
wenzelm@22567
    92
  exception MAXVARS_EXCEEDED;
webertj@14350
    93
webertj@14350
    94
(* ------------------------------------------------------------------------- *)
webertj@14350
    95
(* TREES                                                                     *)
webertj@14350
    96
(* ------------------------------------------------------------------------- *)
webertj@14350
    97
webertj@14350
    98
(* ------------------------------------------------------------------------- *)
webertj@14350
    99
(* tree: implements an arbitrarily (but finitely) branching tree as a list   *)
webertj@14350
   100
(*       of (lists of ...) elements                                          *)
webertj@14350
   101
(* ------------------------------------------------------------------------- *)
webertj@14350
   102
wenzelm@22567
   103
  datatype 'a tree =
wenzelm@22567
   104
      Leaf of 'a
wenzelm@22567
   105
    | Node of ('a tree) list;
webertj@14350
   106
wenzelm@22567
   107
  (* ('a -> 'b) -> 'a tree -> 'b tree *)
webertj@14350
   108
wenzelm@22567
   109
  fun tree_map f tr =
wenzelm@22567
   110
    case tr of
wenzelm@22567
   111
      Leaf x  => Leaf (f x)
wenzelm@22567
   112
    | Node xs => Node (map (tree_map f) xs);
webertj@14350
   113
wenzelm@22567
   114
  (* ('a * 'b -> 'a) -> 'a * ('b tree) -> 'a *)
webertj@14350
   115
wenzelm@22567
   116
  fun tree_foldl f =
wenzelm@22567
   117
  let
wenzelm@22567
   118
    fun itl (e, Leaf x)  = f(e,x)
wenzelm@22567
   119
      | itl (e, Node xs) = Library.foldl (tree_foldl f) (e,xs)
wenzelm@22567
   120
  in
wenzelm@22567
   121
    itl
wenzelm@22567
   122
  end;
webertj@14350
   123
wenzelm@22567
   124
  (* 'a tree * 'b tree -> ('a * 'b) tree *)
webertj@14350
   125
wenzelm@22567
   126
  fun tree_pair (t1, t2) =
wenzelm@22567
   127
    case t1 of
wenzelm@22567
   128
      Leaf x =>
wenzelm@22567
   129
      (case t2 of
wenzelm@22567
   130
          Leaf y => Leaf (x,y)
wenzelm@22567
   131
        | Node _ => raise REFUTE ("tree_pair",
wenzelm@22567
   132
            "trees are of different height (second tree is higher)"))
wenzelm@22567
   133
    | Node xs =>
wenzelm@22567
   134
      (case t2 of
wenzelm@22567
   135
          (* '~~' will raise an exception if the number of branches in   *)
wenzelm@22567
   136
          (* both trees is different at the current node                 *)
wenzelm@22567
   137
          Node ys => Node (map tree_pair (xs ~~ ys))
wenzelm@22567
   138
        | Leaf _  => raise REFUTE ("tree_pair",
wenzelm@22567
   139
            "trees are of different height (first tree is higher)"));
webertj@14350
   140
webertj@14350
   141
(* ------------------------------------------------------------------------- *)
webertj@14807
   142
(* params: parameters that control the translation into a propositional      *)
webertj@14807
   143
(*         formula/model generation                                          *)
webertj@14807
   144
(*                                                                           *)
webertj@14807
   145
(* The following parameters are supported (and required (!), except for      *)
blanchet@30314
   146
(* "sizes" and "expect"):                                                    *)
webertj@14807
   147
(*                                                                           *)
webertj@14807
   148
(* Name          Type    Description                                         *)
webertj@14807
   149
(*                                                                           *)
webertj@14807
   150
(* "sizes"       (string * int) list                                         *)
webertj@14807
   151
(*                       Size of ground types (e.g. 'a=2), or depth of IDTs. *)
webertj@14807
   152
(* "minsize"     int     If >0, minimal size of each ground type/IDT depth.  *)
webertj@14807
   153
(* "maxsize"     int     If >0, maximal size of each ground type/IDT depth.  *)
webertj@14807
   154
(* "maxvars"     int     If >0, use at most 'maxvars' Boolean variables      *)
webertj@14807
   155
(*                       when transforming the term into a propositional     *)
webertj@14807
   156
(*                       formula.                                            *)
webertj@14807
   157
(* "maxtime"     int     If >0, terminate after at most 'maxtime' seconds.   *)
webertj@14807
   158
(* "satsolver"   string  SAT solver to be used.                              *)
blanchet@34120
   159
(* "no_assms"    bool    If "true", assumptions in structured proofs are     *)
blanchet@34120
   160
(*                       not considered.                                     *)
blanchet@30314
   161
(* "expect"      string  Expected result ("genuine", "potential", "none", or *)
blanchet@34120
   162
(*                       "unknown").                                         *)
webertj@14807
   163
(* ------------------------------------------------------------------------- *)
webertj@14807
   164
wenzelm@22567
   165
  type params =
wenzelm@22567
   166
    {
wenzelm@22567
   167
      sizes    : (string * int) list,
wenzelm@22567
   168
      minsize  : int,
wenzelm@22567
   169
      maxsize  : int,
wenzelm@22567
   170
      maxvars  : int,
wenzelm@22567
   171
      maxtime  : int,
blanchet@30314
   172
      satsolver: string,
blanchet@34120
   173
      no_assms : bool,
blanchet@30314
   174
      expect   : string
wenzelm@22567
   175
    };
webertj@14807
   176
webertj@14807
   177
(* ------------------------------------------------------------------------- *)
webertj@14456
   178
(* interpretation: a term's interpretation is given by a variable of type    *)
webertj@14456
   179
(*                 'interpretation'                                          *)
webertj@14350
   180
(* ------------------------------------------------------------------------- *)
webertj@14350
   181
wenzelm@22567
   182
  type interpretation =
wenzelm@22567
   183
    prop_formula list tree;
webertj@14350
   184
webertj@14350
   185
(* ------------------------------------------------------------------------- *)
webertj@14456
   186
(* model: a model specifies the size of types and the interpretation of      *)
webertj@14456
   187
(*        terms                                                              *)
webertj@14350
   188
(* ------------------------------------------------------------------------- *)
webertj@14350
   189
wenzelm@22567
   190
  type model =
wenzelm@33243
   191
    (typ * int) list * (term * interpretation) list;
webertj@14350
   192
webertj@14456
   193
(* ------------------------------------------------------------------------- *)
webertj@14456
   194
(* arguments: additional arguments required during interpretation of terms   *)
webertj@14456
   195
(* ------------------------------------------------------------------------- *)
webertj@14807
   196
wenzelm@22567
   197
  type arguments =
wenzelm@22567
   198
    {
wenzelm@22567
   199
      (* just passed unchanged from 'params': *)
wenzelm@22567
   200
      maxvars   : int,
wenzelm@22567
   201
      (* whether to use 'make_equality' or 'make_def_equality': *)
wenzelm@22567
   202
      def_eq    : bool,
wenzelm@22567
   203
      (* the following may change during the translation: *)
wenzelm@22567
   204
      next_idx  : int,
wenzelm@22567
   205
      bounds    : interpretation list,
wenzelm@22567
   206
      wellformed: prop_formula
wenzelm@22567
   207
    };
webertj@14456
   208
webertj@14350
   209
wenzelm@33522
   210
  structure RefuteData = Theory_Data
wenzelm@22846
   211
  (
wenzelm@22567
   212
    type T =
wenzelm@33243
   213
      {interpreters: (string * (theory -> model -> arguments -> term ->
wenzelm@22567
   214
        (interpretation * model * arguments) option)) list,
wenzelm@33243
   215
       printers: (string * (theory -> model -> typ -> interpretation ->
wenzelm@33243
   216
        (int -> bool) -> term option)) list,
wenzelm@22567
   217
       parameters: string Symtab.table};
wenzelm@22567
   218
    val empty = {interpreters = [], printers = [], parameters = Symtab.empty};
wenzelm@22567
   219
    val extend = I;
wenzelm@33522
   220
    fun merge
wenzelm@22567
   221
      ({interpreters = in1, printers = pr1, parameters = pa1},
wenzelm@33522
   222
       {interpreters = in2, printers = pr2, parameters = pa2}) : T =
wenzelm@22567
   223
      {interpreters = AList.merge (op =) (K true) (in1, in2),
wenzelm@22567
   224
       printers = AList.merge (op =) (K true) (pr1, pr2),
wenzelm@22567
   225
       parameters = Symtab.merge (op=) (pa1, pa2)};
wenzelm@22846
   226
  );
webertj@14456
   227
webertj@14350
   228
webertj@14350
   229
(* ------------------------------------------------------------------------- *)
webertj@15334
   230
(* interpret: interprets the term 't' using a suitable interpreter; returns  *)
webertj@15334
   231
(*            the interpretation and a (possibly extended) model that keeps  *)
webertj@15334
   232
(*            track of the interpretation of subterms                        *)
webertj@14350
   233
(* ------------------------------------------------------------------------- *)
webertj@14350
   234
wenzelm@22567
   235
  (* theory -> model -> arguments -> Term.term ->
wenzelm@22567
   236
    (interpretation * model * arguments) *)
webertj@14456
   237
wenzelm@22567
   238
  fun interpret thy model args t =
wenzelm@22567
   239
    case get_first (fn (_, f) => f thy model args t)
wenzelm@22567
   240
      (#interpreters (RefuteData.get thy)) of
wenzelm@22567
   241
      NONE   => raise REFUTE ("interpret",
wenzelm@26939
   242
        "no interpreter for term " ^ quote (Syntax.string_of_term_global thy t))
wenzelm@22567
   243
    | SOME x => x;
webertj@14456
   244
webertj@14456
   245
(* ------------------------------------------------------------------------- *)
webertj@25014
   246
(* print: converts the interpretation 'intr', which must denote a term of    *)
webertj@25014
   247
(*        type 'T', into a term using a suitable printer                     *)
webertj@14456
   248
(* ------------------------------------------------------------------------- *)
webertj@14350
   249
webertj@25014
   250
  (* theory -> model -> Term.typ -> interpretation -> (int -> bool) ->
wenzelm@22567
   251
    Term.term *)
webertj@14456
   252
webertj@25014
   253
  fun print thy model T intr assignment =
webertj@25014
   254
    case get_first (fn (_, f) => f thy model T intr assignment)
wenzelm@22567
   255
      (#printers (RefuteData.get thy)) of
wenzelm@22567
   256
      NONE   => raise REFUTE ("print",
wenzelm@26939
   257
        "no printer for type " ^ quote (Syntax.string_of_typ_global thy T))
wenzelm@22567
   258
    | SOME x => x;
webertj@14456
   259
webertj@14456
   260
(* ------------------------------------------------------------------------- *)
webertj@14456
   261
(* print_model: turns the model into a string, using a fixed interpretation  *)
webertj@14807
   262
(*              (given by an assignment for Boolean variables) and suitable  *)
webertj@14456
   263
(*              printers                                                     *)
webertj@14456
   264
(* ------------------------------------------------------------------------- *)
webertj@14456
   265
wenzelm@22567
   266
  (* theory -> model -> (int -> bool) -> string *)
webertj@14807
   267
wenzelm@22567
   268
  fun print_model thy model assignment =
wenzelm@22567
   269
  let
wenzelm@22567
   270
    val (typs, terms) = model
wenzelm@22567
   271
    val typs_msg =
wenzelm@22567
   272
      if null typs then
wenzelm@22567
   273
        "empty universe (no type variables in term)\n"
wenzelm@22567
   274
      else
wenzelm@22567
   275
        "Size of types: " ^ commas (map (fn (T, i) =>
wenzelm@26939
   276
          Syntax.string_of_typ_global thy T ^ ": " ^ string_of_int i) typs) ^ "\n"
wenzelm@22567
   277
    val show_consts_msg =
wenzelm@22567
   278
      if not (!show_consts) andalso Library.exists (is_Const o fst) terms then
wenzelm@22567
   279
        "set \"show_consts\" to show the interpretation of constants\n"
wenzelm@22567
   280
      else
wenzelm@22567
   281
        ""
wenzelm@22567
   282
    val terms_msg =
wenzelm@22567
   283
      if null terms then
wenzelm@22567
   284
        "empty interpretation (no free variables in term)\n"
wenzelm@22567
   285
      else
wenzelm@32952
   286
        cat_lines (map_filter (fn (t, intr) =>
wenzelm@22567
   287
          (* print constants only if 'show_consts' is true *)
wenzelm@22567
   288
          if (!show_consts) orelse not (is_Const t) then
wenzelm@26939
   289
            SOME (Syntax.string_of_term_global thy t ^ ": " ^
wenzelm@26939
   290
              Syntax.string_of_term_global thy
webertj@25014
   291
                (print thy model (Term.type_of t) intr assignment))
wenzelm@22567
   292
          else
wenzelm@22567
   293
            NONE) terms) ^ "\n"
wenzelm@22567
   294
  in
wenzelm@22567
   295
    typs_msg ^ show_consts_msg ^ terms_msg
wenzelm@22567
   296
  end;
webertj@14456
   297
webertj@14456
   298
webertj@14456
   299
(* ------------------------------------------------------------------------- *)
webertj@14456
   300
(* PARAMETER MANAGEMENT                                                      *)
webertj@14456
   301
(* ------------------------------------------------------------------------- *)
webertj@14456
   302
wenzelm@22567
   303
  (* string -> (theory -> model -> arguments -> Term.term ->
wenzelm@22567
   304
    (interpretation * model * arguments) option) -> theory -> theory *)
webertj@14456
   305
wenzelm@22567
   306
  fun add_interpreter name f thy =
wenzelm@22567
   307
  let
wenzelm@22567
   308
    val {interpreters, printers, parameters} = RefuteData.get thy
wenzelm@22567
   309
  in
wenzelm@22567
   310
    case AList.lookup (op =) interpreters name of
wenzelm@22567
   311
      NONE   => RefuteData.put {interpreters = (name, f) :: interpreters,
wenzelm@22567
   312
      printers = printers, parameters = parameters} thy
wenzelm@22567
   313
    | SOME _ => error ("Interpreter " ^ name ^ " already declared")
wenzelm@22567
   314
  end;
webertj@14456
   315
webertj@25014
   316
  (* string -> (theory -> model -> Term.typ -> interpretation ->
wenzelm@22567
   317
    (int -> bool) -> Term.term option) -> theory -> theory *)
webertj@14456
   318
wenzelm@22567
   319
  fun add_printer name f thy =
wenzelm@22567
   320
  let
wenzelm@22567
   321
    val {interpreters, printers, parameters} = RefuteData.get thy
wenzelm@22567
   322
  in
wenzelm@22567
   323
    case AList.lookup (op =) printers name of
wenzelm@22567
   324
      NONE   => RefuteData.put {interpreters = interpreters,
wenzelm@22567
   325
      printers = (name, f) :: printers, parameters = parameters} thy
wenzelm@22567
   326
    | SOME _ => error ("Printer " ^ name ^ " already declared")
wenzelm@22567
   327
  end;
webertj@14456
   328
webertj@14456
   329
(* ------------------------------------------------------------------------- *)
webertj@14456
   330
(* set_default_param: stores the '(name, value)' pair in RefuteData's        *)
webertj@14456
   331
(*                    parameter table                                        *)
webertj@14456
   332
(* ------------------------------------------------------------------------- *)
webertj@14456
   333
wenzelm@22567
   334
  (* (string * string) -> theory -> theory *)
webertj@14456
   335
haftmann@29004
   336
  fun set_default_param (name, value) = RefuteData.map 
haftmann@29004
   337
    (fn {interpreters, printers, parameters} =>
wenzelm@22567
   338
      {interpreters = interpreters, printers = printers,
haftmann@29004
   339
        parameters = Symtab.update (name, value) parameters});
webertj@14350
   340
webertj@14350
   341
(* ------------------------------------------------------------------------- *)
webertj@14456
   342
(* get_default_param: retrieves the value associated with 'name' from        *)
webertj@14456
   343
(*                    RefuteData's parameter table                           *)
webertj@14456
   344
(* ------------------------------------------------------------------------- *)
webertj@14456
   345
wenzelm@22567
   346
  (* theory -> string -> string option *)
webertj@14456
   347
wenzelm@22567
   348
  val get_default_param = Symtab.lookup o #parameters o RefuteData.get;
webertj@14456
   349
webertj@14456
   350
(* ------------------------------------------------------------------------- *)
webertj@14456
   351
(* get_default_params: returns a list of all '(name, value)' pairs that are  *)
webertj@14456
   352
(*                     stored in RefuteData's parameter table                *)
webertj@14456
   353
(* ------------------------------------------------------------------------- *)
webertj@14456
   354
wenzelm@22567
   355
  (* theory -> (string * string) list *)
webertj@14456
   356
wenzelm@22567
   357
  val get_default_params = Symtab.dest o #parameters o RefuteData.get;
webertj@14456
   358
webertj@14456
   359
(* ------------------------------------------------------------------------- *)
webertj@14456
   360
(* actual_params: takes a (possibly empty) list 'params' of parameters that  *)
webertj@14456
   361
(*      override the default parameters currently specified in 'thy', and    *)
webertj@14807
   362
(*      returns a record that can be passed to 'find_model'.                 *)
webertj@14456
   363
(* ------------------------------------------------------------------------- *)
webertj@14456
   364
wenzelm@22567
   365
  (* theory -> (string * string) list -> params *)
webertj@14456
   366
wenzelm@22567
   367
  fun actual_params thy override =
wenzelm@22567
   368
  let
blanchet@34120
   369
    (* (string * string) list * string -> bool *)
blanchet@34120
   370
    fun read_bool (parms, name) =
blanchet@34120
   371
      case AList.lookup (op =) parms name of
blanchet@34120
   372
        SOME "true" => true
blanchet@34120
   373
      | SOME "false" => false
blanchet@34120
   374
      | SOME s => error ("parameter " ^ quote name ^
blanchet@34120
   375
        " (value is " ^ quote s ^ ") must be \"true\" or \"false\"")
blanchet@34120
   376
      | NONE   => error ("parameter " ^ quote name ^
blanchet@34120
   377
          " must be assigned a value")
wenzelm@22567
   378
    (* (string * string) list * string -> int *)
wenzelm@22567
   379
    fun read_int (parms, name) =
wenzelm@22567
   380
      case AList.lookup (op =) parms name of
wenzelm@22567
   381
        SOME s => (case Int.fromString s of
wenzelm@22567
   382
          SOME i => i
wenzelm@22567
   383
        | NONE   => error ("parameter " ^ quote name ^
wenzelm@22567
   384
          " (value is " ^ quote s ^ ") must be an integer value"))
wenzelm@22567
   385
      | NONE   => error ("parameter " ^ quote name ^
wenzelm@22567
   386
          " must be assigned a value")
wenzelm@22567
   387
    (* (string * string) list * string -> string *)
wenzelm@22567
   388
    fun read_string (parms, name) =
wenzelm@22567
   389
      case AList.lookup (op =) parms name of
wenzelm@22567
   390
        SOME s => s
wenzelm@22567
   391
      | NONE   => error ("parameter " ^ quote name ^
wenzelm@22567
   392
        " must be assigned a value")
wenzelm@22567
   393
    (* 'override' first, defaults last: *)
wenzelm@22567
   394
    (* (string * string) list *)
wenzelm@22567
   395
    val allparams = override @ (get_default_params thy)
wenzelm@22567
   396
    (* int *)
wenzelm@22567
   397
    val minsize   = read_int (allparams, "minsize")
wenzelm@22567
   398
    val maxsize   = read_int (allparams, "maxsize")
wenzelm@22567
   399
    val maxvars   = read_int (allparams, "maxvars")
wenzelm@22567
   400
    val maxtime   = read_int (allparams, "maxtime")
wenzelm@22567
   401
    (* string *)
wenzelm@22567
   402
    val satsolver = read_string (allparams, "satsolver")
blanchet@34120
   403
    val no_assms = read_bool (allparams, "no_assms")
blanchet@30314
   404
    val expect = the_default "" (AList.lookup (op =) allparams "expect")
wenzelm@22567
   405
    (* all remaining parameters of the form "string=int" are collected in *)
wenzelm@22567
   406
    (* 'sizes'                                                            *)
wenzelm@22567
   407
    (* TODO: it is currently not possible to specify a size for a type    *)
wenzelm@22567
   408
    (*       whose name is one of the other parameters (e.g. 'maxvars')   *)
wenzelm@22567
   409
    (* (string * int) list *)
wenzelm@32952
   410
    val sizes     = map_filter
wenzelm@22567
   411
      (fn (name, value) => Option.map (pair name) (Int.fromString value))
wenzelm@33317
   412
      (filter (fn (name, _) => name<>"minsize" andalso name<>"maxsize"
wenzelm@22567
   413
        andalso name<>"maxvars" andalso name<>"maxtime"
blanchet@34120
   414
        andalso name<>"satsolver" andalso name<>"no_assms") allparams)
wenzelm@22567
   415
  in
wenzelm@22567
   416
    {sizes=sizes, minsize=minsize, maxsize=maxsize, maxvars=maxvars,
blanchet@34120
   417
      maxtime=maxtime, satsolver=satsolver, no_assms=no_assms, expect=expect}
wenzelm@22567
   418
  end;
webertj@14807
   419
webertj@14807
   420
webertj@14807
   421
(* ------------------------------------------------------------------------- *)
webertj@14807
   422
(* TRANSLATION HOL -> PROPOSITIONAL LOGIC, BOOLEAN ASSIGNMENT -> MODEL       *)
webertj@14807
   423
(* ------------------------------------------------------------------------- *)
webertj@14807
   424
haftmann@33968
   425
  fun typ_of_dtyp descr typ_assoc (Datatype_Aux.DtTFree a) =
wenzelm@22567
   426
    (* replace a 'DtTFree' variable by the associated type *)
haftmann@33968
   427
    the (AList.lookup (op =) typ_assoc (Datatype_Aux.DtTFree a))
haftmann@33968
   428
    | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtType (s, ds)) =
wenzelm@22567
   429
    Type (s, map (typ_of_dtyp descr typ_assoc) ds)
haftmann@33968
   430
    | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtRec i) =
wenzelm@22567
   431
    let
wenzelm@29288
   432
      val (s, ds, _) = the (AList.lookup (op =) descr i)
wenzelm@22567
   433
    in
wenzelm@22567
   434
      Type (s, map (typ_of_dtyp descr typ_assoc) ds)
wenzelm@22567
   435
    end;
webertj@15335
   436
webertj@15335
   437
(* ------------------------------------------------------------------------- *)
webertj@21985
   438
(* close_form: universal closure over schematic variables in 't'             *)
webertj@21985
   439
(* ------------------------------------------------------------------------- *)
webertj@21985
   440
wenzelm@22567
   441
  (* Term.term -> Term.term *)
webertj@21985
   442
wenzelm@22567
   443
  fun close_form t =
wenzelm@22567
   444
  let
wenzelm@22567
   445
    (* (Term.indexname * Term.typ) list *)
wenzelm@29265
   446
    val vars = sort_wrt (fst o fst) (map dest_Var (OldTerm.term_vars t))
wenzelm@22567
   447
  in
wenzelm@33246
   448
    fold (fn ((x, i), T) => fn t' =>
wenzelm@33246
   449
      Term.all T $ Abs (x, T, abstract_over (Var ((x, i), T), t'))) vars t
wenzelm@22567
   450
  end;
webertj@21985
   451
webertj@21985
   452
(* ------------------------------------------------------------------------- *)
webertj@21985
   453
(* monomorphic_term: applies a type substitution 'typeSubs' for all type     *)
webertj@21985
   454
(*                   variables in a term 't'                                 *)
webertj@21985
   455
(* ------------------------------------------------------------------------- *)
webertj@21985
   456
wenzelm@22567
   457
  (* Type.tyenv -> Term.term -> Term.term *)
webertj@21985
   458
wenzelm@22567
   459
  fun monomorphic_term typeSubs t =
wenzelm@22567
   460
    map_types (map_type_tvar
wenzelm@22567
   461
      (fn v =>
haftmann@26328
   462
        case Type.lookup typeSubs v of
wenzelm@22567
   463
          NONE =>
wenzelm@22567
   464
          (* schematic type variable not instantiated *)
wenzelm@22567
   465
          raise REFUTE ("monomorphic_term",
wenzelm@22567
   466
            "no substitution for type variable " ^ fst (fst v) ^
wenzelm@26957
   467
            " in term " ^ Syntax.string_of_term_global Pure.thy t)
wenzelm@22567
   468
        | SOME typ =>
wenzelm@22567
   469
          typ)) t;
webertj@21985
   470
webertj@21985
   471
(* ------------------------------------------------------------------------- *)
webertj@21985
   472
(* specialize_type: given a constant 's' of type 'T', which is a subterm of  *)
webertj@21985
   473
(*                  't', where 't' has a (possibly) more general type, the   *)
webertj@21985
   474
(*                  schematic type variables in 't' are instantiated to      *)
webertj@21985
   475
(*                  match the type 'T' (may raise Type.TYPE_MATCH)           *)
webertj@21985
   476
(* ------------------------------------------------------------------------- *)
webertj@21985
   477
wenzelm@22567
   478
  (* theory -> (string * Term.typ) -> Term.term -> Term.term *)
webertj@21985
   479
wenzelm@22567
   480
  fun specialize_type thy (s, T) t =
wenzelm@22567
   481
  let
wenzelm@22567
   482
    fun find_typeSubs (Const (s', T')) =
wenzelm@22567
   483
      if s=s' then
wenzelm@22567
   484
        SOME (Sign.typ_match thy (T', T) Vartab.empty)
wenzelm@22567
   485
          handle Type.TYPE_MATCH => NONE
wenzelm@22567
   486
      else
wenzelm@22567
   487
        NONE
wenzelm@22567
   488
      | find_typeSubs (Free _)           = NONE
wenzelm@22567
   489
      | find_typeSubs (Var _)            = NONE
wenzelm@22567
   490
      | find_typeSubs (Bound _)          = NONE
wenzelm@22567
   491
      | find_typeSubs (Abs (_, _, body)) = find_typeSubs body
wenzelm@22567
   492
      | find_typeSubs (t1 $ t2)          =
wenzelm@22567
   493
      (case find_typeSubs t1 of SOME x => SOME x
wenzelm@22567
   494
                              | NONE   => find_typeSubs t2)
wenzelm@22567
   495
  in
wenzelm@22567
   496
    case find_typeSubs t of
wenzelm@22567
   497
      SOME typeSubs =>
wenzelm@22567
   498
      monomorphic_term typeSubs t
wenzelm@22567
   499
    | NONE =>
wenzelm@22567
   500
      (* no match found - perhaps due to sort constraints *)
wenzelm@22567
   501
      raise Type.TYPE_MATCH
wenzelm@22567
   502
  end;
webertj@21985
   503
webertj@21985
   504
(* ------------------------------------------------------------------------- *)
webertj@21985
   505
(* is_const_of_class: returns 'true' iff 'Const (s, T)' is a constant that   *)
webertj@21985
   506
(*                    denotes membership to an axiomatic type class          *)
webertj@21985
   507
(* ------------------------------------------------------------------------- *)
webertj@21985
   508
wenzelm@22567
   509
  (* theory -> string * Term.typ -> bool *)
webertj@21985
   510
wenzelm@22567
   511
  fun is_const_of_class thy (s, T) =
wenzelm@22567
   512
  let
wenzelm@22567
   513
    val class_const_names = map Logic.const_of_class (Sign.all_classes thy)
wenzelm@22567
   514
  in
wenzelm@22567
   515
    (* I'm not quite sure if checking the name 's' is sufficient, *)
wenzelm@22567
   516
    (* or if we should also check the type 'T'.                   *)
wenzelm@22567
   517
    s mem_string class_const_names
wenzelm@22567
   518
  end;
webertj@21985
   519
webertj@21985
   520
(* ------------------------------------------------------------------------- *)
webertj@21985
   521
(* is_IDT_constructor: returns 'true' iff 'Const (s, T)' is the constructor  *)
webertj@21985
   522
(*                     of an inductive datatype in 'thy'                     *)
webertj@21985
   523
(* ------------------------------------------------------------------------- *)
webertj@21985
   524
wenzelm@22567
   525
  (* theory -> string * Term.typ -> bool *)
webertj@21985
   526
wenzelm@22567
   527
  fun is_IDT_constructor thy (s, T) =
wenzelm@22567
   528
    (case body_type T of
wenzelm@22567
   529
      Type (s', _) =>
haftmann@31784
   530
      (case Datatype.get_constrs thy s' of
wenzelm@22567
   531
        SOME constrs =>
wenzelm@22567
   532
        List.exists (fn (cname, cty) =>
wenzelm@22567
   533
          cname = s andalso Sign.typ_instance thy (T, cty)) constrs
wenzelm@22567
   534
      | NONE =>
wenzelm@22567
   535
        false)
wenzelm@22567
   536
    | _  =>
wenzelm@22567
   537
      false);
webertj@21985
   538
webertj@21985
   539
(* ------------------------------------------------------------------------- *)
webertj@21985
   540
(* is_IDT_recursor: returns 'true' iff 'Const (s, T)' is the recursion       *)
webertj@21985
   541
(*                  operator of an inductive datatype in 'thy'               *)
webertj@21985
   542
(* ------------------------------------------------------------------------- *)
webertj@21985
   543
wenzelm@22567
   544
  (* theory -> string * Term.typ -> bool *)
webertj@21985
   545
wenzelm@22567
   546
  fun is_IDT_recursor thy (s, T) =
wenzelm@22567
   547
  let
wenzelm@22567
   548
    val rec_names = Symtab.fold (append o #rec_names o snd)
haftmann@31784
   549
      (Datatype.get_all thy) []
wenzelm@22567
   550
  in
wenzelm@22567
   551
    (* I'm not quite sure if checking the name 's' is sufficient, *)
wenzelm@22567
   552
    (* or if we should also check the type 'T'.                   *)
wenzelm@22567
   553
    s mem_string rec_names
wenzelm@22567
   554
  end;
webertj@21985
   555
webertj@21985
   556
(* ------------------------------------------------------------------------- *)
blanchet@30275
   557
(* norm_rhs: maps  f ?t1 ... ?tn == rhs  to  %t1...tn. rhs                   *)
blanchet@30275
   558
(* ------------------------------------------------------------------------- *)
blanchet@30275
   559
blanchet@30275
   560
  fun norm_rhs eqn =
blanchet@30275
   561
  let
blanchet@30275
   562
    fun lambda (v as Var ((x, _), T)) t = Abs (x, T, abstract_over (v, t))
blanchet@30275
   563
      | lambda v t                      = raise TERM ("lambda", [v, t])
blanchet@30275
   564
    val (lhs, rhs) = Logic.dest_equals eqn
blanchet@30275
   565
    val (_, args)  = Term.strip_comb lhs
blanchet@30275
   566
  in
blanchet@30275
   567
    fold lambda (rev args) rhs
blanchet@30275
   568
  end
blanchet@30275
   569
blanchet@30275
   570
(* ------------------------------------------------------------------------- *)
webertj@21985
   571
(* get_def: looks up the definition of a constant, as created by "constdefs" *)
webertj@21985
   572
(* ------------------------------------------------------------------------- *)
webertj@21985
   573
wenzelm@22567
   574
  (* theory -> string * Term.typ -> (string * Term.term) option *)
webertj@21985
   575
wenzelm@22567
   576
  fun get_def thy (s, T) =
wenzelm@22567
   577
  let
wenzelm@22567
   578
    (* (string * Term.term) list -> (string * Term.term) option *)
wenzelm@22567
   579
    fun get_def_ax [] = NONE
wenzelm@22567
   580
      | get_def_ax ((axname, ax) :: axioms) =
wenzelm@22567
   581
      (let
wenzelm@22567
   582
        val (lhs, _) = Logic.dest_equals ax  (* equations only *)
wenzelm@22567
   583
        val c        = Term.head_of lhs
wenzelm@22567
   584
        val (s', T') = Term.dest_Const c
wenzelm@22567
   585
      in
wenzelm@22567
   586
        if s=s' then
wenzelm@22567
   587
          let
wenzelm@22567
   588
            val typeSubs = Sign.typ_match thy (T', T) Vartab.empty
wenzelm@22567
   589
            val ax'      = monomorphic_term typeSubs ax
wenzelm@22567
   590
            val rhs      = norm_rhs ax'
wenzelm@22567
   591
          in
wenzelm@22567
   592
            SOME (axname, rhs)
wenzelm@22567
   593
          end
wenzelm@22567
   594
        else
wenzelm@22567
   595
          get_def_ax axioms
wenzelm@22567
   596
      end handle ERROR _         => get_def_ax axioms
wenzelm@22567
   597
               | TERM _          => get_def_ax axioms
wenzelm@22567
   598
               | Type.TYPE_MATCH => get_def_ax axioms)
wenzelm@22567
   599
  in
wenzelm@22567
   600
    get_def_ax (Theory.all_axioms_of thy)
wenzelm@22567
   601
  end;
webertj@21985
   602
webertj@21985
   603
(* ------------------------------------------------------------------------- *)
webertj@21985
   604
(* get_typedef: looks up the definition of a type, as created by "typedef"   *)
webertj@21985
   605
(* ------------------------------------------------------------------------- *)
webertj@21985
   606
blanchet@29802
   607
  (* theory -> Term.typ -> (string * Term.term) option *)
webertj@21985
   608
wenzelm@22567
   609
  fun get_typedef thy T =
wenzelm@22567
   610
  let
wenzelm@22567
   611
    (* (string * Term.term) list -> (string * Term.term) option *)
wenzelm@22567
   612
    fun get_typedef_ax [] = NONE
wenzelm@22567
   613
      | get_typedef_ax ((axname, ax) :: axioms) =
wenzelm@22567
   614
      (let
wenzelm@22567
   615
        (* Term.term -> Term.typ option *)
wenzelm@22567
   616
        fun type_of_type_definition (Const (s', T')) =
wenzelm@35746
   617
          if s'= @{const_name type_definition} then
wenzelm@22567
   618
            SOME T'
wenzelm@22567
   619
          else
wenzelm@22567
   620
            NONE
wenzelm@22567
   621
          | type_of_type_definition (Free _)           = NONE
wenzelm@22567
   622
          | type_of_type_definition (Var _)            = NONE
wenzelm@22567
   623
          | type_of_type_definition (Bound _)          = NONE
wenzelm@22567
   624
          | type_of_type_definition (Abs (_, _, body)) =
wenzelm@22567
   625
          type_of_type_definition body
wenzelm@22567
   626
          | type_of_type_definition (t1 $ t2)          =
wenzelm@22567
   627
          (case type_of_type_definition t1 of
wenzelm@22567
   628
            SOME x => SOME x
wenzelm@22567
   629
          | NONE   => type_of_type_definition t2)
wenzelm@22567
   630
      in
wenzelm@22567
   631
        case type_of_type_definition ax of
wenzelm@22567
   632
          SOME T' =>
wenzelm@22567
   633
          let
wenzelm@22567
   634
            val T''      = (domain_type o domain_type) T'
wenzelm@22567
   635
            val typeSubs = Sign.typ_match thy (T'', T) Vartab.empty
wenzelm@22567
   636
          in
wenzelm@22567
   637
            SOME (axname, monomorphic_term typeSubs ax)
wenzelm@22567
   638
          end
wenzelm@22567
   639
        | NONE =>
wenzelm@22567
   640
          get_typedef_ax axioms
wenzelm@22567
   641
      end handle ERROR _         => get_typedef_ax axioms
wenzelm@22567
   642
               | MATCH           => get_typedef_ax axioms
wenzelm@22567
   643
               | Type.TYPE_MATCH => get_typedef_ax axioms)
wenzelm@22567
   644
  in
wenzelm@22567
   645
    get_typedef_ax (Theory.all_axioms_of thy)
wenzelm@22567
   646
  end;
webertj@21985
   647
webertj@21985
   648
(* ------------------------------------------------------------------------- *)
webertj@21985
   649
(* get_classdef: looks up the defining axiom for an axiomatic type class, as *)
webertj@21985
   650
(*               created by the "axclass" command                            *)
webertj@21985
   651
(* ------------------------------------------------------------------------- *)
webertj@21985
   652
wenzelm@22567
   653
  (* theory -> string -> (string * Term.term) option *)
webertj@21985
   654
wenzelm@22567
   655
  fun get_classdef thy class =
wenzelm@22567
   656
  let
wenzelm@22567
   657
    val axname = class ^ "_class_def"
wenzelm@22567
   658
  in
wenzelm@22567
   659
    Option.map (pair axname)
wenzelm@22567
   660
      (AList.lookup (op =) (Theory.all_axioms_of thy) axname)
wenzelm@22567
   661
  end;
webertj@21985
   662
webertj@21985
   663
(* ------------------------------------------------------------------------- *)
webertj@21985
   664
(* unfold_defs: unfolds all defined constants in a term 't', beta-eta        *)
webertj@21985
   665
(*              normalizes the result term; certain constants are not        *)
webertj@21985
   666
(*              unfolded (cf. 'collect_axioms' and the various interpreters  *)
webertj@21985
   667
(*              below): if the interpretation respects a definition anyway,  *)
webertj@21985
   668
(*              that definition does not need to be unfolded                 *)
webertj@21985
   669
(* ------------------------------------------------------------------------- *)
webertj@21985
   670
wenzelm@22567
   671
  (* theory -> Term.term -> Term.term *)
webertj@21985
   672
wenzelm@22567
   673
  (* Note: we could intertwine unfolding of constants and beta-(eta-)       *)
wenzelm@22567
   674
  (*       normalization; this would save some unfolding for terms where    *)
wenzelm@22567
   675
  (*       constants are eliminated by beta-reduction (e.g. 'K c1 c2').  On *)
wenzelm@22567
   676
  (*       the other hand, this would cause additional work for terms where *)
wenzelm@22567
   677
  (*       constants are duplicated by beta-reduction (e.g. 'S c1 c2 c3').  *)
webertj@21985
   678
wenzelm@22567
   679
  fun unfold_defs thy t =
wenzelm@22567
   680
  let
wenzelm@22567
   681
    (* Term.term -> Term.term *)
wenzelm@22567
   682
    fun unfold_loop t =
wenzelm@22567
   683
      case t of
wenzelm@22567
   684
      (* Pure *)
blanchet@29802
   685
        Const (@{const_name all}, _) => t
blanchet@29802
   686
      | Const (@{const_name "=="}, _) => t
blanchet@29802
   687
      | Const (@{const_name "==>"}, _) => t
blanchet@29802
   688
      | Const (@{const_name TYPE}, _) => t  (* axiomatic type classes *)
wenzelm@22567
   689
      (* HOL *)
blanchet@29802
   690
      | Const (@{const_name Trueprop}, _) => t
blanchet@29802
   691
      | Const (@{const_name Not}, _) => t
wenzelm@22567
   692
      | (* redundant, since 'True' is also an IDT constructor *)
blanchet@29802
   693
        Const (@{const_name True}, _) => t
wenzelm@22567
   694
      | (* redundant, since 'False' is also an IDT constructor *)
blanchet@29802
   695
        Const (@{const_name False}, _) => t
blanchet@29802
   696
      | Const (@{const_name undefined}, _) => t
blanchet@29802
   697
      | Const (@{const_name The}, _) => t
blanchet@29820
   698
      | Const (@{const_name Hilbert_Choice.Eps}, _) => t
blanchet@29802
   699
      | Const (@{const_name All}, _) => t
blanchet@29802
   700
      | Const (@{const_name Ex}, _) => t
blanchet@29802
   701
      | Const (@{const_name "op ="}, _) => t
blanchet@29802
   702
      | Const (@{const_name "op &"}, _) => t
blanchet@29802
   703
      | Const (@{const_name "op |"}, _) => t
blanchet@29802
   704
      | Const (@{const_name "op -->"}, _) => t
wenzelm@22567
   705
      (* sets *)
blanchet@29802
   706
      | Const (@{const_name Collect}, _) => t
blanchet@29802
   707
      | Const (@{const_name "op :"}, _) => t
wenzelm@22567
   708
      (* other optimizations *)
blanchet@29820
   709
      | Const (@{const_name Finite_Set.card}, _) => t
blanchet@29820
   710
      | Const (@{const_name Finite_Set.finite}, _) => t
haftmann@35092
   711
      | Const (@{const_name Orderings.less}, Type ("fun", [Type ("nat", []),
wenzelm@22567
   712
        Type ("fun", [Type ("nat", []), Type ("bool", [])])])) => t
haftmann@35267
   713
      | Const (@{const_name Groups.plus}, Type ("fun", [Type ("nat", []),
wenzelm@22567
   714
        Type ("fun", [Type ("nat", []), Type ("nat", [])])])) => t
haftmann@35267
   715
      | Const (@{const_name Groups.minus}, Type ("fun", [Type ("nat", []),
wenzelm@22567
   716
        Type ("fun", [Type ("nat", []), Type ("nat", [])])])) => t
haftmann@35267
   717
      | Const (@{const_name Groups.times}, Type ("fun", [Type ("nat", []),
wenzelm@22567
   718
        Type ("fun", [Type ("nat", []), Type ("nat", [])])])) => t
blanchet@29820
   719
      | Const (@{const_name List.append}, _) => t
blanchet@36130
   720
(* UNSOUND
blanchet@29802
   721
      | Const (@{const_name lfp}, _) => t
blanchet@29802
   722
      | Const (@{const_name gfp}, _) => t
blanchet@36130
   723
*)
blanchet@29820
   724
      | Const (@{const_name fst}, _) => t
blanchet@29820
   725
      | Const (@{const_name snd}, _) => t
wenzelm@22567
   726
      (* simply-typed lambda calculus *)
wenzelm@22567
   727
      | Const (s, T) =>
wenzelm@22567
   728
        (if is_IDT_constructor thy (s, T)
wenzelm@22567
   729
          orelse is_IDT_recursor thy (s, T) then
wenzelm@22567
   730
          t  (* do not unfold IDT constructors/recursors *)
wenzelm@22567
   731
        (* unfold the constant if there is a defining equation *)
wenzelm@22567
   732
        else case get_def thy (s, T) of
wenzelm@22567
   733
          SOME (axname, rhs) =>
wenzelm@22567
   734
          (* Note: if the term to be unfolded (i.e. 'Const (s, T)')  *)
wenzelm@22567
   735
          (* occurs on the right-hand side of the equation, i.e. in  *)
wenzelm@22567
   736
          (* 'rhs', we must not use this equation to unfold, because *)
wenzelm@22567
   737
          (* that would loop.  Here would be the right place to      *)
wenzelm@22567
   738
          (* check this.  However, getting this really right seems   *)
wenzelm@22567
   739
          (* difficult because the user may state arbitrary axioms,  *)
wenzelm@22567
   740
          (* which could interact with overloading to create loops.  *)
wenzelm@32950
   741
          ((*tracing (" unfolding: " ^ axname);*)
blanchet@29820
   742
           unfold_loop rhs)
wenzelm@22567
   743
        | NONE => t)
wenzelm@22567
   744
      | Free _           => t
wenzelm@22567
   745
      | Var _            => t
wenzelm@22567
   746
      | Bound _          => t
wenzelm@22567
   747
      | Abs (s, T, body) => Abs (s, T, unfold_loop body)
wenzelm@22567
   748
      | t1 $ t2          => (unfold_loop t1) $ (unfold_loop t2)
wenzelm@22567
   749
    val result = Envir.beta_eta_contract (unfold_loop t)
wenzelm@22567
   750
  in
wenzelm@22567
   751
    result
wenzelm@22567
   752
  end;
webertj@21985
   753
webertj@21985
   754
(* ------------------------------------------------------------------------- *)
webertj@21985
   755
(* collect_axioms: collects (monomorphic, universally quantified, unfolded   *)
webertj@21985
   756
(*                 versions of) all HOL axioms that are relevant w.r.t 't'   *)
webertj@14807
   757
(* ------------------------------------------------------------------------- *)
webertj@14807
   758
wenzelm@22567
   759
  (* Note: to make the collection of axioms more easily extensible, this    *)
wenzelm@22567
   760
  (*       function could be based on user-supplied "axiom collectors",     *)
wenzelm@22567
   761
  (*       similar to 'interpret'/interpreters or 'print'/printers          *)
webertj@14807
   762
wenzelm@22567
   763
  (* Note: currently we use "inverse" functions to the definitional         *)
wenzelm@22567
   764
  (*       mechanisms provided by Isabelle/HOL, e.g. for "axclass",         *)
wenzelm@22567
   765
  (*       "typedef", "constdefs".  A more general approach could consider  *)
wenzelm@22567
   766
  (*       *every* axiom of the theory and collect it if it has a constant/ *)
wenzelm@22567
   767
  (*       type/typeclass in common with the term 't'.                      *)
webertj@21985
   768
wenzelm@22567
   769
  (* theory -> Term.term -> Term.term list *)
webertj@14807
   770
wenzelm@22567
   771
  (* Which axioms are "relevant" for a particular term/type goes hand in    *)
wenzelm@22567
   772
  (* hand with the interpretation of that term/type by its interpreter (see *)
wenzelm@22567
   773
  (* way below): if the interpretation respects an axiom anyway, the axiom  *)
wenzelm@22567
   774
  (* does not need to be added as a constraint here.                        *)
webertj@14807
   775
wenzelm@22567
   776
  (* To avoid collecting the same axiom multiple times, we use an           *)
wenzelm@22567
   777
  (* accumulator 'axs' which contains all axioms collected so far.          *)
webertj@14807
   778
wenzelm@22567
   779
  fun collect_axioms thy t =
wenzelm@22567
   780
  let
wenzelm@32950
   781
    val _ = tracing "Adding axioms..."
wenzelm@22567
   782
    val axioms = Theory.all_axioms_of thy
wenzelm@22567
   783
    fun collect_this_axiom (axname, ax) axs =
wenzelm@33246
   784
      let
wenzelm@33246
   785
        val ax' = unfold_defs thy ax
wenzelm@33246
   786
      in
wenzelm@33246
   787
        if member (op aconv) axs ax' then axs
wenzelm@33246
   788
        else (tracing axname; collect_term_axioms ax' (ax' :: axs))
wenzelm@33246
   789
      end
wenzelm@33246
   790
    and collect_sort_axioms T axs =
wenzelm@33246
   791
      let
wenzelm@33246
   792
        val sort =
wenzelm@33246
   793
          (case T of
wenzelm@33246
   794
            TFree (_, sort) => sort
wenzelm@33246
   795
          | TVar (_, sort)  => sort
wenzelm@33246
   796
          | _ => raise REFUTE ("collect_axioms",
wenzelm@33246
   797
              "type " ^ Syntax.string_of_typ_global thy T ^ " is not a variable"))
wenzelm@33246
   798
        (* obtain axioms for all superclasses *)
wenzelm@33246
   799
        val superclasses = sort @ maps (Sign.super_classes thy) sort
wenzelm@33246
   800
        (* merely an optimization, because 'collect_this_axiom' disallows *)
wenzelm@33246
   801
        (* duplicate axioms anyway:                                       *)
wenzelm@33246
   802
        val superclasses = distinct (op =) superclasses
wenzelm@33246
   803
        val class_axioms = maps (fn class => map (fn ax =>
wenzelm@33246
   804
          ("<" ^ class ^ ">", Thm.prop_of ax))
wenzelm@33246
   805
          (#axioms (AxClass.get_info thy class) handle ERROR _ => []))
wenzelm@33246
   806
          superclasses
wenzelm@33246
   807
        (* replace the (at most one) schematic type variable in each axiom *)
wenzelm@33246
   808
        (* by the actual type 'T'                                          *)
wenzelm@33246
   809
        val monomorphic_class_axioms = map (fn (axname, ax) =>
wenzelm@33246
   810
          (case Term.add_tvars ax [] of
wenzelm@33246
   811
            [] => (axname, ax)
wenzelm@33246
   812
          | [(idx, S)] => (axname, monomorphic_term (Vartab.make [(idx, (S, T))]) ax)
wenzelm@33246
   813
          | _ =>
wenzelm@33246
   814
            raise REFUTE ("collect_axioms", "class axiom " ^ axname ^ " (" ^
wenzelm@33246
   815
              Syntax.string_of_term_global thy ax ^
wenzelm@33246
   816
              ") contains more than one type variable")))
wenzelm@33246
   817
          class_axioms
wenzelm@33246
   818
      in
wenzelm@33246
   819
        fold collect_this_axiom monomorphic_class_axioms axs
wenzelm@33246
   820
      end
wenzelm@33246
   821
    and collect_type_axioms T axs =
wenzelm@22567
   822
      case T of
wenzelm@22567
   823
      (* simple types *)
wenzelm@33246
   824
        Type ("prop", []) => axs
wenzelm@33246
   825
      | Type ("fun", [T1, T2]) => collect_type_axioms T2 (collect_type_axioms T1 axs)
wenzelm@22567
   826
      (* axiomatic type classes *)
wenzelm@33246
   827
      | Type ("itself", [T1]) => collect_type_axioms T1 axs
wenzelm@33246
   828
      | Type (s, Ts) =>
haftmann@31784
   829
        (case Datatype.get_info thy s of
wenzelm@22567
   830
          SOME info =>  (* inductive datatype *)
wenzelm@22567
   831
            (* only collect relevant type axioms for the argument types *)
wenzelm@33246
   832
            fold collect_type_axioms Ts axs
wenzelm@22567
   833
        | NONE =>
wenzelm@22567
   834
          (case get_typedef thy T of
wenzelm@22567
   835
            SOME (axname, ax) =>
wenzelm@22567
   836
            collect_this_axiom (axname, ax) axs
wenzelm@22567
   837
          | NONE =>
wenzelm@22567
   838
            (* unspecified type, perhaps introduced with "typedecl" *)
wenzelm@22567
   839
            (* at least collect relevant type axioms for the argument types *)
wenzelm@33246
   840
            fold collect_type_axioms Ts axs))
wenzelm@22567
   841
      (* axiomatic type classes *)
wenzelm@33246
   842
      | TFree _ => collect_sort_axioms T axs
wenzelm@33246
   843
      (* axiomatic type classes *)
wenzelm@33246
   844
      | TVar _ => collect_sort_axioms T axs
wenzelm@33246
   845
    and collect_term_axioms t axs =
wenzelm@22567
   846
      case t of
wenzelm@22567
   847
      (* Pure *)
blanchet@29802
   848
        Const (@{const_name all}, _) => axs
blanchet@29802
   849
      | Const (@{const_name "=="}, _) => axs
blanchet@29802
   850
      | Const (@{const_name "==>"}, _) => axs
wenzelm@22567
   851
      (* axiomatic type classes *)
wenzelm@33246
   852
      | Const (@{const_name TYPE}, T) => collect_type_axioms T axs
wenzelm@22567
   853
      (* HOL *)
blanchet@29802
   854
      | Const (@{const_name Trueprop}, _) => axs
blanchet@29802
   855
      | Const (@{const_name Not}, _) => axs
wenzelm@22567
   856
      (* redundant, since 'True' is also an IDT constructor *)
blanchet@29802
   857
      | Const (@{const_name True}, _) => axs
wenzelm@22567
   858
      (* redundant, since 'False' is also an IDT constructor *)
blanchet@29802
   859
      | Const (@{const_name False}, _) => axs
wenzelm@33246
   860
      | Const (@{const_name undefined}, T) => collect_type_axioms T axs
blanchet@29802
   861
      | Const (@{const_name The}, T) =>
wenzelm@22567
   862
        let
blanchet@29802
   863
          val ax = specialize_type thy (@{const_name The}, T)
wenzelm@29288
   864
            (the (AList.lookup (op =) axioms "HOL.the_eq_trivial"))
wenzelm@22567
   865
        in
wenzelm@22567
   866
          collect_this_axiom ("HOL.the_eq_trivial", ax) axs
wenzelm@22567
   867
        end
blanchet@29820
   868
      | Const (@{const_name Hilbert_Choice.Eps}, T) =>
wenzelm@22567
   869
        let
blanchet@29820
   870
          val ax = specialize_type thy (@{const_name Hilbert_Choice.Eps}, T)
wenzelm@29288
   871
            (the (AList.lookup (op =) axioms "Hilbert_Choice.someI"))
wenzelm@22567
   872
        in
wenzelm@22567
   873
          collect_this_axiom ("Hilbert_Choice.someI", ax) axs
wenzelm@22567
   874
        end
wenzelm@33246
   875
      | Const (@{const_name All}, T) => collect_type_axioms T axs
wenzelm@33246
   876
      | Const (@{const_name Ex}, T) => collect_type_axioms T axs
wenzelm@33246
   877
      | Const (@{const_name "op ="}, T) => collect_type_axioms T axs
blanchet@29802
   878
      | Const (@{const_name "op &"}, _) => axs
blanchet@29802
   879
      | Const (@{const_name "op |"}, _) => axs
blanchet@29802
   880
      | Const (@{const_name "op -->"}, _) => axs
wenzelm@22567
   881
      (* sets *)
wenzelm@33246
   882
      | Const (@{const_name Collect}, T) => collect_type_axioms T axs
wenzelm@33246
   883
      | Const (@{const_name "op :"}, T) => collect_type_axioms T axs
wenzelm@22567
   884
      (* other optimizations *)
wenzelm@33246
   885
      | Const (@{const_name Finite_Set.card}, T) => collect_type_axioms T axs
blanchet@29820
   886
      | Const (@{const_name Finite_Set.finite}, T) =>
wenzelm@33246
   887
        collect_type_axioms T axs
haftmann@35092
   888
      | Const (@{const_name Orderings.less}, T as Type ("fun", [Type ("nat", []),
wenzelm@22567
   889
        Type ("fun", [Type ("nat", []), Type ("bool", [])])])) =>
wenzelm@33246
   890
          collect_type_axioms T axs
haftmann@35267
   891
      | Const (@{const_name Groups.plus}, T as Type ("fun", [Type ("nat", []),
wenzelm@22567
   892
        Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
wenzelm@33246
   893
          collect_type_axioms T axs
haftmann@35267
   894
      | Const (@{const_name Groups.minus}, T as Type ("fun", [Type ("nat", []),
wenzelm@22567
   895
        Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
wenzelm@33246
   896
          collect_type_axioms T axs
haftmann@35267
   897
      | Const (@{const_name Groups.times}, T as Type ("fun", [Type ("nat", []),
wenzelm@22567
   898
        Type ("fun", [Type ("nat", []), Type ("nat", [])])])) =>
wenzelm@33246
   899
          collect_type_axioms T axs
wenzelm@33246
   900
      | Const (@{const_name List.append}, T) => collect_type_axioms T axs
blanchet@36130
   901
(* UNSOUND
wenzelm@33246
   902
      | Const (@{const_name lfp}, T) => collect_type_axioms T axs
wenzelm@33246
   903
      | Const (@{const_name gfp}, T) => collect_type_axioms T axs
blanchet@36130
   904
*)
wenzelm@33246
   905
      | Const (@{const_name fst}, T) => collect_type_axioms T axs
wenzelm@33246
   906
      | Const (@{const_name snd}, T) => collect_type_axioms T axs
wenzelm@22567
   907
      (* simply-typed lambda calculus *)
blanchet@29802
   908
      | Const (s, T) =>
wenzelm@22567
   909
          if is_const_of_class thy (s, T) then
wenzelm@22567
   910
            (* axiomatic type classes: add "OFCLASS(?'a::c, c_class)" *)
wenzelm@22567
   911
            (* and the class definition                               *)
wenzelm@22567
   912
            let
wenzelm@33246
   913
              val class = Logic.class_of_const s
wenzelm@31943
   914
              val of_class = Logic.mk_of_class (TVar (("'a", 0), [class]), class)
wenzelm@33246
   915
              val ax_in = SOME (specialize_type thy (s, T) of_class)
wenzelm@22567
   916
                (* type match may fail due to sort constraints *)
wenzelm@22567
   917
                handle Type.TYPE_MATCH => NONE
wenzelm@33246
   918
              val ax_1 = Option.map (fn ax => (Syntax.string_of_term_global thy ax, ax)) ax_in
wenzelm@33246
   919
              val ax_2 = Option.map (apsnd (specialize_type thy (s, T))) (get_classdef thy class)
wenzelm@22567
   920
            in
wenzelm@33246
   921
              collect_type_axioms T (fold collect_this_axiom (map_filter I [ax_1, ax_2]) axs)
wenzelm@22567
   922
            end
wenzelm@22567
   923
          else if is_IDT_constructor thy (s, T)
wenzelm@22567
   924
            orelse is_IDT_recursor thy (s, T) then
wenzelm@22567
   925
            (* only collect relevant type axioms *)
wenzelm@33246
   926
            collect_type_axioms T axs
wenzelm@22567
   927
          else
wenzelm@22567
   928
            (* other constants should have been unfolded, with some *)
wenzelm@22567
   929
            (* exceptions: e.g. Abs_xxx/Rep_xxx functions for       *)
wenzelm@22567
   930
            (* typedefs, or type-class related constants            *)
wenzelm@22567
   931
            (* only collect relevant type axioms *)
wenzelm@33246
   932
            collect_type_axioms T axs
wenzelm@33246
   933
      | Free (_, T) => collect_type_axioms T axs
wenzelm@33246
   934
      | Var (_, T) => collect_type_axioms T axs
wenzelm@33246
   935
      | Bound _ => axs
wenzelm@33246
   936
      | Abs (_, T, body) => collect_term_axioms body (collect_type_axioms T axs)
wenzelm@33246
   937
      | t1 $ t2 => collect_term_axioms t2 (collect_term_axioms t1 axs)
wenzelm@33246
   938
    val result = map close_form (collect_term_axioms t [])
wenzelm@32950
   939
    val _ = tracing " ...done."
wenzelm@22567
   940
  in
wenzelm@22567
   941
    result
wenzelm@22567
   942
  end;
webertj@14456
   943
webertj@14456
   944
(* ------------------------------------------------------------------------- *)
webertj@14807
   945
(* ground_types: collects all ground types in a term (including argument     *)
webertj@14807
   946
(*               types of other types), suppressing duplicates.  Does not    *)
webertj@14807
   947
(*               return function types, set types, non-recursive IDTs, or    *)
webertj@14807
   948
(*               'propT'.  For IDTs, also the argument types of constructors *)
webertj@25014
   949
(*               and all mutually recursive IDTs are considered.             *)
webertj@14807
   950
(* ------------------------------------------------------------------------- *)
webertj@14807
   951
wenzelm@22567
   952
  fun ground_types thy t =
wenzelm@22567
   953
  let
wenzelm@29272
   954
    fun collect_types T acc =
webertj@25014
   955
      (case T of
wenzelm@29272
   956
        Type ("fun", [T1, T2]) => collect_types T1 (collect_types T2 acc)
webertj@25014
   957
      | Type ("prop", [])      => acc
webertj@25014
   958
      | Type (s, Ts)           =>
haftmann@31784
   959
        (case Datatype.get_info thy s of
webertj@25014
   960
          SOME info =>  (* inductive datatype *)
webertj@25014
   961
          let
webertj@25014
   962
            val index        = #index info
webertj@25014
   963
            val descr        = #descr info
wenzelm@29288
   964
            val (_, typs, _) = the (AList.lookup (op =) descr index)
webertj@25014
   965
            val typ_assoc    = typs ~~ Ts
webertj@25014
   966
            (* sanity check: every element in 'dtyps' must be a *)
webertj@25014
   967
            (* 'DtTFree'                                        *)
webertj@25014
   968
            val _ = if Library.exists (fn d =>
haftmann@33968
   969
              case d of Datatype_Aux.DtTFree _ => false | _ => true) typs then
webertj@25014
   970
              raise REFUTE ("ground_types", "datatype argument (for type "
wenzelm@26939
   971
                ^ Syntax.string_of_typ_global thy T ^ ") is not a variable")
webertj@25014
   972
            else ()
webertj@25014
   973
            (* required for mutually recursive datatypes; those need to   *)
webertj@25014
   974
            (* be added even if they are an instance of an otherwise non- *)
webertj@25014
   975
            (* recursive datatype                                         *)
wenzelm@33339
   976
            fun collect_dtyp d acc =
wenzelm@22567
   977
            let
webertj@25014
   978
              val dT = typ_of_dtyp descr typ_assoc d
webertj@25014
   979
            in
webertj@25014
   980
              case d of
haftmann@33968
   981
                Datatype_Aux.DtTFree _ =>
wenzelm@29272
   982
                collect_types dT acc
haftmann@33968
   983
              | Datatype_Aux.DtType (_, ds) =>
wenzelm@33339
   984
                collect_types dT (fold_rev collect_dtyp ds acc)
haftmann@33968
   985
              | Datatype_Aux.DtRec i =>
webertj@25014
   986
                if dT mem acc then
webertj@25014
   987
                  acc  (* prevent infinite recursion *)
wenzelm@22567
   988
                else
webertj@25014
   989
                  let
wenzelm@29288
   990
                    val (_, dtyps, dconstrs) = the (AList.lookup (op =) descr i)
webertj@25014
   991
                    (* if the current type is a recursive IDT (i.e. a depth *)
webertj@25014
   992
                    (* is required), add it to 'acc'                        *)
webertj@25014
   993
                    val acc_dT = if Library.exists (fn (_, ds) =>
haftmann@33968
   994
                      Library.exists Datatype_Aux.is_rec_type ds) dconstrs then
webertj@25014
   995
                        insert (op =) dT acc
webertj@25014
   996
                      else acc
webertj@25014
   997
                    (* collect argument types *)
wenzelm@33339
   998
                    val acc_dtyps = fold_rev collect_dtyp dtyps acc_dT
webertj@25014
   999
                    (* collect constructor types *)
wenzelm@33339
  1000
                    val acc_dconstrs = fold_rev collect_dtyp (maps snd dconstrs) acc_dtyps
webertj@25014
  1001
                  in
webertj@25014
  1002
                    acc_dconstrs
webertj@25014
  1003
                  end
wenzelm@22567
  1004
            end
webertj@25014
  1005
          in
webertj@25014
  1006
            (* argument types 'Ts' could be added here, but they are also *)
webertj@25014
  1007
            (* added by 'collect_dtyp' automatically                      *)
haftmann@33968
  1008
            collect_dtyp (Datatype_Aux.DtRec index) acc
webertj@25014
  1009
          end
webertj@25014
  1010
        | NONE =>
webertj@25014
  1011
          (* not an inductive datatype, e.g. defined via "typedef" or *)
webertj@25014
  1012
          (* "typedecl"                                               *)
wenzelm@29272
  1013
          insert (op =) T (fold collect_types Ts acc))
webertj@25014
  1014
      | TFree _                => insert (op =) T acc
webertj@25014
  1015
      | TVar _                 => insert (op =) T acc)
wenzelm@22567
  1016
  in
wenzelm@29272
  1017
    fold_types collect_types t []
wenzelm@22567
  1018
  end;
webertj@14807
  1019
webertj@14807
  1020
(* ------------------------------------------------------------------------- *)
webertj@14807
  1021
(* string_of_typ: (rather naive) conversion from types to strings, used to   *)
webertj@14807
  1022
(*                look up the size of a type in 'sizes'.  Parameterized      *)
webertj@14807
  1023
(*                types with different parameters (e.g. "'a list" vs. "bool  *)
webertj@14807
  1024
(*                list") are identified.                                     *)
webertj@14807
  1025
(* ------------------------------------------------------------------------- *)
webertj@14807
  1026
wenzelm@22567
  1027
  (* Term.typ -> string *)
webertj@14807
  1028
wenzelm@22567
  1029
  fun string_of_typ (Type (s, _))     = s
wenzelm@22567
  1030
    | string_of_typ (TFree (s, _))    = s
wenzelm@22567
  1031
    | string_of_typ (TVar ((s,_), _)) = s;
webertj@14807
  1032
webertj@14807
  1033
(* ------------------------------------------------------------------------- *)
webertj@14807
  1034
(* first_universe: returns the "first" (i.e. smallest) universe by assigning *)
webertj@14807
  1035
(*                 'minsize' to every type for which no size is specified in *)
webertj@14807
  1036
(*                 'sizes'                                                   *)
webertj@14807
  1037
(* ------------------------------------------------------------------------- *)
webertj@14807
  1038
wenzelm@22567
  1039
  (* Term.typ list -> (string * int) list -> int -> (Term.typ * int) list *)
webertj@14807
  1040
wenzelm@22567
  1041
  fun first_universe xs sizes minsize =
wenzelm@22567
  1042
  let
wenzelm@22567
  1043
    fun size_of_typ T =
wenzelm@22567
  1044
      case AList.lookup (op =) sizes (string_of_typ T) of
wenzelm@22567
  1045
        SOME n => n
wenzelm@33246
  1046
      | NONE => minsize
wenzelm@22567
  1047
  in
wenzelm@22567
  1048
    map (fn T => (T, size_of_typ T)) xs
wenzelm@22567
  1049
  end;
webertj@14807
  1050
webertj@14807
  1051
(* ------------------------------------------------------------------------- *)
webertj@14807
  1052
(* next_universe: enumerates all universes (i.e. assignments of sizes to     *)
webertj@14807
  1053
(*                types), where the minimal size of a type is given by       *)
webertj@14807
  1054
(*                'minsize', the maximal size is given by 'maxsize', and a   *)
webertj@14807
  1055
(*                type may have a fixed size given in 'sizes'                *)
webertj@14456
  1056
(* ------------------------------------------------------------------------- *)
webertj@14456
  1057
wenzelm@22567
  1058
  (* (Term.typ * int) list -> (string * int) list -> int -> int ->
wenzelm@22567
  1059
    (Term.typ * int) list option *)
webertj@14456
  1060
wenzelm@22567
  1061
  fun next_universe xs sizes minsize maxsize =
wenzelm@22567
  1062
  let
wenzelm@22567
  1063
    (* creates the "first" list of length 'len', where the sum of all list *)
wenzelm@22567
  1064
    (* elements is 'sum', and the length of the list is 'len'              *)
wenzelm@22567
  1065
    (* int -> int -> int -> int list option *)
wenzelm@22567
  1066
    fun make_first _ 0 sum =
wenzelm@22567
  1067
      if sum=0 then
wenzelm@22567
  1068
        SOME []
wenzelm@22567
  1069
      else
wenzelm@22567
  1070
        NONE
wenzelm@22567
  1071
      | make_first max len sum =
wenzelm@22567
  1072
      if sum<=max orelse max<0 then
wenzelm@22567
  1073
        Option.map (fn xs' => sum :: xs') (make_first max (len-1) 0)
wenzelm@22567
  1074
      else
wenzelm@22567
  1075
        Option.map (fn xs' => max :: xs') (make_first max (len-1) (sum-max))
wenzelm@22567
  1076
    (* enumerates all int lists with a fixed length, where 0<=x<='max' for *)
wenzelm@22567
  1077
    (* all list elements x (unless 'max'<0)                                *)
wenzelm@22567
  1078
    (* int -> int -> int -> int list -> int list option *)
wenzelm@22567
  1079
    fun next max len sum [] =
wenzelm@22567
  1080
      NONE
wenzelm@22567
  1081
      | next max len sum [x] =
wenzelm@22567
  1082
      (* we've reached the last list element, so there's no shift possible *)
wenzelm@22567
  1083
      make_first max (len+1) (sum+x+1)  (* increment 'sum' by 1 *)
wenzelm@22567
  1084
      | next max len sum (x1::x2::xs) =
wenzelm@22567
  1085
      if x1>0 andalso (x2<max orelse max<0) then
wenzelm@22567
  1086
        (* we can shift *)
wenzelm@33035
  1087
        SOME (the (make_first max (len+1) (sum+x1-1)) @ (x2+1) :: xs)
wenzelm@22567
  1088
      else
wenzelm@22567
  1089
        (* continue search *)
wenzelm@22567
  1090
        next max (len+1) (sum+x1) (x2::xs)
wenzelm@22567
  1091
    (* only consider those types for which the size is not fixed *)
wenzelm@33317
  1092
    val mutables = filter_out (AList.defined (op =) sizes o string_of_typ o fst) xs
wenzelm@22567
  1093
    (* subtract 'minsize' from every size (will be added again at the end) *)
wenzelm@22567
  1094
    val diffs = map (fn (_, n) => n-minsize) mutables
wenzelm@22567
  1095
  in
wenzelm@22567
  1096
    case next (maxsize-minsize) 0 0 diffs of
wenzelm@22567
  1097
      SOME diffs' =>
wenzelm@22567
  1098
      (* merge with those types for which the size is fixed *)
wenzelm@33246
  1099
      SOME (fst (fold_map (fn (T, _) => fn ds =>
wenzelm@22567
  1100
        case AList.lookup (op =) sizes (string_of_typ T) of
wenzelm@22567
  1101
        (* return the fixed size *)
wenzelm@33246
  1102
          SOME n => ((T, n), ds)
wenzelm@22567
  1103
        (* consume the head of 'ds', add 'minsize' *)
wenzelm@33246
  1104
        | NONE   => ((T, minsize + hd ds), tl ds))
wenzelm@33246
  1105
        xs diffs'))
wenzelm@22567
  1106
    | NONE =>
wenzelm@22567
  1107
      NONE
wenzelm@22567
  1108
  end;
webertj@14807
  1109
webertj@14807
  1110
(* ------------------------------------------------------------------------- *)
webertj@14807
  1111
(* toTrue: converts the interpretation of a Boolean value to a propositional *)
webertj@14807
  1112
(*         formula that is true iff the interpretation denotes "true"        *)
webertj@14807
  1113
(* ------------------------------------------------------------------------- *)
webertj@14807
  1114
wenzelm@22567
  1115
  (* interpretation -> prop_formula *)
webertj@14807
  1116
wenzelm@22567
  1117
  fun toTrue (Leaf [fm, _]) =
wenzelm@22567
  1118
    fm
wenzelm@22567
  1119
    | toTrue _              =
wenzelm@22567
  1120
    raise REFUTE ("toTrue", "interpretation does not denote a Boolean value");
webertj@14807
  1121
webertj@14807
  1122
(* ------------------------------------------------------------------------- *)
webertj@14807
  1123
(* toFalse: converts the interpretation of a Boolean value to a              *)
webertj@14807
  1124
(*          propositional formula that is true iff the interpretation        *)
webertj@14807
  1125
(*          denotes "false"                                                  *)
webertj@14807
  1126
(* ------------------------------------------------------------------------- *)
webertj@14807
  1127
wenzelm@22567
  1128
  (* interpretation -> prop_formula *)
webertj@14807
  1129
wenzelm@22567
  1130
  fun toFalse (Leaf [_, fm]) =
wenzelm@22567
  1131
    fm
wenzelm@22567
  1132
    | toFalse _              =
wenzelm@22567
  1133
    raise REFUTE ("toFalse", "interpretation does not denote a Boolean value");
webertj@14807
  1134
webertj@14807
  1135
(* ------------------------------------------------------------------------- *)
webertj@14807
  1136
(* find_model: repeatedly calls 'interpret' with appropriate parameters,     *)
webertj@14807
  1137
(*             applies a SAT solver, and (in case a model is found) displays *)
webertj@14807
  1138
(*             the model to the user by calling 'print_model'                *)
webertj@14807
  1139
(* thy       : the current theory                                            *)
webertj@14807
  1140
(* {...}     : parameters that control the translation/model generation      *)
blanchet@34120
  1141
(* assm_ts   : assumptions to be considered unless "no_assms" is specified   *)
webertj@14807
  1142
(* t         : term to be translated into a propositional formula            *)
webertj@14807
  1143
(* negate    : if true, find a model that makes 't' false (rather than true) *)
webertj@14807
  1144
(* ------------------------------------------------------------------------- *)
webertj@14807
  1145
wenzelm@22567
  1146
  (* theory -> params -> Term.term -> bool -> unit *)
webertj@14807
  1147
blanchet@30314
  1148
  fun find_model thy {sizes, minsize, maxsize, maxvars, maxtime, satsolver,
blanchet@34120
  1149
    no_assms, expect} assm_ts t negate =
wenzelm@22567
  1150
  let
blanchet@33054
  1151
    (* string -> unit *)
blanchet@33054
  1152
    fun check_expect outcome_code =
blanchet@33054
  1153
      if expect = "" orelse outcome_code = expect then ()
blanchet@33054
  1154
      else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
wenzelm@22567
  1155
    (* unit -> unit *)
wenzelm@22567
  1156
    fun wrapper () =
wenzelm@22567
  1157
    let
blanchet@30349
  1158
      val timer  = Timer.startRealTimer ()
blanchet@34120
  1159
      val t = if no_assms then t
blanchet@34120
  1160
              else if negate then Logic.list_implies (assm_ts, t)
blanchet@34120
  1161
              else Logic.mk_conjunction_list (t :: assm_ts)
wenzelm@22567
  1162
      val u      = unfold_defs thy t
wenzelm@32950
  1163
      val _      = tracing ("Unfolded term: " ^ Syntax.string_of_term_global thy u)
wenzelm@22567
  1164
      val axioms = collect_axioms thy u
wenzelm@22567
  1165
      (* Term.typ list *)
wenzelm@33246
  1166
      val types = fold (union (op =) o ground_types thy) (u :: axioms) []
wenzelm@32950
  1167
      val _     = tracing ("Ground types: "
wenzelm@22567
  1168
        ^ (if null types then "none."
wenzelm@26939
  1169
           else commas (map (Syntax.string_of_typ_global thy) types)))
wenzelm@22567
  1170
      (* we can only consider fragments of recursive IDTs, so we issue a  *)
wenzelm@22567
  1171
      (* warning if the formula contains a recursive IDT                  *)
wenzelm@22567
  1172
      (* TODO: no warning needed for /positive/ occurrences of IDTs       *)
blanchet@30314
  1173
      val maybe_spurious = Library.exists (fn
wenzelm@22567
  1174
          Type (s, _) =>
haftmann@31784
  1175
          (case Datatype.get_info thy s of
wenzelm@22567
  1176
            SOME info =>  (* inductive datatype *)
wenzelm@22567
  1177
            let
wenzelm@22567
  1178
              val index           = #index info
wenzelm@22567
  1179
              val descr           = #descr info
wenzelm@29288
  1180
              val (_, _, constrs) = the (AList.lookup (op =) descr index)
wenzelm@22567
  1181
            in
wenzelm@22567
  1182
              (* recursive datatype? *)
wenzelm@22567
  1183
              Library.exists (fn (_, ds) =>
haftmann@33968
  1184
                Library.exists Datatype_Aux.is_rec_type ds) constrs
wenzelm@22567
  1185
            end
wenzelm@22567
  1186
          | NONE => false)
blanchet@30314
  1187
        | _ => false) types
blanchet@30314
  1188
      val _ = if maybe_spurious then
wenzelm@22567
  1189
          warning ("Term contains a recursive datatype; "
wenzelm@22567
  1190
            ^ "countermodel(s) may be spurious!")
wenzelm@22567
  1191
        else
wenzelm@22567
  1192
          ()
blanchet@30314
  1193
      (* (Term.typ * int) list -> string *)
wenzelm@22567
  1194
      fun find_model_loop universe =
wenzelm@22567
  1195
      let
blanchet@30349
  1196
        val msecs_spent = Time.toMilliseconds (Timer.checkRealTimer timer)
blanchet@30349
  1197
        val _ = maxtime = 0 orelse msecs_spent < 1000 * maxtime
blanchet@30349
  1198
                orelse raise TimeLimit.TimeOut
wenzelm@22567
  1199
        val init_model = (universe, [])
wenzelm@22567
  1200
        val init_args  = {maxvars = maxvars, def_eq = false, next_idx = 1,
wenzelm@22567
  1201
          bounds = [], wellformed = True}
wenzelm@32950
  1202
        val _ = tracing ("Translating term (sizes: "
wenzelm@22567
  1203
          ^ commas (map (fn (_, n) => string_of_int n) universe) ^ ") ...")
wenzelm@22567
  1204
        (* translate 'u' and all axioms *)
wenzelm@33246
  1205
        val (intrs, (model, args)) = fold_map (fn t' => fn (m, a) =>
wenzelm@22567
  1206
          let
wenzelm@22567
  1207
            val (i, m', a') = interpret thy m a t'
wenzelm@22567
  1208
          in
wenzelm@22567
  1209
            (* set 'def_eq' to 'true' *)
wenzelm@33246
  1210
            (i, (m', {maxvars = #maxvars a', def_eq = true,
wenzelm@22567
  1211
              next_idx = #next_idx a', bounds = #bounds a',
wenzelm@33246
  1212
              wellformed = #wellformed a'}))
wenzelm@33246
  1213
          end) (u :: axioms) (init_model, init_args)
wenzelm@22567
  1214
        (* make 'u' either true or false, and make all axioms true, and *)
wenzelm@22567
  1215
        (* add the well-formedness side condition                       *)
wenzelm@22567
  1216
        val fm_u  = (if negate then toFalse else toTrue) (hd intrs)
wenzelm@22567
  1217
        val fm_ax = PropLogic.all (map toTrue (tl intrs))
wenzelm@22567
  1218
        val fm    = PropLogic.all [#wellformed args, fm_ax, fm_u]
blanchet@34017
  1219
        val solver =
blanchet@34017
  1220
          SatSolver.invoke_solver satsolver
blanchet@34017
  1221
          handle Option.Option =>
blanchet@34017
  1222
                 error ("Unknown SAT solver: " ^ quote satsolver ^
blanchet@34017
  1223
                        ". Available solvers: " ^
blanchet@34017
  1224
                        commas (map (quote o fst) (!SatSolver.solvers)) ^ ".")
wenzelm@22567
  1225
      in
wenzelm@32950
  1226
        priority "Invoking SAT solver...";
blanchet@34017
  1227
        (case solver fm of
wenzelm@22567
  1228
          SatSolver.SATISFIABLE assignment =>
wenzelm@32950
  1229
          (priority ("*** Model found: ***\n" ^ print_model thy model
blanchet@30314
  1230
            (fn i => case assignment i of SOME b => b | NONE => true));
blanchet@30347
  1231
           if maybe_spurious then "potential" else "genuine")
wenzelm@22567
  1232
        | SatSolver.UNSATISFIABLE _ =>
wenzelm@32950
  1233
          (priority "No model exists.";
wenzelm@22567
  1234
          case next_universe universe sizes minsize maxsize of
wenzelm@22567
  1235
            SOME universe' => find_model_loop universe'
wenzelm@32950
  1236
          | NONE           => (priority
blanchet@30314
  1237
            "Search terminated, no larger universe within the given limits.";
blanchet@30314
  1238
            "none"))
wenzelm@22567
  1239
        | SatSolver.UNKNOWN =>
wenzelm@32950
  1240
          (priority "No model found.";
wenzelm@22567
  1241
          case next_universe universe sizes minsize maxsize of
wenzelm@22567
  1242
            SOME universe' => find_model_loop universe'
wenzelm@32950
  1243
          | NONE           => (priority
blanchet@30314
  1244
            "Search terminated, no larger universe within the given limits.";
blanchet@30314
  1245
            "unknown"))
wenzelm@22567
  1246
        ) handle SatSolver.NOT_CONFIGURED =>
blanchet@30314
  1247
          (error ("SAT solver " ^ quote satsolver ^ " is not configured.");
blanchet@30314
  1248
           "unknown")
wenzelm@22567
  1249
      end handle MAXVARS_EXCEEDED =>
wenzelm@32950
  1250
        (priority ("Search terminated, number of Boolean variables ("
blanchet@30314
  1251
          ^ string_of_int maxvars ^ " allowed) exceeded.");
blanchet@30314
  1252
          "unknown")
blanchet@30314
  1253
        val outcome_code = find_model_loop (first_universe types sizes minsize)
wenzelm@22567
  1254
      in
blanchet@33054
  1255
        check_expect outcome_code
wenzelm@22567
  1256
      end
wenzelm@22567
  1257
    in
wenzelm@22567
  1258
      (* some parameter sanity checks *)
wenzelm@22567
  1259
      minsize>=1 orelse
wenzelm@22567
  1260
        error ("\"minsize\" is " ^ string_of_int minsize ^ ", must be at least 1");
wenzelm@22567
  1261
      maxsize>=1 orelse
wenzelm@22567
  1262
        error ("\"maxsize\" is " ^ string_of_int maxsize ^ ", must be at least 1");
wenzelm@22567
  1263
      maxsize>=minsize orelse
wenzelm@22567
  1264
        error ("\"maxsize\" (=" ^ string_of_int maxsize ^
wenzelm@22567
  1265
        ") is less than \"minsize\" (=" ^ string_of_int minsize ^ ").");
wenzelm@22567
  1266
      maxvars>=0 orelse
wenzelm@22567
  1267
        error ("\"maxvars\" is " ^ string_of_int maxvars ^ ", must be at least 0");
wenzelm@22567
  1268
      maxtime>=0 orelse
wenzelm@22567
  1269
        error ("\"maxtime\" is " ^ string_of_int maxtime ^ ", must be at least 0");
wenzelm@22567
  1270
      (* enter loop with or without time limit *)
wenzelm@32950
  1271
      priority ("Trying to find a model that "
wenzelm@22567
  1272
        ^ (if negate then "refutes" else "satisfies") ^ ": "
wenzelm@26939
  1273
        ^ Syntax.string_of_term_global thy t);
wenzelm@22567
  1274
      if maxtime>0 then (
wenzelm@24688
  1275
        TimeLimit.timeLimit (Time.fromSeconds maxtime)
wenzelm@22567
  1276
          wrapper ()
wenzelm@24688
  1277
        handle TimeLimit.TimeOut =>
blanchet@33054
  1278
          (priority ("Search terminated, time limit (" ^
blanchet@33054
  1279
              string_of_int maxtime
blanchet@33054
  1280
              ^ (if maxtime=1 then " second" else " seconds") ^ ") exceeded.");
blanchet@33054
  1281
           check_expect "unknown")
wenzelm@22567
  1282
      ) else
wenzelm@22567
  1283
        wrapper ()
wenzelm@22567
  1284
    end;
webertj@14456
  1285
webertj@14456
  1286
webertj@14456
  1287
(* ------------------------------------------------------------------------- *)
webertj@14456
  1288
(* INTERFACE, PART 2: FINDING A MODEL                                        *)
webertj@14350
  1289
(* ------------------------------------------------------------------------- *)
webertj@14350
  1290
webertj@14350
  1291
(* ------------------------------------------------------------------------- *)
webertj@14456
  1292
(* satisfy_term: calls 'find_model' to find a model that satisfies 't'       *)
webertj@14456
  1293
(* params      : list of '(name, value)' pairs used to override default      *)
webertj@14456
  1294
(*               parameters                                                  *)
webertj@14350
  1295
(* ------------------------------------------------------------------------- *)
webertj@14350
  1296
blanchet@34120
  1297
  (* theory -> (string * string) list -> Term.term list -> Term.term -> unit *)
webertj@14350
  1298
blanchet@34120
  1299
  fun satisfy_term thy params assm_ts t =
blanchet@34120
  1300
    find_model thy (actual_params thy params) assm_ts t false;
webertj@14350
  1301
webertj@14350
  1302
(* ------------------------------------------------------------------------- *)
webertj@14456
  1303
(* refute_term: calls 'find_model' to find a model that refutes 't'          *)
webertj@14456
  1304
(* params     : list of '(name, value)' pairs used to override default       *)
webertj@14456
  1305
(*              parameters                                                   *)
webertj@14350
  1306
(* ------------------------------------------------------------------------- *)
webertj@14350
  1307
blanchet@34120
  1308
  (* theory -> (string * string) list -> Term.term list -> Term.term -> unit *)
webertj@14350
  1309
blanchet@34120
  1310
  fun refute_term thy params assm_ts t =
wenzelm@22567
  1311
  let
wenzelm@22567
  1312
    (* disallow schematic type variables, since we cannot properly negate  *)
wenzelm@22567
  1313
    (* terms containing them (their logical meaning is that there EXISTS a *)
wenzelm@22567
  1314
    (* type s.t. ...; to refute such a formula, we would have to show that *)
wenzelm@22567
  1315
    (* for ALL types, not ...)                                             *)
wenzelm@29272
  1316
    val _ = null (Term.add_tvars t []) orelse
wenzelm@22567
  1317
      error "Term to be refuted contains schematic type variables"
webertj@21556
  1318
wenzelm@22567
  1319
    (* existential closure over schematic variables *)
wenzelm@22567
  1320
    (* (Term.indexname * Term.typ) list *)
wenzelm@29265
  1321
    val vars = sort_wrt (fst o fst) (map dest_Var (OldTerm.term_vars t))
wenzelm@22567
  1322
    (* Term.term *)
wenzelm@33246
  1323
    val ex_closure = fold (fn ((x, i), T) => fn t' =>
wenzelm@33246
  1324
      HOLogic.exists_const T $
wenzelm@33246
  1325
        Abs (x, T, abstract_over (Var ((x, i), T), t'))) vars t
wenzelm@22567
  1326
    (* Note: If 't' is of type 'propT' (rather than 'boolT'), applying   *)
wenzelm@22567
  1327
    (* 'HOLogic.exists_const' is not type-correct.  However, this is not *)
wenzelm@22567
  1328
    (* really a problem as long as 'find_model' still interprets the     *)
wenzelm@22567
  1329
    (* resulting term correctly, without checking its type.              *)
webertj@21556
  1330
wenzelm@22567
  1331
    (* replace outermost universally quantified variables by Free's:     *)
wenzelm@22567
  1332
    (* refuting a term with Free's is generally faster than refuting a   *)
wenzelm@22567
  1333
    (* term with (nested) quantifiers, because quantifiers are expanded, *)
wenzelm@22567
  1334
    (* while the SAT solver searches for an interpretation for Free's.   *)
wenzelm@22567
  1335
    (* Also we get more information back that way, namely an             *)
wenzelm@22567
  1336
    (* interpretation which includes values for the (formerly)           *)
wenzelm@22567
  1337
    (* quantified variables.                                             *)
wenzelm@22567
  1338
    (* maps  !!x1...xn. !xk...xm. t   to   t  *)
blanchet@29820
  1339
    fun strip_all_body (Const (@{const_name all}, _) $ Abs (_, _, t)) =
blanchet@29820
  1340
        strip_all_body t
blanchet@29820
  1341
      | strip_all_body (Const (@{const_name Trueprop}, _) $ t) =
blanchet@29820
  1342
        strip_all_body t
blanchet@29820
  1343
      | strip_all_body (Const (@{const_name All}, _) $ Abs (_, _, t)) =
blanchet@29820
  1344
        strip_all_body t
blanchet@29802
  1345
      | strip_all_body t = t
wenzelm@22567
  1346
    (* maps  !!x1...xn. !xk...xm. t   to   [x1, ..., xn, xk, ..., xm]  *)
blanchet@29802
  1347
    fun strip_all_vars (Const (@{const_name all}, _) $ Abs (a, T, t)) =
wenzelm@22567
  1348
      (a, T) :: strip_all_vars t
blanchet@29802
  1349
      | strip_all_vars (Const (@{const_name Trueprop}, _) $ t) =
wenzelm@22567
  1350
      strip_all_vars t
blanchet@29802
  1351
      | strip_all_vars (Const (@{const_name All}, _) $ Abs (a, T, t)) =
wenzelm@22567
  1352
      (a, T) :: strip_all_vars t
blanchet@29802
  1353
      | strip_all_vars t =
wenzelm@22567
  1354
      [] : (string * typ) list
wenzelm@22567
  1355
    val strip_t = strip_all_body ex_closure
wenzelm@22567
  1356
    val frees   = Term.rename_wrt_term strip_t (strip_all_vars ex_closure)
wenzelm@22567
  1357
    val subst_t = Term.subst_bounds (map Free frees, strip_t)
wenzelm@22567
  1358
  in
blanchet@34120
  1359
    find_model thy (actual_params thy params) assm_ts subst_t true
wenzelm@22567
  1360
  end;
webertj@14350
  1361
webertj@14350
  1362
(* ------------------------------------------------------------------------- *)
wenzelm@32857
  1363
(* refute_goal                                                               *)
webertj@14350
  1364
(* ------------------------------------------------------------------------- *)
webertj@14350
  1365
blanchet@34120
  1366
  fun refute_goal ctxt params th i =
blanchet@34120
  1367
  let
blanchet@34120
  1368
    val t = th |> prop_of
blanchet@34120
  1369
  in
blanchet@34120
  1370
    if Logic.count_prems t = 0 then
blanchet@34120
  1371
      priority "No subgoal!"
blanchet@34120
  1372
    else
blanchet@34120
  1373
      let
blanchet@34120
  1374
        val assms = map term_of (Assumption.all_assms_of ctxt)
blanchet@34120
  1375
        val (t, frees) = Logic.goal_params t i
blanchet@34120
  1376
      in
blanchet@34120
  1377
        refute_term (ProofContext.theory_of ctxt) params assms
blanchet@34120
  1378
        (subst_bounds (frees, t))
blanchet@34120
  1379
      end
blanchet@34120
  1380
  end
webertj@14350
  1381
webertj@14350
  1382
webertj@14350
  1383
(* ------------------------------------------------------------------------- *)
webertj@15292
  1384
(* INTERPRETERS: Auxiliary Functions                                         *)
webertj@14350
  1385
(* ------------------------------------------------------------------------- *)
webertj@14350
  1386
webertj@14350
  1387
(* ------------------------------------------------------------------------- *)
webertj@25014
  1388
(* make_constants: returns all interpretations for type 'T' that consist of  *)
webertj@25014
  1389
(*                 unit vectors with 'True'/'False' only (no Boolean         *)
webertj@25014
  1390
(*                 variables)                                                *)
webertj@14350
  1391
(* ------------------------------------------------------------------------- *)
webertj@14350
  1392
webertj@25014
  1393
  (* theory -> model -> Term.typ -> interpretation list *)
webertj@14350
  1394
webertj@25014
  1395
  fun make_constants thy model T =
wenzelm@22567
  1396
  let
wenzelm@22567
  1397
    (* returns a list with all unit vectors of length n *)
wenzelm@22567
  1398
    (* int -> interpretation list *)
wenzelm@22567
  1399
    fun unit_vectors n =
wenzelm@22567
  1400
    let
wenzelm@22567
  1401
      (* returns the k-th unit vector of length n *)
wenzelm@22567
  1402
      (* int * int -> interpretation *)
webertj@25014
  1403
      fun unit_vector (k, n) =
wenzelm@22567
  1404
        Leaf ((replicate (k-1) False) @ (True :: (replicate (n-k) False)))
webertj@25014
  1405
      (* int -> interpretation list *)
webertj@25014
  1406
      fun unit_vectors_loop k =
webertj@25014
  1407
        if k>n then [] else unit_vector (k,n) :: unit_vectors_loop (k+1)
wenzelm@22567
  1408
    in
webertj@25014
  1409
      unit_vectors_loop 1
wenzelm@22567
  1410
    end
wenzelm@22567
  1411
    (* returns a list of lists, each one consisting of n (possibly *)
wenzelm@22567
  1412
    (* identical) elements from 'xs'                               *)
wenzelm@22567
  1413
    (* int -> 'a list -> 'a list list *)
wenzelm@22567
  1414
    fun pick_all 1 xs =
wenzelm@22567
  1415
      map single xs
wenzelm@22567
  1416
      | pick_all n xs =
wenzelm@22567
  1417
      let val rec_pick = pick_all (n-1) xs in
wenzelm@32952
  1418
        maps (fn x => map (cons x) rec_pick) xs
wenzelm@22567
  1419
      end
webertj@25014
  1420
    (* returns all constant interpretations that have the same tree *)
webertj@25014
  1421
    (* structure as the interpretation argument                     *)
webertj@25014
  1422
    (* interpretation -> interpretation list *)
webertj@25014
  1423
    fun make_constants_intr (Leaf xs) = unit_vectors (length xs)
webertj@25014
  1424
      | make_constants_intr (Node xs) = map Node (pick_all (length xs)
webertj@25014
  1425
      (make_constants_intr (hd xs)))
webertj@25014
  1426
    (* obtain the interpretation for a variable of type 'T' *)
webertj@25014
  1427
    val (i, _, _) = interpret thy model {maxvars=0, def_eq=false, next_idx=1,
webertj@25014
  1428
      bounds=[], wellformed=True} (Free ("dummy", T))
wenzelm@22567
  1429
  in
webertj@25014
  1430
    make_constants_intr i
wenzelm@22567
  1431
  end;
webertj@14807
  1432
webertj@14807
  1433
(* ------------------------------------------------------------------------- *)
webertj@25014
  1434
(* power: 'power (a, b)' computes a^b, for a>=0, b>=0                        *)
webertj@25014
  1435
(* ------------------------------------------------------------------------- *)
webertj@25014
  1436
webertj@25014
  1437
  (* int * int -> int *)
webertj@25014
  1438
webertj@25014
  1439
  fun power (a, 0) = 1
webertj@25014
  1440
    | power (a, 1) = a
webertj@25014
  1441
    | power (a, b) = let val ab = power(a, b div 2) in
webertj@25014
  1442
        ab * ab * power(a, b mod 2)
webertj@25014
  1443
      end;
webertj@25014
  1444
webertj@25014
  1445
(* ------------------------------------------------------------------------- *)
webertj@25014
  1446
(* size_of_type: returns the number of elements in a type 'T' (i.e. 'length  *)
webertj@25014
  1447
(*               (make_constants T)', but implemented more efficiently)      *)
webertj@14807
  1448
(* ------------------------------------------------------------------------- *)
webertj@14807
  1449
webertj@25014
  1450
  (* theory -> model -> Term.typ -> int *)
webertj@14807
  1451
webertj@25014
  1452
  (* returns 0 for an empty ground type or a function type with empty      *)
webertj@25014
  1453
  (* codomain, but fails for a function type with empty domain --          *)
webertj@25014
  1454
  (* admissibility of datatype constructor argument types (see "Inductive  *)
webertj@25014
  1455
  (* datatypes in HOL - lessons learned ...", S. Berghofer, M. Wenzel,     *)
webertj@25014
  1456
  (* TPHOLs 99) ensures that recursive, possibly empty, datatype fragments *)
webertj@25014
  1457
  (* never occur as the domain of a function type that is the type of a    *)
webertj@25014
  1458
  (* constructor argument                                                  *)
webertj@25014
  1459
webertj@25014
  1460
  fun size_of_type thy model T =
wenzelm@22567
  1461
  let
webertj@25014
  1462
    (* returns the number of elements that have the same tree structure as a *)
webertj@25014
  1463
    (* given interpretation                                                  *)
webertj@25014
  1464
    fun size_of_intr (Leaf xs) = length xs
webertj@25014
  1465
      | size_of_intr (Node xs) = power (size_of_intr (hd xs), length xs)
webertj@25014
  1466
    (* obtain the interpretation for a variable of type 'T' *)
webertj@25014
  1467
    val (i, _, _) = interpret thy model {maxvars=0, def_eq=false, next_idx=1,
webertj@25014
  1468
      bounds=[], wellformed=True} (Free ("dummy", T))
wenzelm@22567
  1469
  in
webertj@25014
  1470
    size_of_intr i
wenzelm@22567
  1471
  end;
webertj@14807
  1472
webertj@14807
  1473
(* ------------------------------------------------------------------------- *)
webertj@14807
  1474
(* TT/FF: interpretations that denote "true" or "false", respectively        *)
webertj@14807
  1475
(* ------------------------------------------------------------------------- *)
webertj@14807
  1476
wenzelm@22567
  1477
  (* interpretation *)
webertj@14807
  1478
wenzelm@22567
  1479
  val TT = Leaf [True, False];
webertj@14807
  1480
wenzelm@22567
  1481
  val FF = Leaf [False, True];
webertj@14807
  1482
webertj@14807
  1483
(* ------------------------------------------------------------------------- *)
webertj@14807
  1484
(* make_equality: returns an interpretation that denotes (extensional)       *)
webertj@14807
  1485
(*                equality of two interpretations                            *)
webertj@15547
  1486
(* - two interpretations are 'equal' iff they are both defined and denote    *)
webertj@15547
  1487
(*   the same value                                                          *)
webertj@15547
  1488
(* - two interpretations are 'not_equal' iff they are both defined at least  *)
webertj@15547
  1489
(*   partially, and a defined part denotes different values                  *)
webertj@15547
  1490
(* - a completely undefined interpretation is neither 'equal' nor            *)
webertj@15547
  1491
(*   'not_equal' to another interpretation                                   *)
webertj@14807
  1492
(* ------------------------------------------------------------------------- *)
webertj@14807
  1493
wenzelm@22567
  1494
  (* We could in principle represent '=' on a type T by a particular        *)
wenzelm@22567
  1495
  (* interpretation.  However, the size of that interpretation is quadratic *)
wenzelm@22567
  1496
  (* in the size of T.  Therefore comparing the interpretations 'i1' and    *)
wenzelm@22567
  1497
  (* 'i2' directly is more efficient than constructing the interpretation   *)
wenzelm@22567
  1498
  (* for equality on T first, and "applying" this interpretation to 'i1'    *)
wenzelm@22567
  1499
  (* and 'i2' in the usual way (cf. 'interpretation_apply') then.           *)
webertj@14807
  1500
wenzelm@22567
  1501
  (* interpretation * interpretation -> interpretation *)
webertj@14807
  1502
wenzelm@22567
  1503
  fun make_equality (i1, i2) =
wenzelm@22567
  1504
  let
wenzelm@22567
  1505
    (* interpretation * interpretation -> prop_formula *)
wenzelm@22567
  1506
    fun equal (i1, i2) =
wenzelm@22567
  1507
      (case i1 of
wenzelm@22567
  1508
        Leaf xs =>
wenzelm@22567
  1509
        (case i2 of
wenzelm@22567
  1510
          Leaf ys => PropLogic.dot_product (xs, ys)  (* defined and equal *)
wenzelm@22567
  1511
        | Node _  => raise REFUTE ("make_equality",
wenzelm@22567
  1512
          "second interpretation is higher"))
wenzelm@22567
  1513
      | Node xs =>
wenzelm@22567
  1514
        (case i2 of
wenzelm@22567
  1515
          Leaf _  => raise REFUTE ("make_equality",
wenzelm@22567
  1516
          "first interpretation is higher")
wenzelm@22567
  1517
        | Node ys => PropLogic.all (map equal (xs ~~ ys))))
wenzelm@22567
  1518
    (* interpretation * interpretation -> prop_formula *)
wenzelm@22567
  1519
    fun not_equal (i1, i2) =
wenzelm@22567
  1520
      (case i1 of
wenzelm@22567
  1521
        Leaf xs =>
wenzelm@22567
  1522
        (case i2 of
wenzelm@22567
  1523
          (* defined and not equal *)
wenzelm@22567
  1524
          Leaf ys => PropLogic.all ((PropLogic.exists xs)
wenzelm@22567
  1525
          :: (PropLogic.exists ys)
wenzelm@22567
  1526
          :: (map (fn (x,y) => SOr (SNot x, SNot y)) (xs ~~ ys)))
wenzelm@22567
  1527
        | Node _  => raise REFUTE ("make_equality",
wenzelm@22567
  1528
          "second interpretation is higher"))
wenzelm@22567
  1529
      | Node xs =>
wenzelm@22567
  1530
        (case i2 of
wenzelm@22567
  1531
          Leaf _  => raise REFUTE ("make_equality",
wenzelm@22567
  1532
          "first interpretation is higher")
wenzelm@22567
  1533
        | Node ys => PropLogic.exists (map not_equal (xs ~~ ys))))
wenzelm@22567
  1534
  in
wenzelm@22567
  1535
    (* a value may be undefined; therefore 'not_equal' is not just the *)
wenzelm@22567
  1536
    (* negation of 'equal'                                             *)
wenzelm@22567
  1537
    Leaf [equal (i1, i2), not_equal (i1, i2)]
wenzelm@22567
  1538
  end;
webertj@14807
  1539
webertj@15292
  1540
(* ------------------------------------------------------------------------- *)
webertj@15547
  1541
(* make_def_equality: returns an interpretation that denotes (extensional)   *)
webertj@15547
  1542
(*                    equality of two interpretations                        *)
webertj@15547
  1543
(* This function treats undefined/partially defined interpretations          *)
webertj@15547
  1544
(* different from 'make_equality': two undefined interpretations are         *)
webertj@15547
  1545
(* considered equal, while a defined interpretation is considered not equal  *)
webertj@15547
  1546
(* to an undefined interpretation.                                           *)
webertj@15547
  1547
(* ------------------------------------------------------------------------- *)
webertj@15547
  1548
wenzelm@22567
  1549
  (* interpretation * interpretation -> interpretation *)
webertj@15547
  1550
wenzelm@22567
  1551
  fun make_def_equality (i1, i2) =
wenzelm@22567
  1552
  let
wenzelm@22567
  1553
    (* interpretation * interpretation -> prop_formula *)
wenzelm@22567
  1554
    fun equal (i1, i2) =
wenzelm@22567
  1555
      (case i1 of
wenzelm@22567
  1556
        Leaf xs =>
wenzelm@22567
  1557
        (case i2 of
wenzelm@22567
  1558
          (* defined and equal, or both undefined *)
wenzelm@22567
  1559
          Leaf ys => SOr (PropLogic.dot_product (xs, ys),
wenzelm@22567
  1560
          SAnd (PropLogic.all (map SNot xs), PropLogic.all (map SNot ys)))
wenzelm@22567
  1561
        | Node _  => raise REFUTE ("make_def_equality",
wenzelm@22567
  1562
          "second interpretation is higher"))
wenzelm@22567
  1563
      | Node xs =>
wenzelm@22567
  1564
        (case i2 of
wenzelm@22567
  1565
          Leaf _  => raise REFUTE ("make_def_equality",
wenzelm@22567
  1566
          "first interpretation is higher")
wenzelm@22567
  1567
        | Node ys => PropLogic.all (map equal (xs ~~ ys))))
wenzelm@22567
  1568
    (* interpretation *)
wenzelm@22567
  1569
    val eq = equal (i1, i2)
wenzelm@22567
  1570
  in
wenzelm@22567
  1571
    Leaf [eq, SNot eq]
wenzelm@22567
  1572
  end;
webertj@15547
  1573
webertj@15547
  1574
(* ------------------------------------------------------------------------- *)
webertj@15547
  1575
(* interpretation_apply: returns an interpretation that denotes the result   *)
webertj@22092
  1576
(*                       of applying the function denoted by 'i1' to the     *)
webertj@15547
  1577
(*                       argument denoted by 'i2'                            *)
webertj@15547
  1578
(* ------------------------------------------------------------------------- *)
webertj@15547
  1579
wenzelm@22567
  1580
  (* interpretation * interpretation -> interpretation *)
webertj@15547
  1581
wenzelm@22567
  1582
  fun interpretation_apply (i1, i2) =
wenzelm@22567
  1583
  let
wenzelm@22567
  1584
    (* interpretation * interpretation -> interpretation *)
wenzelm@22567
  1585
    fun interpretation_disjunction (tr1,tr2) =
wenzelm@22567
  1586
      tree_map (fn (xs,ys) => map (fn (x,y) => SOr(x,y)) (xs ~~ ys))
wenzelm@22567
  1587
        (tree_pair (tr1,tr2))
wenzelm@22567
  1588
    (* prop_formula * interpretation -> interpretation *)
wenzelm@22567
  1589
    fun prop_formula_times_interpretation (fm,tr) =
wenzelm@22567
  1590
      tree_map (map (fn x => SAnd (fm,x))) tr
wenzelm@22567
  1591
    (* prop_formula list * interpretation list -> interpretation *)
wenzelm@22567
  1592
    fun prop_formula_list_dot_product_interpretation_list ([fm],[tr]) =
wenzelm@22567
  1593
      prop_formula_times_interpretation (fm,tr)
wenzelm@22567
  1594
      | prop_formula_list_dot_product_interpretation_list (fm::fms,tr::trees) =
wenzelm@22567
  1595
      interpretation_disjunction (prop_formula_times_interpretation (fm,tr),
wenzelm@22567
  1596
        prop_formula_list_dot_product_interpretation_list (fms,trees))
wenzelm@22567
  1597
      | prop_formula_list_dot_product_interpretation_list (_,_) =
wenzelm@22567
  1598
      raise REFUTE ("interpretation_apply", "empty list (in dot product)")
wenzelm@22567
  1599
    (* concatenates 'x' with every list in 'xss', returning a new list of *)
wenzelm@22567
  1600
    (* lists                                                              *)
wenzelm@22567
  1601
    (* 'a -> 'a list list -> 'a list list *)
wenzelm@22567
  1602
    fun cons_list x xss =
wenzelm@22567
  1603
      map (cons x) xss
wenzelm@22567
  1604
    (* returns a list of lists, each one consisting of one element from each *)
wenzelm@22567
  1605
    (* element of 'xss'                                                      *)
wenzelm@22567
  1606
    (* 'a list list -> 'a list list *)
wenzelm@22567
  1607
    fun pick_all [xs] =
wenzelm@22567
  1608
      map single xs
wenzelm@22567
  1609
      | pick_all (xs::xss) =
wenzelm@22567
  1610
      let val rec_pick = pick_all xss in
wenzelm@32952
  1611
        maps (fn x => map (cons x) rec_pick) xs
wenzelm@22567
  1612
      end
wenzelm@22567
  1613
      | pick_all _ =
wenzelm@22567
  1614
      raise REFUTE ("interpretation_apply", "empty list (in pick_all)")
wenzelm@22567
  1615
    (* interpretation -> prop_formula list *)
wenzelm@22567
  1616
    fun interpretation_to_prop_formula_list (Leaf xs) =
wenzelm@22567
  1617
      xs
wenzelm@22567
  1618
      | interpretation_to_prop_formula_list (Node trees) =
wenzelm@22567
  1619
      map PropLogic.all (pick_all
wenzelm@22567
  1620
        (map interpretation_to_prop_formula_list trees))
wenzelm@22567
  1621
  in
wenzelm@22567
  1622
    case i1 of
wenzelm@22567
  1623
      Leaf _ =>
wenzelm@22567
  1624
      raise REFUTE ("interpretation_apply", "first interpretation is a leaf")
wenzelm@22567
  1625
    | Node xs =>
wenzelm@22567
  1626
      prop_formula_list_dot_product_interpretation_list
wenzelm@22567
  1627
        (interpretation_to_prop_formula_list i2, xs)
wenzelm@22567
  1628
  end;
webertj@15547
  1629
webertj@15547
  1630
(* ------------------------------------------------------------------------- *)
webertj@15292
  1631
(* eta_expand: eta-expands a term 't' by adding 'i' lambda abstractions      *)
webertj@15292
  1632
(* ------------------------------------------------------------------------- *)
webertj@15292
  1633
wenzelm@22567
  1634
  (* Term.term -> int -> Term.term *)
webertj@15292
  1635
wenzelm@22567
  1636
  fun eta_expand t i =
wenzelm@22567
  1637
  let
wenzelm@22567
  1638
    val Ts = Term.binder_types (Term.fastype_of t)
wenzelm@22567
  1639
    val t' = Term.incr_boundvars i t
wenzelm@22567
  1640
  in
wenzelm@33339
  1641
    fold_rev (fn T => fn term => Abs ("<eta_expand>", T, term))
wenzelm@33339
  1642
      (List.take (Ts, i))
wenzelm@33339
  1643
      (Term.list_comb (t', map Bound (i-1 downto 0)))
wenzelm@22567
  1644
  end;
webertj@15292
  1645
webertj@15335
  1646
(* ------------------------------------------------------------------------- *)
webertj@15547
  1647
(* size_of_dtyp: the size of (an initial fragment of) an inductive data type *)
webertj@15547
  1648
(*               is the sum (over its constructors) of the product (over     *)
webertj@15547
  1649
(*               their arguments) of the size of the argument types          *)
webertj@15335
  1650
(* ------------------------------------------------------------------------- *)
webertj@15335
  1651
wenzelm@22567
  1652
  fun size_of_dtyp thy typ_sizes descr typ_assoc constructors =
wenzelm@33002
  1653
    Integer.sum (map (fn (_, dtyps) =>
wenzelm@33002
  1654
      Integer.prod (map (size_of_type thy (typ_sizes, []) o
webertj@25014
  1655
        (typ_of_dtyp descr typ_assoc)) dtyps))
webertj@25014
  1656
          constructors);
webertj@15335
  1657
webertj@15292
  1658
webertj@15292
  1659
(* ------------------------------------------------------------------------- *)
webertj@15292
  1660
(* INTERPRETERS: Actual Interpreters                                         *)
webertj@15292
  1661
(* ------------------------------------------------------------------------- *)
webertj@14807
  1662
wenzelm@22567
  1663
  (* theory -> model -> arguments -> Term.term ->
wenzelm@22567
  1664
    (interpretation * model * arguments) option *)
webertj@14807
  1665
wenzelm@22567
  1666
  (* simply typed lambda calculus: Isabelle's basic term syntax, with type *)
wenzelm@22567
  1667
  (* variables, function types, and propT                                  *)
webertj@14807
  1668
wenzelm@22567
  1669
  fun stlc_interpreter thy model args t =
wenzelm@22567
  1670
  let
wenzelm@22567
  1671
    val (typs, terms)                                   = model
wenzelm@22567
  1672
    val {maxvars, def_eq, next_idx, bounds, wellformed} = args
wenzelm@22567
  1673
    (* Term.typ -> (interpretation * model * arguments) option *)
wenzelm@22567
  1674
    fun interpret_groundterm T =
wenzelm@22567
  1675
    let
wenzelm@22567
  1676
      (* unit -> (interpretation * model * arguments) option *)
wenzelm@22567
  1677
      fun interpret_groundtype () =
wenzelm@22567
  1678
      let
wenzelm@22567
  1679
        (* the model must specify a size for ground types *)
blanchet@29820
  1680
        val size = if T = Term.propT then 2
blanchet@29820
  1681
          else the (AList.lookup (op =) typs T)
wenzelm@22567
  1682
        val next = next_idx+size
wenzelm@22567
  1683
        (* check if 'maxvars' is large enough *)
wenzelm@22567
  1684
        val _    = (if next-1>maxvars andalso maxvars>0 then
wenzelm@22567
  1685
          raise MAXVARS_EXCEEDED else ())
wenzelm@22567
  1686
        (* prop_formula list *)
wenzelm@22567
  1687
        val fms  = map BoolVar (next_idx upto (next_idx+size-1))
wenzelm@22567
  1688
        (* interpretation *)
wenzelm@22567
  1689
        val intr = Leaf fms
wenzelm@22567
  1690
        (* prop_formula list -> prop_formula *)
wenzelm@22567
  1691
        fun one_of_two_false []      = True
wenzelm@22567
  1692
          | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
wenzelm@22567
  1693
          SOr (SNot x, SNot x')) xs), one_of_two_false xs)
wenzelm@22567
  1694
        (* prop_formula *)
wenzelm@22567
  1695
        val wf   = one_of_two_false fms
wenzelm@22567
  1696
      in
wenzelm@22567
  1697
        (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@22567
  1698
        (* condition                                                  *)
wenzelm@22567
  1699
        SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
wenzelm@22567
  1700
          def_eq = def_eq, next_idx = next, bounds = bounds,
wenzelm@22567
  1701
          wellformed = SAnd (wellformed, wf)})
wenzelm@22567
  1702
      end
wenzelm@22567
  1703
    in
wenzelm@22567
  1704
      case T of
wenzelm@22567
  1705
        Type ("fun", [T1, T2]) =>
wenzelm@22567
  1706
        let
webertj@25014
  1707
          (* we create 'size_of_type ... T1' different copies of the        *)
webertj@25014
  1708
          (* interpretation for 'T2', which are then combined into a single *)
webertj@25014
  1709
          (* new interpretation                                             *)
wenzelm@22567
  1710
          (* make fresh copies, with different variable indices *)
wenzelm@22567
  1711
          (* 'idx': next variable index                         *)
wenzelm@22567
  1712
          (* 'n'  : number of copies                            *)
wenzelm@22567
  1713
          (* int -> int -> (int * interpretation list * prop_formula *)
wenzelm@22567
  1714
          fun make_copies idx 0 =
wenzelm@22567
  1715
            (idx, [], True)
wenzelm@22567
  1716
            | make_copies idx n =
wenzelm@22567
  1717
            let
wenzelm@22567
  1718
              val (copy, _, new_args) = interpret thy (typs, [])
wenzelm@22567
  1719
                {maxvars = maxvars, def_eq = false, next_idx = idx,
wenzelm@22567
  1720
                bounds = [], wellformed = True} (Free ("dummy", T2))
wenzelm@22567
  1721
              val (idx', copies, wf') = make_copies (#next_idx new_args) (n-1)
wenzelm@22567
  1722
            in
wenzelm@22567
  1723
              (idx', copy :: copies, SAnd (#wellformed new_args, wf'))
wenzelm@22567
  1724
            end
webertj@25014
  1725
          val (next, copies, wf) = make_copies next_idx
webertj@25014
  1726
            (size_of_type thy model T1)
wenzelm@22567
  1727
          (* combine copies into a single interpretation *)
wenzelm@22567
  1728
          val intr = Node copies
wenzelm@22567
  1729
        in
wenzelm@22567
  1730
          (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@22567
  1731
          (* condition                                                  *)
wenzelm@22567
  1732
          SOME (intr, (typs, (t, intr)::terms), {maxvars = maxvars,
wenzelm@22567
  1733
            def_eq = def_eq, next_idx = next, bounds = bounds,
wenzelm@22567
  1734
            wellformed = SAnd (wellformed, wf)})
wenzelm@22567
  1735
        end
wenzelm@22567
  1736
      | Type _  => interpret_groundtype ()
wenzelm@22567
  1737
      | TFree _ => interpret_groundtype ()
wenzelm@22567
  1738
      | TVar  _ => interpret_groundtype ()
wenzelm@22567
  1739
    end
wenzelm@22567
  1740
  in
wenzelm@22567
  1741
    case AList.lookup (op =) terms t of
wenzelm@22567
  1742
      SOME intr =>
wenzelm@22567
  1743
      (* return an existing interpretation *)
wenzelm@22567
  1744
      SOME (intr, model, args)
wenzelm@22567
  1745
    | NONE =>
wenzelm@22567
  1746
      (case t of
wenzelm@22567
  1747
        Const (_, T)     =>
wenzelm@22567
  1748
        interpret_groundterm T
wenzelm@22567
  1749
      | Free (_, T)      =>
wenzelm@22567
  1750
        interpret_groundterm T
wenzelm@22567
  1751
      | Var (_, T)       =>
wenzelm@22567
  1752
        interpret_groundterm T
wenzelm@22567
  1753
      | Bound i          =>
wenzelm@22567
  1754
        SOME (List.nth (#bounds args, i), model, args)
wenzelm@22567
  1755
      | Abs (x, T, body) =>
wenzelm@22567
  1756
        let
wenzelm@22567
  1757
          (* create all constants of type 'T' *)
webertj@25014
  1758
          val constants = make_constants thy model T
wenzelm@22567
  1759
          (* interpret the 'body' separately for each constant *)
wenzelm@33246
  1760
          val (bodies, (model', args')) = fold_map
wenzelm@33246
  1761
            (fn c => fn (m, a) =>
wenzelm@22567
  1762
              let
wenzelm@22567
  1763
                (* add 'c' to 'bounds' *)
wenzelm@22567
  1764
                val (i', m', a') = interpret thy m {maxvars = #maxvars a,
wenzelm@22567
  1765
                  def_eq = #def_eq a, next_idx = #next_idx a,
wenzelm@22567
  1766
                  bounds = (c :: #bounds a), wellformed = #wellformed a} body
wenzelm@22567
  1767
              in
wenzelm@22567
  1768
                (* keep the new model m' and 'next_idx' and 'wellformed', *)
wenzelm@22567
  1769
                (* but use old 'bounds'                                   *)
wenzelm@33246
  1770
                (i', (m', {maxvars = maxvars, def_eq = def_eq,
wenzelm@22567
  1771
                  next_idx = #next_idx a', bounds = bounds,
wenzelm@33246
  1772
                  wellformed = #wellformed a'}))
wenzelm@22567
  1773
              end)
wenzelm@33246
  1774
            constants (model, args)
wenzelm@22567
  1775
        in
wenzelm@22567
  1776
          SOME (Node bodies, model', args')
wenzelm@22567
  1777
        end
wenzelm@33246
  1778
      | t1 $ t2 =>
wenzelm@22567
  1779
        let
wenzelm@22567
  1780
          (* interpret 't1' and 't2' separately *)
wenzelm@22567
  1781
          val (intr1, model1, args1) = interpret thy model args t1
wenzelm@22567
  1782
          val (intr2, model2, args2) = interpret thy model1 args1 t2
wenzelm@22567
  1783
        in
wenzelm@22567
  1784
          SOME (interpretation_apply (intr1, intr2), model2, args2)
wenzelm@22567
  1785
        end)
wenzelm@22567
  1786
  end;
webertj@14807
  1787
wenzelm@22567
  1788
  (* theory -> model -> arguments -> Term.term ->
wenzelm@22567
  1789
    (interpretation * model * arguments) option *)
webertj@14807
  1790
wenzelm@22567
  1791
  fun Pure_interpreter thy model args t =
wenzelm@22567
  1792
    case t of
blanchet@29802
  1793
      Const (@{const_name all}, _) $ t1 =>
wenzelm@22567
  1794
      let
wenzelm@22567
  1795
        val (i, m, a) = interpret thy model args t1
wenzelm@22567
  1796
      in
wenzelm@22567
  1797
        case i of
wenzelm@22567
  1798
          Node xs =>
wenzelm@22567
  1799
          (* 3-valued logic *)
wenzelm@22567
  1800
          let
wenzelm@22567
  1801
            val fmTrue  = PropLogic.all (map toTrue xs)
wenzelm@22567
  1802
            val fmFalse = PropLogic.exists (map toFalse xs)
wenzelm@22567
  1803
          in
wenzelm@22567
  1804
            SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@22567
  1805
          end
wenzelm@22567
  1806
        | _ =>
wenzelm@22567
  1807
          raise REFUTE ("Pure_interpreter",
wenzelm@22567
  1808
            "\"all\" is followed by a non-function")
wenzelm@22567
  1809
      end
blanchet@29802
  1810
    | Const (@{const_name all}, _) =>
wenzelm@22567
  1811
      SOME (interpret thy model args (eta_expand t 1))
blanchet@29802
  1812
    | Const (@{const_name "=="}, _) $ t1 $ t2 =>
wenzelm@22567
  1813
      let
wenzelm@22567
  1814
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1815
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1816
      in
wenzelm@22567
  1817
        (* we use either 'make_def_equality' or 'make_equality' *)
wenzelm@22567
  1818
        SOME ((if #def_eq args then make_def_equality else make_equality)
wenzelm@22567
  1819
          (i1, i2), m2, a2)
wenzelm@22567
  1820
      end
blanchet@29802
  1821
    | Const (@{const_name "=="}, _) $ t1 =>
wenzelm@22567
  1822
      SOME (interpret thy model args (eta_expand t 1))
blanchet@29802
  1823
    | Const (@{const_name "=="}, _) =>
wenzelm@22567
  1824
      SOME (interpret thy model args (eta_expand t 2))
blanchet@29802
  1825
    | Const (@{const_name "==>"}, _) $ t1 $ t2 =>
wenzelm@22567
  1826
      (* 3-valued logic *)
wenzelm@22567
  1827
      let
wenzelm@22567
  1828
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1829
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1830
        val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
wenzelm@22567
  1831
        val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
wenzelm@22567
  1832
      in
wenzelm@22567
  1833
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1834
      end
blanchet@29802
  1835
    | Const (@{const_name "==>"}, _) $ t1 =>
wenzelm@22567
  1836
      SOME (interpret thy model args (eta_expand t 1))
blanchet@29802
  1837
    | Const (@{const_name "==>"}, _) =>
wenzelm@22567
  1838
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@22567
  1839
    | _ => NONE;
webertj@14807
  1840
wenzelm@22567
  1841
  (* theory -> model -> arguments -> Term.term ->
wenzelm@22567
  1842
    (interpretation * model * arguments) option *)
webertj@14807
  1843
wenzelm@22567
  1844
  fun HOLogic_interpreter thy model args t =
wenzelm@22567
  1845
  (* Providing interpretations directly is more efficient than unfolding the *)
wenzelm@22567
  1846
  (* logical constants.  In HOL however, logical constants can themselves be *)
wenzelm@22567
  1847
  (* arguments.  They are then translated using eta-expansion.               *)
wenzelm@22567
  1848
    case t of
blanchet@29802
  1849
      Const (@{const_name Trueprop}, _) =>
wenzelm@22567
  1850
      SOME (Node [TT, FF], model, args)
blanchet@29802
  1851
    | Const (@{const_name Not}, _) =>
wenzelm@22567
  1852
      SOME (Node [FF, TT], model, args)
wenzelm@22567
  1853
    (* redundant, since 'True' is also an IDT constructor *)
blanchet@29802
  1854
    | Const (@{const_name True}, _) =>
wenzelm@22567
  1855
      SOME (TT, model, args)
wenzelm@22567
  1856
    (* redundant, since 'False' is also an IDT constructor *)
blanchet@29802
  1857
    | Const (@{const_name False}, _) =>
wenzelm@22567
  1858
      SOME (FF, model, args)
blanchet@29802
  1859
    | Const (@{const_name All}, _) $ t1 =>  (* similar to "all" (Pure) *)
wenzelm@22567
  1860
      let
wenzelm@22567
  1861
        val (i, m, a) = interpret thy model args t1
wenzelm@22567
  1862
      in
wenzelm@22567
  1863
        case i of
wenzelm@22567
  1864
          Node xs =>
wenzelm@22567
  1865
          (* 3-valued logic *)
wenzelm@22567
  1866
          let
wenzelm@22567
  1867
            val fmTrue  = PropLogic.all (map toTrue xs)
wenzelm@22567
  1868
            val fmFalse = PropLogic.exists (map toFalse xs)
wenzelm@22567
  1869
          in
wenzelm@22567
  1870
            SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@22567
  1871
          end
wenzelm@22567
  1872
        | _ =>
wenzelm@22567
  1873
          raise REFUTE ("HOLogic_interpreter",
wenzelm@22567
  1874
            "\"All\" is followed by a non-function")
wenzelm@22567
  1875
      end
blanchet@29802
  1876
    | Const (@{const_name All}, _) =>
wenzelm@22567
  1877
      SOME (interpret thy model args (eta_expand t 1))
blanchet@29802
  1878
    | Const (@{const_name Ex}, _) $ t1 =>
wenzelm@22567
  1879
      let
wenzelm@22567
  1880
        val (i, m, a) = interpret thy model args t1
wenzelm@22567
  1881
      in
wenzelm@22567
  1882
        case i of
wenzelm@22567
  1883
          Node xs =>
wenzelm@22567
  1884
          (* 3-valued logic *)
wenzelm@22567
  1885
          let
wenzelm@22567
  1886
            val fmTrue  = PropLogic.exists (map toTrue xs)
wenzelm@22567
  1887
            val fmFalse = PropLogic.all (map toFalse xs)
wenzelm@22567
  1888
          in
wenzelm@22567
  1889
            SOME (Leaf [fmTrue, fmFalse], m, a)
wenzelm@22567
  1890
          end
wenzelm@22567
  1891
        | _ =>
wenzelm@22567
  1892
          raise REFUTE ("HOLogic_interpreter",
wenzelm@22567
  1893
            "\"Ex\" is followed by a non-function")
wenzelm@22567
  1894
      end
blanchet@29802
  1895
    | Const (@{const_name Ex}, _) =>
wenzelm@22567
  1896
      SOME (interpret thy model args (eta_expand t 1))
blanchet@29802
  1897
    | Const (@{const_name "op ="}, _) $ t1 $ t2 =>  (* similar to "==" (Pure) *)
wenzelm@22567
  1898
      let
wenzelm@22567
  1899
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1900
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1901
      in
wenzelm@22567
  1902
        SOME (make_equality (i1, i2), m2, a2)
wenzelm@22567
  1903
      end
blanchet@29802
  1904
    | Const (@{const_name "op ="}, _) $ t1 =>
wenzelm@22567
  1905
      SOME (interpret thy model args (eta_expand t 1))
blanchet@29802
  1906
    | Const (@{const_name "op ="}, _) =>
wenzelm@22567
  1907
      SOME (interpret thy model args (eta_expand t 2))
blanchet@29802
  1908
    | Const (@{const_name "op &"}, _) $ t1 $ t2 =>
wenzelm@22567
  1909
      (* 3-valued logic *)
wenzelm@22567
  1910
      let
wenzelm@22567
  1911
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1912
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1913
        val fmTrue       = PropLogic.SAnd (toTrue i1, toTrue i2)
wenzelm@22567
  1914
        val fmFalse      = PropLogic.SOr (toFalse i1, toFalse i2)
wenzelm@22567
  1915
      in
wenzelm@22567
  1916
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1917
      end
blanchet@29802
  1918
    | Const (@{const_name "op &"}, _) $ t1 =>
wenzelm@22567
  1919
      SOME (interpret thy model args (eta_expand t 1))
blanchet@29802
  1920
    | Const (@{const_name "op &"}, _) =>
wenzelm@22567
  1921
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@22567
  1922
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1923
      (* "False & undef":                                          *)
wenzelm@22567
  1924
      (* SOME (Node [Node [TT, FF], Node [FF, FF]], model, args) *)
blanchet@29802
  1925
    | Const (@{const_name "op |"}, _) $ t1 $ t2 =>
wenzelm@22567
  1926
      (* 3-valued logic *)
wenzelm@22567
  1927
      let
wenzelm@22567
  1928
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1929
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1930
        val fmTrue       = PropLogic.SOr (toTrue i1, toTrue i2)
wenzelm@22567
  1931
        val fmFalse      = PropLogic.SAnd (toFalse i1, toFalse i2)
wenzelm@22567
  1932
      in
wenzelm@22567
  1933
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1934
      end
blanchet@29802
  1935
    | Const (@{const_name "op |"}, _) $ t1 =>
wenzelm@22567
  1936
      SOME (interpret thy model args (eta_expand t 1))
blanchet@29802
  1937
    | Const (@{const_name "op |"}, _) =>
wenzelm@22567
  1938
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@22567
  1939
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1940
      (* "True | undef":                                           *)
wenzelm@22567
  1941
      (* SOME (Node [Node [TT, TT], Node [TT, FF]], model, args) *)
blanchet@29802
  1942
    | Const (@{const_name "op -->"}, _) $ t1 $ t2 =>  (* similar to "==>" (Pure) *)
wenzelm@22567
  1943
      (* 3-valued logic *)
wenzelm@22567
  1944
      let
wenzelm@22567
  1945
        val (i1, m1, a1) = interpret thy model args t1
wenzelm@22567
  1946
        val (i2, m2, a2) = interpret thy m1 a1 t2
wenzelm@22567
  1947
        val fmTrue       = PropLogic.SOr (toFalse i1, toTrue i2)
wenzelm@22567
  1948
        val fmFalse      = PropLogic.SAnd (toTrue i1, toFalse i2)
wenzelm@22567
  1949
      in
wenzelm@22567
  1950
        SOME (Leaf [fmTrue, fmFalse], m2, a2)
wenzelm@22567
  1951
      end
blanchet@29802
  1952
    | Const (@{const_name "op -->"}, _) $ t1 =>
wenzelm@22567
  1953
      SOME (interpret thy model args (eta_expand t 1))
blanchet@29802
  1954
    | Const (@{const_name "op -->"}, _) =>
wenzelm@22567
  1955
      SOME (interpret thy model args (eta_expand t 2))
wenzelm@22567
  1956
      (* this would make "undef" propagate, even for formulae like *)
wenzelm@22567
  1957
      (* "False --> undef":                                        *)
wenzelm@22567
  1958
      (* SOME (Node [Node [TT, FF], Node [TT, TT]], model, args) *)
wenzelm@22567
  1959
    | _ => NONE;
webertj@14807
  1960
wenzelm@22567
  1961
  (* theory -> model -> arguments -> Term.term ->
wenzelm@22567
  1962
    (interpretation * model * arguments) option *)
webertj@14807
  1963
webertj@25014
  1964
  (* interprets variables and constants whose type is an IDT (this is        *)
webertj@25014
  1965
  (* relatively easy and merely requires us to compute the size of the IDT); *)
webertj@25014
  1966
  (* constructors of IDTs however are properly interpreted by                *)
webertj@25014
  1967
  (* 'IDT_constructor_interpreter'                                           *)
webertj@15547
  1968
wenzelm@22567
  1969
  fun IDT_interpreter thy model args t =
wenzelm@22567
  1970
  let
wenzelm@22567
  1971
    val (typs, terms) = model
wenzelm@22567
  1972
    (* Term.typ -> (interpretation * model * arguments) option *)
wenzelm@22567
  1973
    fun interpret_term (Type (s, Ts)) =
haftmann@31784
  1974
      (case Datatype.get_info thy s of
wenzelm@22567
  1975
        SOME info =>  (* inductive datatype *)
wenzelm@22567
  1976
        let
wenzelm@22567
  1977
          (* int option -- only recursive IDTs have an associated depth *)
wenzelm@22567
  1978
          val depth = AList.lookup (op =) typs (Type (s, Ts))
webertj@25014
  1979
          (* sanity check: depth must be at least 0 *)
webertj@25014
  1980
          val _ = (case depth of SOME n =>
webertj@25014
  1981
            if n<0 then
webertj@25014
  1982
              raise REFUTE ("IDT_interpreter", "negative depth")
webertj@25014
  1983
            else ()
webertj@25014
  1984
            | _ => ())
wenzelm@22567
  1985
        in
wenzelm@22567
  1986
          (* termination condition to avoid infinite recursion *)
wenzelm@22567
  1987
          if depth = (SOME 0) then
wenzelm@22567
  1988
            (* return a leaf of size 0 *)
wenzelm@22567
  1989
            SOME (Leaf [], model, args)
wenzelm@22567
  1990
          else
wenzelm@22567
  1991
            let
wenzelm@22567
  1992
              val index               = #index info
wenzelm@22567
  1993
              val descr               = #descr info
wenzelm@29288
  1994
              val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@22567
  1995
              val typ_assoc           = dtyps ~~ Ts
wenzelm@22567
  1996
              (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
webertj@25014
  1997
              val _ = if Library.exists (fn d =>
haftmann@33968
  1998
                  case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
wenzelm@22567
  1999
                then
wenzelm@22567
  2000
                  raise REFUTE ("IDT_interpreter",
wenzelm@22567
  2001
                    "datatype argument (for type "
wenzelm@26939
  2002
                    ^ Syntax.string_of_typ_global thy (Type (s, Ts))
wenzelm@22567
  2003
                    ^ ") is not a variable")
webertj@25014
  2004
                else ()
wenzelm@22567
  2005
              (* if the model specifies a depth for the current type, *)
wenzelm@22567
  2006
              (* decrement it to avoid infinite recursion             *)
wenzelm@22567
  2007
              val typs'    = case depth of NONE => typs | SOME n =>
wenzelm@22567
  2008
                AList.update (op =) (Type (s, Ts), n-1) typs
wenzelm@22567
  2009
              (* recursively compute the size of the datatype *)
wenzelm@22567
  2010
              val size     = size_of_dtyp thy typs' descr typ_assoc constrs
wenzelm@22567
  2011
              val next_idx = #next_idx args
wenzelm@22567
  2012
              val next     = next_idx+size
wenzelm@22567
  2013
              (* check if 'maxvars' is large enough *)
wenzelm@22567
  2014
              val _        = (if next-1 > #maxvars args andalso
wenzelm@22567
  2015
                #maxvars args > 0 then raise MAXVARS_EXCEEDED else ())
wenzelm@22567
  2016
              (* prop_formula list *)
wenzelm@22567
  2017
              val fms      = map BoolVar (next_idx upto (next_idx+size-1))
wenzelm@22567
  2018
              (* interpretation *)
wenzelm@22567
  2019
              val intr     = Leaf fms
wenzelm@22567
  2020
              (* prop_formula list -> prop_formula *)
wenzelm@22567
  2021
              fun one_of_two_false []      = True
wenzelm@22567
  2022
                | one_of_two_false (x::xs) = SAnd (PropLogic.all (map (fn x' =>
wenzelm@22567
  2023
                SOr (SNot x, SNot x')) xs), one_of_two_false xs)
wenzelm@22567
  2024
              (* prop_formula *)
wenzelm@22567
  2025
              val wf       = one_of_two_false fms
wenzelm@22567
  2026
            in
wenzelm@22567
  2027
              (* extend the model, increase 'next_idx', add well-formedness *)
wenzelm@22567
  2028
              (* condition                                                  *)
wenzelm@22567
  2029
              SOME (intr, (typs, (t, intr)::terms), {maxvars = #maxvars args,
wenzelm@22567
  2030
                def_eq = #def_eq args, next_idx = next, bounds = #bounds args,
wenzelm@22567
  2031
                wellformed = SAnd (#wellformed args, wf)})
wenzelm@22567
  2032
            end
wenzelm@22567
  2033
        end
wenzelm@22567
  2034
      | NONE =>  (* not an inductive datatype *)
wenzelm@22567
  2035
        NONE)
wenzelm@22567
  2036
      | interpret_term _ =  (* a (free or schematic) type variable *)
wenzelm@22567
  2037
      NONE
wenzelm@22567
  2038
  in
wenzelm@22567
  2039
    case AList.lookup (op =) terms t of
wenzelm@22567
  2040
      SOME intr =>
wenzelm@22567
  2041
      (* return an existing interpretation *)
wenzelm@22567
  2042
      SOME (intr, model, args)
wenzelm@22567
  2043
    | NONE =>
wenzelm@22567
  2044
      (case t of
wenzelm@22567
  2045
        Free (_, T)  => interpret_term T
wenzelm@22567
  2046
      | Var (_, T)   => interpret_term T
wenzelm@22567
  2047
      | Const (_, T) => interpret_term T
wenzelm@22567
  2048
      | _            => NONE)
wenzelm@22567
  2049
  end;
webertj@15547
  2050
wenzelm@22567
  2051
  (* theory -> model -> arguments -> Term.term ->
wenzelm@22567
  2052
    (interpretation * model * arguments) option *)
webertj@15547
  2053
webertj@25014
  2054
  (* This function imposes an order on the elements of a datatype fragment  *)
webertj@25014
  2055
  (* as follows: C_i x_1 ... x_n < C_j y_1 ... y_m iff i < j or             *)
webertj@25014
  2056
  (* (x_1, ..., x_n) < (y_1, ..., y_m).  With this order, a constructor is  *)
webertj@25014
  2057
  (* a function C_i that maps some argument indices x_1, ..., x_n to the    *)
webertj@25014
  2058
  (* datatype element given by index C_i x_1 ... x_n.  The idea remains the *)
webertj@25014
  2059
  (* same for recursive datatypes, although the computation of indices gets *)
webertj@25014
  2060
  (* a little tricky.                                                       *)
webertj@25014
  2061
wenzelm@22567
  2062
  fun IDT_constructor_interpreter thy model args t =
wenzelm@22567
  2063
  let
webertj@25014
  2064
    (* returns a list of canonical representations for terms of the type 'T' *)
webertj@25014
  2065
    (* It would be nice if we could just use 'print' for this, but 'print'   *)
webertj@25014
  2066
    (* for IDTs calls 'IDT_constructor_interpreter' again, and this could    *)
webertj@25014
  2067
    (* lead to infinite recursion when we have (mutually) recursive IDTs.    *)
webertj@25014
  2068
    (* (Term.typ * int) list -> Term.typ -> Term.term list *)
webertj@25014
  2069
    fun canonical_terms typs T =
webertj@25014
  2070
      (case T of
webertj@25014
  2071
        Type ("fun", [T1, T2]) =>
webertj@25014
  2072
        (* 'T2' might contain a recursive IDT, so we cannot use 'print' (at *)
webertj@25014
  2073
        (* least not for 'T2'                                               *)
webertj@25014
  2074
        let
webertj@25014
  2075
          (* returns a list of lists, each one consisting of n (possibly *)
webertj@25014
  2076
          (* identical) elements from 'xs'                               *)
webertj@25014
  2077
          (* int -> 'a list -> 'a list list *)
webertj@25014
  2078
          fun pick_all 1 xs =
webertj@25014
  2079
            map single xs
webertj@25014
  2080
          | pick_all n xs =
webertj@25014
  2081
            let val rec_pick = pick_all (n-1) xs in
wenzelm@32952
  2082
              maps (fn x => map (cons x) rec_pick) xs
webertj@25014
  2083
            end
webertj@25014
  2084
          (* ["x1", ..., "xn"] *)
webertj@25014
  2085
          val terms1 = canonical_terms typs T1
webertj@25014
  2086
          (* ["y1", ..., "ym"] *)
webertj@25014
  2087
          val terms2 = canonical_terms typs T2
webertj@25014
  2088
          (* [[("x1", "y1"), ..., ("xn", "y1")], ..., *)
webertj@25014
  2089
          (*   [("x1", "ym"), ..., ("xn", "ym")]]     *)
webertj@25014
  2090
          val functions = map (curry (op ~~) terms1)
webertj@25014
  2091
            (pick_all (length terms1) terms2)
webertj@25014
  2092
          (* [["(x1, y1)", ..., "(xn, y1)"], ..., *)
webertj@25014
  2093
          (*   ["(x1, ym)", ..., "(xn, ym)"]]     *)
webertj@25014
  2094
          val pairss = map (map HOLogic.mk_prod) functions
webertj@25014
  2095
          (* Term.typ *)
webertj@25014
  2096
          val HOLogic_prodT = HOLogic.mk_prodT (T1, T2)
webertj@25014
  2097
          val HOLogic_setT  = HOLogic.mk_setT HOLogic_prodT
webertj@25014
  2098
          (* Term.term *)
blanchet@36130
  2099
          val HOLogic_empty_set = Const (@{const_abbrev Set.empty}, HOLogic_setT)
webertj@25014
  2100
          val HOLogic_insert    =
blanchet@29802
  2101
            Const (@{const_name insert}, HOLogic_prodT --> HOLogic_setT --> HOLogic_setT)
webertj@25014
  2102
        in
webertj@25014
  2103
          (* functions as graphs, i.e. as a (HOL) set of pairs "(x, y)" *)
wenzelm@33339
  2104
          map (fn ps => fold_rev (fn pair => fn acc => HOLogic_insert $ pair $ acc) ps
webertj@25014
  2105
            HOLogic_empty_set) pairss
webertj@25014
  2106
        end
webertj@25014
  2107
      | Type (s, Ts) =>
haftmann@31784
  2108
        (case Datatype.get_info thy s of
webertj@25014
  2109
          SOME info =>
webertj@25014
  2110
          (case AList.lookup (op =) typs T of
webertj@25014
  2111
            SOME 0 =>
webertj@25014
  2112
            (* termination condition to avoid infinite recursion *)
webertj@25014
  2113
            []  (* at depth 0, every IDT is empty *)
webertj@25014
  2114
          | _ =>
webertj@25014
  2115
            let
webertj@25014
  2116
              val index               = #index info
webertj@25014
  2117
              val descr               = #descr info
wenzelm@29288
  2118
              val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
webertj@25014
  2119
              val typ_assoc           = dtyps ~~ Ts
webertj@25014
  2120
              (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
webertj@25014
  2121
              val _ = if Library.exists (fn d =>
haftmann@33968
  2122
                  case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
webertj@25014
  2123
                then
webertj@25014
  2124
                  raise REFUTE ("IDT_constructor_interpreter",
webertj@25014
  2125
                    "datatype argument (for type "
wenzelm@26939
  2126
                    ^ Syntax.string_of_typ_global thy T
webertj@25014
  2127
                    ^ ") is not a variable")
webertj@25014
  2128
                else ()
webertj@25014
  2129
              (* decrement depth for the IDT 'T' *)
webertj@25014
  2130
              val typs' = (case AList.lookup (op =) typs T of NONE => typs
webertj@25014
  2131
                | SOME n => AList.update (op =) (T, n-1) typs)
webertj@25014
  2132
              fun constructor_terms terms [] = terms
webertj@25014
  2133
                | constructor_terms terms (d::ds) =
webertj@25014
  2134
                let
webertj@25014
  2135
                  val dT = typ_of_dtyp descr typ_assoc d
webertj@25014
  2136
                  val d_terms = canonical_terms typs' dT
webertj@25014
  2137
                in
webertj@25014
  2138
                  (* C_i x_1 ... x_n < C_i y_1 ... y_n if *)
webertj@25014
  2139
                  (* (x_1, ..., x_n) < (y_1, ..., y_n)    *)
webertj@25014
  2140
                  constructor_terms
haftmann@25538
  2141
                    (map_product (curry op $) terms d_terms) ds
webertj@25014
  2142
                end
webertj@25014
  2143
            in
webertj@25014
  2144
              (* C_i ... < C_j ... if i < j *)
wenzelm@32952
  2145
              maps (fn (cname, ctyps) =>
webertj@25014
  2146
                let
webertj@25014
  2147
                  val cTerm = Const (cname,
webertj@25014
  2148
                    map (typ_of_dtyp descr typ_assoc) ctyps ---> T)
webertj@25014
  2149
                in
webertj@25014
  2150
                  constructor_terms [cTerm] ctyps
wenzelm@32952
  2151
                end) constrs
webertj@25014
  2152
            end)
webertj@25014
  2153
        | NONE =>
webertj@25014
  2154
          (* not an inductive datatype; in this case the argument types in *)
webertj@25014
  2155
          (* 'Ts' may not be IDTs either, so 'print' should be safe        *)
webertj@25014
  2156
          map (fn intr => print thy (typs, []) T intr (K false))
webertj@25014
  2157
            (make_constants thy (typs, []) T))
webertj@25014
  2158
      | _ =>  (* TFree ..., TVar ... *)
webertj@25014
  2159
        map (fn intr => print thy (typs, []) T intr (K false))
webertj@25014
  2160
          (make_constants thy (typs, []) T))
wenzelm@22567
  2161
    val (typs, terms) = model
wenzelm@22567
  2162
  in
wenzelm@22567
  2163
    case AList.lookup (op =) terms t of
wenzelm@22567
  2164
      SOME intr =>
wenzelm@22567
  2165
      (* return an existing interpretation *)
wenzelm@22567
  2166
      SOME (intr, model, args)
wenzelm@22567
  2167
    | NONE =>
wenzelm@22567
  2168
      (case t of
wenzelm@22567
  2169
        Const (s, T) =>
wenzelm@22567
  2170
        (case body_type T of
wenzelm@22567
  2171
          Type (s', Ts') =>
haftmann@31784
  2172
          (case Datatype.get_info thy s' of
wenzelm@22567
  2173
            SOME info =>  (* body type is an inductive datatype *)
wenzelm@22567
  2174
            let
wenzelm@22567
  2175
              val index               = #index info
wenzelm@22567
  2176
              val descr               = #descr info
wenzelm@29288
  2177
              val (_, dtyps, constrs) = the (AList.lookup (op =) descr index)
wenzelm@22567
  2178
              val typ_assoc           = dtyps ~~ Ts'
wenzelm@22567
  2179
              (* sanity check: every element in 'dtyps' must be a 'DtTFree' *)
webertj@25014
  2180
              val _ = if Library.exists (fn d =>
haftmann@33968
  2181
                  case d of Datatype_Aux.DtTFree _ => false | _ => true) dtyps
wenzelm@22567
  2182
                then
wenzelm@22567
  2183
                  raise REFUTE ("IDT_constructor_interpreter",
wenzelm@22567
  2184
                    "datatype argument (for type "
wenzelm@26939
  2185
                    ^ Syntax.string_of_typ_global thy (Type (s', Ts'))
wenzelm@22567
  2186
                    ^ ") is not a variable")
webertj@25014
  2187
                else ()
wenzelm@22567
  2188
              (* split the constructors into those occuring before/after *)
wenzelm@22567
  2189
              (* 'Const (s, T)'                                          *)
wenzelm@22567
  2190
              val (constrs1, constrs2) = take_prefix (fn (cname, ctypes) =>
wenzelm@22567
  2191
                not (cname = s andalso Sign.typ_instance thy (T,
wenzelm@22567
  2192
                  map (typ_of_dtyp descr typ_assoc) ctypes
wenzelm@22567
  2193
                    ---> Type (s', Ts')))) constrs
wenzelm@22567
  2194
            in
wenzelm@22567
  2195
              case constrs2 of
wenzelm@22567
  2196
                [] =>
wenzelm@22567
  2197
                (* 'Const (s, T)' is not a constructor of this datatype *)
wenzelm@22567
  2198
                NONE
wenzelm@22567
  2199
              | (_, ctypes)::cs =>
wenzelm@22567
  2200
                let
wenzelm@22567
  2201
                  (* int option -- only /recursive/ IDTs have an associated *)
wenzelm@22567
  2202
                  (*               depth                                    *)
wenzelm@22567
  2203
                  val depth = AList.lookup (op =) typs (Type (s', Ts'))
webertj@25014
  2204
                  (* this should never happen: at depth 0, this IDT fragment *)
webertj@25014
  2205
                  (* is definitely empty, and in this case we don't need to  *)
webertj@25014
  2206
                  (* interpret its constructors                              *)
webertj@25014
  2207
                  val _ = (case depth of SOME 0 =>
webertj@25014
  2208
                      raise REFUTE ("IDT_constructor_interpreter",
webertj@25014
  2209
                        "depth is 0")
webertj@25014
  2210
                    | _ => ())
wenzelm@22567
  2211
                  val typs' = (case depth of NONE => typs | SOME n =>
wenzelm@22567
  2212
                    AList.update (op =) (Type (s', Ts'), n-1) typs)
webertj@25014
  2213
                  (* elements of the datatype come before elements generated *)
webertj@25014
  2214
                  (* by 'Const (s, T)' iff they are generated by a           *)
webertj@25014
  2215
                  (* constructor in constrs1                                 *)
webertj@25014
  2216
                  val offset = size_of_dtyp thy typs' descr typ_assoc constrs1
webertj@25014
  2217
                  (* compute the total (current) size of the datatype *)
webertj@25014
  2218
                  val total = offset +
webertj@25014
  2219
                    size_of_dtyp thy typs' descr typ_assoc constrs2
webertj@25014
  2220
                  (* sanity check *)
webertj@25014
  2221
                  val _ = if total <> size_of_type thy (typs, [])
webertj@25014
  2222
                    (Type (s', Ts')) then
webertj@25014
  2223
                      raise REFUTE ("IDT_constructor_interpreter",
webertj@25014
  2224
                        "total is not equal to current size")
webertj@25014
  2225
                    else ()
wenzelm@22567
  2226
                  (* returns an interpretation where everything is mapped to *)
webertj@25014
  2227
                  (* an "undefined" element of the datatype                  *)
wenzelm@22567
  2228
                  fun make_undef [] =
wenzelm@22567
  2229
                    Leaf (replicate total False)
wenzelm@22567
  2230
                    | make_undef (d::ds) =
wenzelm@22567
  2231
                    let
wenzelm@22567
  2232
                      (* compute the current size of the type 'd' *)
webertj@25014
  2233
                      val dT   = typ_of_dtyp descr typ_assoc d
webertj@25014
  2234
                      val size = size_of_type thy (typs, []) dT
wenzelm@22567
  2235
                    in
wenzelm@22567
  2236
                      Node (replicate size (make_undef ds))