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