src/Pure/Isar/rule_insts.ML
author wenzelm
Mon Jun 16 22:13:54 2008 +0200 (2008-06-16)
changeset 27245 817d34377170
parent 27236 80356567e7ad
child 27282 432a5baa7546
permissions -rw-r--r--
added instantiate_tac, cut_inst_tac, forw_inst_tac, dres_inst_tac, make_elim_preserve (from tactic.ML);
pervasive operations;
tuned;
     1 (*  Title:      Pure/Isar/rule_insts.ML
     2     ID:         $Id$
     3     Author:     Makarius
     4 
     5 Rule instantiations -- operations within a rule/subgoal context.
     6 *)
     7 
     8 signature BASIC_RULE_INSTS =
     9 sig
    10   val read_instantiate: Proof.context -> (indexname * string) list -> thm -> thm
    11   val instantiate_tac: Proof.context -> (indexname * string) list -> tactic
    12   val res_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    13   val eres_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    14   val cut_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    15   val forw_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    16   val dres_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    17   val thin_tac: Proof.context -> string -> int -> tactic
    18   val subgoal_tac: Proof.context -> string -> int -> tactic
    19   val subgoals_tac: Proof.context -> string list -> int -> tactic
    20 end;
    21 
    22 signature RULE_INSTS =
    23 sig
    24   include BASIC_RULE_INSTS
    25   val make_elim_preserve: thm -> thm
    26 end;
    27 
    28 structure RuleInsts: RULE_INSTS =
    29 struct
    30 
    31 
    32 (** reading instantiations **)
    33 
    34 local
    35 
    36 fun is_tvar (x, _) = String.isPrefix "'" x;
    37 
    38 fun error_var msg xi = error (msg ^ Term.string_of_vname xi);
    39 
    40 fun the_sort tvars xi = the (AList.lookup (op =) tvars xi)
    41   handle Option.Option => error_var "No such type variable in theorem: " xi;
    42 
    43 fun the_type vars xi = the (AList.lookup (op =) vars xi)
    44   handle Option.Option => error_var "No such variable in theorem: " xi;
    45 
    46 fun unify_vartypes thy vars (xi, u) (unifier, maxidx) =
    47   let
    48     val T = the_type vars xi;
    49     val U = Term.fastype_of u;
    50     val maxidx' = Term.maxidx_term u (Int.max (#2 xi, maxidx));
    51   in
    52     Sign.typ_unify thy (T, U) (unifier, maxidx')
    53       handle Type.TUNIFY => error_var "Incompatible type for instantiation of " xi
    54   end;
    55 
    56 fun instantiate inst =
    57   TermSubst.instantiate ([], map (fn (xi, t) => ((xi, Term.fastype_of t), t)) inst) #>
    58   Envir.beta_norm;
    59 
    60 fun make_instT f v =
    61   let
    62     val T = TVar v;
    63     val T' = f T;
    64   in if T = T' then NONE else SOME (T, T') end;
    65 
    66 fun make_inst f v =
    67   let
    68     val t = Var v;
    69     val t' = f t;
    70   in if t aconv t' then NONE else SOME (t, t') end;
    71 
    72 in
    73 
    74 fun read_termTs ctxt schematic ss Ts =
    75   let
    76     fun parse T = if T = propT then Syntax.parse_prop ctxt else Syntax.parse_term ctxt;
    77     val ts = map2 parse Ts ss;
    78     val ts' =
    79       map2 (TypeInfer.constrain o TypeInfer.paramify_vars) Ts ts
    80       |> Syntax.check_terms ((schematic ? ProofContext.set_mode ProofContext.mode_schematic) ctxt)
    81       |> Variable.polymorphic ctxt;
    82     val Ts' = map Term.fastype_of ts';
    83     val tyenv = fold Type.raw_match (Ts ~~ Ts') Vartab.empty;
    84   in (ts', map (apsnd snd) (Vartab.dest tyenv)) end;
    85 
    86 fun read_insts ctxt mixed_insts (tvars, vars) =
    87   let
    88     val thy = ProofContext.theory_of ctxt;
    89     val cert = Thm.cterm_of thy;
    90     val certT = Thm.ctyp_of thy;
    91 
    92     val (type_insts, term_insts) = List.partition (is_tvar o fst) mixed_insts;
    93     val internal_insts = term_insts |> map_filter
    94       (fn (xi, Args.Term t) => SOME (xi, t)
    95         | (_, Args.Text _) => NONE
    96         | (xi, _) => error_var "Term argument expected for " xi);
    97     val external_insts = term_insts |> map_filter
    98       (fn (xi, Args.Text s) => SOME (xi, s) | _ => NONE);
    99 
   100 
   101     (* mixed type instantiations *)
   102 
   103     fun readT (xi, arg) =
   104       let
   105         val S = the_sort tvars xi;
   106         val T =
   107           (case arg of
   108             Args.Text s => Syntax.read_typ ctxt s
   109           | Args.Typ T => T
   110           | _ => error_var "Type argument expected for " xi);
   111       in
   112         if Sign.of_sort thy (T, S) then ((xi, S), T)
   113         else error_var "Incompatible sort for typ instantiation of " xi
   114       end;
   115 
   116     val type_insts1 = map readT type_insts;
   117     val instT1 = TermSubst.instantiateT type_insts1;
   118     val vars1 = map (apsnd instT1) vars;
   119 
   120 
   121     (* internal term instantiations *)
   122 
   123     val instT2 = Envir.norm_type
   124       (#1 (fold (unify_vartypes thy vars1) internal_insts (Vartab.empty, 0)));
   125     val vars2 = map (apsnd instT2) vars1;
   126     val internal_insts2 = map (apsnd (map_types instT2)) internal_insts;
   127     val inst2 = instantiate internal_insts2;
   128 
   129 
   130     (* external term instantiations *)
   131 
   132     val (xs, strs) = split_list external_insts;
   133     val Ts = map (the_type vars2) xs;
   134     val (ts, inferred) = read_termTs ctxt false strs Ts;
   135 
   136     val instT3 = Term.typ_subst_TVars inferred;
   137     val vars3 = map (apsnd instT3) vars2;
   138     val internal_insts3 = map (apsnd (map_types instT3)) internal_insts2;
   139     val external_insts3 = xs ~~ ts;
   140     val inst3 = instantiate external_insts3;
   141 
   142 
   143     (* results *)
   144 
   145     val type_insts3 = map (fn ((a, _), T) => (a, instT3 (instT2 T))) type_insts1;
   146     val term_insts3 = internal_insts3 @ external_insts3;
   147 
   148     val inst_tvars = map_filter (make_instT (instT3 o instT2 o instT1)) tvars;
   149     val inst_vars = map_filter (make_inst (inst3 o inst2)) vars3;
   150   in
   151     ((type_insts3, term_insts3),
   152       (map (pairself certT) inst_tvars, map (pairself cert) inst_vars))
   153   end;
   154 
   155 fun read_instantiate_mixed ctxt mixed_insts thm =
   156   let
   157     val ctxt' = ctxt |> Variable.declare_thm thm
   158       |> fold (fn a => Variable.declare_internal (Logic.mk_type (TFree (a, [])))) (Drule.add_used thm []);  (* FIXME tmp *)
   159     val tvars = Thm.fold_terms Term.add_tvars thm [];
   160     val vars = Thm.fold_terms Term.add_vars thm [];
   161     val ((type_insts, term_insts), insts) = read_insts ctxt' (map snd mixed_insts) (tvars, vars);
   162 
   163     val _ = (*assign internalized values*)
   164       mixed_insts |> List.app (fn (arg, (xi, _)) =>
   165         if is_tvar xi then
   166           Args.assign (SOME (Args.Typ (the (AList.lookup (op =) type_insts xi)))) arg
   167         else
   168           Args.assign (SOME (Args.Term (the (AList.lookup (op =) term_insts xi)))) arg);
   169   in
   170     Drule.instantiate insts thm |> RuleCases.save thm
   171   end;
   172 
   173 fun read_instantiate_mixed' ctxt (args, concl_args) thm =
   174   let
   175     fun zip_vars _ [] = []
   176       | zip_vars (_ :: xs) ((_, NONE) :: rest) = zip_vars xs rest
   177       | zip_vars ((x, _) :: xs) ((arg, SOME t) :: rest) = (arg, (x, t)) :: zip_vars xs rest
   178       | zip_vars [] _ = error "More instantiations than variables in theorem";
   179     val insts =
   180       zip_vars (rev (Term.add_vars (Thm.full_prop_of thm) [])) args @
   181       zip_vars (rev (Term.add_vars (Thm.concl_of thm) [])) concl_args;
   182   in read_instantiate_mixed ctxt insts thm end;
   183 
   184 end;
   185 
   186 
   187 (* instantiation of rule or goal state *)
   188 
   189 fun read_instantiate ctxt args thm =
   190   read_instantiate_mixed (ctxt |> ProofContext.set_mode ProofContext.mode_schematic)  (* FIXME !? *)
   191     (map (fn (x, y) => (Args.eof, (x, Args.Text y))) args) thm;
   192 
   193 fun instantiate_tac ctxt args = PRIMITIVE (read_instantiate ctxt args);
   194 
   195 
   196 
   197 (** attributes **)
   198 
   199 (* where: named instantiation *)
   200 
   201 local
   202 
   203 val value =
   204   Args.internal_typ >> Args.Typ ||
   205   Args.internal_term >> Args.Term ||
   206   Args.name >> Args.Text;
   207 
   208 val inst = Args.var -- (Args.$$$ "=" |-- Args.ahead -- value)
   209   >> (fn (xi, (a, v)) => (a, (xi, v)));
   210 
   211 in
   212 
   213 val where_att = Attrib.syntax (Args.and_list (Scan.lift inst) >> (fn args =>
   214   Thm.rule_attribute (fn context => read_instantiate_mixed (Context.proof_of context) args)));
   215 
   216 end;
   217 
   218 
   219 (* of: positional instantiation (terms only) *)
   220 
   221 local
   222 
   223 val value =
   224   Args.internal_term >> Args.Term ||
   225   Args.name >> Args.Text;
   226 
   227 val inst = Args.ahead -- Args.maybe value;
   228 val concl = Args.$$$ "concl" -- Args.colon;
   229 
   230 val insts =
   231   Scan.repeat (Scan.unless concl inst) --
   232   Scan.optional (concl |-- Scan.repeat inst) [];
   233 
   234 in
   235 
   236 val of_att = Attrib.syntax (Scan.lift insts >> (fn args =>
   237   Thm.rule_attribute (fn context => read_instantiate_mixed' (Context.proof_of context) args)));
   238 
   239 end;
   240 
   241 
   242 (* setup *)
   243 
   244 val _ = Context.>> (Context.map_theory
   245   (Attrib.add_attributes
   246    [("where", where_att, "named instantiation of theorem"),
   247     ("of", of_att, "positional instantiation of theorem")]));
   248 
   249 
   250 
   251 (** tactics **)
   252 
   253 (* resolution after lifting and instantation; may refer to parameters of the subgoal *)
   254 
   255 (* FIXME cleanup this mess!!! *)
   256 
   257 fun bires_inst_tac bires_flag ctxt insts thm =
   258   let
   259     val thy = ProofContext.theory_of ctxt;
   260     (* Separate type and term insts *)
   261     fun has_type_var ((x, _), _) = (case Symbol.explode x of
   262           "'"::cs => true | cs => false);
   263     val Tinsts = List.filter has_type_var insts;
   264     val tinsts = filter_out has_type_var insts;
   265 
   266     (* Tactic *)
   267     fun tac i st =
   268       let
   269         val (_, _, Bi, _) = Thm.dest_state (st, i);
   270         val params = Logic.strip_params Bi;  (*params of subgoal i as string typ pairs*)
   271         val params = rev (Term.rename_wrt_term Bi params)
   272           (*as they are printed: bound variables with*)
   273           (*the same name are renamed during printing*)
   274 
   275         val (param_names, ctxt') = ctxt
   276           |> Variable.declare_thm thm
   277           |> Thm.fold_terms Variable.declare_constraints st
   278           |> ProofContext.add_fixes_i (map (fn (x, T) => (x, SOME T, NoSyn)) params);
   279 
   280         (* Process type insts: Tinsts_env *)
   281         fun absent xi = error
   282               ("No such variable in theorem: " ^ Term.string_of_vname xi);
   283         val (rtypes, rsorts) = Drule.types_sorts thm;
   284         fun readT (xi, s) =
   285             let val S = case rsorts xi of SOME S => S | NONE => absent xi;
   286                 val T = Syntax.read_typ ctxt' s;
   287                 val U = TVar (xi, S);
   288             in if Sign.typ_instance thy (T, U) then (U, T)
   289                else error ("Instantiation of " ^ Term.string_of_vname xi ^ " fails")
   290             end;
   291         val Tinsts_env = map readT Tinsts;
   292         (* Preprocess rule: extract vars and their types, apply Tinsts *)
   293         fun get_typ xi =
   294           (case rtypes xi of
   295                SOME T => typ_subst_atomic Tinsts_env T
   296              | NONE => absent xi);
   297         val (xis, ss) = Library.split_list tinsts;
   298         val Ts = map get_typ xis;
   299 
   300         val (ts, envT) = read_termTs ctxt' true ss Ts;
   301         val envT' = map (fn (ixn, T) =>
   302           (TVar (ixn, the (rsorts ixn)), T)) envT @ Tinsts_env;
   303         val cenv =
   304           map
   305             (fn (xi, t) =>
   306               pairself (Thm.cterm_of thy) (Var (xi, fastype_of t), t))
   307             (distinct
   308               (fn ((x1, t1), (x2, t2)) => x1 = x2 andalso t1 aconv t2)
   309               (xis ~~ ts));
   310         (* Lift and instantiate rule *)
   311         val {maxidx, ...} = rep_thm st;
   312         val paramTs = map #2 params
   313         and inc = maxidx+1
   314         fun liftvar (Var ((a,j), T)) =
   315               Var((a, j+inc), paramTs ---> Logic.incr_tvar inc T)
   316           | liftvar t = raise TERM("Variable expected", [t]);
   317         fun liftterm t = list_abs_free
   318               (param_names ~~ paramTs, Logic.incr_indexes(paramTs,inc) t)
   319         fun liftpair (cv,ct) =
   320               (cterm_fun liftvar cv, cterm_fun liftterm ct)
   321         val lifttvar = pairself (ctyp_of thy o Logic.incr_tvar inc);
   322         val rule = Drule.instantiate
   323               (map lifttvar envT', map liftpair cenv)
   324               (Thm.lift_rule (Thm.cprem_of st i) thm)
   325       in
   326         if i > nprems_of st then no_tac st
   327         else st |>
   328           compose_tac (bires_flag, rule, nprems_of thm) i
   329       end
   330            handle TERM (msg,_)   => (warning msg; no_tac st)
   331                 | THM  (msg,_,_) => (warning msg; no_tac st);
   332   in tac end;
   333 
   334 val res_inst_tac = bires_inst_tac false;
   335 val eres_inst_tac = bires_inst_tac true;
   336 
   337 
   338 (* forward resolution *)
   339 
   340 fun make_elim_preserve rl =
   341   let
   342     val cert = Thm.cterm_of (Thm.theory_of_thm rl);
   343     val maxidx = Thm.maxidx_of rl;
   344     fun cvar xi = cert (Var (xi, propT));
   345     val revcut_rl' =
   346       instantiate ([], [(cvar ("V", 0), cvar ("V", maxidx + 1)),
   347         (cvar ("W", 0), cvar ("W", maxidx + 1))]) Drule.revcut_rl;
   348   in
   349     (case Seq.list_of (bicompose false (false, rl, Thm.nprems_of rl) 1 revcut_rl') of
   350       [th] => th
   351     | _ => raise THM ("make_elim_preserve", 1, [rl]))
   352   end;
   353 
   354 (*instantiate and cut -- for atomic fact*)
   355 fun cut_inst_tac ctxt insts rule = res_inst_tac ctxt insts (make_elim_preserve rule);
   356 
   357 (*forward tactic applies a rule to an assumption without deleting it*)
   358 fun forw_inst_tac ctxt insts rule = cut_inst_tac ctxt insts rule THEN' assume_tac;
   359 
   360 (*dresolve tactic applies a rule to replace an assumption*)
   361 fun dres_inst_tac ctxt insts rule = eres_inst_tac ctxt insts (make_elim_preserve rule);
   362 
   363 
   364 (* derived tactics *)
   365 
   366 (*deletion of an assumption*)
   367 fun thin_tac ctxt s = eres_inst_tac ctxt [(("V", 0), s)] Drule.thin_rl;
   368 
   369 (*Introduce the given proposition as lemma and subgoal*)
   370 fun subgoal_tac ctxt A = DETERM o res_inst_tac ctxt [(("psi", 0), A)] cut_rl;
   371 fun subgoals_tac ctxt As = EVERY' (map (subgoal_tac ctxt) As);
   372 
   373 
   374 
   375 (** methods **)
   376 
   377 (* rule_tac etc. -- refer to dynamic goal state! *)
   378 
   379 local
   380 
   381 fun gen_inst _ tac _ (quant, ([], thms)) =
   382       Method.METHOD (fn facts => quant (Method.insert_tac facts THEN' tac thms))
   383   | gen_inst inst_tac _ ctxt (quant, (insts, [thm])) =
   384       Method.METHOD (fn facts =>
   385         quant (Method.insert_tac facts THEN' inst_tac ctxt insts thm))
   386   | gen_inst _ _ _ _ = error "Cannot have instantiations with multiple rules";
   387 
   388 in
   389 
   390 val res_inst_meth = gen_inst res_inst_tac Tactic.resolve_tac;
   391 val eres_inst_meth = gen_inst eres_inst_tac Tactic.eresolve_tac;
   392 val cut_inst_meth = gen_inst cut_inst_tac Tactic.cut_rules_tac;
   393 val dres_inst_meth = gen_inst dres_inst_tac Tactic.dresolve_tac;
   394 val forw_inst_meth = gen_inst forw_inst_tac Tactic.forward_tac;
   395 
   396 end;
   397 
   398 
   399 (* method syntax *)
   400 
   401 val insts =
   402   Scan.optional
   403     (Args.enum1 "and" (Scan.lift (Args.name -- (Args.$$$ "=" |-- Args.!!! Args.name))) --|
   404       Scan.lift (Args.$$$ "in")) [] -- Attrib.thms;
   405 
   406 fun inst_args f src ctxt =
   407   f ctxt (fst (Method.syntax (Args.goal_spec HEADGOAL -- insts) src ctxt));
   408 
   409 val insts_var =
   410   Scan.optional
   411     (Args.enum1 "and" (Scan.lift (Args.var -- (Args.$$$ "=" |-- Args.!!! Args.name))) --|
   412       Scan.lift (Args.$$$ "in")) [] -- Attrib.thms;
   413 
   414 fun inst_args_var f src ctxt =
   415   f ctxt (fst (Method.syntax (Args.goal_spec HEADGOAL -- insts_var) src ctxt));
   416 
   417 
   418 (* setup *)
   419 
   420 val _ = Context.>> (Context.map_theory
   421   (Method.add_methods
   422    [("rule_tac", inst_args_var res_inst_meth,
   423       "apply rule (dynamic instantiation)"),
   424     ("erule_tac", inst_args_var eres_inst_meth,
   425       "apply rule in elimination manner (dynamic instantiation)"),
   426     ("drule_tac", inst_args_var dres_inst_meth,
   427       "apply rule in destruct manner (dynamic instantiation)"),
   428     ("frule_tac", inst_args_var forw_inst_meth,
   429       "apply rule in forward manner (dynamic instantiation)"),
   430     ("cut_tac", inst_args_var cut_inst_meth,
   431       "cut rule (dynamic instantiation)"),
   432     ("subgoal_tac", Method.goal_args_ctxt (Scan.repeat1 Args.name) subgoals_tac,
   433       "insert subgoal (dynamic instantiation)"),
   434     ("thin_tac", Method.goal_args_ctxt Args.name thin_tac,
   435       "remove premise (dynamic instantiation)")]));
   436 
   437 end;
   438 
   439 structure BasicRuleInsts: BASIC_RULE_INSTS = RuleInsts;
   440 open BasicRuleInsts;
   441