src/Pure/Tools/rule_insts.ML
author wenzelm
Wed Nov 26 20:05:34 2014 +0100 (2014-11-26)
changeset 59058 a78612c67ec0
parent 58963 26bf09b95dda
child 59498 50b60f501b05
permissions -rw-r--r--
renamed "pairself" to "apply2", in accordance to @{apply 2};
     1 (*  Title:      Pure/Tools/rule_insts.ML
     2     Author:     Makarius
     3 
     4 Rule instantiations -- operations within implicit rule / subgoal context.
     5 *)
     6 
     7 signature BASIC_RULE_INSTS =
     8 sig
     9   val res_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    10   val eres_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    11   val cut_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    12   val forw_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    13   val dres_inst_tac: Proof.context -> (indexname * string) list -> thm -> int -> tactic
    14   val thin_tac: Proof.context -> string -> int -> tactic
    15   val subgoal_tac: Proof.context -> string -> int -> tactic
    16 end;
    17 
    18 signature RULE_INSTS =
    19 sig
    20   include BASIC_RULE_INSTS
    21   val where_rule: Proof.context -> (indexname * string) list ->
    22     (binding * string option * mixfix) list -> thm -> thm
    23   val of_rule: Proof.context -> string option list * string option list ->
    24     (binding * string option * mixfix) list -> thm -> thm
    25   val read_instantiate: Proof.context -> (indexname * string) list -> string list -> thm -> thm
    26   val instantiate_tac: Proof.context -> (indexname * string) list -> string list -> tactic
    27   val make_elim_preserve: Proof.context -> thm -> thm
    28   val method: (Proof.context -> (indexname * string) list -> thm -> int -> tactic) ->
    29     (Proof.context -> thm list -> int -> tactic) -> (Proof.context -> Proof.method) context_parser
    30 end;
    31 
    32 structure Rule_Insts: RULE_INSTS =
    33 struct
    34 
    35 (** reading instantiations **)
    36 
    37 local
    38 
    39 fun error_var msg xi = error (msg ^ quote (Term.string_of_vname xi));
    40 
    41 fun the_sort tvars (xi: indexname) =
    42   (case AList.lookup (op =) tvars xi of
    43     SOME S => S
    44   | NONE => error_var "No such type variable in theorem: " xi);
    45 
    46 fun the_type vars (xi: indexname) =
    47   (case AList.lookup (op =) vars xi of
    48     SOME T => T
    49   | NONE => error_var "No such variable in theorem: " xi);
    50 
    51 fun instantiate inst =
    52   Term_Subst.instantiate ([], map (fn (xi, t) => ((xi, Term.fastype_of t), t)) inst) #>
    53   Envir.beta_norm;
    54 
    55 fun make_instT f v =
    56   let
    57     val T = TVar v;
    58     val T' = f T;
    59   in if T = T' then NONE else SOME (T, T') end;
    60 
    61 fun make_inst f v =
    62   let
    63     val t = Var v;
    64     val t' = f t;
    65   in if t aconv t' then NONE else SOME (t, t') end;
    66 
    67 in
    68 
    69 fun read_termTs ctxt ss Ts =
    70   let
    71     fun parse T = if T = propT then Syntax.parse_prop ctxt else Syntax.parse_term ctxt;
    72     val ts = map2 parse Ts ss;
    73     val ts' =
    74       map2 (Type.constraint o Type_Infer.paramify_vars) Ts ts
    75       |> Syntax.check_terms ctxt
    76       |> Variable.polymorphic ctxt;
    77     val Ts' = map Term.fastype_of ts';
    78     val tyenv = fold Type.raw_match (Ts ~~ Ts') Vartab.empty;
    79   in (ts', map (apsnd snd) (Vartab.dest tyenv)) end;
    80 
    81 fun read_insts ctxt mixed_insts (tvars, vars) =
    82   let
    83     val thy = Proof_Context.theory_of ctxt;
    84     val cert = Thm.cterm_of thy;
    85     val certT = Thm.ctyp_of thy;
    86 
    87     val (type_insts, term_insts) = List.partition (String.isPrefix "'" o fst o fst) mixed_insts;
    88 
    89 
    90     (* type instantiations *)
    91 
    92     fun readT (xi, s) =
    93       let
    94         val S = the_sort tvars xi;
    95         val T = Syntax.read_typ ctxt s;
    96       in
    97         if Sign.of_sort thy (T, S) then ((xi, S), T)
    98         else error_var "Incompatible sort for typ instantiation of " xi
    99       end;
   100 
   101     val instT1 = Term_Subst.instantiateT (map readT type_insts);
   102     val vars1 = map (apsnd instT1) vars;
   103 
   104 
   105     (* term instantiations *)
   106 
   107     val (xs, ss) = split_list term_insts;
   108     val Ts = map (the_type vars1) xs;
   109     val (ts, inferred) = read_termTs ctxt ss Ts;
   110 
   111     val instT2 = Term.typ_subst_TVars inferred;
   112     val vars2 = map (apsnd instT2) vars1;
   113     val inst2 = instantiate (xs ~~ ts);
   114 
   115 
   116     (* result *)
   117 
   118     val inst_tvars = map_filter (make_instT (instT2 o instT1)) tvars;
   119     val inst_vars = map_filter (make_inst inst2) vars2;
   120   in
   121     (map (apply2 certT) inst_tvars, map (apply2 cert) inst_vars)
   122   end;
   123 
   124 fun where_rule ctxt mixed_insts fixes thm =
   125   let
   126     val ctxt' = ctxt
   127       |> Proof_Context.read_vars fixes |-> Proof_Context.add_fixes |> #2
   128       |> Variable.declare_thm thm;
   129     val tvars = Thm.fold_terms Term.add_tvars thm [];
   130     val vars = Thm.fold_terms Term.add_vars thm [];
   131     val insts = read_insts ctxt' mixed_insts (tvars, vars);
   132   in
   133     Drule.instantiate_normalize insts thm
   134     |> singleton (Proof_Context.export ctxt' ctxt)
   135     |> Rule_Cases.save thm
   136   end;
   137 
   138 fun of_rule ctxt (args, concl_args) fixes thm =
   139   let
   140     fun zip_vars _ [] = []
   141       | zip_vars (_ :: xs) (NONE :: rest) = zip_vars xs rest
   142       | zip_vars ((x, _) :: xs) (SOME t :: rest) = (x, t) :: zip_vars xs rest
   143       | zip_vars [] _ = error "More instantiations than variables in theorem";
   144     val insts =
   145       zip_vars (rev (Term.add_vars (Thm.full_prop_of thm) [])) args @
   146       zip_vars (rev (Term.add_vars (Thm.concl_of thm) [])) concl_args;
   147   in where_rule ctxt insts fixes thm end;
   148 
   149 end;
   150 
   151 
   152 (* instantiation of rule or goal state *)
   153 
   154 fun read_instantiate ctxt insts xs =
   155   where_rule ctxt insts (map (fn x => (Binding.name x, NONE, NoSyn)) xs);
   156 
   157 fun instantiate_tac ctxt insts fixes =
   158   PRIMITIVE (read_instantiate ctxt insts fixes);
   159 
   160 
   161 
   162 (** attributes **)
   163 
   164 (* where: named instantiation *)
   165 
   166 val _ = Theory.setup
   167   (Attrib.setup @{binding "where"}
   168     (Scan.lift
   169       (Parse.and_list (Args.var -- (Args.$$$ "=" |-- Args.name_inner_syntax)) -- Parse.for_fixes) >>
   170       (fn (insts, fixes) =>
   171         Thm.rule_attribute (fn context => where_rule (Context.proof_of context) insts fixes)))
   172     "named instantiation of theorem");
   173 
   174 
   175 (* of: positional instantiation (terms only) *)
   176 
   177 local
   178 
   179 val inst = Args.maybe Args.name_inner_syntax;
   180 val concl = Args.$$$ "concl" -- Args.colon;
   181 
   182 val insts =
   183   Scan.repeat (Scan.unless concl inst) --
   184   Scan.optional (concl |-- Scan.repeat inst) [];
   185 
   186 in
   187 
   188 val _ = Theory.setup
   189   (Attrib.setup @{binding "of"}
   190     (Scan.lift (insts -- Parse.for_fixes) >> (fn (args, fixes) =>
   191       Thm.rule_attribute (fn context => of_rule (Context.proof_of context) args fixes)))
   192     "positional instantiation of theorem");
   193 
   194 end;
   195 
   196 
   197 
   198 (** tactics **)
   199 
   200 (* resolution after lifting and instantation; may refer to parameters of the subgoal *)
   201 
   202 (* FIXME cleanup this mess!!! *)
   203 
   204 fun bires_inst_tac bires_flag ctxt insts thm =
   205   let
   206     val thy = Proof_Context.theory_of ctxt;
   207     (* Separate type and term insts *)
   208     fun has_type_var ((x, _), _) =
   209       (case Symbol.explode x of "'" :: _ => true | _ => false);
   210     val Tinsts = filter has_type_var insts;
   211     val tinsts = filter_out has_type_var insts;
   212 
   213     (* Tactic *)
   214     fun tac i st = CSUBGOAL (fn (cgoal, _) =>
   215       let
   216         val goal = term_of cgoal;
   217         val params = Logic.strip_params goal;  (*params of subgoal i as string typ pairs*)
   218         val params = rev (Term.rename_wrt_term goal params)
   219           (*as they are printed: bound variables with*)
   220           (*the same name are renamed during printing*)
   221 
   222         val (param_names, ctxt') = ctxt
   223           |> Variable.declare_thm thm
   224           |> Thm.fold_terms Variable.declare_constraints st
   225           |> Proof_Context.add_fixes (map (fn (x, T) => (Binding.name x, SOME T, NoSyn)) params);
   226 
   227         (* Process type insts: Tinsts_env *)
   228         fun absent xi = error
   229               ("No such variable in theorem: " ^ Term.string_of_vname xi);
   230         val (rtypes, rsorts) = Drule.types_sorts thm;
   231         fun readT (xi, s) =
   232             let val S = case rsorts xi of SOME S => S | NONE => absent xi;
   233                 val T = Syntax.read_typ ctxt' s;
   234                 val U = TVar (xi, S);
   235             in if Sign.typ_instance thy (T, U) then (U, T)
   236                else error ("Instantiation of " ^ Term.string_of_vname xi ^ " fails")
   237             end;
   238         val Tinsts_env = map readT Tinsts;
   239         (* Preprocess rule: extract vars and their types, apply Tinsts *)
   240         fun get_typ xi =
   241           (case rtypes xi of
   242                SOME T => typ_subst_atomic Tinsts_env T
   243              | NONE => absent xi);
   244         val (xis, ss) = Library.split_list tinsts;
   245         val Ts = map get_typ xis;
   246 
   247         val (ts, envT) =
   248           read_termTs (Proof_Context.set_mode Proof_Context.mode_schematic ctxt') ss Ts;
   249         val envT' = map (fn (ixn, T) =>
   250           (TVar (ixn, the (rsorts ixn)), T)) envT @ Tinsts_env;
   251         val cenv =
   252           map
   253             (fn (xi, t) =>
   254               apply2 (Thm.cterm_of thy) (Var (xi, fastype_of t), t))
   255             (distinct
   256               (fn ((x1, t1), (x2, t2)) => x1 = x2 andalso t1 aconv t2)
   257               (xis ~~ ts));
   258         (* Lift and instantiate rule *)
   259         val maxidx = Thm.maxidx_of st;
   260         val paramTs = map #2 params
   261         and inc = maxidx+1
   262         fun liftvar (Var ((a,j), T)) =
   263               Var((a, j+inc), paramTs ---> Logic.incr_tvar inc T)
   264           | liftvar t = raise TERM("Variable expected", [t]);
   265         fun liftterm t =
   266           fold_rev absfree (param_names ~~ paramTs) (Logic.incr_indexes (paramTs, inc) t);
   267         fun liftpair (cv, ct) = (cterm_fun liftvar cv, cterm_fun liftterm ct);
   268         val lifttvar = apply2 (ctyp_of thy o Logic.incr_tvar inc);
   269         val rule = Drule.instantiate_normalize
   270               (map lifttvar envT', map liftpair cenv)
   271               (Thm.lift_rule cgoal thm)
   272       in
   273         compose_tac ctxt' (bires_flag, rule, nprems_of thm) i
   274       end) i st;
   275   in tac end;
   276 
   277 val res_inst_tac = bires_inst_tac false;
   278 val eres_inst_tac = bires_inst_tac true;
   279 
   280 
   281 (* forward resolution *)
   282 
   283 fun make_elim_preserve ctxt rl =
   284   let
   285     val cert = Thm.cterm_of (Thm.theory_of_thm rl);
   286     val maxidx = Thm.maxidx_of rl;
   287     fun cvar xi = cert (Var (xi, propT));
   288     val revcut_rl' =
   289       Drule.instantiate_normalize ([], [(cvar ("V", 0), cvar ("V", maxidx + 1)),
   290         (cvar ("W", 0), cvar ("W", maxidx + 1))]) Drule.revcut_rl;
   291   in
   292     (case Seq.list_of
   293       (Thm.bicompose (SOME ctxt) {flatten = true, match = false, incremented = false}
   294         (false, rl, Thm.nprems_of rl) 1 revcut_rl')
   295      of
   296       [th] => th
   297     | _ => raise THM ("make_elim_preserve", 1, [rl]))
   298   end;
   299 
   300 (*instantiate and cut -- for atomic fact*)
   301 fun cut_inst_tac ctxt insts rule = res_inst_tac ctxt insts (make_elim_preserve ctxt rule);
   302 
   303 (*forward tactic applies a rule to an assumption without deleting it*)
   304 fun forw_inst_tac ctxt insts rule = cut_inst_tac ctxt insts rule THEN' assume_tac ctxt;
   305 
   306 (*dresolve tactic applies a rule to replace an assumption*)
   307 fun dres_inst_tac ctxt insts rule = eres_inst_tac ctxt insts (make_elim_preserve ctxt rule);
   308 
   309 
   310 (* derived tactics *)
   311 
   312 (*deletion of an assumption*)
   313 fun thin_tac ctxt s = eres_inst_tac ctxt [(("V", 0), s)] Drule.thin_rl;
   314 
   315 (*Introduce the given proposition as lemma and subgoal*)
   316 fun subgoal_tac ctxt A = DETERM o res_inst_tac ctxt [(("psi", 0), A)] cut_rl;
   317 
   318 
   319 
   320 (* method wrapper *)
   321 
   322 fun method inst_tac tac =
   323   Args.goal_spec --
   324   Scan.optional (Scan.lift
   325     (Parse.and_list1 (Args.var -- (Args.$$$ "=" |-- Parse.!!! Args.name_inner_syntax)) --|
   326       Args.$$$ "in")) [] --
   327   Attrib.thms >>
   328   (fn ((quant, insts), thms) => fn ctxt => METHOD (fn facts =>
   329     if null insts then quant (Method.insert_tac facts THEN' tac ctxt thms)
   330     else
   331       (case thms of
   332         [thm] => quant (Method.insert_tac facts THEN' inst_tac ctxt insts thm)
   333       | _ => error "Cannot have instantiations with multiple rules")));
   334 
   335 
   336 (* setup *)
   337 
   338 (*warning: rule_tac etc. refer to dynamic subgoal context!*)
   339 
   340 val _ = Theory.setup
   341  (Method.setup @{binding rule_tac} (method res_inst_tac (K resolve_tac))
   342     "apply rule (dynamic instantiation)" #>
   343   Method.setup @{binding erule_tac} (method eres_inst_tac (K eresolve_tac))
   344     "apply rule in elimination manner (dynamic instantiation)" #>
   345   Method.setup @{binding drule_tac} (method dres_inst_tac (K dresolve_tac))
   346     "apply rule in destruct manner (dynamic instantiation)" #>
   347   Method.setup @{binding frule_tac} (method forw_inst_tac (K forward_tac))
   348     "apply rule in forward manner (dynamic instantiation)" #>
   349   Method.setup @{binding cut_tac} (method cut_inst_tac (K cut_rules_tac))
   350     "cut rule (dynamic instantiation)" #>
   351   Method.setup @{binding subgoal_tac}
   352     (Args.goal_spec -- Scan.lift (Scan.repeat1 Args.name_inner_syntax) >>
   353       (fn (quant, props) => fn ctxt =>
   354         SIMPLE_METHOD'' quant (EVERY' (map (subgoal_tac ctxt) props))))
   355     "insert subgoal (dynamic instantiation)" #>
   356   Method.setup @{binding thin_tac}
   357     (Args.goal_spec -- Scan.lift Args.name_inner_syntax >>
   358       (fn (quant, prop) => fn ctxt => SIMPLE_METHOD'' quant (thin_tac ctxt prop)))
   359       "remove premise (dynamic instantiation)");
   360 
   361 end;
   362 
   363 structure Basic_Rule_Insts: BASIC_RULE_INSTS = Rule_Insts;
   364 open Basic_Rule_Insts;