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