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