src/Pure/old_goals.ML
author wenzelm
Sun, 07 Mar 2010 12:19:47 +0100
changeset 35625 9c818cab0dd0
parent 35237 b625eb708d94
child 35990 3418cdf1855e
permissions -rw-r--r--
modernized structure Object_Logic;
wenzelm@18120
     1
(*  Title:      Pure/old_goals.ML
wenzelm@18120
     2
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
wenzelm@18120
     3
    Copyright   1993  University of Cambridge
wenzelm@18120
     4
wenzelm@18120
     5
Old-style goal stack package.  The goal stack initially holds a dummy
wenzelm@18120
     6
proof, and can never become empty.  Each goal stack consists of a list
wenzelm@18120
     7
of levels.  The undo list is a list of goal stacks.  Finally, there
wenzelm@18120
     8
may be a stack of pending proofs.
wenzelm@18120
     9
*)
wenzelm@18120
    10
wenzelm@32173
    11
signature OLD_GOALS =
wenzelm@18120
    12
sig
wenzelm@32235
    13
  val strip_context: term -> (string * typ) list * term list * term
wenzelm@32235
    14
  val metahyps_thms: int -> thm -> thm list option
wenzelm@32235
    15
  val METAHYPS: (thm list -> tactic) -> int -> tactic
wenzelm@32173
    16
  val simple_read_term: theory -> typ -> string -> term
wenzelm@32173
    17
  val read_term: theory -> string -> term
wenzelm@32173
    18
  val read_prop: theory -> string -> term
wenzelm@35237
    19
  val get_def: theory -> xstring -> thm
wenzelm@32173
    20
  type proof
wenzelm@18120
    21
  val premises: unit -> thm list
wenzelm@32173
    22
  val reset_goals: unit -> unit
wenzelm@32738
    23
  val result_error_fn: (thm -> string -> thm) Unsynchronized.ref
wenzelm@32173
    24
  val print_sign_exn: theory -> exn -> 'a
wenzelm@32173
    25
  val prove_goalw_cterm: thm list->cterm->(thm list->tactic list)->thm
wenzelm@32173
    26
  val prove_goalw_cterm_nocheck: thm list->cterm->(thm list->tactic list)->thm
wenzelm@32173
    27
  val prove_goalw: theory -> thm list -> string -> (thm list -> tactic list) -> thm
wenzelm@18120
    28
  val prove_goal: theory -> string -> (thm list -> tactic list) -> thm
wenzelm@18120
    29
  val topthm: unit -> thm
wenzelm@18120
    30
  val result: unit -> thm
wenzelm@18120
    31
  val uresult: unit -> thm
wenzelm@18120
    32
  val getgoal: int -> term
wenzelm@18120
    33
  val gethyps: int -> thm list
wenzelm@32173
    34
  val print_exn: exn -> 'a
wenzelm@32173
    35
  val filter_goal: (term*term->bool) -> thm list -> int -> thm list
wenzelm@18120
    36
  val prlev: int -> unit
wenzelm@18120
    37
  val pr: unit -> unit
wenzelm@18120
    38
  val prlim: int -> unit
wenzelm@32173
    39
  val goalw_cterm: thm list -> cterm -> thm list
wenzelm@32173
    40
  val goalw: theory -> thm list -> string -> thm list
wenzelm@18120
    41
  val goal: theory -> string -> thm list
wenzelm@32173
    42
  val Goalw: thm list -> string -> thm list
wenzelm@18120
    43
  val Goal: string -> thm list
wenzelm@32173
    44
  val simple_prove_goal_cterm: cterm->(thm list->tactic list)->thm
wenzelm@18120
    45
  val by: tactic -> unit
wenzelm@32173
    46
  val byev: tactic list -> unit
wenzelm@18120
    47
  val back: unit -> unit
wenzelm@18120
    48
  val choplev: int -> unit
wenzelm@32173
    49
  val chop: unit -> unit
wenzelm@18120
    50
  val undo: unit -> unit
wenzelm@32173
    51
  val save_proof: unit -> proof
wenzelm@32173
    52
  val restore_proof: proof -> thm list
wenzelm@32173
    53
  val push_proof: unit -> unit
wenzelm@32173
    54
  val pop_proof: unit -> thm list
wenzelm@32173
    55
  val rotate_proof: unit -> thm list
wenzelm@18120
    56
  val qed: string -> unit
wenzelm@18120
    57
  val qed_goal: string -> theory -> string -> (thm list -> tactic list) -> unit
wenzelm@18120
    58
  val qed_goalw: string -> theory -> thm list -> string
wenzelm@18120
    59
    -> (thm list -> tactic list) -> unit
wenzelm@18120
    60
  val qed_spec_mp: string -> unit
wenzelm@18120
    61
  val qed_goal_spec_mp: string -> theory -> string -> (thm list -> tactic list) -> unit
wenzelm@18120
    62
  val qed_goalw_spec_mp: string -> theory -> thm list -> string
wenzelm@18120
    63
    -> (thm list -> tactic list) -> unit
wenzelm@18120
    64
end;
wenzelm@18120
    65
wenzelm@18120
    66
structure OldGoals: OLD_GOALS =
wenzelm@18120
    67
struct
wenzelm@18120
    68
wenzelm@32235
    69
