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