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