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