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