src/Pure/Isar/proof.ML
author wenzelm
Sat Jan 21 23:02:14 2006 +0100 (2006-01-21)
changeset 18728 6790126ab5f6
parent 18678 dd0c569fa43d
child 18784 2d93559db27e
permissions -rw-r--r--
simplified type attribute;
     1 (*  Title:      Pure/Isar/proof.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 The Isar/VM proof language interpreter.
     6 *)
     7 
     8 signature PROOF =
     9 sig
    10   type context (*= Context.proof*)
    11   type method (*= Method.method*)
    12   type state
    13   val init: context -> state
    14   val level: state -> int
    15   val assert_bottom: bool -> state -> state
    16   val context_of: state -> context
    17   val theory_of: state -> theory
    18   val sign_of: state -> theory    (*obsolete*)
    19   val map_context: (context -> context) -> state -> state
    20   val warn_extra_tfrees: state -> state -> state
    21   val add_binds_i: (indexname * term option) list -> state -> state
    22   val put_thms: string * thm list option -> state -> state
    23   val the_facts: state -> thm list
    24   val the_fact: state -> thm
    25   val put_facts: thm list option -> state -> state
    26   val assert_forward: state -> state
    27   val assert_chain: state -> state
    28   val assert_forward_or_chain: state -> state
    29   val assert_backward: state -> state
    30   val assert_no_chain: state -> state
    31   val enter_forward: state -> state
    32   val get_goal: state -> context * (thm list * thm)
    33   val show_main_goal: bool ref
    34   val verbose: bool ref
    35   val pretty_state: int -> state -> Pretty.T list
    36   val pretty_goals: bool -> state -> Pretty.T list
    37   val refine: Method.text -> state -> state Seq.seq
    38   val refine_end: Method.text -> state -> state Seq.seq
    39   val refine_goals: (context -> thm -> unit) -> context -> thm list -> state -> state Seq.seq
    40   val match_bind: (string list * string) list -> state -> state
    41   val match_bind_i: (term list * term) list -> state -> state
    42   val let_bind: (string list * string) list -> state -> state
    43   val let_bind_i: (term list * term) list -> state -> state
    44   val fix: (string * string option) list -> state -> state
    45   val fix_i: (string * typ option) list -> state -> state
    46   val assm: ProofContext.export ->
    47     ((string * Attrib.src list) * (string * (string list * string list)) list) list ->
    48     state -> state
    49   val assm_i: ProofContext.export ->
    50     ((string * attribute list) * (term * (term list * term list)) list) list
    51     -> state -> state
    52   val assume: ((string * Attrib.src list) * (string * (string list * string list)) list) list ->
    53     state -> state
    54   val assume_i: ((string * attribute list) * (term * (term list * term list)) list) list
    55     -> state -> state
    56   val presume: ((string * Attrib.src list) * (string * (string list * string list)) list) list
    57     -> state -> state
    58   val presume_i: ((string * attribute list) * (term * (term list * term list)) list) list
    59     -> state -> state
    60   val def: ((string * Attrib.src list) * (string * (string * string list))) list ->
    61     state -> state
    62   val def_i: ((string * attribute list) * (string * (term * term list))) list ->
    63     state -> state
    64   val chain: state -> state
    65   val chain_facts: thm list -> state -> state
    66   val get_thmss: state -> (thmref * Attrib.src list) list -> thm list
    67   val simple_note_thms: string -> thm list -> state -> state
    68   val note_thmss: ((string * Attrib.src list) *
    69     (thmref * Attrib.src list) list) list -> state -> state
    70   val note_thmss_i: ((string * attribute list) *
    71     (thm list * attribute list) list) list -> state -> state
    72   val from_thmss: ((thmref * Attrib.src list) list) list -> state -> state
    73   val from_thmss_i: ((thm list * attribute list) list) list -> state -> state
    74   val with_thmss: ((thmref * Attrib.src list) list) list -> state -> state
    75   val with_thmss_i: ((thm list * attribute list) list) list -> state -> state
    76   val using: ((thmref * Attrib.src list) list) list -> state -> state
    77   val using_i: ((thm list * attribute list) list) list -> state -> state
    78   val unfolding: ((thmref * Attrib.src list) list) list -> state -> state
    79   val unfolding_i: ((thm list * attribute list) list) list -> state -> state
    80   val invoke_case: string * string option list * Attrib.src list -> state -> state
    81   val invoke_case_i: string * string option list * attribute list -> state -> state
    82   val begin_block: state -> state
    83   val next_block: state -> state
    84   val end_block: state -> state Seq.seq
    85   val proof: Method.text option -> state -> state Seq.seq
    86   val defer: int option -> state -> state Seq.seq
    87   val prefer: int -> state -> state Seq.seq
    88   val apply: Method.text -> state -> state Seq.seq
    89   val apply_end: Method.text -> state -> state Seq.seq
    90   val goal_names: string option -> string -> string list -> string
    91   val local_goal: (context -> ((string * string) * (string * thm list) list) -> unit) ->
    92     (theory -> 'a -> attribute) ->
    93     (context * 'b list -> context * (term list list * (context -> context))) ->
    94     string -> Method.text option -> (thm list list -> state -> state Seq.seq) ->
    95     ((string * 'a list) * 'b) list -> state -> state
    96   val local_qed: Method.text option * bool -> state -> state Seq.seq
    97   val global_goal: (context -> (string * string) * (string * thm list) list -> unit) ->
    98     (theory -> 'a -> attribute) ->
    99     (context * 'b list -> context * (term list list * (context -> context))) ->
   100     string -> Method.text option -> (thm list list -> theory -> theory) ->
   101     string option -> string * 'a list -> ((string * 'a list) * 'b) list -> context -> state
   102   val global_qed: Method.text option * bool -> state -> theory * context
   103   val local_terminal_proof: Method.text * Method.text option -> state -> state Seq.seq
   104   val local_default_proof: state -> state Seq.seq
   105   val local_immediate_proof: state -> state Seq.seq
   106   val local_done_proof: state -> state Seq.seq
   107   val local_skip_proof: bool -> state -> state Seq.seq
   108   val global_terminal_proof: Method.text * Method.text option -> state -> theory * context
   109   val global_default_proof: state -> theory * context
   110   val global_immediate_proof: state -> theory * context
   111   val global_done_proof: state -> theory * context
   112   val global_skip_proof: bool -> state -> theory * context
   113   val have: Method.text option -> (thm list list -> state -> state Seq.seq) ->
   114     ((string * Attrib.src list) * (string * (string list * string list)) list) list ->
   115     bool -> state -> state
   116   val have_i: Method.text option -> (thm list list -> state -> state Seq.seq) ->
   117     ((string * attribute list) * (term * (term list * term list)) list) list ->
   118     bool -> state -> state
   119   val show: Method.text option -> (thm list list -> state -> state Seq.seq) ->
   120     ((string * Attrib.src list) * (string * (string list * string list)) list) list ->
   121     bool -> state -> state
   122   val show_i: Method.text option -> (thm list list -> state -> state Seq.seq) ->
   123     ((string * attribute list) * (term * (term list * term list)) list) list ->
   124     bool -> state -> state
   125   val theorem: string -> Method.text option -> (thm list list -> theory -> theory) ->
   126     string option -> string * Attrib.src list ->
   127     ((string * Attrib.src list) * (string * (string list * string list)) list) list ->
   128     context -> state
   129   val theorem_i: string -> Method.text option -> (thm list list -> theory -> theory) ->
   130     string option -> string * attribute list ->
   131     ((string * attribute list) * (term * (term list * term list)) list) list ->
   132     context -> state
   133 end;
   134 
   135 structure Proof: PROOF =
   136 struct
   137 
   138 type context = ProofContext.context;
   139 type method = Method.method;
   140 
   141 
   142 (** proof state **)
   143 
   144 (* datatype state *)
   145 
   146 datatype mode = Forward | Chain | Backward;
   147 
   148 datatype state =
   149   State of node Stack.T
   150 and node =
   151   Node of
   152    {context: context,
   153     facts: thm list option,
   154     mode: mode,
   155     goal: goal option}
   156 and goal =
   157   Goal of
   158    {statement: string * term list list,     (*goal kind and statement*)
   159     using: thm list,                        (*goal facts*)
   160     goal: thm,                              (*subgoals ==> statement*)
   161     before_qed: Method.text option,
   162     after_qed:
   163       (thm list list -> state -> state Seq.seq) *
   164       (thm list list -> theory -> theory)};
   165 
   166 fun make_goal (statement, using, goal, before_qed, after_qed) =
   167   Goal {statement = statement, using = using, goal = goal,
   168     before_qed = before_qed, after_qed = after_qed};
   169 
   170 fun make_node (context, facts, mode, goal) =
   171   Node {context = context, facts = facts, mode = mode, goal = goal};
   172 
   173 fun map_node f (Node {context, facts, mode, goal}) =
   174   make_node (f (context, facts, mode, goal));
   175 
   176 fun init ctxt = State (Stack.init (make_node (ctxt, NONE, Forward, NONE)));
   177 
   178 fun current (State st) = Stack.top st |> (fn Node node => node);
   179 fun map_current f (State st) = State (Stack.map (map_node f) st);
   180 
   181 
   182 
   183 (** basic proof state operations **)
   184 
   185 (* block structure *)
   186 
   187 fun open_block (State st) = State (Stack.push st);
   188 
   189 fun close_block (State st) = State (Stack.pop st)
   190   handle Empty => error "Unbalanced block parentheses";
   191 
   192 fun level (State st) = Stack.level st;
   193 
   194 fun assert_bottom b state =
   195   let val b' = (level state <= 2) in
   196     if b andalso not b' then error "Not at bottom of proof!"
   197     else if not b andalso b' then error "Already at bottom of proof!"
   198     else state
   199   end;
   200 
   201 
   202 (* context *)
   203 
   204 val context_of = #context o current;
   205 val theory_of = ProofContext.theory_of o context_of;
   206 val sign_of = theory_of;
   207 
   208 fun map_context f =
   209   map_current (fn (ctxt, facts, mode, goal) => (f ctxt, facts, mode, goal));
   210 
   211 fun map_context_result f state =
   212   f (context_of state) ||> (fn ctxt => map_context (K ctxt) state);
   213 
   214 val warn_extra_tfrees = map_context o ProofContext.warn_extra_tfrees o context_of;
   215 val add_binds_i = map_context o ProofContext.add_binds_i;
   216 val put_thms = map_context o ProofContext.put_thms;
   217 val get_case = ProofContext.get_case o context_of;
   218 
   219 
   220 (* facts *)
   221 
   222 val get_facts = #facts o current;
   223 
   224 fun the_facts state =
   225   (case get_facts state of SOME facts => facts
   226   | NONE => error "No current facts available");
   227 
   228 fun the_fact state =
   229   (case the_facts state of [thm] => thm
   230   | _ => error "Single theorem expected");
   231 
   232 fun put_facts facts =
   233   map_current (fn (ctxt, _, mode, goal) => (ctxt, facts, mode, goal))
   234   #> put_thms (AutoBind.thisN, facts);
   235 
   236 fun these_factss more_facts (named_factss, state) =
   237   (named_factss, state |> put_facts (SOME (List.concat (map snd named_factss) @ more_facts)));
   238 
   239 fun export_facts inner outer =
   240   (case get_facts inner of
   241     NONE => Seq.single (put_facts NONE outer)
   242   | SOME thms =>
   243       thms
   244       |> Seq.map_list (ProofContext.exports (context_of inner) (context_of outer))
   245       |> Seq.map (fn ths => put_facts (SOME ths) outer));
   246 
   247 
   248 (* mode *)
   249 
   250 val get_mode = #mode o current;
   251 fun put_mode mode = map_current (fn (ctxt, facts, _, goal) => (ctxt, facts, mode, goal));
   252 
   253 val mode_name = (fn Forward => "state" | Chain => "chain" | Backward => "prove");
   254 
   255 fun assert_mode pred state =
   256   let val mode = get_mode state in
   257     if pred mode then state
   258     else error ("Illegal application of proof command in " ^ quote (mode_name mode) ^ " mode")
   259   end;
   260 
   261 val assert_forward = assert_mode (equal Forward);
   262 val assert_chain = assert_mode (equal Chain);
   263 val assert_forward_or_chain = assert_mode (equal Forward orf equal Chain);
   264 val assert_backward = assert_mode (equal Backward);
   265 val assert_no_chain = assert_mode (not_equal Chain);
   266 
   267 val enter_forward = put_mode Forward;
   268 val enter_chain = put_mode Chain;
   269 val enter_backward = put_mode Backward;
   270 
   271 
   272 (* current goal *)
   273 
   274 fun current_goal state =
   275   (case current state of
   276     {context, goal = SOME (Goal goal), ...} => (context, goal)
   277   | _ => error "No current goal!");
   278 
   279 fun assert_current_goal g state =
   280   let val g' = can current_goal state in
   281     if g andalso not g' then error "No goal in this block!"
   282     else if not g andalso g' then error "Goal present in this block!"
   283     else state
   284   end;
   285 
   286 fun put_goal goal = map_current (fn (ctxt, using, mode, _) => (ctxt, using, mode, goal));
   287 
   288 val before_qed = #before_qed o #2 o current_goal;
   289 
   290 
   291 (* nested goal *)
   292 
   293 fun map_goal f g (State (Node {context, facts, mode, goal = SOME goal}, nodes)) =
   294       let
   295         val Goal {statement, using, goal, before_qed, after_qed} = goal;
   296         val goal' = make_goal (g (statement, using, goal, before_qed, after_qed));
   297       in State (make_node (f context, facts, mode, SOME goal'), nodes) end
   298   | map_goal f g (State (nd, node :: nodes)) =
   299       let val State (node', nodes') = map_goal f g (State (node, nodes))
   300       in map_context f (State (nd, node' :: nodes')) end
   301   | map_goal _ _ state = state;
   302 
   303 fun using_facts using = map_goal I (fn (statement, _, goal, before_qed, after_qed) =>
   304   (statement, using, goal, before_qed, after_qed));
   305 
   306 local
   307   fun find i state =
   308     (case try current_goal state of
   309       SOME (ctxt, goal) => (ctxt, (i, goal))
   310     | NONE => find (i + 1) (close_block state handle ERROR _ => error "No goal present"));
   311 in val find_goal = find 0 end;
   312 
   313 fun get_goal state =
   314   let val (ctxt, (_, {using, goal, ...})) = find_goal state
   315   in (ctxt, (using, goal)) end;
   316 
   317 
   318 
   319 (** pretty_state **)
   320 
   321 val show_main_goal = ref false;
   322 val verbose = ProofContext.verbose;
   323 
   324 val pretty_goals_local = Display.pretty_goals_aux o ProofContext.pp;
   325 
   326 fun pretty_facts _ _ NONE = []
   327   | pretty_facts s ctxt (SOME ths) =
   328       [Pretty.big_list (s ^ "this:") (map (ProofContext.pretty_thm ctxt) ths), Pretty.str ""];
   329 
   330 fun pretty_state nr state =
   331   let
   332     val {context, facts, mode, goal = _} = current state;
   333     val ref (_, _, bg) = Display.current_goals_markers;
   334 
   335     fun levels_up 0 = ""
   336       | levels_up 1 = "1 level up"
   337       | levels_up i = string_of_int i ^ " levels up";
   338 
   339     fun subgoals 0 = ""
   340       | subgoals 1 = "1 subgoal"
   341       | subgoals n = string_of_int n ^ " subgoals";
   342 
   343     fun description strs =
   344       (case filter_out (equal "") strs of [] => ""
   345       | strs' => enclose " (" ")" (commas strs'));
   346 
   347     fun prt_goal (SOME (ctxt, (i, {statement = (kind, _), using, goal, before_qed, after_qed}))) =
   348           pretty_facts "using " ctxt
   349             (if mode <> Backward orelse null using then NONE else SOME using) @
   350           [Pretty.str ("goal" ^ description [kind, levels_up (i div 2),
   351               subgoals (Thm.nprems_of goal)] ^ ":")] @
   352           pretty_goals_local ctxt bg (true, ! show_main_goal) (! Display.goals_limit) goal
   353       | prt_goal NONE = [];
   354 
   355     val prt_ctxt =
   356       if ! verbose orelse mode = Forward then ProofContext.pretty_context context
   357       else if mode = Backward then ProofContext.pretty_ctxt context
   358       else [];
   359   in
   360     [Pretty.str ("proof (" ^ mode_name mode ^ "): step " ^ string_of_int nr ^
   361       (if ! verbose then ", depth " ^ string_of_int (level state div 2 - 1) else "")),
   362       Pretty.str ""] @
   363     (if null prt_ctxt then [] else prt_ctxt @ [Pretty.str ""]) @
   364     (if ! verbose orelse mode = Forward then
   365        pretty_facts "" context facts @ prt_goal (try find_goal state)
   366      else if mode = Chain then pretty_facts "picking " context facts
   367      else prt_goal (try find_goal state))
   368   end;
   369 
   370 fun pretty_goals main state =
   371   let val (ctxt, (_, {goal, ...})) = find_goal state
   372   in pretty_goals_local ctxt "" (false, main) (! Display.goals_limit) goal end;
   373 
   374 
   375 
   376 (** proof steps **)
   377 
   378 (* refine via method *)
   379 
   380 local
   381 
   382 fun goalN i = "goal" ^ string_of_int i;
   383 fun goals st = map goalN (1 upto Thm.nprems_of st);
   384 
   385 fun no_goal_cases st = map (rpair NONE) (goals st);
   386 
   387 fun goal_cases st =
   388   RuleCases.make_common true (Thm.theory_of_thm st, Thm.prop_of st) (map (rpair []) (goals st));
   389 
   390 fun check_theory thy state =
   391   if subthy (thy, theory_of state) then state
   392   else error ("Bad theory of method result: " ^ Context.str_of_thy thy);
   393 
   394 fun apply_method current_context meth_fun state =
   395   let
   396     val (goal_ctxt, (_, {statement, using, goal, before_qed, after_qed})) = find_goal state;
   397     val meth = meth_fun (if current_context then context_of state else goal_ctxt);
   398   in
   399     Method.apply meth using goal |> Seq.map (fn (meth_cases, goal') =>
   400       state
   401       |> check_theory (Thm.theory_of_thm goal')
   402       |> map_goal
   403           (ProofContext.add_cases false (no_goal_cases goal @ goal_cases goal') #>
   404            ProofContext.add_cases true meth_cases)
   405           (K (statement, using, goal', before_qed, after_qed)))
   406   end;
   407 
   408 fun apply_text cc text state =
   409   let
   410     val thy = theory_of state;
   411 
   412     fun eval (Method.Basic m) = apply_method cc m
   413       | eval (Method.Source src) = apply_method cc (Method.method thy src)
   414       | eval (Method.Then txts) = Seq.EVERY (map eval txts)
   415       | eval (Method.Orelse txts) = Seq.FIRST (map eval txts)
   416       | eval (Method.Try txt) = Seq.TRY (eval txt)
   417       | eval (Method.Repeat1 txt) = Seq.REPEAT1 (eval txt);
   418   in eval text state end;
   419 
   420 in
   421 
   422 val refine = apply_text true;
   423 val refine_end = apply_text false;
   424 
   425 end;
   426 
   427 
   428 (* refine via sub-proof *)
   429 
   430 local
   431 
   432 fun refine_tac rule =
   433   Tactic.norm_hhf_tac THEN' Tactic.rtac rule THEN_ALL_NEW
   434     (Tactic.norm_hhf_tac THEN' (SUBGOAL (fn (goal, i) =>
   435       if can Logic.unprotect (Logic.strip_assums_concl goal) then
   436         Tactic.etac Drule.protectI i
   437       else all_tac)));
   438 
   439 fun refine_goal print_rule inner raw_rule state =
   440   let val (outer, (_, {statement, using, goal, before_qed, after_qed})) = find_goal state in
   441     raw_rule
   442     |> ProofContext.goal_exports inner outer
   443     |> Seq.maps (fn rule =>
   444       (print_rule outer rule;
   445         goal
   446         |> FINDGOAL (refine_tac rule)
   447         |> Seq.map (fn goal' =>
   448           map_goal I (K (statement, using, goal', before_qed, after_qed)) state)))
   449   end;
   450 
   451 in
   452 
   453 fun refine_goals print_rule inner raw_rules =
   454   Seq.EVERY (map (refine_goal print_rule inner) raw_rules);
   455 
   456 end;
   457 
   458 
   459 (* conclude_goal *)
   460 
   461 fun conclude_goal state goal propss =
   462   let
   463     val ctxt = context_of state;
   464 
   465     val ngoals = Thm.nprems_of goal;
   466     val _ = conditional (ngoals > 0) (fn () =>
   467       error (Pretty.string_of (Pretty.chunks
   468         (pretty_goals_local ctxt "" (true, ! show_main_goal) (! Display.goals_limit) goal @
   469           [Pretty.str (string_of_int ngoals ^ " unsolved goal(s)!")]))));
   470 
   471     val {hyps, thy, ...} = Thm.rep_thm goal;
   472     val bad_hyps = fold (remove (op aconv)) (ProofContext.assms_of ctxt) hyps;
   473     val _ = conditional (not (null bad_hyps)) (fn () => error ("Additional hypotheses:\n" ^
   474         cat_lines (map (ProofContext.string_of_term ctxt) bad_hyps)));
   475 
   476     val th = Goal.conclude goal;
   477     val _ = conditional (not (Pattern.matches thy
   478         (Logic.mk_conjunction_list2 propss, Thm.prop_of th))) (fn () =>
   479       error ("Proved a different theorem:\n" ^ ProofContext.string_of_thm ctxt th));
   480   in Drule.conj_elim_precise (map length propss) th end;
   481 
   482 
   483 
   484 (*** structured proof commands ***)
   485 
   486 (** context elements **)
   487 
   488 (* bindings *)
   489 
   490 local
   491 
   492 fun gen_bind bind args state =
   493   state
   494   |> assert_forward
   495   |> map_context (bind args #> snd)
   496   |> put_facts NONE;
   497 
   498 in
   499 
   500 val match_bind = gen_bind (ProofContext.match_bind false);
   501 val match_bind_i = gen_bind (ProofContext.match_bind_i false);
   502 val let_bind = gen_bind (ProofContext.match_bind true);
   503 val let_bind_i = gen_bind (ProofContext.match_bind_i true);
   504 
   505 end;
   506 
   507 
   508 (* fix *)
   509 
   510 local
   511 
   512 fun gen_fix add_fixes args =
   513   assert_forward
   514   #> map_context (snd o add_fixes (map Syntax.no_syn args))
   515   #> put_facts NONE;
   516 
   517 in
   518 
   519 val fix = gen_fix ProofContext.add_fixes;
   520 val fix_i = gen_fix ProofContext.add_fixes_i;
   521 
   522 end;
   523 
   524 
   525 (* assume etc. *)
   526 
   527 local
   528 
   529 fun gen_assume asm prep_att exp args state =
   530   state
   531   |> assert_forward
   532   |> map_context_result (asm exp (Attrib.map_specs (prep_att (theory_of state)) args))
   533   |> these_factss [] |> #2;
   534 
   535 in
   536 
   537 val assm      = gen_assume ProofContext.add_assms Attrib.attribute;
   538 val assm_i    = gen_assume ProofContext.add_assms_i (K I);
   539 val assume    = assm ProofContext.assume_export;
   540 val assume_i  = assm_i ProofContext.assume_export;
   541 val presume   = assm ProofContext.presume_export;
   542 val presume_i = assm_i ProofContext.presume_export;
   543 
   544 end;
   545 
   546 
   547 (* def *)
   548 
   549 local
   550 
   551 fun gen_def fix prep_att prep_binds args state =
   552   let
   553     val _ = assert_forward state;
   554     val thy = theory_of state;
   555 
   556     val ((raw_names, raw_atts), (xs, raw_rhss)) = args |> split_list |>> split_list ||> split_list;
   557     val names = map (fn ("", x) => Thm.def_name x | (name, _) => name) (raw_names ~~ xs);
   558     val atts = map (map (prep_att thy)) raw_atts;
   559     val (rhss, state') = state |> map_context_result (prep_binds false (map swap raw_rhss));
   560     val eqs = ProofContext.mk_def (context_of state') (xs ~~ rhss);
   561   in
   562     state'
   563     |> fix (map (rpair NONE) xs)
   564     |> assm_i ProofContext.def_export ((names ~~ atts) ~~ map (fn eq => [(eq, ([], []))]) eqs)
   565   end;
   566 
   567 in
   568 
   569 val def = gen_def fix Attrib.attribute ProofContext.match_bind;
   570 val def_i = gen_def fix_i (K I) ProofContext.match_bind_i;
   571 
   572 end;
   573 
   574 
   575 
   576 (** facts **)
   577 
   578 (* chain *)
   579 
   580 val chain =
   581   assert_forward
   582   #> tap the_facts
   583   #> enter_chain;
   584 
   585 fun chain_facts facts =
   586   put_facts (SOME facts)
   587   #> chain;
   588 
   589 
   590 (* note etc. *)
   591 
   592 fun no_binding args = map (pair ("", [])) args;
   593 
   594 local
   595 
   596 fun gen_thmss note_ctxt more_facts opt_chain opt_result prep_atts args state =
   597   state
   598   |> assert_forward
   599   |> map_context_result (note_ctxt (Attrib.map_facts (prep_atts (theory_of state)) args))
   600   |> these_factss (more_facts state)
   601   ||> opt_chain
   602   |> opt_result;
   603 
   604 in
   605 
   606 val note_thmss = gen_thmss ProofContext.note_thmss (K []) I #2 Attrib.attribute;
   607 val note_thmss_i = gen_thmss ProofContext.note_thmss_i (K []) I #2 (K I);
   608 
   609 val from_thmss =
   610   gen_thmss ProofContext.note_thmss (K []) chain #2 Attrib.attribute o no_binding;
   611 val from_thmss_i = gen_thmss ProofContext.note_thmss_i (K []) chain #2 (K I) o no_binding;
   612 
   613 val with_thmss =
   614   gen_thmss ProofContext.note_thmss the_facts chain #2 Attrib.attribute o no_binding;
   615 val with_thmss_i = gen_thmss ProofContext.note_thmss_i the_facts chain #2 (K I) o no_binding;
   616 
   617 val local_results = gen_thmss ProofContext.note_thmss_i (K []) I I (K I);
   618 fun global_results kind =
   619   PureThy.note_thmss_i (Drule.kind kind) o map (apsnd Thm.simple_fact);
   620 
   621 fun get_thmss state srcs = the_facts (note_thmss [(("", []), srcs)] state);
   622 fun simple_note_thms name thms = note_thmss_i [((name, []), [(thms, [])])];
   623 
   624 end;
   625 
   626 
   627 (* using/unfolding *)
   628 
   629 local
   630 
   631 fun gen_using f g note prep_atts args state =
   632   state
   633   |> assert_backward
   634   |> map_context_result (note (Attrib.map_facts (prep_atts (theory_of state)) (no_binding args)))
   635   |-> (fn named_facts => map_goal I (fn (statement, using, goal, before_qed, after_qed) =>
   636     let val ths = List.concat (map snd named_facts)
   637     in (statement, f ths using, g ths goal, before_qed, after_qed) end));
   638 
   639 fun append_using ths using = using @ ths;
   640 fun unfold_using ths = map (Tactic.rewrite_rule ths);
   641 val unfold_goal = Tactic.rewrite_goals_rule;
   642 
   643 in
   644 
   645 val using = gen_using append_using (K I) ProofContext.note_thmss Attrib.attribute;
   646 val using_i = gen_using append_using (K I) ProofContext.note_thmss_i (K I);
   647 val unfolding = gen_using unfold_using unfold_goal ProofContext.note_thmss Attrib.attribute;
   648 val unfolding_i = gen_using unfold_using unfold_goal ProofContext.note_thmss_i (K I);
   649 
   650 end;
   651 
   652 
   653 (* case *)
   654 
   655 local
   656 
   657 fun gen_invoke_case prep_att (name, xs, raw_atts) state =
   658   let
   659     val atts = map (prep_att (theory_of state)) raw_atts;
   660     val (asms, state') =
   661       map_context_result (ProofContext.apply_case (get_case state name xs)) state;
   662     val assumptions = asms |> map (fn (a, ts) => ((a, atts), map (rpair ([], [])) ts));
   663   in
   664     state'
   665     |> map_context (ProofContext.qualified_names #> ProofContext.no_base_names)
   666     |> assume_i assumptions
   667     |> add_binds_i AutoBind.no_facts
   668     |> map_context (ProofContext.restore_naming (context_of state))
   669     |> `the_facts |-> simple_note_thms name
   670   end;
   671 
   672 in
   673 
   674 val invoke_case = gen_invoke_case Attrib.attribute;
   675 val invoke_case_i = gen_invoke_case (K I);
   676 
   677 end;
   678 
   679 
   680 
   681 (** proof structure **)
   682 
   683 (* blocks *)
   684 
   685 val begin_block =
   686   assert_forward
   687   #> open_block
   688   #> put_goal NONE
   689   #> open_block;
   690 
   691 val next_block =
   692   assert_forward
   693   #> close_block
   694   #> open_block
   695   #> put_goal NONE
   696   #> put_facts NONE;
   697 
   698 fun end_block state =
   699   state
   700   |> assert_forward
   701   |> close_block
   702   |> assert_current_goal false
   703   |> close_block
   704   |> export_facts state;
   705 
   706 
   707 (* sub-proofs *)
   708 
   709 fun proof opt_text =
   710   assert_backward
   711   #> refine (the_default Method.default_text opt_text)
   712   #> Seq.map (using_facts [] #> enter_forward);
   713 
   714 fun end_proof bot txt =
   715   assert_forward
   716   #> assert_bottom bot
   717   #> close_block
   718   #> assert_current_goal true
   719   #> using_facts []
   720   #> `before_qed #-> (refine o the_default Method.succeed_text)
   721   #> Seq.maps (refine (Method.finish_text txt));
   722 
   723 
   724 (* unstructured refinement *)
   725 
   726 fun defer i = assert_no_chain #> refine (Method.Basic (K (Method.defer i)));
   727 fun prefer i = assert_no_chain #> refine (Method.Basic (K (Method.prefer i)));
   728 
   729 fun apply text = assert_backward #> refine text #> Seq.map (using_facts []);
   730 fun apply_end text = assert_forward #> refine_end text;
   731 
   732 
   733 
   734 (** goals **)
   735 
   736 (* goal names *)
   737 
   738 fun prep_names prep_att stmt =
   739   let
   740     val (names_attss, propp) = split_list (Attrib.map_specs prep_att stmt);
   741     val (names, attss) = split_list names_attss;
   742   in ((names, attss), propp) end;
   743 
   744 fun goal_names target name names =
   745   (case target of NONE => "" | SOME "" => "" | SOME loc => " (in " ^ loc ^ ")") ^
   746   (if name = "" then "" else " " ^ name) ^
   747   (case filter_out (equal "") names of [] => ""
   748   | nms => " " ^ enclose "(" ")" (space_implode " and " (Library.take (7, nms) @
   749       (if length nms > 7 then ["..."] else []))));
   750 
   751 
   752 (* generic goals *)
   753 
   754 fun check_tvars props state =
   755   (case fold Term.add_tvars props [] of [] => ()
   756   | tvars => error ("Goal statement contains illegal schematic type variable(s): " ^
   757       commas (map (ProofContext.string_of_typ (context_of state) o TVar) tvars)));
   758 
   759 fun check_vars props state =
   760   (case fold Term.add_vars props [] of [] => ()
   761   | vars => warning ("Goal statement contains unbound schematic variable(s): " ^
   762       commas (map (ProofContext.string_of_term (context_of state) o Var) vars)));
   763 
   764 fun generic_goal prepp kind before_qed after_qed raw_propp state =
   765   let
   766     val thy = theory_of state;
   767     val chaining = can assert_chain state;
   768 
   769     val ((propss, after_ctxt), goal_state) =
   770       state
   771       |> assert_forward_or_chain
   772       |> enter_forward
   773       |> open_block
   774       |> map_context_result (fn ctxt => swap (prepp (ctxt, raw_propp)));
   775     val props = List.concat propss;
   776 
   777     val goal = Goal.init (Thm.cterm_of thy (Logic.mk_conjunction_list2 propss));
   778     val after_qed' = after_qed |>> (fn after_local =>
   779       fn results => map_context after_ctxt #> after_local results);
   780   in
   781     goal_state
   782     |> tap (check_tvars props)
   783     |> tap (check_vars props)
   784     |> map_context (ProofContext.set_body true)
   785     |> put_goal (SOME (make_goal ((kind, propss), [], goal, before_qed, after_qed')))
   786     |> map_context (ProofContext.add_cases false (AutoBind.cases thy props))
   787     |> map_context (ProofContext.auto_bind_goal props)
   788     |> K chaining ? (`the_facts #-> using_facts)
   789     |> put_facts NONE
   790     |> open_block
   791     |> put_goal NONE
   792     |> enter_backward
   793     |> K (null props) ? (refine (Method.Basic Method.assumption) #> Seq.hd)
   794   end;
   795 
   796 fun generic_qed state =
   797   let
   798     val (goal_ctxt, {statement = (_, stmt), using = _, goal, before_qed = _, after_qed}) =
   799       current_goal state;
   800     val outer_state = state |> close_block;
   801     val outer_ctxt = context_of outer_state;
   802 
   803     val props =
   804       List.concat stmt
   805       |> ProofContext.generalize goal_ctxt outer_ctxt;
   806     val results =
   807       stmt
   808       |> conclude_goal state goal
   809       |> (Seq.map_list o Seq.map_list) (ProofContext.exports goal_ctxt outer_ctxt);
   810   in
   811     outer_state
   812     |> map_context (ProofContext.auto_bind_facts props)
   813     |> pair (after_qed, results)
   814   end;
   815 
   816 
   817 (* local goals *)
   818 
   819 fun local_goal print_results prep_att prepp kind before_qed after_qed stmt state =
   820   let
   821     val ((names, attss), propp) = prep_names (prep_att (theory_of state)) stmt;
   822 
   823     fun after_qed' results =
   824       local_results ((names ~~ attss) ~~ map Thm.simple_fact results)
   825       #-> (fn res => tap (fn st => print_results (context_of st) ((kind, ""), res) : unit))
   826       #> after_qed results;
   827   in
   828     state
   829     |> generic_goal prepp (kind ^ goal_names NONE "" names) before_qed (after_qed', K I) propp
   830     |> warn_extra_tfrees state
   831   end;
   832 
   833 fun local_qed txt =
   834   end_proof false txt
   835   #> Seq.map generic_qed
   836   #> Seq.maps (uncurry (fn ((after_qed, _), results) => Seq.lifts after_qed results));
   837 
   838 
   839 (* global goals *)
   840 
   841 fun global_goal print_results prep_att prepp
   842     kind before_qed after_qed target (name, raw_atts) stmt ctxt =
   843   let
   844     val thy = ProofContext.theory_of ctxt;
   845     val thy_ctxt = ProofContext.init thy;
   846 
   847     val atts = map (prep_att thy) raw_atts;
   848     val ((names, attss), propp) = prep_names (prep_att thy) stmt;
   849 
   850     fun store_results prfx res =
   851       K (prfx <> "") ? (Sign.add_path prfx #> Sign.no_base_names)
   852       #> global_results kind ((names ~~ attss) ~~ res)
   853       #-> (fn res' =>
   854         (print_results thy_ctxt ((kind, name), res') : unit;
   855           #2 o global_results kind [((name, atts), List.concat (map #2 res'))]))
   856       #> Sign.restore_naming thy;
   857 
   858     fun after_qed' results =
   859       (case target of NONE => I
   860       | SOME prfx => store_results (NameSpace.base prfx)
   861           (map (map (ProofContext.export ctxt thy_ctxt
   862             #> Drule.strip_shyps_warning)) results))
   863       #> after_qed results;
   864   in
   865     init ctxt
   866     |> generic_goal (prepp #> ProofContext.auto_fixes) (kind ^ goal_names target name names)
   867       before_qed (K Seq.single, after_qed') propp
   868   end;
   869 
   870 fun check_result msg sq =
   871   (case Seq.pull sq of
   872     NONE => error msg
   873   | SOME res => Seq.cons res);
   874 
   875 fun global_qeds txt =
   876   end_proof true txt
   877   #> Seq.map generic_qed
   878   #> Seq.maps (fn (((_, after_qed), results), state) =>
   879     Seq.lift after_qed results (theory_of state)
   880     |> Seq.map (rpair (context_of state)))
   881   |> Seq.DETERM;   (*backtracking may destroy theory!*)
   882 
   883 fun global_qed txt =
   884   global_qeds txt
   885   #> check_result "Failed to finish proof"
   886   #> Seq.hd;
   887 
   888 
   889 (* concluding steps *)
   890 
   891 fun local_terminal_proof (text, opt_text) =
   892   proof (SOME text) #> Seq.maps (local_qed (opt_text, true));
   893 
   894 val local_default_proof = local_terminal_proof (Method.default_text, NONE);
   895 val local_immediate_proof = local_terminal_proof (Method.this_text, NONE);
   896 val local_done_proof = proof (SOME Method.done_text) #> Seq.maps (local_qed (NONE, false));
   897 fun local_skip_proof int = local_terminal_proof (Method.sorry_text int, NONE);
   898 
   899 fun global_term_proof immed (text, opt_text) =
   900   proof (SOME text)
   901   #> check_result "Terminal proof method failed"
   902   #> Seq.maps (global_qeds (opt_text, immed))
   903   #> check_result "Failed to finish proof (after successful terminal method)"
   904   #> Seq.hd;
   905 
   906 val global_terminal_proof = global_term_proof true;
   907 val global_default_proof = global_terminal_proof (Method.default_text, NONE);
   908 val global_immediate_proof = global_terminal_proof (Method.this_text, NONE);
   909 val global_done_proof = global_term_proof false (Method.done_text, NONE);
   910 fun global_skip_proof int = global_terminal_proof (Method.sorry_text int, NONE);
   911 
   912 
   913 (* common goal statements *)
   914 
   915 local
   916 
   917 fun gen_have prep_att prepp before_qed after_qed stmt int =
   918   local_goal (ProofDisplay.print_results int) prep_att prepp "have" before_qed after_qed stmt;
   919 
   920 fun gen_show prep_att prepp before_qed after_qed stmt int state =
   921   let
   922     val testing = ref false;
   923     val rule = ref (NONE: thm option);
   924     fun fail_msg ctxt =
   925       "Local statement will fail to solve any pending goal" ::
   926       (case ! rule of NONE => [] | SOME th => [ProofDisplay.string_of_rule ctxt "Failed" th])
   927       |> cat_lines;
   928 
   929     fun print_results ctxt res =
   930       if ! testing then () else ProofDisplay.print_results int ctxt res;
   931     fun print_rule ctxt th =
   932       if ! testing then rule := SOME th
   933       else if int then priority (ProofDisplay.string_of_rule ctxt "Successful" th)
   934       else ();
   935     val test_proof =
   936       (Seq.pull oo local_skip_proof) true
   937       |> setmp testing true
   938       |> setmp proofs 0
   939       |> capture;
   940 
   941     fun after_qed' results =
   942       refine_goals print_rule (context_of state) (List.concat results)
   943       #> Seq.maps (after_qed results);
   944   in
   945     state
   946     |> local_goal print_results prep_att prepp "show" before_qed after_qed' stmt
   947     |> K int ? (fn goal_state =>
   948       (case test_proof goal_state of
   949         Result (SOME _) => goal_state
   950       | Result NONE => error (fail_msg (context_of goal_state))
   951       | Exn Interrupt => raise Interrupt
   952       | Exn exn => raise EXCEPTION (exn, fail_msg (context_of goal_state))))
   953   end;
   954 
   955 fun gen_theorem prep_att prepp kind before_qed after_qed target a =
   956   global_goal ProofDisplay.present_results prep_att prepp kind before_qed after_qed target a;
   957 
   958 in
   959 
   960 val have = gen_have Attrib.attribute ProofContext.bind_propp;
   961 val have_i = gen_have (K I) ProofContext.bind_propp_i;
   962 val show = gen_show Attrib.attribute ProofContext.bind_propp;
   963 val show_i = gen_show (K I) ProofContext.bind_propp_i;
   964 val theorem = gen_theorem Attrib.attribute ProofContext.bind_propp_schematic;
   965 val theorem_i = gen_theorem (K I) ProofContext.bind_propp_schematic_i;
   966 
   967 end;
   968 
   969 end;