src/Pure/Isar/proof.ML
author wenzelm
Mon Jun 28 21:46:33 1999 +0200 (1999-06-28)
changeset 6848 3d82756e1af5
parent 6798 f6bc583a5776
child 6853 80f88b762816
permissions -rw-r--r--
tuned print_state;
datatype method = Method of thm list -> tactic;
assumptions: back-pressure solver as parameter;
     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 REV_RANGE _ [] = all_tac
   402   | REV_RANGE k (tac :: tacs) = tac k THEN REV_RANGE (k - 1) tacs;
   403 
   404 fun solve_goal rule tacs state =
   405   let
   406     val rev_tacs = rev tacs;
   407     val n = length rev_tacs - 1;
   408 
   409     val (_, (result, (facts, thm))) = find_goal 0 state;
   410     val thms' = FIRSTGOAL (rtac rule THEN' (fn i => REV_RANGE (i + n) rev_tacs)) thm;
   411   in Seq.map (fn thm' => map_goal (K (result, (facts, thm'))) state) thms' end;
   412 
   413 
   414 
   415 (*** structured proof commands ***)
   416 
   417 (** context **)
   418 
   419 (* bind *)
   420 
   421 fun gen_bind f x state =
   422   state
   423   |> assert_forward
   424   |> map_context (f x)
   425   |> reset_facts;
   426 
   427 val bind = gen_bind ProofContext.add_binds;
   428 val bind_i = gen_bind ProofContext.add_binds_i;
   429 
   430 val match_bind = gen_bind ProofContext.match_binds;
   431 val match_bind_i = gen_bind ProofContext.match_binds_i;
   432 
   433 
   434 (* have_thmss *)
   435 
   436 fun have_thmss name atts ths_atts state =
   437   state
   438   |> assert_forward
   439   |> map_context_result (ProofContext.have_thmss (PureThy.default_name name) atts ths_atts)
   440   |> these_facts;
   441 
   442 
   443 (* fix *)
   444 
   445 fun gen_fix f xs state =
   446   state
   447   |> assert_forward
   448   |> map_context (f xs)
   449   |> reset_facts;
   450 
   451 val fix = gen_fix ProofContext.fix;
   452 val fix_i = gen_fix ProofContext.fix_i;
   453 
   454 
   455 (* assume *)
   456 
   457 fun gen_assume f tac name atts props state =
   458   state
   459   |> assert_forward
   460   |> map_context_result (f tac (PureThy.default_name name) atts props)
   461   |> (fn (st, (facts, prems)) =>
   462     (st, facts)
   463     |> these_facts
   464     |> put_thms ("prems", prems));
   465 
   466 val assume = gen_assume ProofContext.assume;
   467 val assume_i = gen_assume ProofContext.assume_i;
   468 
   469 
   470 
   471 (** goals **)
   472 
   473 (* forward chaining *)
   474 
   475 fun chain state =
   476   state
   477   |> assert_forward
   478   |> assert_facts
   479   |> enter_forward_chain;
   480 
   481 fun from_facts facts state =
   482   state
   483   |> put_facts (Some facts)
   484   |> chain;
   485 
   486 
   487 (* setup goals *)
   488 
   489 fun setup_goal opt_block prepp kind name atts raw_propp state =
   490   let
   491     val (state', concl) =
   492       state
   493       |> assert_forward_or_chain
   494       |> enter_forward
   495       |> opt_block
   496       |> map_context_result (fn c => prepp (c, raw_propp));
   497     val cterm_of = Thm.cterm_of (sign_of state);
   498 
   499     val (casms, asm_tacs) = Library.split_list (ProofContext.assumptions (context_of state'));
   500     val cprems = map cterm_of (Logic.strip_imp_prems concl);
   501     val prem_tacs = replicate (length cprems) (K all_tac);
   502 
   503     val prop = Logic.list_implies (map Thm.term_of casms, concl);
   504     val cprop = cterm_of prop;
   505     val thm = Drule.mk_triv_goal cprop;
   506   in
   507     state'
   508     |> put_goal (Some ((kind atts, (PureThy.default_name name), casms @ cprems,
   509         asm_tacs @ prem_tacs, prop), ([], thm)))
   510     |> auto_bind_goal prop
   511     |> (if is_chain state then use_facts else reset_facts)
   512     |> new_block
   513     |> enter_backward
   514   end;
   515 
   516 
   517 (*global goals*)
   518 fun global_goal prep kind name atts x thy =
   519   setup_goal I prep kind name atts x (init_state thy);
   520 
   521 val theorem = global_goal ProofContext.bind_propp Theorem;
   522 val theorem_i = global_goal ProofContext.bind_propp_i Theorem;
   523 val lemma = global_goal ProofContext.bind_propp Lemma;
   524 val lemma_i = global_goal ProofContext.bind_propp_i Lemma;
   525 
   526 
   527 (*local goals*)
   528 fun local_goal prep kind name atts x =
   529   setup_goal open_block prep kind name atts x;
   530 
   531 val show   = local_goal ProofContext.bind_propp Goal;
   532 val show_i = local_goal ProofContext.bind_propp_i Goal;
   533 val have   = local_goal ProofContext.bind_propp Aux;
   534 val have_i = local_goal ProofContext.bind_propp_i Aux;
   535 
   536 
   537 
   538 (** blocks **)
   539 
   540 (* begin_block *)
   541 
   542 fun begin_block state =
   543   state
   544   |> assert_forward
   545   |> new_block
   546   |> reset_facts
   547   |> open_block;
   548 
   549 
   550 (* next_block *)
   551 
   552 fun next_block state =
   553   state
   554   |> assert_forward
   555   |> close_block
   556   |> new_block;
   557 
   558 
   559 
   560 (** conclusions **)
   561 
   562 (* current goal *)
   563 
   564 fun current_goal (State ({goal = Some goal, ...}, _)) = goal
   565   | current_goal state = raise STATE ("No current goal!", state);
   566 
   567 fun assert_current_goal true (state as State ({goal = None, ...}, _)) =
   568       raise STATE ("No goal in this block!", state)
   569   | assert_current_goal false (state as State ({goal = Some _, ...}, _)) =
   570       raise STATE ("Goal present in this block!", state)
   571   | assert_current_goal _ state = state;
   572 
   573 fun assert_bottom true (state as State (_, _ :: _)) =
   574       raise STATE ("Not at bottom of proof!", state)
   575   | assert_bottom false (state as State (_, [])) =
   576       raise STATE ("Already at bottom of proof!", state)
   577   | assert_bottom _ state = state;
   578 
   579 val at_bottom = can (assert_bottom true o close_block);
   580 
   581 
   582 (* finish proof *)
   583 
   584 fun check_finished state states =
   585   (case Seq.pull states of
   586     None => raise STATE ("Failed to finish proof", state)
   587   | Some s_sq => Seq.cons s_sq);
   588 
   589 fun finish_proof bot finalize state =
   590   state
   591   |> assert_forward
   592   |> close_block
   593   |> assert_bottom bot
   594   |> assert_current_goal true
   595   |> finalize
   596   |> check_finished state;
   597 
   598 
   599 (* end_block *)
   600 
   601 fun end_block state =
   602   state
   603   |> assert_forward
   604   |> close_block
   605   |> assert_current_goal false
   606   |> close_block
   607   |> fetch_facts state;
   608 
   609 
   610 (* local_qed *)
   611 
   612 fun finish_local print_result state =
   613   let
   614     val ((kind, name, asms, tacs, t), (_, raw_thm)) = current_goal state;
   615     val (result, result_prop) = prep_result state asms t raw_thm;
   616     val (atts, opt_solve) =
   617       (case kind of
   618         Goal atts => (atts, solve_goal result tacs)
   619       | Aux atts => (atts, Seq.single)
   620       | _ => raise STATE ("No local goal!", state));
   621   in
   622     print_result {kind = kind_name kind, name = name, thm = result};
   623     state
   624     |> close_block
   625     |> auto_bind_facts name [result_prop]
   626     |> have_thmss name atts [Thm.no_attributes [result]]
   627     |> opt_solve
   628   end;
   629 
   630 fun local_qed finalize print_result state =
   631   state
   632   |> finish_proof false finalize
   633   |> (Seq.flat o Seq.map (finish_local print_result));
   634 
   635 
   636 (* global_qed *)
   637 
   638 fun finish_global alt_name alt_atts state =
   639   let
   640     val ((kind, def_name, asms, _, t), (_, raw_thm)) = current_goal state;
   641     val result = final_result state (#1 (prep_result state asms t raw_thm));
   642 
   643     val name = if_none alt_name def_name;
   644     val atts =
   645       (case kind of
   646         Theorem atts => if_none alt_atts atts
   647       | Lemma atts => (if_none alt_atts atts) @ [Drule.tag_lemma]
   648       | _ => raise STATE ("No global goal!", state));
   649 
   650     val (thy', result') = PureThy.store_thm ((name, result), atts) (theory_of state);
   651   in (thy', {kind = kind_name kind, name = name, thm = result'}) end;
   652 
   653 fun global_qed finalize alt_name alt_atts state =
   654   state
   655   |> finish_proof true finalize
   656   |> Seq.hd
   657   |> finish_global alt_name alt_atts;
   658 
   659 
   660 end;