src/Pure/old_goals.ML
author wenzelm
Mon Jul 27 20:45:40 2009 +0200 (2009-07-27)
changeset 32231 95b8afcbb0ed
parent 32187 cca43ca13f4f
child 32432 64f30bdd3ba1
permissions -rw-r--r--
moved METAHYPS to old_goals.ML (cf. SUBPROOF and FOCUS in subgoal.ML for properly localized versions of the same idea);
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@32231
    13
  val strip_context: term -> (string * typ) list * term list * term
wenzelm@32231
    14
  val metahyps_thms: int -> thm -> thm list option
wenzelm@32231
    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@32173
    19
  type proof
wenzelm@18120
    20
  val premises: unit -> thm list
wenzelm@32173
    21
  val reset_goals: unit -> unit
wenzelm@32173
    22
  val result_error_fn: (thm -> string -> thm) ref
wenzelm@32173
    23
  val print_sign_exn: theory -> exn -> 'a
wenzelm@32173
    24
  val prove_goalw_cterm: thm list->cterm->(thm list->tactic list)->thm
wenzelm@32173
    25
  val prove_goalw_cterm_nocheck: thm list->cterm->(thm list->tactic list)->thm
wenzelm@32173
    26
  val prove_goalw: theory -> thm list -> string -> (thm list -> tactic list) -> thm
wenzelm@18120
    27
  val prove_goal: theory -> string -> (thm list -> tactic list) -> thm
wenzelm@18120
    28
  val topthm: unit -> thm
wenzelm@18120
    29
  val result: unit -> thm
wenzelm@18120
    30
  val uresult: unit -> thm
wenzelm@18120
    31
  val getgoal: int -> term
wenzelm@18120
    32
  val gethyps: int -> thm list
wenzelm@32173
    33
  val print_exn: exn -> 'a
wenzelm@32173
    34
  val filter_goal: (term*term->bool) -> thm list -> int -> thm list
wenzelm@18120
    35
  val prlev: int -> unit
wenzelm@18120
    36
  val pr: unit -> unit
wenzelm@18120
    37
  val prlim: int -> unit
wenzelm@32173
    38
  val goalw_cterm: thm list -> cterm -> thm list
wenzelm@32173
    39
  val goalw: theory -> thm list -> string -> thm list
wenzelm@18120
    40
  val goal: theory -> string -> thm list
wenzelm@32173
    41
  val Goalw: thm list -> string -> thm list
wenzelm@18120
    42
  val Goal: string -> thm list
wenzelm@32173
    43
  val simple_prove_goal_cterm: cterm->(thm list->tactic list)->thm
wenzelm@18120
    44
  val by: tactic -> unit
wenzelm@32173
    45
  val byev: tactic list -> unit
wenzelm@18120
    46
  val back: unit -> unit
wenzelm@18120
    47
  val choplev: int -> unit
wenzelm@32173
    48
  val chop: unit -> unit
wenzelm@18120
    49
  val undo: unit -> unit
wenzelm@32173
    50
  val save_proof: unit -> proof
wenzelm@32173
    51
  val restore_proof: proof -> thm list
wenzelm@32173
    52
  val push_proof: unit -> unit
wenzelm@32173
    53
  val pop_proof: unit -> thm list
wenzelm@32173
    54
  val rotate_proof: unit -> thm list
wenzelm@18120
    55
  val qed: string -> unit
wenzelm@18120
    56
  val qed_goal: string -> theory -> string -> (thm list -> tactic list) -> unit
wenzelm@18120
    57
  val qed_goalw: string -> theory -> thm list -> string
wenzelm@18120
    58
    -> (thm list -> tactic list) -> unit
wenzelm@18120
    59
  val qed_spec_mp: string -> unit
wenzelm@18120
    60
  val qed_goal_spec_mp: string -> theory -> string -> (thm list -> tactic list) -> unit
wenzelm@18120
    61
  val qed_goalw_spec_mp: string -> theory -> thm list -> string
wenzelm@18120
    62
    -> (thm list -> tactic list) -> unit
