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