src/Pure/Isar/proof.ML
author wenzelm
Mon Jun 28 23:02:38 1999 +0200 (1999-06-28)
changeset 6853 80f88b762816
parent 6848 3d82756e1af5
child 6871 01866edde713
permissions -rw-r--r--
improved RANGE;
     1 (*  Title:      Pure/Isar/proof.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Proof states and methods.
     6 *)
     7 
     8 signature PROOF =
     9 sig
    10   type context
    11   type state
    12   exception STATE of string * state
    13   val context_of: state -> context
    14   val theory_of: state -> theory
    15   val sign_of: state -> Sign.sg
    16   val the_facts: state -> thm list
    17   val the_fact: state -> thm
    18   val goal_facts: (state -> thm list) -> state -> state
    19   val use_facts: state -> state
    20   val reset_facts: state -> state
    21   val assert_backward: state -> state
    22   val enter_forward: state -> state
    23   val verbose: bool ref
    24   val print_state: state -> unit
    25   val level: state -> int
    26   type method
    27   val method: (thm list -> tactic) -> method
    28   val refine: (context -> method) -> state -> state Seq.seq
    29   val bind: (indexname * string) list -> state -> state
    30   val bind_i: (indexname * term) list -> state -> state
    31   val match_bind: (string list * string) list -> state -> state
    32   val match_bind_i: (term list * term) list -> state -> state
    33   val have_thmss: string -> context attribute list ->
    34     (thm list * context attribute list) list -> state -> state
    35   val assume: (int -> tactic) -> string -> context attribute list -> (string * string list) list
    36     -> state -> state
    37   val assume_i: (int -> tactic) -> string -> context attribute list -> (term * term list) list
    38     -> state -> state
    39   val fix: (string * string option) list -> state -> state
    40   val fix_i: (string * typ) list -> state -> state
    41   val theorem: bstring -> theory attribute list -> string * string list -> theory -> state
    42   val theorem_i: bstring -> theory attribute list -> term * term list -> theory -> state
    43   val lemma: bstring -> theory attribute list -> string * string list -> theory -> state
    44   val lemma_i: bstring -> theory attribute list -> term * term list -> theory -> state
    45   val chain: state -> state
    46   val from_facts: thm list -> state -> state
    47   val show: string -> context attribute list -> string * string list -> state -> state
    48   val show_i: string -> context attribute list -> term * term list -> state -> state
    49   val have: string -> context attribute list -> string * string list -> state -> state
    50   val have_i: string -> context attribute list -> term * term list -> state -> state
    51   val begin_block: state -> state
    52   val next_block: state -> state
    53   val end_block: state -> state
    54   val at_bottom: state -> bool
    55   val local_qed: (state -> state Seq.seq) -> ({kind: string, name: string, thm: thm} -> unit)
    56     -> state -> state Seq.seq
    57   val global_qed: (state -> state Seq.seq) -> bstring option
    58     -> theory attribute list option -> state -> theory * {kind: string, name: string, thm: thm}
    59 end;
    60 
    61 signature PROOF_PRIVATE =
    62 sig
    63   include PROOF
    64   val put_data: Object.kind -> ('a -> Object.T) -> 'a -> state -> state
    65 end;
    66 
    67 structure Proof: PROOF_PRIVATE =
    68 struct
    69 
    70 
    71 (** proof state **)
    72 
    73 type context = ProofContext.context;
    74 
    75 
    76 (* type goal *)
    77 
    78 datatype kind =
    79   Theorem of theory attribute list |    (*top-level theorem*)
    80   Lemma of theory attribute list |      (*top-level lemma*)
    81   Goal of context attribute list |      (*intermediate result, solving subgoal*)
    82   Aux of context attribute list ;       (*intermediate result*)
    83 
    84 val kind_name =
    85   fn Theorem _ => "theorem" | Lemma _ => "lemma" | Goal _ => "show" | Aux _ => "have";
    86 
    87 type goal =
    88  (kind *               		(*result kind*)
    89   string *                      (*result name*)
    90   cterm list *			(*result assumptions*)
    91   (int -> tactic) list *      	(*tactics to solve result assumptions*)
    92   term) *                       (*result statement*)
    93  (thm list *                    (*use facts*)
    94   thm);                         (*goal: subgoals ==> statement*)
    95 
    96 
    97 (* type mode *)
    98 
    99 datatype mode = Forward | ForwardChain | Backward;
   100 
   101 val mode_name =
   102   enclose "`" "'" o
   103     (fn Forward => "state" | ForwardChain => "chain" | Backward => "prove");
   104 
   105 
   106 (* type node *)
   107 
   108 type node =
   109  {context: context,
   110   facts: thm list option,
   111   mode: mode,
   112   goal: goal option};
   113 
   114 fun make_node (context, facts, mode, goal) =
   115   {context = context, facts = facts, mode = mode, goal = goal}: node;
   116 
   117 
   118 (* datatype state *)
   119 
   120 datatype state =
   121   State of
   122     node *              (*current*)
   123     node list;          (*parents wrt. block structure*)
   124 
   125 exception STATE of string * state;
   126 
   127 fun err_malformed name state =
   128   raise STATE (name ^ ": internal error -- malformed proof state", state);
   129 
   130 
   131 fun map_current f (State ({context, facts, mode, goal}, nodes)) =
   132   State (make_node (f (context, facts, mode, goal)), nodes);
   133 
   134 fun init_state thy =
   135   State (make_node (ProofContext.init thy, None, Forward, None), []);
   136 
   137 
   138 
   139 (** basic proof state operations **)
   140 
   141 (* context *)
   142 
   143 fun context_of (State ({context, ...}, _)) = context;
   144 val theory_of = ProofContext.theory_of o context_of;
   145 val sign_of = ProofContext.sign_of o context_of;
   146 
   147 fun map_context f = map_current (fn (ctxt, facts, mode, goal) => (f ctxt, facts, mode, goal));
   148 
   149 fun map_context_result f (state as State ({context, facts, mode, goal}, nodes)) =
   150   let val (context', result) = f context
   151   in (State (make_node (context', facts, mode, goal), nodes), result) end;
   152 
   153 
   154 fun put_data kind f = map_context o ProofContext.put_data kind f;
   155 val declare_term = map_context o ProofContext.declare_term;
   156 val add_binds = map_context o ProofContext.add_binds_i;
   157 val auto_bind_goal = map_context o ProofContext.auto_bind_goal;
   158 val auto_bind_facts = map_context oo ProofContext.auto_bind_facts;
   159 val put_thms = map_context o ProofContext.put_thms;
   160 val put_thmss = map_context o ProofContext.put_thmss;
   161 
   162 
   163 (* facts *)
   164 
   165 fun the_facts (State ({facts = Some facts, ...}, _)) = facts
   166   | the_facts state = raise STATE ("No current facts available", state);
   167 
   168 fun the_fact state =
   169   (case the_facts state of
   170     [fact] => fact
   171   | _ => raise STATE ("Single fact expected", state));
   172 
   173 fun assert_facts state = (the_facts state; state);
   174 
   175 fun put_facts facts state =
   176   state
   177   |> map_current (fn (ctxt, _, mode, goal) => (ctxt, facts, mode, goal))
   178   |> put_thms ("facts", if_none facts []);
   179 
   180 val reset_facts = put_facts None;
   181 
   182 fun have_facts (name, facts) state =
   183   state
   184   |> put_facts (Some facts)
   185   |> put_thms (name, facts);
   186 
   187 fun these_facts (state, ths) = have_facts ths state;
   188 fun fetch_facts (State ({facts, ...}, _)) = put_facts facts;
   189 
   190 
   191 (* goal *)
   192 
   193 fun find_goal i (State ({goal = Some goal, ...}, _)) = (i, goal)
   194   | find_goal i (State ({goal = None, ...}, node :: nodes)) =
   195       find_goal (i + 1) (State (node, nodes))
   196   | find_goal _ (state as State (_, [])) = err_malformed "find_goal" state;
   197 
   198 fun put_goal goal = map_current (fn (ctxt, facts, mode, _) => (ctxt, facts, mode, goal));
   199 
   200 fun map_goal f (State ({context, facts, mode, goal = Some goal}, nodes)) =
   201       State (make_node (context, facts, mode, Some (f goal)), nodes)
   202   | map_goal f (State (nd, node :: nodes)) =
   203       let val State (node', nodes') = map_goal f (State (node, nodes))
   204       in State (nd, node' :: nodes') end
   205   | map_goal _ state = state;
   206 
   207 fun goal_facts get state =
   208   state
   209   |> map_goal (fn (result, (_, thm)) => (result, (get state, thm)));
   210 
   211 fun use_facts state =
   212   state
   213   |> goal_facts the_facts
   214   |> reset_facts;
   215 
   216 
   217 (* mode *)
   218 
   219 fun get_mode (State ({mode, ...}, _)) = mode;
   220 fun put_mode mode = map_current (fn (ctxt, facts, _, goal) => (ctxt, facts, mode, goal));
   221 
   222 val enter_forward = put_mode Forward;
   223 val enter_forward_chain = put_mode ForwardChain;
   224 val enter_backward = put_mode Backward;
   225 
   226 fun assert_mode pred state =
   227   let val mode = get_mode state in
   228     if pred mode then state
   229     else raise STATE ("Illegal application of proof command in " ^ mode_name mode ^ " mode", state)
   230   end;
   231 
   232 fun is_chain state = get_mode state = ForwardChain;
   233 val assert_forward = assert_mode (equal Forward);
   234 val assert_forward_or_chain = assert_mode (equal Forward orf equal ForwardChain);
   235 val assert_backward = assert_mode (equal Backward);
   236 
   237 
   238 (* blocks *)
   239 
   240 fun level (State (_, nodes)) = length nodes;
   241 
   242 fun open_block (State (node, nodes)) = State (node, node :: nodes);
   243 
   244 fun new_block state =
   245   state
   246   |> open_block
   247   |> put_goal None;
   248 
   249 fun close_block (State (_, node :: nodes)) = State (node, nodes)
   250   | close_block state = raise STATE ("Unbalanced block parentheses", state);
   251 
   252 
   253 
   254 (** print_state **)
   255 
   256 val verbose = ProofContext.verbose;
   257 
   258 fun print_facts _ None = ()
   259   | print_facts s (Some ths) =
   260       Pretty.writeln (Pretty.big_list (s ^ " facts:") (map Display.pretty_thm ths));
   261 
   262 fun print_state (state as State ({context, facts, mode, goal = _}, nodes)) =
   263   let
   264     val ref (_, _, begin_goal) = Goals.current_goals_markers;
   265 
   266     fun levels_up 0 = ""
   267       | levels_up i = " (" ^ string_of_int i ^ " levels up)";
   268 
   269     fun print_goal (i, ((kind, name, _, _, _), (goal_facts, thm))) =
   270       (print_facts "Using" (if null goal_facts then None else Some goal_facts);
   271         writeln (kind_name kind ^ " " ^ quote name ^ levels_up (i div 2) ^ ":");
   272         Locale.print_goals_marker begin_goal (! goals_limit) thm);
   273 
   274     val ctxt_strings = ProofContext.strings_of_context context;
   275   in
   276     writeln ("Nesting level: " ^ string_of_int (length nodes div 2));
   277     writeln "";
   278     writeln (mode_name mode ^ " mode");
   279     writeln "";
   280     if ! verbose orelse mode = Forward then
   281       (if null ctxt_strings then () else (seq writeln ctxt_strings; writeln "");
   282         print_facts "Current" facts;
   283         print_goal (find_goal 0 state))
   284     else if mode = ForwardChain then print_facts "Picking" facts
   285     else print_goal (find_goal 0 state)
   286   end;
   287 
   288 
   289 
   290 (** proof steps **)
   291 
   292 (* datatype method *)
   293 
   294 datatype method = Method of thm list -> tactic;
   295 val method = Method;
   296 
   297 
   298 (* refine goal *)
   299 
   300 fun check_sign sg state =
   301   if Sign.subsig (sg, sign_of state) then state
   302   else raise STATE ("Bad signature of result: " ^ Sign.str_of_sg sg, state);
   303 
   304 fun refine meth_fun (state as State ({context, ...}, _)) =
   305   let
   306     val Method meth = meth_fun context;
   307     val (_, (result, (facts, thm))) = find_goal 0 state;
   308 
   309     fun refn thm' =
   310       state
   311       |> check_sign (Thm.sign_of_thm thm')
   312       |> map_goal (K (result, (facts, thm')));
   313   in Seq.map refn (meth facts thm) end;
   314 
   315 
   316 (* prepare result *)
   317 
   318 fun varify_frees names thm =
   319   let
   320     fun get_free x (None, t as Free (y, _)) = if x = y then Some t else None
   321       | get_free _ (opt, _) = opt;
   322 
   323     fun find_free t x = foldl_aterms (get_free x) (None, t);
   324 
   325     val {sign, maxidx, prop, ...} = Thm.rep_thm thm;
   326     val frees = map (Thm.cterm_of sign) (mapfilter (find_free prop) names);
   327   in
   328     thm
   329     |> Drule.forall_intr_list frees
   330     |> Drule.forall_elim_vars (maxidx + 1)
   331   end;
   332 
   333 fun varify_tfrees thm =
   334   let
   335     val {hyps, prop, ...} = Thm.rep_thm thm;
   336     val frees = foldr Term.add_term_frees (prop :: hyps, []);
   337     val leave_tfrees = foldr Term.add_term_tfree_names (frees, []);
   338   in thm |> Thm.varifyT' leave_tfrees end;
   339 
   340 fun implies_elim_hyps thm =
   341   foldl (uncurry Thm.implies_elim) (thm, map Thm.assume (Drule.cprems_of thm));
   342 
   343 
   344 fun prep_result state asms t raw_thm =
   345   let
   346     val ctxt = context_of state;
   347     fun err msg = raise STATE (msg, state);
   348 
   349     val ngoals = Thm.nprems_of raw_thm;
   350     val _ =
   351       if ngoals = 0 then ()
   352       else (Locale.print_goals ngoals raw_thm; err (string_of_int ngoals ^ " unsolved goal(s)!"));
   353 
   354     val thm =
   355       raw_thm RS Drule.rev_triv_goal
   356       |> implies_elim_hyps
   357       |> Drule.implies_intr_list asms
   358       |> varify_frees (ProofContext.fixed_names ctxt)
   359       |> varify_tfrees;
   360 
   361     val {hyps, prop, sign, ...} = Thm.rep_thm thm;
   362     val tsig = Sign.tsig_of sign;
   363   in
   364 (* FIXME
   365     if not (Pattern.matches tsig (t, Logic.skip_flexpairs prop)) then
   366       warning ("Proved a different theorem: " ^ Sign.string_of_term sign prop)
   367     else ();
   368 *)
   369     if not (null hyps) then
   370       err ("Additional hypotheses:\n" ^ cat_lines (map (Sign.string_of_term sign) hyps))
   371 (* FIXME    else if not (Pattern.matches tsig (t, Logic.skip_flexpairs prop)) then
   372       err ("Proved a different theorem: " ^ Sign.string_of_term sign prop) *)
   373     else (thm, prop)
   374   end;
   375 
   376 
   377 (* prepare final result *)
   378 
   379 fun strip_flexflex thm =
   380   Seq.hd (Thm.flexflex_rule thm) handle THM _ => thm;
   381 
   382 fun final_result state pre_thm =
   383   let
   384     val thm =
   385       pre_thm
   386       |> strip_flexflex
   387       |> Thm.strip_shyps
   388       |> Drule.standard;
   389 
   390     val str_of_sort = Sign.str_of_sort (Thm.sign_of_thm thm);
   391     val xshyps = Thm.extra_shyps thm;
   392   in
   393     if not (null xshyps) then
   394       raise STATE ("Extra sort hypotheses: " ^ commas (map str_of_sort xshyps), state)
   395     else thm
   396   end;
   397 
   398 
   399 (* solve goal *)
   400 
   401 fun RANGE [] _ = all_tac
   402   | RANGE (tac :: tacs) i = RANGE tacs (i + 1) THEN tac i;
   403 
   404 fun solve_goal rule tacs state =
   405   let
   406     val (_, (result, (facts, thm))) = find_goal 0 state;
   407     val thms' = FIRSTGOAL (rtac rule THEN' RANGE tacs) thm;
   408   in Seq.map (fn thm' => map_goal (K (result, (facts, thm'))) state) thms' end;
   409 
   410 
   411 
   412 (*** structured proof commands ***)
   413 
   414 (** context **)
   415 
   416 (* bind *)
   417 
   418 fun gen_bind f x state =
   419   state
   420   |> assert_forward
   421   |> map_context (f x)
   422   |> reset_facts;
   423 
   424 val bind = gen_bind ProofContext.add_binds;
   425 val bind_i = gen_bind ProofContext.add_binds_i;
   426 
   427 val match_bind = gen_bind ProofContext.match_binds;
   428 val match_bind_i = gen_bind ProofContext.match_binds_i;
   429 
   430 
   431 (* have_thmss *)
   432 
   433 fun have_thmss name atts ths_atts state =
   434   state
   435   |> assert_forward
   436   |> map_context_result (ProofContext.have_thmss (PureThy.default_name name) atts ths_atts)
   437   |> these_facts;
   438 
   439 
   440 (* fix *)
   441 
   442 fun gen_fix f xs state =
   443   state
   444   |> assert_forward
   445   |> map_context (f xs)
   446   |> reset_facts;
   447 
   448 val fix = gen_fix ProofContext.fix;
   449 val fix_i = gen_fix ProofContext.fix_i;
   450 
   451 
   452 (* assume *)
   453 
   454 fun gen_assume f tac name atts props state =
   455   state
   456   |> assert_forward
   457   |> map_context_result (f tac (PureThy.default_name name) atts props)
   458   |> (fn (st, (facts, prems)) =>
   459     (st, facts)
   460     |> these_facts
   461     |> put_thms ("prems", prems));
   462 
   463 val assume = gen_assume ProofContext.assume;
   464 val assume_i = gen_assume ProofContext.assume_i;
   465 
   466 
   467 
   468 (** goals **)
   469 
   470 (* forward chaining *)
   471 
   472 fun chain state =
   473   state
   474   |> assert_forward
   475   |> assert_facts
   476   |> enter_forward_chain;
   477 
   478 fun from_facts facts state =
   479   state
   480   |> put_facts (Some facts)
   481   |> chain;
   482 
   483 
   484 (* setup goals *)
   485 
   486 fun setup_goal opt_block prepp kind name atts raw_propp state =
   487   let
   488     val (state', concl) =
   489       state
   490       |> assert_forward_or_chain
   491       |> enter_forward
   492       |> opt_block
   493       |> map_context_result (fn c => prepp (c, raw_propp));
   494     val cterm_of = Thm.cterm_of (sign_of state);
   495 
   496     val (casms, asm_tacs) = Library.split_list (ProofContext.assumptions (context_of state'));
   497     val cprems = map cterm_of (Logic.strip_imp_prems concl);
   498     val prem_tacs = replicate (length cprems) (K all_tac);
   499 
   500     val prop = Logic.list_implies (map Thm.term_of casms, concl);
   501     val cprop = cterm_of prop;
   502     val thm = Drule.mk_triv_goal cprop;
   503   in
   504     state'
   505     |> put_goal (Some ((kind atts, (PureThy.default_name name), casms @ cprems,
   506         asm_tacs @ prem_tacs, prop), ([], thm)))
   507     |> auto_bind_goal prop
   508     |> (if is_chain state then use_facts else reset_facts)
   509     |> new_block
   510     |> enter_backward
   511   end;
   512 
   513 
   514 (*global goals*)
   515 fun global_goal prep kind name atts x thy =
   516   setup_goal I prep kind name atts x (init_state thy);
   517 
   518 val theorem = global_goal ProofContext.bind_propp Theorem;
   519 val theorem_i = global_goal ProofContext.bind_propp_i Theorem;
   520 val lemma = global_goal ProofContext.bind_propp Lemma;
   521 val lemma_i = global_goal ProofContext.bind_propp_i Lemma;
   522 
   523 
   524 (*local goals*)
   525 fun local_goal prep kind name atts x =
   526   setup_goal open_block prep kind name atts x;
   527 
   528 val show   = local_goal ProofContext.bind_propp Goal;
   529 val show_i = local_goal ProofContext.bind_propp_i Goal;
   530 val have   = local_goal ProofContext.bind_propp Aux;
   531 val have_i = local_goal ProofContext.bind_propp_i Aux;
   532 
   533 
   534 
   535 (** blocks **)
   536 
   537 (* begin_block *)
   538 
   539 fun begin_block state =
   540   state
   541   |> assert_forward
   542   |> new_block
   543   |> reset_facts
   544   |> open_block;
   545 
   546 
   547 (* next_block *)
   548 
   549 fun next_block state =
   550   state
   551   |> assert_forward
   552   |> close_block
   553   |> new_block;
   554 
   555 
   556 
   557 (** conclusions **)
   558 
   559 (* current goal *)
   560 
   561 fun current_goal (State ({goal = Some goal, ...}, _)) = goal
   562   | current_goal state = raise STATE ("No current goal!", state);
   563 
   564 fun assert_current_goal true (state as State ({goal = None, ...}, _)) =
   565       raise STATE ("No goal in this block!", state)
   566   | assert_current_goal false (state as State ({goal = Some _, ...}, _)) =
   567       raise STATE ("Goal present in this block!", state)
   568   | assert_current_goal _ state = state;
   569 
   570 fun assert_bottom true (state as State (_, _ :: _)) =
   571       raise STATE ("Not at bottom of proof!", state)
   572   | assert_bottom false (state as State (_, [])) =
   573       raise STATE ("Already at bottom of proof!", state)
   574   | assert_bottom _ state = state;
   575 
   576 val at_bottom = can (assert_bottom true o close_block);
   577 
   578 
   579 (* finish proof *)
   580 
   581 fun check_finished state states =
   582   (case Seq.pull states of
   583     None => raise STATE ("Failed to finish proof", state)
   584   | Some s_sq => Seq.cons s_sq);
   585 
   586 fun finish_proof bot finalize state =
   587   state
   588   |> assert_forward
   589   |> close_block
   590   |> assert_bottom bot
   591   |> assert_current_goal true
   592   |> finalize
   593   |> check_finished state;
   594 
   595 
   596 (* end_block *)
   597 
   598 fun end_block state =
   599   state
   600   |> assert_forward
   601   |> close_block
   602   |> assert_current_goal false
   603   |> close_block
   604   |> fetch_facts state;
   605 
   606 
   607 (* local_qed *)
   608 
   609 fun finish_local print_result state =
   610   let
   611     val ((kind, name, asms, tacs, t), (_, raw_thm)) = current_goal state;
   612     val (result, result_prop) = prep_result state asms t raw_thm;
   613     val (atts, opt_solve) =
   614       (case kind of
   615         Goal atts => (atts, solve_goal result tacs)
   616       | Aux atts => (atts, Seq.single)
   617       | _ => raise STATE ("No local goal!", state));
   618   in
   619     print_result {kind = kind_name kind, name = name, thm = result};
   620     state
   621     |> close_block
   622     |> auto_bind_facts name [result_prop]
   623     |> have_thmss name atts [Thm.no_attributes [result]]
   624     |> opt_solve
   625   end;
   626 
   627 fun local_qed finalize print_result state =
   628   state
   629   |> finish_proof false finalize
   630   |> (Seq.flat o Seq.map (finish_local print_result));
   631 
   632 
   633 (* global_qed *)
   634 
   635 fun finish_global alt_name alt_atts state =
   636   let
   637     val ((kind, def_name, asms, _, t), (_, raw_thm)) = current_goal state;
   638     val result = final_result state (#1 (prep_result state asms t raw_thm));
   639 
   640     val name = if_none alt_name def_name;
   641     val atts =
   642       (case kind of
   643         Theorem atts => if_none alt_atts atts
   644       | Lemma atts => (if_none alt_atts atts) @ [Drule.tag_lemma]
   645       | _ => raise STATE ("No global goal!", state));
   646 
   647     val (thy', result') = PureThy.store_thm ((name, result), atts) (theory_of state);
   648   in (thy', {kind = kind_name kind, name = name, thm = result'}) end;
   649 
   650 fun global_qed finalize alt_name alt_atts state =
   651   state
   652   |> finish_proof true finalize
   653   |> Seq.hd
   654   |> finish_global alt_name alt_atts;
   655 
   656 
   657 end;