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