src/Pure/goals.ML
author berghofe
Wed Oct 31 19:37:04 2001 +0100 (2001-10-31)
changeset 11998 b14e7686ce84
parent 11963 a6608d44a46b
child 12012 1d534baa2827
permissions -rw-r--r--
- enter_thmx -> enter_thms
- improved naming of theorems: enter_thms now takes functions pre_name and post_name
as arguments
clasohm@1460
     1
(*  Title: 	Pure/goals.ML
clasohm@0
     2
    ID:         $Id$
clasohm@1460
     3
    Author: 	Lawrence C Paulson, Cambridge University Computer Laboratory
clasohm@0
     4
    Copyright   1993  University of Cambridge
clasohm@0
     5
clasohm@0
     6
Goal stack package.  The goal stack initially holds a dummy proof, and can
clasohm@0
     7
never become empty.  Each goal stack consists of a list of levels.  The
clasohm@0
     8
undo list is a list of goal stacks.  Finally, there may be a stack of
clasohm@0
     9
pending proofs.
clasohm@0
    10
*)
clasohm@0
    11
clasohm@0
    12
signature GOALS =
wenzelm@11884
    13
sig
clasohm@0
    14
  type proof
wenzelm@7234
    15
  val reset_goals       : unit -> unit
nipkow@5041
    16
  val atomic_goal	: theory -> string -> thm list
nipkow@5041
    17
  val atomic_goalw	: theory -> thm list -> string -> thm list
wenzelm@6189
    18
  val Goal		: string -> thm list
wenzelm@6189
    19
  val Goalw		: thm list -> string -> thm list
clasohm@1460
    20
  val ba		: int -> unit
clasohm@1460
    21
  val back		: unit -> unit
clasohm@1460
    22
  val bd		: thm -> int -> unit
clasohm@1460
    23
  val bds		: thm list -> int -> unit
clasohm@1460
    24
  val be		: thm -> int -> unit
clasohm@1460
    25
  val bes		: thm list -> int -> unit
clasohm@1460
    26
  val br		: thm -> int -> unit
clasohm@1460
    27
  val brs		: thm list -> int -> unit
clasohm@1460
    28
  val bw		: thm -> unit
clasohm@1460
    29
  val bws		: thm list -> unit
clasohm@1460
    30
  val by		: tactic -> unit
clasohm@1460
    31
  val byev		: tactic list -> unit
clasohm@1460
    32
  val chop		: unit -> unit
clasohm@1460
    33
  val choplev		: int -> unit
paulson@6017
    34
  val export_thy        : theory -> thm -> thm
wenzelm@5246
    35
  val export            : thm -> thm
wenzelm@6189
    36
  val Export		: thm -> thm
clasohm@1460
    37
  val fa		: unit -> unit
clasohm@1460
    38
  val fd		: thm -> unit
clasohm@1460
    39
  val fds		: thm list -> unit
clasohm@1460
    40
  val fe		: thm -> unit
clasohm@1460
    41
  val fes		: thm list -> unit
clasohm@1460
    42
  val filter_goal	: (term*term->bool) -> thm list -> int -> thm list
clasohm@1460
    43
  val fr		: thm -> unit
clasohm@1460
    44
  val frs		: thm list -> unit
clasohm@1460
    45
  val getgoal		: int -> term
clasohm@1460
    46
  val gethyps		: int -> thm list
clasohm@1460
    47
  val goal		: theory -> string -> thm list
clasohm@1460
    48
  val goalw		: theory -> thm list -> string -> thm list
clasohm@1460
    49
  val goalw_cterm	: thm list -> cterm -> thm list
clasohm@1460
    50
  val pop_proof		: unit -> thm list
clasohm@1460
    51
  val pr		: unit -> unit
wenzelm@8884
    52
  val disable_pr        : unit -> unit
wenzelm@8884
    53
  val enable_pr         : unit -> unit
paulson@2580
    54
  val prlev		: int -> unit
paulson@2514
    55
  val prlim		: int -> unit
clasohm@1460
    56
  val premises		: unit -> thm list
clasohm@1460
    57
  val prin		: term -> unit
clasohm@1460
    58
  val printyp		: typ -> unit
clasohm@1460
    59
  val pprint_term	: term -> pprint_args -> unit
clasohm@1460
    60
  val pprint_typ	: typ -> pprint_args -> unit
clasohm@1460
    61
  val print_exn		: exn -> 'a
clasohm@1460
    62
  val print_sign_exn	: Sign.sg -> exn -> 'a
clasohm@1460
    63
  val prove_goal	: theory -> string -> (thm list -> tactic list) -> thm
lcp@577
    64
  val prove_goalw      : theory->thm list->string->(thm list->tactic list)->thm
clasohm@1460
    65
  val prove_goalw_cterm	: thm list->cterm->(thm list->tactic list)->thm
paulson@5311
    66
  val prove_goalw_cterm_nocheck	: thm list->cterm->(thm list->tactic list)->thm
wenzelm@11884
    67
  val quick_and_dirty_prove_goalw_cterm: theory -> thm list -> cterm
wenzelm@11884
    68
    -> (thm list -> tactic list) -> thm
clasohm@1460
    69
  val push_proof	: unit -> unit
clasohm@1460
    70
  val read		: string -> term
clasohm@1460
    71
  val ren		: string -> int -> unit
clasohm@1460
    72
  val restore_proof	: proof -> thm list
clasohm@1460
    73
  val result		: unit -> thm  
wenzelm@3532
    74
  val result_error_fn   : (thm -> string -> thm) ref
clasohm@1460
    75
  val rotate_proof	: unit -> thm list
clasohm@1460
    76
  val uresult		: unit -> thm  
clasohm@1460
    77
  val save_proof	: unit -> proof
clasohm@1460
    78
  val topthm		: unit -> thm
clasohm@1460
    79
  val undo		: unit -> unit
wenzelm@11884
    80
  val bind_thm          : string * thm -> unit
