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