TFL/tfl.ML
author nipkow
Wed May 26 14:57:06 2004 +0200 (2004-05-26)
changeset 14804 8de39d3e8eb6
parent 14240 d3843feb9de7
child 14820 3f80d6510ee9
permissions -rw-r--r--
Corrected printer bug for bounded quantifiers Q x<=y. P
wenzelm@10769
     1
(*  Title:      TFL/tfl.ML
wenzelm@10769
     2
    ID:         $Id$
wenzelm@10769
     3
    Author:     Konrad Slind, Cambridge University Computer Laboratory
wenzelm@10769
     4
    Copyright   1997  University of Cambridge
wenzelm@10769
     5
wenzelm@10769
     6
First part of main module.
wenzelm@10769
     7
*)
wenzelm@10769
     8
wenzelm@10769
     9
signature PRIM =
wenzelm@10769
    10
sig
wenzelm@10769
    11
  val trace: bool ref
paulson@14240
    12
  val trace_thms: string -> thm list -> unit
paulson@14240
    13
  val trace_cterms: string -> cterm list -> unit
wenzelm@10769
    14
  type pattern
wenzelm@10769
    15
  val mk_functional: theory -> term list -> {functional: term, pats: pattern list}
wenzelm@10769
    16
  val wfrec_definition0: theory -> string -> term -> term -> theory * thm
wenzelm@10769
    17
  val post_definition: thm list -> theory * (thm * pattern list) ->
wenzelm@10769
    18
   {theory: theory,
wenzelm@10769
    19
    rules: thm,
wenzelm@10769
    20
    rows: int list,
wenzelm@10769
    21
    TCs: term list list,
wenzelm@10769
    22
    full_pats_TCs: (term * term list) list}
wenzelm@10769
    23
  val wfrec_eqns: theory -> xstring -> thm list -> term list ->
wenzelm@10769
    24
   {WFR: term,
wenzelm@10769
    25
    SV: term list,
wenzelm@10769
    26
    proto_def: term,
wenzelm@10769
    27
    extracta: (thm * term list) list,
wenzelm@10769
    28
    pats: pattern list}
wenzelm@10769
    29
  val lazyR_def: theory -> xstring -> thm list -> term list ->
wenzelm@10769
    30
   {theory: theory,
wenzelm@10769
    31
    rules: thm,
wenzelm@10769
    32
    R: term,
wenzelm@10769
    33
    SV: term list,
wenzelm@10769
    34
    full_pats_TCs: (term * term list) list,
wenzelm@10769
    35
    patterns : pattern list}
wenzelm@10769
    36
  val mk_induction: theory ->
wenzelm@10769
    37
    {fconst: term, R: term, SV: term list, pat_TCs_list: (term * term list) list} -> thm
wenzelm@11632
    38
  val postprocess: bool -> {wf_tac: tactic, terminator: tactic, simplifier: cterm -> thm}
wenzelm@11632
    39
    -> theory -> {rules: thm, induction: thm, TCs: term list list}
wenzelm@11632
    40
    -> {rules: thm, induction: thm, nested_tcs: thm list}
wenzelm@10769
    41
end;
wenzelm@10769
    42
wenzelm@10769
    43
structure Prim: PRIM =
wenzelm@10769
    44
struct
wenzelm@10769
    45
wenzelm@10769
    46
val trace = ref false;
wenzelm@10769
    47
wenzelm@10769
    48
open BasisLibrary;
wenzelm@10769
    49
wenzelm@10769
    50
structure R = Rules;
wenzelm@10769
    51
structure S = USyntax;
wenzelm@10769
    52
structure U = Utils;
wenzelm@10769
    53
wenzelm@10769
    54
wenzelm@10769
    55
fun TFL_ERR func mesg = U.ERR {module = "Tfl", func = func, mesg = mesg};
wenzelm@10769
    56
wenzelm@10769
    57
val concl = #2 o R.dest_thm;
wenzelm@10769
    58
val hyp = #1 o R.dest_thm;
wenzelm@10769
    59
wenzelm@10769
    60
val list_mk_type = U.end_itlist (curry (op -->));
wenzelm@10769
    61
wenzelm@10769
    62
fun enumerate xs = ListPair.zip(xs, 0 upto (length xs - 1));
wenzelm@10769
    63
wenzelm@10769
    64
fun front_last [] = raise TFL_ERR "front_last" "empty list"
wenzelm@10769
    65
  | front_last [x] = ([],x)
wenzelm@10769
    66
  | front_last (h::t) =
wenzelm@10769
    67
     let val (pref,x) = front_last t
wenzelm@10769
    68
     in
wenzelm@10769
    69
        (h::pref,x)
wenzelm@10769
    70
     end;
wenzelm@10769
    71
wenzelm@10769
    72
wenzelm@10769
    73
(*---------------------------------------------------------------------------
wenzelm@10769
    74
 * The next function is common to pattern-match translation and
wenzelm@10769
    75
 * proof of completeness of cases for the induction theorem.
wenzelm@10769
    76
 *
wenzelm@10769
    77
 * The curried function "gvvariant" returns a function to generate distinct
wenzelm@10769
    78
 * variables that are guaranteed not to be in names.  The names of
wenzelm@10769
    79
 * the variables go u, v, ..., z, aa, ..., az, ...  The returned
wenzelm@10769
    80
 * function contains embedded refs!
wenzelm@10769
    81
 *---------------------------------------------------------------------------*)
wenzelm@10769
    82
fun gvvariant names =
wenzelm@10769
    83
  let val slist = ref names
wenzelm@10769
    84
      val vname = ref "u"
wenzelm@10769
    85
      fun new() =
wenzelm@10769
    86
         if !vname mem_string (!slist)
wenzelm@12902
    87
         then (vname := Symbol.bump_string (!vname);  new())
wenzelm@10769
    88
         else (slist := !vname :: !slist;  !vname)
wenzelm@10769
    89
  in
wenzelm@10769
    90
  fn ty => Free(new(), ty)
wenzelm@10769
    91
  end;
wenzelm@10769
    92
wenzelm@10769
    93
wenzelm@10769
    94
(*---------------------------------------------------------------------------
wenzelm@10769
    95
 * Used in induction theorem production. This is the simple case of
wenzelm@10769
    96
 * partitioning up pattern rows by the leading constructor.
wenzelm@10769
    97
 *---------------------------------------------------------------------------*)
wenzelm@10769
    98
fun ipartition gv (constructors,rows) =
wenzelm@10769
    99
  let fun pfail s = raise TFL_ERR "partition.part" s
wenzelm@10769
   100
      fun part {constrs = [],   rows = [],   A} = rev A
wenzelm@10769
   101
        | part {constrs = [],   rows = _::_, A} = pfail"extra cases in defn"
wenzelm@10769
   102
        | part {constrs = _::_, rows = [],   A} = pfail"cases missing in defn"
wenzelm@10769
   103
        | part {constrs = c::crst, rows,     A} =
wenzelm@10769
   104
          let val (Name,Ty) = dest_Const c
wenzelm@10769
   105
              val L = binder_types Ty
wenzelm@10769
   106
              val (in_group, not_in_group) =
