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