src/Pure/Isar/obtain.ML
author wenzelm
Wed Aug 02 22:27:02 2006 +0200 (2006-08-02)
changeset 20308 ddb7e7129481
parent 20224 9c40a144ee0e
child 20804 0e2591606867
permissions -rw-r--r--
added tactical result;
simplified obtain_export: no Seq.seq, no lifting of result prems;
tuned;
     1 (*  Title:      Pure/Isar/obtain.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 The 'obtain' and 'guess' language elements -- generalized existence at
     6 the level of proof texts: 'obtain' involves a proof that certain
     7 fixes/assumes may be introduced into the present context; 'guess' is
     8 similar, but derives these elements from the course of reasoning!
     9 
    10   <chain_facts>
    11   obtain x where "A x" <proof> ==
    12 
    13   have "!!thesis. (!!x. A x ==> thesis) ==> thesis"
    14   proof succeed
    15     fix thesis
    16     assume that [intro?]: "!!x. A x ==> thesis"
    17     <chain_facts>
    18     show thesis
    19       apply (insert that)
    20       <proof>
    21   qed
    22   fix x assm <<obtain_export>> "A x"
    23 
    24 
    25   <chain_facts>
    26   guess x <proof body> <proof end> ==
    27 
    28   {
    29     fix thesis
    30     <chain_facts> have "PROP ?guess"
    31       apply magic      -- {* turns goal into "thesis ==> #thesis" *}
    32       <proof body>
    33       apply_end magic  -- {* turns final "(!!x. P x ==> thesis) ==> #thesis" into
    34         "#((!!x. A x ==> thesis) ==> thesis)" which is a finished goal state *}
    35       <proof end>
    36   }
    37   fix x assm <<obtain_export>> "A x"
    38 *)
    39 
    40 signature OBTAIN =
    41 sig
    42   val obtain: string -> (string * string option * mixfix) list ->
    43     ((string * Attrib.src list) * (string * string list) list) list ->
    44     bool -> Proof.state -> Proof.state
    45   val obtain_i: string -> (string * typ option * mixfix) list ->
    46     ((string * attribute list) * (term * term list) list) list ->
    47     bool -> Proof.state -> Proof.state
    48   val result: (Proof.context -> tactic) -> thm list -> Proof.context ->
    49     (cterm list * thm list) * Proof.context
    50   val guess: (string * string option * mixfix) list -> bool -> Proof.state -> Proof.state
    51   val guess_i: (string * typ option * mixfix) list -> bool -> Proof.state -> Proof.state
    52   val statement: (string * ((string * 'typ option) list * 'term list)) list ->
    53     (('typ, 'term, 'fact) Element.ctxt list *
    54       ((string * Attrib.src list) * ('term * 'term list) list) list) *
    55     (((string * Attrib.src list) * (term * term list) list) list -> Proof.context ->
    56       (((string * Attrib.src list) * (term * term list) list) list * thm list) * Proof.context)
    57 end;
    58 
    59 structure Obtain: OBTAIN =
    60 struct
    61 
    62 (** obtain_export **)
    63 
    64 (*
    65   [x, A x]
    66      :
    67      B
    68   --------
    69      B
    70 *)
    71 fun obtain_export fix_ctxt rule xs _ As thm =
    72   let
    73     val thy = ProofContext.theory_of fix_ctxt;
    74 
    75     val vs = map (dest_Free o Thm.term_of) xs;
    76     val bads = Term.fold_aterms (fn t as Free v =>
    77       if member (op =) vs v then insert (op aconv) t else I | _ => I) (Thm.prop_of thm) [];
    78     val _ = null bads orelse
    79       error ("Result contains obtained parameters: " ^
    80         space_implode " " (map (ProofContext.string_of_term fix_ctxt) bads));
    81     val _ = ObjectLogic.is_judgment thy (Thm.concl_of thm) orelse
    82       error "Conclusion in obtained context must be object-logic judgment";
    83 
    84     val ((_, [thm']), ctxt') = Variable.import true [thm] fix_ctxt;
    85     val prems = Drule.strip_imp_prems (#prop (Thm.crep_thm thm'));
    86   in
    87     ((Drule.implies_elim_list thm' (map Thm.assume prems)
    88         |> Drule.implies_intr_list (map Drule.norm_hhf_cterm As)
    89         |> Drule.forall_intr_list xs)
    90       COMP rule)
    91     |> Drule.implies_intr_list prems
    92     |> singleton (Variable.export ctxt' fix_ctxt)
    93   end;
    94 
    95 
    96 
    97 (** obtain **)
    98 
    99 fun bind_judgment ctxt name =
   100   let
   101     val (bind, ctxt') = ProofContext.bind_fixes [name] ctxt;
   102     val (t as _ $ Free v) = bind (ObjectLogic.fixed_judgment (ProofContext.theory_of ctxt) name);
   103   in ((v, t), ctxt') end;
   104 
   105 val thatN = "that";
   106 
   107 local
   108 
   109 fun gen_obtain prep_att prep_vars prep_propp
   110     name raw_vars raw_asms int state =
   111   let
   112     val _ = Proof.assert_forward_or_chain state;
   113     val thy = Proof.theory_of state;
   114     val cert = Thm.cterm_of thy;
   115     val ctxt = Proof.context_of state;
   116     val chain_facts = if can Proof.assert_chain state then Proof.the_facts state else [];
   117 
   118     (*obtain vars*)
   119     val (vars, vars_ctxt) = prep_vars raw_vars ctxt;
   120     val (_, fix_ctxt) = vars_ctxt |> ProofContext.add_fixes_i vars;
   121     val xs = map #1 vars;
   122 
   123     (*obtain asms*)
   124     val (asms_ctxt, proppss) = prep_propp (fix_ctxt, map snd raw_asms);
   125     val asm_props = maps (map fst) proppss;
   126     val asms = map fst (Attrib.map_specs (prep_att thy) raw_asms) ~~ proppss;
   127 
   128     val _ = Variable.warn_extra_tfrees fix_ctxt asms_ctxt;
   129 
   130     (*obtain statements*)
   131     val thesisN = Name.variant xs AutoBind.thesisN;
   132     val (thesis_var, thesis) = #1 (bind_judgment fix_ctxt thesisN);
   133 
   134     val asm_frees = fold Term.add_frees asm_props [];
   135     val parms = xs |> map (fn x =>
   136       let val x' = ProofContext.get_skolem fix_ctxt x
   137       in (x', the_default propT (AList.lookup (op =) asm_frees x')) end);
   138 
   139     val that_name = if name = "" then thatN else name;
   140     val that_prop =
   141       Term.list_all_free (parms, Logic.list_implies (asm_props, thesis))
   142       |> Library.curry Logic.list_rename_params xs;
   143     val obtain_prop =
   144       Logic.list_rename_params ([AutoBind.thesisN],
   145         Term.list_all_free ([thesis_var], Logic.mk_implies (that_prop, thesis)));
   146 
   147     fun after_qed _ =
   148       Proof.local_qed (NONE, false)
   149       #> Seq.map (`Proof.the_fact #-> (fn rule =>
   150         Proof.fix_i (map2 (fn x => fn (_, T, mx) => (x, T, mx)) xs vars)
   151         #> Proof.assm_i (obtain_export fix_ctxt rule (map (cert o Free) parms)) asms));
   152   in
   153     state
   154     |> Proof.enter_forward
   155     |> Proof.have_i NONE (K Seq.single) [(("", []), [(obtain_prop, [])])] int
   156     |> Proof.proof (SOME Method.succeed_text) |> Seq.hd
   157     |> Proof.fix_i [(thesisN, NONE, NoSyn)]
   158     |> Proof.assume_i [((that_name, [ContextRules.intro_query NONE]), [(that_prop, [])])]
   159     |> `Proof.the_facts
   160     ||> Proof.chain_facts chain_facts
   161     ||> Proof.show_i NONE after_qed [(("", []), [(thesis, [])])] false
   162     |-> Proof.refine_insert
   163   end;
   164 
   165 in
   166 
   167 val obtain = gen_obtain Attrib.attribute ProofContext.read_vars ProofContext.read_propp;
   168 val obtain_i = gen_obtain (K I) ProofContext.cert_vars ProofContext.cert_propp;
   169 
   170 end;
   171 
   172 
   173 
   174 (** tactical result **)
   175 
   176 fun check_result ctxt thesis th =
   177   (case Thm.prems_of th of
   178     [prem] =>
   179       if Thm.concl_of th aconv thesis andalso
   180         Logic.strip_assums_concl prem aconv thesis then th
   181       else error ("Guessed a different clause:\n" ^ ProofContext.string_of_thm ctxt th)
   182   | [] => error "Goal solved -- nothing guessed."
   183   | _ => error ("Guess split into several cases:\n" ^ ProofContext.string_of_thm ctxt th));
   184 
   185 fun result tac facts ctxt =
   186   let
   187     val thy = ProofContext.theory_of ctxt;
   188     val cert = Thm.cterm_of thy;
   189 
   190     val ((thesis_var, thesis), thesis_ctxt) = bind_judgment ctxt AutoBind.thesisN;
   191     val rule =
   192       (case SINGLE (Method.insert_tac facts 1 THEN tac thesis_ctxt) (Goal.init (cert thesis)) of
   193         NONE => raise THM ("Obtain.result: tactic failed", 0, facts)
   194       | SOME th => check_result ctxt thesis (norm_hhf (Goal.conclude th)));
   195 
   196     val closed_rule = Thm.forall_intr (cert (Free thesis_var)) rule;
   197     val ((_, [rule']), ctxt') = Variable.import false [closed_rule] ctxt;
   198     val obtain_rule = Thm.forall_elim (cert (Logic.varify (Free thesis_var))) rule';
   199     val ((params, stmt), fix_ctxt) = Variable.focus (Thm.cprem_of obtain_rule 1) ctxt';
   200     val (prems, ctxt'') =
   201       Assumption.add_assms (obtain_export fix_ctxt obtain_rule params)
   202         (Drule.strip_imp_prems stmt) fix_ctxt;
   203   in ((params, prems), ctxt'') end;
   204 
   205 
   206 
   207 (** guess **)
   208 
   209 local
   210 
   211 fun unify_params vars thesis_var raw_rule ctxt =
   212   let
   213     val thy = ProofContext.theory_of ctxt;
   214     val certT = Thm.ctyp_of thy;
   215     val cert = Thm.cterm_of thy;
   216     val string_of_typ = ProofContext.string_of_typ ctxt;
   217     val string_of_term = setmp show_types true (ProofContext.string_of_term ctxt);
   218 
   219     fun err msg th = error (msg ^ ":\n" ^ ProofContext.string_of_thm ctxt th);
   220 
   221     val maxidx = fold (Term.maxidx_typ o snd o fst) vars ~1;
   222     val rule = Thm.incr_indexes (maxidx + 1) raw_rule;
   223 
   224     val params = RuleCases.strip_params (Logic.nth_prem (1, Thm.prop_of rule));
   225     val m = length vars;
   226     val n = length params;
   227     val _ = m <= n orelse err "More variables than parameters in obtained rule" rule;
   228 
   229     fun unify ((x, T), (y, U)) (tyenv, max) = Sign.typ_unify thy (T, U) (tyenv, max)
   230       handle Type.TUNIFY =>
   231         err ("Failed to unify variable " ^
   232           string_of_term (Free (x, Envir.norm_type tyenv T)) ^ " against parameter " ^
   233           string_of_term (Syntax.mark_boundT (y, Envir.norm_type tyenv U)) ^ " in") rule;
   234     val (tyenv, _) = fold unify (map #1 vars ~~ Library.take (m, params))
   235       (Vartab.empty, Int.max (maxidx, Thm.maxidx_of rule));
   236     val norm_type = Envir.norm_type tyenv;
   237 
   238     val xs = map (apsnd norm_type o fst) vars;
   239     val ys = map (apsnd norm_type) (Library.drop (m, params));
   240     val ys' = map Name.internal (Name.variant_list (map fst xs) (map fst ys)) ~~ map #2 ys;
   241     val terms = map (Drule.mk_term o cert o Free) (xs @ ys');
   242 
   243     val instT =
   244       fold (Term.add_tvarsT o #2) params []
   245       |> map (TVar #> (fn T => (certT T, certT (norm_type T))));
   246     val closed_rule = rule
   247       |> Thm.forall_intr (cert (Free thesis_var))
   248       |> Thm.instantiate (instT, []);
   249 
   250     val ((_, rule' :: terms'), ctxt') = Variable.import false (closed_rule :: terms) ctxt;
   251     val vars' =
   252       map (dest_Free o Thm.term_of o Drule.dest_term) terms' ~~
   253       (map snd vars @ replicate (length ys) NoSyn);
   254     val rule'' = Thm.forall_elim (cert (Logic.varify (Free thesis_var))) rule';
   255   in ((vars', rule''), ctxt') end;
   256 
   257 fun inferred_type (x, _, mx) ctxt =
   258   let val ((_, T), ctxt') = ProofContext.inferred_param x ctxt
   259   in ((x, T, mx), ctxt') end;
   260 
   261 fun polymorphic ctxt vars =
   262   let val Ts = map Logic.dest_type (Variable.polymorphic ctxt (map (Logic.mk_type o #2) vars))
   263   in map2 (fn (x, _, mx) => fn T => ((x, T), mx)) vars Ts end;
   264 
   265 fun gen_guess prep_vars raw_vars int state =
   266   let
   267     val _ = Proof.assert_forward_or_chain state;
   268     val thy = Proof.theory_of state;
   269     val cert = Thm.cterm_of thy;
   270     val ctxt = Proof.context_of state;
   271     val chain_facts = if can Proof.assert_chain state then Proof.the_facts state else [];
   272 
   273     val (thesis_var, thesis) = #1 (bind_judgment ctxt AutoBind.thesisN);
   274     val vars = ctxt |> prep_vars raw_vars |-> fold_map inferred_type |> fst |> polymorphic ctxt;
   275 
   276     fun guess_context raw_rule state' =
   277       let
   278         val ((parms, rule), ctxt') =
   279           unify_params vars thesis_var raw_rule (Proof.context_of state');
   280         val (bind, _) = ProofContext.bind_fixes (map (#1 o #1) parms) ctxt';
   281         val ts = map (bind o Free o #1) parms;
   282         val ps = map dest_Free ts;
   283         val asms =
   284           Logic.strip_assums_hyp (Logic.nth_prem (1, Thm.prop_of rule))
   285           |> map (fn asm => (Term.betapplys (Term.list_abs (ps, asm), ts), []));
   286         val _ = not (null asms) orelse error "Trivial result -- nothing guessed";
   287       in
   288         state'
   289         |> Proof.map_context (K ctxt')
   290         |> Proof.fix_i (map (fn ((x, T), mx) => (x, SOME T, mx)) parms)
   291         |> `Proof.context_of |-> (fn fix_ctxt =>
   292             Proof.assm_i (obtain_export fix_ctxt rule (map cert ts)) [(("", []), asms)])
   293         |> Proof.add_binds_i AutoBind.no_facts
   294       end;
   295 
   296     val goal = Var (("guess", 0), propT);
   297     fun print_result ctxt' (k, [(s, [_, th])]) =
   298       ProofDisplay.print_results int ctxt' (k, [(s, [th])]);
   299     val before_qed = SOME (Method.primitive_text (Goal.conclude #> norm_hhf #>
   300         (fn th => Goal.protect (Conjunction.intr (Drule.mk_term (Thm.cprop_of th)) th))));
   301     fun after_qed [[_, res]] =
   302       Proof.end_block #> guess_context (check_result ctxt thesis res) #> Seq.single;
   303   in
   304     state
   305     |> Proof.enter_forward
   306     |> Proof.begin_block
   307     |> Proof.fix_i [(AutoBind.thesisN, NONE, NoSyn)]
   308     |> Proof.chain_facts chain_facts
   309     |> Proof.local_goal print_result (K I) (apsnd (rpair I))
   310       "guess" before_qed after_qed [(("", []), [Logic.mk_term goal, goal])]
   311     |> Proof.refine (Method.primitive_text (K (Goal.init (cert thesis)))) |> Seq.hd
   312   end;
   313 
   314 in
   315 
   316 val guess = gen_guess ProofContext.read_vars;
   317 val guess_i = gen_guess ProofContext.cert_vars;
   318 
   319 end;
   320 
   321 
   322 
   323 (** statements with several cases **)
   324 
   325 fun statement cases =
   326   let
   327     val names =
   328       cases |> map_index (fn (i, ("", _)) => string_of_int (i + 1) | (_, (name, _)) => name);
   329     val elems = cases |> map (fn (_, (vars, _)) =>
   330       Element.Constrains (vars |> map_filter (fn (x, SOME T) => SOME (x, T) | _ => NONE)));
   331     val concl = cases |> map (fn (_, (_, props)) => (("", []), map (rpair []) props));
   332 
   333     fun mk_stmt stmt ctxt =
   334       let
   335         val thesis =
   336           ObjectLogic.fixed_judgment (ProofContext.theory_of ctxt) AutoBind.thesisN;
   337         val atts = map Attrib.internal
   338           [RuleCases.consumes (~ (length cases)), RuleCases.case_names names];
   339 
   340         fun assume_case ((name, (vars, _)), (_, propp)) ctxt' =
   341           let
   342             val xs = map fst vars;
   343             val props = map fst propp;
   344             val (parms, ctxt'') =
   345               ctxt'
   346               |> fold Variable.declare_term props
   347               |> fold_map ProofContext.inferred_param xs;
   348             val asm = Term.list_all_free (parms, Logic.list_implies (props, thesis));
   349           in
   350             ctxt' |> (snd o ProofContext.add_fixes_i (map (fn x => (x, NONE, NoSyn)) xs));
   351             ctxt' |> ProofContext.add_assms_i Assumption.assume_export
   352               [((name, [ContextRules.intro_query NONE]), [(asm, [])])]
   353             |>> (fn [(_, [th])] => th)
   354           end;
   355         val (ths, ctxt') = ctxt
   356           |> (snd o ProofContext.add_fixes_i [(AutoBind.thesisN, NONE, NoSyn)])
   357           |> fold_map assume_case (cases ~~ stmt)
   358           |-> (fn ths => ProofContext.note_thmss_i [((thatN, []), [(ths, [])])] #> #2 #> pair ths);
   359       in (([(("", atts), [(thesis, [])])], ths), ctxt') end;
   360   in ((elems, concl), mk_stmt) end;
   361 
   362 end;