src/Pure/Isar/proof.ML
author wenzelm
Fri Apr 27 22:47:30 2012 +0200 (2012-04-27 ago)
changeset 47815 43f677b3ae91
parent 47431 d9dd4a9f18fc
child 49011 9c68e43502ce
permissions -rw-r--r--
clarified signature;
     1 (*  Title:      Pure/Isar/proof.ML
     2     Author:     Markus Wenzel, TU Muenchen
     3 
     4 The Isar/VM proof language interpreter: maintains a structured flow of
     5 context elements, goals, refinements, and facts.
     6 *)
     7 
     8 signature PROOF =
     9 sig
    10   type context = Proof.context
    11   type method = Method.method
    12   type state
    13   val init: context -> state
    14   val level: state -> int
    15   val assert_bottom: bool -> state -> state
    16   val context_of: state -> context
    17   val theory_of: state -> theory
    18   val map_context: (context -> context) -> state -> state
    19   val map_context_result : (context -> 'a * context) -> state -> 'a * state
    20   val map_contexts: (context -> context) -> state -> state
    21   val propagate_ml_env: state -> state
    22   val bind_terms: (indexname * term option) list -> state -> state
    23   val put_thms: bool -> string * thm list option -> state -> state
    24   val the_facts: state -> thm list
    25   val the_fact: state -> thm
    26   val set_facts: thm list -> state -> state
    27   val reset_facts: state -> state
    28   val assert_forward: state -> state
    29   val assert_chain: state -> state
    30   val assert_forward_or_chain: state -> state
    31   val assert_backward: state -> state
    32   val assert_no_chain: state -> state
    33   val enter_forward: state -> state
    34   val goal_message: (unit -> Pretty.T) -> state -> state
    35   val pretty_state: int -> state -> Pretty.T list
    36   val pretty_goals: bool -> state -> Pretty.T list
    37   val refine: Method.text -> state -> state Seq.seq
    38   val refine_end: Method.text -> state -> state Seq.seq
    39   val refine_insert: thm list -> state -> state
    40   val refine_goals: (context -> thm -> unit) -> context -> thm list -> state -> state Seq.seq
    41   val raw_goal: state -> {context: context, facts: thm list, goal: thm}
    42   val goal: state -> {context: context, facts: thm list, goal: thm}
    43   val simple_goal: state -> {context: context, goal: thm}
    44   val status_markup: state -> Markup.T
    45   val let_bind: (term list * term) list -> state -> state
    46   val let_bind_cmd: (string list * string) list -> state -> state
    47   val write: Syntax.mode -> (term * mixfix) list -> state -> state
    48   val write_cmd: Syntax.mode -> (string * mixfix) list -> state -> state
    49   val fix: (binding * typ option * mixfix) list -> state -> state
    50   val fix_cmd: (binding * string option * mixfix) list -> state -> state
    51   val assm: Assumption.export ->
    52     (Thm.binding * (term * term list) list) list -> state -> state
    53   val assm_cmd: Assumption.export ->
    54     (Attrib.binding * (string * string list) list) list -> state -> state
    55   val assume: (Thm.binding * (term * term list) list) list -> state -> state
    56   val assume_cmd: (Attrib.binding * (string * string list) list) list -> state -> state
    57   val presume: (Thm.binding * (term * term list) list) list -> state -> state
    58   val presume_cmd: (Attrib.binding * (string * string list) list) list -> state -> state
    59   val def: (Thm.binding * ((binding * mixfix) * (term * term list))) list -> state -> state
    60   val def_cmd: (Attrib.binding * ((binding * mixfix) * (string * string list))) list -> state -> state
    61   val chain: state -> state
    62   val chain_facts: thm list -> state -> state
    63   val note_thmss: (Thm.binding * (thm list * attribute list) list) list -> state -> state
    64   val note_thmss_cmd: (Attrib.binding * (Facts.ref * Attrib.src list) list) list -> state -> state
    65   val from_thmss: ((thm list * attribute list) list) list -> state -> state
    66   val from_thmss_cmd: ((Facts.ref * Attrib.src list) list) list -> state -> state
    67   val with_thmss: ((thm list * attribute list) list) list -> state -> state
    68   val with_thmss_cmd: ((Facts.ref * Attrib.src list) list) list -> state -> state
    69   val using: ((thm list * attribute list) list) list -> state -> state
    70   val using_cmd: ((Facts.ref * Attrib.src list) list) list -> state -> state
    71   val unfolding: ((thm list * attribute list) list) list -> state -> state
    72   val unfolding_cmd: ((Facts.ref * Attrib.src list) list) list -> state -> state
    73   val invoke_case: string * binding option list * attribute list -> state -> state
    74   val invoke_case_cmd: string * binding option list * Attrib.src list -> state -> state
    75   val begin_block: state -> state
    76   val next_block: state -> state
    77   val end_block: state -> state
    78   val begin_notepad: Proof.context -> state
    79   val end_notepad: state -> Proof.context
    80   val proof: Method.text option -> state -> state Seq.seq
    81   val defer: int option -> state -> state Seq.seq
    82   val prefer: int -> state -> state Seq.seq
    83   val apply: Method.text -> state -> state Seq.seq
    84   val apply_end: Method.text -> state -> state Seq.seq
    85   val local_goal: (context -> ((string * string) * (string * thm list) list) -> unit) ->
    86     (Proof.context -> 'a -> attribute) ->
    87     ('b list -> context -> (term list list * (context -> context)) * context) ->
    88     string -> Method.text option -> (thm list list -> state -> state) ->
    89     ((binding * 'a list) * 'b) list -> state -> state
    90   val local_qed: Method.text option * bool -> state -> state
    91   val theorem: Method.text option -> (thm list list -> context -> context) ->
    92     (term * term list) list list -> context -> state
    93   val theorem_cmd: Method.text option -> (thm list list -> context -> context) ->
    94     (string * string list) list list -> context -> state
    95   val global_qed: Method.text option * bool -> state -> context
    96   val local_terminal_proof: Method.text * Method.text option -> state -> state
    97   val local_default_proof: state -> state
    98   val local_immediate_proof: state -> state
    99   val local_skip_proof: bool -> state -> state
   100   val local_done_proof: state -> state
   101   val global_terminal_proof: Method.text * Method.text option -> state -> context
   102   val global_default_proof: state -> context
   103   val global_immediate_proof: state -> context
   104   val global_skip_proof: bool -> state -> context
   105   val global_done_proof: state -> context
   106   val have: Method.text option -> (thm list list -> state -> state) ->
   107     (Thm.binding * (term * term list) list) list -> bool -> state -> state
   108   val have_cmd: Method.text option -> (thm list list -> state -> state) ->
   109     (Attrib.binding * (string * string list) list) list -> bool -> state -> state
   110   val show: Method.text option -> (thm list list -> state -> state) ->
   111     (Thm.binding * (term * term list) list) list -> bool -> state -> state
   112   val show_cmd: Method.text option -> (thm list list -> state -> state) ->
   113     (Attrib.binding * (string * string list) list) list -> bool -> state -> state
   114   val schematic_goal: state -> bool
   115   val local_future_proof: (state -> ('a * state) future) -> state -> 'a future * state
   116   val global_future_proof: (state -> ('a * Proof.context) future) -> state -> 'a future * context
   117   val local_future_terminal_proof: Method.text * Method.text option -> bool -> state -> state
   118   val global_future_terminal_proof: Method.text * Method.text option -> bool -> state -> context
   119 end;
   120 
   121 structure Proof: PROOF =
   122 struct
   123 
   124 type context = Proof.context;
   125 type method = Method.method;
   126 
   127 
   128 (** proof state **)
   129 
   130 (* datatype state *)
   131 
   132 datatype mode = Forward | Chain | Backward;
   133 
   134 datatype state =
   135   State of node Stack.T
   136 and node =
   137   Node of
   138    {context: context,
   139     facts: thm list option,
   140     mode: mode,
   141     goal: goal option}
   142 and goal =
   143   Goal of
   144    {statement: (string * Position.T) * term list list * term,
   145       (*goal kind and statement (starting with vars), initial proposition*)
   146     messages: (unit -> Pretty.T) list,    (*persistent messages (hints etc.)*)
   147     using: thm list,                      (*goal facts*)
   148     goal: thm,                            (*subgoals ==> statement*)
   149     before_qed: Method.text option,
   150     after_qed:
   151       (thm list list -> state -> state) *
   152       (thm list list -> context -> context)};
   153 
   154 fun make_goal (statement, messages, using, goal, before_qed, after_qed) =
   155   Goal {statement = statement, messages = messages, using = using, goal = goal,
   156     before_qed = before_qed, after_qed = after_qed};
   157 
   158 fun make_node (context, facts, mode, goal) =
   159   Node {context = context, facts = facts, mode = mode, goal = goal};
   160 
   161 fun map_node f (Node {context, facts, mode, goal}) =
   162   make_node (f (context, facts, mode, goal));
   163 
   164 val init_context =
   165   Proof_Context.set_stmt true #>
   166   Proof_Context.map_naming (K Name_Space.local_naming);
   167 
   168 fun init ctxt =
   169   State (Stack.init (make_node (init_context ctxt, NONE, Forward, NONE)));
   170 
   171 fun current (State st) = Stack.top st |> (fn Node node => node);
   172 fun map_current f (State st) = State (Stack.map_top (map_node f) st);
   173 fun map_all f (State st) = State (Stack.map_all (map_node f) st);
   174 
   175 
   176 
   177 (** basic proof state operations **)
   178 
   179 (* block structure *)
   180 
   181 fun open_block (State st) = State (Stack.push st);
   182 
   183 fun close_block (State st) = State (Stack.pop st)
   184   handle List.Empty => error "Unbalanced block parentheses";
   185 
   186 fun level (State st) = Stack.level st;
   187 
   188 fun assert_bottom b state =
   189   let val b' = level state <= 2 in
   190     if b andalso not b' then error "Not at bottom of proof"
   191     else if not b andalso b' then error "Already at bottom of proof"
   192     else state
   193   end;
   194 
   195 
   196 (* context *)
   197 
   198 val context_of = #context o current;
   199 val theory_of = Proof_Context.theory_of o context_of;
   200 
   201 fun map_node_context f =
   202   map_node (fn (ctxt, facts, mode, goal) => (f ctxt, facts, mode, goal));
   203 
   204 fun map_context f =
   205   map_current (fn (ctxt, facts, mode, goal) => (f ctxt, facts, mode, goal));
   206 
   207 fun map_context_result f state =
   208   f (context_of state) ||> (fn ctxt => map_context (K ctxt) state);
   209 
   210 fun map_contexts f = map_all (fn (ctxt, facts, mode, goal) => (f ctxt, facts, mode, goal));
   211 
   212 fun propagate_ml_env state = map_contexts
   213   (Context.proof_map (ML_Env.inherit (Context.Proof (context_of state)))) state;
   214 
   215 val bind_terms = map_context o Proof_Context.bind_terms;
   216 val put_thms = map_context oo Proof_Context.put_thms;
   217 
   218 
   219 (* facts *)
   220 
   221 val get_facts = #facts o current;
   222 
   223 fun the_facts state =
   224   (case get_facts state of SOME facts => facts
   225   | NONE => error "No current facts available");
   226 
   227 fun the_fact state =
   228   (case the_facts state of [thm] => thm
   229   | _ => error "Single theorem expected");
   230 
   231 fun put_facts facts =
   232   map_current (fn (ctxt, _, mode, goal) => (ctxt, facts, mode, goal)) #>
   233   put_thms true (Auto_Bind.thisN, facts);
   234 
   235 val set_facts = put_facts o SOME;
   236 val reset_facts = put_facts NONE;
   237 
   238 fun these_factss more_facts (named_factss, state) =
   239   (named_factss, state |> set_facts (maps snd named_factss @ more_facts));
   240 
   241 fun export_facts inner outer =
   242   (case get_facts inner of
   243     NONE => reset_facts outer
   244   | SOME thms =>
   245       thms
   246       |> Proof_Context.export (context_of inner) (context_of outer)
   247       |> (fn ths => set_facts ths outer));
   248 
   249 
   250 (* mode *)
   251 
   252 val get_mode = #mode o current;
   253 fun put_mode mode = map_current (fn (ctxt, facts, _, goal) => (ctxt, facts, mode, goal));
   254 
   255 val mode_name = (fn Forward => "state" | Chain => "chain" | Backward => "prove");
   256 
   257 fun assert_mode pred state =
   258   let val mode = get_mode state in
   259     if pred mode then state
   260     else error ("Illegal application of proof command in " ^ quote (mode_name mode) ^ " mode")
   261   end;
   262 
   263 val assert_forward = assert_mode (fn mode => mode = Forward);
   264 val assert_chain = assert_mode (fn mode => mode = Chain);
   265 val assert_forward_or_chain = assert_mode (fn mode => mode = Forward orelse mode = Chain);
   266 val assert_backward = assert_mode (fn mode => mode = Backward);
   267 val assert_no_chain = assert_mode (fn mode => mode <> Chain);
   268 
   269 val enter_forward = put_mode Forward;
   270 val enter_chain = put_mode Chain;
   271 val enter_backward = put_mode Backward;
   272 
   273 
   274 (* current goal *)
   275 
   276 fun current_goal state =
   277   (case current state of
   278     {context, goal = SOME (Goal goal), ...} => (context, goal)
   279   | _ => error "No current goal");
   280 
   281 fun assert_current_goal g state =
   282   let val g' = can current_goal state in
   283     if g andalso not g' then error "No goal in this block"
   284     else if not g andalso g' then error "Goal present in this block"
   285     else state
   286   end;
   287 
   288 fun put_goal goal = map_current (fn (ctxt, using, mode, _) => (ctxt, using, mode, goal));
   289 
   290 val set_goal = put_goal o SOME;
   291 val reset_goal = put_goal NONE;
   292 
   293 val before_qed = #before_qed o #2 o current_goal;
   294 
   295 
   296 (* nested goal *)
   297 
   298 fun map_goal f g h (State (Node {context, facts, mode, goal = SOME goal}, node :: nodes)) =
   299       let
   300         val Goal {statement, messages, using, goal, before_qed, after_qed} = goal;
   301         val goal' = make_goal (g (statement, messages, using, goal, before_qed, after_qed));
   302         val node' = map_node_context h node;
   303       in State (make_node (f context, facts, mode, SOME goal'), node' :: nodes) end
   304   | map_goal f g h (State (nd, node :: nodes)) =
   305       let
   306         val nd' = map_node_context f nd;
   307         val State (node', nodes') = map_goal f g h (State (node, nodes));
   308       in State (nd', node' :: nodes') end
   309   | map_goal _ _ _ state = state;
   310 
   311 fun provide_goal goal = map_goal I (fn (statement, _, using, _, before_qed, after_qed) =>
   312   (statement, [], using, goal, before_qed, after_qed)) I;
   313 
   314 fun goal_message msg = map_goal I (fn (statement, messages, using, goal, before_qed, after_qed) =>
   315   (statement, msg :: messages, using, goal, before_qed, after_qed)) I;
   316 
   317 fun using_facts using = map_goal I (fn (statement, _, _, goal, before_qed, after_qed) =>
   318   (statement, [], using, goal, before_qed, after_qed)) I;
   319 
   320 local
   321   fun find i state =
   322     (case try current_goal state of
   323       SOME (ctxt, goal) => (ctxt, (i, goal))
   324     | NONE => find (i + 1) (close_block state handle ERROR _ => error "No goal present"));
   325 in val find_goal = find 0 end;
   326 
   327 fun get_goal state =
   328   let val (ctxt, (_, {using, goal, ...})) = find_goal state
   329   in (ctxt, (using, goal)) end;
   330 
   331 
   332 
   333 (** pretty_state **)
   334 
   335 fun pretty_facts _ _ NONE = []
   336   | pretty_facts s ctxt (SOME ths) =
   337       [Pretty.big_list (s ^ "this:") (map (Display.pretty_thm ctxt) ths), Pretty.str ""];
   338 
   339 fun pretty_state nr state =
   340   let
   341     val {context = ctxt, facts, mode, goal = _} = current state;
   342     val verbose = Config.get ctxt Proof_Context.verbose;
   343 
   344     fun levels_up 0 = ""
   345       | levels_up 1 = "1 level up"
   346       | levels_up i = string_of_int i ^ " levels up";
   347 
   348     fun subgoals 0 = ""
   349       | subgoals 1 = "1 subgoal"
   350       | subgoals n = string_of_int n ^ " subgoals";
   351 
   352     fun description strs =
   353       (case filter_out (fn s => s = "") strs of [] => ""
   354       | strs' => enclose " (" ")" (commas strs'));
   355 
   356     fun prt_goal (SOME (_, (i,
   357       {statement = ((_, pos), _, _), messages, using, goal, before_qed = _, after_qed = _}))) =
   358           pretty_facts "using " ctxt
   359             (if mode <> Backward orelse null using then NONE else SOME using) @
   360           [Pretty.str ("goal" ^
   361             description [levels_up (i div 2), subgoals (Thm.nprems_of goal)] ^ ":")] @
   362           Goal_Display.pretty_goals ctxt goal @
   363           (map (fn msg => Position.setmp_thread_data pos msg ()) (rev messages))
   364       | prt_goal NONE = [];
   365 
   366     val prt_ctxt =
   367       if verbose orelse mode = Forward then Proof_Context.pretty_context ctxt
   368       else if mode = Backward then Proof_Context.pretty_ctxt ctxt
   369       else [];
   370   in
   371     [Pretty.str ("proof (" ^ mode_name mode ^ "): step " ^ string_of_int nr ^
   372       (if verbose then ", depth " ^ string_of_int (level state div 2 - 1) else "")),
   373       Pretty.str ""] @
   374     (if null prt_ctxt then [] else prt_ctxt @ [Pretty.str ""]) @
   375     (if verbose orelse mode = Forward then
   376        pretty_facts "" ctxt facts @ prt_goal (try find_goal state)
   377      else if mode = Chain then pretty_facts "picking " ctxt facts
   378      else prt_goal (try find_goal state))
   379   end;
   380 
   381 fun pretty_goals main state =
   382   let
   383     val (_, (_, goal)) = get_goal state;
   384     val ctxt = context_of state
   385       |> Config.put Goal_Display.show_main_goal main
   386       |> Config.put Goal_Display.goals_total false;
   387   in Goal_Display.pretty_goals ctxt goal end;
   388 
   389 
   390 
   391 (** proof steps **)
   392 
   393 (* refine via method *)
   394 
   395 local
   396 
   397 fun goalN i = "goal" ^ string_of_int i;
   398 fun goals st = map goalN (1 upto Thm.nprems_of st);
   399 
   400 fun no_goal_cases st = map (rpair NONE) (goals st);
   401 
   402 fun goal_cases st =
   403   Rule_Cases.make_common
   404     (Thm.theory_of_thm st, Thm.prop_of st) (map (rpair [] o rpair []) (goals st));
   405 
   406 fun apply_method current_context meth state =
   407   let
   408     val (goal_ctxt, (_, {statement, messages = _, using, goal, before_qed, after_qed})) =
   409       find_goal state;
   410     val ctxt = if current_context then context_of state else goal_ctxt;
   411   in
   412     Method.apply meth ctxt using goal |> Seq.map (fn (meth_cases, goal') =>
   413       state
   414       |> map_goal
   415           (Proof_Context.add_cases false (no_goal_cases goal @ goal_cases goal') #>
   416            Proof_Context.add_cases true meth_cases)
   417           (K (statement, [], using, goal', before_qed, after_qed)) I)
   418   end;
   419 
   420 fun select_goals n meth state =
   421   state
   422   |> (#2 o #2 o get_goal)
   423   |> ALLGOALS Goal.conjunction_tac
   424   |> Seq.maps (fn goal =>
   425     state
   426     |> Seq.lift provide_goal (Goal.extract 1 n goal |> Seq.maps (Goal.conjunction_tac 1))
   427     |> Seq.maps meth
   428     |> Seq.maps (fn state' => state'
   429       |> Seq.lift provide_goal (Goal.retrofit 1 n (#2 (#2 (get_goal state'))) goal))
   430     |> Seq.maps (apply_method true (K Method.succeed)));
   431 
   432 fun apply_text cc text state =
   433   let
   434     val thy = theory_of state;
   435 
   436     fun eval (Method.Basic m) = apply_method cc m
   437       | eval (Method.Source src) = apply_method cc (Method.method thy src)
   438       | eval (Method.Source_i src) = apply_method cc (Method.method_i thy src)
   439       | eval (Method.Then txts) = Seq.EVERY (map eval txts)
   440       | eval (Method.Orelse txts) = Seq.FIRST (map eval txts)
   441       | eval (Method.Try txt) = Seq.TRY (eval txt)
   442       | eval (Method.Repeat1 txt) = Seq.REPEAT1 (eval txt)
   443       | eval (Method.SelectGoals (n, txt)) = select_goals n (eval txt);
   444   in eval text state end;
   445 
   446 in
   447 
   448 val refine = apply_text true;
   449 val refine_end = apply_text false;
   450 fun refine_insert ths = Seq.hd o refine (Method.Basic (K (Method.insert ths)));
   451 
   452 end;
   453 
   454 
   455 (* refine via sub-proof *)
   456 
   457 local
   458 
   459 fun finish_tac 0 = K all_tac
   460   | finish_tac n =
   461       Goal.norm_hhf_tac THEN'
   462       SUBGOAL (fn (goal, i) =>
   463         if can Logic.unprotect (Logic.strip_assums_concl goal) then
   464           Tactic.etac Drule.protectI i THEN finish_tac (n - 1) i
   465         else finish_tac (n - 1) (i + 1));
   466 
   467 fun goal_tac rule =
   468   Goal.norm_hhf_tac THEN'
   469   Tactic.rtac rule THEN'
   470   finish_tac (Thm.nprems_of rule);
   471 
   472 fun FINDGOAL tac st =
   473   let fun find i n = if i > n then Seq.fail else Seq.APPEND (tac i, find (i + 1) n)
   474   in find 1 (Thm.nprems_of st) st end;
   475 
   476 in
   477 
   478 fun refine_goals print_rule inner raw_rules state =
   479   let
   480     val (outer, (_, goal)) = get_goal state;
   481     fun refine rule st = (print_rule outer rule; FINDGOAL (goal_tac rule) st);
   482   in
   483     raw_rules
   484     |> Proof_Context.goal_export inner outer
   485     |> (fn rules => Seq.lift provide_goal (EVERY (map refine rules) goal) state)
   486   end;
   487 
   488 end;
   489 
   490 
   491 (* conclude_goal *)
   492 
   493 fun conclude_goal ctxt goal propss =
   494   let
   495     val thy = Proof_Context.theory_of ctxt;
   496     val string_of_term = Syntax.string_of_term ctxt;
   497     val string_of_thm = Display.string_of_thm ctxt;
   498 
   499     val ngoals = Thm.nprems_of goal;
   500     val _ = ngoals = 0 orelse error (Pretty.string_of (Pretty.chunks
   501       (Goal_Display.pretty_goals ctxt goal @
   502         [Pretty.str (string_of_int ngoals ^ " unsolved goal(s)")])));
   503 
   504     val extra_hyps = Assumption.extra_hyps ctxt goal;
   505     val _ = null extra_hyps orelse
   506       error ("Additional hypotheses:\n" ^ cat_lines (map string_of_term extra_hyps));
   507 
   508     fun lost_structure () = error ("Lost goal structure:\n" ^ string_of_thm goal);
   509 
   510     val th = Goal.conclude
   511       (if length (flat propss) > 1 then Thm.norm_proof goal else goal)
   512       handle THM _ => lost_structure ();
   513     val goal_propss = filter_out null propss;
   514     val results =
   515       Conjunction.elim_balanced (length goal_propss) th
   516       |> map2 Conjunction.elim_balanced (map length goal_propss)
   517       handle THM _ => lost_structure ();
   518     val _ = Unify.matches_list thy (flat goal_propss) (map Thm.prop_of (flat results)) orelse
   519       error ("Proved a different theorem:\n" ^ string_of_thm th);
   520     val _ = Thm.check_shyps (Variable.sorts_of ctxt) th;
   521 
   522     fun recover_result ([] :: pss) thss = [] :: recover_result pss thss
   523       | recover_result (_ :: pss) (ths :: thss) = ths :: recover_result pss thss
   524       | recover_result [] [] = []
   525       | recover_result _ _ = lost_structure ();
   526   in recover_result propss results end;
   527 
   528 
   529 (* goal views -- corresponding to methods *)
   530 
   531 fun raw_goal state =
   532   let val (ctxt, (facts, goal)) = get_goal state
   533   in {context = ctxt, facts = facts, goal = goal} end;
   534 
   535 val goal = raw_goal o refine_insert [];
   536 
   537 fun simple_goal state =
   538   let
   539     val (_, (facts, _)) = get_goal state;
   540     val (ctxt, (_, goal)) = get_goal (refine_insert facts state);
   541   in {context = ctxt, goal = goal} end;
   542 
   543 fun status_markup state =
   544   (case try goal state of
   545     SOME {goal, ...} => Isabelle_Markup.proof_state (Thm.nprems_of goal)
   546   | NONE => Markup.empty);
   547 
   548 
   549 
   550 (*** structured proof commands ***)
   551 
   552 (** context elements **)
   553 
   554 (* let bindings *)
   555 
   556 local
   557 
   558 fun gen_bind bind args state =
   559   state
   560   |> assert_forward
   561   |> map_context (bind true args #> snd)
   562   |> reset_facts;
   563 
   564 in
   565 
   566 val let_bind = gen_bind Proof_Context.match_bind_i;
   567 val let_bind_cmd = gen_bind Proof_Context.match_bind;
   568 
   569 end;
   570 
   571 
   572 (* concrete syntax *)
   573 
   574 local
   575 
   576 fun gen_write prep_arg mode args =
   577   assert_forward
   578   #> map_context (fn ctxt => ctxt |> Proof_Context.notation true mode (map (prep_arg ctxt) args))
   579   #> reset_facts;
   580 
   581 in
   582 
   583 val write = gen_write (K I);
   584 
   585 val write_cmd =
   586   gen_write (fn ctxt => fn (c, mx) =>
   587     (Proof_Context.read_const ctxt false (Mixfix.mixfixT mx) c, mx));
   588 
   589 end;
   590 
   591 
   592 (* fix *)
   593 
   594 local
   595 
   596 fun gen_fix prep_vars args =
   597   assert_forward
   598   #> map_context (fn ctxt => snd (Proof_Context.add_fixes (fst (prep_vars args ctxt)) ctxt))
   599   #> reset_facts;
   600 
   601 in
   602 
   603 val fix = gen_fix Proof_Context.cert_vars;
   604 val fix_cmd = gen_fix Proof_Context.read_vars;
   605 
   606 end;
   607 
   608 
   609 (* assume etc. *)
   610 
   611 local
   612 
   613 fun gen_assume asm prep_att exp args state =
   614   state
   615   |> assert_forward
   616   |> map_context_result (asm exp (Attrib.map_specs (map (prep_att (context_of state))) args))
   617   |> these_factss [] |> #2;
   618 
   619 in
   620 
   621 val assm = gen_assume Proof_Context.add_assms_i (K I);
   622 val assm_cmd = gen_assume Proof_Context.add_assms Attrib.attribute_cmd;
   623 val assume = assm Assumption.assume_export;
   624 val assume_cmd = assm_cmd Assumption.assume_export;
   625 val presume = assm Assumption.presume_export;
   626 val presume_cmd = assm_cmd Assumption.presume_export;
   627 
   628 end;
   629 
   630 
   631 (* def *)
   632 
   633 local
   634 
   635 fun gen_def prep_att prep_vars prep_binds args state =
   636   let
   637     val _ = assert_forward state;
   638     val (raw_name_atts, (raw_vars, raw_rhss)) = args |> split_list ||> split_list;
   639     val name_atts = map (apsnd (map (prep_att (context_of state)))) raw_name_atts;
   640   in
   641     state
   642     |> map_context_result (prep_vars (map (fn (x, mx) => (x, NONE, mx)) raw_vars))
   643     |>> map (fn (x, _, mx) => (x, mx))
   644     |-> (fn vars =>
   645       map_context_result (prep_binds false (map swap raw_rhss))
   646       #-> (fn rhss => map_context_result (Local_Defs.add_defs (vars ~~ (name_atts ~~ rhss)))))
   647     |-> (set_facts o map (#2 o #2))
   648   end;
   649 
   650 in
   651 
   652 val def = gen_def (K I) Proof_Context.cert_vars Proof_Context.match_bind_i;
   653 val def_cmd = gen_def Attrib.attribute_cmd Proof_Context.read_vars Proof_Context.match_bind;
   654 
   655 end;
   656 
   657 
   658 
   659 (** facts **)
   660 
   661 (* chain *)
   662 
   663 fun clean_facts ctxt =
   664   set_facts (filter_out Thm.is_dummy (the_facts ctxt)) ctxt;
   665 
   666 val chain =
   667   assert_forward
   668   #> clean_facts
   669   #> enter_chain;
   670 
   671 fun chain_facts facts =
   672   set_facts facts
   673   #> chain;
   674 
   675 
   676 (* note etc. *)
   677 
   678 fun no_binding args = map (pair (Binding.empty, [])) args;
   679 
   680 local
   681 
   682 fun gen_thmss more_facts opt_chain opt_result prep_atts prep_fact args state =
   683   state
   684   |> assert_forward
   685   |> map_context_result (fn ctxt => ctxt |> Proof_Context.note_thmss ""
   686     (Attrib.map_facts_refs (map (prep_atts ctxt)) (prep_fact ctxt) args))
   687   |> these_factss (more_facts state)
   688   ||> opt_chain
   689   |> opt_result;
   690 
   691 in
   692 
   693 val note_thmss = gen_thmss (K []) I #2 (K I) (K I);
   694 val note_thmss_cmd = gen_thmss (K []) I #2 Attrib.attribute_cmd Proof_Context.get_fact;
   695 
   696 val from_thmss = gen_thmss (K []) chain #2 (K I) (K I) o no_binding;
   697 val from_thmss_cmd =
   698   gen_thmss (K []) chain #2 Attrib.attribute_cmd Proof_Context.get_fact o no_binding;
   699 
   700 val with_thmss = gen_thmss the_facts chain #2 (K I) (K I) o no_binding;
   701 val with_thmss_cmd =
   702   gen_thmss the_facts chain #2 Attrib.attribute_cmd Proof_Context.get_fact o no_binding;
   703 
   704 val local_results = gen_thmss (K []) I I (K I) (K I) o map (apsnd Thm.simple_fact);
   705 
   706 end;
   707 
   708 
   709 (* using/unfolding *)
   710 
   711 local
   712 
   713 fun gen_using f g prep_att prep_fact args state =
   714   state
   715   |> assert_backward
   716   |> map_context_result
   717     (fn ctxt => ctxt |> Proof_Context.note_thmss ""
   718       (Attrib.map_facts_refs (map (prep_att ctxt)) (prep_fact ctxt) (no_binding args)))
   719   |> (fn (named_facts, state') =>
   720     state' |> map_goal I (fn (statement, _, using, goal, before_qed, after_qed) =>
   721       let
   722         val ctxt = context_of state';
   723         val ths = maps snd named_facts;
   724       in (statement, [], f ctxt ths using, g ctxt ths goal, before_qed, after_qed) end) I);
   725 
   726 fun append_using _ ths using = using @ filter_out Thm.is_dummy ths;
   727 fun unfold_using ctxt ths = map (Local_Defs.unfold ctxt ths);
   728 val unfold_goals = Local_Defs.unfold_goals;
   729 
   730 in
   731 
   732 val using = gen_using append_using (K (K I)) (K I) (K I);
   733 val using_cmd = gen_using append_using (K (K I)) Attrib.attribute_cmd Proof_Context.get_fact;
   734 val unfolding = gen_using unfold_using unfold_goals (K I) (K I);
   735 val unfolding_cmd = gen_using unfold_using unfold_goals Attrib.attribute_cmd Proof_Context.get_fact;
   736 
   737 end;
   738 
   739 
   740 (* case *)
   741 
   742 local
   743 
   744 fun qualified_binding a =
   745   Binding.qualify true (Long_Name.qualifier a) (Binding.name (Long_Name.base_name a));
   746 
   747 fun gen_invoke_case prep_att (name, xs, raw_atts) state =
   748   let
   749     val atts = map (prep_att (context_of state)) raw_atts;
   750     val (asms, state') = state |> map_context_result (fn ctxt =>
   751       ctxt |> Proof_Context.apply_case (Proof_Context.get_case ctxt name xs));
   752     val assumptions = asms |> map (fn (a, ts) => ((qualified_binding a, atts), map (rpair []) ts));
   753   in
   754     state'
   755     |> assume assumptions
   756     |> bind_terms Auto_Bind.no_facts
   757     |> `the_facts |-> (fn thms => note_thmss [((Binding.name name, []), [(thms, [])])])
   758   end;
   759 
   760 in
   761 
   762 val invoke_case = gen_invoke_case (K I);
   763 val invoke_case_cmd = gen_invoke_case Attrib.attribute_cmd;
   764 
   765 end;
   766 
   767 
   768 
   769 (** proof structure **)
   770 
   771 (* blocks *)
   772 
   773 val begin_block =
   774   assert_forward
   775   #> open_block
   776   #> reset_goal
   777   #> open_block;
   778 
   779 val next_block =
   780   assert_forward
   781   #> close_block
   782   #> open_block
   783   #> reset_goal
   784   #> reset_facts;
   785 
   786 fun end_block state =
   787   state
   788   |> assert_forward
   789   |> assert_bottom false
   790   |> close_block
   791   |> assert_current_goal false
   792   |> close_block
   793   |> export_facts state;
   794 
   795 
   796 (* global notepad *)
   797 
   798 val begin_notepad =
   799   init
   800   #> open_block
   801   #> map_context (Variable.set_body true)
   802   #> open_block;
   803 
   804 val end_notepad =
   805   assert_forward
   806   #> assert_bottom true
   807   #> close_block
   808   #> assert_current_goal false
   809   #> close_block
   810   #> context_of;
   811 
   812 
   813 (* sub-proofs *)
   814 
   815 fun proof opt_text =
   816   assert_backward
   817   #> refine (the_default Method.default_text opt_text)
   818   #> Seq.map (using_facts [] #> enter_forward);
   819 
   820 fun end_proof bot txt state =
   821   state
   822   |> assert_forward
   823   |> assert_bottom bot
   824   |> close_block
   825   |> assert_current_goal true
   826   |> using_facts []
   827   |> `before_qed |-> (refine o the_default Method.succeed_text)
   828   |> Seq.maps (refine (Method.finish_text txt));
   829 
   830 fun check_result msg sq =
   831   (case Seq.pull sq of
   832     NONE => error msg
   833   | SOME (s, _) => s);
   834 
   835 fun check_finish sq = check_result "Failed to finish proof" sq;
   836 
   837 
   838 (* unstructured refinement *)
   839 
   840 fun defer i = assert_no_chain #> refine (Method.Basic (K (Method.defer i)));
   841 fun prefer i = assert_no_chain #> refine (Method.Basic (K (Method.prefer i)));
   842 
   843 fun apply text = assert_backward #> refine text #> Seq.map (using_facts []);
   844 fun apply_end text = assert_forward #> refine_end text;
   845 
   846 
   847 
   848 (** goals **)
   849 
   850 (* generic goals *)
   851 
   852 local
   853 
   854 val is_var =
   855   can (dest_TVar o Logic.dest_type o Logic.dest_term) orf
   856   can (dest_Var o Logic.dest_term);
   857 
   858 fun implicit_vars props =
   859   let
   860     val (var_props, _) = take_prefix is_var props;
   861     val explicit_vars = fold Term.add_vars var_props [];
   862     val vars = filter_out (member (op =) explicit_vars) (fold Term.add_vars props []);
   863   in map (Logic.mk_term o Var) vars end;
   864 
   865 fun refine_terms n =
   866   refine (Method.Basic (K (RAW_METHOD
   867     (K (HEADGOAL (PRECISE_CONJUNCTS n
   868       (HEADGOAL (CONJUNCTS (ALLGOALS (rtac Drule.termI))))))))))
   869   #> Seq.hd;
   870 
   871 in
   872 
   873 fun generic_goal prepp kind before_qed after_qed raw_propp state =
   874   let
   875     val thy = theory_of state;
   876     val cert = Thm.cterm_of thy;
   877     val chaining = can assert_chain state;
   878     val pos = Position.thread_data ();
   879 
   880     val ((propss, after_ctxt), goal_state) =
   881       state
   882       |> assert_forward_or_chain
   883       |> enter_forward
   884       |> open_block
   885       |> map_context_result (prepp raw_propp);
   886     val props = flat propss;
   887 
   888     val vars = implicit_vars props;
   889     val propss' = vars :: propss;
   890     val goal_propss = filter_out null propss';
   891     val goal =
   892       cert (Logic.mk_conjunction_balanced (map Logic.mk_conjunction_balanced goal_propss))
   893       |> Thm.weaken_sorts (Variable.sorts_of (context_of goal_state));
   894     val statement = ((kind, pos), propss', Thm.term_of goal);
   895     val after_qed' = after_qed |>> (fn after_local =>
   896       fn results => map_context after_ctxt #> after_local results);
   897   in
   898     goal_state
   899     |> map_context (init_context #> Variable.set_body true)
   900     |> set_goal (make_goal (statement, [], [], Goal.init goal, before_qed, after_qed'))
   901     |> map_context (Proof_Context.auto_bind_goal props)
   902     |> chaining ? (`the_facts #-> using_facts)
   903     |> reset_facts
   904     |> open_block
   905     |> reset_goal
   906     |> enter_backward
   907     |> not (null vars) ? refine_terms (length goal_propss)
   908     |> null props ? (refine (Method.Basic Method.assumption) #> Seq.hd)
   909   end;
   910 
   911 fun generic_qed after_ctxt state =
   912   let
   913     val (goal_ctxt, {statement = (_, stmt, _), goal, after_qed, ...}) = current_goal state;
   914     val outer_state = state |> close_block;
   915     val outer_ctxt = context_of outer_state;
   916 
   917     val props =
   918       flat (tl stmt)
   919       |> Variable.exportT_terms goal_ctxt outer_ctxt;
   920     val results =
   921       tl (conclude_goal goal_ctxt goal stmt)
   922       |> burrow (Proof_Context.export goal_ctxt outer_ctxt);
   923   in
   924     outer_state
   925     |> map_context (after_ctxt props)
   926     |> pair (after_qed, results)
   927   end;
   928 
   929 end;
   930 
   931 
   932 (* local goals *)
   933 
   934 fun local_goal print_results prep_att prepp kind before_qed after_qed stmt state =
   935   let
   936     val ((names, attss), propp) =
   937       Attrib.map_specs (map (prep_att (context_of state))) stmt |> split_list |>> split_list;
   938 
   939     fun after_qed' results =
   940       local_results ((names ~~ attss) ~~ results)
   941       #-> (fn res => tap (fn st => print_results (context_of st) ((kind, ""), res) : unit))
   942       #> after_qed results;
   943   in
   944     state
   945     |> generic_goal prepp kind before_qed (after_qed', K I) propp
   946     |> tap (Variable.warn_extra_tfrees (context_of state) o context_of)
   947   end;
   948 
   949 fun local_qeds txt =
   950   end_proof false txt
   951   #> Seq.map (generic_qed Proof_Context.auto_bind_facts #->
   952     (fn ((after_qed, _), results) => after_qed results));
   953 
   954 fun local_qed txt = local_qeds txt #> check_finish;
   955 
   956 
   957 (* global goals *)
   958 
   959 fun prepp_auto_fixes prepp args =
   960   prepp args #>
   961   (fn ((propss, a), ctxt) => ((propss, a), (fold o fold) Variable.auto_fixes propss ctxt));
   962 
   963 fun global_goal prepp before_qed after_qed propp =
   964   init #>
   965   generic_goal (prepp_auto_fixes prepp) "" before_qed (K I, after_qed) propp;
   966 
   967 val theorem = global_goal Proof_Context.bind_propp_schematic_i;
   968 val theorem_cmd = global_goal Proof_Context.bind_propp_schematic;
   969 
   970 fun global_qeds txt =
   971   end_proof true txt
   972   #> Seq.map (generic_qed (K I) #> (fn (((_, after_qed), results), state) =>
   973     after_qed results (context_of state)));
   974 
   975 fun global_qed txt = global_qeds txt #> check_finish;
   976 
   977 
   978 (* concluding steps *)
   979 
   980 fun terminal_proof qed initial terminal =
   981   proof (SOME initial) #> Seq.maps (qed terminal) #> check_finish;
   982 
   983 fun local_terminal_proof (text, opt_text) = terminal_proof local_qeds text (opt_text, true);
   984 val local_default_proof = local_terminal_proof (Method.default_text, NONE);
   985 val local_immediate_proof = local_terminal_proof (Method.this_text, NONE);
   986 fun local_skip_proof int = local_terminal_proof (Method.sorry_text int, NONE);
   987 val local_done_proof = terminal_proof local_qeds Method.done_text (NONE, false);
   988 
   989 fun global_terminal_proof (text, opt_text) = terminal_proof global_qeds text (opt_text, true);
   990 val global_default_proof = global_terminal_proof (Method.default_text, NONE);
   991 val global_immediate_proof = global_terminal_proof (Method.this_text, NONE);
   992 fun global_skip_proof int = global_terminal_proof (Method.sorry_text int, NONE);
   993 val global_done_proof = terminal_proof global_qeds Method.done_text (NONE, false);
   994 
   995 
   996 (* common goal statements *)
   997 
   998 local
   999 
  1000 fun gen_have prep_att prepp before_qed after_qed stmt int =
  1001   local_goal (Proof_Display.print_results Isabelle_Markup.state int)
  1002     prep_att prepp "have" before_qed after_qed stmt;
  1003 
  1004 fun gen_show prep_att prepp before_qed after_qed stmt int state =
  1005   let
  1006     val testing = Unsynchronized.ref false;
  1007     val rule = Unsynchronized.ref (NONE: thm option);
  1008     fun fail_msg ctxt =
  1009       "Local statement will fail to refine any pending goal" ::
  1010       (case ! rule of NONE => [] | SOME th => [Proof_Display.string_of_rule ctxt "Failed" th])
  1011       |> cat_lines;
  1012 
  1013     fun print_results ctxt res =
  1014       if ! testing then ()
  1015       else Proof_Display.print_results Isabelle_Markup.state int ctxt res;
  1016     fun print_rule ctxt th =
  1017       if ! testing then rule := SOME th
  1018       else if int then
  1019         writeln
  1020           (Markup.markup Isabelle_Markup.state (Proof_Display.string_of_rule ctxt "Successful" th))
  1021       else ();
  1022     val test_proof =
  1023       try (local_skip_proof true)
  1024       |> Unsynchronized.setmp testing true
  1025       |> Exn.interruptible_capture;
  1026 
  1027     fun after_qed' results =
  1028       refine_goals print_rule (context_of state) (flat results)
  1029       #> check_result "Failed to refine any pending goal"
  1030       #> after_qed results;
  1031   in
  1032     state
  1033     |> local_goal print_results prep_att prepp "show" before_qed after_qed' stmt
  1034     |> int ? (fn goal_state =>
  1035       (case test_proof goal_state of
  1036         Exn.Res (SOME _) => goal_state
  1037       | Exn.Res NONE => error (fail_msg (context_of goal_state))
  1038       | Exn.Exn exn => raise Exn.EXCEPTIONS ([exn, ERROR (fail_msg (context_of goal_state))])))
  1039   end;
  1040 
  1041 in
  1042 
  1043 val have = gen_have (K I) Proof_Context.bind_propp_i;
  1044 val have_cmd = gen_have Attrib.attribute_cmd Proof_Context.bind_propp;
  1045 val show = gen_show (K I) Proof_Context.bind_propp_i;
  1046 val show_cmd = gen_show Attrib.attribute_cmd Proof_Context.bind_propp;
  1047 
  1048 end;
  1049 
  1050 
  1051 
  1052 (** future proofs **)
  1053 
  1054 (* relevant proof states *)
  1055 
  1056 fun is_schematic t =
  1057   Term.exists_subterm Term.is_Var t orelse
  1058   Term.exists_type (Term.exists_subtype Term.is_TVar) t;
  1059 
  1060 fun schematic_goal state =
  1061   let val (_, (_, {statement = (_, _, prop), ...})) = find_goal state
  1062   in is_schematic prop end;
  1063 
  1064 fun is_relevant state =
  1065   (case try find_goal state of
  1066     NONE => true
  1067   | SOME (_, (_, {statement = (_, _, prop), goal, ...})) =>
  1068       is_schematic prop orelse not (Logic.protect prop aconv Thm.concl_of goal));
  1069 
  1070 
  1071 (* full proofs *)
  1072 
  1073 local
  1074 
  1075 fun future_proof done get_context fork_proof state =
  1076   let
  1077     val _ = assert_backward state;
  1078     val (goal_ctxt, (_, goal)) = find_goal state;
  1079     val {statement as (kind, _, prop), messages, using, goal, before_qed, after_qed} = goal;
  1080     val goal_tfrees =
  1081       fold Term.add_tfrees
  1082         (prop :: map Thm.term_of (Assumption.all_assms_of goal_ctxt)) [];
  1083 
  1084     val _ = is_relevant state andalso error "Cannot fork relevant proof";
  1085 
  1086     val prop' = Logic.protect prop;
  1087     val statement' = (kind, [[], [prop']], prop');
  1088     val goal' = Thm.adjust_maxidx_thm (Thm.maxidx_of goal)
  1089       (Drule.comp_no_flatten (goal, Thm.nprems_of goal) 1 Drule.protectI);
  1090 
  1091     fun after_local' [[th]] = put_thms false (Auto_Bind.thisN, SOME [th]);
  1092     fun after_global' [[th]] = Proof_Context.put_thms false (Auto_Bind.thisN, SOME [th]);
  1093     val after_qed' = (after_local', after_global');
  1094     val this_name = Proof_Context.full_name goal_ctxt (Binding.name Auto_Bind.thisN);
  1095 
  1096     val result_ctxt =
  1097       state
  1098       |> map_goal I (K (statement', messages, using, goal', before_qed, after_qed'))
  1099         (fold (Variable.declare_typ o TFree) goal_tfrees)
  1100       |> fork_proof;
  1101 
  1102     val future_thm = result_ctxt |> Future.map (fn (_, x) =>
  1103       Proof_Context.get_fact_single (get_context x) (Facts.named this_name));
  1104     val finished_goal = Goal.future_result goal_ctxt future_thm prop';
  1105     val state' =
  1106       state
  1107       |> map_goal I (K (statement, messages, using, finished_goal, NONE, after_qed)) I
  1108       |> done;
  1109   in (Future.map #1 result_ctxt, state') end;
  1110 
  1111 in
  1112 
  1113 fun local_future_proof x = future_proof local_done_proof context_of x;
  1114 fun global_future_proof x = future_proof global_done_proof I x;
  1115 
  1116 end;
  1117 
  1118 
  1119 (* terminal proofs *)
  1120 
  1121 local
  1122 
  1123 fun future_terminal_proof proof1 proof2 meths int state =
  1124   if int orelse is_relevant state orelse not (Goal.local_future_enabled ())
  1125   then proof1 meths state
  1126   else snd (proof2 (fn state' =>
  1127     Goal.fork_name "Proof.future_terminal_proof" (fn () => ((), proof1 meths state'))) state);
  1128 
  1129 in
  1130 
  1131 fun local_future_terminal_proof x =
  1132   future_terminal_proof local_terminal_proof local_future_proof x;
  1133 
  1134 fun global_future_terminal_proof x =
  1135   future_terminal_proof global_terminal_proof global_future_proof x;
  1136 
  1137 end;
  1138 
  1139 end;
  1140