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