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