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