src/Pure/goal.ML
author wenzelm
Wed Jan 16 16:26:36 2013 +0100 (2013-01-16)
changeset 50911 ee7fe4230642
parent 50201 c26369c9eda6
child 50914 fe4714886d92
permissions -rw-r--r--
more explicit treatment of (optional) exception properties, notably for "serial" -- avoid conflict with startPosition = offset;
     1 (*  Title:      Pure/goal.ML
     2     Author:     Makarius
     3 
     4 Goals in tactical theorem proving, with support for forked proofs.
     5 *)
     6 
     7 signature BASIC_GOAL =
     8 sig
     9   val parallel_proofs: int Unsynchronized.ref
    10   val parallel_proofs_threshold: int Unsynchronized.ref
    11   val SELECT_GOAL: tactic -> int -> tactic
    12   val CONJUNCTS: tactic -> int -> tactic
    13   val PRECISE_CONJUNCTS: int -> tactic -> int -> tactic
    14   val PARALLEL_CHOICE: tactic list -> tactic
    15   val PARALLEL_GOALS: tactic -> tactic
    16 end;
    17 
    18 signature GOAL =
    19 sig
    20   include BASIC_GOAL
    21   val init: cterm -> thm
    22   val protect: thm -> thm
    23   val conclude: thm -> thm
    24   val check_finished: Proof.context -> thm -> thm
    25   val finish: Proof.context -> thm -> thm
    26   val norm_result: thm -> thm
    27   val fork_name: string -> (unit -> 'a) -> 'a future
    28   val fork: (unit -> 'a) -> 'a future
    29   val peek_futures: serial -> unit future list
    30   val reset_futures: unit -> Future.group list
    31   val future_enabled_level: int -> bool
    32   val future_enabled: unit -> bool
    33   val future_enabled_nested: int -> bool
    34   val future_result: Proof.context -> thm future -> term -> thm
    35   val prove_internal: cterm list -> cterm -> (thm list -> tactic) -> thm
    36   val prove_multi: Proof.context -> string list -> term list -> term list ->
    37     ({prems: thm list, context: Proof.context} -> tactic) -> thm list
    38   val prove_future: Proof.context -> string list -> term list -> term ->
    39     ({prems: thm list, context: Proof.context} -> tactic) -> thm
    40   val prove: Proof.context -> string list -> term list -> term ->
    41     ({prems: thm list, context: Proof.context} -> tactic) -> thm
    42   val prove_global: theory -> string list -> term list -> term ->
    43     ({prems: thm list, context: Proof.context} -> tactic) -> thm
    44   val extract: int -> int -> thm -> thm Seq.seq
    45   val retrofit: int -> int -> thm -> thm -> thm Seq.seq
    46   val conjunction_tac: int -> tactic
    47   val precise_conjunction_tac: int -> int -> tactic
    48   val recover_conjunction_tac: tactic
    49   val norm_hhf_tac: int -> tactic
    50   val compose_hhf_tac: thm -> int -> tactic
    51   val assume_rule_tac: Proof.context -> int -> tactic
    52 end;
    53 
    54 structure Goal: GOAL =
    55 struct
    56 
    57 (** goals **)
    58 
    59 (*
    60   -------- (init)
    61   C ==> #C
    62 *)
    63 val init =
    64   let val A = #1 (Thm.dest_implies (Thm.cprop_of Drule.protectI))
    65   in fn C => Thm.instantiate ([], [(A, C)]) Drule.protectI end;
    66 
    67 (*
    68    C
    69   --- (protect)
    70   #C
    71 *)
    72 fun protect th = Drule.comp_no_flatten (th, 0) 1 Drule.protectI;
    73 
    74 (*
    75   A ==> ... ==> #C
    76   ---------------- (conclude)
    77   A ==> ... ==> C
    78 *)
    79 fun conclude th = Drule.comp_no_flatten (th, Thm.nprems_of th) 1 Drule.protectD;
    80 
    81 (*
    82   #C
    83   --- (finish)
    84    C
    85 *)
    86 fun check_finished ctxt th =
    87   (case Thm.nprems_of th of
    88     0 => th
    89   | n => raise THM ("Proof failed.\n" ^
    90       Pretty.string_of (Goal_Display.pretty_goal {main = true, limit = false} ctxt th), 0, [th]));
    91 
    92 fun finish ctxt = check_finished ctxt #> conclude;
    93 
    94 
    95 
    96 (** results **)
    97 
    98 (* normal form *)
    99 
   100 val norm_result =
   101   Drule.flexflex_unique
   102   #> Raw_Simplifier.norm_hhf_protect
   103   #> Thm.strip_shyps
   104   #> Drule.zero_var_indexes;
   105 
   106 
   107 (* forked proofs *)
   108 
   109 local
   110 
   111 val forked_proofs =
   112   Synchronized.var "forked_proofs"
   113     (0, []: Future.group list, Inttab.empty: unit future list Inttab.table);
   114 
   115 fun count_forked i =
   116   Synchronized.change forked_proofs (fn (m, groups, tab) =>
   117     let
   118       val n = m + i;
   119       val _ =
   120         Multithreading.tracing 2 (fn () =>
   121           ("PROOFS " ^ Time.toString (Time.now ()) ^ ": " ^ string_of_int n));
   122     in (n, groups, tab) end);
   123 
   124 fun register_forked id future =
   125   Synchronized.change forked_proofs (fn (m, groups, tab) =>
   126     let
   127       val groups' = Task_Queue.group_of_task (Future.task_of future) :: groups;
   128       val tab' = Inttab.cons_list (id, Future.map (K ()) future) tab;
   129     in (m, groups', tab') end);
   130 
   131 fun status task markups =
   132   let val props = Markup.properties [(Markup.taskN, Task_Queue.str_of_task task)]
   133   in Output.status (implode (map (Markup.markup_only o props) markups)) end;
   134 
   135 in
   136 
   137 fun fork_name name e =
   138   uninterruptible (fn _ => fn () =>
   139     let
   140       val id = the_default 0 (Position.parse_id (Position.thread_data ()));
   141       val _ = count_forked 1;
   142       val future =
   143         (singleton o Future.forks)
   144           {name = name, group = NONE, deps = [], pri = ~1, interrupts = false}
   145           (fn () =>
   146             let
   147               val task = the (Future.worker_task ());
   148               val _ = status task [Markup.running];
   149               val result = Exn.capture (Future.interruptible_task e) ();
   150               val _ = status task [Markup.finished, Markup.joined];
   151               val _ =
   152                 (case result of
   153                   Exn.Res _ => ()
   154                 | Exn.Exn exn =>
   155                     if id = 0 orelse Exn.is_interrupt exn then ()
   156                     else
   157                       (status task [Markup.failed];
   158                        Output.report (Markup.markup_only Markup.bad);
   159                        Output.error_msg (ML_Compiler.exn_message exn)));
   160               val _ = count_forked ~1;
   161             in Exn.release result end);
   162       val _ = status (Future.task_of future) [Markup.forked];
   163       val _ = register_forked id future;
   164     in future end) ();
   165 
   166 fun fork e = fork_name "Goal.fork" e;
   167 
   168 fun forked_count () = #1 (Synchronized.value forked_proofs);
   169 
   170 fun peek_futures id =
   171   Inttab.lookup_list (#3 (Synchronized.value forked_proofs)) id;
   172 
   173 fun reset_futures () =
   174   Synchronized.change_result forked_proofs (fn (m, groups, tab) =>
   175     (groups, (0, [], Inttab.empty)));
   176 
   177 end;
   178 
   179 
   180 (* scheduling parameters *)
   181 
   182 val parallel_proofs = Unsynchronized.ref 1;
   183 val parallel_proofs_threshold = Unsynchronized.ref 50;
   184 
   185 fun future_enabled_level n =
   186   Multithreading.enabled () andalso ! parallel_proofs >= n andalso
   187   is_some (Future.worker_task ());
   188 
   189 fun future_enabled () = future_enabled_level 1;
   190 
   191 fun future_enabled_nested n =
   192   future_enabled_level n andalso
   193   forked_count () < ! parallel_proofs_threshold * Multithreading.max_threads_value ();
   194 
   195 
   196 (* future_result *)
   197 
   198 fun future_result ctxt result prop =
   199   let
   200     val thy = Proof_Context.theory_of ctxt;
   201     val _ = Context.reject_draft thy;
   202     val cert = Thm.cterm_of thy;
   203     val certT = Thm.ctyp_of thy;
   204 
   205     val assms = Assumption.all_assms_of ctxt;
   206     val As = map Thm.term_of assms;
   207 
   208     val xs = map Free (fold Term.add_frees (prop :: As) []);
   209     val fixes = map cert xs;
   210 
   211     val tfrees = fold Term.add_tfrees (prop :: As) [];
   212     val instT = map (fn (a, S) => (certT (TVar ((a, 0), S)), certT (TFree (a, S)))) tfrees;
   213 
   214     val global_prop =
   215       cert (Logic.varify_types_global (fold_rev Logic.all xs (Logic.list_implies (As, prop))))
   216       |> Thm.weaken_sorts (Variable.sorts_of ctxt);
   217     val global_result = result |> Future.map
   218       (Drule.flexflex_unique #>
   219         Thm.adjust_maxidx_thm ~1 #>
   220         Drule.implies_intr_list assms #>
   221         Drule.forall_intr_list fixes #>
   222         Thm.generalize (map #1 tfrees, []) 0 #>
   223         Thm.strip_shyps);
   224     val local_result =
   225       Thm.future global_result global_prop
   226       |> Thm.instantiate (instT, [])
   227       |> Drule.forall_elim_list fixes
   228       |> fold (Thm.elim_implies o Thm.assume) assms;
   229   in local_result end;
   230 
   231 
   232 
   233 (** tactical theorem proving **)
   234 
   235 (* prove_internal -- minimal checks, no normalization of result! *)
   236 
   237 fun prove_internal casms cprop tac =
   238   (case SINGLE (tac (map Assumption.assume casms)) (init cprop) of
   239     SOME th => Drule.implies_intr_list casms
   240       (finish (Syntax.init_pretty_global (Thm.theory_of_thm th)) th)
   241   | NONE => error "Tactic failed");
   242 
   243 
   244 (* prove_common etc. *)
   245 
   246 fun prove_common immediate ctxt xs asms props tac =
   247   let
   248     val thy = Proof_Context.theory_of ctxt;
   249     val string_of_term = Syntax.string_of_term ctxt;
   250 
   251     val pos = Position.thread_data ();
   252     fun err msg = cat_error msg
   253       ("The error(s) above occurred for the goal statement:\n" ^
   254         string_of_term (Logic.list_implies (asms, Logic.mk_conjunction_list props)) ^
   255         (case Position.here pos of "" => "" | s => "\n" ^ s));
   256 
   257     fun cert_safe t = Thm.cterm_of thy (Envir.beta_norm (Term.no_dummy_patterns t))
   258       handle TERM (msg, _) => err msg | TYPE (msg, _, _) => err msg;
   259     val casms = map cert_safe asms;
   260     val cprops = map cert_safe props;
   261 
   262     val (prems, ctxt') = ctxt
   263       |> Variable.add_fixes_direct xs
   264       |> fold Variable.declare_term (asms @ props)
   265       |> Assumption.add_assumes casms
   266       ||> Variable.set_body true;
   267     val sorts = Variable.sorts_of ctxt';
   268 
   269     val stmt = Thm.weaken_sorts sorts (Conjunction.mk_conjunction_balanced cprops);
   270 
   271     fun result () =
   272       (case SINGLE (tac {prems = prems, context = ctxt'}) (init stmt) of
   273         NONE => err "Tactic failed"
   274       | SOME st =>
   275           let val res = finish ctxt' st handle THM (msg, _, _) => err msg in
   276             if Unify.matches_list thy [Thm.term_of stmt] [Thm.prop_of res]
   277             then Thm.check_shyps sorts res
   278             else err ("Proved a different theorem: " ^ string_of_term (Thm.prop_of res))
   279           end);
   280     val res =
   281       if immediate orelse #maxidx (Thm.rep_cterm stmt) >= 0 orelse not (future_enabled ())
   282       then result ()
   283       else future_result ctxt' (fork result) (Thm.term_of stmt);
   284   in
   285     Conjunction.elim_balanced (length props) res
   286     |> map (Assumption.export false ctxt' ctxt)
   287     |> Variable.export ctxt' ctxt
   288     |> map Drule.zero_var_indexes
   289   end;
   290 
   291 val prove_multi = prove_common true;
   292 
   293 fun prove_future ctxt xs asms prop tac = hd (prove_common false ctxt xs asms [prop] tac);
   294 fun prove ctxt xs asms prop tac = hd (prove_common true ctxt xs asms [prop] tac);
   295 
   296 fun prove_global thy xs asms prop tac =
   297   Drule.export_without_context (prove (Proof_Context.init_global thy) xs asms prop tac);
   298 
   299 
   300 
   301 (** goal structure **)
   302 
   303 (* nested goals *)
   304 
   305 fun extract i n st =
   306   (if i < 1 orelse n < 1 orelse i + n - 1 > Thm.nprems_of st then Seq.empty
   307    else if n = 1 then Seq.single (Thm.cprem_of st i)
   308    else
   309      Seq.single (Conjunction.mk_conjunction_balanced (map (Thm.cprem_of st) (i upto i + n - 1))))
   310   |> Seq.map (Thm.adjust_maxidx_cterm ~1 #> init);
   311 
   312 fun retrofit i n st' st =
   313   (if n = 1 then st
   314    else st |> Drule.with_subgoal i (Conjunction.uncurry_balanced n))
   315   |> Thm.compose_no_flatten false (conclude st', Thm.nprems_of st') i;
   316 
   317 fun SELECT_GOAL tac i st =
   318   if Thm.nprems_of st = 1 andalso i = 1 then tac st
   319   else Seq.lifts (retrofit i 1) (Seq.maps tac (extract i 1 st)) st;
   320 
   321 
   322 (* multiple goals *)
   323 
   324 fun precise_conjunction_tac 0 i = eq_assume_tac i
   325   | precise_conjunction_tac 1 i = SUBGOAL (K all_tac) i
   326   | precise_conjunction_tac n i = PRIMITIVE (Drule.with_subgoal i (Conjunction.curry_balanced n));
   327 
   328 val adhoc_conjunction_tac = REPEAT_ALL_NEW
   329   (SUBGOAL (fn (goal, i) =>
   330     if can Logic.dest_conjunction goal then rtac Conjunction.conjunctionI i
   331     else no_tac));
   332 
   333 val conjunction_tac = SUBGOAL (fn (goal, i) =>
   334   precise_conjunction_tac (length (Logic.dest_conjunctions goal)) i ORELSE
   335   TRY (adhoc_conjunction_tac i));
   336 
   337 val recover_conjunction_tac = PRIMITIVE (fn th =>
   338   Conjunction.uncurry_balanced (Thm.nprems_of th) th);
   339 
   340 fun PRECISE_CONJUNCTS n tac =
   341   SELECT_GOAL (precise_conjunction_tac n 1
   342     THEN tac
   343     THEN recover_conjunction_tac);
   344 
   345 fun CONJUNCTS tac =
   346   SELECT_GOAL (conjunction_tac 1
   347     THEN tac
   348     THEN recover_conjunction_tac);
   349 
   350 
   351 (* hhf normal form *)
   352 
   353 val norm_hhf_tac =
   354   rtac Drule.asm_rl  (*cheap approximation -- thanks to builtin Logic.flatten_params*)
   355   THEN' SUBGOAL (fn (t, i) =>
   356     if Drule.is_norm_hhf t then all_tac
   357     else rewrite_goal_tac Drule.norm_hhf_eqs i);
   358 
   359 fun compose_hhf_tac th i st =
   360   PRIMSEQ (Thm.bicompose false (false, Drule.lift_all (Thm.cprem_of st i) th, 0) i) st;
   361 
   362 
   363 (* non-atomic goal assumptions *)
   364 
   365 fun non_atomic (Const ("==>", _) $ _ $ _) = true
   366   | non_atomic (Const ("all", _) $ _) = true
   367   | non_atomic _ = false;
   368 
   369 fun assume_rule_tac ctxt = norm_hhf_tac THEN' CSUBGOAL (fn (goal, i) =>
   370   let
   371     val ((_, goal'), ctxt') = Variable.focus_cterm goal ctxt;
   372     val goal'' = Drule.cterm_rule (singleton (Variable.export ctxt' ctxt)) goal';
   373     val Rs = filter (non_atomic o Thm.term_of) (Drule.strip_imp_prems goal'');
   374     val tacs = Rs |> map (fn R =>
   375       Tactic.etac (Raw_Simplifier.norm_hhf (Thm.trivial R)) THEN_ALL_NEW assume_tac);
   376   in fold_rev (curry op APPEND') tacs (K no_tac) i end);
   377 
   378 
   379 (* parallel tacticals *)
   380 
   381 (*parallel choice of single results*)
   382 fun PARALLEL_CHOICE tacs st =
   383   (case Par_List.get_some (fn tac => SINGLE tac st) tacs of
   384     NONE => Seq.empty
   385   | SOME st' => Seq.single st');
   386 
   387 (*parallel refinement of non-schematic goal by single results*)
   388 exception FAILED of unit;
   389 fun PARALLEL_GOALS tac =
   390   Thm.adjust_maxidx_thm ~1 #>
   391   (fn st =>
   392     if not (Multithreading.enabled ()) orelse Thm.maxidx_of st >= 0 orelse Thm.nprems_of st <= 1
   393     then DETERM tac st
   394     else
   395       let
   396         fun try_tac g =
   397           (case SINGLE tac g of
   398             NONE => raise FAILED ()
   399           | SOME g' => g');
   400 
   401         val goals = Drule.strip_imp_prems (Thm.cprop_of st);
   402         val results = Par_List.map (try_tac o init) goals;
   403       in ALLGOALS (fn i => retrofit i 1 (nth results (i - 1))) st end
   404       handle FAILED () => Seq.empty);
   405 
   406 end;
   407 
   408 structure Basic_Goal: BASIC_GOAL = Goal;
   409 open Basic_Goal;