wenzelm@11884
    81
  val bind_thms         : string * thm list -> unit
wenzelm@11884
    82
  val qed               : string -> unit
wenzelm@11884
    83
  val qed_goal          : string -> theory -> string -> (thm list -> tactic list) -> unit
wenzelm@11884
    84
  val qed_goalw         : string -> theory -> thm list -> string
wenzelm@11884
    85
    -> (thm list -> tactic list) -> unit
wenzelm@11884
    86
  val qed_spec_mp       : string -> unit
wenzelm@11884
    87
  val qed_goal_spec_mp  : string -> theory -> string -> (thm list -> tactic list) -> unit
wenzelm@11884
    88
  val qed_goalw_spec_mp : string -> theory -> thm list -> string
wenzelm@11884
    89
    -> (thm list -> tactic list) -> unit
wenzelm@11884
    90
  val no_qed: unit -> unit
wenzelm@11884
    91
  val thms_containing   : xstring list -> (string * thm) list
wenzelm@11884
    92
  val findI             : int -> (string * thm) list
wenzelm@11884
    93
  val findEs            : int -> (string * thm) list
wenzelm@11884
    94
  val findE             : int -> int -> (string * thm) list
wenzelm@11884
    95
end;
clasohm@0
    96
paulson@1500
    97
structure Goals : GOALS =
clasohm@0
    98
struct
clasohm@0
    99
clasohm@0
   100
(*Each level of goal stack includes a proof state and alternative states,
clasohm@0
   101
  the output of the tactic applied to the preceeding level.  *)
wenzelm@4270
   102
type gstack = (thm * thm Seq.seq) list;
clasohm@0
   103
clasohm@0
   104
datatype proof = Proof of gstack list * thm list * (bool*thm->thm);
clasohm@0
   105
wenzelm@5246
   106
clasohm@0
   107
(*** References ***)
clasohm@0
   108
clasohm@0
   109
(*Current assumption list -- set by "goal".*)
clasohm@0
   110
val curr_prems = ref([] : thm list);
clasohm@0
   111
clasohm@0
   112
(*Return assumption list -- useful if you didn't save "goal"'s result. *)
clasohm@0
   113
fun premises() = !curr_prems;
clasohm@0
   114
clasohm@0
   115
(*Current result maker -- set by "goal", used by "result".  *)
wenzelm@7234
   116
fun init_mkresult _ = error "No goal has been supplied in subgoal module";
wenzelm@7234
   117
val curr_mkresult = ref (init_mkresult: bool*thm->thm);
clasohm@0
   118
wenzelm@6390
   119
val dummy = trivial(read_cterm (Theory.sign_of ProtoPure.thy)
clasohm@0
   120
    ("PROP No_goal_has_been_supplied",propT));
clasohm@0
   121
clasohm@0
   122
(*List of previous goal stacks, for the undo operation.  Set by setstate. 
clasohm@0
   123
  A list of lists!*)
wenzelm@4270
   124
val undo_list = ref([[(dummy, Seq.empty)]] : gstack list);
clasohm@0
   125
clasohm@0
   126
(* Stack of proof attempts *)
clasohm@0
   127
val proofstack = ref([]: proof list);
clasohm@0
   128
wenzelm@7234
   129
(*reset all refs*)
wenzelm@7234
   130
fun reset_goals () =
wenzelm@7234
   131
  (curr_prems := []; curr_mkresult := init_mkresult;
oheimb@7942
   132
    undo_list := [[(dummy, Seq.empty)]]);
wenzelm@7234
   133
clasohm@0
   134
clasohm@0
   135
(*** Setting up goal-directed proof ***)
clasohm@0
   136
clasohm@0
   137