wenzelm@18120
    63
end;
wenzelm@18120
    64
wenzelm@18120
    65
structure OldGoals: OLD_GOALS =
wenzelm@18120
    66
struct
wenzelm@18120
    67
wenzelm@32231
    68
(**** METAHYPS -- tactical for using hypotheses as meta-level assumptions
wenzelm@32231
    69
       METAHYPS (fn prems => tac prems) i
wenzelm@32231
    70
wenzelm@32231
    71
converts subgoal i, of the form !!x1...xm. [| A1;...;An] ==> A into a new
wenzelm@32231
    72
proof state A==>A, supplying A1,...,An as meta-level assumptions (in
wenzelm@32231
    73
"prems").  The parameters x1,...,xm become free variables.  If the
wenzelm@32231
    74
resulting proof state is [| B1;...;Bk] ==> C (possibly assuming A1,...,An)
wenzelm@32231
    75
then it is lifted back into the original context, yielding k subgoals.
wenzelm@32231
    76
wenzelm@32231
    77
Replaces unknowns in the context by Frees having the prefix METAHYP_
wenzelm@32231
    78
New unknowns in [| B1;...;Bk] ==> C are lifted over x1,...,xm.
wenzelm@32231
    79
DOES NOT HANDLE TYPE UNKNOWNS.
wenzelm@32231
    80
wenzelm@32231
    81
wenzelm@32231
    82
NOTE: This version does not observe the proof context, and thus cannot
wenzelm@32231
    83
work reliably.  See also Subgoal.SUBPROOF and Subgoal.FOCUS for
wenzelm@32231
    84
properly localized variants of the same idea.
wenzelm@32231
    85
****)
wenzelm@32231
    86
wenzelm@32231
    87
(*Strips assumptions in goal yielding  ( [x1,...,xm], [H1,...,Hn], B )
wenzelm@32231
    88
    H1,...,Hn are the hypotheses;  x1...xm are variants of the parameters.
wenzelm@32231
    89
  Main difference from strip_assums concerns parameters:
wenzelm@32231
    90
    it replaces the bound variables by free variables.  *)
wenzelm@32231
    91
fun strip_context_aux (params, Hs, Const ("==>", _) $ H $ B) =
wenzelm@32231
    92
      strip_context_aux (params, H :: Hs, B)
wenzelm@32231
    93
  | strip_context_aux (params, Hs, Const ("all",_) $ Abs (a, T, t)) =
wenzelm@32231
    94
      let val (b, u) = Syntax.variant_abs (a, T, t)
wenzelm@32231
    95
      in strip_context_aux ((b, T) :: params, Hs, u) end
wenzelm@32231
    96
  | strip_context_aux (params, Hs, B) = (rev params, rev Hs, B);
wenzelm@32231
    97
wenzelm@32231
    98
fun strip_context A = strip_context_aux ([], [], A);
wenzelm@32231
    99
wenzelm@32231
   100
local
wenzelm@32231
   101
wenzelm@32231
   102
  (*Left-to-right replacements: ctpairs = [...,(vi,ti),...].
wenzelm@32231
   103
    Instantiates distinct free variables by terms of same type.*)
wenzelm@32231
   104
  fun free_instantiate ctpairs =
wenzelm@32231
   105
    forall_elim_list (map snd ctpairs) o forall_intr_list (map fst ctpairs);
wenzelm@32231
   106
wenzelm@32231
   107
  fun free_of s ((a, i), T) =
wenzelm@32231
   108
    Free (s ^ (case i of 0 => a | _ => a ^ "_" ^ string_of_int i), T)
wenzelm@32231
   109
wenzelm@32231
   110
  fun mk_inst v = (Var v, free_of "METAHYP1_" v)
wenzelm@32231
   111
in
wenzelm@32231
   112
wenzelm@32231
   113
(*Common code for METAHYPS and metahyps_thms*)
wenzelm@32231
   114
fun metahyps_split_prem prem =
wenzelm@32231
   115
  let (*find all vars in the hyps -- should find tvars also!*)
