src/Pure/old_goals.ML
author wenzelm
Tue Jul 21 01:03:18 2009 +0200 (2009-07-21)
changeset 32091 30e2ffbba718
parent 32089 568a23753e3a
child 32145 220c9e439d39
permissions -rw-r--r--
proper context for Display.pretty_thm etc. or old-style versions Display.pretty_thm_global, Display.pretty_thm_without_context etc.;
     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 GOALS =
    12 sig
    13   val the_context: unit -> theory
    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 topthm: unit -> thm
    18   val result: unit -> thm
    19   val uresult: unit -> thm
    20   val getgoal: int -> term
    21   val gethyps: int -> thm list
    22   val prlev: int -> unit
    23   val pr: unit -> unit
    24   val prlim: int -> unit
    25   val goal: theory -> string -> thm list
    26   val goalw: theory -> thm list -> string -> thm list
    27   val Goal: string -> thm list
    28   val Goalw: thm list -> string -> thm list
    29   val by: tactic -> unit
    30   val back: unit -> unit
    31   val choplev: int -> unit
    32   val undo: unit -> unit
    33   val qed: string -> unit
    34   val qed_goal: string -> theory -> string -> (thm list -> tactic list) -> unit
    35   val qed_goalw: string -> theory -> thm list -> string
    36     -> (thm list -> tactic list) -> unit
    37   val qed_spec_mp: string -> unit
    38   val qed_goal_spec_mp: string -> theory -> string -> (thm list -> tactic list) -> unit
    39   val qed_goalw_spec_mp: string -> theory -> thm list -> string
    40     -> (thm list -> tactic list) -> unit
    41 end;
    42 
    43 signature OLD_GOALS =
    44 sig
    45   include GOALS
    46   val simple_read_term: theory -> typ -> string -> term
    47   val read_term: theory -> string -> term
    48   val read_prop: theory -> string -> term
    49   type proof
    50   val chop: unit -> unit
    51   val reset_goals: unit -> unit
    52   val result_error_fn: (thm -> string -> thm) ref
    53   val print_sign_exn: theory -> exn -> 'a
    54   val prove_goalw_cterm: thm list->cterm->(thm list->tactic list)->thm
    55   val prove_goalw_cterm_nocheck: thm list->cterm->(thm list->tactic list)->thm
    56   val print_exn: exn -> 'a
    57   val filter_goal: (term*term->bool) -> thm list -> int -> thm list
    58   val goalw_cterm: thm list -> cterm -> thm list
    59   val simple_prove_goal_cterm: cterm->(thm list->tactic list)->thm
    60   val byev: tactic list -> unit
    61   val save_proof: unit -> proof
    62   val restore_proof: proof -> thm list
    63   val push_proof: unit -> unit
    64   val pop_proof: unit -> thm list
    65   val rotate_proof: unit -> thm list
    66 end;
    67 
    68 structure OldGoals: OLD_GOALS =
    69 struct
    70 
    71 (* global context *)
    72 
    73 val the_context = ML_Context.the_global_context;
    74 
    75 
    76 (* old ways of reading terms *)
    77 
    78 fun simple_read_term thy T s =
    79   let
    80     val ctxt = ProofContext.init thy
    81       |> ProofContext.allow_dummies
    82       |> ProofContext.set_mode ProofContext.mode_schematic;
    83     val parse = if T = propT then Syntax.parse_prop else Syntax.parse_term;
    84   in parse ctxt s |> TypeInfer.constrain T |> Syntax.check_term ctxt end;
    85 
    86 fun read_term thy = simple_read_term thy dummyT;
    87 fun read_prop thy = simple_read_term thy propT;
    88 
    89 
    90 
    91 (*** Goal package ***)
    92 
    93 (*Each level of goal stack includes a proof state and alternative states,
    94   the output of the tactic applied to the preceeding level.  *)
    95 type gstack = (thm * thm Seq.seq) list;
    96 
    97 datatype proof = Proof of gstack list * thm list * (bool*thm->thm);
    98 
    99 
   100 (*** References ***)
   101 
   102 (*Current assumption list -- set by "goal".*)
   103 val curr_prems = ref([] : thm list);
   104 
   105 (*Return assumption list -- useful if you didn't save "goal"'s result. *)
   106 fun premises() = !curr_prems;
   107 
   108 (*Current result maker -- set by "goal", used by "result".  *)
   109 fun init_mkresult _ = error "No goal has been supplied in subgoal module";
   110 val curr_mkresult = ref (init_mkresult: bool*thm->thm);
   111 
   112 (*List of previous goal stacks, for the undo operation.  Set by setstate.
   113   A list of lists!*)
   114 val undo_list = ref([[(asm_rl, Seq.empty)]] : gstack list);
   115 
   116 (* Stack of proof attempts *)
   117 val proofstack = ref([]: proof list);
   118 
   119 (*reset all refs*)
   120 fun reset_goals () =
   121   (curr_prems := []; curr_mkresult := init_mkresult;
   122     undo_list := [[(asm_rl, Seq.empty)]]);
   123 
   124 
   125 (*** Setting up goal-directed proof ***)
   126 
   127 (*Generates the list of new theories when the proof state's theory changes*)
   128 fun thy_error (thy,thy') =
   129   let val names = Context.display_names thy' \\ Context.display_names thy
   130   in  case names of
   131         [name] => "\nNew theory: " ^ name
   132       | _       => "\nNew theories: " ^ space_implode ", " names
   133   end;
   134 
   135 (*Default action is to print an error message; could be suppressed for
   136   special applications.*)
   137 fun result_error_default state msg : thm =
   138   Pretty.str "Bad final proof state:" :: Display_Goal.pretty_goals (!goals_limit) state @
   139     [Pretty.str msg, Pretty.str "Proof failed!"] |> Pretty.chunks |> Pretty.string_of |> error;
   140 
   141 val result_error_fn = ref result_error_default;
   142 
   143 
   144 (*Common treatment of "goal" and "prove_goal":
   145   Return assumptions, initial proof state, and function to make result.
   146   "atomic" indicates if the goal should be wrapped up in the function
   147   "Goal::prop=>prop" to avoid assumptions being returned separately.
   148 *)
   149 fun prepare_proof atomic rths chorn =
   150   let
   151       val _ = legacy_feature "Old goal command";
   152       val thy = Thm.theory_of_cterm chorn;
   153       val horn = Thm.term_of chorn;
   154       val _ = Term.no_dummy_patterns horn handle TERM (msg, _) => error msg;
   155       val (As, B) = Logic.strip_horn horn;
   156       val atoms = atomic andalso
   157             forall (fn t => not (can Logic.dest_implies t orelse Logic.is_all t)) As;
   158       val (As,B) = if atoms then ([],horn) else (As,B);
   159       val cAs = map (cterm_of thy) As;
   160       val prems = map (rewrite_rule rths o Thm.forall_elim_vars 0 o Thm.assume) cAs;
   161       val cB = cterm_of thy B;
   162       val st0 = let val st = Goal.init cB |> fold Thm.weaken cAs
   163                 in  rewrite_goals_rule rths st end
   164       (*discharges assumptions from state in the order they appear in goal;
   165         checks (if requested) that resulting theorem is equivalent to goal. *)
   166       fun mkresult (check,state) =
   167         let val state = Seq.hd (flexflex_rule state)
   168                         handle THM _ => state   (*smash flexflex pairs*)
   169             val ngoals = nprems_of state
   170             val ath = implies_intr_list cAs state
   171             val th = Goal.conclude ath
   172             val thy' = Thm.theory_of_thm th
   173             val {hyps, prop, ...} = Thm.rep_thm th
   174             val final_th = standard th
   175         in  if not check then final_th
   176             else if not (Theory.eq_thy(thy,thy')) then !result_error_fn state
   177                 ("Theory of proof state has changed!" ^
   178                  thy_error (thy,thy'))
   179             else if ngoals>0 then !result_error_fn state
   180                 (string_of_int ngoals ^ " unsolved goals!")
   181             else if not (null hyps) then !result_error_fn state
   182                 ("Additional hypotheses:\n" ^
   183                  cat_lines (map (Syntax.string_of_term_global thy) hyps))
   184             else if Pattern.matches thy
   185                                     (Envir.beta_norm (term_of chorn), Envir.beta_norm prop)
   186                  then final_th
   187             else  !result_error_fn state "proved a different theorem"
   188         end
   189   in
   190      if Theory.eq_thy(thy, Thm.theory_of_thm st0)
   191      then (prems, st0, mkresult)
   192      else error ("Definitions would change the proof state's theory" ^
   193                  thy_error (thy, Thm.theory_of_thm st0))
   194   end
   195   handle THM(s,_,_) => error("prepare_proof: exception THM was raised!\n" ^ s);
   196 
   197 (*Prints exceptions readably to users*)
   198 fun print_sign_exn_unit thy e =
   199   case e of
   200      THM (msg,i,thms) =>
   201          (writeln ("Exception THM " ^ string_of_int i ^ " raised:\n" ^ msg);
   202           List.app (writeln o Display.string_of_thm_global thy) thms)
   203    | THEORY (msg,thys) =>
   204          (writeln ("Exception THEORY raised:\n" ^ msg);
   205           List.app (writeln o Context.str_of_thy) thys)
   206    | TERM (msg,ts) =>
   207          (writeln ("Exception TERM raised:\n" ^ msg);
   208           List.app (writeln o Syntax.string_of_term_global thy) ts)
   209    | TYPE (msg,Ts,ts) =>
   210          (writeln ("Exception TYPE raised:\n" ^ msg);
   211           List.app (writeln o Syntax.string_of_typ_global thy) Ts;
   212           List.app (writeln o Syntax.string_of_term_global thy) ts)
   213    | e => raise e;
   214 
   215 (*Prints an exception, then fails*)
   216 fun print_sign_exn thy e = (print_sign_exn_unit thy e; raise ERROR "");
   217 
   218 (** the prove_goal.... commands
   219     Prove theorem using the listed tactics; check it has the specified form.
   220     Augment theory with all type assignments of goal.
   221     Syntax is similar to "goal" command for easy keyboard use. **)
   222 
   223 (*Version taking the goal as a cterm*)
   224 fun prove_goalw_cterm_general check rths chorn tacsf =
   225   let val (prems, st0, mkresult) = prepare_proof false rths chorn
   226       val tac = EVERY (tacsf prems)
   227       fun statef() =
   228           (case Seq.pull (tac st0) of
   229                SOME(st,_) => st
   230              | _ => error ("prove_goal: tactic failed"))
   231   in  mkresult (check, cond_timeit (!Output.timing) "" statef)  end
   232   handle e => (print_sign_exn_unit (Thm.theory_of_cterm chorn) e;
   233                writeln ("The exception above was raised for\n" ^
   234                       Display.string_of_cterm chorn); raise e);
   235 
   236 (*Two variants: one checking the result, one not.
   237   Neither prints runtime messages: they are for internal packages.*)
   238 fun prove_goalw_cterm rths chorn =
   239         setmp Output.timing false (prove_goalw_cterm_general true rths chorn)
   240 and prove_goalw_cterm_nocheck rths chorn =
   241         setmp Output.timing false (prove_goalw_cterm_general false rths chorn);
   242 
   243 
   244 (*Version taking the goal as a string*)
   245 fun prove_goalw thy rths agoal tacsf =
   246   let val chorn = cterm_of thy (read_prop thy agoal)
   247   in prove_goalw_cterm_general true rths chorn tacsf end
   248   handle ERROR msg => cat_error msg (*from read_prop?*)
   249                 ("The error(s) above occurred for " ^ quote agoal);
   250 
   251 (*String version with no meta-rewrite-rules*)
   252 fun prove_goal thy = prove_goalw thy [];
   253 
   254 
   255 
   256 (*** Commands etc ***)
   257 
   258 (*Return the current goal stack, if any, from undo_list*)
   259 fun getstate() : gstack = case !undo_list of
   260       []   => error"No current state in subgoal module"
   261     | x::_ => x;
   262 
   263 (*Pops the given goal stack*)
   264 fun pop [] = error"Cannot go back past the beginning of the proof!"
   265   | pop (pair::pairs) = (pair,pairs);
   266 
   267 
   268 (* Print a level of the goal stack *)
   269 
   270 fun print_top ((th, _), pairs) =
   271   let
   272     val n = length pairs;
   273     val m = (! goals_limit);
   274     val ngoals = nprems_of th;
   275   in
   276     [Pretty.str ("Level " ^ string_of_int n ^
   277       (if ngoals > 0 then " (" ^ string_of_int ngoals ^ " subgoal" ^
   278         (if ngoals <> 1 then "s" else "") ^ ")"
   279       else ""))] @
   280     Display_Goal.pretty_goals m th
   281   end |> Pretty.chunks |> Pretty.writeln;
   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 = apply_fun (print_top o pop o (chop_level n));
   337 fun 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 (cterm_of thy (read_prop thy agoal))
   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 (ML_Context.the_global_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 _ = legacy_feature "Old goal command";
   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 Thm.eq_thm(th,th2)
   395           then warning "Warning: same as previous level"
   396           else if Thm.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 Thm.eq_thm(th,th2)
   417               then warning "Warning: same as previous choice at this level"
   418               else if Thm.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 (** theorem bindings **)
   468 
   469 fun qed name = ML_Context.ml_store_thm (name, result ());
   470 fun qed_goal name thy goal tacsf = ML_Context.ml_store_thm (name, prove_goal thy goal tacsf);
   471 fun qed_goalw name thy rews goal tacsf =
   472   ML_Context.ml_store_thm (name, prove_goalw thy rews goal tacsf);
   473 fun qed_spec_mp name =
   474   ML_Context.ml_store_thm (name, ObjectLogic.rulify_no_asm (result ()));
   475 fun qed_goal_spec_mp name thy s p =
   476   bind_thm (name, ObjectLogic.rulify_no_asm (prove_goal thy s p));
   477 fun qed_goalw_spec_mp name thy defs s p =
   478   bind_thm (name, ObjectLogic.rulify_no_asm (prove_goalw thy defs s p));
   479 
   480 end;
   481 
   482 structure Goals: GOALS = OldGoals;
   483 open Goals;