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