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