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