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