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