src/Pure/old_goals.ML
author wenzelm
Thu May 27 17:41:27 2010 +0200 (2010-05-27)
changeset 37145 01aa36932739
parent 36944 dbf831a50e4a
child 37330 a7a150650d40
permissions -rw-r--r--
renamed structure TypeInfer to Type_Infer, keeping the old name as legacy alias for some time;
     1 (*  Title:      Pure/old_goals.ML
     2     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     3     Copyright   1993  University of Cambridge
     4 
     5 Old-style goal stack package.  The goal stack initially holds a dummy
     6 proof, and can never become empty.  Each goal stack consists of a list
     7 of levels.  The undo list is a list of goal stacks.  Finally, there
     8 may be a stack of pending proofs.
     9 *)
    10 
    11 signature OLD_GOALS =
    12 sig
    13   val mk_defpair: term * term -> string * term
    14   val strip_context: term -> (string * typ) list * term list * term
    15   val metahyps_thms: int -> thm -> thm list option
    16   val METAHYPS: (thm list -> tactic) -> int -> tactic
    17   val simple_read_term: theory -> typ -> string -> term
    18   val read_term: theory -> string -> term
    19   val read_prop: theory -> string -> term
    20   val get_def: theory -> xstring -> thm
    21   type proof
    22   val premises: unit -> thm list
    23   val reset_goals: unit -> unit
    24   val result_error_fn: (thm -> string -> thm) Unsynchronized.ref
    25   val print_sign_exn: theory -> exn -> 'a
    26   val prove_goalw_cterm: thm list->cterm->(thm list->tactic list)->thm
    27   val prove_goalw_cterm_nocheck: thm list->cterm->(thm list->tactic list)->thm
    28   val prove_goalw: theory -> thm list -> string -> (thm list -> tactic list) -> thm
    29   val prove_goal: theory -> string -> (thm list -> tactic list) -> thm
    30   val topthm: unit -> thm
    31   val result: unit -> thm
    32   val uresult: unit -> thm
    33   val getgoal: int -> term
    34   val gethyps: int -> thm list
    35   val print_exn: exn -> 'a
    36   val filter_goal: (term*term->bool) -> thm list -> int -> thm list
    37   val prlev: int -> unit
    38   val pr: unit -> unit
    39   val prlim: int -> unit
    40   val goalw_cterm: thm list -> cterm -> thm list
    41   val goalw: theory -> thm list -> string -> thm list
    42   val goal: theory -> string -> thm list
    43   val Goalw: thm list -> string -> thm list
    44   val Goal: string -> thm list
    45   val simple_prove_goal_cterm: cterm->(thm list->tactic list)->thm
    46   val by: tactic -> unit
    47   val byev: tactic list -> unit
    48   val back: unit -> unit
    49   val choplev: int -> unit
    50   val chop: unit -> unit
    51   val undo: unit -> unit
    52   val save_proof: unit -> proof
    53   val restore_proof: proof -> thm list
    54   val push_proof: unit -> unit
    55   val pop_proof: unit -> thm list
    56   val rotate_proof: unit -> thm list
    57   val qed: string -> unit
    58   val qed_goal: string -> theory -> string -> (thm list -> tactic list) -> unit
    59   val qed_goalw: string -> theory -> thm list -> string
    60     -> (thm list -> tactic list) -> unit
    61   val qed_spec_mp: string -> unit
    62   val qed_goal_spec_mp: string -> theory -> string -> (thm list -> tactic list) -> unit
    63   val qed_goalw_spec_mp: string -> theory -> thm list -> string
    64     -> (thm list -> tactic list) -> unit
    65 end;
    66 
    67 structure OldGoals: OLD_GOALS =
    68 struct
    69 
    70 fun mk_defpair (lhs, rhs) =
    71   (case Term.head_of lhs of
    72     Const (name, _) =>
    73       (Long_Name.base_name name ^ "_def", Logic.mk_equals (lhs, rhs))
    74   | _ => raise TERM ("Malformed definition: head of lhs not a constant", [lhs, rhs]));
    75 
    76 
    77 (**** METAHYPS -- tactical for using hypotheses as meta-level assumptions
    78        METAHYPS (fn prems => tac prems) i
    79 
    80 converts subgoal i, of the form !!x1...xm. [| A1;...;An] ==> A into a new
    81 proof state A==>A, supplying A1,...,An as meta-level assumptions (in
    82 "prems").  The parameters x1,...,xm become free variables.  If the
    83 resulting proof state is [| B1;...;Bk] ==> C (possibly assuming A1,...,An)
    84 then it is lifted back into the original context, yielding k subgoals.
    85 
    86 Replaces unknowns in the context by Frees having the prefix METAHYP_
    87 New unknowns in [| B1;...;Bk] ==> C are lifted over x1,...,xm.
    88 DOES NOT HANDLE TYPE UNKNOWNS.
    89 
    90 
    91 NOTE: This version does not observe the proof context, and thus cannot
    92 work reliably.  See also Subgoal.SUBPROOF and Subgoal.FOCUS for
    93 properly localized variants of the same idea.
    94 ****)
    95 
    96 (*Strips assumptions in goal yielding  ( [x1,...,xm], [H1,...,Hn], B )
    97     H1,...,Hn are the hypotheses;  x1...xm are variants of the parameters.
    98   Main difference from strip_assums concerns parameters:
    99     it replaces the bound variables by free variables.  *)
   100 fun strip_context_aux (params, Hs, Const ("==>", _) $ H $ B) =
   101       strip_context_aux (params, H :: Hs, B)
   102   | strip_context_aux (params, Hs, Const ("all",_) $ Abs (a, T, t)) =
   103       let val (b, u) = Syntax.variant_abs (a, T, t)
   104       in strip_context_aux ((b, T) :: params, Hs, u) end
   105   | strip_context_aux (params, Hs, B) = (rev params, rev Hs, B);
   106 
   107 fun strip_context A = strip_context_aux ([], [], A);
   108 
   109 local
   110 
   111   (*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
   112     Instantiates distinct free variables by terms of same type.*)
   113   fun free_instantiate ctpairs =
   114     forall_elim_list (map snd ctpairs) o forall_intr_list (map fst ctpairs);
   115 
   116   fun free_of s ((a, i), T) =
   117     Free (s ^ (case i of 0 => a | _ => a ^ "_" ^ string_of_int i), T)
   118 
   119   fun mk_inst v = (Var v, free_of "METAHYP1_" v)
   120 in
   121 
   122 (*Common code for METAHYPS and metahyps_thms*)
   123 fun metahyps_split_prem prem =
   124   let (*find all vars in the hyps -- should find tvars also!*)
   125       val hyps_vars = fold Term.add_vars (Logic.strip_assums_hyp prem) []
   126       val insts = map mk_inst hyps_vars
   127       (*replace the hyps_vars by Frees*)
   128       val prem' = subst_atomic insts prem
   129       val (params,hyps,concl) = strip_context prem'
   130   in (insts,params,hyps,concl)  end;
   131 
   132 fun metahyps_aux_tac tacf (prem,gno) state =
   133   let val (insts,params,hyps,concl) = metahyps_split_prem prem
   134       val maxidx = Thm.maxidx_of state
   135       val cterm = Thm.cterm_of (Thm.theory_of_thm state)
   136       val chyps = map cterm hyps
   137       val hypths = map Thm.assume chyps
   138       val subprems = map (Thm.forall_elim_vars 0) hypths
   139       val fparams = map Free params
   140       val cparams = map cterm fparams
   141       fun swap_ctpair (t,u) = (cterm u, cterm t)
   142       (*Subgoal variables: make Free; lift type over params*)
   143       fun mk_subgoal_inst concl_vars (v, T) =
   144           if member (op =) concl_vars (v, T)
   145           then ((v, T), true, free_of "METAHYP2_" (v, T))
   146           else ((v, T), false, free_of "METAHYP2_" (v, map #2 params ---> T))
   147       (*Instantiate subgoal vars by Free applied to params*)
   148       fun mk_ctpair (v, in_concl, u) =
   149           if in_concl then (cterm (Var v), cterm u)
   150           else (cterm (Var v), cterm (list_comb (u, fparams)))
   151       (*Restore Vars with higher type and index*)
   152       fun mk_subgoal_swap_ctpair (((a, i), T), in_concl, u as Free (_, U)) =
   153           if in_concl then (cterm u, cterm (Var ((a, i), T)))
   154           else (cterm u, cterm (Var ((a, i + maxidx), U)))
   155       (*Embed B in the original context of params and hyps*)
   156       fun embed B = list_all_free (params, Logic.list_implies (hyps, B))
   157       (*Strip the context using elimination rules*)
   158       fun elim Bhyp = implies_elim_list (forall_elim_list cparams Bhyp) hypths
   159       (*A form of lifting that discharges assumptions.*)
   160       fun relift st =
   161         let val prop = Thm.prop_of st
   162             val subgoal_vars = (*Vars introduced in the subgoals*)
   163               fold Term.add_vars (Logic.strip_imp_prems prop) []
   164             and concl_vars = Term.add_vars (Logic.strip_imp_concl prop) []
   165             val subgoal_insts = map (mk_subgoal_inst concl_vars) subgoal_vars
   166             val st' = Thm.instantiate ([], map mk_ctpair subgoal_insts) st
   167             val emBs = map (cterm o embed) (prems_of st')
   168             val Cth  = implies_elim_list st' (map (elim o Thm.assume) emBs)
   169         in  (*restore the unknowns to the hypotheses*)
   170             free_instantiate (map swap_ctpair insts @
   171                               map mk_subgoal_swap_ctpair subgoal_insts)
   172                 (*discharge assumptions from state in same order*)
   173                 (implies_intr_list emBs
   174                   (forall_intr_list cparams (implies_intr_list chyps Cth)))
   175         end
   176       (*function to replace the current subgoal*)
   177       fun next st = Thm.bicompose false (false, relift st, nprems_of st) gno state
   178   in Seq.maps next (tacf subprems (Thm.trivial (cterm concl))) end;
   179 
   180 end;
   181 
   182 (*Returns the theorem list that METAHYPS would supply to its tactic*)
   183 fun metahyps_thms i state =
   184   let val prem = Logic.nth_prem (i, Thm.prop_of state)
   185       and cterm = cterm_of (Thm.theory_of_thm state)
   186       val (_,_,hyps,_) = metahyps_split_prem prem
   187   in SOME (map (Thm.forall_elim_vars 0 o Thm.assume o cterm) hyps) end
   188   handle TERM ("nth_prem", [A]) => NONE;
   189 
   190 local
   191 
   192 fun print_vars_terms thy (n,thm) =
   193   let
   194     fun typed ty = " has type: " ^ Syntax.string_of_typ_global thy ty;
   195     fun find_vars thy (Const (c, ty)) =
   196           if null (Term.add_tvarsT ty []) then I
   197           else insert (op =) (c ^ typed ty)
   198       | find_vars thy (Var (xi, ty)) = insert (op =) (Term.string_of_vname xi ^ typed ty)
   199       | find_vars _ (Free _) = I
   200       | find_vars _ (Bound _) = I
   201       | find_vars thy (Abs (_, _, t)) = find_vars thy t
   202       | find_vars thy (t1 $ t2) =
   203           find_vars thy t1 #> find_vars thy t1;
   204     val prem = Logic.nth_prem (n, Thm.prop_of thm)
   205     val tms = find_vars thy prem []
   206   in
   207     (warning "Found schematic vars in assumptions:"; warning (cat_lines tms))
   208   end;
   209 
   210 in
   211 
   212 fun METAHYPS tacf n thm = SUBGOAL (metahyps_aux_tac tacf) n thm
   213   handle THM("assume: variables",_,_) => (print_vars_terms (theory_of_thm thm) (n,thm); Seq.empty)
   214 
   215 end;
   216 
   217 
   218 (* old ways of reading terms *)
   219 
   220 fun simple_read_term thy T s =
   221   let
   222     val ctxt = ProofContext.init_global thy
   223       |> ProofContext.allow_dummies
   224       |> ProofContext.set_mode ProofContext.mode_schematic;
   225     val parse = if T = propT then Syntax.parse_prop else Syntax.parse_term;
   226   in parse ctxt s |> Type_Infer.constrain T |> Syntax.check_term ctxt end;
   227 
   228 fun read_term thy = simple_read_term thy dummyT;
   229 fun read_prop thy = simple_read_term thy propT;
   230 
   231 
   232 fun get_def thy = Thm.axiom thy o Name_Space.intern (Theory.axiom_space thy) o Thm.def_name;
   233 
   234 
   235 (*** Goal package ***)
   236 
   237 (*Each level of goal stack includes a proof state and alternative states,
   238   the output of the tactic applied to the preceeding level.  *)
   239 type gstack = (thm * thm Seq.seq) list;
   240 
   241 datatype proof = Proof of gstack list * thm list * (bool*thm->thm);
   242 
   243 
   244 (*** References ***)
   245 
   246 (*Current assumption list -- set by "goal".*)
   247 val curr_prems = Unsynchronized.ref([] : thm list);
   248 
   249 (*Return assumption list -- useful if you didn't save "goal"'s result. *)
   250 fun premises() = !curr_prems;
   251 
   252 (*Current result maker -- set by "goal", used by "result".  *)
   253 fun init_mkresult _ = error "No goal has been supplied in subgoal module";
   254 val curr_mkresult = Unsynchronized.ref (init_mkresult: bool*thm->thm);
   255 
   256 (*List of previous goal stacks, for the undo operation.  Set by setstate.
   257   A list of lists!*)
   258 val undo_list = Unsynchronized.ref([[(asm_rl, Seq.empty)]] : gstack list);
   259 
   260 (* Stack of proof attempts *)
   261 val proofstack = Unsynchronized.ref([]: proof list);
   262 
   263 (*reset all refs*)
   264 fun reset_goals () =
   265   (curr_prems := []; curr_mkresult := init_mkresult;
   266     undo_list := [[(asm_rl, Seq.empty)]]);
   267 
   268 
   269 (*** Setting up goal-directed proof ***)
   270 
   271 (*Generates the list of new theories when the proof state's theory changes*)
   272 fun thy_error (thy,thy') =
   273   let val names = subtract (op =) (Context.display_names thy) (Context.display_names thy')
   274   in  case names of
   275         [name] => "\nNew theory: " ^ name
   276       | _       => "\nNew theories: " ^ space_implode ", " names
   277   end;
   278 
   279 (*Default action is to print an error message; could be suppressed for
   280   special applications.*)
   281 fun result_error_default state msg : thm =
   282   Pretty.str "Bad final proof state:" ::
   283       Goal_Display.pretty_goals_without_context (!goals_limit) state @
   284     [Pretty.str msg, Pretty.str "Proof failed!"] |> Pretty.chunks |> Pretty.string_of |> error;
   285 
   286 val result_error_fn = Unsynchronized.ref result_error_default;
   287 
   288 
   289 (*Common treatment of "goal" and "prove_goal":
   290   Return assumptions, initial proof state, and function to make result.
   291   "atomic" indicates if the goal should be wrapped up in the function
   292   "Goal::prop=>prop" to avoid assumptions being returned separately.
   293 *)
   294 fun prepare_proof atomic rths chorn =
   295   let
   296       val thy = Thm.theory_of_cterm chorn;
   297       val horn = Thm.term_of chorn;
   298       val _ = Term.no_dummy_patterns horn handle TERM (msg, _) => error msg;
   299       val (As, B) = Logic.strip_horn horn;
   300       val atoms = atomic andalso
   301             forall (fn t => not (can Logic.dest_implies t orelse Logic.is_all t)) As;
   302       val (As,B) = if atoms then ([],horn) else (As,B);
   303       val cAs = map (cterm_of thy) As;
   304       val prems = map (rewrite_rule rths o Thm.forall_elim_vars 0 o Thm.assume) cAs;
   305       val cB = cterm_of thy B;
   306       val st0 = let val st = Goal.init cB |> fold Thm.weaken cAs
   307                 in  rewrite_goals_rule rths st end
   308       (*discharges assumptions from state in the order they appear in goal;
   309         checks (if requested) that resulting theorem is equivalent to goal. *)
   310       fun mkresult (check,state) =
   311         let val state = Seq.hd (Thm.flexflex_rule state)
   312                         handle THM _ => state   (*smash flexflex pairs*)
   313             val ngoals = nprems_of state
   314             val ath = implies_intr_list cAs state
   315             val th = Goal.conclude ath
   316             val thy' = Thm.theory_of_thm th
   317             val {hyps, prop, ...} = Thm.rep_thm th
   318             val final_th = Drule.export_without_context th
   319         in  if not check then final_th
   320             else if not (Theory.eq_thy(thy,thy')) then !result_error_fn state
   321                 ("Theory of proof state has changed!" ^
   322                  thy_error (thy,thy'))
   323             else if ngoals>0 then !result_error_fn state
   324                 (string_of_int ngoals ^ " unsolved goals!")
   325             else if not (null hyps) then !result_error_fn state
   326                 ("Additional hypotheses:\n" ^
   327                  cat_lines (map (Syntax.string_of_term_global thy) hyps))
   328             else if Pattern.matches thy
   329                                     (Envir.beta_norm (term_of chorn), Envir.beta_norm prop)
   330                  then final_th
   331             else  !result_error_fn state "proved a different theorem"
   332         end
   333   in
   334      if Theory.eq_thy(thy, Thm.theory_of_thm st0)
   335      then (prems, st0, mkresult)
   336      else error ("Definitions would change the proof state's theory" ^
   337                  thy_error (thy, Thm.theory_of_thm st0))
   338   end
   339   handle THM(s,_,_) => error("prepare_proof: exception THM was raised!\n" ^ s);
   340 
   341 (*Prints exceptions readably to users*)
   342 fun print_sign_exn_unit thy e =
   343   case e of
   344      THM (msg,i,thms) =>
   345          (writeln ("Exception THM " ^ string_of_int i ^ " raised:\n" ^ msg);
   346           List.app (writeln o Display.string_of_thm_global thy) thms)
   347    | THEORY (msg,thys) =>
   348          (writeln ("Exception THEORY raised:\n" ^ msg);
   349           List.app (writeln o Context.str_of_thy) thys)
   350    | TERM (msg,ts) =>
   351          (writeln ("Exception TERM raised:\n" ^ msg);
   352           List.app (writeln o Syntax.string_of_term_global thy) ts)
   353    | TYPE (msg,Ts,ts) =>
   354          (writeln ("Exception TYPE raised:\n" ^ msg);
   355           List.app (writeln o Syntax.string_of_typ_global thy) Ts;
   356           List.app (writeln o Syntax.string_of_term_global thy) ts)
   357    | e => raise e;
   358 
   359 (*Prints an exception, then fails*)
   360 fun print_sign_exn thy e = (print_sign_exn_unit thy e; raise ERROR "");
   361 
   362 (** the prove_goal.... commands
   363     Prove theorem using the listed tactics; check it has the specified form.
   364     Augment theory with all type assignments of goal.
   365     Syntax is similar to "goal" command for easy keyboard use. **)
   366 
   367 (*Version taking the goal as a cterm*)
   368 fun prove_goalw_cterm_general check rths chorn tacsf =
   369   let val (prems, st0, mkresult) = prepare_proof false rths chorn
   370       val tac = EVERY (tacsf prems)
   371       fun statef() =
   372           (case Seq.pull (tac st0) of
   373                SOME(st,_) => st
   374              | _ => error ("prove_goal: tactic failed"))
   375   in  mkresult (check, cond_timeit (!Output.timing) "" statef)  end;
   376 
   377 (*Two variants: one checking the result, one not.
   378   Neither prints runtime messages: they are for internal packages.*)
   379 fun prove_goalw_cterm rths chorn =
   380         setmp_CRITICAL Output.timing false (prove_goalw_cterm_general true rths chorn)
   381 and prove_goalw_cterm_nocheck rths chorn =
   382         setmp_CRITICAL Output.timing false (prove_goalw_cterm_general false rths chorn);
   383 
   384 
   385 (*Version taking the goal as a string*)
   386 fun prove_goalw thy rths agoal tacsf =
   387   let val chorn = cterm_of thy (read_prop thy agoal)
   388   in prove_goalw_cterm_general true rths chorn tacsf end
   389   handle ERROR msg => cat_error msg (*from read_prop?*)
   390                 ("The error(s) above occurred for " ^ quote agoal);
   391 
   392 (*String version with no meta-rewrite-rules*)
   393 fun prove_goal thy = prove_goalw thy [];
   394 
   395 
   396 
   397 (*** Commands etc ***)
   398 
   399 (*Return the current goal stack, if any, from undo_list*)
   400 fun getstate() : gstack = case !undo_list of
   401       []   => error"No current state in subgoal module"
   402     | x::_ => x;
   403 
   404 (*Pops the given goal stack*)
   405 fun pop [] = error"Cannot go back past the beginning of the proof!"
   406   | pop (pair::pairs) = (pair,pairs);
   407 
   408 
   409 (* Print a level of the goal stack *)
   410 
   411 fun print_top ((th, _), pairs) =
   412   let
   413     val n = length pairs;
   414     val m = (! goals_limit);
   415     val ngoals = nprems_of th;
   416   in
   417     [Pretty.str ("Level " ^ string_of_int n ^
   418       (if ngoals > 0 then " (" ^ string_of_int ngoals ^ " subgoal" ^
   419         (if ngoals <> 1 then "s" else "") ^ ")"
   420       else ""))] @
   421     Goal_Display.pretty_goals_without_context m th
   422   end |> Pretty.chunks |> Pretty.writeln;
   423 
   424 (*Printing can raise exceptions, so the assignment occurs last.
   425   Can do   setstate[(st,Seq.empty)]  to set st as the state.  *)
   426 fun setstate newgoals =
   427   (print_top (pop newgoals);  undo_list := newgoals :: !undo_list);
   428 
   429 (*Given a proof state transformation, return a command that updates
   430     the goal stack*)
   431 fun make_command com = setstate (com (pop (getstate())));
   432 
   433 (*Apply a function on proof states to the current goal stack*)
   434 fun apply_fun f = f (pop(getstate()));
   435 
   436 (*Return the top theorem, representing the proof state*)
   437 fun topthm () = apply_fun  (fn ((th,_), _) => th);
   438 
   439 (*Return the final result.  *)
   440 fun result () = !curr_mkresult (true, topthm());
   441 
   442 (*Return the result UNCHECKED that it equals the goal -- for synthesis,
   443   answer extraction, or other instantiation of Vars *)
   444 fun uresult () = !curr_mkresult (false, topthm());
   445 
   446 (*Get subgoal i from goal stack*)
   447 fun getgoal i = Logic.get_goal (prop_of (topthm())) i;
   448 
   449 (*Return subgoal i's hypotheses as meta-level assumptions.
   450   For debugging uses of METAHYPS*)
   451 local exception GETHYPS of thm list
   452 in
   453 fun gethyps i =
   454     (METAHYPS (fn hyps => raise (GETHYPS hyps)) i (topthm());  [])
   455     handle GETHYPS hyps => hyps
   456 end;
   457 
   458 (*Prints exceptions nicely at top level;
   459   raises the exception in order to have a polymorphic type!*)
   460 fun print_exn e = (print_sign_exn_unit (Thm.theory_of_thm (topthm())) e;  raise e);
   461 
   462 (*Which thms could apply to goal i? (debugs tactics involving filter_thms) *)
   463 fun filter_goal could ths i = filter_thms could (999, getgoal i, ths);
   464 
   465 (*For inspecting earlier levels of the backward proof*)
   466 fun chop_level n (pair,pairs) =
   467   let val level = length pairs
   468   in  if n<0 andalso ~n <= level
   469       then  List.drop (pair::pairs, ~n)
   470       else if 0<=n andalso n<= level
   471       then  List.drop (pair::pairs, level - n)
   472       else  error ("Level number must lie between 0 and " ^
   473                    string_of_int level)
   474   end;
   475 
   476 (*Print the given level of the proof; prlev ~1 prints previous level*)
   477 fun prlev n = apply_fun (print_top o pop o (chop_level n));
   478 fun pr () = apply_fun print_top;
   479 
   480 (*Set goals_limit and print again*)
   481 fun prlim n = (goals_limit:=n; pr());
   482 
   483 (** the goal.... commands
   484     Read main goal.  Set global variables curr_prems, curr_mkresult.
   485     Initial subgoal and premises are rewritten using rths. **)
   486 
   487 (*Version taking the goal as a cterm; if you have a term t and theory thy, use
   488     goalw_cterm rths (cterm_of thy t);      *)
   489 fun agoalw_cterm atomic rths chorn =
   490   let val (prems, st0, mkresult) = prepare_proof atomic rths chorn
   491   in  undo_list := [];
   492       setstate [ (st0, Seq.empty) ];
   493       curr_prems := prems;
   494       curr_mkresult := mkresult;
   495       prems
   496   end;
   497 
   498 val goalw_cterm = agoalw_cterm false;
   499 
   500 (*Version taking the goal as a string*)
   501 fun agoalw atomic thy rths agoal =
   502     agoalw_cterm atomic rths (cterm_of thy (read_prop thy agoal))
   503     handle ERROR msg => cat_error msg (*from type_assign, etc via prepare_proof*)
   504         ("The error(s) above occurred for " ^ quote agoal);
   505 
   506 val goalw = agoalw false;
   507 fun goal thy = goalw thy [];
   508 
   509 (*now the versions that wrap the goal up in `Goal' to make it atomic*)
   510 fun Goalw thms s = agoalw true (ML_Context.the_global_context ()) thms s;
   511 val Goal = Goalw [];
   512 
   513 (*simple version with minimal amount of checking and postprocessing*)
   514 fun simple_prove_goal_cterm G f =
   515   let
   516     val As = Drule.strip_imp_prems G;
   517     val B = Drule.strip_imp_concl G;
   518     val asms = map Assumption.assume As;
   519     fun check NONE = error "prove_goal: tactic failed"
   520       | check (SOME (thm, _)) = (case nprems_of thm of
   521             0 => thm
   522           | i => !result_error_fn thm (string_of_int i ^ " unsolved goals!"))
   523   in
   524     Drule.export_without_context (implies_intr_list As
   525       (check (Seq.pull (EVERY (f asms) (Thm.trivial B)))))
   526   end;
   527 
   528 
   529 (*Proof step "by" the given tactic -- apply tactic to the proof state*)
   530 fun by_com tac ((th,ths), pairs) : gstack =
   531   (case  Seq.pull(tac th)  of
   532      NONE      => error"by: tactic failed"
   533    | SOME(th2,ths2) =>
   534        (if Thm.eq_thm(th,th2)
   535           then warning "Warning: same as previous level"
   536           else if Thm.eq_thm_thy(th,th2) then ()
   537           else warning ("Warning: theory of proof state has changed" ^
   538                        thy_error (Thm.theory_of_thm th, Thm.theory_of_thm th2));
   539        ((th2,ths2)::(th,ths)::pairs)));
   540 
   541 fun by tac = cond_timeit (!Output.timing) ""
   542     (fn() => make_command (by_com tac));
   543 
   544 (* byev[tac1,...,tacn] applies tac1 THEN ... THEN tacn.
   545    Good for debugging proofs involving prove_goal.*)
   546 val byev = by o EVERY;
   547 
   548 
   549 (*Backtracking means find an alternative result from a tactic.
   550   If none at this level, try earlier levels*)
   551 fun backtrack [] = error"back: no alternatives"
   552   | backtrack ((th,thstr) :: pairs) =
   553      (case Seq.pull thstr of
   554           NONE      => (writeln"Going back a level..."; backtrack pairs)
   555         | SOME(th2,thstr2) =>
   556            (if Thm.eq_thm(th,th2)
   557               then warning "Warning: same as previous choice at this level"
   558               else if Thm.eq_thm_thy(th,th2) then ()
   559               else warning "Warning: theory of proof state has changed";
   560             (th2,thstr2)::pairs));
   561 
   562 fun back() = setstate (backtrack (getstate()));
   563 
   564 (*Chop back to previous level of the proof*)
   565 fun choplev n = make_command (chop_level n);
   566 
   567 (*Chopping back the goal stack*)
   568 fun chop () = make_command (fn (_,pairs) => pairs);
   569 
   570 (*Restore the previous proof state;  discard current state. *)
   571 fun undo() = case !undo_list of
   572       [] => error"No proof state"
   573     | [_] => error"Already at initial state"
   574     | _::newundo =>  (undo_list := newundo;  pr()) ;
   575 
   576 
   577 (*** Managing the proof stack ***)
   578 
   579 fun save_proof() = Proof(!undo_list, !curr_prems, !curr_mkresult);
   580 
   581 fun restore_proof(Proof(ul,prems,mk)) =
   582  (undo_list:= ul;  curr_prems:= prems;  curr_mkresult := mk;  prems);
   583 
   584 
   585 fun top_proof() = case !proofstack of
   586         [] => error("Stack of proof attempts is empty!")
   587     | p::ps => (p,ps);
   588 
   589 (*  push a copy of the current proof state on to the stack *)
   590 fun push_proof() = (proofstack := (save_proof() :: !proofstack));
   591 
   592 (* discard the top proof state of the stack *)
   593 fun pop_proof() =
   594   let val (p,ps) = top_proof()
   595       val prems = restore_proof p
   596   in proofstack := ps;  pr();  prems end;
   597 
   598 (* rotate the stack so that the top element goes to the bottom *)
   599 fun rotate_proof() =
   600   let val (p,ps) = top_proof()
   601   in proofstack := ps@[save_proof()];
   602      restore_proof p;
   603      pr();
   604      !curr_prems
   605   end;
   606 
   607 
   608 (** theorem bindings **)
   609 
   610 fun qed name = ML_Context.ml_store_thm (name, result ());
   611 fun qed_goal name thy goal tacsf = ML_Context.ml_store_thm (name, prove_goal thy goal tacsf);
   612 fun qed_goalw name thy rews goal tacsf =
   613   ML_Context.ml_store_thm (name, prove_goalw thy rews goal tacsf);
   614 fun qed_spec_mp name =
   615   ML_Context.ml_store_thm (name, Object_Logic.rulify_no_asm (result ()));
   616 fun qed_goal_spec_mp name thy s p =
   617   bind_thm (name, Object_Logic.rulify_no_asm (prove_goal thy s p));
   618 fun qed_goalw_spec_mp name thy defs s p =
   619   bind_thm (name, Object_Logic.rulify_no_asm (prove_goalw thy defs s p));
   620 
   621 end;
   622