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