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