wenzelm@32231
   116
      val hyps_vars = fold Term.add_vars (Logic.strip_assums_hyp prem) []
wenzelm@32231
   117
      val insts = map mk_inst hyps_vars
wenzelm@32231
   118
      (*replace the hyps_vars by Frees*)
wenzelm@32231
   119
      val prem' = subst_atomic insts prem
wenzelm@32231
   120
      val (params,hyps,concl) = strip_context prem'
wenzelm@32231
   121
  in (insts,params,hyps,concl)  end;
wenzelm@32231
   122
wenzelm@32231
   123
fun metahyps_aux_tac tacf (prem,gno) state =
wenzelm@32231
   124
  let val (insts,params,hyps,concl) = metahyps_split_prem prem
wenzelm@32231
   125
      val maxidx = Thm.maxidx_of state
wenzelm@32231
   126
      val cterm = Thm.cterm_of (Thm.theory_of_thm state)
wenzelm@32231
   127
      val chyps = map cterm hyps
wenzelm@32231
   128
      val hypths = map assume chyps
wenzelm@32231
   129
      val subprems = map (Thm.forall_elim_vars 0) hypths
wenzelm@32231
   130
      val fparams = map Free params
wenzelm@32231
   131
      val cparams = map cterm fparams
wenzelm@32231
   132
      fun swap_ctpair (t,u) = (cterm u, cterm t)
wenzelm@32231
   133
      (*Subgoal variables: make Free; lift type over params*)
wenzelm@32231
   134
      fun mk_subgoal_inst concl_vars (v, T) =
wenzelm@32231
   135
          if member (op =) concl_vars (v, T)
wenzelm@32231
   136
          then ((v, T), true, free_of "METAHYP2_" (v, T))
