src/Pure/Isar/obtain.ML
author wenzelm
Sun Jun 11 21:59:24 2006 +0200 (2006-06-11)
changeset 19844 2c1fdc397ded
parent 19779 5c77dfb74c7b
child 19897 fe661eb3b0e7
permissions -rw-r--r--
fixes: include mixfix syntax;
     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 guess: (string * string option * mixfix) list -> bool -> Proof.state -> Proof.state
    49   val guess_i: (string * typ option * mixfix) list -> bool -> Proof.state -> Proof.state
    50   val statement: (string * ((string * 'typ option) list * 'term list)) list ->
    51     (('typ, 'term, 'fact) Element.ctxt list *
    52       ((string * Attrib.src list) * ('term * 'term list) list) list) *
    53     (((string * Attrib.src list) * (term * term list) list) list -> Proof.context ->
    54       (((string * Attrib.src list) * (term * term list) list) list * thm list) * Proof.context)
    55 end;
    56 
    57 structure Obtain: OBTAIN =
    58 struct
    59 
    60 
    61 (** obtain_export **)
    62 
    63 (*
    64   [x, A x]
    65      :
    66      B
    67   --------
    68      B
    69 *)
    70 fun obtain_export ctxt parms rule cprops thm =
    71   let
    72     val {thy, prop, maxidx, ...} = Thm.rep_thm thm;
    73     val cparms = map (Thm.cterm_of thy) parms;
    74 
    75     val thm' = thm
    76       |> Drule.implies_intr_protected cprops
    77       |> Drule.forall_intr_list cparms
    78       |> Drule.forall_elim_vars (maxidx + 1);
    79     val elim_tacs = replicate (length cprops) (Tactic.etac Drule.protectI);
    80 
    81     val concl = Logic.strip_assums_concl prop;
    82     val bads = parms inter (Term.term_frees concl);
    83   in
    84     if not (null bads) then
    85       error ("Conclusion contains obtained parameters: " ^
    86         space_implode " " (map (ProofContext.string_of_term ctxt) bads))
    87     else if not (ObjectLogic.is_judgment thy concl) then
    88       error "Conclusion in obtained context must be object-logic judgments"
    89     else (Tactic.rtac thm' THEN' RANGE elim_tacs) 1 rule
    90   end;
    91 
    92 
    93 
    94 (** obtain **)
    95 
    96 fun bind_judgment ctxt name =
    97   let
    98     val (bind, _) = ProofContext.bind_fixes [name] ctxt;
    99     val (t as _ $ Free v) = bind (ObjectLogic.fixed_judgment (ProofContext.theory_of ctxt) name);
   100   in (v, t) end;
   101 
   102 val thatN = "that";
   103 
   104 local
   105 
   106 fun gen_obtain prep_att prep_vars prep_propp
   107     name raw_vars raw_asms int state =
   108   let
   109     val _ = Proof.assert_forward_or_chain state;
   110     val ctxt = Proof.context_of state;
   111     val thy = Proof.theory_of state;
   112     val chain_facts = if can Proof.assert_chain state then Proof.the_facts state else [];
   113 
   114     (*obtain vars*)
   115     val (vars, vars_ctxt) = prep_vars raw_vars ctxt;
   116     val (_, fix_ctxt) = vars_ctxt |> ProofContext.add_fixes_i vars;
   117     val xs = map #1 vars;
   118 
   119     (*obtain asms*)
   120     val (asms_ctxt, proppss) = prep_propp (fix_ctxt, map snd raw_asms);
   121     val asm_props = maps (map fst) proppss;
   122     val asms = map fst (Attrib.map_specs (prep_att thy) raw_asms) ~~ proppss;
   123 
   124     val _ = ProofContext.warn_extra_tfrees fix_ctxt asms_ctxt;
   125 
   126     (*obtain statements*)
   127     val thesisN = Term.variant xs AutoBind.thesisN;
   128     val (thesis_var, thesis) = bind_judgment fix_ctxt thesisN;
   129 
   130     fun occs_var x = Library.get_first (fn t =>
   131       Term.find_free t (ProofContext.get_skolem fix_ctxt x)) asm_props;
   132     val raw_parms = map occs_var xs;
   133     val parms = map_filter I raw_parms;
   134     val parm_names =
   135       map_filter (fn (SOME (Free a), x) => SOME (a, x) | _ => NONE) (raw_parms ~~ xs);
   136 
   137     val that_name = if name = "" then thatN else name;
   138     val that_prop =
   139       Term.list_all_free (map #1 parm_names, Logic.list_implies (asm_props, thesis))
   140       |> Library.curry Logic.list_rename_params (map #2 parm_names);
   141     val obtain_prop =
   142       Logic.list_rename_params ([AutoBind.thesisN],
   143         Term.list_all_free ([thesis_var], Logic.mk_implies (that_prop, thesis)));
   144 
   145     fun after_qed _ =
   146       Proof.local_qed (NONE, false)
   147       #> Seq.map (`Proof.the_fact #-> (fn rule =>
   148         Proof.fix_i (map2 (fn x => fn (_, T, mx) => (x, T, mx)) xs vars)
   149         #> Proof.assm_i (K (obtain_export ctxt parms rule)) asms));
   150   in
   151     state
   152     |> Proof.enter_forward
   153     |> Proof.have_i NONE (K Seq.single) [(("", []), [(obtain_prop, [])])] int
   154     |> Proof.proof (SOME Method.succeed_text) |> Seq.hd
   155     |> Proof.fix_i [(thesisN, NONE, NoSyn)]
   156     |> Proof.assume_i [((that_name, [ContextRules.intro_query NONE]), [(that_prop, [])])]
   157     |> `Proof.the_facts
   158     ||> Proof.chain_facts chain_facts
   159     ||> Proof.show_i NONE after_qed [(("", []), [(thesis, [])])] false
   160     |-> Proof.refine_insert
   161   end;
   162 
   163 in
   164 
   165 val obtain = gen_obtain Attrib.attribute ProofContext.read_vars ProofContext.read_propp;
   166 val obtain_i = gen_obtain (K I) ProofContext.cert_vars ProofContext.cert_propp;
   167 
   168 end;
   169 
   170 
   171 
   172 (** guess **)
   173 
   174 local
   175 
   176 fun unify_params ctxt vars raw_rule =
   177   let
   178     val thy = ProofContext.theory_of ctxt;
   179     val string_of_typ = ProofContext.string_of_typ ctxt;
   180     val string_of_term = setmp show_types true (ProofContext.string_of_term ctxt);
   181 
   182     fun err msg th = error (msg ^ ":\n" ^ ProofContext.string_of_thm ctxt th);
   183 
   184     val maxidx = fold (Term.maxidx_typ o snd) vars ~1;
   185     val rule = Thm.incr_indexes (maxidx + 1) raw_rule;
   186 
   187     val params = RuleCases.strip_params (Logic.nth_prem (1, Thm.prop_of rule));
   188     val m = length vars;
   189     val n = length params;
   190     val _ = m <= n orelse err "More variables than parameters in obtained rule" rule;
   191 
   192     fun unify ((x, T), (y, U)) (tyenv, max) = Sign.typ_unify thy (T, U) (tyenv, max)
   193       handle Type.TUNIFY =>
   194         err ("Failed to unify variable " ^
   195           string_of_term (Free (x, Envir.norm_type tyenv T)) ^ " against parameter " ^
   196           string_of_term (Syntax.mark_boundT (y, Envir.norm_type tyenv U)) ^ " in") rule;
   197     val (tyenv, _) = fold unify (vars ~~ Library.take (m, params))
   198       (Vartab.empty, Int.max (maxidx, Thm.maxidx_of rule));
   199     val norm_type = Envir.norm_type tyenv;
   200 
   201     val xs = map (apsnd norm_type) vars;
   202     val ys = map (apsnd norm_type) (Library.drop (m, params));
   203     val ys' = map Syntax.internal (Term.variantlist (map fst ys, map fst xs)) ~~ map #2 ys;
   204 
   205     val instT =
   206       fold (Term.add_tvarsT o #2) params []
   207       |> map (TVar #> (fn T => (Thm.ctyp_of thy T, Thm.ctyp_of thy (norm_type T))));
   208     val rule' = rule |> Thm.instantiate (instT, []);
   209 
   210     val tvars = Drule.tvars_of rule';
   211     val vars = subtract (op =) (Term.add_vars (Thm.concl_of rule') []) (Drule.vars_of rule');
   212     val _ =
   213       if null tvars andalso null vars then ()
   214       else err ("Illegal schematic variable(s) " ^
   215         commas (map (string_of_typ o TVar) tvars @ map (string_of_term o Var) vars) ^ " in") rule';
   216   in (xs @ ys', rule') end;
   217 
   218 fun inferred_type (x, _, mx) ctxt =
   219   let val ((_, T), ctxt') = ProofContext.inferred_param x ctxt
   220   in ((x, T, mx), ctxt') end;
   221 
   222 fun polymorphic (vars, ctxt) =
   223   let val Ts = map Logic.dest_type (ProofContext.polymorphic ctxt (map (Logic.mk_type o #2) vars))
   224   in map2 (fn (x, _, mx) => fn T => ((x, T), mx)) vars Ts end;
   225 
   226 fun gen_guess prep_vars raw_vars int state =
   227   let
   228     val _ = Proof.assert_forward_or_chain state;
   229     val thy = Proof.theory_of state;
   230     val ctxt = Proof.context_of state;
   231     val chain_facts = if can Proof.assert_chain state then Proof.the_facts state else [];
   232 
   233     val (thesis_var, thesis) = bind_judgment ctxt AutoBind.thesisN;
   234     val vars = ctxt |> prep_vars raw_vars |-> fold_map inferred_type |> polymorphic;
   235 
   236     fun check_result th =
   237       (case Thm.prems_of th of
   238         [prem] =>
   239           if Thm.concl_of th aconv thesis andalso
   240             Logic.strip_assums_concl prem aconv thesis then ()
   241           else error ("Guessed a different clause:\n" ^ ProofContext.string_of_thm ctxt th)
   242       | [] => error "Goal solved -- nothing guessed."
   243       | _ => error ("Guess split into several cases:\n" ^ ProofContext.string_of_thm ctxt th));
   244 
   245     fun guess_context [_, raw_rule] =
   246       let
   247         val (parms, rule) = unify_params ctxt (map #1 vars) raw_rule;
   248         val (bind, _) = ProofContext.bind_fixes (map #1 parms) ctxt;
   249         val ts = map (bind o Free) parms;
   250         val ps = map dest_Free ts;
   251         val asms =
   252           Logic.strip_assums_hyp (Logic.nth_prem (1, Thm.prop_of rule))
   253           |> map (fn asm => (Term.betapplys (Term.list_abs (ps, asm), ts), []));
   254         val _ = not (null asms) orelse error "Trivial result -- nothing guessed";
   255       in
   256         Proof.fix_i (map2 (fn (x, T) => fn (_, mx) => (x, SOME T, mx)) parms vars)
   257         #> Proof.assm_i (K (obtain_export ctxt ts rule)) [(("", []), asms)]
   258         #> Proof.add_binds_i AutoBind.no_facts
   259       end;
   260 
   261     val goal = Var (("guess", 0), propT);
   262     fun print_result ctxt' (k, [(s, [_, th])]) =
   263       ProofDisplay.print_results int ctxt' (k, [(s, [th])]);
   264     val before_qed = SOME (Method.primitive_text (Goal.conclude #> (fn th =>
   265       Goal.protect (Conjunction.intr (Drule.mk_term (Thm.cprop_of th)) th))));
   266     fun after_qed [[_, res]] =
   267       (check_result res; Proof.end_block #> Seq.map (`Proof.the_facts #-> guess_context));
   268   in
   269     state
   270     |> Proof.enter_forward
   271     |> Proof.begin_block
   272     |> Proof.fix_i [(AutoBind.thesisN, NONE, NoSyn)]
   273     |> Proof.chain_facts chain_facts
   274     |> Proof.local_goal print_result (K I) (apsnd (rpair I))
   275       "guess" before_qed after_qed [(("", []), [Logic.mk_term goal, goal])]
   276     |> Proof.refine (Method.primitive_text (K (Goal.init (Thm.cterm_of thy thesis)))) |> Seq.hd
   277   end;
   278 
   279 in
   280 
   281 val guess = gen_guess ProofContext.read_vars;
   282 val guess_i = gen_guess ProofContext.cert_vars;
   283 
   284 end;
   285 
   286 
   287 
   288 (** statements with several cases **)
   289 
   290 fun statement cases =
   291   let
   292     val names =
   293       cases |> map_index (fn (i, ("", _)) => string_of_int (i + 1) | (_, (name, _)) => name);
   294     val elems = cases |> map (fn (_, (vars, _)) =>
   295       Element.Constrains (vars |> map_filter (fn (x, SOME T) => SOME (x, T) | _ => NONE)));
   296     val concl = cases |> map (fn (_, (_, props)) => (("", []), map (rpair []) props));
   297 
   298     fun mk_stmt stmt ctxt =
   299       let
   300         val thesis =
   301           ObjectLogic.fixed_judgment (ProofContext.theory_of ctxt) AutoBind.thesisN;
   302         val atts = map Attrib.internal
   303           [RuleCases.consumes (~ (length cases)), RuleCases.case_names names];
   304 
   305         fun assume_case ((name, (vars, _)), (_, propp)) ctxt' =
   306           let
   307             val xs = map fst vars;
   308             val props = map fst propp;
   309             val (parms, ctxt'') =
   310               ctxt'
   311               |> fold ProofContext.declare_term props
   312               |> fold_map ProofContext.inferred_param xs;
   313             val asm = Term.list_all_free (parms, Logic.list_implies (props, thesis));
   314           in
   315             ctxt' |> (snd o ProofContext.add_fixes_i (map (fn x => (x, NONE, NoSyn)) xs));
   316             ctxt' |> ProofContext.add_assms_i ProofContext.assume_export
   317               [((name, [ContextRules.intro_query NONE]), [(asm, [])])]
   318             |>> (fn [(_, [th])] => th)
   319           end;
   320         val (ths, ctxt') = ctxt
   321           |> (snd o ProofContext.add_fixes_i [(AutoBind.thesisN, NONE, NoSyn)])
   322           |> fold_map assume_case (cases ~~ stmt)
   323           |-> (fn ths => ProofContext.note_thmss_i [((thatN, []), [(ths, [])])] #> #2 #> pair ths);
   324       in (([(("", atts), [(thesis, [])])], ths), ctxt') end;
   325   in ((elems, concl), mk_stmt) end;
   326 
   327 end;