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