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