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