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