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