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