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