src/Pure/Isar/proof.ML
author wenzelm
Wed Dec 19 00:28:27 2001 +0100 (2001-12-19)
changeset 12549 65f03a3f7998
parent 12534 5729b8cac4e1
child 12698 b87b41ade3b2
permissions -rw-r--r--
tuned interface of ProofContext.generalize;
tuned;
     1 (*  Title:      Pure/Isar/proof.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4     License:    GPL (GNU GENERAL PUBLIC LICENSE)
     5 
     6 Proof states and methods.
     7 *)
     8 
     9 signature BASIC_PROOF =
    10 sig
    11   val FINDGOAL: (int -> thm -> 'a Seq.seq) -> thm -> 'a Seq.seq
    12   val HEADGOAL: (int -> thm -> 'a Seq.seq) -> thm -> 'a Seq.seq
    13 end;
    14 
    15 signature PROOF =
    16 sig
    17   include BASIC_PROOF
    18   type context
    19   type state
    20   exception STATE of string * state
    21   val check_result: string -> state -> 'a Seq.seq -> 'a Seq.seq
    22   val init_state: theory -> state
    23   val context_of: state -> context
    24   val theory_of: state -> theory
    25   val sign_of: state -> Sign.sg
    26   val warn_extra_tfrees: state -> state -> state
    27   val reset_thms: string -> state -> state
    28   val the_facts: state -> thm list
    29   val the_fact: state -> thm
    30   val get_goal: state -> context * (thm list * thm)
    31   val goal_facts: (state -> thm list) -> state -> state
    32   val use_facts: state -> state
    33   val reset_facts: state -> state
    34   val is_chain: state -> bool
    35   val assert_forward: state -> state
    36   val assert_forward_or_chain: state -> state
    37   val assert_backward: state -> state
    38   val assert_no_chain: state -> state
    39   val enter_forward: state -> state
    40   val verbose: bool ref
    41   val pretty_state: int -> state -> Pretty.T list
    42   val pretty_goals: bool -> state -> Pretty.T list
    43   val level: state -> int
    44   type method
    45   val method: (thm list -> tactic) -> method
    46   val method_cases: (thm list -> thm -> (thm * (string * RuleCases.T) list) Seq.seq) -> method
    47   val refine: (context -> method) -> state -> state Seq.seq
    48   val refine_end: (context -> method) -> state -> state Seq.seq
    49   val match_bind: (string list * string) list -> state -> state
    50   val match_bind_i: (term list * term) list -> state -> state
    51   val let_bind: (string list * string) list -> state -> state
    52   val let_bind_i: (term list * term) list -> state -> state
    53   val simple_have_thms: string -> thm list -> state -> state
    54   val have_thmss: ((string * context attribute list) *
    55     (thm list * context attribute list) list) list -> state -> state
    56   val with_thmss: ((string * context attribute list) *
    57     (thm list * context attribute list) list) list -> state -> state
    58   val fix: (string list * string option) list -> state -> state
    59   val fix_i: (string list * typ option) list -> state -> state
    60   val assm: ProofContext.exporter
    61     -> ((string * context attribute list) * (string * (string list * string list)) list) list
    62     -> state -> state
    63   val assm_i: ProofContext.exporter
    64     -> ((string * context attribute list) * (term * (term list * term list)) list) list
    65     -> state -> state
    66   val assume:
    67     ((string * context attribute list) * (string * (string list * string list)) list) list
    68     -> state -> state
    69   val assume_i: ((string * context attribute list) * (term * (term list * term list)) list) list
    70     -> state -> state
    71   val presume:
    72     ((string * context attribute list) * (string * (string list * string list)) list) list
    73     -> state -> state
    74   val presume_i: ((string * context attribute list) * (term * (term list * term list)) list) list
    75     -> state -> state
    76   val def: string -> context attribute list -> string *  (string * string list) -> state -> state
    77   val def_i: string -> context attribute list -> string * (term * term list) -> state -> state
    78   val invoke_case: string * string option list * context attribute list -> state -> state
    79   val multi_theorem: string -> bstring * theory attribute list
    80     -> (xstring * context attribute list) option -> context attribute Locale.element list
    81     -> ((bstring * theory attribute list) * (string * (string list * string list)) list) list
    82     -> theory -> state
    83   val multi_theorem_i: string -> bstring * theory attribute list
    84     -> (string * context attribute list) option -> context attribute Locale.element_i list
    85     -> ((bstring * theory attribute list) * (term * (term list * term list)) list) list
    86     -> theory -> state
    87   val theorem: string
    88     -> (xstring * context attribute list) option -> context attribute Locale.element list
    89     -> bstring -> theory attribute list -> string * (string list * string list) -> theory -> state
    90   val theorem_i: string
    91     -> (string * context attribute list) option -> context attribute Locale.element_i list
    92     -> bstring -> theory attribute list -> term * (term list * term list) -> theory -> state
    93   val chain: state -> state
    94   val from_facts: thm list -> state -> state
    95   val show: (bool -> state -> state) -> (state -> state Seq.seq)
    96     -> ((string * context attribute list) * (string * (string list * string list)) list) list
    97     -> bool -> state -> state
    98   val show_i: (bool -> state -> state) -> (state -> state Seq.seq)
    99     -> ((string * context attribute list) * (term * (term list * term list)) list) list
   100     -> bool -> state -> state
   101   val have: (state -> state Seq.seq)
   102     -> ((string * context attribute list) * (string * (string list * string list)) list) list
   103     -> state -> state
   104   val have_i: (state -> state Seq.seq)
   105     -> ((string * context attribute list) * (term * (term list * term list)) list) list
   106     -> state -> state
   107   val at_bottom: state -> bool
   108   val local_qed: (state -> state Seq.seq)
   109     -> (context -> string * (string * thm list) list -> unit) * (context -> thm -> unit)
   110     -> state -> state Seq.seq
   111   val global_qed: (state -> state Seq.seq) -> state
   112     -> (theory * ((string * string) * (string * thm list) list)) Seq.seq
   113   val begin_block: state -> state
   114   val end_block: state -> state Seq.seq
   115   val next_block: state -> state
   116 end;
   117 
   118 signature PRIVATE_PROOF =
   119 sig
   120   include PROOF
   121   val put_data: Object.kind -> ('a -> Object.T) -> 'a -> state -> state
   122 end;
   123 
   124 structure Proof: PRIVATE_PROOF =
   125 struct
   126 
   127 
   128 (** proof state **)
   129 
   130 type context = ProofContext.context;
   131 
   132 
   133 (* type goal *)
   134 
   135 datatype kind =
   136   Theorem of string *                           (*theorem kind*)
   137     (bstring * theory attribute list) *         (*common result binding*)
   138     (string * context attribute list) option *  (*target locale*)
   139     theory attribute list list |                (*attributes of individual result binding*)
   140   Show of context attribute list list |         (*intermediate result, solving subgoal*)
   141   Have of context attribute list list;          (*intermediate result*)
   142 
   143 fun common_name "" = "" | common_name a = " " ^ a;
   144 
   145 fun kind_name _ (Theorem (s, (a, _), None, _)) = s ^ common_name a
   146   | kind_name sg (Theorem (s, (a, _), Some (name, _), _)) =
   147       s ^ common_name a ^ " (in " ^ Locale.cond_extern sg name ^ ")"
   148   | kind_name _ (Show _) = "show"
   149   | kind_name _ (Have _) = "have";
   150 
   151 type goal =
   152  (kind *             (*result kind*)
   153   string list *      (*result names*)
   154   term list list) *  (*result statements*)
   155  (thm list *         (*use facts*)
   156   thm);              (*goal: subgoals ==> statement*)
   157 
   158 
   159 (* type mode *)
   160 
   161 datatype mode = Forward | ForwardChain | Backward;
   162 val mode_name = (fn Forward => "state" | ForwardChain => "chain" | Backward => "prove");
   163 
   164 
   165 (* datatype state *)
   166 
   167 datatype node =
   168   Node of
   169    {context: context,
   170     facts: thm list option,
   171     mode: mode,
   172     goal: (goal * (state -> state Seq.seq)) option}
   173 and state =
   174   State of
   175     node *              (*current*)
   176     node list;          (*parents wrt. block structure*)
   177 
   178 fun make_node (context, facts, mode, goal) =
   179   Node {context = context, facts = facts, mode = mode, goal = goal};
   180 
   181 
   182 exception STATE of string * state;
   183 
   184 fun err_malformed name state =
   185   raise STATE (name ^ ": internal error -- malformed proof state", state);
   186 
   187 fun check_result msg state sq =
   188   (case Seq.pull sq of
   189     None => raise STATE (msg, state)
   190   | Some s_sq => Seq.cons s_sq);
   191 
   192 
   193 fun map_current f (State (Node {context, facts, mode, goal}, nodes)) =
   194   State (make_node (f (context, facts, mode, goal)), nodes);
   195 
   196 fun init_state thy =
   197   State (make_node (ProofContext.init thy, None, Forward, None), []);
   198 
   199 
   200 
   201 (** basic proof state operations **)
   202 
   203 (* context *)
   204 
   205 fun context_of (State (Node {context, ...}, _)) = context;
   206 val theory_of = ProofContext.theory_of o context_of;
   207 val sign_of = ProofContext.sign_of o context_of;
   208 
   209 fun map_context f = map_current (fn (ctxt, facts, mode, goal) => (f ctxt, facts, mode, goal));
   210 
   211 fun map_context_result f (state as State (Node {context, facts, mode, goal}, nodes)) =
   212   let val (context', result) = f context
   213   in (State (make_node (context', facts, mode, goal), nodes), result) end;
   214 
   215 
   216 fun put_data kind f = map_context o ProofContext.put_data kind f;
   217 val warn_extra_tfrees = map_context o ProofContext.warn_extra_tfrees o context_of;
   218 val add_binds_i = map_context o ProofContext.add_binds_i;
   219 val auto_bind_goal = map_context o ProofContext.auto_bind_goal;
   220 val auto_bind_facts = map_context o ProofContext.auto_bind_facts;
   221 val put_thms = map_context o ProofContext.put_thms;
   222 val put_thmss = map_context o ProofContext.put_thmss;
   223 val reset_thms = map_context o ProofContext.reset_thms;
   224 val get_case = ProofContext.get_case o context_of;
   225 
   226 
   227 (* facts *)
   228 
   229 fun the_facts (State (Node {facts = Some facts, ...}, _)) = facts
   230   | the_facts state = raise STATE ("No current facts available", state);
   231 
   232 fun the_fact state =
   233   (case the_facts state of
   234     [thm] => thm
   235   | _ => raise STATE ("Single fact expected", state));
   236 
   237 fun assert_facts state = (the_facts state; state);
   238 fun get_facts (State (Node {facts, ...}, _)) = facts;
   239 
   240 
   241 val thisN = "this";
   242 
   243 fun put_facts facts state =
   244   state
   245   |> map_current (fn (ctxt, _, mode, goal) => (ctxt, facts, mode, goal))
   246   |> (case facts of None => reset_thms thisN | Some ths => put_thms (thisN, ths));
   247 
   248 val reset_facts = put_facts None;
   249 
   250 fun these_factss (state, named_factss) =
   251   state
   252   |> put_thmss named_factss
   253   |> put_facts (Some (flat (map #2 named_factss)));
   254 
   255 
   256 (* goal *)
   257 
   258 local
   259   fun find i (state as State (Node {goal = Some goal, ...}, _)) = (context_of state, (i, goal))
   260     | find i (State (Node {goal = None, ...}, node :: nodes)) = find (i + 1) (State (node, nodes))
   261     | find _ (state as State (_, [])) = err_malformed "find_goal" state;
   262 in val find_goal = find 0 end;
   263 
   264 fun get_goal state =
   265   let val (ctxt, (_, ((_, x), _))) = find_goal state
   266   in (ctxt, x) end;
   267 
   268 fun put_goal goal = map_current (fn (ctxt, facts, mode, _) => (ctxt, facts, mode, goal));
   269 
   270 fun map_goal f g (State (Node {context, facts, mode, goal = Some goal}, nodes)) =
   271       State (make_node (f context, facts, mode, Some (g goal)), nodes)
   272   | map_goal f g (State (nd, node :: nodes)) =
   273       let val State (node', nodes') = map_goal f g (State (node, nodes))
   274       in map_context f (State (nd, node' :: nodes')) end
   275   | map_goal _ _ state = state;
   276 
   277 fun goal_facts get state =
   278   state
   279   |> map_goal I (fn ((result, (_, thm)), f) => ((result, (get state, thm)), f));
   280 
   281 fun use_facts state =
   282   state
   283   |> goal_facts the_facts
   284   |> reset_facts;
   285 
   286 
   287 (* mode *)
   288 
   289 fun get_mode (State (Node {mode, ...}, _)) = mode;
   290 fun put_mode mode = map_current (fn (ctxt, facts, _, goal) => (ctxt, facts, mode, goal));
   291 
   292 val enter_forward = put_mode Forward;
   293 val enter_forward_chain = put_mode ForwardChain;
   294 val enter_backward = put_mode Backward;
   295 
   296 fun assert_mode pred state =
   297   let val mode = get_mode state in
   298     if pred mode then state
   299     else raise STATE ("Illegal application of proof command in "
   300       ^ quote (mode_name mode) ^ " mode", state)
   301   end;
   302 
   303 fun is_chain state = get_mode state = ForwardChain;
   304 val assert_forward = assert_mode (equal Forward);
   305 val assert_forward_or_chain = assert_mode (equal Forward orf equal ForwardChain);
   306 val assert_backward = assert_mode (equal Backward);
   307 val assert_no_chain = assert_mode (not_equal ForwardChain);
   308 
   309 
   310 (* blocks *)
   311 
   312 fun level (State (_, nodes)) = length nodes;
   313 
   314 fun open_block (State (node, nodes)) = State (node, node :: nodes);
   315 
   316 fun new_block state =
   317   state
   318   |> open_block
   319   |> put_goal None;
   320 
   321 fun close_block (state as State (_, node :: nodes)) = State (node, nodes)
   322   | close_block state = raise STATE ("Unbalanced block parentheses", state);
   323 
   324 
   325 
   326 (** pretty_state **)
   327 
   328 val verbose = ProofContext.verbose;
   329 
   330 fun pretty_goals_local ctxt = Display.pretty_goals_aux
   331   (ProofContext.pretty_sort ctxt, ProofContext.pretty_typ ctxt, ProofContext.pretty_term ctxt);
   332 
   333 fun pretty_facts _ _ None = []
   334   | pretty_facts s ctxt (Some ths) =
   335       [Pretty.big_list (s ^ "this:") (map (ProofContext.pretty_thm ctxt) ths), Pretty.str ""];
   336 
   337 fun pretty_state nr (state as State (Node {context = ctxt, facts, mode, goal = _}, nodes)) =
   338   let
   339     val ref (_, _, begin_goal) = Display.current_goals_markers;
   340 
   341     fun levels_up 0 = ""
   342       | levels_up 1 = ", 1 level up"
   343       | levels_up i = ", " ^ string_of_int i ^ " levels up";
   344 
   345     fun subgoals 0 = ""
   346       | subgoals 1 = ", 1 subgoal"
   347       | subgoals n = ", " ^ string_of_int n ^ " subgoals";
   348 
   349     fun prt_names names =
   350       (case filter_out (equal "") names of [] => ""
   351       | nms => " " ^ enclose "(" ")" (space_implode " and " (take (7, nms) @
   352           (if length nms > 7 then ["..."] else []))));
   353 
   354     fun prt_goal (_, (i, (((kind, names, _), (goal_facts, thm)), _))) =
   355       pretty_facts "using " ctxt
   356         (if mode <> Backward orelse null goal_facts then None else Some goal_facts) @
   357       [Pretty.str ("goal (" ^ kind_name (sign_of state) kind ^ prt_names names ^
   358           levels_up (i div 2) ^ subgoals (Thm.nprems_of thm) ^ "):")] @
   359       pretty_goals_local ctxt begin_goal (true, true) (! Display.goals_limit) thm;
   360 
   361     val ctxt_prts =
   362       if ! verbose orelse mode = Forward then ProofContext.pretty_context ctxt
   363       else if mode = Backward then ProofContext.pretty_asms ctxt
   364       else [];
   365 
   366     val prts =
   367      [Pretty.str ("proof (" ^ mode_name mode ^ "): step " ^ string_of_int nr ^
   368         (if ! verbose then ", depth " ^ string_of_int (length nodes div 2 - 1)
   369         else "")), Pretty.str ""] @
   370      (if null ctxt_prts then [] else ctxt_prts @ [Pretty.str ""]) @
   371      (if ! verbose orelse mode = Forward then
   372        (pretty_facts "" ctxt facts @ prt_goal (find_goal state))
   373       else if mode = ForwardChain then pretty_facts "picking " ctxt facts
   374       else prt_goal (find_goal state))
   375   in prts end;
   376 
   377 fun pretty_goals main state =
   378   let val (ctxt, (_, ((_, (_, thm)), _))) = find_goal state
   379   in pretty_goals_local ctxt "" (false, main) (! Display.goals_limit) thm end;
   380 
   381 
   382 
   383 (** proof steps **)
   384 
   385 (* datatype method *)
   386 
   387 datatype method =
   388   Method of thm list -> thm -> (thm * (string * RuleCases.T) list) Seq.seq;
   389 
   390 fun method tac = Method (fn facts => fn st => Seq.map (rpair []) (tac facts st));
   391 val method_cases = Method;
   392 
   393 
   394 (* refine goal *)
   395 
   396 local
   397 
   398 fun check_sign sg state =
   399   if Sign.subsig (sg, sign_of state) then state
   400   else raise STATE ("Bad signature of result: " ^ Sign.str_of_sg sg, state);
   401 
   402 fun gen_refine current_context meth_fun state =
   403   let
   404     val (goal_ctxt, (_, ((result, (facts, thm)), f))) = find_goal state;
   405     val Method meth = meth_fun (if current_context then context_of state else goal_ctxt);
   406 
   407     fun refn (thm', cases) =
   408       state
   409       |> check_sign (Thm.sign_of_thm thm')
   410       |> map_goal (ProofContext.add_cases cases) (K ((result, (facts, thm')), f));
   411   in Seq.map refn (meth facts thm) end;
   412 
   413 in
   414 
   415 val refine = gen_refine true;
   416 val refine_end = gen_refine false;
   417 
   418 end;
   419 
   420 
   421 (* goal addressing *)
   422 
   423 fun FINDGOAL tac st =
   424   let fun find (i, n) = if i > n then Seq.fail else Seq.APPEND (tac i, find (i + 1, n))
   425   in find (1, Thm.nprems_of st) st end;
   426 
   427 fun HEADGOAL tac = tac 1;
   428 
   429 
   430 (* export results *)
   431 
   432 fun refine_tac rule =
   433   Tactic.rtac rule THEN_ALL_NEW (SUBGOAL (fn (goal, i) =>
   434     if can Logic.dest_goal (Logic.strip_assums_concl goal) then
   435       Tactic.etac Drule.triv_goal i
   436     else all_tac));
   437 
   438 fun export_goal inner print_rule raw_rule state =
   439   let
   440     val (outer, (_, ((result, (facts, thm)), f))) = find_goal state;
   441     val exp_tac = ProofContext.export true inner outer;
   442     fun exp_rule rule =
   443       let
   444         val _ = print_rule outer rule;
   445         val thmq = FINDGOAL (refine_tac rule) thm;
   446       in Seq.map (fn th => map_goal I (K ((result, (facts, th)), f)) state) thmq end;
   447   in raw_rule |> exp_tac |> (Seq.flat o Seq.map exp_rule) end;
   448 
   449 fun export_goals inner print_rule raw_rules =
   450   Seq.EVERY (map (export_goal inner print_rule) raw_rules);
   451 
   452 fun transfer_facts inner_state state =
   453   (case get_facts inner_state of
   454     None => Seq.single (reset_facts state)
   455   | Some thms =>
   456       let
   457         val exp_tac = ProofContext.export false (context_of inner_state) (context_of state);
   458         val thmqs = map exp_tac thms;
   459       in Seq.map (fn ths => put_facts (Some ths) state) (Seq.commute thmqs) end);
   460 
   461 
   462 (* prepare result *)
   463 
   464 fun prep_result state ts raw_th =
   465   let
   466     val ctxt = context_of state;
   467     fun err msg = raise STATE (msg, state);
   468 
   469     val ngoals = Thm.nprems_of raw_th;
   470     val _ =
   471       if ngoals = 0 then ()
   472       else (err (Pretty.string_of (Pretty.chunks (pretty_goals_local ctxt "" (true, true)
   473             (! Display.goals_limit) raw_th @
   474           [Pretty.str (string_of_int ngoals ^ " unsolved goal(s)!")]))));
   475 
   476     val {hyps, sign, ...} = Thm.rep_thm raw_th;
   477     val tsig = Sign.tsig_of sign;
   478     val casms = flat (map #1 (ProofContext.assumptions_of (context_of state)));
   479     val bad_hyps = Library.gen_rems Term.aconv (hyps, map Thm.term_of casms);
   480 
   481     val th = raw_th RS Drule.rev_triv_goal;
   482     val ths = Drule.conj_elim_precise (length ts) th
   483       handle THM _ => err "Main goal structure corrupted";
   484     val props = map (#prop o Thm.rep_thm) ths;
   485   in
   486     conditional (not (null bad_hyps)) (fn () => err ("Additional hypotheses:\n" ^
   487         cat_lines (map (ProofContext.string_of_term ctxt) bad_hyps)));
   488     conditional (exists (not o Pattern.matches tsig) (ts ~~ props)) (fn () =>
   489       err ("Proved a different theorem: " ^ Pretty.string_of (ProofContext.pretty_thm ctxt th)));
   490     ths
   491   end;
   492 
   493 
   494 
   495 (*** structured proof commands ***)
   496 
   497 (** context **)
   498 
   499 (* bind *)
   500 
   501 fun gen_bind f x state =
   502   state
   503   |> assert_forward
   504   |> map_context (f x)
   505   |> reset_facts;
   506 
   507 val match_bind = gen_bind (ProofContext.match_bind false);
   508 val match_bind_i = gen_bind (ProofContext.match_bind_i false);
   509 val let_bind = gen_bind (ProofContext.match_bind true);
   510 val let_bind_i = gen_bind (ProofContext.match_bind_i true);
   511 
   512 
   513 (* have_thmss etc. *)
   514 
   515 fun have_thmss args state =
   516   state
   517   |> assert_forward
   518   |> map_context_result (ProofContext.have_thmss args)
   519   |> these_factss;
   520 
   521 fun simple_have_thms name thms = have_thmss [((name, []), [(thms, [])])];
   522 
   523 fun with_thmss args state =
   524   let val state' = state |> have_thmss args
   525   in state' |> simple_have_thms "" (the_facts state' @ the_facts state) end;
   526 
   527 
   528 (* fix *)
   529 
   530 fun gen_fix f xs state =
   531   state
   532   |> assert_forward
   533   |> map_context (f xs)
   534   |> reset_facts;
   535 
   536 val fix = gen_fix ProofContext.fix;
   537 val fix_i = gen_fix ProofContext.fix_i;
   538 
   539 
   540 (* assume and presume *)
   541 
   542 fun gen_assume f exp args state =
   543   state
   544   |> assert_forward
   545   |> map_context_result (f exp args)
   546   |> these_factss;
   547 
   548 val assm = gen_assume ProofContext.assume;
   549 val assm_i = gen_assume ProofContext.assume_i;
   550 val assume = assm ProofContext.export_assume;
   551 val assume_i = assm_i ProofContext.export_assume;
   552 val presume = assm ProofContext.export_presume;
   553 val presume_i = assm_i ProofContext.export_presume;
   554 
   555 
   556 
   557 (** local definitions **)
   558 
   559 fun gen_def fix prep_term prep_pats raw_name atts (x, (raw_rhs, raw_pats)) state =
   560   let
   561     val _ = assert_forward state;
   562     val ctxt = context_of state;
   563 
   564     (*rhs*)
   565     val name = if raw_name = "" then Thm.def_name x else raw_name;
   566     val rhs = prep_term ctxt raw_rhs;
   567     val T = Term.fastype_of rhs;
   568     val pats = prep_pats T (ProofContext.declare_term rhs ctxt) raw_pats;
   569 
   570     (*lhs*)
   571     val lhs = ProofContext.bind_skolem ctxt [x] (Free (x, T));
   572   in
   573     state
   574     |> fix [([x], None)]
   575     |> match_bind_i [(pats, rhs)]
   576     |> assm_i ProofContext.export_def [((name, atts), [(Logic.mk_equals (lhs, rhs), ([], []))])]
   577   end;
   578 
   579 val def = gen_def fix ProofContext.read_term ProofContext.read_term_pats;
   580 val def_i = gen_def fix_i ProofContext.cert_term ProofContext.cert_term_pats;
   581 
   582 
   583 (* invoke_case *)
   584 
   585 fun invoke_case (name, xs, atts) state =
   586   let
   587     val (state', (lets, asms)) =
   588       map_context_result (ProofContext.apply_case (get_case state name xs)) state;
   589   in
   590     state'
   591     |> add_binds_i lets
   592     |> assume_i [((name, atts), map (rpair ([], [])) asms)]
   593   end;
   594 
   595 
   596 
   597 (** goals **)
   598 
   599 (* forward chaining *)
   600 
   601 fun chain state =
   602   state
   603   |> assert_forward
   604   |> assert_facts
   605   |> enter_forward_chain;
   606 
   607 fun from_facts facts state =
   608   state
   609   |> put_facts (Some facts)
   610   |> chain;
   611 
   612 
   613 (* setup goals *)
   614 
   615 val rule_contextN = "rule_context";
   616 
   617 fun setup_goal opt_block prepp autofix kind after_qed names raw_propp state =
   618   let
   619     val (state', (propss, gen_binds)) =
   620       state
   621       |> assert_forward_or_chain
   622       |> enter_forward
   623       |> opt_block
   624       |> map_context_result (fn ctxt => prepp (ctxt, raw_propp));
   625 
   626     val props = flat propss;
   627     val cprop = Thm.cterm_of (sign_of state') (foldr1 Logic.mk_conjunction props);
   628     val goal = Drule.mk_triv_goal cprop;
   629 
   630     val tvars = foldr Term.add_term_tvars (props, []);
   631     val vars = foldr Term.add_term_vars (props, []);
   632   in
   633     if null tvars then ()
   634     else raise STATE ("Goal statement contains illegal schematic type variable(s): " ^
   635       commas (map (Syntax.string_of_vname o #1) tvars), state);
   636     if null vars then ()
   637     else warning ("Goal statement contains unbound schematic variable(s): " ^
   638       commas (map (ProofContext.string_of_term (context_of state')) vars));
   639     state'
   640     |> map_context (autofix props)
   641     |> put_goal (Some (((kind, names, propss), ([], goal)), after_qed o map_context gen_binds))
   642     |> map_context (ProofContext.add_cases
   643      (if length props = 1 then RuleCases.make true goal [rule_contextN]
   644       else [(rule_contextN, RuleCases.empty)]))
   645     |> auto_bind_goal props
   646     |> (if is_chain state then use_facts else reset_facts)
   647     |> new_block
   648     |> enter_backward
   649   end;
   650 
   651 (*global goals*)
   652 fun global_goal prep kind a raw_locale elems args thy =
   653   let
   654     val init = init_state thy;
   655     val (opt_name, locale_ctxt, elems_ctxt, propp) =
   656       prep (apsome fst raw_locale) elems (map snd args) (context_of init);
   657     val locale = (case raw_locale of None => None | Some (_, atts) => Some (the opt_name, atts));
   658   in
   659     init
   660     |> open_block
   661     |> map_context (K locale_ctxt)
   662     |> open_block
   663     |> map_context (K elems_ctxt)
   664     |> setup_goal I ProofContext.bind_propp_schematic_i
   665       ProofContext.fix_frees (Theorem (kind, a, locale, map (snd o fst) args))
   666       Seq.single (map (fst o fst) args) propp
   667   end;
   668 
   669 val multi_theorem = global_goal Locale.read_context_statement;
   670 val multi_theorem_i = global_goal Locale.cert_context_statement;
   671 
   672 fun theorem k locale elems name atts p =
   673   multi_theorem k (name, atts) locale elems [(("", []), [p])];
   674 fun theorem_i k locale elems name atts p =
   675   multi_theorem_i k (name, atts) locale elems [(("", []), [p])];
   676 
   677 
   678 (*local goals*)
   679 fun local_goal' prepp kind (check: bool -> state -> state) f args int state =
   680   state
   681   |> setup_goal open_block prepp (K I) (kind (map (snd o fst) args))
   682     f (map (fst o fst) args) (map snd args)
   683   |> warn_extra_tfrees state
   684   |> check int;
   685 
   686 fun local_goal prepp kind f args = local_goal' prepp kind (K I) f args false;
   687 
   688 val show = local_goal' ProofContext.bind_propp Show;
   689 val show_i = local_goal' ProofContext.bind_propp_i Show;
   690 val have = local_goal ProofContext.bind_propp Have;
   691 val have_i = local_goal ProofContext.bind_propp_i Have;
   692 
   693 
   694 
   695 (** conclusions **)
   696 
   697 (* current goal *)
   698 
   699 fun current_goal (State (Node {context, goal = Some goal, ...}, _)) = (context, goal)
   700   | current_goal state = raise STATE ("No current goal!", state);
   701 
   702 fun assert_current_goal true (state as State (Node {goal = None, ...}, _)) =
   703       raise STATE ("No goal in this block!", state)
   704   | assert_current_goal false (state as State (Node {goal = Some _, ...}, _)) =
   705       raise STATE ("Goal present in this block!", state)
   706   | assert_current_goal _ state = state;
   707 
   708 fun assert_bottom b (state as State (_, nodes)) =
   709   let val bot = (length nodes <= 2) in
   710     if b andalso not bot then raise STATE ("Not at bottom of proof!", state)
   711     else if not b andalso bot then raise STATE ("Already at bottom of proof!", state)
   712     else state
   713   end;
   714 
   715 val at_bottom = can (assert_bottom true o close_block);
   716 
   717 fun end_proof bot state =
   718   state
   719   |> assert_forward
   720   |> close_block
   721   |> assert_bottom bot
   722   |> assert_current_goal true
   723   |> goal_facts (K []);
   724 
   725 
   726 (* local_qed *)
   727 
   728 fun finish_local (print_result, print_rule) state =
   729   let
   730     val (goal_ctxt, (((kind, names, tss), (_, raw_thm)), after_qed)) = current_goal state;
   731     val outer_state = state |> close_block;
   732     val outer_ctxt = context_of outer_state;
   733 
   734     val ts = flat tss;
   735     val results = prep_result state ts raw_thm;
   736     val resultq =
   737       results |> map (ProofContext.export false goal_ctxt outer_ctxt)
   738       |> Seq.commute |> Seq.map (Library.unflat tss);
   739 
   740     val (attss, opt_solve) =
   741       (case kind of
   742         Show attss => (attss, export_goals goal_ctxt print_rule results)
   743       | Have attss => (attss, Seq.single)
   744       | _ => err_malformed "finish_local" state);
   745   in
   746     print_result goal_ctxt (kind_name (sign_of state) kind, names ~~ Library.unflat tss results);
   747     outer_state
   748     |> auto_bind_facts (ProofContext.generalize goal_ctxt outer_ctxt ts)
   749     |> (fn st => Seq.map (fn res =>
   750       have_thmss ((names ~~ attss) ~~ map (single o Thm.no_attributes) res) st) resultq)
   751     |> (Seq.flat o Seq.map opt_solve)
   752     |> (Seq.flat o Seq.map after_qed)
   753   end;
   754 
   755 fun local_qed finalize print state =
   756   state
   757   |> end_proof false
   758   |> finalize
   759   |> (Seq.flat o Seq.map (finish_local print));
   760 
   761 
   762 (* global_qed *)
   763 
   764 fun locale_prefix None f thy = f thy
   765   | locale_prefix (Some (loc, _)) f thy =
   766       thy |> Theory.add_path (Sign.base_name loc) |> f |>> Theory.parent_path;
   767 
   768 fun locale_add_thmss None _ = I
   769   | locale_add_thmss (Some (loc, atts)) ths = Locale.add_thmss loc (map (rpair atts) ths);
   770 
   771 fun finish_global state =
   772   let
   773     fun export inner outer th =
   774       (case Seq.pull (ProofContext.export false inner outer th) of
   775         Some (th', _) => th' |> Drule.local_standard
   776       | None => raise STATE ("Internal failure of theorem export", state));
   777 
   778     val (goal_ctxt, (((kind, names, tss), (_, raw_thm)), _)) = current_goal state;
   779     val locale_ctxt = context_of (state |> close_block);
   780     val theory_ctxt = context_of (state |> close_block |> close_block);
   781 
   782     val ts = flat tss;
   783     val locale_results =
   784       prep_result state ts raw_thm |> map (export goal_ctxt locale_ctxt);
   785     val results = locale_results
   786       |> map (Drule.strip_shyps_warning o export locale_ctxt theory_ctxt);
   787 
   788     val (k, (cname, catts), locale, attss) =
   789       (case kind of Theorem x => x | _ => err_malformed "finish_global" state);
   790     val (thy1, res') =
   791       theory_of state
   792       |> locale_prefix locale (PureThy.have_thmss [Drule.kind k]
   793           ((names ~~ attss) ~~ map (single o Thm.no_attributes) (Library.unflat tss results)))
   794       |>> locale_add_thmss locale (names ~~ Library.unflat tss locale_results);
   795     val thy2 = thy1 |> PureThy.add_thmss [((cname, flat (map #2 res')), catts)] |> #1;
   796   in (thy2, ((k, cname), res')) end;
   797 
   798 (*note: clients should inspect first result only, as backtracking may destroy theory*)
   799 fun global_qed finalize state =
   800   state
   801   |> end_proof true
   802   |> finalize
   803   |> Seq.map finish_global;
   804 
   805 
   806 
   807 (** blocks **)
   808 
   809 (* begin_block *)
   810 
   811 fun begin_block state =
   812   state
   813   |> assert_forward
   814   |> new_block
   815   |> open_block;
   816 
   817 
   818 (* end_block *)
   819 
   820 fun end_block state =
   821   state
   822   |> assert_forward
   823   |> close_block
   824   |> assert_current_goal false
   825   |> close_block
   826   |> transfer_facts state;
   827 
   828 
   829 (* next_block *)
   830 
   831 fun next_block state =
   832   state
   833   |> assert_forward
   834   |> close_block
   835   |> new_block
   836   |> reset_facts;
   837 
   838 
   839 end;
   840 
   841 structure BasicProof: BASIC_PROOF = Proof;
   842 open BasicProof;