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