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