src/Pure/Isar/proof.ML
author ballarin
Tue Sep 30 15:13:02 2003 +0200 (2003-09-30)
changeset 14215 ebf291f3b449
parent 14129 d4e2ab7cc86b
child 14404 4952c5a92e04
permissions -rw-r--r--
Improvements to Isar/Locales: premises generated by "includes" elements
changed. Bugfix "unify_frozen".
     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   datatype mode = Forward | ForwardChain | Backward
    21   exception STATE of string * state
    22   val check_result: string -> state -> 'a Seq.seq -> 'a Seq.seq
    23   val init_state: theory -> state
    24   val context_of: state -> context
    25   val theory_of: state -> theory
    26   val sign_of: state -> Sign.sg
    27   val map_context: (context -> context) -> state -> state
    28   val warn_extra_tfrees: state -> state -> state
    29   val reset_thms: string -> state -> state
    30   val the_facts: state -> thm list
    31   val the_fact: state -> thm
    32   val get_goal: state -> context * (thm list * thm)
    33   val goal_facts: (state -> thm list) -> state -> state
    34   val use_facts: state -> state
    35   val reset_facts: state -> state
    36   val get_mode: state -> mode
    37   val is_chain: state -> bool
    38   val assert_forward: state -> state
    39   val assert_forward_or_chain: state -> state
    40   val assert_backward: state -> state
    41   val assert_no_chain: state -> state
    42   val enter_forward: state -> state
    43   val verbose: bool ref
    44   val show_main_goal: bool ref
    45   val pretty_state: int -> state -> Pretty.T list
    46   val pretty_goals: bool -> state -> Pretty.T list
    47   val level: state -> int
    48   type method
    49   val method: (thm list -> tactic) -> method
    50   val method_cases: (thm list -> thm -> (thm * (string * RuleCases.T) list) Seq.seq) -> method
    51   val refine: (context -> method) -> state -> state Seq.seq
    52   val refine_end: (context -> method) -> state -> state Seq.seq
    53   val match_bind: (string list * string) list -> state -> state
    54   val match_bind_i: (term list * term) list -> state -> state
    55   val let_bind: (string list * string) list -> state -> state
    56   val let_bind_i: (term list * term) list -> state -> state
    57   val simple_have_thms: string -> thm list -> state -> state
    58   val have_thmss: ((bstring * context attribute list) *
    59     (xstring * context attribute list) list) list -> state -> state
    60   val have_thmss_i: ((bstring * context attribute list) *
    61     (thm list * context attribute list) list) list -> state -> state
    62   val with_thmss: ((bstring * context attribute list) *
    63     (xstring * context attribute list) list) list -> state -> state
    64   val with_thmss_i: ((bstring * context attribute list) *
    65     (thm list * context attribute list) list) list -> state -> state
    66   val using_thmss: ((xstring * context attribute list) list) list -> state -> state
    67   val using_thmss_i: ((thm list * context attribute list) list) list -> state -> state
    68   val fix: (string list * string option) list -> state -> state
    69   val fix_i: (string list * typ option) list -> state -> state
    70   val assm: ProofContext.exporter
    71     -> ((string * context attribute list) * (string * (string list * string list)) list) list
    72     -> state -> state
    73   val assm_i: ProofContext.exporter
    74     -> ((string * context attribute list) * (term * (term list * term list)) list) list
    75     -> state -> state
    76   val assume:
    77     ((string * context attribute list) * (string * (string list * string list)) list) list
    78     -> state -> state
    79   val assume_i: ((string * context attribute list) * (term * (term list * term list)) list) list
    80     -> state -> state
    81   val presume:
    82     ((string * context attribute list) * (string * (string list * string list)) list) list
    83     -> state -> state
    84   val presume_i: ((string * context attribute list) * (term * (term list * term list)) list) list
    85     -> state -> state
    86   val def: string -> context attribute list -> string *  (string * string list) -> state -> state
    87   val def_i: string -> context attribute list -> string * (term * term list) -> state -> state
    88   val invoke_case: string * string option list * context attribute list -> state -> state
    89   val multi_theorem: string
    90     -> (xstring * (context attribute list * context attribute list list)) option
    91     -> bstring * theory attribute list -> context attribute Locale.element list
    92     -> ((bstring * theory attribute list) * (string * (string list * string list)) list) list
    93     -> theory -> state
    94   val multi_theorem_i: string
    95     -> (string * (context attribute list * context attribute list list)) option
    96     -> bstring * theory attribute list
    97     -> context attribute Locale.element_i list
    98     -> ((bstring * theory attribute list) * (term * (term list * term list)) list) list
    99     -> theory -> state
   100   val chain: state -> state
   101   val from_facts: thm list -> state -> state
   102   val show: (bool -> state -> state) -> (state -> state Seq.seq) -> bool
   103     -> ((string * context attribute list) * (string * (string list * string list)) list) list
   104     -> bool -> state -> state
   105   val show_i: (bool -> state -> state) -> (state -> state Seq.seq) -> bool
   106     -> ((string * context attribute list) * (term * (term list * term list)) list) list
   107     -> bool -> state -> state
   108   val have: (state -> state Seq.seq) -> bool
   109     -> ((string * context attribute list) * (string * (string list * string list)) list) list
   110     -> state -> state
   111   val have_i: (state -> state Seq.seq) -> bool
   112     -> ((string * context attribute list) * (term * (term list * term list)) list) list
   113     -> state -> state
   114   val at_bottom: state -> bool
   115   val local_qed: (state -> state Seq.seq)
   116     -> (context -> string * (string * thm list) list -> unit) * (context -> thm -> unit)
   117     -> state -> state Seq.seq
   118   val global_qed: (state -> state Seq.seq) -> state
   119     -> (theory * ((string * string) * (string * thm list) list)) Seq.seq
   120   val begin_block: state -> state
   121   val end_block: state -> state Seq.seq
   122   val next_block: state -> state
   123 end;
   124 
   125 structure Proof: PROOF =
   126 struct
   127 
   128 
   129 (** proof state **)
   130 
   131 type context = ProofContext.context;
   132 
   133 
   134 (* type goal *)
   135 
   136 datatype kind =
   137   Theorem of {kind: string,
   138     theory_spec: (bstring * theory attribute list) * theory attribute list list,
   139     locale_spec: (string * (context attribute list * context attribute list list)) option,
   140     view: cterm list} |
   141   Show of context attribute list list |
   142   Have of context attribute list list;
   143 
   144 fun kind_name _ (Theorem {kind = s, theory_spec = ((a, _), _),
   145         locale_spec = None, view = _}) = s ^ (if a = "" then "" else " " ^ a)
   146   | kind_name sg (Theorem {kind = s, theory_spec = ((a, _), _),
   147         locale_spec = Some (name, _), view = _}) =
   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 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 |> put_facts (Some (flat (map snd named_factss)));
   252 
   253 
   254 (* goal *)
   255 
   256 local
   257   fun find i (state as State (Node {goal = Some goal, ...}, _)) = (context_of state, (i, goal))
   258     | find i (State (Node {goal = None, ...}, node :: nodes)) = find (i + 1) (State (node, nodes))
   259     | find _ (state as State (_, [])) = err_malformed "find_goal" state;
   260 in val find_goal = find 0 end;
   261 
   262 fun get_goal state =
   263   let val (ctxt, (_, ((_, x), _))) = find_goal state
   264   in (ctxt, x) end;
   265 
   266 fun put_goal goal = map_current (fn (ctxt, facts, mode, _) => (ctxt, facts, mode, goal));
   267 
   268 fun map_goal f g (State (Node {context, facts, mode, goal = Some goal}, nodes)) =
   269       State (make_node (f context, facts, mode, Some (g goal)), nodes)
   270   | map_goal f g (State (nd, node :: nodes)) =
   271       let val State (node', nodes') = map_goal f g (State (node, nodes))
   272       in map_context f (State (nd, node' :: nodes')) end
   273   | map_goal _ _ state = state;
   274 
   275 fun goal_facts get state =
   276   state
   277   |> map_goal I (fn ((result, (_, thm)), f) => ((result, (get state, thm)), f));
   278 
   279 fun use_facts state =
   280   state
   281   |> goal_facts the_facts
   282   |> reset_facts;
   283 
   284 
   285 (* mode *)
   286 
   287 fun get_mode (State (Node {mode, ...}, _)) = mode;
   288 fun put_mode mode = map_current (fn (ctxt, facts, _, goal) => (ctxt, facts, mode, goal));
   289 
   290 val enter_forward = put_mode Forward;
   291 val enter_forward_chain = put_mode ForwardChain;
   292 val enter_backward = put_mode Backward;
   293 
   294 fun assert_mode pred state =
   295   let val mode = get_mode state in
   296     if pred mode then state
   297     else raise STATE ("Illegal application of proof command in "
   298       ^ quote (mode_name mode) ^ " mode", state)
   299   end;
   300 
   301 fun is_chain state = get_mode state = ForwardChain;
   302 val assert_forward = assert_mode (equal Forward);
   303 val assert_forward_or_chain = assert_mode (equal Forward orf equal ForwardChain);
   304 val assert_backward = assert_mode (equal Backward);
   305 val assert_no_chain = assert_mode (not_equal ForwardChain);
   306 
   307 
   308 (* blocks *)
   309 
   310 fun level (State (_, nodes)) = length nodes;
   311 
   312 fun open_block (State (node, nodes)) = State (node, node :: nodes);
   313 
   314 fun new_block state =
   315   state
   316   |> open_block
   317   |> put_goal None;
   318 
   319 fun close_block (state as State (_, node :: nodes)) = State (node, nodes)
   320   | close_block state = raise STATE ("Unbalanced block parentheses", state);
   321 
   322 
   323 
   324 (** pretty_state **)
   325 
   326 val show_main_goal = ref false;
   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, !show_main_goal) (! 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)), x))) = 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')), x));
   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.norm_hhf_tac THEN' 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)), x))) = 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)), x)) 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, !show_main_goal)
   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   in
   485     conditional (not (null bad_hyps)) (fn () => err ("Additional hypotheses:\n" ^
   486         cat_lines (map (ProofContext.string_of_term ctxt) bad_hyps)));
   487     conditional (exists (not o Pattern.matches tsig) (ts ~~ map Thm.prop_of ths)) (fn () =>
   488       err ("Proved a different theorem: " ^ Pretty.string_of (ProofContext.pretty_thm ctxt th)));
   489     ths
   490   end;
   491 
   492 
   493 
   494 (*** structured proof commands ***)
   495 
   496 (** context **)
   497 
   498 (* bind *)
   499 
   500 fun gen_bind f x state =
   501   state
   502   |> assert_forward
   503   |> map_context (f x)
   504   |> reset_facts;
   505 
   506 val match_bind = gen_bind (ProofContext.match_bind false);
   507 val match_bind_i = gen_bind (ProofContext.match_bind_i false);
   508 val let_bind = gen_bind (ProofContext.match_bind true);
   509 val let_bind_i = gen_bind (ProofContext.match_bind_i true);
   510 
   511 
   512 (* have_thmss *)
   513 
   514 local
   515 
   516 fun gen_have_thmss f args state =
   517   state
   518   |> assert_forward
   519   |> map_context_result (f args)
   520   |> these_factss;
   521 
   522 in
   523 
   524 val have_thmss = gen_have_thmss ProofContext.have_thmss;
   525 val have_thmss_i = gen_have_thmss ProofContext.have_thmss_i;
   526 
   527 fun simple_have_thms name thms = have_thmss_i [((name, []), [(thms, [])])];
   528 
   529 end;
   530 
   531 
   532 (* with_thmss *)
   533 
   534 local
   535 
   536 fun gen_with_thmss f args state =
   537   let val state' = state |> f args
   538   in state' |> simple_have_thms "" (the_facts state' @ the_facts state) end;
   539 
   540 in
   541 
   542 val with_thmss = gen_with_thmss have_thmss;
   543 val with_thmss_i = gen_with_thmss have_thmss_i;
   544 
   545 end;
   546 
   547 
   548 (* using_thmss *)
   549 
   550 local
   551 
   552 fun gen_using_thmss f args state =
   553   state
   554   |> assert_backward
   555   |> map_context_result (f (map (pair ("", [])) args))
   556   |> (fn (st, named_facts) =>
   557     let val (_, (_, ((result, (facts, thm)), x))) = find_goal st;
   558     in st |> map_goal I (K ((result, (facts @ flat (map snd named_facts), thm)), x)) end);
   559 
   560 in
   561 
   562 val using_thmss = gen_using_thmss ProofContext.have_thmss;
   563 val using_thmss_i = gen_using_thmss ProofContext.have_thmss_i;
   564 
   565 end;
   566 
   567 
   568 (* fix *)
   569 
   570 fun gen_fix f xs state =
   571   state
   572   |> assert_forward
   573   |> map_context (f xs)
   574   |> reset_facts;
   575 
   576 val fix = gen_fix ProofContext.fix;
   577 val fix_i = gen_fix ProofContext.fix_i;
   578 
   579 
   580 (* assume and presume *)
   581 
   582 fun gen_assume f exp args state =
   583   state
   584   |> assert_forward
   585   |> map_context_result (f exp args)
   586   |> these_factss;
   587 
   588 val assm = gen_assume ProofContext.assume;
   589 val assm_i = gen_assume ProofContext.assume_i;
   590 val assume = assm ProofContext.export_assume;
   591 val assume_i = assm_i ProofContext.export_assume;
   592 val presume = assm ProofContext.export_presume;
   593 val presume_i = assm_i ProofContext.export_presume;
   594 
   595 
   596 
   597 (** local definitions **)
   598 
   599 fun gen_def fix prep_term prep_pats raw_name atts (x, (raw_rhs, raw_pats)) state =
   600   let
   601     val _ = assert_forward state;
   602     val ctxt = context_of state;
   603 
   604     (*rhs*)
   605     val name = if raw_name = "" then Thm.def_name x else raw_name;
   606     val rhs = prep_term ctxt raw_rhs;
   607     val T = Term.fastype_of rhs;
   608     val pats = prep_pats T (ProofContext.declare_term rhs ctxt) raw_pats;
   609 
   610     (*lhs*)
   611     val lhs = ProofContext.bind_skolem ctxt [x] (Free (x, T));
   612   in
   613     state
   614     |> fix [([x], None)]
   615     |> match_bind_i [(pats, rhs)]
   616     |> assm_i ProofContext.export_def [((name, atts), [(Logic.mk_equals (lhs, rhs), ([], []))])]
   617   end;
   618 
   619 val def = gen_def fix ProofContext.read_term ProofContext.read_term_pats;
   620 val def_i = gen_def fix_i ProofContext.cert_term ProofContext.cert_term_pats;
   621 
   622 
   623 (* invoke_case *)
   624 
   625 fun invoke_case (name, xs, atts) state =
   626   let
   627     val (state', (lets, asms)) =
   628       map_context_result (ProofContext.apply_case (get_case state name xs)) state;
   629     val assumptions = asms |> map (fn (a, ts) =>
   630       ((if a = "" then "" else NameSpace.append name a, atts), map (rpair ([], [])) ts));
   631     val qnames = filter_out (equal "") (map (#1 o #1) assumptions);
   632   in
   633     state'
   634     |> add_binds_i lets
   635     |> map_context (ProofContext.qualified true)
   636     |> assume_i assumptions
   637     |> map_context (ProofContext.hide_thms false qnames)
   638     |> (fn st => simple_have_thms name (the_facts st) st)
   639     |> map_context (ProofContext.restore_qualified (context_of state))
   640   end;
   641 
   642 
   643 
   644 (** goals **)
   645 
   646 (* forward chaining *)
   647 
   648 fun chain state =
   649   state
   650   |> assert_forward
   651   |> assert_facts
   652   |> enter_forward_chain;
   653 
   654 fun from_facts facts state =
   655   state
   656   |> put_facts (Some facts)
   657   |> chain;
   658 
   659 
   660 (* setup goals *)
   661 
   662 val rule_contextN = "rule_context";
   663 
   664 fun setup_goal opt_block prepp autofix kind after_qed pr names raw_propp state =
   665   let
   666     val (state', (propss, gen_binds)) =
   667       state
   668       |> assert_forward_or_chain
   669       |> enter_forward
   670       |> opt_block
   671       |> map_context_result (fn ctxt => prepp (ctxt, raw_propp));
   672     val sign' = sign_of state';
   673 
   674     val props = flat propss;
   675     val cprop = Thm.cterm_of sign' (Logic.mk_conjunction_list props);
   676     val goal = Drule.mk_triv_goal cprop;
   677 
   678     val tvars = foldr Term.add_term_tvars (props, []);
   679     val vars = foldr Term.add_term_vars (props, []);
   680   in
   681     if null tvars then ()
   682     else raise STATE ("Goal statement contains illegal schematic type variable(s): " ^
   683       commas (map (Syntax.string_of_vname o #1) tvars), state);
   684     if null vars then ()
   685     else warning ("Goal statement contains unbound schematic variable(s): " ^
   686       commas (map (ProofContext.string_of_term (context_of state')) vars));
   687     state'
   688     |> map_context (autofix props)
   689     |> put_goal (Some (((kind, names, propss), ([], goal)),
   690       (after_qed o map_context gen_binds, pr)))
   691     |> map_context (ProofContext.add_cases
   692      (if length props = 1 then
   693       RuleCases.make None None (Thm.sign_of_thm goal, Thm.prop_of goal) [rule_contextN]
   694       else [(rule_contextN, RuleCases.empty)]))
   695     |> auto_bind_goal props
   696     |> (if is_chain state then use_facts else reset_facts)
   697     |> new_block
   698     |> enter_backward
   699   end;
   700 
   701 (*global goals*)
   702 fun global_goal prep kind raw_locale a elems concl thy =
   703   let
   704     val init = init_state thy;
   705     val (opt_name, view, locale_ctxt, elems_ctxt, propp) =
   706       prep (apsome fst raw_locale) elems (map snd concl) (context_of init);
   707   in
   708     init
   709     |> open_block
   710     |> map_context (K locale_ctxt)
   711     |> open_block
   712     |> map_context (K elems_ctxt)
   713     |> setup_goal I ProofContext.bind_propp_schematic_i ProofContext.fix_frees
   714       (Theorem {kind = kind,
   715         theory_spec = (a, map (snd o fst) concl),
   716         locale_spec = (case raw_locale of None => None | Some (_, x) => Some (the opt_name, x)),
   717         view = view})
   718       Seq.single true (map (fst o fst) concl) propp
   719   end;
   720 
   721 val multi_theorem = global_goal Locale.read_context_statement;
   722 val multi_theorem_i = global_goal Locale.cert_context_statement;
   723 
   724 
   725 (*local goals*)
   726 fun local_goal' prepp kind (check: bool -> state -> state) f pr args int state =
   727   state
   728   |> setup_goal open_block prepp (K I) (kind (map (snd o fst) args))
   729     f pr (map (fst o fst) args) (map snd args)
   730   |> warn_extra_tfrees state
   731   |> check int;
   732 
   733 fun local_goal prepp kind f pr args = local_goal' prepp kind (K I) f pr args false;
   734 
   735 val show = local_goal' ProofContext.bind_propp Show;
   736 val show_i = local_goal' ProofContext.bind_propp_i Show;
   737 val have = local_goal ProofContext.bind_propp Have;
   738 val have_i = local_goal ProofContext.bind_propp_i Have;
   739 
   740 
   741 
   742 (** conclusions **)
   743 
   744 (* current goal *)
   745 
   746 fun current_goal (State (Node {context, goal = Some goal, ...}, _)) = (context, goal)
   747   | current_goal state = raise STATE ("No current goal!", state);
   748 
   749 fun assert_current_goal true (state as State (Node {goal = None, ...}, _)) =
   750       raise STATE ("No goal in this block!", state)
   751   | assert_current_goal false (state as State (Node {goal = Some _, ...}, _)) =
   752       raise STATE ("Goal present in this block!", state)
   753   | assert_current_goal _ state = state;
   754 
   755 fun assert_bottom b (state as State (_, nodes)) =
   756   let val bot = (length nodes <= 2) in
   757     if b andalso not bot then raise STATE ("Not at bottom of proof!", state)
   758     else if not b andalso bot then raise STATE ("Already at bottom of proof!", state)
   759     else state
   760   end;
   761 
   762 val at_bottom = can (assert_bottom true o close_block);
   763 
   764 fun end_proof bot state =
   765   state
   766   |> assert_forward
   767   |> close_block
   768   |> assert_bottom bot
   769   |> assert_current_goal true
   770   |> goal_facts (K []);
   771 
   772 
   773 (* local_qed *)
   774 
   775 fun finish_local (print_result, print_rule) state =
   776   let
   777     val (goal_ctxt, (((kind, names, tss), (_, raw_thm)), (after_qed, pr))) = current_goal state;
   778     val outer_state = state |> close_block;
   779     val outer_ctxt = context_of outer_state;
   780 
   781     val ts = flat tss;
   782     val results = prep_result state ts raw_thm;
   783     val resultq =
   784       results |> map (ProofContext.export false goal_ctxt outer_ctxt)
   785       |> Seq.commute |> Seq.map (Library.unflat tss);
   786 
   787     val (attss, opt_solve) =
   788       (case kind of
   789         Show attss => (attss,
   790           export_goals goal_ctxt (if pr then print_rule else (K (K ()))) results)
   791       | Have attss => (attss, Seq.single)
   792       | _ => err_malformed "finish_local" state);
   793   in
   794     conditional pr (fn () => print_result goal_ctxt
   795       (kind_name (sign_of state) kind, names ~~ Library.unflat tss results));
   796     outer_state
   797     |> auto_bind_facts (ProofContext.generalize goal_ctxt outer_ctxt ts)
   798     |> (fn st => Seq.map (fn res =>
   799       have_thmss_i ((names ~~ attss) ~~ map (single o Thm.no_attributes) res) st) resultq)
   800     |> (Seq.flat o Seq.map opt_solve)
   801     |> (Seq.flat o Seq.map after_qed)
   802   end;
   803 
   804 fun local_qed finalize print state =
   805   state
   806   |> end_proof false
   807   |> finalize
   808   |> (Seq.flat o Seq.map (finish_local print));
   809 
   810 
   811 (* global_qed *)
   812 
   813 fun finish_global state =
   814   let
   815     val (goal_ctxt, (((kind, names, tss), (_, raw_thm)), _)) = current_goal state;
   816     val locale_ctxt = context_of (state |> close_block);
   817     val theory_ctxt = context_of (state |> close_block |> close_block);
   818     val {kind = k, theory_spec = ((name, atts), attss), locale_spec, view} =
   819       (case kind of Theorem x => x | _ => err_malformed "finish_global" state);
   820 
   821     val ts = flat tss;
   822     val locale_results = map (ProofContext.export_standard [] goal_ctxt locale_ctxt)
   823       (prep_result state ts raw_thm);
   824 
   825     val locale_results' = map
   826       (Locale.prune_prems (ProofContext.theory_of locale_ctxt))
   827       locale_results;
   828 
   829     val results = map (Drule.strip_shyps_warning o
   830       ProofContext.export_standard view locale_ctxt theory_ctxt) locale_results';
   831 
   832     val (theory', results') =
   833       theory_of state
   834       |> (case locale_spec of None => I | Some (loc, (loc_atts, loc_attss)) => fn thy =>
   835         if length names <> length loc_attss then
   836           raise THEORY ("Bad number of locale attributes", [thy])
   837         else (thy, locale_ctxt)
   838           |> Locale.add_thmss loc ((names ~~ Library.unflat tss locale_results') ~~ loc_attss)
   839           |> (fn ((thy', ctxt'), res) =>
   840             if name = "" andalso null loc_atts then thy'
   841             else (thy', ctxt')
   842               |> (#1 o #1 o Locale.add_thmss loc [((name, flat (map #2 res)), loc_atts)])))
   843       |> Locale.smart_have_thmss k locale_spec
   844         ((names ~~ attss) ~~ map (single o Thm.no_attributes) (Library.unflat tss results))
   845       |> (fn (thy, res) => (thy, res)
   846           |>> (#1 o Locale.smart_have_thmss k locale_spec
   847             [((name, atts), [(flat (map #2 res), [])])]));
   848   in (theory', ((k, name), results')) end;
   849 
   850 
   851 (*note: clients should inspect first result only, as backtracking may destroy theory*)
   852 fun global_qed finalize state =
   853   state
   854   |> end_proof true
   855   |> finalize
   856   |> Seq.map finish_global;
   857 
   858 
   859 
   860 (** blocks **)
   861 
   862 (* begin_block *)
   863 
   864 fun begin_block state =
   865   state
   866   |> assert_forward
   867   |> new_block
   868   |> open_block;
   869 
   870 
   871 (* end_block *)
   872 
   873 fun end_block state =
   874   state
   875   |> assert_forward
   876   |> close_block
   877   |> assert_current_goal false
   878   |> close_block
   879   |> transfer_facts state;
   880 
   881 
   882 (* next_block *)
   883 
   884 fun next_block state =
   885   state
   886   |> assert_forward
   887   |> close_block
   888   |> new_block
   889   |> reset_facts;
   890 
   891 
   892 end;
   893 
   894 structure BasicProof: BASIC_PROOF = Proof;
   895 open BasicProof;