wenzelm@10769
   107
               U.itlist (fn (row as (p::rst, rhs)) =>
wenzelm@10769
   108
                         fn (in_group,not_in_group) =>
wenzelm@10769
   109
                  let val (pc,args) = S.strip_comb p
wenzelm@10769
   110
                  in if (#1(dest_Const pc) = Name)
wenzelm@10769
   111
                     then ((args@rst, rhs)::in_group, not_in_group)
wenzelm@10769
   112
                     else (in_group, row::not_in_group)
wenzelm@10769
   113
                  end)      rows ([],[])
wenzelm@10769
   114
              val col_types = U.take type_of (length L, #1(hd in_group))
wenzelm@10769
   115
          in
wenzelm@10769
   116
          part{constrs = crst, rows = not_in_group,
wenzelm@10769
   117
               A = {constructor = c,
wenzelm@10769
   118
                    new_formals = map gv col_types,
wenzelm@10769
   119
                    group = in_group}::A}
wenzelm@10769
   120
          end
wenzelm@10769
   121
  in part{constrs = constructors, rows = rows, A = []}
wenzelm@10769
   122
  end;
wenzelm@10769
   123
wenzelm@10769
   124
wenzelm@10769
   125
wenzelm@10769
   126
(*---------------------------------------------------------------------------
wenzelm@10769
   127
 * Each pattern carries with it a tag (i,b) where
wenzelm@10769
   128
 * i is the clause it came from and
wenzelm@10769
   129
 * b=true indicates that clause was given by the user
wenzelm@10769
   130
 * (or is an instantiation of a user supplied pattern)
wenzelm@10769
   131
 * b=false --> i = ~1
wenzelm@10769
   132
 *---------------------------------------------------------------------------*)
wenzelm@10769
   133
wenzelm@10769
   134
type pattern = term * (int * bool)
wenzelm@10769
   135
wenzelm@10769
   136
fun pattern_map f (tm,x) = (f tm, x);
wenzelm@10769
   137
wenzelm@10769
   138
fun pattern_subst theta = pattern_map (subst_free theta);
wenzelm@10769
   139
wenzelm@10769
   140
val pat_of = fst;
wenzelm@10769
   141
fun row_of_pat x = fst (snd x);
wenzelm@10769
   142
fun given x = snd (snd x);
wenzelm@10769
   143
wenzelm@10769
   144
(*---------------------------------------------------------------------------
wenzelm@10769
   145
 * Produce an instance of a constructor, plus genvars for its arguments.
wenzelm@10769
   146
 *---------------------------------------------------------------------------*)
wenzelm@10769
   147
fun fresh_constr ty_match colty gv c =
wenzelm@10769
   148
  let val (_,Ty) = dest_Const c
wenzelm@10769
   149
      val L = binder_types Ty
wenzelm@10769
   150
      and ty = body_type Ty
wenzelm@10769
   151
      val ty_theta = ty_match ty colty
wenzelm@10769
   152
      val c' = S.inst ty_theta c
wenzelm@10769
   153
      val gvars = map (S.inst ty_theta o gv) L
wenzelm@10769
   154
  in (c', gvars)
wenzelm@10769
   155
  end;
wenzelm@10769
   156
wenzelm@10769
   157
wenzelm@10769
   158
(*---------------------------------------------------------------------------
wenzelm@10769
   159
 * Goes through a list of rows and picks out the ones beginning with a
wenzelm@10769
   160
 * pattern with constructor = Name.
wenzelm@10769
   161
 *---------------------------------------------------------------------------*)
wenzelm@10769
   162
fun mk_group Name rows =
wenzelm@10769
   163
  U.itlist (fn (row as ((prfx, p::rst), rhs)) =>
wenzelm@10769
   164
            fn (in_group,not_in_group) =>
wenzelm@10769
   165
               let val (pc,args) = S.strip_comb p
wenzelm@10769
   166
               in if ((#1 (Term.dest_Const pc) = Name) handle TERM _ => false)
wenzelm@10769
   167
                  then (((prfx,args@rst), rhs)::in_group, not_in_group)
wenzelm@10769
   168
                  else (in_group, row::not_in_group) end)
wenzelm@10769
   169
      rows ([],[]);
wenzelm@10769
   170
wenzelm@10769
   171
(*---------------------------------------------------------------------------
wenzelm@10769
   172
 * Partition the rows. Not efficient: we should use hashing.
wenzelm@10769
   173
 *---------------------------------------------------------------------------*)
wenzelm@10769
   174
fun partition _ _ (_,_,_,[]) = raise TFL_ERR "partition" "no rows"
wenzelm@10769
   175
  | partition gv ty_match
wenzelm@10769
   176
              (constructors, colty, res_ty, rows as (((prfx,_),_)::_)) =
wenzelm@10769
   177
let val fresh = fresh_constr ty_match colty gv
wenzelm@10769
   178
     fun part {constrs = [],      rows, A} = rev A
wenzelm@10769
   179
       | part {constrs = c::crst, rows, A} =
wenzelm@10769
   180
         let val (c',gvars) = fresh c
wenzelm@10769
   181
             val (Name,Ty) = dest_Const c'
wenzelm@10769
   182
             val (in_group, not_in_group) = mk_group Name rows
wenzelm@10769
   183
             val in_group' =
wenzelm@10769
   184
                 if (null in_group)  (* Constructor not given *)
wenzelm@10769
   185
                 then [((prfx, #2(fresh c)), (S.ARB res_ty, (~1,false)))]
wenzelm@10769
   186
                 else in_group
wenzelm@10769
   187
         in
wenzelm@10769
   188
         part{constrs = crst,
wenzelm@10769
   189
              rows = not_in_group,
wenzelm@10769
   190
              A = {constructor = c',
wenzelm@10769
   191
                   new_formals = gvars,
wenzelm@10769
   192
                   group = in_group'}::A}
wenzelm@10769
   193
         end
wenzelm@10769
   194
in part{constrs=constructors, rows=rows, A=[]}
wenzelm@10769
   195
end;
wenzelm@10769
   196
wenzelm@10769
   197
(*---------------------------------------------------------------------------
wenzelm@10769
   198
 * Misc. routines used in mk_case
wenzelm@10769
   199
 *---------------------------------------------------------------------------*)
wenzelm@10769
   200
wenzelm@10769
   201
fun mk_pat (c,l) =
wenzelm@10769
   202
  let val L = length (binder_types (type_of c))
wenzelm@10769
   203
      fun build (prfx,tag,plist) =
wenzelm@10769
   204
          let val args   = take (L,plist)
wenzelm@10769
   205
              and plist' = drop(L,plist)
wenzelm@10769
   206
          in (prfx,tag,list_comb(c,args)::plist') end
wenzelm@10769
   207
  in map build l end;
wenzelm@10769
   208
wenzelm@10769
   209
fun v_to_prfx (prfx, v::pats) = (v::prfx,pats)
wenzelm@10769
   210
  | v_to_prfx _ = raise TFL_ERR "mk_case" "v_to_prfx";
wenzelm@10769
   211
wenzelm@10769
   212
fun v_to_pats (v::prfx,tag, pats) = (prfx, tag, v::pats)
wenzelm@10769
   213
  | v_to_pats _ = raise TFL_ERR "mk_case" "v_to_pats";
wenzelm@10769
   214
wenzelm@10769
   215
wenzelm@10769
   216
(*----------------------------------------------------------------------------
wenzelm@10769
   217
 * Translation of pattern terms into nested case expressions.
wenzelm@10769
   218
 *
wenzelm@10769
   219
 * This performs the translation and also builds the full set of patterns.
wenzelm@10769
   220
 * Thus it supports the construction of induction theorems even when an
wenzelm@10769
   221
 * incomplete set of patterns is given.
wenzelm@10769
   222
 *---------------------------------------------------------------------------*)
wenzelm@10769
   223
wenzelm@10769
   224
fun mk_case ty_info ty_match usednames range_ty =
wenzelm@10769
   225
 let
wenzelm@10769
   226
 fun mk_case_fail s = raise TFL_ERR "mk_case" s
wenzelm@10769
   227
 val fresh_var = gvvariant usednames
wenzelm@10769
   228
 val divide = partition fresh_var ty_match
wenzelm@10769
   229
 fun expand constructors ty ((_,[]), _) = mk_case_fail"expand_var_row"
wenzelm@10769
   230
   | expand constructors ty (row as ((prfx, p::rst), rhs)) =
wenzelm@10769
   231
       if (is_Free p)
wenzelm@10769
   232
       then let val fresh = fresh_constr ty_match ty fresh_var
wenzelm@10769
   233
                fun expnd (c,gvs) =
wenzelm@10769
   234
                  let val capp = list_comb(c,gvs)
wenzelm@10769
   235
                  in ((prfx, capp::rst), pattern_subst[(p,capp)] rhs)
wenzelm@10769
   236
                  end
wenzelm@10769
   237
            in map expnd (map fresh constructors)  end
wenzelm@10769
   238
       else [row]
wenzelm@10769
   239
 fun mk{rows=[],...} = mk_case_fail"no rows"
wenzelm@10769
   240
   | mk{path=[], rows = ((prfx, []), (tm,tag))::_} =  (* Done *)
wenzelm@10769
   241
        ([(prfx,tag,[])], tm)
wenzelm@10769
   242
   | mk{path=[], rows = _::_} = mk_case_fail"blunder"
wenzelm@10769
   243
   | mk{path as u::rstp, rows as ((prfx, []), rhs)::rst} =
wenzelm@10769
   244
        mk{path = path,
wenzelm@10769
   245
           rows = ((prfx, [fresh_var(type_of u)]), rhs)::rst}
wenzelm@10769
   246
   | mk{path = u::rstp, rows as ((_, p::_), _)::_} =
wenzelm@10769
   247
     let val (pat_rectangle,rights) = ListPair.unzip rows
wenzelm@10769
   248
         val col0 = map(hd o #2) pat_rectangle
wenzelm@10769
   249
     in
wenzelm@10769
   250
     if (forall is_Free col0)
wenzelm@10769
   251
     then let val rights' = map (fn(v,e) => pattern_subst[(v,u)] e)
wenzelm@10769
   252
                                (ListPair.zip (col0, rights))
wenzelm@10769
   253
              val pat_rectangle' = map v_to_prfx pat_rectangle
wenzelm@10769
   254
              val (pref_patl,tm) = mk{path = rstp,
wenzelm@10769
   255
                                      rows = ListPair.zip (pat_rectangle',
wenzelm@10769
   256
                                                           rights')}
wenzelm@10769
   257
          in (map v_to_pats pref_patl, tm)
wenzelm@10769
   258
          end
wenzelm@10769
   259
     else
wenzelm@10769
   260
     let val pty as Type (ty_name,_) = type_of p
wenzelm@10769
   261
     in
wenzelm@10769
   262
     case (ty_info ty_name)
wenzelm@10769
   263
     of None => mk_case_fail("Not a known datatype: "^ty_name)
wenzelm@10769
   264
      | Some{case_const,constructors} =>
wenzelm@10769
   265
        let
wenzelm@10769
   266
            val case_const_name = #1(dest_Const case_const)
wenzelm@10769
   267
            val nrows = List.concat (map (expand constructors pty) rows)
wenzelm@10769
   268
            val subproblems = divide(constructors, pty, range_ty, nrows)
wenzelm@10769
   269
            val groups      = map #group subproblems
wenzelm@10769
   270
            and new_formals = map #new_formals subproblems
wenzelm@10769
   271
            and constructors' = map #constructor subproblems
wenzelm@10769
   272
            val news = map (fn (nf,rows) => {path = nf@rstp, rows=rows})
wenzelm@10769
   273
                           (ListPair.zip (new_formals, groups))
wenzelm@10769
   274
            val rec_calls = map mk news
wenzelm@10769
   275
            val (pat_rect,dtrees) = ListPair.unzip rec_calls
wenzelm@10769
   276
            val case_functions = map S.list_mk_abs
wenzelm@10769
   277
                                  (ListPair.zip (new_formals, dtrees))
wenzelm@10769
   278
            val types = map type_of (case_functions@[u]) @ [range_ty]
wenzelm@10769
   279
            val case_const' = Const(case_const_name, list_mk_type types)
wenzelm@10769
   280
            val tree = list_comb(case_const', case_functions@[u])
wenzelm@10769
   281
            val pat_rect1 = List.concat
wenzelm@10769
   282
                              (ListPair.map mk_pat (constructors', pat_rect))
wenzelm@10769
   283
        in (pat_rect1,tree)
wenzelm@10769
   284
        end
wenzelm@10769
   285
     end end
wenzelm@10769
   286
 in mk
wenzelm@10769
   287
 end;
wenzelm@10769
   288
wenzelm@10769
   289
wenzelm@10769
   290
(* Repeated variable occurrences in a pattern are not allowed. *)
wenzelm@10769
   291
fun FV_multiset tm =
wenzelm@10769
   292
   case (S.dest_term tm)
wenzelm@10769
   293
     of S.VAR{Name,Ty} => [Free(Name,Ty)]
wenzelm@10769
   294
      | S.CONST _ => []
wenzelm@10769
   295
      | S.COMB{Rator, Rand} => FV_multiset Rator @ FV_multiset Rand
wenzelm@10769
   296
      | S.LAMB _ => raise TFL_ERR "FV_multiset" "lambda";
wenzelm@10769
   297
wenzelm@10769
   298
fun no_repeat_vars thy pat =
wenzelm@10769
   299
 let fun check [] = true
wenzelm@10769
   300
       | check (v::rst) =
wenzelm@10769
   301
         if mem_term (v,rst) then
wenzelm@10769
   302
            raise TFL_ERR "no_repeat_vars"
wenzelm@10769
   303
                          (quote (#1 (dest_Free v)) ^
wenzelm@10769
   304
                          " occurs repeatedly in the pattern " ^
wenzelm@10769
   305
                          quote (string_of_cterm (Thry.typecheck thy pat)))
wenzelm@10769
   306
         else check rst
wenzelm@10769
   307
 in check (FV_multiset pat)
wenzelm@10769
   308
 end;
wenzelm@10769
   309
wenzelm@10769
   310
fun dest_atom (Free p) = p
wenzelm@10769
   311
  | dest_atom (Const p) = p
wenzelm@10769
   312
  | dest_atom  _ = raise TFL_ERR "dest_atom" "function name not an identifier";
wenzelm@10769
   313
wenzelm@10769
   314
fun same_name (p,q) = #1(dest_atom p) = #1(dest_atom q);
wenzelm@10769
   315
wenzelm@10769
   316
local fun mk_functional_err s = raise TFL_ERR "mk_functional" s
wenzelm@10769
   317
      fun single [_$_] =
wenzelm@10769
   318
              mk_functional_err "recdef does not allow currying"
wenzelm@10769
   319
        | single [f] = f
wenzelm@10769
   320
        | single fs  =
wenzelm@10769
   321
              (*multiple function names?*)
wenzelm@10769
   322
              if length (gen_distinct same_name fs) < length fs
wenzelm@10769
   323
              then mk_functional_err
wenzelm@10769
   324
                   "The function being declared appears with multiple types"
wenzelm@10769
   325
              else mk_functional_err
wenzelm@10769
   326
                   (Int.toString (length fs) ^
wenzelm@10769
   327
                    " distinct function names being declared")
wenzelm@10769
   328
in
wenzelm@10769
   329
fun mk_functional thy clauses =
wenzelm@10769
   330
 let val (L,R) = ListPair.unzip (map HOLogic.dest_eq clauses
wenzelm@10769
   331
                   handle TERM _ => raise TFL_ERR "mk_functional"
wenzelm@10769
   332
                        "recursion equations must use the = relation")
wenzelm@10769
   333
     val (funcs,pats) = ListPair.unzip (map (fn (t$u) =>(t,u)) L)
wenzelm@10769
   334
     val atom = single (gen_distinct (op aconv) funcs)
wenzelm@10769
   335
     val (fname,ftype) = dest_atom atom
wenzelm@10769
   336
     val dummy = map (no_repeat_vars thy) pats
wenzelm@10769
   337
     val rows = ListPair.zip (map (fn x => ([]:term list,[x])) pats,
wenzelm@10769
   338
                              map (fn (t,i) => (t,(i,true))) (enumerate R))
wenzelm@10769
   339
     val names = foldr add_term_names (R,[])
wenzelm@10769
   340
     val atype = type_of(hd pats)
wenzelm@10769
   341
     and aname = variant names "a"
wenzelm@10769
   342
     val a = Free(aname,atype)
wenzelm@10769
   343
     val ty_info = Thry.match_info thy
wenzelm@10769
   344
     val ty_match = Thry.match_type thy
wenzelm@10769
   345
     val range_ty = type_of (hd R)
wenzelm@10769
   346
     val (patts, case_tm) = mk_case ty_info ty_match (aname::names) range_ty
wenzelm@10769
   347
                                    {path=[a], rows=rows}
wenzelm@10769
   348
     val patts1 = map (fn (_,tag,[pat]) => (pat,tag)) patts
wenzelm@10769
   349
          handle Match => mk_functional_err "error in pattern-match translation"
wenzelm@10769
   350
     val patts2 = Library.sort (Library.int_ord o Library.pairself row_of_pat) patts1
wenzelm@10769
   351
     val finals = map row_of_pat patts2
wenzelm@10769
   352
     val originals = map (row_of_pat o #2) rows
wenzelm@10769
   353
     val dummy = case (originals\\finals)
wenzelm@10769
   354
             of [] => ()
wenzelm@10769
   355
          | L => mk_functional_err
wenzelm@10769
   356
 ("The following clauses are redundant (covered by preceding clauses): " ^
wenzelm@10769
   357
                   commas (map (fn i => Int.toString (i + 1)) L))
wenzelm@10769
   358
 in {functional = Abs(Sign.base_name fname, ftype,
wenzelm@10769
   359
                      abstract_over (atom,
wenzelm@10769
   360
                                     absfree(aname,atype, case_tm))),
wenzelm@10769
   361
     pats = patts2}
wenzelm@10769
   362
end end;
wenzelm@10769
   363
wenzelm@10769
   364
wenzelm@10769
   365
(*----------------------------------------------------------------------------
wenzelm@10769
   366
 *
wenzelm@10769
   367
 *                    PRINCIPLES OF DEFINITION
wenzelm@10769
   368
 *
wenzelm@10769
   369
 *---------------------------------------------------------------------------*)
wenzelm@10769
   370
wenzelm@10769
   371
wenzelm@10769
   372
(*For Isabelle, the lhs of a definition must be a constant.*)
wenzelm@10769
   373
fun mk_const_def sign (Name, Ty, rhs) =
wenzelm@10769
   374
    Sign.infer_types sign (K None) (K None) [] false
wenzelm@10769
   375
               ([Const("==",dummyT) $ Const(Name,Ty) $ rhs], propT)
wenzelm@10769
   376
    |> #1;
wenzelm@10769
   377
wenzelm@10769
   378
(*Make all TVars available for instantiation by adding a ? to the front*)
wenzelm@10769
   379
fun poly_tvars (Type(a,Ts)) = Type(a, map (poly_tvars) Ts)
wenzelm@10769
   380
  | poly_tvars (TFree (a,sort)) = TVar (("?" ^ a, 0), sort)
wenzelm@10769
   381
  | poly_tvars (TVar ((a,i),sort)) = TVar (("?" ^ a, i+1), sort);
wenzelm@10769
   382
wenzelm@10769
   383
local val f_eq_wfrec_R_M =
wenzelm@10769
   384
           #ant(S.dest_imp(#2(S.strip_forall (concl Thms.WFREC_COROLLARY))))
wenzelm@10769
   385
      val {lhs=f, rhs} = S.dest_eq f_eq_wfrec_R_M
wenzelm@10769
   386
      val (fname,_) = dest_Free f
wenzelm@10769
   387
      val (wfrec,_) = S.strip_comb rhs
wenzelm@10769
   388
in
wenzelm@10769
   389
fun wfrec_definition0 thy fid R (functional as Abs(Name, Ty, _)) =
wenzelm@10769
   390
 let val def_name = if Name<>fid then
wenzelm@10769
   391
                        raise TFL_ERR "wfrec_definition0"
wenzelm@10769
   392
                                      ("Expected a definition of " ^
wenzelm@10769
   393
                                             quote fid ^ " but found one of " ^
wenzelm@10769
   394
                                      quote Name)
wenzelm@10769
   395
                    else Name ^ "_def"
wenzelm@10769
   396
     val wfrec_R_M =  map_term_types poly_tvars
wenzelm@10769
   397
                          (wfrec $ map_term_types poly_tvars R)
wenzelm@10769
   398
                      $ functional
wenzelm@10769
   399
     val def_term = mk_const_def (Theory.sign_of thy) (Name, Ty, wfrec_R_M)
wenzelm@10769
   400
     val (thy', [def]) = PureThy.add_defs_i false [Thm.no_attributes (def_name, def_term)] thy
wenzelm@10769
   401
 in (thy', def) end;
wenzelm@10769
   402
end;
wenzelm@10769
   403
wenzelm@10769
   404
wenzelm@10769
   405
wenzelm@10769
   406
(*---------------------------------------------------------------------------
wenzelm@10769
   407
 * This structure keeps track of congruence rules that aren't derived
wenzelm@10769
   408
 * from a datatype definition.
wenzelm@10769
   409
 *---------------------------------------------------------------------------*)
wenzelm@10769
   410
fun extraction_thms thy =
wenzelm@10769
   411
 let val {case_rewrites,case_congs} = Thry.extract_info thy
wenzelm@10769
   412
 in (case_rewrites, case_congs)
wenzelm@10769
   413
 end;
wenzelm@10769
   414
wenzelm@10769
   415
wenzelm@10769
   416
(*---------------------------------------------------------------------------
wenzelm@10769
   417
 * Pair patterns with termination conditions. The full list of patterns for
wenzelm@10769
   418
 * a definition is merged with the TCs arising from the user-given clauses.
wenzelm@10769
   419
 * There can be fewer clauses than the full list, if the user omitted some
wenzelm@10769
   420
 * cases. This routine is used to prepare input for mk_induction.
wenzelm@10769
   421
 *---------------------------------------------------------------------------*)
wenzelm@10769
   422
fun merge full_pats TCs =
wenzelm@10769
   423
let fun insert (p,TCs) =
wenzelm@10769
   424
      let fun insrt ((x as (h,[]))::rst) =
wenzelm@10769
   425
                 if (p aconv h) then (p,TCs)::rst else x::insrt rst
wenzelm@10769
   426
            | insrt (x::rst) = x::insrt rst
wenzelm@10769
   427
            | insrt[] = raise TFL_ERR "merge.insert" "pattern not found"
wenzelm@10769
   428
      in insrt end
wenzelm@10769
   429
    fun pass ([],ptcl_final) = ptcl_final
wenzelm@10769
   430
      | pass (ptcs::tcl, ptcl) = pass(tcl, insert ptcs ptcl)
wenzelm@10769
   431
in
wenzelm@10769
   432
  pass (TCs, map (fn p => (p,[])) full_pats)
wenzelm@10769
   433
end;
wenzelm@10769
   434
wenzelm@10769
   435
wenzelm@10769
   436
fun givens pats = map pat_of (filter given pats);
wenzelm@10769
   437
wenzelm@10769
   438
fun post_definition meta_tflCongs (theory, (def, pats)) =
wenzelm@10769
   439
 let val tych = Thry.typecheck theory
wenzelm@10769
   440
     val f = #lhs(S.dest_eq(concl def))
wenzelm@10769
   441
     val corollary = R.MATCH_MP Thms.WFREC_COROLLARY def
wenzelm@10769
   442
     val pats' = filter given pats
wenzelm@10769
   443
     val given_pats = map pat_of pats'
wenzelm@10769
   444
     val rows = map row_of_pat pats'
wenzelm@10769
   445
     val WFR = #ant(S.dest_imp(concl corollary))
wenzelm@10769
   446
     val R = #Rand(S.dest_comb WFR)
wenzelm@10769
   447
     val corollary' = R.UNDISCH corollary  (* put WF R on assums *)
wenzelm@10769
   448
     val corollaries = map (fn pat => R.SPEC (tych pat) corollary')
wenzelm@10769
   449
                           given_pats
wenzelm@10769
   450
     val (case_rewrites,context_congs) = extraction_thms theory
paulson@14219
   451
     (*case_ss causes minimal simplification: bodies of case expressions are
paulson@14219
   452
       not simplified. Otherwise large examples (Red-Black trees) are too 
paulson@14219
   453
       slow.*)
berghofe@14217
   454
     val case_ss = HOL_basic_ss addcongs
berghofe@14217
   455
       DatatypePackage.weak_case_congs_of theory addsimps case_rewrites
berghofe@14217
   456
     val corollaries' = map (Simplifier.simplify case_ss) corollaries
wenzelm@10769
   457
     val extract = R.CONTEXT_REWRITE_RULE
wenzelm@10769
   458
                     (f, [R], cut_apply, meta_tflCongs@context_congs)
wenzelm@10769
   459
     val (rules, TCs) = ListPair.unzip (map extract corollaries')
wenzelm@10769
   460
     val rules0 = map (rewrite_rule [Thms.CUT_DEF]) rules
wenzelm@10769
   461
     val mk_cond_rule = R.FILTER_DISCH_ALL(not o curry (op aconv) WFR)
wenzelm@10769
   462
     val rules1 = R.LIST_CONJ(map mk_cond_rule rules0)
wenzelm@10769
   463
 in
wenzelm@10769
   464
 {theory = theory,
wenzelm@10769
   465
  rules = rules1,
wenzelm@10769
   466
  rows = rows,
wenzelm@10769
   467
  full_pats_TCs = merge (map pat_of pats) (ListPair.zip (given_pats, TCs)),
wenzelm@10769
   468
  TCs = TCs}
wenzelm@10769
   469
 end;
wenzelm@10769
   470
wenzelm@10769
   471
wenzelm@10769
   472
(*---------------------------------------------------------------------------
wenzelm@10769
   473
 * Perform the extraction without making the definition. Definition and
wenzelm@10769
   474
 * extraction commute for the non-nested case.  (Deferred recdefs)
wenzelm@10769
   475
 *
wenzelm@10769
   476
 * The purpose of wfrec_eqns is merely to instantiate the recursion theorem
wenzelm@10769
   477
 * and extract termination conditions: no definition is made.
wenzelm@10769
   478
 *---------------------------------------------------------------------------*)
wenzelm@10769
   479
wenzelm@10769
   480
fun wfrec_eqns thy fid tflCongs eqns =
wenzelm@10769
   481
 let val {lhs,rhs} = S.dest_eq (hd eqns)
wenzelm@10769
   482
     val (f,args) = S.strip_comb lhs
wenzelm@10769
   483
     val (fname,fty) = dest_atom f
wenzelm@10769
   484
     val (SV,a) = front_last args    (* SV = schematic variables *)
wenzelm@10769
   485
     val g = list_comb(f,SV)
wenzelm@10769
   486
     val h = Free(fname,type_of g)
wenzelm@10769
   487
     val eqns1 = map (subst_free[(g,h)]) eqns
wenzelm@10769
   488
     val {functional as Abs(Name, Ty, _),  pats} = mk_functional thy eqns1
wenzelm@10769
   489
     val given_pats = givens pats
wenzelm@10769
   490
     (* val f = Free(Name,Ty) *)
wenzelm@10769
   491
     val Type("fun", [f_dty, f_rty]) = Ty
wenzelm@10769
   492
     val dummy = if Name<>fid then
wenzelm@10769
   493
                        raise TFL_ERR "wfrec_eqns"
wenzelm@10769
   494
                                      ("Expected a definition of " ^
wenzelm@10769
   495
                                      quote fid ^ " but found one of " ^
wenzelm@10769
   496
                                      quote Name)
wenzelm@10769
   497
                 else ()
wenzelm@10769
   498
     val (case_rewrites,context_congs) = extraction_thms thy
wenzelm@10769
   499
     val tych = Thry.typecheck thy
wenzelm@10769
   500
     val WFREC_THM0 = R.ISPEC (tych functional) Thms.WFREC_COROLLARY
wenzelm@10769
   501
     val Const("All",_) $ Abs(Rname,Rtype,_) = concl WFREC_THM0
wenzelm@10769
   502
     val R = Free (variant (foldr add_term_names (eqns,[])) Rname,
wenzelm@10769
   503
                   Rtype)
wenzelm@10769
   504
     val WFREC_THM = R.ISPECL [tych R, tych g] WFREC_THM0
wenzelm@10769
   505
     val ([proto_def, WFR],_) = S.strip_imp(concl WFREC_THM)
wenzelm@10769
   506
     val dummy =
wenzelm@10769
   507
           if !trace then
wenzelm@10769
   508
               writeln ("ORIGINAL PROTO_DEF: " ^
wenzelm@10769
   509
                          Sign.string_of_term (Theory.sign_of thy) proto_def)
wenzelm@10769
   510
           else ()
wenzelm@10769
   511
     val R1 = S.rand WFR
wenzelm@10769
   512
     val corollary' = R.UNDISCH(R.UNDISCH WFREC_THM)
wenzelm@10769
   513
     val corollaries = map (fn pat => R.SPEC (tych pat) corollary') given_pats
wenzelm@10769
   514
     val corollaries' = map (rewrite_rule case_rewrites) corollaries
wenzelm@10769
   515
     fun extract X = R.CONTEXT_REWRITE_RULE
wenzelm@10769
   516
                       (f, R1::SV, cut_apply, tflCongs@context_congs) X
wenzelm@10769
   517
 in {proto_def = proto_def,
wenzelm@10769
   518
     SV=SV,
wenzelm@10769
   519
     WFR=WFR,
wenzelm@10769
   520
     pats=pats,
wenzelm@10769
   521
     extracta = map extract corollaries'}
wenzelm@10769
   522
 end;
wenzelm@10769
   523
wenzelm@10769
   524
wenzelm@10769
   525
(*---------------------------------------------------------------------------
wenzelm@10769
   526
 * Define the constant after extracting the termination conditions. The
wenzelm@10769
   527
 * wellfounded relation used in the definition is computed by using the
wenzelm@10769
   528
 * choice operator on the extracted conditions (plus the condition that
wenzelm@10769
   529
 * such a relation must be wellfounded).
wenzelm@10769
   530
 *---------------------------------------------------------------------------*)
wenzelm@10769
   531
wenzelm@10769
   532
fun lazyR_def thy fid tflCongs eqns =
wenzelm@10769
   533
 let val {proto_def,WFR,pats,extracta,SV} =
wenzelm@10769
   534
           wfrec_eqns thy fid tflCongs eqns
wenzelm@10769
   535
     val R1 = S.rand WFR
wenzelm@10769
   536
     val f = #lhs(S.dest_eq proto_def)
wenzelm@10769
   537
     val (extractants,TCl) = ListPair.unzip extracta
wenzelm@10769
   538
     val dummy = if !trace
wenzelm@10769
   539
                 then (writeln "Extractants = ";
wenzelm@10769
   540
                       prths extractants;
wenzelm@10769
   541
                       ())
wenzelm@10769
   542
                 else ()
wenzelm@10769
   543
     val TCs = foldr (gen_union (op aconv)) (TCl, [])
wenzelm@10769
   544
     val full_rqt = WFR::TCs
wenzelm@10769
   545
     val R' = S.mk_select{Bvar=R1, Body=S.list_mk_conj full_rqt}
wenzelm@10769
   546
     val R'abs = S.rand R'
wenzelm@10769
   547
     val proto_def' = subst_free[(R1,R')] proto_def
wenzelm@10769
   548
     val dummy = if !trace then writeln ("proto_def' = " ^
wenzelm@10769
   549
                                         Sign.string_of_term
wenzelm@10769
   550
                                         (Theory.sign_of thy) proto_def')
wenzelm@10769
   551
                           else ()
wenzelm@10769
   552
     val {lhs,rhs} = S.dest_eq proto_def'
wenzelm@10769
   553
     val (c,args) = S.strip_comb lhs
wenzelm@10769
   554
     val (Name,Ty) = dest_atom c
wenzelm@10769
   555
     val defn = mk_const_def (Theory.sign_of thy)
wenzelm@10769
   556
                 (Name, Ty, S.list_mk_abs (args,rhs))
wenzelm@10769
   557
     val (theory, [def0]) =
wenzelm@10769
   558
       thy
wenzelm@10769
   559
       |> PureThy.add_defs_i false
wenzelm@10769
   560
            [Thm.no_attributes (fid ^ "_def", defn)]
wenzelm@10769
   561
     val def = freezeT def0;
wenzelm@10769
   562
     val dummy = if !trace then writeln ("DEF = " ^ string_of_thm def)
wenzelm@10769
   563
                           else ()
wenzelm@10769
   564
     (* val fconst = #lhs(S.dest_eq(concl def))  *)
wenzelm@10769
   565
     val tych = Thry.typecheck theory
wenzelm@10769
   566
     val full_rqt_prop = map (Dcterm.mk_prop o tych) full_rqt
wenzelm@10769
   567
         (*lcp: a lot of object-logic inference to remove*)
wenzelm@10769
   568
     val baz = R.DISCH_ALL
wenzelm@10769
   569
                 (U.itlist R.DISCH full_rqt_prop
wenzelm@10769
   570
                  (R.LIST_CONJ extractants))
wenzelm@10769
   571
     val dum = if !trace then writeln ("baz = " ^ string_of_thm baz)
wenzelm@10769
   572
                           else ()
wenzelm@10769
   573
     val f_free = Free (fid, fastype_of f)  (*'cos f is a Const*)
wenzelm@10769
   574
     val SV' = map tych SV;
wenzelm@10769
   575
     val SVrefls = map reflexive SV'
wenzelm@10769
   576
     val def0 = (U.rev_itlist (fn x => fn th => R.rbeta(combination th x))
wenzelm@10769
   577
                   SVrefls def)
wenzelm@10769
   578
                RS meta_eq_to_obj_eq
wenzelm@10769
   579
     val def' = R.MP (R.SPEC (tych R') (R.GEN (tych R1) baz)) def0
wenzelm@10769
   580
     val body_th = R.LIST_CONJ (map R.ASSUME full_rqt_prop)
paulson@11455
   581
     val SELECT_AX = (*in this way we hope to avoid a STATIC dependence upon
paulson@11455
   582
                       theory Hilbert_Choice*)
paulson@11455
   583
         thm "Hilbert_Choice.tfl_some" 
paulson@11455
   584
         handle ERROR => error
paulson@11455
   585
    "defer_recdef requires theory Main or at least Hilbert_Choice as parent"
paulson@11455
   586
     val bar = R.MP (R.ISPECL[tych R'abs, tych R1] SELECT_AX) body_th
wenzelm@10769
   587
 in {theory = theory, R=R1, SV=SV,
wenzelm@10769
   588
     rules = U.rev_itlist (U.C R.MP) (R.CONJUNCTS bar) def',
wenzelm@10769
   589
     full_pats_TCs = merge (map pat_of pats) (ListPair.zip (givens pats, TCl)),
wenzelm@10769
   590
     patterns = pats}
wenzelm@10769
   591
 end;
wenzelm@10769
   592
wenzelm@10769
   593
wenzelm@10769
   594
wenzelm@10769
   595
(*----------------------------------------------------------------------------
wenzelm@10769
   596
 *
wenzelm@10769
   597
 *                           INDUCTION THEOREM
wenzelm@10769
   598
 *
wenzelm@10769
   599
 *---------------------------------------------------------------------------*)
wenzelm@10769
   600
wenzelm@10769
   601
wenzelm@10769
   602
(*------------------------  Miscellaneous function  --------------------------
wenzelm@10769
   603
 *
wenzelm@10769
   604
 *           [x_1,...,x_n]     ?v_1...v_n. M[v_1,...,v_n]
wenzelm@10769
   605
 *     -----------------------------------------------------------
wenzelm@10769
   606
 *     ( M[x_1,...,x_n], [(x_i,?v_1...v_n. M[v_1,...,v_n]),
wenzelm@10769
   607
 *                        ...
wenzelm@10769
   608
 *                        (x_j,?v_n. M[x_1,...,x_(n-1),v_n])] )
wenzelm@10769
   609
 *
wenzelm@10769
   610
 * This function is totally ad hoc. Used in the production of the induction
wenzelm@10769
   611
 * theorem. The nchotomy theorem can have clauses that look like
wenzelm@10769
   612
 *
wenzelm@10769
   613
 *     ?v1..vn. z = C vn..v1
wenzelm@10769
   614
 *
wenzelm@10769
   615
 * in which the order of quantification is not the order of occurrence of the
wenzelm@10769
   616
 * quantified variables as arguments to C. Since we have no control over this
wenzelm@10769
   617
 * aspect of the nchotomy theorem, we make the correspondence explicit by
wenzelm@10769
   618
 * pairing the incoming new variable with the term it gets beta-reduced into.
wenzelm@10769
   619
 *---------------------------------------------------------------------------*)
wenzelm@10769
   620
wenzelm@10769
   621
fun alpha_ex_unroll (xlist, tm) =
wenzelm@10769
   622
  let val (qvars,body) = S.strip_exists tm
wenzelm@10769
   623
      val vlist = #2(S.strip_comb (S.rhs body))
wenzelm@10769
   624
      val plist = ListPair.zip (vlist, xlist)
wenzelm@10769
   625
      val args = map (fn qv => the (gen_assoc (op aconv) (plist, qv))) qvars
wenzelm@10769
   626
                   handle Library.OPTION => sys_error
wenzelm@10769
   627
                       "TFL fault [alpha_ex_unroll]: no correspondence"
wenzelm@10769
   628
      fun build ex      []   = []
wenzelm@10769
   629
        | build (_$rex) (v::rst) =
wenzelm@10769
   630
           let val ex1 = betapply(rex, v)
wenzelm@10769
   631
           in  ex1 :: build ex1 rst
wenzelm@10769
   632
           end
wenzelm@10769
   633
     val (nex::exl) = rev (tm::build tm args)
wenzelm@10769
   634
  in
wenzelm@10769
   635
  (nex, ListPair.zip (args, rev exl))
wenzelm@10769
   636
  end;
wenzelm@10769
   637
wenzelm@10769
   638
wenzelm@10769
   639
wenzelm@10769
   640
(*----------------------------------------------------------------------------
wenzelm@10769
   641
 *
wenzelm@10769
   642
 *             PROVING COMPLETENESS OF PATTERNS
wenzelm@10769
   643
 *
wenzelm@10769
   644
 *---------------------------------------------------------------------------*)
wenzelm@10769
   645
wenzelm@10769
   646
fun mk_case ty_info usednames thy =
wenzelm@10769
   647
 let
wenzelm@10769
   648
 val divide = ipartition (gvvariant usednames)
wenzelm@10769
   649
 val tych = Thry.typecheck thy
wenzelm@10769
   650
 fun tych_binding(x,y) = (tych x, tych y)
wenzelm@10769
   651
 fun fail s = raise TFL_ERR "mk_case" s
wenzelm@10769
   652
 fun mk{rows=[],...} = fail"no rows"
wenzelm@10769
   653
   | mk{path=[], rows = [([], (thm, bindings))]} =
wenzelm@10769
   654
                         R.IT_EXISTS (map tych_binding bindings) thm
wenzelm@10769
   655
   | mk{path = u::rstp, rows as (p::_, _)::_} =
wenzelm@10769
   656
     let val (pat_rectangle,rights) = ListPair.unzip rows
wenzelm@10769
   657
         val col0 = map hd pat_rectangle
wenzelm@10769
   658
         val pat_rectangle' = map tl pat_rectangle
wenzelm@10769
   659
     in
wenzelm@10769
   660
     if (forall is_Free col0) (* column 0 is all variables *)
wenzelm@10769
   661
     then let val rights' = map (fn ((thm,theta),v) => (thm,theta@[(u,v)]))
wenzelm@10769
   662
                                (ListPair.zip (rights, col0))
wenzelm@10769
   663
          in mk{path = rstp, rows = ListPair.zip (pat_rectangle', rights')}
wenzelm@10769
   664
          end
wenzelm@10769
   665
     else                     (* column 0 is all constructors *)
wenzelm@10769
   666
     let val Type (ty_name,_) = type_of p
wenzelm@10769
   667
     in
wenzelm@10769
   668
     case (ty_info ty_name)
wenzelm@10769
   669
     of None => fail("Not a known datatype: "^ty_name)
wenzelm@10769
   670
      | Some{constructors,nchotomy} =>
wenzelm@10769
   671
        let val thm' = R.ISPEC (tych u) nchotomy
wenzelm@10769
   672
            val disjuncts = S.strip_disj (concl thm')
wenzelm@10769
   673
            val subproblems = divide(constructors, rows)
wenzelm@10769
   674
            val groups      = map #group subproblems
wenzelm@10769
   675
            and new_formals = map #new_formals subproblems
wenzelm@10769
   676
            val existentials = ListPair.map alpha_ex_unroll
wenzelm@10769
   677
                                   (new_formals, disjuncts)
wenzelm@10769
   678
            val constraints = map #1 existentials
wenzelm@10769
   679
            val vexl = map #2 existentials
wenzelm@10769
   680
            fun expnd tm (pats,(th,b)) = (pats,(R.SUBS[R.ASSUME(tych tm)]th,b))
wenzelm@10769
   681
            val news = map (fn (nf,rows,c) => {path = nf@rstp,
wenzelm@10769
   682
                                               rows = map (expnd c) rows})
wenzelm@10769
   683
                           (U.zip3 new_formals groups constraints)
wenzelm@10769
   684
            val recursive_thms = map mk news
wenzelm@10769
   685
            val build_exists = foldr
wenzelm@10769
   686
                                (fn((x,t), th) =>
wenzelm@10769
   687
                                 R.CHOOSE (tych x, R.ASSUME (tych t)) th)
wenzelm@10769
   688
            val thms' = ListPair.map build_exists (vexl, recursive_thms)
wenzelm@10769
   689
            val same_concls = R.EVEN_ORS thms'
wenzelm@10769
   690
        in R.DISJ_CASESL thm' same_concls
wenzelm@10769
   691
        end
wenzelm@10769
   692
     end end
wenzelm@10769
   693
 in mk
wenzelm@10769
   694
 end;
wenzelm@10769
   695
wenzelm@10769
   696
wenzelm@10769
   697
fun complete_cases thy =
wenzelm@10769
   698
 let val tych = Thry.typecheck thy
wenzelm@10769
   699
     val ty_info = Thry.induct_info thy
wenzelm@10769
   700
 in fn pats =>
wenzelm@10769
   701
 let val names = foldr add_term_names (pats,[])
wenzelm@10769
   702
     val T = type_of (hd pats)
wenzelm@10769
   703
     val aname = Term.variant names "a"
wenzelm@10769
   704
     val vname = Term.variant (aname::names) "v"
wenzelm@10769
   705
     val a = Free (aname, T)
wenzelm@10769
   706
     val v = Free (vname, T)
wenzelm@10769
   707
     val a_eq_v = HOLogic.mk_eq(a,v)
wenzelm@10769
   708
     val ex_th0 = R.EXISTS (tych (S.mk_exists{Bvar=v,Body=a_eq_v}), tych a)
wenzelm@10769
   709
                           (R.REFL (tych a))
wenzelm@10769
   710
     val th0 = R.ASSUME (tych a_eq_v)
wenzelm@10769
   711
     val rows = map (fn x => ([x], (th0,[]))) pats
wenzelm@10769
   712
 in
wenzelm@10769
   713
 R.GEN (tych a)
wenzelm@10769
   714
       (R.RIGHT_ASSOC
wenzelm@10769
   715
          (R.CHOOSE(tych v, ex_th0)
wenzelm@10769
   716
                (mk_case ty_info (vname::aname::names)
wenzelm@10769
   717
                 thy {path=[v], rows=rows})))
wenzelm@10769
   718
 end end;
wenzelm@10769
   719
wenzelm@10769
   720
wenzelm@10769
   721
(*---------------------------------------------------------------------------
wenzelm@10769
   722
 * Constructing induction hypotheses: one for each recursive call.
wenzelm@10769
   723
 *
wenzelm@10769
   724
 * Note. R will never occur as a variable in the ind_clause, because
wenzelm@10769
   725
 * to do so, it would have to be from a nested definition, and we don't
wenzelm@10769
   726
 * allow nested defns to have R variable.
wenzelm@10769
   727
 *
wenzelm@10769
   728
 * Note. When the context is empty, there can be no local variables.
wenzelm@10769
   729
 *---------------------------------------------------------------------------*)
wenzelm@10769
   730
(*
wenzelm@10769
   731
local infix 5 ==>
wenzelm@10769
   732
      fun (tm1 ==> tm2) = S.mk_imp{ant = tm1, conseq = tm2}
wenzelm@10769
   733
in
wenzelm@10769
   734
fun build_ih f P (pat,TCs) =
wenzelm@10769
   735
 let val globals = S.free_vars_lr pat
wenzelm@10769
   736
     fun nested tm = is_some (S.find_term (curry (op aconv) f) tm)
wenzelm@10769
   737
     fun dest_TC tm =
wenzelm@10769
   738
         let val (cntxt,R_y_pat) = S.strip_imp(#2(S.strip_forall tm))
wenzelm@10769
   739
             val (R,y,_) = S.dest_relation R_y_pat
wenzelm@10769
   740
             val P_y = if (nested tm) then R_y_pat ==> P$y else P$y
wenzelm@10769
   741
         in case cntxt
wenzelm@10769
   742
              of [] => (P_y, (tm,[]))
wenzelm@10769
   743
               | _  => let
wenzelm@10769
   744
                    val imp = S.list_mk_conj cntxt ==> P_y
wenzelm@10769
   745
                    val lvs = gen_rems (op aconv) (S.free_vars_lr imp, globals)
wenzelm@10769
   746
                    val locals = #2(U.pluck (curry (op aconv) P) lvs) handle U.ERR _ => lvs
wenzelm@10769
   747
                    in (S.list_mk_forall(locals,imp), (tm,locals)) end
wenzelm@10769
   748
         end
wenzelm@10769
   749
 in case TCs
wenzelm@10769
   750
    of [] => (S.list_mk_forall(globals, P$pat), [])
wenzelm@10769
   751
     |  _ => let val (ihs, TCs_locals) = ListPair.unzip(map dest_TC TCs)
wenzelm@10769
   752
                 val ind_clause = S.list_mk_conj ihs ==> P$pat
wenzelm@10769
   753
             in (S.list_mk_forall(globals,ind_clause), TCs_locals)
wenzelm@10769
   754
             end
wenzelm@10769
   755
 end
wenzelm@10769
   756
end;
wenzelm@10769
   757
*)
wenzelm@10769
   758
wenzelm@10769
   759
local infix 5 ==>
wenzelm@10769
   760
      fun (tm1 ==> tm2) = S.mk_imp{ant = tm1, conseq = tm2}
wenzelm@10769
   761
in
wenzelm@10769
   762
fun build_ih f (P,SV) (pat,TCs) =
wenzelm@10769
   763
 let val pat_vars = S.free_vars_lr pat
wenzelm@10769
   764
     val globals = pat_vars@SV
wenzelm@10769
   765
     fun nested tm = is_some (S.find_term (curry (op aconv) f) tm)
wenzelm@10769
   766
     fun dest_TC tm =
wenzelm@10769
   767
         let val (cntxt,R_y_pat) = S.strip_imp(#2(S.strip_forall tm))
wenzelm@10769
   768
             val (R,y,_) = S.dest_relation R_y_pat
wenzelm@10769
   769
             val P_y = if (nested tm) then R_y_pat ==> P$y else P$y
wenzelm@10769
   770
         in case cntxt
wenzelm@10769
   771
              of [] => (P_y, (tm,[]))
wenzelm@10769
   772
               | _  => let
wenzelm@10769
   773
                    val imp = S.list_mk_conj cntxt ==> P_y
wenzelm@10769
   774
                    val lvs = gen_rems (op aconv) (S.free_vars_lr imp, globals)
wenzelm@10769
   775
                    val locals = #2(U.pluck (curry (op aconv) P) lvs) handle U.ERR _ => lvs
wenzelm@10769
   776
                    in (S.list_mk_forall(locals,imp), (tm,locals)) end
wenzelm@10769
   777
         end
wenzelm@10769
   778
 in case TCs
wenzelm@10769
   779
    of [] => (S.list_mk_forall(pat_vars, P$pat), [])
wenzelm@10769
   780
     |  _ => let val (ihs, TCs_locals) = ListPair.unzip(map dest_TC TCs)
wenzelm@10769
   781
                 val ind_clause = S.list_mk_conj ihs ==> P$pat
wenzelm@10769
   782
             in (S.list_mk_forall(pat_vars,ind_clause), TCs_locals)
wenzelm@10769
   783
             end
wenzelm@10769
   784
 end
wenzelm@10769
   785
end;
wenzelm@10769
   786
wenzelm@10769
   787
(*---------------------------------------------------------------------------
wenzelm@10769
   788
 * This function makes good on the promise made in "build_ih".
wenzelm@10769
   789
 *
wenzelm@10769
   790
 * Input  is tm = "(!y. R y pat ==> P y) ==> P pat",
wenzelm@10769
   791
 *           TCs = TC_1[pat] ... TC_n[pat]
wenzelm@10769
   792
 *           thm = ih1 /\ ... /\ ih_n |- ih[pat]
wenzelm@10769
   793
 *---------------------------------------------------------------------------*)
wenzelm@10769
   794
fun prove_case f thy (tm,TCs_locals,thm) =
wenzelm@10769
   795
 let val tych = Thry.typecheck thy
wenzelm@10769
   796
     val antc = tych(#ant(S.dest_imp tm))
wenzelm@10769
   797
     val thm' = R.SPEC_ALL thm
wenzelm@10769
   798
     fun nested tm = is_some (S.find_term (curry (op aconv) f) tm)
wenzelm@10769
   799
     fun get_cntxt TC = tych(#ant(S.dest_imp(#2(S.strip_forall(concl TC)))))
wenzelm@10769
   800
     fun mk_ih ((TC,locals),th2,nested) =
wenzelm@10769
   801
         R.GENL (map tych locals)
wenzelm@10769
   802
            (if nested then R.DISCH (get_cntxt TC) th2 handle U.ERR _ => th2
wenzelm@10769
   803
             else if S.is_imp (concl TC) then R.IMP_TRANS TC th2
wenzelm@10769
   804
             else R.MP th2 TC)
wenzelm@10769
   805
 in
wenzelm@10769
   806
 R.DISCH antc
wenzelm@10769
   807
 (if S.is_imp(concl thm') (* recursive calls in this clause *)
wenzelm@10769
   808
  then let val th1 = R.ASSUME antc
wenzelm@10769
   809
           val TCs = map #1 TCs_locals
wenzelm@10769
   810
           val ylist = map (#2 o S.dest_relation o #2 o S.strip_imp o
wenzelm@10769
   811
                            #2 o S.strip_forall) TCs
wenzelm@10769
   812
           val TClist = map (fn(TC,lvs) => (R.SPEC_ALL(R.ASSUME(tych TC)),lvs))
wenzelm@10769
   813
                            TCs_locals
wenzelm@10769
   814
           val th2list = map (U.C R.SPEC th1 o tych) ylist
wenzelm@10769
   815
           val nlist = map nested TCs
wenzelm@10769
   816
           val triples = U.zip3 TClist th2list nlist
wenzelm@10769
   817
           val Pylist = map mk_ih triples
wenzelm@10769
   818
       in R.MP thm' (R.LIST_CONJ Pylist) end
wenzelm@10769
   819
  else thm')
wenzelm@10769
   820
 end;
wenzelm@10769
   821
wenzelm@10769
   822
wenzelm@10769
   823
(*---------------------------------------------------------------------------
wenzelm@10769
   824
 *
wenzelm@10769
   825
 *         x = (v1,...,vn)  |- M[x]
wenzelm@10769
   826
 *    ---------------------------------------------
wenzelm@10769
   827
 *      ?v1 ... vn. x = (v1,...,vn) |- M[x]
wenzelm@10769
   828
 *
wenzelm@10769
   829
 *---------------------------------------------------------------------------*)
wenzelm@10769
   830
fun LEFT_ABS_VSTRUCT tych thm =
wenzelm@10769
   831
  let fun CHOOSER v (tm,thm) =
wenzelm@10769
   832
        let val ex_tm = S.mk_exists{Bvar=v,Body=tm}
wenzelm@10769
   833
        in (ex_tm, R.CHOOSE(tych v, R.ASSUME (tych ex_tm)) thm)
wenzelm@10769
   834
        end
wenzelm@10769
   835
      val [veq] = filter (can S.dest_eq) (#1 (R.dest_thm thm))
wenzelm@10769
   836
      val {lhs,rhs} = S.dest_eq veq
wenzelm@10769
   837
      val L = S.free_vars_lr rhs
wenzelm@10769
   838
  in  #2 (U.itlist CHOOSER L (veq,thm))  end;
wenzelm@10769
   839
wenzelm@10769
   840
wenzelm@10769
   841
(*----------------------------------------------------------------------------
wenzelm@10769
   842
 * Input : f, R,  and  [(pat1,TCs1),..., (patn,TCsn)]
wenzelm@10769
   843
 *
wenzelm@10769
   844
 * Instantiates WF_INDUCTION_THM, getting Sinduct and then tries to prove
wenzelm@10769
   845
 * recursion induction (Rinduct) by proving the antecedent of Sinduct from
wenzelm@10769
   846
 * the antecedent of Rinduct.
wenzelm@10769
   847
 *---------------------------------------------------------------------------*)
wenzelm@10769
   848
fun mk_induction thy {fconst, R, SV, pat_TCs_list} =
wenzelm@10769
   849
let val tych = Thry.typecheck thy
wenzelm@10769
   850
    val Sinduction = R.UNDISCH (R.ISPEC (tych R) Thms.WF_INDUCTION_THM)
wenzelm@10769
   851
    val (pats,TCsl) = ListPair.unzip pat_TCs_list
wenzelm@10769
   852
    val case_thm = complete_cases thy pats
wenzelm@10769
   853
    val domain = (type_of o hd) pats
wenzelm@10769
   854
    val Pname = Term.variant (foldr (foldr add_term_names)
wenzelm@10769
   855
                              (pats::TCsl, [])) "P"
wenzelm@10769
   856
    val P = Free(Pname, domain --> HOLogic.boolT)
wenzelm@10769
   857
    val Sinduct = R.SPEC (tych P) Sinduction
wenzelm@10769
   858
    val Sinduct_assumf = S.rand ((#ant o S.dest_imp o concl) Sinduct)
wenzelm@10769
   859
    val Rassums_TCl' = map (build_ih fconst (P,SV)) pat_TCs_list
wenzelm@10769
   860
    val (Rassums,TCl') = ListPair.unzip Rassums_TCl'
wenzelm@10769
   861
    val Rinduct_assum = R.ASSUME (tych (S.list_mk_conj Rassums))
wenzelm@10769
   862
    val cases = map (fn pat => betapply (Sinduct_assumf, pat)) pats
wenzelm@10769
   863
    val tasks = U.zip3 cases TCl' (R.CONJUNCTS Rinduct_assum)
wenzelm@10769
   864
    val proved_cases = map (prove_case fconst thy) tasks
wenzelm@10769
   865
    val v = Free (variant (foldr add_term_names (map concl proved_cases, []))
wenzelm@10769
   866
                    "v",
wenzelm@10769
   867
                  domain)
wenzelm@10769
   868
    val vtyped = tych v
wenzelm@10769
   869
    val substs = map (R.SYM o R.ASSUME o tych o (curry HOLogic.mk_eq v)) pats
wenzelm@10769
   870
    val proved_cases1 = ListPair.map (fn (th,th') => R.SUBS[th]th')
wenzelm@10769
   871
                          (substs, proved_cases)
wenzelm@10769
   872
    val abs_cases = map (LEFT_ABS_VSTRUCT tych) proved_cases1
wenzelm@10769
   873
    val dant = R.GEN vtyped (R.DISJ_CASESL (R.ISPEC vtyped case_thm) abs_cases)
wenzelm@10769
   874
    val dc = R.MP Sinduct dant
wenzelm@10769
   875
    val Parg_ty = type_of(#Bvar(S.dest_forall(concl dc)))
wenzelm@10769
   876
    val vars = map (gvvariant[Pname]) (S.strip_prod_type Parg_ty)
wenzelm@10769
   877
    val dc' = U.itlist (R.GEN o tych) vars
wenzelm@10769
   878
                       (R.SPEC (tych(S.mk_vstruct Parg_ty vars)) dc)
wenzelm@10769
   879
in
wenzelm@10769
   880
   R.GEN (tych P) (R.DISCH (tych(concl Rinduct_assum)) dc')
wenzelm@10769
   881
end
wenzelm@10769
   882
handle U.ERR _ => raise TFL_ERR "mk_induction" "failed derivation";
wenzelm@10769
   883
wenzelm@10769
   884
wenzelm@10769
   885
wenzelm@10769
   886
wenzelm@10769
   887
(*---------------------------------------------------------------------------
wenzelm@10769
   888
 *
wenzelm@10769
   889
 *                        POST PROCESSING
wenzelm@10769
   890
 *
wenzelm@10769
   891
 *---------------------------------------------------------------------------*)
wenzelm@10769
   892
wenzelm@10769
   893
wenzelm@10769
   894
fun simplify_induction thy hth ind =
wenzelm@10769
   895
  let val tych = Thry.typecheck thy
wenzelm@10769
   896
      val (asl,_) = R.dest_thm ind
wenzelm@10769
   897
      val (_,tc_eq_tc') = R.dest_thm hth
wenzelm@10769
   898
      val tc = S.lhs tc_eq_tc'
wenzelm@10769
   899
      fun loop [] = ind
wenzelm@10769
   900
        | loop (asm::rst) =
wenzelm@10769
   901
          if (can (Thry.match_term thy asm) tc)
wenzelm@10769
   902
          then R.UNDISCH
wenzelm@10769
   903
                 (R.MATCH_MP
wenzelm@10769
   904
                     (R.MATCH_MP Thms.simp_thm (R.DISCH (tych asm) ind))
wenzelm@10769
   905
                     hth)
wenzelm@10769
   906
         else loop rst
wenzelm@10769
   907
  in loop asl
wenzelm@10769
   908
end;
wenzelm@10769
   909
wenzelm@10769
   910
wenzelm@10769
   911
(*---------------------------------------------------------------------------
wenzelm@10769
   912
 * The termination condition is an antecedent to the rule, and an
wenzelm@10769
   913
 * assumption to the theorem.
wenzelm@10769
   914
 *---------------------------------------------------------------------------*)
wenzelm@10769
   915
fun elim_tc tcthm (rule,induction) =
wenzelm@10769
   916
   (R.MP rule tcthm, R.PROVE_HYP tcthm induction)
wenzelm@10769
   917
wenzelm@10769
   918
paulson@14240
   919
fun trace_thms s L =
paulson@14240
   920
  if !trace then writeln (cat_lines (s :: map string_of_thm L))
paulson@14240
   921
  else ();
paulson@14240
   922
paulson@14240
   923
fun trace_cterms s L =
paulson@14240
   924
  if !trace then writeln (cat_lines (s :: map string_of_cterm L))
paulson@14240
   925
  else ();;
paulson@14240
   926
paulson@14240
   927
wenzelm@11632
   928
fun postprocess strict {wf_tac, terminator, simplifier} theory {rules,induction,TCs} =
wenzelm@10769
   929
let val tych = Thry.typecheck theory
wenzelm@11632
   930
    val prove = R.prove strict;
wenzelm@10769
   931
wenzelm@10769
   932
   (*---------------------------------------------------------------------
wenzelm@10769
   933
    * Attempt to eliminate WF condition. It's the only assumption of rules
wenzelm@10769
   934
    *---------------------------------------------------------------------*)
wenzelm@10769
   935
   val (rules1,induction1)  =
wenzelm@11632
   936
       let val thm = prove(tych(HOLogic.mk_Trueprop
wenzelm@10769
   937
                                  (hd(#1(R.dest_thm rules)))),
wenzelm@10769
   938
                             wf_tac)
wenzelm@10769
   939
       in (R.PROVE_HYP thm rules,  R.PROVE_HYP thm induction)
wenzelm@10769
   940
       end handle U.ERR _ => (rules,induction);
wenzelm@10769
   941
wenzelm@10769
   942
   (*----------------------------------------------------------------------
wenzelm@10769
   943
    * The termination condition (tc) is simplified to |- tc = tc' (there
wenzelm@10769
   944
    * might not be a change!) and then 3 attempts are made:
wenzelm@10769
   945
    *
wenzelm@10769
   946
    *   1. if |- tc = T, then eliminate it with eqT; otherwise,
wenzelm@10769
   947
    *   2. apply the terminator to tc'. If |- tc' = T then eliminate; else
wenzelm@10769
   948
    *   3. replace tc by tc' in both the rules and the induction theorem.
wenzelm@10769
   949
    *---------------------------------------------------------------------*)
wenzelm@10769
   950
wenzelm@10769
   951
   fun simplify_tc tc (r,ind) =
wenzelm@10769
   952
       let val tc1 = tych tc
paulson@14240
   953
           val _ = trace_cterms "TC before simplification: " [tc1]
wenzelm@10769
   954
           val tc_eq = simplifier tc1
paulson@14240
   955
           val _ = trace_thms "result: " [tc_eq]
wenzelm@10769
   956
       in
wenzelm@10769
   957
       elim_tc (R.MATCH_MP Thms.eqT tc_eq) (r,ind)
wenzelm@10769
   958
       handle U.ERR _ =>
wenzelm@10769
   959
        (elim_tc (R.MATCH_MP(R.MATCH_MP Thms.rev_eq_mp tc_eq)
wenzelm@11632
   960
                  (prove(tych(HOLogic.mk_Trueprop(S.rhs(concl tc_eq))),
wenzelm@10769
   961
                           terminator)))
wenzelm@10769
   962
                 (r,ind)
wenzelm@10769
   963
         handle U.ERR _ =>
wenzelm@10769
   964
          (R.UNDISCH(R.MATCH_MP (R.MATCH_MP Thms.simp_thm r) tc_eq),
wenzelm@10769
   965
           simplify_induction theory tc_eq ind))
wenzelm@10769
   966
       end
wenzelm@10769
   967
wenzelm@10769
   968
   (*----------------------------------------------------------------------
wenzelm@10769
   969
    * Nested termination conditions are harder to get at, since they are
wenzelm@10769
   970
    * left embedded in the body of the function (and in induction
wenzelm@10769
   971
    * theorem hypotheses). Our "solution" is to simplify them, and try to
wenzelm@10769
   972
    * prove termination, but leave the application of the resulting theorem
wenzelm@10769
   973
    * to a higher level. So things go much as in "simplify_tc": the
wenzelm@10769
   974
    * termination condition (tc) is simplified to |- tc = tc' (there might
wenzelm@10769
   975
    * not be a change) and then 2 attempts are made:
wenzelm@10769
   976
    *
wenzelm@10769
   977
    *   1. if |- tc = T, then return |- tc; otherwise,
wenzelm@10769
   978
    *   2. apply the terminator to tc'. If |- tc' = T then return |- tc; else
wenzelm@10769
   979
    *   3. return |- tc = tc'
wenzelm@10769
   980
    *---------------------------------------------------------------------*)
wenzelm@10769
   981
   fun simplify_nested_tc tc =
wenzelm@10769
   982
      let val tc_eq = simplifier (tych (#2 (S.strip_forall tc)))
wenzelm@10769
   983
      in
wenzelm@10769
   984
      R.GEN_ALL
wenzelm@10769
   985
       (R.MATCH_MP Thms.eqT tc_eq
wenzelm@10769
   986
        handle U.ERR _ =>
wenzelm@10769
   987
          (R.MATCH_MP(R.MATCH_MP Thms.rev_eq_mp tc_eq)
wenzelm@11632
   988
                      (prove(tych(HOLogic.mk_Trueprop (S.rhs(concl tc_eq))),
wenzelm@10769
   989
                               terminator))
wenzelm@10769
   990
            handle U.ERR _ => tc_eq))
wenzelm@10769
   991
      end
wenzelm@10769
   992
wenzelm@10769
   993
   (*-------------------------------------------------------------------
wenzelm@10769
   994
    * Attempt to simplify the termination conditions in each rule and
wenzelm@10769
   995
    * in the induction theorem.
wenzelm@10769
   996
    *-------------------------------------------------------------------*)
wenzelm@10769
   997
   fun strip_imp tm = if S.is_neg tm then ([],tm) else S.strip_imp tm
wenzelm@10769
   998
   fun loop ([],extras,R,ind) = (rev R, ind, extras)
wenzelm@10769
   999
     | loop ((r,ftcs)::rst, nthms, R, ind) =
wenzelm@10769
  1000
        let val tcs = #1(strip_imp (concl r))
wenzelm@10769
  1001
            val extra_tcs = gen_rems (op aconv) (ftcs, tcs)
wenzelm@10769
  1002
            val extra_tc_thms = map simplify_nested_tc extra_tcs
wenzelm@10769
  1003
            val (r1,ind1) = U.rev_itlist simplify_tc tcs (r,ind)
wenzelm@10769
  1004
            val r2 = R.FILTER_DISCH_ALL(not o S.is_WFR) r1
wenzelm@10769
  1005
        in loop(rst, nthms@extra_tc_thms, r2::R, ind1)
wenzelm@10769
  1006
        end
wenzelm@10769
  1007
   val rules_tcs = ListPair.zip (R.CONJUNCTS rules1, TCs)
wenzelm@10769
  1008
   val (rules2,ind2,extras) = loop(rules_tcs,[],[],induction1)
wenzelm@10769
  1009
in
wenzelm@10769
  1010
  {induction = ind2, rules = R.LIST_CONJ rules2, nested_tcs = extras}
wenzelm@10769
  1011
end;
wenzelm@10769
  1012
wenzelm@10769
  1013
wenzelm@10769
  1014
end;