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