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