src/HOL/HOLCF/Tools/fixrec.ML
changeset 40774 0437dbc127b3
parent 40327 1dfdbd66093a
child 40832 4352ca878c41
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/HOL/HOLCF/Tools/fixrec.ML	Sat Nov 27 16:08:10 2010 -0800
     1.3 @@ -0,0 +1,417 @@
     1.4 +(*  Title:      HOLCF/Tools/fixrec.ML
     1.5 +    Author:     Amber Telfer and Brian Huffman
     1.6 +
     1.7 +Recursive function definition package for HOLCF.
     1.8 +*)
     1.9 +
    1.10 +signature FIXREC =
    1.11 +sig
    1.12 +  val add_fixrec: (binding * typ option * mixfix) list
    1.13 +    -> (bool * (Attrib.binding * term)) list -> local_theory -> local_theory
    1.14 +  val add_fixrec_cmd: (binding * string option * mixfix) list
    1.15 +    -> (bool * (Attrib.binding * string)) list -> local_theory -> local_theory
    1.16 +  val add_matchers: (string * string) list -> theory -> theory
    1.17 +  val fixrec_simp_tac: Proof.context -> int -> tactic
    1.18 +  val setup: theory -> theory
    1.19 +end;
    1.20 +
    1.21 +structure Fixrec :> FIXREC =
    1.22 +struct
    1.23 +
    1.24 +open HOLCF_Library;
    1.25 +
    1.26 +infixr 6 ->>;
    1.27 +infix -->>;
    1.28 +infix 9 `;
    1.29 +
    1.30 +val def_cont_fix_eq = @{thm def_cont_fix_eq};
    1.31 +val def_cont_fix_ind = @{thm def_cont_fix_ind};
    1.32 +
    1.33 +fun fixrec_err s = error ("fixrec definition error:\n" ^ s);
    1.34 +fun fixrec_eq_err thy s eq =
    1.35 +  fixrec_err (s ^ "\nin\n" ^ quote (Syntax.string_of_term_global thy eq));
    1.36 +
    1.37 +(*************************************************************************)
    1.38 +(***************************** building types ****************************)
    1.39 +(*************************************************************************)
    1.40 +
    1.41 +local
    1.42 +
    1.43 +fun binder_cfun (Type(@{type_name cfun},[T, U])) = T :: binder_cfun U
    1.44 +  | binder_cfun (Type(@{type_name "fun"},[T, U])) = T :: binder_cfun U
    1.45 +  | binder_cfun _   =  [];
    1.46 +
    1.47 +fun body_cfun (Type(@{type_name cfun},[T, U])) = body_cfun U
    1.48 +  | body_cfun (Type(@{type_name "fun"},[T, U])) = body_cfun U
    1.49 +  | body_cfun T   =  T;
    1.50 +
    1.51 +fun strip_cfun T : typ list * typ =
    1.52 +  (binder_cfun T, body_cfun T);
    1.53 +
    1.54 +in
    1.55 +
    1.56 +fun matcherT (T, U) =
    1.57 +  body_cfun T ->> (binder_cfun T -->> U) ->> U;
    1.58 +
    1.59 +end
    1.60 +
    1.61 +(*************************************************************************)
    1.62 +(***************************** building terms ****************************)
    1.63 +(*************************************************************************)
    1.64 +
    1.65 +val mk_trp = HOLogic.mk_Trueprop;
    1.66 +
    1.67 +(* splits a cterm into the right and lefthand sides of equality *)
    1.68 +fun dest_eqs t = HOLogic.dest_eq (HOLogic.dest_Trueprop t);
    1.69 +
    1.70 +(* similar to Thm.head_of, but for continuous application *)
    1.71 +fun chead_of (Const(@{const_name Rep_cfun},_)$f$t) = chead_of f
    1.72 +  | chead_of u = u;
    1.73 +
    1.74 +infix 0 ==;  val (op ==) = Logic.mk_equals;
    1.75 +infix 1 ===; val (op ===) = HOLogic.mk_eq;
    1.76 +
    1.77 +fun mk_mplus (t, u) =
    1.78 +  let val mT = Term.fastype_of t
    1.79 +  in Const(@{const_name Fixrec.mplus}, mT ->> mT ->> mT) ` t ` u end;
    1.80 +
    1.81 +fun mk_run t =
    1.82 +  let
    1.83 +    val mT = Term.fastype_of t
    1.84 +    val T = dest_matchT mT
    1.85 +    val run = Const(@{const_name Fixrec.run}, mT ->> T)
    1.86 +  in
    1.87 +    case t of
    1.88 +      Const(@{const_name Rep_cfun}, _) $
    1.89 +        Const(@{const_name Fixrec.succeed}, _) $ u => u
    1.90 +    | _ => run ` t
    1.91 +  end;
    1.92 +
    1.93 +
    1.94 +(*************************************************************************)
    1.95 +(************* fixed-point definitions and unfolding theorems ************)
    1.96 +(*************************************************************************)
    1.97 +
    1.98 +structure FixrecUnfoldData = Generic_Data
    1.99 +(
   1.100 +  type T = thm Symtab.table;
   1.101 +  val empty = Symtab.empty;
   1.102 +  val extend = I;
   1.103 +  fun merge data : T = Symtab.merge (K true) data;
   1.104 +);
   1.105 +
   1.106 +local
   1.107 +
   1.108 +fun name_of (Const (n, T)) = n
   1.109 +  | name_of (Free (n, T)) = n
   1.110 +  | name_of t = raise TERM ("Fixrec.add_unfold: lhs not a constant", [t]);
   1.111 +
   1.112 +val lhs_name =
   1.113 +  name_of o head_of o fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of;
   1.114 +
   1.115 +in
   1.116 +
   1.117 +val add_unfold : attribute =
   1.118 +  Thm.declaration_attribute
   1.119 +    (fn th => FixrecUnfoldData.map (Symtab.insert (K true) (lhs_name th, th)));
   1.120 +
   1.121 +end
   1.122 +
   1.123 +fun add_fixdefs
   1.124 +  (fixes : ((binding * typ) * mixfix) list)
   1.125 +  (spec : (Attrib.binding * term) list)
   1.126 +  (lthy : local_theory) =
   1.127 +  let
   1.128 +    val thy = ProofContext.theory_of lthy;
   1.129 +    val names = map (Binding.name_of o fst o fst) fixes;
   1.130 +    val all_names = space_implode "_" names;
   1.131 +    val (lhss, rhss) = ListPair.unzip (map (dest_eqs o snd) spec);
   1.132 +    val functional = lambda_tuple lhss (mk_tuple rhss);
   1.133 +    val fixpoint = mk_fix (mk_cabs functional);
   1.134 +
   1.135 +    val cont_thm =
   1.136 +      let
   1.137 +        val prop = mk_trp (mk_cont functional);
   1.138 +        fun err _ = error (
   1.139 +          "Continuity proof failed; please check that cont2cont rules\n" ^
   1.140 +          "or simp rules are configured for all non-HOLCF constants.\n" ^
   1.141 +          "The error occurred for the goal statement:\n" ^
   1.142 +          Syntax.string_of_term lthy prop);
   1.143 +        val rules = Cont2ContData.get lthy;
   1.144 +        val fast_tac = SOLVED' (REPEAT_ALL_NEW (match_tac rules));
   1.145 +        val slow_tac = SOLVED' (simp_tac (simpset_of lthy));
   1.146 +        val tac = fast_tac 1 ORELSE slow_tac 1 ORELSE err;
   1.147 +      in
   1.148 +        Goal.prove lthy [] [] prop (K tac)
   1.149 +      end;
   1.150 +
   1.151 +    fun one_def (l as Free(n,_)) r =
   1.152 +          let val b = Long_Name.base_name n
   1.153 +          in ((Binding.name (b^"_def"), []), r) end
   1.154 +      | one_def _ _ = fixrec_err "fixdefs: lhs not of correct form";
   1.155 +    fun defs [] _ = []
   1.156 +      | defs (l::[]) r = [one_def l r]
   1.157 +      | defs (l::ls) r = one_def l (mk_fst r) :: defs ls (mk_snd r);
   1.158 +    val fixdefs = defs lhss fixpoint;
   1.159 +    val (fixdef_thms : (term * (string * thm)) list, lthy) = lthy
   1.160 +      |> fold_map Local_Theory.define (map (apfst fst) fixes ~~ fixdefs);
   1.161 +    fun pair_equalI (thm1, thm2) = @{thm Pair_equalI} OF [thm1, thm2];
   1.162 +    val tuple_fixdef_thm = foldr1 pair_equalI (map (snd o snd) fixdef_thms);
   1.163 +    val P = Var (("P", 0), map Term.fastype_of lhss ---> HOLogic.boolT);
   1.164 +    val predicate = lambda_tuple lhss (list_comb (P, lhss));
   1.165 +    val tuple_induct_thm = (def_cont_fix_ind OF [tuple_fixdef_thm, cont_thm])
   1.166 +      |> Drule.instantiate' [] [SOME (Thm.cterm_of thy predicate)]
   1.167 +      |> Local_Defs.unfold lthy @{thms split_paired_all split_conv split_strict};
   1.168 +    val tuple_unfold_thm = (def_cont_fix_eq OF [tuple_fixdef_thm, cont_thm])
   1.169 +      |> Local_Defs.unfold lthy @{thms split_conv};
   1.170 +    fun unfolds [] thm = []
   1.171 +      | unfolds (n::[]) thm = [(n, thm)]
   1.172 +      | unfolds (n::ns) thm = let
   1.173 +          val thmL = thm RS @{thm Pair_eqD1};
   1.174 +          val thmR = thm RS @{thm Pair_eqD2};
   1.175 +        in (n, thmL) :: unfolds ns thmR end;
   1.176 +    val unfold_thms = unfolds names tuple_unfold_thm;
   1.177 +    val induct_note : Attrib.binding * Thm.thm list =
   1.178 +      let
   1.179 +        val thm_name = Binding.qualify true all_names (Binding.name "induct");
   1.180 +      in
   1.181 +        ((thm_name, []), [tuple_induct_thm])
   1.182 +      end;
   1.183 +    fun unfold_note (name, thm) : Attrib.binding * Thm.thm list =
   1.184 +      let
   1.185 +        val thm_name = Binding.qualify true name (Binding.name "unfold");
   1.186 +        val src = Attrib.internal (K add_unfold);
   1.187 +      in
   1.188 +        ((thm_name, [src]), [thm])
   1.189 +      end;
   1.190 +    val (thmss, lthy) = lthy
   1.191 +      |> fold_map Local_Theory.note (induct_note :: map unfold_note unfold_thms);
   1.192 +  in
   1.193 +    (lthy, names, fixdef_thms, map snd unfold_thms)
   1.194 +  end;
   1.195 +
   1.196 +(*************************************************************************)
   1.197 +(*********** monadic notation and pattern matching compilation ***********)
   1.198 +(*************************************************************************)
   1.199 +
   1.200 +structure FixrecMatchData = Theory_Data
   1.201 +(
   1.202 +  type T = string Symtab.table;
   1.203 +  val empty = Symtab.empty;
   1.204 +  val extend = I;
   1.205 +  fun merge data = Symtab.merge (K true) data;
   1.206 +);
   1.207 +
   1.208 +(* associate match functions with pattern constants *)
   1.209 +fun add_matchers ms = FixrecMatchData.map (fold Symtab.update ms);
   1.210 +
   1.211 +fun taken_names (t : term) : bstring list =
   1.212 +  let
   1.213 +    fun taken (Const(a,_), bs) = insert (op =) (Long_Name.base_name a) bs
   1.214 +      | taken (Free(a,_) , bs) = insert (op =) a bs
   1.215 +      | taken (f $ u     , bs) = taken (f, taken (u, bs))
   1.216 +      | taken (Abs(a,_,t), bs) = taken (t, insert (op =) a bs)
   1.217 +      | taken (_         , bs) = bs;
   1.218 +  in
   1.219 +    taken (t, [])
   1.220 +  end;
   1.221 +
   1.222 +(* builds a monadic term for matching a pattern *)
   1.223 +(* returns (rhs, free variable, used varnames) *)
   1.224 +fun compile_pat match_name pat rhs taken =
   1.225 +  let
   1.226 +    fun comp_pat p rhs taken =
   1.227 +      if is_Free p then (rhs, p, taken)
   1.228 +      else comp_con (fastype_of p) p rhs [] taken
   1.229 +    (* compiles a monadic term for a constructor pattern *)
   1.230 +    and comp_con T p rhs vs taken =
   1.231 +      case p of
   1.232 +        Const(@{const_name Rep_cfun},_) $ f $ x =>
   1.233 +          let val (rhs', v, taken') = comp_pat x rhs taken
   1.234 +          in comp_con T f rhs' (v::vs) taken' end
   1.235 +      | f $ x =>
   1.236 +          let val (rhs', v, taken') = comp_pat x rhs taken
   1.237 +          in comp_con T f rhs' (v::vs) taken' end
   1.238 +      | Const (c, cT) =>
   1.239 +          let
   1.240 +            val n = Name.variant taken "v"
   1.241 +            val v = Free(n, T)
   1.242 +            val m = Const(match_name c, matcherT (cT, fastype_of rhs))
   1.243 +            val k = big_lambdas vs rhs
   1.244 +          in
   1.245 +            (m`v`k, v, n::taken)
   1.246 +          end
   1.247 +      | _ => raise TERM ("fixrec: invalid pattern ", [p])
   1.248 +  in
   1.249 +    comp_pat pat rhs taken
   1.250 +  end;
   1.251 +
   1.252 +(* builds a monadic term for matching a function definition pattern *)
   1.253 +(* returns (constant, (vars, matcher)) *)
   1.254 +fun compile_lhs match_name pat rhs vs taken =
   1.255 +  case pat of
   1.256 +    Const(@{const_name Rep_cfun}, _) $ f $ x =>
   1.257 +      let val (rhs', v, taken') = compile_pat match_name x rhs taken;
   1.258 +      in compile_lhs match_name f rhs' (v::vs) taken' end
   1.259 +  | Free(_,_) => (pat, (vs, rhs))
   1.260 +  | Const(_,_) => (pat, (vs, rhs))
   1.261 +  | _ => fixrec_err ("invalid function pattern: "
   1.262 +                    ^ ML_Syntax.print_term pat);
   1.263 +
   1.264 +fun strip_alls t =
   1.265 +  if Logic.is_all t then strip_alls (snd (Logic.dest_all t)) else t;
   1.266 +
   1.267 +fun compile_eq match_name eq =
   1.268 +  let
   1.269 +    val (lhs,rhs) = dest_eqs (Logic.strip_imp_concl (strip_alls eq));
   1.270 +  in
   1.271 +    compile_lhs match_name lhs (mk_succeed rhs) [] (taken_names eq)
   1.272 +  end;
   1.273 +
   1.274 +(* this is the pattern-matching compiler function *)
   1.275 +fun compile_eqs match_name eqs =
   1.276 +  let
   1.277 +    val (consts, matchers) =
   1.278 +      ListPair.unzip (map (compile_eq match_name) eqs);
   1.279 +    val const =
   1.280 +        case distinct (op =) consts of
   1.281 +          [n] => n
   1.282 +        | _ => fixrec_err "all equations in block must define the same function";
   1.283 +    val vars =
   1.284 +        case distinct (op = o pairself length) (map fst matchers) of
   1.285 +          [vars] => vars
   1.286 +        | _ => fixrec_err "all equations in block must have the same arity";
   1.287 +    (* rename so all matchers use same free variables *)
   1.288 +    fun rename (vs, t) = Term.subst_free (filter_out (op =) (vs ~~ vars)) t;
   1.289 +    val rhs = big_lambdas vars (mk_run (foldr1 mk_mplus (map rename matchers)));
   1.290 +  in
   1.291 +    mk_trp (const === rhs)
   1.292 +  end;
   1.293 +
   1.294 +(*************************************************************************)
   1.295 +(********************** Proving associated theorems **********************)
   1.296 +(*************************************************************************)
   1.297 +
   1.298 +fun eta_tac i = CONVERSION Thm.eta_conversion i;
   1.299 +
   1.300 +fun fixrec_simp_tac ctxt =
   1.301 +  let
   1.302 +    val tab = FixrecUnfoldData.get (Context.Proof ctxt);
   1.303 +    val ss = Simplifier.simpset_of ctxt;
   1.304 +    fun concl t =
   1.305 +      if Logic.is_all t then concl (snd (Logic.dest_all t))
   1.306 +      else HOLogic.dest_Trueprop (Logic.strip_imp_concl t);
   1.307 +    fun tac (t, i) =
   1.308 +      let
   1.309 +        val (c, T) =
   1.310 +            (dest_Const o head_of o chead_of o fst o HOLogic.dest_eq o concl) t;
   1.311 +        val unfold_thm = the (Symtab.lookup tab c);
   1.312 +        val rule = unfold_thm RS @{thm ssubst_lhs};
   1.313 +      in
   1.314 +        CHANGED (rtac rule i THEN eta_tac i THEN asm_simp_tac ss i)
   1.315 +      end
   1.316 +  in
   1.317 +    SUBGOAL (fn ti => the_default no_tac (try tac ti))
   1.318 +  end;
   1.319 +
   1.320 +(* proves a block of pattern matching equations as theorems, using unfold *)
   1.321 +fun make_simps ctxt (unfold_thm, eqns : (Attrib.binding * term) list) =
   1.322 +  let
   1.323 +    val ss = Simplifier.simpset_of ctxt;
   1.324 +    val rule = unfold_thm RS @{thm ssubst_lhs};
   1.325 +    val tac = rtac rule 1 THEN eta_tac 1 THEN asm_simp_tac ss 1;
   1.326 +    fun prove_term t = Goal.prove ctxt [] [] t (K tac);
   1.327 +    fun prove_eqn (bind, eqn_t) = (bind, prove_term eqn_t);
   1.328 +  in
   1.329 +    map prove_eqn eqns
   1.330 +  end;
   1.331 +
   1.332 +(*************************************************************************)
   1.333 +(************************* Main fixrec function **************************)
   1.334 +(*************************************************************************)
   1.335 +
   1.336 +local
   1.337 +(* code adapted from HOL/Tools/primrec.ML *)
   1.338 +
   1.339 +fun gen_fixrec
   1.340 +  prep_spec
   1.341 +  (raw_fixes : (binding * 'a option * mixfix) list)
   1.342 +  (raw_spec' : (bool * (Attrib.binding * 'b)) list)
   1.343 +  (lthy : local_theory) =
   1.344 +  let
   1.345 +    val (skips, raw_spec) = ListPair.unzip raw_spec';
   1.346 +    val (fixes : ((binding * typ) * mixfix) list,
   1.347 +         spec : (Attrib.binding * term) list) =
   1.348 +          fst (prep_spec raw_fixes raw_spec lthy);
   1.349 +    val chead_of_spec =
   1.350 +      chead_of o fst o dest_eqs o Logic.strip_imp_concl o strip_alls o snd;
   1.351 +    fun name_of (Free (n, _)) = n
   1.352 +      | name_of t = fixrec_err ("unknown term");
   1.353 +    val all_names = map (name_of o chead_of_spec) spec;
   1.354 +    val names = distinct (op =) all_names;
   1.355 +    fun block_of_name n =
   1.356 +      map_filter
   1.357 +        (fn (m,eq) => if m = n then SOME eq else NONE)
   1.358 +        (all_names ~~ (spec ~~ skips));
   1.359 +    val blocks = map block_of_name names;
   1.360 +
   1.361 +    val matcher_tab = FixrecMatchData.get (ProofContext.theory_of lthy);
   1.362 +    fun match_name c =
   1.363 +      case Symtab.lookup matcher_tab c of SOME m => m
   1.364 +        | NONE => fixrec_err ("unknown pattern constructor: " ^ c);
   1.365 +
   1.366 +    val matches = map (compile_eqs match_name) (map (map (snd o fst)) blocks);
   1.367 +    val spec' = map (pair Attrib.empty_binding) matches;
   1.368 +    val (lthy, cnames, fixdef_thms, unfold_thms) =
   1.369 +      add_fixdefs fixes spec' lthy;
   1.370 +
   1.371 +    val blocks' = map (map fst o filter_out snd) blocks;
   1.372 +    val simps : (Attrib.binding * thm) list list =
   1.373 +      map (make_simps lthy) (unfold_thms ~~ blocks');
   1.374 +    fun mk_bind n : Attrib.binding =
   1.375 +     (Binding.qualify true n (Binding.name "simps"),
   1.376 +       [Attrib.internal (K Simplifier.simp_add)]);
   1.377 +    val simps1 : (Attrib.binding * thm list) list =
   1.378 +      map (fn (n,xs) => (mk_bind n, map snd xs)) (names ~~ simps);
   1.379 +    val simps2 : (Attrib.binding * thm list) list =
   1.380 +      map (apsnd (fn thm => [thm])) (flat simps);
   1.381 +    val (_, lthy) = lthy
   1.382 +      |> fold_map Local_Theory.note (simps1 @ simps2);
   1.383 +  in
   1.384 +    lthy
   1.385 +  end;
   1.386 +
   1.387 +in
   1.388 +
   1.389 +val add_fixrec = gen_fixrec Specification.check_spec;
   1.390 +val add_fixrec_cmd = gen_fixrec Specification.read_spec;
   1.391 +
   1.392 +end; (* local *)
   1.393 +
   1.394 +
   1.395 +(*************************************************************************)
   1.396 +(******************************** Parsers ********************************)
   1.397 +(*************************************************************************)
   1.398 +
   1.399 +val opt_thm_name' : (bool * Attrib.binding) parser =
   1.400 +  Parse.$$$ "(" -- Parse.$$$ "unchecked" -- Parse.$$$ ")" >> K (true, Attrib.empty_binding)
   1.401 +    || Parse_Spec.opt_thm_name ":" >> pair false;
   1.402 +
   1.403 +val spec' : (bool * (Attrib.binding * string)) parser =
   1.404 +  opt_thm_name' -- Parse.prop >> (fn ((a, b), c) => (a, (b, c)));
   1.405 +
   1.406 +val alt_specs' : (bool * (Attrib.binding * string)) list parser =
   1.407 +  let val unexpected = Scan.ahead (Parse.name || Parse.$$$ "[" || Parse.$$$ "(");
   1.408 +  in Parse.enum1 "|" (spec' --| Scan.option (unexpected -- Parse.!!! (Parse.$$$ "|"))) end;
   1.409 +
   1.410 +val _ =
   1.411 +  Outer_Syntax.local_theory "fixrec" "define recursive functions (HOLCF)" Keyword.thy_decl
   1.412 +    (Parse.fixes -- (Parse.where_ |-- Parse.!!! alt_specs')
   1.413 +      >> (fn (fixes, specs) => add_fixrec_cmd fixes specs));
   1.414 +
   1.415 +val setup =
   1.416 +  Method.setup @{binding fixrec_simp}
   1.417 +    (Scan.succeed (SIMPLE_METHOD' o fixrec_simp_tac))
   1.418 +    "pattern prover for fixrec constants";
   1.419 +
   1.420 +end;