src/Pure/Isar/proof.ML
author wenzelm
Sun, 29 Jan 2006 19:23:50 +0100
changeset 18843 23db974a0575
parent 18826 2a805b3dd9f0
child 18878 08b06ec0ef74
permissions -rw-r--r--
'unfolding': LocalDefs.unfold;
     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 -> context * theory
   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 -> context * theory
   109   val global_default_proof: state -> context * theory
   110   val global_immediate_proof: state -> context * theory
   111   val global_done_proof: state -> context * theory
   112   val global_skip_proof: bool -> state -> context * theory
   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 = LocalDefs.mk_def (context_of state') (xs ~~ rhss);
   561   in
   562     state'
   563     |> fix (map (rpair NONE) xs)
   564     |> assm_i LocalDefs.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 =
   618   gen_thmss ProofContext.note_thmss_i (K []) I I (K I) o map (apsnd Thm.simple_fact);
   619 fun global_results kind = PureThy.note_thmss_i 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, state') =>
   636     state' |> map_goal I (fn (statement, using, goal, before_qed, after_qed) =>
   637       let
   638         val ctxt = context_of state';
   639         val ths = List.concat (map snd named_facts);
   640       in (statement, f ctxt ths using, g ctxt ths goal, before_qed, after_qed) end));
   641 
   642 fun append_using _ ths using = using @ ths;
   643 fun unfold_using ctxt ths = map (LocalDefs.unfold ctxt true ths);
   644 fun unfold_goals ctxt ths = LocalDefs.unfold_goals ctxt true ths;
   645 
   646 in
   647 
   648 val using = gen_using append_using (K (K I)) ProofContext.note_thmss Attrib.attribute;
   649 val using_i = gen_using append_using (K (K I)) ProofContext.note_thmss_i (K I);
   650 val unfolding = gen_using unfold_using unfold_goals ProofContext.note_thmss Attrib.attribute;
   651 val unfolding_i = gen_using unfold_using unfold_goals ProofContext.note_thmss_i (K I);
   652 
   653 end;
   654 
   655 
   656 (* case *)
   657 
   658 local
   659 
   660 fun gen_invoke_case prep_att (name, xs, raw_atts) state =
   661   let
   662     val atts = map (prep_att (theory_of state)) raw_atts;
   663     val (asms, state') =
   664       map_context_result (ProofContext.apply_case (get_case state name xs)) state;
   665     val assumptions = asms |> map (fn (a, ts) => ((a, atts), map (rpair ([], [])) ts));
   666   in
   667     state'
   668     |> map_context (ProofContext.qualified_names #> ProofContext.no_base_names)
   669     |> assume_i assumptions
   670     |> add_binds_i AutoBind.no_facts
   671     |> map_context (ProofContext.restore_naming (context_of state))
   672     |> `the_facts |-> simple_note_thms name
   673   end;
   674 
   675 in
   676 
   677 val invoke_case = gen_invoke_case Attrib.attribute;
   678 val invoke_case_i = gen_invoke_case (K I);
   679 
   680 end;
   681 
   682 
   683 
   684 (** proof structure **)
   685 
   686 (* blocks *)
   687 
   688 val begin_block =
   689   assert_forward
   690   #> open_block
   691   #> put_goal NONE
   692   #> open_block;
   693 
   694 val next_block =
   695   assert_forward
   696   #> close_block
   697   #> open_block
   698   #> put_goal NONE
   699   #> put_facts NONE;
   700 
   701 fun end_block state =
   702   state
   703   |> assert_forward
   704   |> close_block
   705   |> assert_current_goal false
   706   |> close_block
   707   |> export_facts state;
   708 
   709 
   710 (* sub-proofs *)
   711 
   712 fun proof opt_text =
   713   assert_backward
   714   #> refine (the_default Method.default_text opt_text)
   715   #> Seq.map (using_facts [] #> enter_forward);
   716 
   717 fun end_proof bot txt =
   718   assert_forward
   719   #> assert_bottom bot
   720   #> close_block
   721   #> assert_current_goal true
   722   #> using_facts []
   723   #> `before_qed #-> (refine o the_default Method.succeed_text)
   724   #> Seq.maps (refine (Method.finish_text txt));
   725 
   726 
   727 (* unstructured refinement *)
   728 
   729 fun defer i = assert_no_chain #> refine (Method.Basic (K (Method.defer i)));
   730 fun prefer i = assert_no_chain #> refine (Method.Basic (K (Method.prefer i)));
   731 
   732 fun apply text = assert_backward #> refine text #> Seq.map (using_facts []);
   733 fun apply_end text = assert_forward #> refine_end text;
   734 
   735 
   736 
   737 (** goals **)
   738 
   739 (* goal names *)
   740 
   741 fun prep_names prep_att stmt =
   742   let
   743     val (names_attss, propp) = split_list (Attrib.map_specs prep_att stmt);
   744     val (names, attss) = split_list names_attss;
   745   in ((names, attss), propp) end;
   746 
   747 fun goal_names target name names =
   748   (case target of NONE => "" | SOME "" => "" | SOME loc => " (in " ^ loc ^ ")") ^
   749   (if name = "" then "" else " " ^ name) ^
   750   (case filter_out (equal "") names of [] => ""
   751   | nms => " " ^ enclose "(" ")" (space_implode " and " (Library.take (7, nms) @
   752       (if length nms > 7 then ["..."] else []))));
   753 
   754 
   755 (* generic goals *)
   756 
   757 fun check_tvars props state =
   758   (case fold Term.add_tvars props [] of [] => ()
   759   | tvars => error ("Goal statement contains illegal schematic type variable(s): " ^
   760       commas (map (ProofContext.string_of_typ (context_of state) o TVar) tvars)));
   761 
   762 fun check_vars props state =
   763   (case fold Term.add_vars props [] of [] => ()
   764   | vars => warning ("Goal statement contains unbound schematic variable(s): " ^
   765       commas (map (ProofContext.string_of_term (context_of state) o Var) vars)));
   766 
   767 fun generic_goal prepp kind before_qed after_qed raw_propp state =
   768   let
   769     val thy = theory_of state;
   770     val chaining = can assert_chain state;
   771 
   772     val ((propss, after_ctxt), goal_state) =
   773       state
   774       |> assert_forward_or_chain
   775       |> enter_forward
   776       |> open_block
   777       |> map_context_result (fn ctxt => swap (prepp (ctxt, raw_propp)));
   778     val props = List.concat propss;
   779 
   780     val goal = Goal.init (Thm.cterm_of thy (Logic.mk_conjunction_list2 propss));
   781     val after_qed' = after_qed |>> (fn after_local =>
   782       fn results => map_context after_ctxt #> after_local results);
   783   in
   784     goal_state
   785     |> tap (check_tvars props)
   786     |> tap (check_vars props)
   787     |> map_context (ProofContext.set_body true)
   788     |> put_goal (SOME (make_goal ((kind, propss), [], goal, before_qed, after_qed')))
   789     |> map_context (ProofContext.add_cases false (AutoBind.cases thy props))
   790     |> map_context (ProofContext.auto_bind_goal props)
   791     |> K chaining ? (`the_facts #-> using_facts)
   792     |> put_facts NONE
   793     |> open_block
   794     |> put_goal NONE
   795     |> enter_backward
   796     |> K (null props) ? (refine (Method.Basic Method.assumption) #> Seq.hd)
   797   end;
   798 
   799 fun generic_qed state =
   800   let
   801     val (goal_ctxt, {statement = (_, stmt), using = _, goal, before_qed = _, after_qed}) =
   802       current_goal state;
   803     val outer_state = state |> close_block;
   804     val outer_ctxt = context_of outer_state;
   805 
   806     val props =
   807       List.concat stmt
   808       |> ProofContext.generalize goal_ctxt outer_ctxt;
   809     val results =
   810       stmt
   811       |> conclude_goal state goal
   812       |> (Seq.map_list o Seq.map_list) (ProofContext.exports goal_ctxt outer_ctxt);
   813   in
   814     outer_state
   815     |> map_context (ProofContext.auto_bind_facts props)
   816     |> pair (after_qed, results)
   817   end;
   818 
   819 
   820 (* local goals *)
   821 
   822 fun local_goal print_results prep_att prepp kind before_qed after_qed stmt state =
   823   let
   824     val ((names, attss), propp) = prep_names (prep_att (theory_of state)) stmt;
   825 
   826     fun after_qed' results =
   827       local_results ((names ~~ attss) ~~ results)
   828       #-> (fn res => tap (fn st => print_results (context_of st) ((kind, ""), res) : unit))
   829       #> after_qed results;
   830   in
   831     state
   832     |> generic_goal prepp (kind ^ goal_names NONE "" names) before_qed (after_qed', K I) propp
   833     |> warn_extra_tfrees state
   834   end;
   835 
   836 fun local_qed txt =
   837   end_proof false txt
   838   #> Seq.map generic_qed
   839   #> Seq.maps (uncurry (fn ((after_qed, _), results) => Seq.lifts after_qed results));
   840 
   841 
   842 (* global goals *)
   843 
   844 fun global_goal print_results prep_att prepp
   845     kind before_qed after_qed target (name, raw_atts) stmt ctxt =
   846   let
   847     val thy = ProofContext.theory_of ctxt;
   848     val thy_ctxt = ProofContext.init thy;
   849 
   850     val atts = map (prep_att thy) raw_atts;
   851     val ((names, attss), propp) = prep_names (prep_att thy) stmt;
   852 
   853     fun store_results prfx res =
   854       K (prfx <> "") ? (Sign.add_path prfx #> Sign.no_base_names)
   855       #> global_results kind ((names ~~ attss) ~~ res)
   856       #-> (fn res' =>
   857         (print_results thy_ctxt ((kind, name), res') : unit;
   858           #2 o global_results kind [((name, atts), List.concat (map #2 res'))]))
   859       #> Sign.restore_naming thy;
   860 
   861     fun after_qed' results =
   862       (case target of NONE => I
   863       | SOME prfx => store_results (NameSpace.base prfx)
   864           (map (map (ProofContext.export_standard ctxt thy_ctxt
   865             #> Drule.strip_shyps_warning)) results))
   866       #> after_qed results;
   867   in
   868     init ctxt
   869     |> generic_goal (prepp #> ProofContext.auto_fixes) (kind ^ goal_names target name names)
   870       before_qed (K Seq.single, after_qed') propp
   871   end;
   872 
   873 fun check_result msg sq =
   874   (case Seq.pull sq of
   875     NONE => error msg
   876   | SOME res => Seq.cons res);
   877 
   878 fun global_qeds txt =
   879   end_proof true txt
   880   #> Seq.map generic_qed
   881   #> Seq.maps (fn (((_, after_qed), results), state) =>
   882     Seq.lift after_qed results (theory_of state)
   883     |> Seq.map (pair (context_of state)))
   884   |> Seq.DETERM;   (*backtracking may destroy theory!*)
   885 
   886 fun global_qed txt =
   887   global_qeds txt
   888   #> check_result "Failed to finish proof"
   889   #> Seq.hd;
   890 
   891 
   892 (* concluding steps *)
   893 
   894 fun local_terminal_proof (text, opt_text) =
   895   proof (SOME text) #> Seq.maps (local_qed (opt_text, true));
   896 
   897 val local_default_proof = local_terminal_proof (Method.default_text, NONE);
   898 val local_immediate_proof = local_terminal_proof (Method.this_text, NONE);
   899 val local_done_proof = proof (SOME Method.done_text) #> Seq.maps (local_qed (NONE, false));
   900 fun local_skip_proof int = local_terminal_proof (Method.sorry_text int, NONE);
   901 
   902 fun global_term_proof immed (text, opt_text) =
   903   proof (SOME text)
   904   #> check_result "Terminal proof method failed"
   905   #> Seq.maps (global_qeds (opt_text, immed))
   906   #> check_result "Failed to finish proof (after successful terminal method)"
   907   #> Seq.hd;
   908 
   909 val global_terminal_proof = global_term_proof true;
   910 val global_default_proof = global_terminal_proof (Method.default_text, NONE);
   911 val global_immediate_proof = global_terminal_proof (Method.this_text, NONE);
   912 val global_done_proof = global_term_proof false (Method.done_text, NONE);
   913 fun global_skip_proof int = global_terminal_proof (Method.sorry_text int, NONE);
   914 
   915 
   916 (* common goal statements *)
   917 
   918 local
   919 
   920 fun gen_have prep_att prepp before_qed after_qed stmt int =
   921   local_goal (ProofDisplay.print_results int) prep_att prepp "have" before_qed after_qed stmt;
   922 
   923 fun gen_show prep_att prepp before_qed after_qed stmt int state =
   924   let
   925     val testing = ref false;
   926     val rule = ref (NONE: thm option);
   927     fun fail_msg ctxt =
   928       "Local statement will fail to solve any pending goal" ::
   929       (case ! rule of NONE => [] | SOME th => [ProofDisplay.string_of_rule ctxt "Failed" th])
   930       |> cat_lines;
   931 
   932     fun print_results ctxt res =
   933       if ! testing then () else ProofDisplay.print_results int ctxt res;
   934     fun print_rule ctxt th =
   935       if ! testing then rule := SOME th
   936       else if int then priority (ProofDisplay.string_of_rule ctxt "Successful" th)
   937       else ();
   938     val test_proof =
   939       (Seq.pull oo local_skip_proof) true
   940       |> setmp testing true
   941       |> setmp proofs 0
   942       |> capture;
   943 
   944     fun after_qed' results =
   945       refine_goals print_rule (context_of state) (List.concat results)
   946       #> Seq.maps (after_qed results);
   947   in
   948     state
   949     |> local_goal print_results prep_att prepp "show" before_qed after_qed' stmt
   950     |> K int ? (fn goal_state =>
   951       (case test_proof goal_state of
   952         Result (SOME _) => goal_state
   953       | Result NONE => error (fail_msg (context_of goal_state))
   954       | Exn Interrupt => raise Interrupt
   955       | Exn exn => raise EXCEPTION (exn, fail_msg (context_of goal_state))))
   956   end;
   957 
   958 fun gen_theorem prep_att prepp kind before_qed after_qed target a =
   959   global_goal ProofDisplay.present_results prep_att prepp kind before_qed after_qed target a;
   960 
   961 in
   962 
   963 val have = gen_have Attrib.attribute ProofContext.bind_propp;
   964 val have_i = gen_have (K I) ProofContext.bind_propp_i;
   965 val show = gen_show Attrib.attribute ProofContext.bind_propp;
   966 val show_i = gen_show (K I) ProofContext.bind_propp_i;
   967 val theorem = gen_theorem Attrib.attribute ProofContext.bind_propp_schematic;
   968 val theorem_i = gen_theorem (K I) ProofContext.bind_propp_schematic_i;
   969 
   970 end;
   971 
   972 end;