(**** METAHYPS -- tactical for using hypotheses as meta-level assumptions
wenzelm@32235
    70
       METAHYPS (fn prems => tac prems) i
wenzelm@32235
    71
wenzelm@32235
    72
converts subgoal i, of the form !!x1...xm. [| A1;...;An] ==> A into a new
wenzelm@32235
    73
proof state A==>A, supplying A1,...,An as meta-level assumptions (in
wenzelm@32235
    74
"prems").  The parameters x1,...,xm become free variables.  If the
wenzelm@32235
    75
resulting proof state is [| B1;...;Bk] ==> C (possibly assuming A1,...,An)
wenzelm@32235
    76
then it is lifted back into the original context, yielding k subgoals.
wenzelm@32235
    77
wenzelm@32235
    78
Replaces unknowns in the context by Frees having the prefix METAHYP_
wenzelm@32235
    79
New unknowns in [| B1;...;Bk] ==> C are lifted over x1,...,xm.
wenzelm@32235
    80
DOES NOT HANDLE TYPE UNKNOWNS.
wenzelm@32235
    81
wenzelm@32235
    82
wenzelm@32235
    83
NOTE: This version does not observe the proof context, and thus cannot
wenzelm@32235
    84
work reliably.  See also Subgoal.SUBPROOF and Subgoal.FOCUS for
wenzelm@32235
    85
properly localized variants of the same idea.
wenzelm@32235
    86
****)
wenzelm@32235
    87
wenzelm@32235
    88
(*Strips assumptions in goal yielding  ( [x1,...,xm], [H1,...,Hn], B )
wenzelm@32235
    89
    H1,...,Hn are the hypotheses;  x1...xm are variants of the parameters.
wenzelm@32235
    90
  Main difference from strip_assums concerns parameters:
wenzelm@32235
    91
    it replaces the bound variables by free variables.  *)
wenzelm@32235
    92
fun strip_context_aux (params, Hs, Const ("==>", _) $ H $ B) =
wenzelm@32235
    93
      strip_context_aux (params, H :: Hs, B)
wenzelm@32235
    94
  | strip_context_aux (params, Hs, Const ("all",_) $ Abs (a, T, t)) =
wenzelm@32235
    95
      let val (b, u) = Syntax.variant_abs (a, T, t)
wenzelm@32235
    96
      in strip_context_aux ((b, T) :: params, Hs, u) end
wenzelm@32235
    97
  | strip_context_aux (params, Hs, B) = (rev params, rev Hs, B);
wenzelm@32235
    98
wenzelm@32235
    99
fun strip_context A = strip_context_aux ([], [], A);
wenzelm@32235
   100
wenzelm@32235
   101
local
wenzelm@32235
   102
wenzelm@32235
   103
  (*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
wenzelm@32235
   104
    Instantiates distinct free variables by terms of same type.*)
wenzelm@32235
   105
  fun free_instantiate ctpairs =
wenzelm@32235
   106
    forall_elim_list (map snd ctpairs) o forall_intr_list (map fst ctpairs);
wenzelm@32235
   107
wenzelm@32235
   108
  fun free_of s ((a, i), T) =
wenzelm@32235
   109
    Free (s ^ (case i of 0 => a | _ => a ^ "_" ^ string_of_int i), T)
wenzelm@32235
   110
wenzelm@32235
   111
  fun mk_inst v = (Var v, free_of "METAHYP1_" v)
wenzelm@32235
   112
in
wenzelm@32235
   113
wenzelm@32235
   114
(*Common code for METAHYPS and metahyps_thms*)
wenzelm@32235
   115
fun metahyps_split_prem prem =
wenzelm@32235
   116
  let (*find all vars in the hyps -- should find tvars also!*)
wenzelm@32235
   117
      val hyps_vars = fold Term.add_vars (Logic.strip_assums_hyp prem) []
wenzelm@32235
   118
      val insts = map mk_inst hyps_vars
wenzelm@32235
   119
      (*replace the hyps_vars by Frees*)
wenzelm@32235
   120
      val prem' = subst_atomic insts prem
wenzelm@32235
   121
      val (params,hyps,concl) = strip_context prem'
wenzelm@32235
   122
  in (insts,params,hyps,concl)  end;
wenzelm@32235
   123
wenzelm@32235
   124
fun metahyps_aux_tac tacf (prem,gno) state =
wenzelm@32235
   125
  let val (insts,params,hyps,concl) = metahyps_split_prem prem
wenzelm@32235
   126
      val maxidx = Thm.maxidx_of state
wenzelm@32235
   127
      val cterm = Thm.cterm_of (Thm.theory_of_thm state)
wenzelm@32235
   128
      val chyps = map cterm hyps
wenzelm@32235
   129
      val hypths = map assume chyps
wenzelm@32235
   130
      val subprems = map (Thm.forall_elim_vars 0) hypths
wenzelm@32235
   131
      val fparams = map Free params
wenzelm@32235
   132
      val cparams = map cterm fparams
wenzelm@32235
   133
      fun swap_ctpair (t,u) = (cterm u, cterm t)
wenzelm@32235
   134
      (*Subgoal variables: make Free; lift type over params*)
wenzelm@32235
   135
      fun mk_subgoal_inst concl_vars (v, T) =
wenzelm@32235
   136
          if member (op =) concl_vars (v, T)
wenzelm@32235
   137
          then ((v, T), true, free_of "METAHYP2_" (v, T))
