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