src/Pure/Isar/rule_insts.ML
author wenzelm
Wed Nov 07 22:20:12 2007 +0100 (2007-11-07)
changeset 25333 0c509c33cfb7
parent 25329 63e8de11c8e9
child 25354 69560579abf1
permissions -rw-r--r--
Syntax.read_typ;
rule_tac etc.: proper read_termTs (discontinued rogue type-inference);
     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 true (* FIXME 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.add_setup (Attrib.add_attributes
   222  [("where", where_att, "named instantiation of theorem"),
   223   ("of", of_att, "positional instantiation of theorem")]);
   224 
   225 
   226 
   227 (** methods **)
   228 
   229 (* rule_tac etc. -- refer to dynamic goal state!! *)   (* FIXME cleanup!! *)
   230 
   231 fun bires_inst_tac bires_flag ctxt insts thm =
   232   let
   233     val thy = ProofContext.theory_of ctxt;
   234     (* Separate type and term insts *)
   235     fun has_type_var ((x, _), _) = (case Symbol.explode x of
   236           "'"::cs => true | cs => false);
   237     val Tinsts = List.filter has_type_var insts;
   238     val tinsts = filter_out has_type_var insts;
   239 
   240     (* Tactic *)
   241     fun tac i st =
   242       let
   243         val (_, _, Bi, _) = Thm.dest_state (st, i);
   244         val params = Logic.strip_params Bi;  (*params of subgoal i as string typ pairs*)
   245         val params = rev (Term.rename_wrt_term Bi params)
   246           (*as they are printed: bound variables with*)
   247           (*the same name are renamed during printing*)
   248 
   249         val (param_names, ctxt') = ctxt
   250           |> Variable.declare_thm thm
   251           |> Thm.fold_terms Variable.declare_constraints st
   252           |> ProofContext.add_fixes_i (map (fn (x, T) => (x, SOME T, NoSyn)) params);
   253 
   254         (* Process type insts: Tinsts_env *)
   255         fun absent xi = error
   256               ("No such variable in theorem: " ^ Term.string_of_vname xi);
   257         val (rtypes, rsorts) = Drule.types_sorts thm;
   258         fun readT (xi, s) =
   259             let val S = case rsorts xi of SOME S => S | NONE => absent xi;
   260                 val T = Syntax.read_typ ctxt' s;
   261                 val U = TVar (xi, S);
   262             in if Sign.typ_instance thy (T, U) then (U, T)
   263                else error ("Instantiation of " ^ Term.string_of_vname xi ^ " fails")
   264             end;
   265         val Tinsts_env = map readT Tinsts;
   266         (* Preprocess rule: extract vars and their types, apply Tinsts *)
   267         fun get_typ xi =
   268           (case rtypes xi of
   269                SOME T => typ_subst_atomic Tinsts_env T
   270              | NONE => absent xi);
   271         val (xis, ss) = Library.split_list tinsts;
   272         val Ts = map get_typ xis;
   273 
   274         val (ts, envT) = read_termTs ctxt' true ss Ts;
   275         val envT' = map (fn (ixn, T) =>
   276           (TVar (ixn, the (rsorts ixn)), T)) envT @ Tinsts_env;
   277         val cenv =
   278           map
   279             (fn (xi, t) =>
   280               pairself (Thm.cterm_of thy) (Var (xi, fastype_of t), t))
   281             (distinct
   282               (fn ((x1, t1), (x2, t2)) => x1 = x2 andalso t1 aconv t2)
   283               (xis ~~ ts));
   284         (* Lift and instantiate rule *)
   285         val {maxidx, ...} = rep_thm st;
   286         val paramTs = map #2 params
   287         and inc = maxidx+1
   288         fun liftvar (Var ((a,j), T)) =
   289               Var((a, j+inc), paramTs ---> Logic.incr_tvar inc T)
   290           | liftvar t = raise TERM("Variable expected", [t]);
   291         fun liftterm t = list_abs_free
   292               (param_names ~~ paramTs, Logic.incr_indexes(paramTs,inc) t)
   293         fun liftpair (cv,ct) =
   294               (cterm_fun liftvar cv, cterm_fun liftterm ct)
   295         val lifttvar = pairself (ctyp_of thy o Logic.incr_tvar inc);
   296         val rule = Drule.instantiate
   297               (map lifttvar envT', map liftpair cenv)
   298               (Thm.lift_rule (Thm.cprem_of st i) thm)
   299       in
   300         if i > nprems_of st then no_tac st
   301         else st |>
   302           compose_tac (bires_flag, rule, nprems_of thm) i
   303       end
   304            handle TERM (msg,_)   => (warning msg; no_tac st)
   305                 | THM  (msg,_,_) => (warning msg; no_tac st);
   306   in tac end;
   307 
   308 local
   309 
   310 fun gen_inst _ tac _ (quant, ([], thms)) =
   311       Method.METHOD (fn facts => quant (Method.insert_tac facts THEN' tac thms))
   312   | gen_inst inst_tac _ ctxt (quant, (insts, [thm])) =
   313       Method.METHOD (fn facts =>
   314         quant (Method.insert_tac facts THEN' inst_tac ctxt insts thm))
   315   | gen_inst _ _ _ _ = error "Cannot have instantiations with multiple rules";
   316 
   317 in
   318 
   319 val res_inst_meth = gen_inst (bires_inst_tac false) Tactic.resolve_tac;
   320 
   321 val eres_inst_meth = gen_inst (bires_inst_tac true) Tactic.eresolve_tac;
   322 
   323 val cut_inst_meth =
   324   gen_inst
   325     (fn ctxt => fn insts => bires_inst_tac false ctxt insts o Tactic.make_elim_preserve)
   326     Tactic.cut_rules_tac;
   327 
   328 val dres_inst_meth =
   329   gen_inst
   330     (fn ctxt => fn insts => bires_inst_tac true ctxt insts o Tactic.make_elim_preserve)
   331     Tactic.dresolve_tac;
   332 
   333 val forw_inst_meth =
   334   gen_inst
   335     (fn ctxt => fn insts => fn rule =>
   336        bires_inst_tac false ctxt insts (Tactic.make_elim_preserve rule) THEN'
   337        assume_tac)
   338     Tactic.forward_tac;
   339 
   340 fun subgoal_tac ctxt sprop =
   341   DETERM o bires_inst_tac false ctxt [(("psi", 0), sprop)] cut_rl;
   342 
   343 fun subgoals_tac ctxt sprops = EVERY' (map (subgoal_tac ctxt) sprops);
   344 
   345 fun thin_tac ctxt s =
   346   bires_inst_tac true ctxt [(("V", 0), s)] thin_rl;
   347 
   348 
   349 (* method syntax *)
   350 
   351 val insts =
   352   Scan.optional
   353     (Args.enum1 "and" (Scan.lift (Args.name -- (Args.$$$ "=" |-- Args.!!! Args.name))) --|
   354       Scan.lift (Args.$$$ "in")) [] -- Attrib.thms;
   355 
   356 fun inst_args f src ctxt =
   357   f ctxt (fst (Method.syntax (Args.goal_spec HEADGOAL -- insts) src ctxt));
   358 
   359 val insts_var =
   360   Scan.optional
   361     (Args.enum1 "and" (Scan.lift (Args.var -- (Args.$$$ "=" |-- Args.!!! Args.name))) --|
   362       Scan.lift (Args.$$$ "in")) [] -- Attrib.thms;
   363 
   364 fun inst_args_var f src ctxt =
   365   f ctxt (fst (Method.syntax (Args.goal_spec HEADGOAL -- insts_var) src ctxt));
   366 
   367 
   368 (* setup *)
   369 
   370 val _ = Context.add_setup (Method.add_methods
   371  [("rule_tac", inst_args_var res_inst_meth,
   372     "apply rule (dynamic instantiation)"),
   373   ("erule_tac", inst_args_var eres_inst_meth,
   374     "apply rule in elimination manner (dynamic instantiation)"),
   375   ("drule_tac", inst_args_var dres_inst_meth,
   376     "apply rule in destruct manner (dynamic instantiation)"),
   377   ("frule_tac", inst_args_var forw_inst_meth,
   378     "apply rule in forward manner (dynamic instantiation)"),
   379   ("cut_tac", inst_args_var cut_inst_meth,
   380     "cut rule (dynamic instantiation)"),
   381   ("subgoal_tac", Method.goal_args_ctxt (Scan.repeat1 Args.name) subgoals_tac,
   382     "insert subgoal (dynamic instantiation)"),
   383   ("thin_tac", Method.goal_args_ctxt Args.name thin_tac,
   384     "remove premise (dynamic instantiation)")]);
   385 
   386 end;
   387 
   388 end;