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