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