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