wenzelm@32231
   137
          else ((v, T), false, free_of "METAHYP2_" (v, map #2 params ---> T))
wenzelm@32231
   138
      (*Instantiate subgoal vars by Free applied to params*)
wenzelm@32231
   139
      fun mk_ctpair (v, in_concl, u) =
wenzelm@32231
   140
          if in_concl then (cterm (Var v), cterm u)
wenzelm@32231
   141
          else (cterm (Var v), cterm (list_comb (u, fparams)))
wenzelm@32231
   142
      (*Restore Vars with higher type and index*)
wenzelm@32231
   143
      fun mk_subgoal_swap_ctpair (((a, i), T), in_concl, u as Free (_, U)) =
wenzelm@32231
   144
          if in_concl then (cterm u, cterm (Var ((a, i), T)))
wenzelm@32231
   145
          else (cterm u, cterm (Var ((a, i + maxidx), U)))
wenzelm@32231
   146
      (*Embed B in the original context of params and hyps*)
wenzelm@32231
   147
      fun embed B = list_all_free (params, Logic.list_implies (hyps, B))
wenzelm@32231
   148
      (*Strip the context using elimination rules*)
wenzelm@32231
   149
      fun elim Bhyp = implies_elim_list (forall_elim_list cparams Bhyp) hypths
wenzelm@32231
   150
      (*A form of lifting that discharges assumptions.*)
wenzelm@32231
   151
      fun relift st =
wenzelm@32231
   152
        let val prop = Thm.prop_of st
wenzelm@32231
   153
            val subgoal_vars = (*Vars introduced in the subgoals*)
wenzelm@32231
   154
              fold Term.add_vars (Logic.strip_imp_prems prop) []
wenzelm@32231
   155
            and concl_vars = Term.add_vars (Logic.strip_imp_concl prop) []
wenzelm@32231
   156
            val subgoal_insts = map (mk_subgoal_inst concl_vars) subgoal_vars
wenzelm@32231
   157
            val st' = Thm.instantiate ([], map mk_ctpair subgoal_insts) st
wenzelm@32231
   158
            val emBs = map (cterm o embed) (prems_of st')
wenzelm@32231
   159
            val Cth  = implies_elim_list st' (map (elim o assume) emBs)
wenzelm@32231
   160
        in  (*restore the unknowns to the hypotheses*)
wenzelm@32231
   161
            free_instantiate (map swap_ctpair insts @
wenzelm@32231
   162
                              map mk_subgoal_swap_ctpair subgoal_insts)
wenzelm@32231
   163
                (*discharge assumptions from state in same order*)
wenzelm@32231
   164
                (implies_intr_list emBs
wenzelm@32231
   165
                  (forall_intr_list cparams (implies_intr_list chyps Cth)))
wenzelm@32231
   166
        end
wenzelm@32231
   167
      (*function to replace the current subgoal*)
wenzelm@32231
   168
      fun next st = Thm.bicompose false (false, relift st, nprems_of st) gno state
wenzelm@32231
   169
  in Seq.maps next (tacf subprems (trivial (cterm concl))) end;
wenzelm@32231
   170
wenzelm@32231
   171
end;
wenzelm@32231
   172
wenzelm@32231
   173
(*Returns the theorem list that METAHYPS would supply to its tactic*)
wenzelm@32231
   174
fun metahyps_thms i state =
wenzelm@32231
   175
  let val prem = Logic.nth_prem (i, Thm.prop_of state)
wenzelm@32231
   176
      and cterm = cterm_of (Thm.theory_of_thm state)
wenzelm@32231
   177
      val (_,_,hyps,_) = metahyps_split_prem prem
wenzelm@32231
   178
  in SOME (map (Thm.forall_elim_vars 0 o Thm.assume o cterm) hyps) end
wenzelm@32231
   179
  handle TERM ("nth_prem", [A]) => NONE;
wenzelm@32231
   180
wenzelm@32231
   181
local
wenzelm@32231
   182
wenzelm@32231
   183
fun print_vars_terms thy (n,thm) =
wenzelm@32231
   184
  let
wenzelm@32231
   185
    fun typed ty = " has type: " ^ Syntax.string_of_typ_global thy ty;
wenzelm@32231
   186
    fun find_vars thy (Const (c, ty)) =
wenzelm@32231
   187
          if null (Term.add_tvarsT ty []) then I
wenzelm@32231
   188
          else insert (op =) (c ^ typed ty)
wenzelm@32231
   189
      | find_vars thy (Var (xi, ty)) = insert (op =) (Term.string_of_vname xi ^ typed ty)
wenzelm@32231
   190
      | find_vars _ (Free _) = I
wenzelm@32231
   191
      | find_vars _ (Bound _) = I
wenzelm@32231
   192
      | find_vars thy (Abs (_, _, t)) = find_vars thy t
wenzelm@32231
   193
      | find_vars thy (t1 $ t2) =
wenzelm@32231
   194
          find_vars thy t1 #> find_vars thy t1;
wenzelm@32231
   195
    val prem = Logic.nth_prem (n, Thm.prop_of thm)
wenzelm@32231
   196
    val tms = find_vars thy prem []
wenzelm@32231
   197
  in
wenzelm@32231
   198
    (warning "Found schematic vars in assumptions:"; warning (cat_lines tms))
wenzelm@32231
   199
  end;
wenzelm@32231
   200
wenzelm@32231
   201
in
wenzelm@32231
   202
wenzelm@32231
   203
fun METAHYPS tacf n thm = SUBGOAL (metahyps_aux_tac tacf) n thm
wenzelm@32231
   204
  handle THM("assume: variables",_,_) => (print_vars_terms (theory_of_thm thm) (n,thm); Seq.empty)
wenzelm@32231
   205
wenzelm@32231
   206
end;
wenzelm@32231
   207
wenzelm@32231
   208
wenzelm@27256
   209
(* old ways of reading terms *)
wenzelm@27256
   210
wenzelm@27256
   211
fun simple_read_term thy T s =
wenzelm@27256
   212
  let
wenzelm@27256
   213
    val ctxt = ProofContext.init thy
wenzelm@27256
   214
      |> ProofContext.allow_dummies
wenzelm@27256
   215
      |> ProofContext.set_mode ProofContext.mode_schematic;
wenzelm@27256
   216
    val parse = if T = propT then Syntax.parse_prop else Syntax.parse_term;
wenzelm@27256
   217
  in parse ctxt s |> TypeInfer.constrain T |> Syntax.check_term ctxt end;
wenzelm@27256
   218
wenzelm@27256
   219
fun read_term thy = simple_read_term thy dummyT;
wenzelm@27256
   220
fun read_prop thy = simple_read_term thy propT;
wenzelm@27256
   221
wenzelm@27256
   222
wenzelm@27256
   223
wenzelm@18120
   224
(*** Goal package ***)
wenzelm@18120
   225
wenzelm@18120
   226
(*Each level of goal stack includes a proof state and alternative states,
wenzelm@18120
   227
  the output of the tactic applied to the preceeding level.  *)
wenzelm@18120
   228
type gstack = (thm * thm Seq.seq) list;
wenzelm@18120
   229
wenzelm@18120
   230
datatype proof = Proof of gstack list * thm list * (bool*thm->thm);
wenzelm@18120
   231
wenzelm@18120
   232
wenzelm@18120
   233
(*** References ***)
wenzelm@18120
   234
wenzelm@18120
   235
(*Current assumption list -- set by "goal".*)
wenzelm@18120
   236
val curr_prems = ref([] : thm list);
wenzelm@18120
   237
wenzelm@18120
   238
(*Return assumption list -- useful if you didn't save "goal"'s result. *)
wenzelm@18120
   239
fun premises() = !curr_prems;
wenzelm@18120
   240
wenzelm@18120
   241
(*Current result maker -- set by "goal", used by "result".  *)
wenzelm@18120
   242
fun init_mkresult _ = error "No goal has been supplied in subgoal module";
wenzelm@18120
   243
val curr_mkresult = ref (init_mkresult: bool*thm->thm);
wenzelm@18120
   244
wenzelm@18120
   245
(*List of previous goal stacks, for the undo operation.  Set by setstate.
wenzelm@18120
   246
  A list of lists!*)
wenzelm@26429
   247
val undo_list = ref([[(asm_rl, Seq.empty)]] : gstack list);
wenzelm@18120
   248
wenzelm@18120
   249
(* Stack of proof attempts *)
wenzelm@18120
   250
val proofstack = ref([]: proof list);
wenzelm@18120
   251
wenzelm@18120
   252
(*reset all refs*)
wenzelm@18120
   253
fun reset_goals () =
wenzelm@18120
   254
  (curr_prems := []; curr_mkresult := init_mkresult;
wenzelm@26429
   255
    undo_list := [[(asm_rl, Seq.empty)]]);
wenzelm@18120
   256
wenzelm@18120
   257
wenzelm@18120
   258
(*** Setting up goal-directed proof ***)
wenzelm@18120
   259
wenzelm@18120
   260
(*Generates the list of new theories when the proof state's theory changes*)
wenzelm@18120
   261
fun thy_error (thy,thy') =
wenzelm@29091
   262
  let val names = Context.display_names thy' \\ Context.display_names thy
wenzelm@18120
   263
  in  case names of
wenzelm@18120
   264
        [name] => "\nNew theory: " ^ name
wenzelm@18120
   265
      | _       => "\nNew theories: " ^ space_implode ", " names
wenzelm@18120
   266
  end;
wenzelm@18120
   267
wenzelm@18120
   268
(*Default action is to print an error message; could be suppressed for
wenzelm@18120
   269
  special applications.*)
wenzelm@18120
   270
fun result_error_default state msg : thm =
wenzelm@32145
   271
  Pretty.str "Bad final proof state:" ::
wenzelm@32187
   272
      Goal_Display.pretty_goals_without_context (!goals_limit) state @
wenzelm@18120
   273
    [Pretty.str msg, Pretty.str "Proof failed!"] |> Pretty.chunks |> Pretty.string_of |> error;
wenzelm@18120
   274
wenzelm@18120
   275
val result_error_fn = ref result_error_default;
wenzelm@18120
   276
wenzelm@18120
   277
wenzelm@18120
   278
(*Common treatment of "goal" and "prove_goal":
wenzelm@18120
   279
  Return assumptions, initial proof state, and function to make result.
wenzelm@18120
   280
  "atomic" indicates if the goal should be wrapped up in the function
wenzelm@18120
   281
  "Goal::prop=>prop" to avoid assumptions being returned separately.
wenzelm@18120
   282
*)
wenzelm@18120
   283
fun prepare_proof atomic rths chorn =
wenzelm@18120
   284
  let
wenzelm@26291
   285
      val _ = legacy_feature "Old goal command";
wenzelm@26626
   286
      val thy = Thm.theory_of_cterm chorn;
wenzelm@26626
   287
      val horn = Thm.term_of chorn;
wenzelm@18120
   288
      val _ = Term.no_dummy_patterns horn handle TERM (msg, _) => error msg;
wenzelm@18120
   289
      val (As, B) = Logic.strip_horn horn;
wenzelm@18120
   290
      val atoms = atomic andalso
wenzelm@27332
   291
            forall (fn t => not (can Logic.dest_implies t orelse Logic.is_all t)) As;
wenzelm@18120
   292
      val (As,B) = if atoms then ([],horn) else (As,B);
wenzelm@18120
   293
      val cAs = map (cterm_of thy) As;
wenzelm@26653
   294
      val prems = map (rewrite_rule rths o Thm.forall_elim_vars 0 o Thm.assume) cAs;
wenzelm@18120
   295
      val cB = cterm_of thy B;
wenzelm@18120
   296
      val st0 = let val st = Goal.init cB |> fold Thm.weaken cAs
wenzelm@18120
   297
                in  rewrite_goals_rule rths st end
wenzelm@18120
   298
      (*discharges assumptions from state in the order they appear in goal;
wenzelm@18120
   299
        checks (if requested) that resulting theorem is equivalent to goal. *)
wenzelm@18120
   300
      fun mkresult (check,state) =
wenzelm@18120
   301
        let val state = Seq.hd (flexflex_rule state)
wenzelm@18120
   302
                        handle THM _ => state   (*smash flexflex pairs*)
wenzelm@18120
   303
            val ngoals = nprems_of state
wenzelm@18120
   304
            val ath = implies_intr_list cAs state
wenzelm@18120
   305
            val th = Goal.conclude ath
wenzelm@26626
   306
            val thy' = Thm.theory_of_thm th
wenzelm@26626
   307
            val {hyps, prop, ...} = Thm.rep_thm th
wenzelm@18120
   308
            val final_th = standard th
wenzelm@18120
   309
        in  if not check then final_th
wenzelm@26665
   310
            else if not (Theory.eq_thy(thy,thy')) then !result_error_fn state
wenzelm@18120
   311
                ("Theory of proof state has changed!" ^
wenzelm@18120
   312
                 thy_error (thy,thy'))
wenzelm@18120
   313
            else if ngoals>0 then !result_error_fn state
wenzelm@18120
   314
                (string_of_int ngoals ^ " unsolved goals!")
wenzelm@18120
   315
            else if not (null hyps) then !result_error_fn state
wenzelm@18120
   316
                ("Additional hypotheses:\n" ^
wenzelm@26939
   317
                 cat_lines (map (Syntax.string_of_term_global thy) hyps))
wenzelm@18120
   318
            else if Pattern.matches thy
wenzelm@18120
   319
                                    (Envir.beta_norm (term_of chorn), Envir.beta_norm prop)
wenzelm@18120
   320
                 then final_th
wenzelm@18120
   321
            else  !result_error_fn state "proved a different theorem"
wenzelm@18120
   322
        end
wenzelm@18120
   323
  in
wenzelm@26665
   324
     if Theory.eq_thy(thy, Thm.theory_of_thm st0)
wenzelm@18120
   325
     then (prems, st0, mkresult)
wenzelm@18120
   326
     else error ("Definitions would change the proof state's theory" ^
wenzelm@18120
   327
                 thy_error (thy, Thm.theory_of_thm st0))
wenzelm@18120
   328
  end
wenzelm@18120
   329
  handle THM(s,_,_) => error("prepare_proof: exception THM was raised!\n" ^ s);
wenzelm@18120
   330
wenzelm@18120
   331
(*Prints exceptions readably to users*)
wenzelm@18120
   332
fun print_sign_exn_unit thy e =
wenzelm@18120
   333
  case e of
wenzelm@18120
   334
     THM (msg,i,thms) =>
wenzelm@18120
   335
         (writeln ("Exception THM " ^ string_of_int i ^ " raised:\n" ^ msg);
wenzelm@32091
   336
          List.app (writeln o Display.string_of_thm_global thy) thms)
wenzelm@18120
   337
   | THEORY (msg,thys) =>
wenzelm@18120
   338
         (writeln ("Exception THEORY raised:\n" ^ msg);
wenzelm@18120
   339
          List.app (writeln o Context.str_of_thy) thys)
wenzelm@18120
   340
   | TERM (msg,ts) =>
wenzelm@18120
   341
         (writeln ("Exception TERM raised:\n" ^ msg);
wenzelm@26939
   342
          List.app (writeln o Syntax.string_of_term_global thy) ts)
wenzelm@18120
   343
   | TYPE (msg,Ts,ts) =>
wenzelm@18120
   344
         (writeln ("Exception TYPE raised:\n" ^ msg);
wenzelm@26939
   345
          List.app (writeln o Syntax.string_of_typ_global thy) Ts;
wenzelm@26939
   346
          List.app (writeln o Syntax.string_of_term_global thy) ts)
wenzelm@18120
   347
   | e => raise e;
wenzelm@18120
   348
wenzelm@18120
   349
(*Prints an exception, then fails*)
wenzelm@18678
   350
fun print_sign_exn thy e = (print_sign_exn_unit thy e; raise ERROR "");
wenzelm@18120
   351
wenzelm@18120
   352
(** the prove_goal.... commands
wenzelm@18120
   353
    Prove theorem using the listed tactics; check it has the specified form.
wenzelm@18120
   354
    Augment theory with all type assignments of goal.
wenzelm@18120
   355
    Syntax is similar to "goal" command for easy keyboard use. **)
wenzelm@18120
   356
wenzelm@18120
   357
(*Version taking the goal as a cterm*)
wenzelm@18120
   358
fun prove_goalw_cterm_general check rths chorn tacsf =
wenzelm@18120
   359
  let val (prems, st0, mkresult) = prepare_proof false rths chorn
wenzelm@18120
   360
      val tac = EVERY (tacsf prems)
wenzelm@18120
   361
      fun statef() =
wenzelm@18120
   362
          (case Seq.pull (tac st0) of
wenzelm@18120
   363
               SOME(st,_) => st
wenzelm@18120
   364
             | _ => error ("prove_goal: tactic failed"))
wenzelm@25685
   365
  in  mkresult (check, cond_timeit (!Output.timing) "" statef)  end
wenzelm@26626
   366
  handle e => (print_sign_exn_unit (Thm.theory_of_cterm chorn) e;
wenzelm@18120
   367
               writeln ("The exception above was raised for\n" ^
wenzelm@18120
   368
                      Display.string_of_cterm chorn); raise e);
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@18120
   373
        setmp Output.timing false (prove_goalw_cterm_general true rths chorn)
wenzelm@18120
   374
and prove_goalw_cterm_nocheck rths chorn =
wenzelm@18120
   375
        setmp 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@18120
   518
    standard (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@26414
   609
  ML_Context.ml_store_thm (name, ObjectLogic.rulify_no_asm (result ()));
wenzelm@18120
   610
fun qed_goal_spec_mp name thy s p =
wenzelm@18120
   611
  bind_thm (name, ObjectLogic.rulify_no_asm (prove_goal thy s p));
wenzelm@18120
   612
fun qed_goalw_spec_mp name thy defs s p =
wenzelm@18120
   613
  bind_thm (name, ObjectLogic.rulify_no_asm (prove_goalw thy defs s p));
wenzelm@18120
   614
wenzelm@18120
   615
end;
wenzelm@18120
   616