src/Pure/goal.ML
author wenzelm
Sat Oct 13 19:53:04 2012 +0200 (2012-10-13)
changeset 49847 ed5080c03165
parent 49845 9b19c0e81166
child 49893 0d4106850eb2
permissions -rw-r--r--
some attempts to unify/simplify pretty_goal;
     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 cancel_futures: unit -> unit
    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 [(Isabelle_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 =
   141         (case Position.get_id (Position.thread_data ()) of
   142           NONE => 0
   143         | SOME id => Markup.parse_int id);
   144       val _ = count_forked 1;
   145       val future =
   146         (singleton o Future.forks)
   147           {name = name, group = NONE, deps = [], pri = ~1, interrupts = false}
   148           (fn () =>
   149             let
   150               val task = the (Future.worker_task ());
   151               val _ = status task [Isabelle_Markup.running];
   152               val result = Exn.capture (Future.interruptible_task e) ();
   153               val _ = status task [Isabelle_Markup.finished, Isabelle_Markup.joined];
   154               val _ =
   155                 (case result of
   156                   Exn.Res _ => ()
   157                 | Exn.Exn exn =>
   158                     if id = 0 orelse Exn.is_interrupt exn then ()
   159                     else
   160                       (status task [Isabelle_Markup.failed];
   161                        Output.report (Markup.markup_only Isabelle_Markup.bad);
   162                        Output.error_msg (ML_Compiler.exn_message exn)));
   163               val _ = count_forked ~1;
   164             in Exn.release result end);
   165       val _ = status (Future.task_of future) [Isabelle_Markup.forked];
   166       val _ = register_forked id future;
   167     in future end) ();
   168 
   169 fun fork e = fork_name "Goal.fork" e;
   170 
   171 fun forked_count () = #1 (Synchronized.value forked_proofs);
   172 
   173 fun peek_futures id =
   174   Inttab.lookup_list (#3 (Synchronized.value forked_proofs)) id;
   175 
   176 fun cancel_futures () =
   177   Synchronized.change forked_proofs (fn (m, groups, tab) =>
   178     (List.app Future.cancel_group groups; (0, [], Inttab.empty)));
   179 
   180 end;
   181 
   182 
   183 (* scheduling parameters *)
   184 
   185 val parallel_proofs = Unsynchronized.ref 1;
   186 val parallel_proofs_threshold = Unsynchronized.ref 50;
   187 
   188 fun future_enabled_level n =
   189   Multithreading.enabled () andalso ! parallel_proofs >= n andalso
   190   is_some (Future.worker_task ());
   191 
   192 fun future_enabled () = future_enabled_level 1;
   193 
   194 fun future_enabled_nested n =
   195   future_enabled_level n andalso
   196   forked_count () < ! parallel_proofs_threshold * Multithreading.max_threads_value ();
   197 
   198 
   199 (* future_result *)
   200 
   201 fun future_result ctxt result prop =
   202   let
   203     val thy = Proof_Context.theory_of ctxt;
   204     val _ = Context.reject_draft thy;
   205     val cert = Thm.cterm_of thy;
   206     val certT = Thm.ctyp_of thy;
   207 
   208     val assms = Assumption.all_assms_of ctxt;
   209     val As = map Thm.term_of assms;
   210 
   211     val xs = map Free (fold Term.add_frees (prop :: As) []);
   212     val fixes = map cert xs;
   213 
   214     val tfrees = fold Term.add_tfrees (prop :: As) [];
   215     val instT = map (fn (a, S) => (certT (TVar ((a, 0), S)), certT (TFree (a, S)))) tfrees;
   216 
   217     val global_prop =
   218       cert (Logic.varify_types_global (fold_rev Logic.all xs (Logic.list_implies (As, prop))))
   219       |> Thm.weaken_sorts (Variable.sorts_of ctxt);
   220     val global_result = result |> Future.map
   221       (Drule.flexflex_unique #>
   222         Thm.adjust_maxidx_thm ~1 #>
   223         Drule.implies_intr_list assms #>
   224         Drule.forall_intr_list fixes #>
   225         Thm.generalize (map #1 tfrees, []) 0 #>
   226         Thm.strip_shyps);
   227     val local_result =
   228       Thm.future global_result global_prop
   229       |> Thm.instantiate (instT, [])
   230       |> Drule.forall_elim_list fixes
   231       |> fold (Thm.elim_implies o Thm.assume) assms;
   232   in local_result end;
   233 
   234 
   235 
   236 (** tactical theorem proving **)
   237 
   238 (* prove_internal -- minimal checks, no normalization of result! *)
   239 
   240 fun prove_internal casms cprop tac =
   241   (case SINGLE (tac (map Assumption.assume casms)) (init cprop) of
   242     SOME th => Drule.implies_intr_list casms
   243       (finish (Syntax.init_pretty_global (Thm.theory_of_thm th)) th)
   244   | NONE => error "Tactic failed");
   245 
   246 
   247 (* prove_common etc. *)
   248 
   249 fun prove_common immediate ctxt xs asms props tac =
   250   let
   251     val thy = Proof_Context.theory_of ctxt;
   252     val string_of_term = Syntax.string_of_term ctxt;
   253 
   254     val pos = Position.thread_data ();
   255     fun err msg = cat_error msg
   256       ("The error(s) above occurred for the goal statement:\n" ^
   257         string_of_term (Logic.list_implies (asms, Logic.mk_conjunction_list props)) ^
   258         (case Position.here pos of "" => "" | s => "\n" ^ s));
   259 
   260     fun cert_safe t = Thm.cterm_of thy (Envir.beta_norm (Term.no_dummy_patterns t))
   261       handle TERM (msg, _) => err msg | TYPE (msg, _, _) => err msg;
   262     val casms = map cert_safe asms;
   263     val cprops = map cert_safe props;
   264 
   265     val (prems, ctxt') = ctxt
   266       |> Variable.add_fixes_direct xs
   267       |> fold Variable.declare_term (asms @ props)
   268       |> Assumption.add_assumes casms
   269       ||> Variable.set_body true;
   270     val sorts = Variable.sorts_of ctxt';
   271 
   272     val stmt = Thm.weaken_sorts sorts (Conjunction.mk_conjunction_balanced cprops);
   273 
   274     fun result () =
   275       (case SINGLE (tac {prems = prems, context = ctxt'}) (init stmt) of
   276         NONE => err "Tactic failed"
   277       | SOME st =>
   278           let val res = finish ctxt' st handle THM (msg, _, _) => err msg in
   279             if Unify.matches_list thy [Thm.term_of stmt] [Thm.prop_of res]
   280             then Thm.check_shyps sorts res
   281             else err ("Proved a different theorem: " ^ string_of_term (Thm.prop_of res))
   282           end);
   283     val res =
   284       if immediate orelse #maxidx (Thm.rep_cterm stmt) >= 0 orelse not (future_enabled ())
   285       then result ()
   286       else future_result ctxt' (fork result) (Thm.term_of stmt);
   287   in
   288     Conjunction.elim_balanced (length props) res
   289     |> map (Assumption.export false ctxt' ctxt)
   290     |> Variable.export ctxt' ctxt
   291     |> map Drule.zero_var_indexes
   292   end;
   293 
   294 val prove_multi = prove_common true;
   295 
   296 fun prove_future ctxt xs asms prop tac = hd (prove_common false ctxt xs asms [prop] tac);
   297 fun prove ctxt xs asms prop tac = hd (prove_common true ctxt xs asms [prop] tac);
   298 
   299 fun prove_global thy xs asms prop tac =
   300   Drule.export_without_context (prove (Proof_Context.init_global thy) xs asms prop tac);
   301 
   302 
   303 
   304 (** goal structure **)
   305 
   306 (* nested goals *)
   307 
   308 fun extract i n st =
   309   (if i < 1 orelse n < 1 orelse i + n - 1 > Thm.nprems_of st then Seq.empty
   310    else if n = 1 then Seq.single (Thm.cprem_of st i)
   311    else
   312      Seq.single (Conjunction.mk_conjunction_balanced (map (Thm.cprem_of st) (i upto i + n - 1))))
   313   |> Seq.map (Thm.adjust_maxidx_cterm ~1 #> init);
   314 
   315 fun retrofit i n st' st =
   316   (if n = 1 then st
   317    else st |> Drule.with_subgoal i (Conjunction.uncurry_balanced n))
   318   |> Thm.compose_no_flatten false (conclude st', Thm.nprems_of st') i;
   319 
   320 fun SELECT_GOAL tac i st =
   321   if Thm.nprems_of st = 1 andalso i = 1 then tac st
   322   else Seq.lifts (retrofit i 1) (Seq.maps tac (extract i 1 st)) st;
   323 
   324 
   325 (* multiple goals *)
   326 
   327 fun precise_conjunction_tac 0 i = eq_assume_tac i
   328   | precise_conjunction_tac 1 i = SUBGOAL (K all_tac) i
   329   | precise_conjunction_tac n i = PRIMITIVE (Drule.with_subgoal i (Conjunction.curry_balanced n));
   330 
   331 val adhoc_conjunction_tac = REPEAT_ALL_NEW
   332   (SUBGOAL (fn (goal, i) =>
   333     if can Logic.dest_conjunction goal then rtac Conjunction.conjunctionI i
   334     else no_tac));
   335 
   336 val conjunction_tac = SUBGOAL (fn (goal, i) =>
   337   precise_conjunction_tac (length (Logic.dest_conjunctions goal)) i ORELSE
   338   TRY (adhoc_conjunction_tac i));
   339 
   340 val recover_conjunction_tac = PRIMITIVE (fn th =>
   341   Conjunction.uncurry_balanced (Thm.nprems_of th) th);
   342 
   343 fun PRECISE_CONJUNCTS n tac =
   344   SELECT_GOAL (precise_conjunction_tac n 1
   345     THEN tac
   346     THEN recover_conjunction_tac);
   347 
   348 fun CONJUNCTS tac =
   349   SELECT_GOAL (conjunction_tac 1
   350     THEN tac
   351     THEN recover_conjunction_tac);
   352 
   353 
   354 (* hhf normal form *)
   355 
   356 val norm_hhf_tac =
   357   rtac Drule.asm_rl  (*cheap approximation -- thanks to builtin Logic.flatten_params*)
   358   THEN' SUBGOAL (fn (t, i) =>
   359     if Drule.is_norm_hhf t then all_tac
   360     else rewrite_goal_tac Drule.norm_hhf_eqs i);
   361 
   362 fun compose_hhf_tac th i st =
   363   PRIMSEQ (Thm.bicompose false (false, Drule.lift_all (Thm.cprem_of st i) th, 0) i) st;
   364 
   365 
   366 (* non-atomic goal assumptions *)
   367 
   368 fun non_atomic (Const ("==>", _) $ _ $ _) = true
   369   | non_atomic (Const ("all", _) $ _) = true
   370   | non_atomic _ = false;
   371 
   372 fun assume_rule_tac ctxt = norm_hhf_tac THEN' CSUBGOAL (fn (goal, i) =>
   373   let
   374     val ((_, goal'), ctxt') = Variable.focus_cterm goal ctxt;
   375     val goal'' = Drule.cterm_rule (singleton (Variable.export ctxt' ctxt)) goal';
   376     val Rs = filter (non_atomic o Thm.term_of) (Drule.strip_imp_prems goal'');
   377     val tacs = Rs |> map (fn R =>
   378       Tactic.etac (Raw_Simplifier.norm_hhf (Thm.trivial R)) THEN_ALL_NEW assume_tac);
   379   in fold_rev (curry op APPEND') tacs (K no_tac) i end);
   380 
   381 
   382 (* parallel tacticals *)
   383 
   384 (*parallel choice of single results*)
   385 fun PARALLEL_CHOICE tacs st =
   386   (case Par_List.get_some (fn tac => SINGLE tac st) tacs of
   387     NONE => Seq.empty
   388   | SOME st' => Seq.single st');
   389 
   390 (*parallel refinement of non-schematic goal by single results*)
   391 exception FAILED of unit;
   392 fun PARALLEL_GOALS tac =
   393   Thm.adjust_maxidx_thm ~1 #>
   394   (fn st =>
   395     if not (Multithreading.enabled ()) orelse Thm.maxidx_of st >= 0 orelse Thm.nprems_of st <= 1
   396     then DETERM tac st
   397     else
   398       let
   399         fun try_tac g =
   400           (case SINGLE tac g of
   401             NONE => raise FAILED ()
   402           | SOME g' => g');
   403 
   404         val goals = Drule.strip_imp_prems (Thm.cprop_of st);
   405         val results = Par_List.map (try_tac o init) goals;
   406       in ALLGOALS (fn i => retrofit i 1 (nth results (i - 1))) st end
   407       handle FAILED () => Seq.empty);
   408 
   409 end;
   410 
   411 structure Basic_Goal: BASIC_GOAL = Goal;
   412 open Basic_Goal;