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