src/Pure/old_goals.ML
author wenzelm
Mon Jun 23 23:45:45 2008 +0200 (2008-06-23)
changeset 27332 94790a9620c3
parent 27256 bcb071683184
child 29091 b81fe045e799
permissions -rw-r--r--
Logic.is_all;
     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   val simple_read_term: theory -> typ -> string -> term
    48   val read_term: theory -> string -> term
    49   val read_prop: theory -> string -> term
    50   type proof
    51   val chop: unit -> unit
    52   val reset_goals: unit -> unit
    53   val result_error_fn: (thm -> string -> thm) ref
    54   val print_sign_exn: theory -> exn -> 'a
    55   val prove_goalw_cterm: thm list->cterm->(thm list->tactic list)->thm
    56   val prove_goalw_cterm_nocheck: thm list->cterm->(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 end;
    68 
    69 structure OldGoals: OLD_GOALS =
    70 struct
    71 
    72 (* global context *)
    73 
    74 val the_context = ML_Context.the_global_context;
    75 
    76 
    77 (* old ways of reading terms *)
    78 
    79 fun simple_read_term thy T s =
    80   let
    81     val ctxt = ProofContext.init thy
    82       |> ProofContext.allow_dummies
    83       |> ProofContext.set_mode ProofContext.mode_schematic;
    84     val parse = if T = propT then Syntax.parse_prop else Syntax.parse_term;
    85   in parse ctxt s |> TypeInfer.constrain T |> Syntax.check_term ctxt end;
    86 
    87 fun read_term thy = simple_read_term thy dummyT;
    88 fun read_prop thy = simple_read_term thy propT;
    89 
    90 
    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 (*List of previous goal stacks, for the undo operation.  Set by setstate.
   114   A list of lists!*)
   115 val undo_list = ref([[(asm_rl, Seq.empty)]] : gstack list);
   116 
   117 (* Stack of proof attempts *)
   118 val proofstack = ref([]: proof list);
   119 
   120 (*reset all refs*)
   121 fun reset_goals () =
   122   (curr_prems := []; curr_mkresult := init_mkresult;
   123     undo_list := [[(asm_rl, Seq.empty)]]);
   124 
   125 
   126 (*** Setting up goal-directed proof ***)
   127 
   128 (*Generates the list of new theories when the proof state's theory changes*)
   129 fun thy_error (thy,thy') =
   130   let val names = Context.names_of thy' \\ Context.names_of thy
   131   in  case names of
   132         [name] => "\nNew theory: " ^ name
   133       | _       => "\nNew theories: " ^ space_implode ", " names
   134   end;
   135 
   136 (*Default action is to print an error message; could be suppressed for
   137   special applications.*)
   138 fun result_error_default state msg : thm =
   139   Pretty.str "Bad final proof state:" :: Display.pretty_goals (!goals_limit) state @
   140     [Pretty.str msg, Pretty.str "Proof failed!"] |> Pretty.chunks |> Pretty.string_of |> error;
   141 
   142 val result_error_fn = ref result_error_default;
   143 
   144 
   145 (*Common treatment of "goal" and "prove_goal":
   146   Return assumptions, initial proof state, and function to make result.
   147   "atomic" indicates if the goal should be wrapped up in the function
   148   "Goal::prop=>prop" to avoid assumptions being returned separately.
   149 *)
   150 fun prepare_proof atomic rths chorn =
   151   let
   152       val _ = legacy_feature "Old goal command";
   153       val thy = Thm.theory_of_cterm chorn;
   154       val horn = Thm.term_of chorn;
   155       val _ = Term.no_dummy_patterns horn handle TERM (msg, _) => error msg;
   156       val (As, B) = Logic.strip_horn horn;
   157       val atoms = atomic andalso
   158             forall (fn t => not (can Logic.dest_implies t orelse Logic.is_all t)) As;
   159       val (As,B) = if atoms then ([],horn) else (As,B);
   160       val cAs = map (cterm_of thy) As;
   161       val prems = map (rewrite_rule rths o Thm.forall_elim_vars 0 o Thm.assume) cAs;
   162       val cB = cterm_of thy B;
   163       val st0 = let val st = Goal.init cB |> fold Thm.weaken cAs
   164                 in  rewrite_goals_rule rths st end
   165       (*discharges assumptions from state in the order they appear in goal;
   166         checks (if requested) that resulting theorem is equivalent to goal. *)
   167       fun mkresult (check,state) =
   168         let val state = Seq.hd (flexflex_rule state)
   169                         handle THM _ => state   (*smash flexflex pairs*)
   170             val ngoals = nprems_of state
   171             val ath = implies_intr_list cAs state
   172             val th = Goal.conclude ath
   173             val thy' = Thm.theory_of_thm th
   174             val {hyps, prop, ...} = Thm.rep_thm th
   175             val final_th = standard th
   176         in  if not check then final_th
   177             else if not (Theory.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 (Syntax.string_of_term_global 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 Theory.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 Display.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 Syntax.string_of_term_global thy) ts)
   210    | TYPE (msg,Ts,ts) =>
   211          (writeln ("Exception TYPE raised:\n" ^ msg);
   212           List.app (writeln o Syntax.string_of_typ_global thy) Ts;
   213           List.app (writeln o Syntax.string_of_term_global 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 (Thm.theory_of_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 = cterm_of thy (read_prop thy agoal)
   248   in prove_goalw_cterm_general true rths chorn tacsf end
   249   handle ERROR msg => cat_error msg (*from read_prop?*)
   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 
   256 
   257 (*** Commands etc ***)
   258 
   259 (*Return the current goal stack, if any, from undo_list*)
   260 fun getstate() : gstack = case !undo_list of
   261       []   => error"No current state in subgoal module"
   262     | x::_ => x;
   263 
   264 (*Pops the given goal stack*)
   265 fun pop [] = error"Cannot go back past the beginning of the proof!"
   266   | pop (pair::pairs) = (pair,pairs);
   267 
   268 
   269 (* Print a level of the goal stack *)
   270 
   271 fun print_top ((th, _), pairs) =
   272   let
   273     val n = length pairs;
   274     val m = (! goals_limit);
   275     val ngoals = nprems_of th;
   276   in
   277     [Pretty.str ("Level " ^ string_of_int n ^
   278       (if ngoals > 0 then " (" ^ string_of_int ngoals ^ " subgoal" ^
   279         (if ngoals <> 1 then "s" else "") ^ ")"
   280       else ""))] @
   281     Display.pretty_goals m th
   282   end |> Pretty.chunks |> Pretty.writeln;
   283 
   284 (*Printing can raise exceptions, so the assignment occurs last.
   285   Can do   setstate[(st,Seq.empty)]  to set st as the state.  *)
   286 fun setstate newgoals =
   287   (print_top (pop newgoals);  undo_list := newgoals :: !undo_list);
   288 
   289 (*Given a proof state transformation, return a command that updates
   290     the goal stack*)
   291 fun make_command com = setstate (com (pop (getstate())));
   292 
   293 (*Apply a function on proof states to the current goal stack*)
   294 fun apply_fun f = f (pop(getstate()));
   295 
   296 (*Return the top theorem, representing the proof state*)
   297 fun topthm () = apply_fun  (fn ((th,_), _) => th);
   298 
   299 (*Return the final result.  *)
   300 fun result () = !curr_mkresult (true, topthm());
   301 
   302 (*Return the result UNCHECKED that it equals the goal -- for synthesis,
   303   answer extraction, or other instantiation of Vars *)
   304 fun uresult () = !curr_mkresult (false, topthm());
   305 
   306 (*Get subgoal i from goal stack*)
   307 fun getgoal i = Logic.get_goal (prop_of (topthm())) i;
   308 
   309 (*Return subgoal i's hypotheses as meta-level assumptions.
   310   For debugging uses of METAHYPS*)
   311 local exception GETHYPS of thm list
   312 in
   313 fun gethyps i =
   314     (METAHYPS (fn hyps => raise (GETHYPS hyps)) i (topthm());  [])
   315     handle GETHYPS hyps => hyps
   316 end;
   317 
   318 (*Prints exceptions nicely at top level;
   319   raises the exception in order to have a polymorphic type!*)
   320 fun print_exn e = (print_sign_exn_unit (Thm.theory_of_thm (topthm())) e;  raise e);
   321 
   322 (*Which thms could apply to goal i? (debugs tactics involving filter_thms) *)
   323 fun filter_goal could ths i = filter_thms could (999, getgoal i, ths);
   324 
   325 (*For inspecting earlier levels of the backward proof*)
   326 fun chop_level n (pair,pairs) =
   327   let val level = length pairs
   328   in  if n<0 andalso ~n <= level
   329       then  List.drop (pair::pairs, ~n)
   330       else if 0<=n andalso n<= level
   331       then  List.drop (pair::pairs, level - n)
   332       else  error ("Level number must lie between 0 and " ^
   333                    string_of_int level)
   334   end;
   335 
   336 (*Print the given level of the proof; prlev ~1 prints previous level*)
   337 fun prlev n = apply_fun (print_top o pop o (chop_level n));
   338 fun pr () = apply_fun print_top;
   339 
   340 (*Set goals_limit and print again*)
   341 fun prlim n = (goals_limit:=n; pr());
   342 
   343 (** the goal.... commands
   344     Read main goal.  Set global variables curr_prems, curr_mkresult.
   345     Initial subgoal and premises are rewritten using rths. **)
   346 
   347 (*Version taking the goal as a cterm; if you have a term t and theory thy, use
   348     goalw_cterm rths (cterm_of thy t);      *)
   349 fun agoalw_cterm atomic rths chorn =
   350   let val (prems, st0, mkresult) = prepare_proof atomic rths chorn
   351   in  undo_list := [];
   352       setstate [ (st0, Seq.empty) ];
   353       curr_prems := prems;
   354       curr_mkresult := mkresult;
   355       prems
   356   end;
   357 
   358 val goalw_cterm = agoalw_cterm false;
   359 
   360 (*Version taking the goal as a string*)
   361 fun agoalw atomic thy rths agoal =
   362     agoalw_cterm atomic rths (cterm_of thy (read_prop thy agoal))
   363     handle ERROR msg => cat_error msg (*from type_assign, etc via prepare_proof*)
   364         ("The error(s) above occurred for " ^ quote agoal);
   365 
   366 val goalw = agoalw false;
   367 fun goal thy = goalw thy [];
   368 
   369 (*now the versions that wrap the goal up in `Goal' to make it atomic*)
   370 fun Goalw thms s = agoalw true (ML_Context.the_global_context ()) thms s;
   371 val Goal = Goalw [];
   372 
   373 (*simple version with minimal amount of checking and postprocessing*)
   374 fun simple_prove_goal_cterm G f =
   375   let
   376     val _ = legacy_feature "Old goal command";
   377     val As = Drule.strip_imp_prems G;
   378     val B = Drule.strip_imp_concl G;
   379     val asms = map Assumption.assume As;
   380     fun check NONE = error "prove_goal: tactic failed"
   381       | check (SOME (thm, _)) = (case nprems_of thm of
   382             0 => thm
   383           | i => !result_error_fn thm (string_of_int i ^ " unsolved goals!"))
   384   in
   385     standard (implies_intr_list As
   386       (check (Seq.pull (EVERY (f asms) (trivial B)))))
   387   end;
   388 
   389 
   390 (*Proof step "by" the given tactic -- apply tactic to the proof state*)
   391 fun by_com tac ((th,ths), pairs) : gstack =
   392   (case  Seq.pull(tac th)  of
   393      NONE      => error"by: tactic failed"
   394    | SOME(th2,ths2) =>
   395        (if Thm.eq_thm(th,th2)
   396           then warning "Warning: same as previous level"
   397           else if Thm.eq_thm_thy(th,th2) then ()
   398           else warning ("Warning: theory of proof state has changed" ^
   399                        thy_error (Thm.theory_of_thm th, Thm.theory_of_thm th2));
   400        ((th2,ths2)::(th,ths)::pairs)));
   401 
   402 fun by tac = cond_timeit (!Output.timing) ""
   403     (fn() => make_command (by_com tac));
   404 
   405 (* byev[tac1,...,tacn] applies tac1 THEN ... THEN tacn.
   406    Good for debugging proofs involving prove_goal.*)
   407 val byev = by o EVERY;
   408 
   409 
   410 (*Backtracking means find an alternative result from a tactic.
   411   If none at this level, try earlier levels*)
   412 fun backtrack [] = error"back: no alternatives"
   413   | backtrack ((th,thstr) :: pairs) =
   414      (case Seq.pull thstr of
   415           NONE      => (writeln"Going back a level..."; backtrack pairs)
   416         | SOME(th2,thstr2) =>
   417            (if Thm.eq_thm(th,th2)
   418               then warning "Warning: same as previous choice at this level"
   419               else if Thm.eq_thm_thy(th,th2) then ()
   420               else warning "Warning: theory of proof state has changed";
   421             (th2,thstr2)::pairs));
   422 
   423 fun back() = setstate (backtrack (getstate()));
   424 
   425 (*Chop back to previous level of the proof*)
   426 fun choplev n = make_command (chop_level n);
   427 
   428 (*Chopping back the goal stack*)
   429 fun chop () = make_command (fn (_,pairs) => pairs);
   430 
   431 (*Restore the previous proof state;  discard current state. *)
   432 fun undo() = case !undo_list of
   433       [] => error"No proof state"
   434     | [_] => error"Already at initial state"
   435     | _::newundo =>  (undo_list := newundo;  pr()) ;
   436 
   437 
   438 (*** Managing the proof stack ***)
   439 
   440 fun save_proof() = Proof(!undo_list, !curr_prems, !curr_mkresult);
   441 
   442 fun restore_proof(Proof(ul,prems,mk)) =
   443  (undo_list:= ul;  curr_prems:= prems;  curr_mkresult := mk;  prems);
   444 
   445 
   446 fun top_proof() = case !proofstack of
   447         [] => error("Stack of proof attempts is empty!")
   448     | p::ps => (p,ps);
   449 
   450 (*  push a copy of the current proof state on to the stack *)
   451 fun push_proof() = (proofstack := (save_proof() :: !proofstack));
   452 
   453 (* discard the top proof state of the stack *)
   454 fun pop_proof() =
   455   let val (p,ps) = top_proof()
   456       val prems = restore_proof p
   457   in proofstack := ps;  pr();  prems end;
   458 
   459 (* rotate the stack so that the top element goes to the bottom *)
   460 fun rotate_proof() = let val (p,ps) = top_proof()
   461                     in proofstack := ps@[save_proof()];
   462                        restore_proof p;
   463                        pr();
   464                        !curr_prems
   465                     end;
   466 
   467 
   468 (** theorem bindings **)
   469 
   470 fun qed name = ML_Context.ml_store_thm (name, result ());
   471 fun qed_goal name thy goal tacsf = ML_Context.ml_store_thm (name, prove_goal thy goal tacsf);
   472 fun qed_goalw name thy rews goal tacsf =
   473   ML_Context.ml_store_thm (name, prove_goalw thy rews goal tacsf);
   474 fun qed_spec_mp name =
   475   ML_Context.ml_store_thm (name, ObjectLogic.rulify_no_asm (result ()));
   476 fun qed_goal_spec_mp name thy s p =
   477   bind_thm (name, ObjectLogic.rulify_no_asm (prove_goal thy s p));
   478 fun qed_goalw_spec_mp name thy defs s p =
   479   bind_thm (name, ObjectLogic.rulify_no_asm (prove_goalw thy defs s p));
   480 
   481 end;
   482 
   483 structure Goals: GOALS = OldGoals;
   484 open Goals;