wenzelm@32235
   138
          else ((v, T), false, free_of "METAHYP2_" (v, map #2 params ---> T))
wenzelm@32235
   139
      (*Instantiate subgoal vars by Free applied to params*)
wenzelm@32235
   140
      fun mk_ctpair (v, in_concl, u) =
wenzelm@32235
   141
          if in_concl then (cterm (Var v), cterm u)
wenzelm@32235
   142
          else (cterm (Var v), cterm (list_comb (u, fparams)))
wenzelm@32235
   143
      (*Restore Vars with higher type and index*)
wenzelm@32235
   144
      fun mk_subgoal_swap_ctpair (((a, i), T), in_concl, u as Free (_, U)) =
wenzelm@32235
   145
          if in_concl then (cterm u, cterm (Var ((a, i), T)))
wenzelm@32235
   146
          else (cterm u, cterm (Var ((a, i + maxidx), U)))
wenzelm@32235
   147
      (*Embed B in the original context of params and hyps*)
wenzelm@32235
   148
      fun embed B = list_all_free (params, Logic.list_implies (hyps, B))
wenzelm@32235
   149
      (*Strip the context using elimination rules*)
wenzelm@32235
   150
      fun elim Bhyp = implies_elim_list (forall_elim_list cparams Bhyp) hypths
wenzelm@32235
   151
      (*A form of lifting that discharges assumptions.*)
wenzelm@32235
   152
      fun relift st =
wenzelm@32235
   153
        let val prop = Thm.prop_of st
wenzelm@32235
   154
            val subgoal_vars = (*Vars introduced in the subgoals*)
wenzelm@32235
   155
              fold Term.add_vars (Logic.strip_imp_prems prop) []
wenzelm@32235
   156
            and concl_vars = Term.add_vars (Logic.strip_imp_concl prop) []
wenzelm@32235
   157
            val subgoal_insts = map (mk_subgoal_inst concl_vars) subgoal_vars
wenzelm@32235
   158
            val st' = Thm.instantiate ([], map mk_ctpair subgoal_insts) st
wenzelm@32235
   159
            val emBs = map (cterm o embed) (prems_of st')
wenzelm@32235
   160
            val Cth  = implies_elim_list st' (map (elim o assume) emBs)
wenzelm@32235
   161
        in  (*restore the unknowns to the hypotheses*)
wenzelm@32235
   162
            free_instantiate (map swap_ctpair insts @
wenzelm@32235
   163
                              map mk_subgoal_swap_ctpair subgoal_insts)
wenzelm@32235
   164
                (*discharge assumptions from state in same order*)
wenzelm@32235
   165
                (implies_intr_list emBs
wenzelm@32235
   166
                  (forall_intr_list cparams (implies_intr_list chyps Cth)))
wenzelm@32235
   167
        end
wenzelm@32235
   168
      (*function to replace the current subgoal*)
wenzelm@32235
   169
      fun next st = Thm.bicompose false (false, relift st, nprems_of st) gno state
wenzelm@32235
   170
  in Seq.maps next (tacf subprems (trivial (cterm concl))) end;
wenzelm@32235
   171
wenzelm@32235
   172
end;
wenzelm@32235
   173
wenzelm@32235
   174
(*Returns the theorem list that METAHYPS would supply to its tactic*)
wenzelm@32235
   175
fun metahyps_thms i state =
wenzelm@32235
   176
  let val prem = Logic.nth_prem (i, Thm.prop_of state)
wenzelm@32235
   177
      and cterm = cterm_of (Thm.theory_of_thm state)
wenzelm@32235
   178
      val (_,_,hyps,_) = metahyps_split_prem prem
wenzelm@32235
   179
  in SOME (map (Thm.forall_elim_vars 0 o Thm.assume o cterm) hyps) end
wenzelm@32235
   180
  handle TERM ("nth_prem", [A]) => NONE;
wenzelm@32235
   181
wenzelm@32235
   182
local
wenzelm@32235
   183
wenzelm@32235
   184
fun print_vars_terms thy (n,thm) =
wenzelm@32235
   185
  let
wenzelm@32235
   186
    fun typed ty = " has type: " ^ Syntax.string_of_typ_global thy ty;
wenzelm@32235
   187
    fun find_vars thy (Const (c, ty)) =
wenzelm@32235
   188
          if null (Term.add_tvarsT ty []) then I
wenzelm@32235
   189
          else insert (op =) (c ^ typed ty)
wenzelm@32235
   190
      | find_vars thy (Var (xi, ty)) = insert (op =) (Term.string_of_vname xi ^ typed ty)
wenzelm@32235
   191
      | find_vars _ (Free _) = I
wenzelm@32235
   192
      | find_vars _ (Bound _) = I
wenzelm@32235
   193
      | find_vars thy (Abs (_, _, t)) = find_vars thy t
wenzelm@32235
   194
      | find_vars thy (t1 $ t2) =
wenzelm@32235
   195
          find_vars thy t1 #> find_vars thy t1;
wenzelm@32235
   196
    val prem = Logic.nth_prem (n, Thm.prop_of thm)
wenzelm@32235
   197
    val tms = find_vars thy prem []
wenzelm@32235
   198
  in
wenzelm@32235
   199
    (warning "Found schematic vars in assumptions:"; warning (cat_lines tms))
wenzelm@32235
   200
  end;
wenzelm@32235
   201
wenzelm@32235
   202
in
wenzelm@32235
   203
wenzelm@32235
   204
fun METAHYPS tacf n thm = SUBGOAL (metahyps_aux_tac tacf) n thm
wenzelm@32235
   205
  handle THM("assume: variables",_,_) => (print_vars_terms (theory_of_thm thm) (n,thm); Seq.empty)
wenzelm@32235
   206
wenzelm@32235
   207
end;
wenzelm@32235
   208
wenzelm@32235
   209
wenzelm@27256
   210
(* old ways of reading terms *)
wenzelm@27256
   211
wenzelm@27256
   212
fun simple_read_term thy T s =
wenzelm@27256
   213
  let
wenzelm@27256
   214
    val ctxt = ProofContext.init thy
wenzelm@27256
   215
      |> ProofContext.allow_dummies
wenzelm@27256
   216
      |> ProofContext.set_mode ProofContext.mode_schematic;
wenzelm@27256
   217
    val parse = if T = propT then Syntax.parse_prop else Syntax.parse_term;
wenzelm@27256
   218
  in parse ctxt s |> TypeInfer.constrain T |> Syntax.check_term ctxt end;
wenzelm@27256
   219
wenzelm@27256
   220
fun read_term thy = simple_read_term thy dummyT;
wenzelm@27256
   221
fun read_prop thy = simple_read_term thy propT;
wenzelm@27256
   222
wenzelm@27256
   223
wenzelm@35237
   224
fun get_def thy = Thm.axiom thy o Name_Space.intern (Theory.axiom_space thy) o Thm.def_name;
wenzelm@35237
   225
wenzelm@27256
   226
wenzelm@18120
   227
(*** Goal package ***)
wenzelm@18120
   228
wenzelm@18120
   229
(*Each level of goal stack includes a proof state and alternative states,
wenzelm@18120
   230
  the output of the tactic applied to the preceeding level.  *)
wenzelm@18120
   231
type gstack = (thm * thm Seq.seq) list;
wenzelm@18120
   232
wenzelm@18120
   233
datatype proof = Proof of gstack list * thm list * (bool*thm->thm);
wenzelm@18120
   234
wenzelm@18120
   235
wenzelm@18120
   236
(*** References ***)
wenzelm@18120
   237
wenzelm@18120
   238
(*Current assumption list -- set by "goal".*)
wenzelm@32738
   239
val curr_prems = Unsynchronized.ref([] : thm list);
wenzelm@18120
   240
wenzelm@18120
   241
(*Return assumption list -- useful if you didn't save "goal"'s result. *)
wenzelm@18120
   242
fun premises() = !curr_prems;
wenzelm@18120
   243
wenzelm@18120
   244
(*Current result maker -- set by "goal", used by "result".  *)
wenzelm@18120
   245
fun init_mkresult _ = error "No goal has been supplied in subgoal module";
wenzelm@32738
   246
val curr_mkresult = Unsynchronized.ref (init_mkresult: bool*thm->thm);
wenzelm@18120
   247
wenzelm@18120
   248
(*List of previous goal stacks, for the undo operation.  Set by setstate.
wenzelm@18120
   249
  A list of lists!*)
wenzelm@32738
   250
val undo_list = Unsynchronized.ref([[(asm_rl, Seq.empty)]] : gstack list);
wenzelm@18120
   251
wenzelm@18120
   252
(* Stack of proof attempts *)
wenzelm@32738
   253
val proofstack = Unsynchronized.ref([]: proof list);
wenzelm@18120
   254
wenzelm@18120
   255
(*reset all refs*)
wenzelm@18120
   256
fun reset_goals () =
wenzelm@18120
   257
  (curr_prems := []; curr_mkresult := init_mkresult;
wenzelm@26429
   258
    undo_list := [[(asm_rl, Seq.empty)]]);
wenzelm@18120
   259
wenzelm@18120
   260
wenzelm@18120
   261
(*** Setting up goal-directed proof ***)
wenzelm@18120
   262
wenzelm@18120
   263
(*Generates the list of new theories when the proof state's theory changes*)
wenzelm@18120
   264
fun thy_error (thy,thy') =
haftmann@33040
   265
  let val names = subtract (op =) (Context.display_names thy) (Context.display_names thy')
wenzelm@18120
   266
  in  case names of
wenzelm@18120
   267
        [name] => "\nNew theory: " ^ name
wenzelm@18120
   268
      | _       => "\nNew theories: " ^ space_implode ", " names
wenzelm@18120
   269
  end;
wenzelm@18120
   270
wenzelm@18120
   271
(*Default action is to print an error message; could be suppressed for
wenzelm@18120
   272
  special applications.*)
wenzelm@18120
   273
fun result_error_default state msg : thm =
wenzelm@32145
   274
  Pretty.str "Bad final proof state:" ::
wenzelm@32187
   275
      Goal_Display.pretty_goals_without_context (!goals_limit) state @
wenzelm@18120
   276
    [Pretty.str msg, Pretty.str "Proof failed!"] |> Pretty.chunks |> Pretty.string_of |> error;
wenzelm@18120
   277
wenzelm@32738
   278
val result_error_fn = Unsynchronized.ref result_error_default;
wenzelm@18120
   279
wenzelm@18120
   280
wenzelm@18120
   281
(*Common treatment of "goal" and "prove_goal":
wenzelm@18120
   282
  Return assumptions, initial proof state, and function to make result.
wenzelm@18120
   283
  "atomic" indicates if the goal should be wrapped up in the function
wenzelm@18120
   284
  "Goal::prop=>prop" to avoid assumptions being returned separately.
wenzelm@18120
   285
*)
wenzelm@18120
   286
fun prepare_proof atomic rths chorn =
wenzelm@18120
   287
  let
wenzelm@26291
   288
      val _ = legacy_feature "Old goal command";
wenzelm@26626
   289
      val thy = Thm.theory_of_cterm chorn;
wenzelm@26626
   290
      val horn = Thm.term_of chorn;
wenzelm@18120
   291
      val _ = Term.no_dummy_patterns horn handle TERM (msg, _) => error msg;
wenzelm@18120
   292
      val (As, B) = Logic.strip_horn horn;
wenzelm@18120
   293
      val atoms = atomic andalso
wenzelm@27332
   294
            forall (fn t => not (can Logic.dest_implies t orelse Logic.is_all t)) As;
wenzelm@18120
   295
      val (As,B) = if atoms then ([],horn) else (As,B);
wenzelm@18120
   296
      val cAs = map (cterm_of thy) As;
wenzelm@26653
   297
      val prems = map (rewrite_rule rths o Thm.forall_elim_vars 0 o Thm.assume) cAs;
wenzelm@18120
   298
      val cB = cterm_of thy B;
wenzelm@18120
   299
      val st0 = let val st = Goal.init cB |> fold Thm.weaken cAs
wenzelm@18120
   300
                in  rewrite_goals_rule rths st end
wenzelm@18120
   301
      (*discharges assumptions from state in the order they appear in goal;
wenzelm@18120
   302
        checks (if requested) that resulting theorem is equivalent to goal. *)
wenzelm@18120
   303
      fun mkresult (check,state) =
wenzelm@18120
   304
        let val state = Seq.hd (flexflex_rule state)
wenzelm@18120
   305
                        handle THM _ => state   (*smash flexflex pairs*)
wenzelm@18120
   306
            val ngoals = nprems_of state
wenzelm@18120
   307
            val ath = implies_intr_list cAs state
wenzelm@18120
   308
            val th = Goal.conclude ath
wenzelm@26626
   309
            val thy' = Thm.theory_of_thm th
wenzelm@26626
   310
            val {hyps, prop, ...} = Thm.rep_thm th
wenzelm@35021
   311
            val final_th = Drule.export_without_context th
wenzelm@18120
   312
        in  if not check then final_th
wenzelm@26665
   313
            else if not (Theory.eq_thy(thy,thy')) then !result_error_fn state
wenzelm@18120
   314
                ("Theory of proof state has changed!" ^
wenzelm@18120
   315
                 thy_error (thy,thy'))
wenzelm@18120
   316
            else if ngoals>0 then !result_error_fn state
wenzelm@18120
   317
                (string_of_int ngoals ^ " unsolved goals!")
wenzelm@18120
   318
            else if not (null hyps) then !result_error_fn state
wenzelm@18120
   319
                ("Additional hypotheses:\n" ^
wenzelm@26939
   320
                 cat_lines (map (Syntax.string_of_term_global thy) hyps))
wenzelm@18120
   321
            else if Pattern.matches thy
wenzelm@18120
   322
                                    (Envir.beta_norm (term_of chorn), Envir.beta_norm prop)
wenzelm@18120
   323
                 then final_th
wenzelm@18120
   324
            else  !result_error_fn state "proved a different theorem"
wenzelm@18120
   325
        end
wenzelm@18120
   326
  in
wenzelm@26665
   327
     if Theory.eq_thy(thy, Thm.theory_of_thm st0)
wenzelm@18120
   328
     then (prems, st0, mkresult)
wenzelm@18120
   329
     else error ("Definitions would change the proof state's theory" ^
wenzelm@18120
   330
                 thy_error (thy, Thm.theory_of_thm st0))
wenzelm@18120
   331
  end
wenzelm@18120
   332
  handle THM(s,_,_) => error("prepare_proof: exception THM was raised!\n" ^ s);
wenzelm@18120
   333
wenzelm@18120
   334
(*Prints exceptions readably to users*)
wenzelm@18120
   335
fun print_sign_exn_unit thy e =
wenzelm@18120
   336
  case e of
wenzelm@18120
   337
     THM (msg,i,thms) =>
wenzelm@18120
   338
         (writeln ("Exception THM " ^ string_of_int i ^ " raised:\n" ^ msg);
wenzelm@32111
   339
          List.app (writeln o Display.string_of_thm_global thy) thms)
wenzelm@18120
   340
   | THEORY (msg,thys) =>
wenzelm@18120
   341
         (writeln ("Exception THEORY raised:\n" ^ msg);
wenzelm@18120
   342
          List.app (writeln o Context.str_of_thy) thys)
wenzelm@18120
   343
   | TERM (msg,ts) =>
wenzelm@18120
   344
         (writeln ("Exception TERM raised:\n" ^ msg);
wenzelm@26939
   345
          List.app (writeln o Syntax.string_of_term_global thy) ts)
wenzelm@18120
   346
   | TYPE (msg,Ts,ts) =>
wenzelm@18120
   347
         (writeln ("Exception TYPE raised:\n" ^ msg);
wenzelm@26939
   348
          List.app (writeln o Syntax.string_of_typ_global thy) Ts;
wenzelm@26939
   349
          List.app (writeln o Syntax.string_of_term_global thy) ts)
wenzelm@18120
   350
   | e => raise e;
wenzelm@18120
   351
wenzelm@18120
   352
(*Prints an exception, then fails*)
wenzelm@18678
   353
fun print_sign_exn thy e = (print_sign_exn_unit thy e; raise ERROR "");
wenzelm@18120
   354
wenzelm@18120
   355
(** the prove_goal.... commands
wenzelm@18120
   356
    Prove theorem using the listed tactics; check it has the specified form.
wenzelm@18120
   357
    Augment theory with all type assignments of goal.
wenzelm@18120
   358
    Syntax is similar to "goal" command for easy keyboard use. **)
wenzelm@18120
   359
wenzelm@18120
   360
(*Version taking the goal as a cterm*)
wenzelm@18120
   361
fun prove_goalw_cterm_general check rths chorn tacsf =
wenzelm@18120
   362
  let val (prems, st0, mkresult) = prepare_proof false rths chorn
wenzelm@18120
   363
      val tac = EVERY (tacsf prems)
wenzelm@18120
   364
      fun statef() =
wenzelm@18120
   365
          (case Seq.pull (tac st0) of
wenzelm@18120
   366
               SOME(st,_) => st
wenzelm@18120
   367
             | _ => error ("prove_goal: tactic failed"))
wenzelm@32445
   368
  in  mkresult (check, cond_timeit (!Output.timing) "" statef)  end;
wenzelm@18120
   369
wenzelm@18120
   370
(*Two variants: one checking the result, one not.
wenzelm@18120
   371
  Neither prints runtime messages: they are for internal packages.*)
wenzelm@18120
   372
fun prove_goalw_cterm rths chorn =
wenzelm@32966
   373
        setmp_CRITICAL Output.timing false (prove_goalw_cterm_general true rths chorn)
wenzelm@18120
   374
and prove_goalw_cterm_nocheck rths chorn =
wenzelm@32966
   375
        setmp_CRITICAL Output.timing false (prove_goalw_cterm_general false rths chorn);
wenzelm@18120
   376
wenzelm@18120
   377
wenzelm@18120
   378
(*Version taking the goal as a string*)
wenzelm@18120
   379
fun prove_goalw thy rths agoal tacsf =
wenzelm@27256
   380
  let val chorn = cterm_of thy (read_prop thy agoal)
wenzelm@18120
   381
  in prove_goalw_cterm_general true rths chorn tacsf end
wenzelm@27256
   382
  handle ERROR msg => cat_error msg (*from read_prop?*)
wenzelm@18120
   383
                ("The error(s) above occurred for " ^ quote agoal);
wenzelm@18120
   384
wenzelm@18120
   385
(*String version with no meta-rewrite-rules*)
wenzelm@18120
   386
fun prove_goal thy = prove_goalw thy [];
wenzelm@18120
   387
wenzelm@18120
   388
wenzelm@18120
   389
wenzelm@18120
   390
(*** Commands etc ***)
wenzelm@18120
   391
wenzelm@18120
   392
(*Return the current goal stack, if any, from undo_list*)
wenzelm@18120
   393
fun getstate() : gstack = case !undo_list of
wenzelm@18120
   394
      []   => error"No current state in subgoal module"
wenzelm@18120
   395
    | x::_ => x;
wenzelm@18120
   396
wenzelm@18120
   397
(*Pops the given goal stack*)
wenzelm@18120
   398
fun pop [] = error"Cannot go back past the beginning of the proof!"
wenzelm@18120
   399
  | pop (pair::pairs) = (pair,pairs);
wenzelm@18120
   400
wenzelm@18120
   401
wenzelm@23635
   402
(* Print a level of the goal stack *)
wenzelm@18120
   403
wenzelm@18120
   404
fun print_top ((th, _), pairs) =
wenzelm@23635
   405
  let
wenzelm@23635
   406
    val n = length pairs;
wenzelm@23635
   407
    val m = (! goals_limit);
wenzelm@23635
   408
    val ngoals = nprems_of th;
wenzelm@23635
   409
  in
wenzelm@23635
   410
    [Pretty.str ("Level " ^ string_of_int n ^
wenzelm@23635
   411
      (if ngoals > 0 then " (" ^ string_of_int ngoals ^ " subgoal" ^
wenzelm@23635
   412
        (if ngoals <> 1 then "s" else "") ^ ")"
wenzelm@23635
   413
      else ""))] @
wenzelm@32187
   414
    Goal_Display.pretty_goals_without_context m th
wenzelm@23635
   415
  end |> Pretty.chunks |> Pretty.writeln;
wenzelm@18120
   416
wenzelm@18120
   417
(*Printing can raise exceptions, so the assignment occurs last.
wenzelm@18120
   418
  Can do   setstate[(st,Seq.empty)]  to set st as the state.  *)
wenzelm@18120
   419
fun setstate newgoals =
wenzelm@18120
   420
  (print_top (pop newgoals);  undo_list := newgoals :: !undo_list);
wenzelm@18120
   421
wenzelm@18120
   422
(*Given a proof state transformation, return a command that updates
wenzelm@18120
   423
    the goal stack*)
wenzelm@18120
   424
fun make_command com = setstate (com (pop (getstate())));
wenzelm@18120
   425
wenzelm@18120
   426
(*Apply a function on proof states to the current goal stack*)
wenzelm@18120
   427
fun apply_fun f = f (pop(getstate()));
wenzelm@18120
   428
wenzelm@18120
   429
(*Return the top theorem, representing the proof state*)
wenzelm@18120
   430
fun topthm () = apply_fun  (fn ((th,_), _) => th);
wenzelm@18120
   431
wenzelm@18120
   432
(*Return the final result.  *)
wenzelm@18120
   433
fun result () = !curr_mkresult (true, topthm());
wenzelm@18120
   434
wenzelm@18120
   435
(*Return the result UNCHECKED that it equals the goal -- for synthesis,
wenzelm@18120
   436
  answer extraction, or other instantiation of Vars *)
wenzelm@18120
   437
fun uresult () = !curr_mkresult (false, topthm());
wenzelm@18120
   438
wenzelm@18120
   439
(*Get subgoal i from goal stack*)
wenzelm@18120
   440
fun getgoal i = Logic.get_goal (prop_of (topthm())) i;
wenzelm@18120
   441
wenzelm@18120
   442
(*Return subgoal i's hypotheses as meta-level assumptions.
wenzelm@18120
   443
  For debugging uses of METAHYPS*)
wenzelm@18120
   444
local exception GETHYPS of thm list
wenzelm@18120
   445
in
wenzelm@18120
   446
fun gethyps i =
wenzelm@18120
   447
    (METAHYPS (fn hyps => raise (GETHYPS hyps)) i (topthm());  [])
wenzelm@18120
   448
    handle GETHYPS hyps => hyps
wenzelm@18120
   449
end;
wenzelm@18120
   450
wenzelm@18120
   451
(*Prints exceptions nicely at top level;
wenzelm@18120
   452
  raises the exception in order to have a polymorphic type!*)
wenzelm@18120
   453
fun print_exn e = (print_sign_exn_unit (Thm.theory_of_thm (topthm())) e;  raise e);
wenzelm@18120
   454
wenzelm@18120
   455
(*Which thms could apply to goal i? (debugs tactics involving filter_thms) *)
wenzelm@18120
   456
fun filter_goal could ths i = filter_thms could (999, getgoal i, ths);
wenzelm@18120
   457
wenzelm@18120
   458
(*For inspecting earlier levels of the backward proof*)
wenzelm@18120
   459
fun chop_level n (pair,pairs) =
wenzelm@18120
   460
  let val level = length pairs
wenzelm@18120
   461
  in  if n<0 andalso ~n <= level
wenzelm@18120
   462
      then  List.drop (pair::pairs, ~n)
wenzelm@18120
   463
      else if 0<=n andalso n<= level
wenzelm@18120
   464
      then  List.drop (pair::pairs, level - n)
wenzelm@18120
   465
      else  error ("Level number must lie between 0 and " ^
wenzelm@18120
   466
                   string_of_int level)
wenzelm@18120
   467
  end;
wenzelm@18120
   468
wenzelm@18120
   469
(*Print the given level of the proof; prlev ~1 prints previous level*)
wenzelm@23635
   470
fun prlev n = apply_fun (print_top o pop o (chop_level n));
wenzelm@23635
   471
fun pr () = apply_fun print_top;
wenzelm@18120
   472
wenzelm@18120
   473
(*Set goals_limit and print again*)
wenzelm@18120
   474
fun prlim n = (goals_limit:=n; pr());
wenzelm@18120
   475
wenzelm@18120
   476
(** the goal.... commands
wenzelm@18120
   477
    Read main goal.  Set global variables curr_prems, curr_mkresult.
wenzelm@18120
   478
    Initial subgoal and premises are rewritten using rths. **)
wenzelm@18120
   479
wenzelm@18120
   480
(*Version taking the goal as a cterm; if you have a term t and theory thy, use
wenzelm@18120
   481
    goalw_cterm rths (cterm_of thy t);      *)
wenzelm@18120
   482
fun agoalw_cterm atomic rths chorn =
wenzelm@18120
   483
  let val (prems, st0, mkresult) = prepare_proof atomic rths chorn
wenzelm@18120
   484
  in  undo_list := [];
wenzelm@18120
   485
      setstate [ (st0, Seq.empty) ];
wenzelm@18120
   486
      curr_prems := prems;
wenzelm@18120
   487
      curr_mkresult := mkresult;
wenzelm@18120
   488
      prems
wenzelm@18120
   489
  end;
wenzelm@18120
   490
wenzelm@18120
   491
val goalw_cterm = agoalw_cterm false;
wenzelm@18120
   492
wenzelm@18120
   493
(*Version taking the goal as a string*)
wenzelm@18120
   494
fun agoalw atomic thy rths agoal =
wenzelm@27256
   495
    agoalw_cterm atomic rths (cterm_of thy (read_prop thy agoal))
wenzelm@18678
   496
    handle ERROR msg => cat_error msg (*from type_assign, etc via prepare_proof*)
wenzelm@18120
   497
        ("The error(s) above occurred for " ^ quote agoal);
wenzelm@18120
   498
wenzelm@18120
   499
val goalw = agoalw false;
wenzelm@18120
   500
fun goal thy = goalw thy [];
wenzelm@18120
   501
wenzelm@18120
   502
(*now the versions that wrap the goal up in `Goal' to make it atomic*)
wenzelm@26429
   503
fun Goalw thms s = agoalw true (ML_Context.the_global_context ()) thms s;
wenzelm@18120
   504
val Goal = Goalw [];
wenzelm@18120
   505
wenzelm@18120
   506
(*simple version with minimal amount of checking and postprocessing*)
wenzelm@18120
   507
fun simple_prove_goal_cterm G f =
wenzelm@18120
   508
  let
wenzelm@26291
   509
    val _ = legacy_feature "Old goal command";
wenzelm@18120
   510
    val As = Drule.strip_imp_prems G;
wenzelm@18120
   511
    val B = Drule.strip_imp_concl G;
wenzelm@20229
   512
    val asms = map Assumption.assume As;
wenzelm@18120
   513
    fun check NONE = error "prove_goal: tactic failed"
wenzelm@18120
   514
      | check (SOME (thm, _)) = (case nprems_of thm of
wenzelm@18120
   515
            0 => thm
wenzelm@18120
   516
          | i => !result_error_fn thm (string_of_int i ^ " unsolved goals!"))
wenzelm@18120
   517
  in
wenzelm@35021
   518
    Drule.export_without_context (implies_intr_list As
wenzelm@18120
   519
      (check (Seq.pull (EVERY (f asms) (trivial B)))))
wenzelm@18120
   520
  end;
wenzelm@18120
   521
wenzelm@18120
   522
wenzelm@18120
   523
(*Proof step "by" the given tactic -- apply tactic to the proof state*)
wenzelm@18120
   524
fun by_com tac ((th,ths), pairs) : gstack =
wenzelm@18120
   525
  (case  Seq.pull(tac th)  of
wenzelm@18120
   526
     NONE      => error"by: tactic failed"
wenzelm@18120
   527
   | SOME(th2,ths2) =>
wenzelm@22360
   528
       (if Thm.eq_thm(th,th2)
wenzelm@18120
   529
          then warning "Warning: same as previous level"
wenzelm@22360
   530
          else if Thm.eq_thm_thy(th,th2) then ()
wenzelm@18120
   531
          else warning ("Warning: theory of proof state has changed" ^
wenzelm@18120
   532
                       thy_error (Thm.theory_of_thm th, Thm.theory_of_thm th2));
wenzelm@18120
   533
       ((th2,ths2)::(th,ths)::pairs)));
wenzelm@18120
   534
wenzelm@25685
   535
fun by tac = cond_timeit (!Output.timing) ""
wenzelm@18120
   536
    (fn() => make_command (by_com tac));
wenzelm@18120
   537
wenzelm@18120
   538
(* byev[tac1,...,tacn] applies tac1 THEN ... THEN tacn.
wenzelm@18120
   539
   Good for debugging proofs involving prove_goal.*)
wenzelm@18120
   540
val byev = by o EVERY;
wenzelm@18120
   541
wenzelm@18120
   542
wenzelm@18120
   543
(*Backtracking means find an alternative result from a tactic.
wenzelm@18120
   544
  If none at this level, try earlier levels*)
wenzelm@18120
   545
fun backtrack [] = error"back: no alternatives"
wenzelm@18120
   546
  | backtrack ((th,thstr) :: pairs) =
wenzelm@18120
   547
     (case Seq.pull thstr of
wenzelm@18120
   548
          NONE      => (writeln"Going back a level..."; backtrack pairs)
wenzelm@18120
   549
        | SOME(th2,thstr2) =>
wenzelm@22360
   550
           (if Thm.eq_thm(th,th2)
wenzelm@18120
   551
              then warning "Warning: same as previous choice at this level"
wenzelm@22360
   552
              else if Thm.eq_thm_thy(th,th2) then ()
wenzelm@18120
   553
              else warning "Warning: theory of proof state has changed";
wenzelm@18120
   554
            (th2,thstr2)::pairs));
wenzelm@18120
   555
wenzelm@18120
   556
fun back() = setstate (backtrack (getstate()));
wenzelm@18120
   557
wenzelm@18120
   558
(*Chop back to previous level of the proof*)
wenzelm@18120
   559
fun choplev n = make_command (chop_level n);
wenzelm@18120
   560
wenzelm@18120
   561
(*Chopping back the goal stack*)
wenzelm@18120
   562
fun chop () = make_command (fn (_,pairs) => pairs);
wenzelm@18120
   563
wenzelm@18120
   564
(*Restore the previous proof state;  discard current state. *)
wenzelm@18120
   565
fun undo() = case !undo_list of
wenzelm@18120
   566
      [] => error"No proof state"
wenzelm@18120
   567
    | [_] => error"Already at initial state"
wenzelm@18120
   568
    | _::newundo =>  (undo_list := newundo;  pr()) ;
wenzelm@18120
   569
wenzelm@18120
   570
wenzelm@18120
   571
(*** Managing the proof stack ***)
wenzelm@18120
   572
wenzelm@18120
   573
fun save_proof() = Proof(!undo_list, !curr_prems, !curr_mkresult);
wenzelm@18120
   574
wenzelm@18120
   575
fun restore_proof(Proof(ul,prems,mk)) =
wenzelm@18120
   576
 (undo_list:= ul;  curr_prems:= prems;  curr_mkresult := mk;  prems);
wenzelm@18120
   577
wenzelm@18120
   578
wenzelm@18120
   579
fun top_proof() = case !proofstack of
wenzelm@18120
   580
        [] => error("Stack of proof attempts is empty!")
wenzelm@18120
   581
    | p::ps => (p,ps);
wenzelm@18120
   582
wenzelm@18120
   583
(*  push a copy of the current proof state on to the stack *)
wenzelm@18120
   584
fun push_proof() = (proofstack := (save_proof() :: !proofstack));
wenzelm@18120
   585
wenzelm@18120
   586
(* discard the top proof state of the stack *)
wenzelm@18120
   587
fun pop_proof() =
wenzelm@18120
   588
  let val (p,ps) = top_proof()
wenzelm@18120
   589
      val prems = restore_proof p
wenzelm@18120
   590
  in proofstack := ps;  pr();  prems end;
wenzelm@18120
   591
wenzelm@18120
   592
(* rotate the stack so that the top element goes to the bottom *)
wenzelm@32173
   593
fun rotate_proof() =
wenzelm@32173
   594
  let val (p,ps) = top_proof()
wenzelm@32173
   595
  in proofstack := ps@[save_proof()];
wenzelm@32173
   596
     restore_proof p;
wenzelm@32173
   597
     pr();
wenzelm@32173
   598
     !curr_prems
wenzelm@32173
   599
  end;
wenzelm@18120
   600
wenzelm@18120
   601
wenzelm@26414
   602
(** theorem bindings **)
wenzelm@18120
   603
wenzelm@26414
   604
fun qed name = ML_Context.ml_store_thm (name, result ());
wenzelm@26414
   605
fun qed_goal name thy goal tacsf = ML_Context.ml_store_thm (name, prove_goal thy goal tacsf);
wenzelm@18120
   606
fun qed_goalw name thy rews goal tacsf =
wenzelm@26414
   607
  ML_Context.ml_store_thm (name, prove_goalw thy rews goal tacsf);
wenzelm@18120
   608
fun qed_spec_mp name =
wenzelm@35625
   609
  ML_Context.ml_store_thm (name, Object_Logic.rulify_no_asm (result ()));
wenzelm@18120
   610
fun qed_goal_spec_mp name thy s p =
wenzelm@35625
   611
  bind_thm (name, Object_Logic.rulify_no_asm (prove_goal thy s p));
wenzelm@18120
   612
fun qed_goalw_spec_mp name thy defs s p =
wenzelm@35625
   613
  bind_thm (name, Object_Logic.rulify_no_asm (prove_goalw thy defs s p));
wenzelm@18120
   614
wenzelm@18120
   615
end;
wenzelm@18120
   616