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