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