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