src/Pure/old_goals.ML
author wenzelm
Tue Nov 28 00:35:21 2006 +0100 (2006-11-28)
changeset 21566 af2932baf068
parent 20872 528054ca23e3
child 22109 9188aed2c3ca
permissions -rw-r--r--
dest_term: strip_imp_concl;
     1 (*  Title:      Pure/old_goals.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1993  University of Cambridge
     5 
     6 Old-style goal stack package.  The goal stack initially holds a dummy
     7 proof, and can never become empty.  Each goal stack consists of a list
     8 of levels.  The undo list is a list of goal stacks.  Finally, there
     9 may be a stack of pending proofs.
    10 *)
    11 
    12 signature GOALS =
    13 sig
    14   val premises: unit -> thm list
    15   val prove_goal: theory -> string -> (thm list -> tactic list) -> thm
    16   val prove_goalw: theory -> thm list -> string -> (thm list -> tactic list) -> thm
    17   val disable_pr: unit -> unit
    18   val enable_pr: unit -> unit
    19   val topthm: unit -> thm
    20   val result: unit -> thm
    21   val uresult: unit -> thm
    22   val getgoal: int -> term
    23   val gethyps: int -> thm list
    24   val prlev: int -> unit
    25   val pr: unit -> unit
    26   val prlim: int -> unit
    27   val goal: theory -> string -> thm list
    28   val goalw: theory -> thm list -> string -> thm list
    29   val Goal: string -> thm list
    30   val Goalw: thm list -> string -> thm list
    31   val by: tactic -> unit
    32   val back: unit -> unit
    33   val choplev: int -> unit
    34   val undo: unit -> unit
    35   val bind_thm: string * thm -> unit
    36   val bind_thms: string * thm list -> unit
    37   val qed: string -> unit
    38   val qed_goal: string -> theory -> string -> (thm list -> tactic list) -> unit
    39   val qed_goalw: string -> theory -> thm list -> string
    40     -> (thm list -> tactic list) -> unit
    41   val qed_spec_mp: string -> unit
    42   val qed_goal_spec_mp: string -> theory -> string -> (thm list -> tactic list) -> unit
    43   val qed_goalw_spec_mp: string -> theory -> thm list -> string
    44     -> (thm list -> tactic list) -> unit
    45   val no_qed: unit -> unit
    46 end;
    47 
    48 signature OLD_GOALS =
    49 sig
    50   include GOALS
    51   type proof
    52   val chop: unit -> unit
    53   val reset_goals: unit -> unit
    54   val result_error_fn: (thm -> string -> thm) ref
    55   val print_sign_exn: theory -> exn -> 'a
    56   val prove_goalw_cterm: thm list->cterm->(thm list->tactic list)->thm
    57   val prove_goalw_cterm_nocheck: thm list->cterm->(thm list->tactic list)->thm
    58   val quick_and_dirty_prove_goalw_cterm: theory -> thm list -> cterm
    59     -> (thm list -> tactic list) -> thm
    60   val print_exn: exn -> 'a
    61   val filter_goal: (term*term->bool) -> thm list -> int -> thm list
    62   val goalw_cterm: thm list -> cterm -> thm list
    63   val simple_prove_goal_cterm: cterm->(thm list->tactic list)->thm
    64   val byev: tactic list -> unit
    65   val save_proof: unit -> proof
    66   val restore_proof: proof -> thm list
    67   val push_proof: unit -> unit
    68   val pop_proof: unit -> thm list
    69   val rotate_proof: unit -> thm list
    70   val bws: thm list -> unit
    71   val bw: thm -> unit
    72   val brs: thm list -> int -> unit
    73   val br: thm -> int -> unit
    74   val bes: thm list -> int -> unit
    75   val be: thm -> int -> unit
    76   val bds: thm list -> int -> unit
    77   val bd: thm -> int -> unit
    78   val ba: int -> unit
    79   val ren: string -> int -> unit
    80   val frs: thm list -> unit
    81   val fr: thm -> unit
    82   val fes: thm list -> unit
    83   val fe: thm -> unit
    84   val fds: thm list -> unit
    85   val fd: thm -> unit
    86   val fa: unit -> unit
    87 end;
    88 
    89 structure OldGoals: OLD_GOALS =
    90 struct
    91 
    92 (*** Goal package ***)
    93 
    94 (*Each level of goal stack includes a proof state and alternative states,
    95   the output of the tactic applied to the preceeding level.  *)
    96 type gstack = (thm * thm Seq.seq) list;
    97 
    98 datatype proof = Proof of gstack list * thm list * (bool*thm->thm);
    99 
   100 
   101 (*** References ***)
   102 
   103 (*Current assumption list -- set by "goal".*)
   104 val curr_prems = ref([] : thm list);
   105 
   106 (*Return assumption list -- useful if you didn't save "goal"'s result. *)
   107 fun premises() = !curr_prems;
   108 
   109 (*Current result maker -- set by "goal", used by "result".  *)
   110 fun init_mkresult _ = error "No goal has been supplied in subgoal module";
   111 val curr_mkresult = ref (init_mkresult: bool*thm->thm);
   112 
   113 val dummy = Thm.trivial (read_cterm ProtoPure.thy ("PROP No_goal_has_been_supplied", propT));
   114 
   115 (*List of previous goal stacks, for the undo operation.  Set by setstate.
   116   A list of lists!*)
   117 val undo_list = ref([[(dummy, Seq.empty)]] : gstack list);
   118 
   119 (* Stack of proof attempts *)
   120 val proofstack = ref([]: proof list);
   121 
   122 (*reset all refs*)
   123 fun reset_goals () =
   124   (curr_prems := []; curr_mkresult := init_mkresult;
   125     undo_list := [[(dummy, Seq.empty)]]);
   126 
   127 
   128 (*** Setting up goal-directed proof ***)
   129 
   130 (*Generates the list of new theories when the proof state's theory changes*)
   131 fun thy_error (thy,thy') =
   132   let val names = Context.names_of thy' \\ Context.names_of thy
   133   in  case names of
   134         [name] => "\nNew theory: " ^ name
   135       | _       => "\nNew theories: " ^ space_implode ", " names
   136   end;
   137 
   138 (*Default action is to print an error message; could be suppressed for
   139   special applications.*)
   140 fun result_error_default state msg : thm =
   141   Pretty.str "Bad final proof state:" :: Display.pretty_goals (!goals_limit) state @
   142     [Pretty.str msg, Pretty.str "Proof failed!"] |> Pretty.chunks |> Pretty.string_of |> error;
   143 
   144 val result_error_fn = ref result_error_default;
   145 
   146 
   147 (*Common treatment of "goal" and "prove_goal":
   148   Return assumptions, initial proof state, and function to make result.
   149   "atomic" indicates if the goal should be wrapped up in the function
   150   "Goal::prop=>prop" to avoid assumptions being returned separately.
   151 *)
   152 fun prepare_proof atomic rths chorn =
   153   let
   154       val _ = warning "Obsolete goal command encountered";
   155       val {thy, t=horn,...} = rep_cterm chorn;
   156       val _ = Term.no_dummy_patterns horn handle TERM (msg, _) => error msg;
   157       val (As, B) = Logic.strip_horn horn;
   158       val atoms = atomic andalso
   159             forall (fn t => not (can Logic.dest_implies t orelse Logic.is_all t)) As;
   160       val (As,B) = if atoms then ([],horn) else (As,B);
   161       val cAs = map (cterm_of thy) As;
   162       val prems = map (rewrite_rule rths o forall_elim_vars 0 o Thm.assume) cAs;
   163       val cB = cterm_of thy B;
   164       val st0 = let val st = Goal.init cB |> fold Thm.weaken cAs
   165                 in  rewrite_goals_rule rths st end
   166       (*discharges assumptions from state in the order they appear in goal;
   167         checks (if requested) that resulting theorem is equivalent to goal. *)
   168       fun mkresult (check,state) =
   169         let val state = Seq.hd (flexflex_rule state)
   170                         handle THM _ => state   (*smash flexflex pairs*)
   171             val ngoals = nprems_of state
   172             val ath = implies_intr_list cAs state
   173             val th = Goal.conclude ath
   174             val {hyps,prop,thy=thy',...} = rep_thm th
   175             val final_th = standard th
   176         in  if not check then final_th
   177             else if not (eq_thy(thy,thy')) then !result_error_fn state
   178                 ("Theory of proof state has changed!" ^
   179                  thy_error (thy,thy'))
   180             else if ngoals>0 then !result_error_fn state
   181                 (string_of_int ngoals ^ " unsolved goals!")
   182             else if not (null hyps) then !result_error_fn state
   183                 ("Additional hypotheses:\n" ^
   184                  cat_lines (map (Sign.string_of_term thy) hyps))
   185             else if Pattern.matches thy
   186                                     (Envir.beta_norm (term_of chorn), Envir.beta_norm prop)
   187                  then final_th
   188             else  !result_error_fn state "proved a different theorem"
   189         end
   190   in
   191      if eq_thy(thy, Thm.theory_of_thm st0)
   192      then (prems, st0, mkresult)
   193      else error ("Definitions would change the proof state's theory" ^
   194                  thy_error (thy, Thm.theory_of_thm st0))
   195   end
   196   handle THM(s,_,_) => error("prepare_proof: exception THM was raised!\n" ^ s);
   197 
   198 (*Prints exceptions readably to users*)
   199 fun print_sign_exn_unit thy e =
   200   case e of
   201      THM (msg,i,thms) =>
   202          (writeln ("Exception THM " ^ string_of_int i ^ " raised:\n" ^ msg);
   203           List.app print_thm thms)
   204    | THEORY (msg,thys) =>
   205          (writeln ("Exception THEORY raised:\n" ^ msg);
   206           List.app (writeln o Context.str_of_thy) thys)
   207    | TERM (msg,ts) =>
   208          (writeln ("Exception TERM raised:\n" ^ msg);
   209           List.app (writeln o Sign.string_of_term thy) ts)
   210    | TYPE (msg,Ts,ts) =>
   211          (writeln ("Exception TYPE raised:\n" ^ msg);
   212           List.app (writeln o Sign.string_of_typ thy) Ts;
   213           List.app (writeln o Sign.string_of_term thy) ts)
   214    | e => raise e;
   215 
   216 (*Prints an exception, then fails*)
   217 fun print_sign_exn thy e = (print_sign_exn_unit thy e; raise ERROR "");
   218 
   219 (** the prove_goal.... commands
   220     Prove theorem using the listed tactics; check it has the specified form.
   221     Augment theory with all type assignments of goal.
   222     Syntax is similar to "goal" command for easy keyboard use. **)
   223 
   224 (*Version taking the goal as a cterm*)
   225 fun prove_goalw_cterm_general check rths chorn tacsf =
   226   let val (prems, st0, mkresult) = prepare_proof false rths chorn
   227       val tac = EVERY (tacsf prems)
   228       fun statef() =
   229           (case Seq.pull (tac st0) of
   230                SOME(st,_) => st
   231              | _ => error ("prove_goal: tactic failed"))
   232   in  mkresult (check, cond_timeit (!Output.timing) statef)  end
   233   handle e => (print_sign_exn_unit (#thy (rep_cterm chorn)) e;
   234                writeln ("The exception above was raised for\n" ^
   235                       Display.string_of_cterm chorn); raise e);
   236 
   237 (*Two variants: one checking the result, one not.
   238   Neither prints runtime messages: they are for internal packages.*)
   239 fun prove_goalw_cterm rths chorn =
   240         setmp Output.timing false (prove_goalw_cterm_general true rths chorn)
   241 and prove_goalw_cterm_nocheck rths chorn =
   242         setmp Output.timing false (prove_goalw_cterm_general false rths chorn);
   243 
   244 
   245 (*Version taking the goal as a string*)
   246 fun prove_goalw thy rths agoal tacsf =
   247   let val chorn = read_cterm thy (agoal, propT)
   248   in prove_goalw_cterm_general true rths chorn tacsf end
   249   handle ERROR msg => cat_error msg (*from read_cterm?*)
   250                 ("The error(s) above occurred for " ^ quote agoal);
   251 
   252 (*String version with no meta-rewrite-rules*)
   253 fun prove_goal thy = prove_goalw thy [];
   254 
   255 (*quick and dirty version (conditional)*)
   256 fun quick_and_dirty_prove_goalw_cterm thy rews ct tacs =
   257   prove_goalw_cterm rews ct
   258     (if ! quick_and_dirty then (K [SkipProof.cheat_tac thy]) else tacs);
   259 
   260 
   261 (*** Commands etc ***)
   262 
   263 (*Return the current goal stack, if any, from undo_list*)
   264 fun getstate() : gstack = case !undo_list of
   265       []   => error"No current state in subgoal module"
   266     | x::_ => x;
   267 
   268 (*Pops the given goal stack*)
   269 fun pop [] = error"Cannot go back past the beginning of the proof!"
   270   | pop (pair::pairs) = (pair,pairs);
   271 
   272 
   273 (* Print a level of the goal stack -- subject to quiet mode *)
   274 
   275 val quiet = ref false;
   276 fun disable_pr () = quiet := true;
   277 fun enable_pr () = quiet := false;
   278 
   279 fun print_top ((th, _), pairs) =
   280   if ! quiet then ()
   281   else ! Display.print_current_goals_fn (length pairs) (! goals_limit) th;
   282 
   283 (*Printing can raise exceptions, so the assignment occurs last.
   284   Can do   setstate[(st,Seq.empty)]  to set st as the state.  *)
   285 fun setstate newgoals =
   286   (print_top (pop newgoals);  undo_list := newgoals :: !undo_list);
   287 
   288 (*Given a proof state transformation, return a command that updates
   289     the goal stack*)
   290 fun make_command com = setstate (com (pop (getstate())));
   291 
   292 (*Apply a function on proof states to the current goal stack*)
   293 fun apply_fun f = f (pop(getstate()));
   294 
   295 (*Return the top theorem, representing the proof state*)
   296 fun topthm () = apply_fun  (fn ((th,_), _) => th);
   297 
   298 (*Return the final result.  *)
   299 fun result () = !curr_mkresult (true, topthm());
   300 
   301 (*Return the result UNCHECKED that it equals the goal -- for synthesis,
   302   answer extraction, or other instantiation of Vars *)
   303 fun uresult () = !curr_mkresult (false, topthm());
   304 
   305 (*Get subgoal i from goal stack*)
   306 fun getgoal i = Logic.get_goal (prop_of (topthm())) i;
   307 
   308 (*Return subgoal i's hypotheses as meta-level assumptions.
   309   For debugging uses of METAHYPS*)
   310 local exception GETHYPS of thm list
   311 in
   312 fun gethyps i =
   313     (METAHYPS (fn hyps => raise (GETHYPS hyps)) i (topthm());  [])
   314     handle GETHYPS hyps => hyps
   315 end;
   316 
   317 (*Prints exceptions nicely at top level;
   318   raises the exception in order to have a polymorphic type!*)
   319 fun print_exn e = (print_sign_exn_unit (Thm.theory_of_thm (topthm())) e;  raise e);
   320 
   321 (*Which thms could apply to goal i? (debugs tactics involving filter_thms) *)
   322 fun filter_goal could ths i = filter_thms could (999, getgoal i, ths);
   323 
   324 (*For inspecting earlier levels of the backward proof*)
   325 fun chop_level n (pair,pairs) =
   326   let val level = length pairs
   327   in  if n<0 andalso ~n <= level
   328       then  List.drop (pair::pairs, ~n)
   329       else if 0<=n andalso n<= level
   330       then  List.drop (pair::pairs, level - n)
   331       else  error ("Level number must lie between 0 and " ^
   332                    string_of_int level)
   333   end;
   334 
   335 (*Print the given level of the proof; prlev ~1 prints previous level*)
   336 fun prlev n = (enable_pr (); apply_fun (print_top o pop o (chop_level n)));
   337 fun pr () = (enable_pr (); apply_fun print_top);
   338 
   339 (*Set goals_limit and print again*)
   340 fun prlim n = (goals_limit:=n; pr());
   341 
   342 (** the goal.... commands
   343     Read main goal.  Set global variables curr_prems, curr_mkresult.
   344     Initial subgoal and premises are rewritten using rths. **)
   345 
   346 (*Version taking the goal as a cterm; if you have a term t and theory thy, use
   347     goalw_cterm rths (cterm_of thy t);      *)
   348 fun agoalw_cterm atomic rths chorn =
   349   let val (prems, st0, mkresult) = prepare_proof atomic rths chorn
   350   in  undo_list := [];
   351       setstate [ (st0, Seq.empty) ];
   352       curr_prems := prems;
   353       curr_mkresult := mkresult;
   354       prems
   355   end;
   356 
   357 val goalw_cterm = agoalw_cterm false;
   358 
   359 (*Version taking the goal as a string*)
   360 fun agoalw atomic thy rths agoal =
   361     agoalw_cterm atomic rths (read_cterm thy (agoal, propT))
   362     handle ERROR msg => cat_error msg (*from type_assign, etc via prepare_proof*)
   363         ("The error(s) above occurred for " ^ quote agoal);
   364 
   365 val goalw = agoalw false;
   366 fun goal thy = goalw thy [];
   367 
   368 (*now the versions that wrap the goal up in `Goal' to make it atomic*)
   369 fun Goalw thms s = agoalw true (Context.the_context ()) thms s;
   370 val Goal = Goalw [];
   371 
   372 (*simple version with minimal amount of checking and postprocessing*)
   373 fun simple_prove_goal_cterm G f =
   374   let
   375     val _ = warning "Obsolete goal command encountered";
   376     val As = Drule.strip_imp_prems G;
   377     val B = Drule.strip_imp_concl G;
   378     val asms = map Assumption.assume As;
   379     fun check NONE = error "prove_goal: tactic failed"
   380       | check (SOME (thm, _)) = (case nprems_of thm of
   381             0 => thm
   382           | i => !result_error_fn thm (string_of_int i ^ " unsolved goals!"))
   383   in
   384     standard (implies_intr_list As
   385       (check (Seq.pull (EVERY (f asms) (trivial B)))))
   386   end;
   387 
   388 
   389 (*Proof step "by" the given tactic -- apply tactic to the proof state*)
   390 fun by_com tac ((th,ths), pairs) : gstack =
   391   (case  Seq.pull(tac th)  of
   392      NONE      => error"by: tactic failed"
   393    | SOME(th2,ths2) =>
   394        (if eq_thm(th,th2)
   395           then warning "Warning: same as previous level"
   396           else if eq_thm_thy(th,th2) then ()
   397           else warning ("Warning: theory of proof state has changed" ^
   398                        thy_error (Thm.theory_of_thm th, Thm.theory_of_thm th2));
   399        ((th2,ths2)::(th,ths)::pairs)));
   400 
   401 fun by tac = cond_timeit (!Output.timing)
   402     (fn() => make_command (by_com tac));
   403 
   404 (* byev[tac1,...,tacn] applies tac1 THEN ... THEN tacn.
   405    Good for debugging proofs involving prove_goal.*)
   406 val byev = by o EVERY;
   407 
   408 
   409 (*Backtracking means find an alternative result from a tactic.
   410   If none at this level, try earlier levels*)
   411 fun backtrack [] = error"back: no alternatives"
   412   | backtrack ((th,thstr) :: pairs) =
   413      (case Seq.pull thstr of
   414           NONE      => (writeln"Going back a level..."; backtrack pairs)
   415         | SOME(th2,thstr2) =>
   416            (if eq_thm(th,th2)
   417               then warning "Warning: same as previous choice at this level"
   418               else if eq_thm_thy(th,th2) then ()
   419               else warning "Warning: theory of proof state has changed";
   420             (th2,thstr2)::pairs));
   421 
   422 fun back() = setstate (backtrack (getstate()));
   423 
   424 (*Chop back to previous level of the proof*)
   425 fun choplev n = make_command (chop_level n);
   426 
   427 (*Chopping back the goal stack*)
   428 fun chop () = make_command (fn (_,pairs) => pairs);
   429 
   430 (*Restore the previous proof state;  discard current state. *)
   431 fun undo() = case !undo_list of
   432       [] => error"No proof state"
   433     | [_] => error"Already at initial state"
   434     | _::newundo =>  (undo_list := newundo;  pr()) ;
   435 
   436 
   437 (*** Managing the proof stack ***)
   438 
   439 fun save_proof() = Proof(!undo_list, !curr_prems, !curr_mkresult);
   440 
   441 fun restore_proof(Proof(ul,prems,mk)) =
   442  (undo_list:= ul;  curr_prems:= prems;  curr_mkresult := mk;  prems);
   443 
   444 
   445 fun top_proof() = case !proofstack of
   446         [] => error("Stack of proof attempts is empty!")
   447     | p::ps => (p,ps);
   448 
   449 (*  push a copy of the current proof state on to the stack *)
   450 fun push_proof() = (proofstack := (save_proof() :: !proofstack));
   451 
   452 (* discard the top proof state of the stack *)
   453 fun pop_proof() =
   454   let val (p,ps) = top_proof()
   455       val prems = restore_proof p
   456   in proofstack := ps;  pr();  prems end;
   457 
   458 (* rotate the stack so that the top element goes to the bottom *)
   459 fun rotate_proof() = let val (p,ps) = top_proof()
   460                     in proofstack := ps@[save_proof()];
   461                        restore_proof p;
   462                        pr();
   463                        !curr_prems
   464                     end;
   465 
   466 
   467 (** Shortcuts for commonly-used tactics **)
   468 
   469 fun bws rls = by (rewrite_goals_tac rls);
   470 fun bw rl = bws [rl];
   471 
   472 fun brs rls i = by (resolve_tac rls i);
   473 fun br rl = brs [rl];
   474 
   475 fun bes rls i = by (eresolve_tac rls i);
   476 fun be rl = bes [rl];
   477 
   478 fun bds rls i = by (dresolve_tac rls i);
   479 fun bd rl = bds [rl];
   480 
   481 fun ba i = by (assume_tac i);
   482 
   483 fun ren str i = by (rename_tac str i);
   484 
   485 (** Shortcuts to work on the first applicable subgoal **)
   486 
   487 fun frs rls = by (FIRSTGOAL (trace_goalno_tac (resolve_tac rls)));
   488 fun fr rl = frs [rl];
   489 
   490 fun fes rls = by (FIRSTGOAL (trace_goalno_tac (eresolve_tac rls)));
   491 fun fe rl = fes [rl];
   492 
   493 fun fds rls = by (FIRSTGOAL (trace_goalno_tac (dresolve_tac rls)));
   494 fun fd rl = fds [rl];
   495 
   496 fun fa() = by (FIRSTGOAL (trace_goalno_tac assume_tac));
   497 
   498 
   499 (** theorem database **)
   500 
   501 fun bind_thm (name, thm) = ThmDatabase.ml_store_thm (name, standard thm);
   502 fun bind_thms (name, thms) = ThmDatabase.ml_store_thms (name, map standard thms);
   503 
   504 fun qed name = ThmDatabase.ml_store_thm (name, result ());
   505 fun qed_goal name thy goal tacsf = ThmDatabase.ml_store_thm (name, prove_goal thy goal tacsf);
   506 fun qed_goalw name thy rews goal tacsf =
   507   ThmDatabase.ml_store_thm (name, prove_goalw thy rews goal tacsf);
   508 fun qed_spec_mp name =
   509   ThmDatabase.ml_store_thm (name, ObjectLogic.rulify_no_asm (result ()));
   510 fun qed_goal_spec_mp name thy s p =
   511   bind_thm (name, ObjectLogic.rulify_no_asm (prove_goal thy s p));
   512 fun qed_goalw_spec_mp name thy defs s p =
   513   bind_thm (name, ObjectLogic.rulify_no_asm (prove_goalw thy defs s p));
   514 
   515 fun no_qed () = ();
   516 
   517 end;
   518 
   519 structure Goals: GOALS = OldGoals;
   520 open Goals;