(*Generates the list of new theories when the proof state's signature changes*)
clasohm@0
   138
fun sign_error (sign,sign') =
wenzelm@3974
   139
  let val names = Sign.stamp_names_of sign' \\ Sign.stamp_names_of sign
wenzelm@3974
   140
  in  case names of
wenzelm@3974
   141
        [name] => "\nNew theory: " ^ name
wenzelm@3974
   142
      | _       => "\nNew theories: " ^ space_implode ", " names
clasohm@0
   143
  end;
clasohm@0
   144
paulson@1928
   145
(*Default action is to print an error message; could be suppressed for
paulson@1928
   146
  special applications.*)
wenzelm@3669
   147
fun result_error_default state msg : thm =
wenzelm@11884
   148
  Pretty.str "Bad final proof state:" :: Display.pretty_goals (!goals_limit) state @
wenzelm@11562
   149
    [Pretty.str msg, Pretty.str "Proof failed!"] |> Pretty.chunks |> Pretty.string_of |> error;
paulson@1928
   150
wenzelm@3532
   151
val result_error_fn = ref result_error_default;
paulson@1928
   152
wenzelm@5246
   153
(* alternative to standard: this function does not discharge the hypotheses
wenzelm@5246
   154
   first. Is used for locales, in the following function prepare_proof *)
wenzelm@5246
   155
fun varify th =
wenzelm@5246
   156
  let val {maxidx,...} = rep_thm th
wenzelm@5246
   157
  in
wenzelm@5246
   158
    th |> forall_intr_frees |> forall_elim_vars (maxidx + 1)
wenzelm@7637
   159
       |> Drule.strip_shyps_warning
wenzelm@5246
   160
       |> zero_var_indexes |> Thm.varifyT |> Thm.compress
wenzelm@5246
   161
  end;
wenzelm@5246
   162
wenzelm@5246
   163
(** exporting a theorem out of a locale means turning all meta-hyps into assumptions
paulson@6017
   164
    and expand and cancel the locale definitions. 
paulson@6017
   165
    export goes through all levels in case of nested locales, whereas
wenzelm@6189
   166
    export_thy just goes one up. **)
paulson@6017
   167
paulson@6017
   168
fun get_top_scope_thms thy = 
wenzelm@6390
   169
   let val sc = (Locale.get_scope_sg (Theory.sign_of thy))
paulson@6017
   170
   in if (null sc) then (warning "No locale in theory"; [])
paulson@6017
   171
      else map (#prop o rep_thm) (map #2 (#thms(snd(hd sc))))
paulson@6017
   172
   end;
paulson@6017
   173
paulson@6017
   174
fun implies_intr_some_hyps thy A_set th = 
paulson@6017
   175
   let 
wenzelm@6390
   176
       val sign = Theory.sign_of thy;
paulson@6017
   177
       val used_As = A_set inter #hyps(rep_thm(th));
paulson@6017
   178
       val ctl = map (cterm_of sign) used_As
paulson@6017
   179
   in foldl (fn (x, y) => Thm.implies_intr y x) (th, ctl)
paulson@6017
   180
   end; 
paulson@6017
   181
paulson@6017
   182
fun standard_some thy A_set th =
paulson@6017
   183
  let val {maxidx,...} = rep_thm th
paulson@6017
   184
  in
paulson@6017
   185
    th |> implies_intr_some_hyps thy A_set
paulson@6017
   186
       |> forall_intr_frees |> forall_elim_vars (maxidx + 1)
wenzelm@7637
   187
       |> Drule.strip_shyps_warning
paulson@6017
   188
       |> zero_var_indexes |> Thm.varifyT |> Thm.compress
paulson@6017
   189
  end;
paulson@6017
   190
paulson@6017
   191
fun export_thy thy th = 
paulson@6017
   192
  let val A_set = get_top_scope_thms thy
paulson@6017
   193
  in
paulson@6017
   194
     standard_some thy [] (Seq.hd ((REPEAT (FIRSTGOAL (rtac reflexive_thm))) (standard_some thy A_set th)))
paulson@6017
   195
  end;
paulson@6017
   196
wenzelm@5246
   197
val export = standard o Seq.hd o (REPEAT (FIRSTGOAL (rtac reflexive_thm))) o standard;
wenzelm@5246
   198
wenzelm@6189
   199
fun Export th = export_thy (the_context ()) th;
wenzelm@6189
   200
wenzelm@6189
   201
clasohm@0
   202
(*Common treatment of "goal" and "prove_goal":
nipkow@5041
   203
  Return assumptions, initial proof state, and function to make result.
nipkow@5041
   204
  "atomic" indicates if the goal should be wrapped up in the function
nipkow@5041
   205
  "Goal::prop=>prop" to avoid assumptions being returned separately.
nipkow@5041
   206
*)
nipkow@5041
   207
fun prepare_proof atomic rths chorn =
lcp@230
   208
  let val {sign, t=horn,...} = rep_cterm chorn;
wenzelm@9533
   209
      val _ = Term.no_dummy_patterns horn handle TERM (msg, _) => error msg;
clasohm@0
   210
      val (_,As,B) = Logic.strip_horn(horn);
nipkow@5041
   211
      val atoms = atomic andalso
nipkow@5041
   212
            forall (fn t => not(Logic.is_implies t orelse Logic.is_all t)) As;
nipkow@5041
   213
      val (As,B) = if atoms then ([],horn) else (As,B);
lcp@230
   214
      val cAs = map (cterm_of sign) As;
wenzelm@11963
   215
      val prems = map (rewrite_rule rths o forall_elim_vars 0 o Thm.assume) cAs;
nipkow@5041
   216
      val cB = cterm_of sign B;
wenzelm@11963
   217
      val st0 = let val st = Drule.impose_hyps cAs (Drule.mk_triv_goal cB)
nipkow@5041
   218
                in  rewrite_goals_rule rths st end
clasohm@0
   219
      (*discharges assumptions from state in the order they appear in goal;
clasohm@1460
   220
	checks (if requested) that resulting theorem is equivalent to goal. *)
clasohm@0
   221
      fun mkresult (check,state) =
wenzelm@4270
   222
        let val state = Seq.hd (flexflex_rule state)
paulson@1565
   223
	    		handle THM _ => state   (*smash flexflex pairs*)
clasohm@1460
   224
	    val ngoals = nprems_of state
wenzelm@7637
   225
            val ath = implies_intr_list cAs state
nipkow@5041
   226
            val th = ath RS Drule.rev_triv_goal
wenzelm@1240
   227
            val {hyps,prop,sign=sign',...} = rep_thm th
paulson@9573
   228
            val final_th = if (null(hyps)) then standard th else varify th
paulson@9573
   229
        in  if not check then final_th
wenzelm@3532
   230
	    else if not (Sign.eq_sg(sign,sign')) then !result_error_fn state
clasohm@1460
   231
		("Signature of proof state has changed!" ^
clasohm@1460
   232
		 sign_error (sign,sign'))
wenzelm@3532
   233
            else if ngoals>0 then !result_error_fn state
clasohm@1460
   234
		(string_of_int ngoals ^ " unsolved goals!")
wenzelm@5246
   235
            else if (not (null hyps) andalso (not (Locale.in_locale hyps sign)))
wenzelm@5246
   236
		 then !result_error_fn state
paulson@5748
   237
                  ("Additional hypotheses:\n" ^ 
paulson@5748
   238
		   cat_lines 
paulson@5748
   239
		    (map (Sign.string_of_term sign) 
paulson@5748
   240
		     (filter (fn x => (not (Locale.in_locale [x] sign))) 
paulson@5748
   241
		      hyps)))
clasohm@1460
   242
	    else if Pattern.matches (#tsig(Sign.rep_sg sign)) 
wenzelm@10487
   243
			            (Envir.beta_norm (term_of chorn), Envir.beta_norm prop)
paulson@9573
   244
		 then final_th
wenzelm@3532
   245
	    else  !result_error_fn state "proved a different theorem"
clasohm@0
   246
        end
nipkow@678
   247
  in
nipkow@678
   248
     if Sign.eq_sg(sign, #sign(rep_thm st0))
clasohm@0
   249
     then (prems, st0, mkresult)
clasohm@0
   250
     else error ("Definitions would change the proof state's signature" ^
clasohm@1460
   251
		 sign_error (sign, #sign(rep_thm st0)))
clasohm@0
   252
  end
clasohm@0
   253
  handle THM(s,_,_) => error("prepare_proof: exception THM was raised!\n" ^ s);
clasohm@0
   254
clasohm@0
   255
(*Prints exceptions readably to users*)
lcp@577
   256
fun print_sign_exn_unit sign e = 
clasohm@0
   257
  case e of
clasohm@0
   258
     THM (msg,i,thms) =>
clasohm@1460
   259
	 (writeln ("Exception THM " ^ string_of_int i ^ " raised:\n" ^ msg);
clasohm@1460
   260
	  seq print_thm thms)
clasohm@0
   261
   | THEORY (msg,thys) =>
clasohm@1460
   262
	 (writeln ("Exception THEORY raised:\n" ^ msg);
wenzelm@4994
   263
	  seq (Pretty.writeln o Display.pretty_theory) thys)
clasohm@0
   264
   | TERM (msg,ts) =>
clasohm@1460
   265
	 (writeln ("Exception TERM raised:\n" ^ msg);
clasohm@1460
   266
	  seq (writeln o Sign.string_of_term sign) ts)
clasohm@0
   267
   | TYPE (msg,Ts,ts) =>
clasohm@1460
   268
	 (writeln ("Exception TYPE raised:\n" ^ msg);
clasohm@1460
   269
	  seq (writeln o Sign.string_of_typ sign) Ts;
clasohm@1460
   270
	  seq (writeln o Sign.string_of_term sign) ts)
clasohm@0
   271
   | e => raise e;
clasohm@0
   272
lcp@577
   273
(*Prints an exception, then fails*)
lcp@577
   274
fun print_sign_exn sign e = (print_sign_exn_unit sign e; raise ERROR);
lcp@577
   275
clasohm@0
   276
(** the prove_goal.... commands
clasohm@0
   277
    Prove theorem using the listed tactics; check it has the specified form.
clasohm@0
   278
    Augment signature with all type assignments of goal.
clasohm@0
   279
    Syntax is similar to "goal" command for easy keyboard use. **)
clasohm@0
   280
clasohm@0
   281
(*Version taking the goal as a cterm*)
paulson@5311
   282
fun prove_goalw_cterm_general check rths chorn tacsf =
nipkow@5041
   283
  let val (prems, st0, mkresult) = prepare_proof false rths chorn
clasohm@0
   284
      val tac = EVERY (tacsf prems)
clasohm@0
   285
      fun statef() = 
wenzelm@4270
   286
	  (case Seq.pull (tac st0) of 
clasohm@1460
   287
	       Some(st,_) => st
clasohm@1460
   288
	     | _ => error ("prove_goal: tactic failed"))
wenzelm@8999
   289
  in  mkresult (check, cond_timeit (!Library.timing) statef)  end
lcp@914
   290
  handle e => (print_sign_exn_unit (#sign (rep_cterm chorn)) e;
wenzelm@6960
   291
	       writeln ("The exception above was raised for\n" ^ 
wenzelm@11884
   292
		      Display.string_of_cterm chorn); raise e);
lcp@545
   293
paulson@5614
   294
(*Two variants: one checking the result, one not.  
paulson@5614
   295
  Neither prints runtime messages: they are for internal packages.*)
paulson@5614
   296
fun prove_goalw_cterm rths chorn = 
wenzelm@8999
   297
	setmp Library.timing false (prove_goalw_cterm_general true rths chorn)
paulson@5614
   298
and prove_goalw_cterm_nocheck rths chorn = 
wenzelm@8999
   299
	setmp Library.timing false (prove_goalw_cterm_general false rths chorn);
paulson@5311
   300
clasohm@0
   301
clasohm@0
   302
(*Version taking the goal as a string*)
clasohm@0
   303
fun prove_goalw thy rths agoal tacsf =
wenzelm@6390
   304
  let val sign = Theory.sign_of thy
lcp@230
   305
      val chorn = read_cterm sign (agoal,propT)
paulson@5614
   306
  in  prove_goalw_cterm_general true rths chorn tacsf end
lcp@545
   307
  handle ERROR => error (*from read_cterm?*)
wenzelm@3536
   308
		("The error(s) above occurred for " ^ quote agoal);
clasohm@0
   309
clasohm@0
   310
(*String version with no meta-rewrite-rules*)
clasohm@0
   311
fun prove_goal thy = prove_goalw thy [];
clasohm@0
   312
wenzelm@11884
   313
(*quick and dirty version (conditional)*)
wenzelm@11884
   314
fun quick_and_dirty_prove_goalw_cterm thy rews ct tacs =
wenzelm@11884
   315
  prove_goalw_cterm rews ct
wenzelm@11884
   316
    (if ! quick_and_dirty then (K [SkipProof.cheat_tac thy]) else tacs);
wenzelm@11884
   317
clasohm@0
   318
clasohm@0
   319
(*** Commands etc ***)
clasohm@0
   320
clasohm@0
   321
(*Return the current goal stack, if any, from undo_list*)
clasohm@0
   322
fun getstate() : gstack = case !undo_list of 
clasohm@0
   323
      []   => error"No current state in subgoal module"
clasohm@0
   324
    | x::_ => x;
clasohm@0
   325
clasohm@0
   326
(*Pops the given goal stack*)
clasohm@0
   327
fun pop [] = error"Cannot go back past the beginning of the proof!"
clasohm@0
   328
  | pop (pair::pairs) = (pair,pairs);
clasohm@0
   329
clasohm@0
   330
wenzelm@8884
   331
(* Print a level of the goal stack -- subject to quiet mode *)
wenzelm@8884
   332
wenzelm@8884
   333
val quiet = ref false;
wenzelm@8884
   334
fun disable_pr () = quiet := true;
wenzelm@8884
   335
fun enable_pr () = quiet := false;
wenzelm@8884
   336
wenzelm@3532
   337
fun print_top ((th, _), pairs) =
wenzelm@8884
   338
  if ! quiet then ()
wenzelm@11884
   339
  else ! Display.print_current_goals_fn (length pairs) (! goals_limit) th;
clasohm@0
   340
clasohm@0
   341
(*Printing can raise exceptions, so the assignment occurs last.
wenzelm@4270
   342
  Can do   setstate[(st,Seq.empty)]  to set st as the state.  *)
clasohm@0
   343
fun setstate newgoals = 
clasohm@0
   344
  (print_top (pop newgoals);  undo_list := newgoals :: !undo_list);
clasohm@0
   345
clasohm@0
   346
(*Given a proof state transformation, return a command that updates
clasohm@0
   347
    the goal stack*)
clasohm@0
   348
fun make_command com = setstate (com (pop (getstate())));
clasohm@0
   349
clasohm@0
   350
(*Apply a function on proof states to the current goal stack*)
clasohm@0
   351
fun apply_fun f = f (pop(getstate()));
clasohm@0
   352
clasohm@0
   353
(*Return the top theorem, representing the proof state*)
clasohm@0
   354
fun topthm () = apply_fun  (fn ((th,_), _) => th);
clasohm@0
   355
clasohm@0
   356
(*Return the final result.  *)
clasohm@0
   357
fun result () = !curr_mkresult (true, topthm());
clasohm@0
   358
clasohm@0
   359
(*Return the result UNCHECKED that it equals the goal -- for synthesis,
clasohm@0
   360
  answer extraction, or other instantiation of Vars *)
clasohm@0
   361
fun uresult () = !curr_mkresult (false, topthm());
clasohm@0
   362
clasohm@0
   363
(*Get subgoal i from goal stack*)
paulson@2580
   364
fun getgoal i = List.nth (prems_of (topthm()), i-1)
paulson@2580
   365
                handle Subscript => error"getgoal: Goal number out of range";
clasohm@0
   366
clasohm@0
   367
(*Return subgoal i's hypotheses as meta-level assumptions.
clasohm@0
   368
  For debugging uses of METAHYPS*)
clasohm@0
   369
local exception GETHYPS of thm list
clasohm@0
   370
in
clasohm@0
   371
fun gethyps i = 
paulson@1500
   372
    (METAHYPS (fn hyps => raise (GETHYPS hyps)) i (topthm());  [])
clasohm@0
   373
    handle GETHYPS hyps => hyps
clasohm@0
   374
end;
clasohm@0
   375
clasohm@0
   376
(*Which thms could apply to goal i? (debugs tactics involving filter_thms) *)
clasohm@0
   377
fun filter_goal could ths i = filter_thms could (999, getgoal i, ths);
clasohm@0
   378
clasohm@0
   379
(*For inspecting earlier levels of the backward proof*)
clasohm@0
   380
fun chop_level n (pair,pairs) = 
clasohm@0
   381
  let val level = length pairs
paulson@2126
   382
  in  if n<0 andalso ~n <= level
paulson@2580
   383
      then  List.drop (pair::pairs, ~n) 
paulson@2126
   384
      else if 0<=n andalso n<= level
paulson@2580
   385
      then  List.drop (pair::pairs, level - n) 
clasohm@0
   386
      else  error ("Level number must lie between 0 and " ^ 
clasohm@1460
   387
		   string_of_int level)
clasohm@0
   388
  end;
clasohm@0
   389
paulson@2514
   390
(*Print the given level of the proof; prlev ~1 prints previous level*)
wenzelm@8884
   391
fun prlev n = (enable_pr (); apply_fun (print_top o pop o (chop_level n)));
wenzelm@8884
   392
fun pr () = (enable_pr (); apply_fun print_top);
clasohm@0
   393
paulson@2514
   394
(*Set goals_limit and print again*)
paulson@2514
   395
fun prlim n = (goals_limit:=n; pr());
paulson@2514
   396
clasohm@0
   397
(** the goal.... commands
clasohm@0
   398
    Read main goal.  Set global variables curr_prems, curr_mkresult. 
clasohm@0
   399
    Initial subgoal and premises are rewritten using rths. **)
clasohm@0
   400
clasohm@0
   401
(*Version taking the goal as a cterm; if you have a term t and theory thy, use
wenzelm@6390
   402
    goalw_cterm rths (cterm_of (Theory.sign_of thy) t);      *)
nipkow@5041
   403
fun agoalw_cterm atomic rths chorn = 
nipkow@5041
   404
  let val (prems, st0, mkresult) = prepare_proof atomic rths chorn
clasohm@0
   405
  in  undo_list := [];
wenzelm@4270
   406
      setstate [ (st0, Seq.empty) ];  
clasohm@0
   407
      curr_prems := prems;
clasohm@0
   408
      curr_mkresult := mkresult;
clasohm@0
   409
      prems
clasohm@0
   410
  end;
clasohm@0
   411
nipkow@5041
   412
val goalw_cterm = agoalw_cterm false;
nipkow@5041
   413
clasohm@0
   414
(*Version taking the goal as a string*)
nipkow@5041
   415
fun agoalw atomic thy rths agoal = 
wenzelm@6390
   416
    agoalw_cterm atomic rths (Locale.read_cterm(Theory.sign_of thy)(agoal,propT))
wenzelm@5246
   417
    handle ERROR => error (*from type_assign, etc via prepare_proof*)
wenzelm@5246
   418
	("The error(s) above occurred for " ^ quote agoal);
clasohm@0
   419
nipkow@5041
   420
val goalw = agoalw false;
nipkow@5041
   421
clasohm@0
   422
(*String version with no meta-rewrite-rules*)
nipkow@5041
   423
fun agoal atomic thy = agoalw atomic thy [];
nipkow@5041
   424
val goal = agoal false;
nipkow@5041
   425
nipkow@5041
   426
(*now the versions that wrap the goal up in `Goal' to make it atomic*)
nipkow@5041
   427
val atomic_goalw = agoalw true;
nipkow@5041
   428
val atomic_goal = agoal true;
nipkow@5041
   429
wenzelm@6189
   430
(*implicit context versions*)
wenzelm@6189
   431
fun Goal s = atomic_goal (Context.the_context ()) s;
wenzelm@6189
   432
fun Goalw thms s = atomic_goalw (Context.the_context ()) thms s;
wenzelm@6189
   433
clasohm@0
   434
clasohm@0
   435
(*Proof step "by" the given tactic -- apply tactic to the proof state*)
clasohm@0
   436
fun by_com tac ((th,ths), pairs) : gstack =
wenzelm@4270
   437
  (case  Seq.pull(tac th)  of
clasohm@0
   438
     None      => error"by: tactic failed"
clasohm@0
   439
   | Some(th2,ths2) => 
clasohm@0
   440
       (if eq_thm(th,th2) 
paulson@3707
   441
	  then warning "Warning: same as previous level"
clasohm@1460
   442
	  else if eq_thm_sg(th,th2) then ()
wenzelm@4280
   443
	  else warning ("Warning: signature of proof state has changed" ^
clasohm@1460
   444
		       sign_error (#sign(rep_thm th), #sign(rep_thm th2)));
clasohm@0
   445
       ((th2,ths2)::(th,ths)::pairs)));
clasohm@0
   446
wenzelm@8999
   447
fun by tac = cond_timeit (!Library.timing) 
clasohm@0
   448
    (fn() => make_command (by_com tac));
clasohm@0
   449
clasohm@0
   450
(* byev[tac1,...,tacn] applies tac1 THEN ... THEN tacn.
clasohm@0
   451
   Good for debugging proofs involving prove_goal.*)
clasohm@0
   452
val byev = by o EVERY;
clasohm@0
   453
clasohm@0
   454
clasohm@0
   455
(*Backtracking means find an alternative result from a tactic.
clasohm@0
   456
  If none at this level, try earlier levels*)
clasohm@0
   457
fun backtrack [] = error"back: no alternatives"
clasohm@0
   458
  | backtrack ((th,thstr) :: pairs) =
wenzelm@4270
   459
     (case Seq.pull thstr of
clasohm@1460
   460
	  None      => (writeln"Going back a level..."; backtrack pairs)
clasohm@1460
   461
	| Some(th2,thstr2) =>  
clasohm@1460
   462
	   (if eq_thm(th,th2) 
paulson@3707
   463
	      then warning "Warning: same as previous choice at this level"
clasohm@1460
   464
	      else if eq_thm_sg(th,th2) then ()
paulson@3707
   465
	      else warning "Warning: signature of proof state has changed";
clasohm@1460
   466
	    (th2,thstr2)::pairs));
clasohm@0
   467
clasohm@0
   468
fun back() = setstate (backtrack (getstate()));
clasohm@0
   469
clasohm@0
   470
(*Chop back to previous level of the proof*)
clasohm@0
   471
fun choplev n = make_command (chop_level n);
clasohm@0
   472
clasohm@0
   473
(*Chopping back the goal stack*)
clasohm@0
   474
fun chop () = make_command (fn (_,pairs) => pairs);
clasohm@0
   475
clasohm@0
   476
(*Restore the previous proof state;  discard current state. *)
clasohm@0
   477
fun undo() = case !undo_list of
clasohm@0
   478
      [] => error"No proof state"
clasohm@0
   479
    | [_] => error"Already at initial state"
clasohm@0
   480
    | _::newundo =>  (undo_list := newundo;  pr()) ;
clasohm@0
   481
clasohm@0
   482
clasohm@0
   483
(*** Managing the proof stack ***)
clasohm@0
   484
clasohm@0
   485
fun save_proof() = Proof(!undo_list, !curr_prems, !curr_mkresult);
clasohm@0
   486
clasohm@0
   487
fun restore_proof(Proof(ul,prems,mk)) =
clasohm@0
   488
 (undo_list:= ul;  curr_prems:= prems;  curr_mkresult := mk;  prems);
clasohm@0
   489
clasohm@0
   490
clasohm@0
   491
fun top_proof() = case !proofstack of
clasohm@1460
   492
	[] => error("Stack of proof attempts is empty!")
clasohm@0
   493
    | p::ps => (p,ps);
clasohm@0
   494
clasohm@0
   495
(*  push a copy of the current proof state on to the stack *)
clasohm@0
   496
fun push_proof() = (proofstack := (save_proof() :: !proofstack));
clasohm@0
   497
clasohm@0
   498
(* discard the top proof state of the stack *)
clasohm@0
   499
fun pop_proof() = 
clasohm@0
   500
  let val (p,ps) = top_proof()
clasohm@0
   501
      val prems = restore_proof p
clasohm@0
   502
  in proofstack := ps;  pr();  prems end;
clasohm@0
   503
clasohm@0
   504
(* rotate the stack so that the top element goes to the bottom *)
clasohm@0
   505
fun rotate_proof() = let val (p,ps) = top_proof()
clasohm@1460
   506
		    in proofstack := ps@[save_proof()];
clasohm@1460
   507
		       restore_proof p;
clasohm@1460
   508
		       pr();
clasohm@1460
   509
		       !curr_prems
clasohm@1460
   510
		    end;
clasohm@0
   511
clasohm@0
   512
clasohm@0
   513
(** Shortcuts for commonly-used tactics **)
clasohm@0
   514
clasohm@0
   515
fun bws rls = by (rewrite_goals_tac rls);
clasohm@0
   516
fun bw rl = bws [rl];
clasohm@0
   517
clasohm@0
   518
fun brs rls i = by (resolve_tac rls i);
clasohm@0
   519
fun br rl = brs [rl];
clasohm@0
   520
clasohm@0
   521
fun bes rls i = by (eresolve_tac rls i);
clasohm@0
   522
fun be rl = bes [rl];
clasohm@0
   523
clasohm@0
   524
fun bds rls i = by (dresolve_tac rls i);
clasohm@0
   525
fun bd rl = bds [rl];
clasohm@0
   526
clasohm@0
   527
fun ba i = by (assume_tac i);
clasohm@0
   528
clasohm@0
   529
fun ren str i = by (rename_tac str i);
clasohm@0
   530
clasohm@0
   531
(** Shortcuts to work on the first applicable subgoal **)
clasohm@0
   532
clasohm@0
   533
fun frs rls = by (FIRSTGOAL (trace_goalno_tac (resolve_tac rls)));
clasohm@0
   534
fun fr rl = frs [rl];
clasohm@0
   535
clasohm@0
   536
fun fes rls = by (FIRSTGOAL (trace_goalno_tac (eresolve_tac rls)));
clasohm@0
   537
fun fe rl = fes [rl];
clasohm@0
   538
clasohm@0
   539
fun fds rls = by (FIRSTGOAL (trace_goalno_tac (dresolve_tac rls)));
clasohm@0
   540
fun fd rl = fds [rl];
clasohm@0
   541
clasohm@0
   542
fun fa() = by (FIRSTGOAL (trace_goalno_tac assume_tac));
clasohm@0
   543
clasohm@0
   544
(** Reading and printing terms wrt the current theory **)
clasohm@0
   545
clasohm@0
   546
fun top_sg() = #sign(rep_thm(topthm()));
clasohm@0
   547
wenzelm@8086
   548
fun read s = term_of (read_cterm (top_sg()) (s, TypeInfer.logicT));
clasohm@0
   549
clasohm@0
   550
(*Print a term under the current signature of the proof state*)
clasohm@0
   551
fun prin t = writeln (Sign.string_of_term (top_sg()) t);
clasohm@0
   552
clasohm@0
   553
fun printyp T = writeln (Sign.string_of_typ (top_sg()) T);
clasohm@0
   554
clasohm@0
   555
fun pprint_term t = Sign.pprint_term (top_sg()) t;
clasohm@0
   556
clasohm@0
   557
fun pprint_typ T = Sign.pprint_typ (top_sg()) T;
clasohm@0
   558
berghofe@1628
   559
clasohm@0
   560
(*Prints exceptions nicely at top level; 
clasohm@0
   561
  raises the exception in order to have a polymorphic type!*)
lcp@914
   562
fun print_exn e = (print_sign_exn_unit (top_sg()) e;  raise e);
clasohm@0
   563
wenzelm@11884
   564
wenzelm@11884
   565
wenzelm@11884
   566
(** theorem database operations **)
wenzelm@11884
   567
wenzelm@11884
   568
(* storing *)
wenzelm@11884
   569
wenzelm@11884
   570
fun bind_thm (name, thm) = ThmDatabase.ml_store_thm (name, standard thm);
wenzelm@11884
   571
fun bind_thms (name, thms) = ThmDatabase.ml_store_thms (name, map standard thms);
wenzelm@11884
   572
wenzelm@11884
   573
fun qed name = ThmDatabase.ml_store_thm (name, result ());
wenzelm@11884
   574
fun qed_goal name thy goal tacsf = ThmDatabase.ml_store_thm (name, prove_goal thy goal tacsf);
wenzelm@11884
   575
fun qed_goalw name thy rews goal tacsf =
wenzelm@11884
   576
  ThmDatabase.ml_store_thm (name, prove_goalw thy rews goal tacsf);
wenzelm@11884
   577
fun qed_spec_mp name =
wenzelm@11884
   578
  ThmDatabase.ml_store_thm (name, ObjectLogic.rulify_no_asm (result ()));
wenzelm@11884
   579
fun qed_goal_spec_mp name thy s p =
wenzelm@11884
   580
  bind_thm (name, ObjectLogic.rulify_no_asm (prove_goal thy s p));
wenzelm@11884
   581
fun qed_goalw_spec_mp name thy defs s p =
wenzelm@11884
   582
  bind_thm (name, ObjectLogic.rulify_no_asm (prove_goalw thy defs s p));
wenzelm@11884
   583
wenzelm@11884
   584
fun no_qed () = ();
wenzelm@11884
   585
wenzelm@11884
   586
wenzelm@11884
   587
(* retrieval *)
wenzelm@11884
   588
wenzelm@11884
   589
fun theory_of_goal () = ThyInfo.theory_of_sign (Thm.sign_of_thm (topthm ()));
wenzelm@11884
   590
wenzelm@11884
   591
fun thms_containing raw_consts =
wenzelm@11884
   592
  let
wenzelm@11884
   593
    val thy = theory_of_goal ();
wenzelm@11884
   594
    val consts = map (Sign.intern_const (Theory.sign_of thy)) raw_consts;
wenzelm@11884
   595
  in ThmDatabase.thms_containing thy consts end;
wenzelm@11884
   596
wenzelm@11884
   597
wenzelm@11884
   598
(*top_const: main constant, ignoring Trueprop*)
wenzelm@11884
   599
fun top_const (_ $ t) = (case head_of t of Const (c, _) => Some c | _ => None)
wenzelm@11884
   600
  | top_const _ = None;
wenzelm@11884
   601
wenzelm@11884
   602
val intro_const = top_const o concl_of;
wenzelm@11884
   603
wenzelm@11884
   604
fun elim_const thm = case prems_of thm of [] => None | p::_ => top_const p;
wenzelm@11884
   605
wenzelm@11884
   606
(* In case faster access is necessary, the thm db should provide special
wenzelm@11884
   607
functions
wenzelm@11884
   608
wenzelm@11884
   609
index_intros, index_elims: string -> (string * thm) list
wenzelm@11884
   610
wenzelm@11884
   611
where thm [| A1 ; ...; An |] ==> B is returned by
wenzelm@11884
   612
- index_intros c if B  is of the form c t1 ... tn
wenzelm@11884
   613
- index_elims c  if A1 is of the form c t1 ... tn
wenzelm@11884
   614
*)
wenzelm@11884
   615
wenzelm@11884
   616
(* could be provided by thm db *)
wenzelm@11884
   617
fun index_intros c =
wenzelm@11884
   618
  let fun topc(_,thm) = intro_const thm = Some(c);
wenzelm@11884
   619
      val named_thms = ThmDatabase.thms_containing (theory_of_goal ()) [c]
wenzelm@11884
   620
  in filter topc named_thms end;
wenzelm@11884
   621
wenzelm@11884
   622
(* could be provided by thm db *)
wenzelm@11884
   623
fun index_elims c =
wenzelm@11884
   624
  let fun topc(_,thm) = elim_const thm = Some(c);
wenzelm@11884
   625
      val named_thms = ThmDatabase.thms_containing (theory_of_goal ()) [c]
wenzelm@11884
   626
  in filter topc named_thms end;
wenzelm@11884
   627
wenzelm@11884
   628
(*assume that parameters have unique names; reverse them for substitution*)
wenzelm@11884
   629
fun goal_params i =
wenzelm@11884
   630
  let val gi = getgoal i
wenzelm@11884
   631
      val rfrees = rev(map Free (Logic.strip_params gi))
wenzelm@11884
   632
  in (gi,rfrees) end;
wenzelm@11884
   633
wenzelm@11884
   634
fun concl_of_goal i =
wenzelm@11884
   635
  let val (gi,rfrees) = goal_params i
wenzelm@11884
   636
      val B = Logic.strip_assums_concl gi
wenzelm@11884
   637
  in subst_bounds(rfrees,B) end;
wenzelm@11884
   638
wenzelm@11884
   639
fun prems_of_goal i =
wenzelm@11884
   640
  let val (gi,rfrees) = goal_params i
wenzelm@11884
   641
      val As = Logic.strip_assums_hyp gi
wenzelm@11884
   642
  in map (fn A => subst_bounds(rfrees,A)) As end;
wenzelm@11884
   643
wenzelm@11884
   644
(*returns all those named_thms whose subterm extracted by extract can be
wenzelm@11884
   645
  instantiated to obj; the list is sorted according to the number of premises
wenzelm@11884
   646
  and the size of the required substitution.*)
wenzelm@11884
   647
fun select_match(obj, signobj, named_thms, extract) =
wenzelm@11884
   648
  let fun matches(prop, tsig) =
wenzelm@11884
   649
            case extract prop of
wenzelm@11884
   650
              None => false
wenzelm@11884
   651
            | Some pat => Pattern.matches tsig (pat, obj);
wenzelm@11884
   652
wenzelm@11884
   653
      fun substsize(prop, tsig) =
wenzelm@11884
   654
            let val Some pat = extract prop
wenzelm@11884
   655
                val (_,subst) = Pattern.match tsig (pat,obj)
wenzelm@11884
   656
            in foldl op+
wenzelm@11884
   657
                (0, map (fn (_,t) => size_of_term t) subst)
wenzelm@11884
   658
            end
wenzelm@11884
   659
wenzelm@11884
   660
      fun thm_ord ((p0,s0,_),(p1,s1,_)) =
wenzelm@11884
   661
            prod_ord (int_ord o pairself (fn 0 => 0 | x => 1)) int_ord ((p0,s0),(p1,s1));
wenzelm@11884
   662
wenzelm@11884
   663
      fun select((p as (_,thm))::named_thms, sels) =
wenzelm@11884
   664
            let val {prop, sign, ...} = rep_thm thm
wenzelm@11884
   665
            in select(named_thms,
wenzelm@11884
   666
                      if Sign.subsig(sign, signobj) andalso
wenzelm@11884
   667
                         matches(prop,#tsig(Sign.rep_sg signobj))
wenzelm@11884
   668
                      then
wenzelm@11884
   669
                        (nprems_of thm,substsize(prop,#tsig(Sign.rep_sg signobj)),p)::sels
wenzelm@11884
   670
                      else sels)
wenzelm@11884
   671
            end
wenzelm@11884
   672
        | select([],sels) = sels
wenzelm@11884
   673
wenzelm@11884
   674
  in map (fn (_,_,t) => t) (sort thm_ord (select(named_thms, []))) end;
wenzelm@11884
   675
wenzelm@11884
   676
fun find_matching(prop,sign,index,extract) =
wenzelm@11884
   677
  (case top_const prop of
wenzelm@11884
   678
     Some c => select_match(prop,sign,index c,extract)
wenzelm@11884
   679
   | _      => []);
wenzelm@11884
   680
wenzelm@11884
   681
fun find_intros(prop,sign) =
wenzelm@11884
   682
  find_matching(prop,sign,index_intros,Some o Logic.strip_imp_concl);
wenzelm@11884
   683
wenzelm@11884
   684
fun find_elims sign prop =
wenzelm@11884
   685
  let fun major prop = case Logic.strip_imp_prems prop of
wenzelm@11884
   686
                         [] => None | p::_ => Some p
wenzelm@11884
   687
  in find_matching(prop,sign,index_elims,major) end;
wenzelm@11884
   688
wenzelm@11884
   689
fun findI i = find_intros(concl_of_goal i,#sign(rep_thm(topthm())));
wenzelm@11884
   690
wenzelm@11884
   691
fun findEs i =
wenzelm@11884
   692
  let fun eq_nth((n1,th1),(n2,th2)) = n1=n2 andalso eq_thm(th1,th2);
wenzelm@11884
   693
      val sign = #sign(rep_thm(topthm()))
wenzelm@11884
   694
      val thmss = map (find_elims sign) (prems_of_goal i)
wenzelm@11884
   695
  in foldl (gen_union eq_nth) ([],thmss) end;
wenzelm@11884
   696
wenzelm@11884
   697
fun findE i j =
wenzelm@11884
   698
  let val sign = #sign(rep_thm(topthm()))
wenzelm@11884
   699
  in find_elims sign (nth_elem(j-1, prems_of_goal i)) end;
wenzelm@11884
   700
clasohm@0
   701
end;
paulson@1500
   702
paulson@1500
   703
open Goals;