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