src/HOLCF/fixrec_package.ML
author wenzelm
Sat Jan 14 22:25:34 2006 +0100 (2006-01-14)
changeset 18688 abf0f018b5ec
parent 18377 0e1d025d57b3
child 18728 6790126ab5f6
permissions -rw-r--r--
generic attributes;
huffman@16226
     1
(*  Title:      HOLCF/fixrec_package.ML
huffman@16226
     2
    ID:         $Id$
huffman@16226
     3
    Author:     Amber Telfer and Brian Huffman
huffman@16226
     4
huffman@16226
     5
Recursive function definition package for HOLCF.
huffman@16226
     6
*)
huffman@16226
     7
huffman@16226
     8
signature FIXREC_PACKAGE =
huffman@16226
     9
sig
huffman@16552
    10
  val add_fixrec: bool -> ((string * Attrib.src list) * string) list list
huffman@16552
    11
    -> theory -> theory
huffman@16552
    12
  val add_fixrec_i: bool -> ((string * theory attribute list) * term) list list
huffman@16552
    13
    -> theory -> theory
huffman@16552
    14
  val add_fixpat: (string * Attrib.src list) * string list
huffman@16552
    15
    -> theory -> theory
huffman@16552
    16
  val add_fixpat_i: (string * theory attribute list) * term list
huffman@16552
    17
    -> theory -> theory
huffman@16226
    18
end;
huffman@16226
    19
huffman@16226
    20
structure FixrecPackage: FIXREC_PACKAGE =
huffman@16226
    21
struct
huffman@16226
    22
huffman@16552
    23
fun fixrec_err s = error ("fixrec definition error:\n" ^ s);
huffman@16628
    24
fun fixrec_eq_err thy s eq =
huffman@16628
    25
  fixrec_err (s ^ "\nin\n" ^ quote (Sign.string_of_term thy eq));
huffman@16552
    26
huffman@16226
    27
(* ->> is taken from holcf_logic.ML *)
huffman@16226
    28
(* TODO: fix dependencies so we can import HOLCFLogic here *)
huffman@16226
    29
infixr 6 ->>;
huffman@16226
    30
fun S ->> T = Type ("Cfun.->",[S,T]);
huffman@16226
    31
huffman@16226
    32
(* extern_name is taken from domain/library.ML *)
huffman@16226
    33
fun extern_name con = case Symbol.explode con of 
huffman@16226
    34
		   ("o"::"p"::" "::rest) => implode rest
huffman@16226
    35
		   | _ => con;
huffman@16226
    36
huffman@16401
    37
val mk_trp = HOLogic.mk_Trueprop;
huffman@16401
    38
huffman@16226
    39
(* splits a cterm into the right and lefthand sides of equality *)
huffman@16552
    40
fun dest_eqs t = HOLogic.dest_eq (HOLogic.dest_Trueprop t);
huffman@16552
    41
(*
huffman@16226
    42
fun dest_eqs (Const ("==", _)$lhs$rhs) = (lhs, rhs)
huffman@16461
    43
  | dest_eqs (Const ("Trueprop", _)$(Const ("op =", _)$lhs$rhs)) = (lhs,rhs)
huffman@16552
    44
  | dest_eqs t = fixrec_err (Sign.string_of_term (sign_of (the_context())) t);
huffman@16552
    45
*)
huffman@16461
    46
(* similar to Thm.head_of, but for continuous application *)
huffman@16461
    47
fun chead_of (Const("Cfun.Rep_CFun",_)$f$t) = chead_of f
huffman@16461
    48
  | chead_of u = u;
huffman@16461
    49
huffman@16387
    50
(* these are helpful functions copied from HOLCF/domain/library.ML *)
huffman@16387
    51
fun %: s = Free(s,dummyT);
huffman@16387
    52
fun %%: s = Const(s,dummyT);
huffman@16387
    53
infix 0 ==;  fun S ==  T = %%:"==" $ S $ T;
huffman@16387
    54
infix 1 ===; fun S === T = %%:"op =" $ S $ T;
huffman@16401
    55
infix 9 `  ; fun f ` x = %%:"Cfun.Rep_CFun" $ f $ x;
huffman@16387
    56
huffman@16387
    57
(* infers the type of a term *)
huffman@16402
    58
(* similar to Theory.inferT_axm, but allows any type, not just propT *)
huffman@16401
    59
fun infer sg t =
huffman@16401
    60
  fst (Sign.infer_types (Sign.pp sg) sg (K NONE) (K NONE) [] true ([t],dummyT));
huffman@16401
    61
huffman@16402
    62
(* Similar to Term.lambda, but also allows abstraction over constants *)
huffman@16401
    63
fun lambda' (v as Free (x, T)) t = Abs (x, T, abstract_over (v, t))
huffman@16401
    64
  | lambda' (v as Var ((x, _), T)) t = Abs (x, T, abstract_over (v, t))
huffman@16401
    65
  | lambda' (v as Const (x, T)) t = Abs (Sign.base_name x, T, abstract_over (v, t))
huffman@16401
    66
  | lambda' v t = raise TERM ("lambda'", [v, t]);
huffman@16401
    67
huffman@16401
    68
(* builds the expression (LAM v. rhs) *)
huffman@16401
    69
fun big_lambda v rhs = %%:"Cfun.Abs_CFun"$(lambda' v rhs);
huffman@16401
    70
huffman@16401
    71
(* builds the expression (LAM v1 v2 .. vn. rhs) *)
huffman@16401
    72
fun big_lambdas [] rhs = rhs
huffman@16401
    73
  | big_lambdas (v::vs) rhs = big_lambda v (big_lambdas vs rhs);
huffman@16401
    74
huffman@16401
    75
(* builds the expression (LAM <v1,v2,..,vn>. rhs) *)
huffman@16401
    76
fun lambda_ctuple [] rhs = big_lambda (%:"unit") rhs
huffman@16401
    77
  | lambda_ctuple (v::[]) rhs = big_lambda v rhs
huffman@16401
    78
  | lambda_ctuple (v::vs) rhs =
huffman@16401
    79
      %%:"Cprod.csplit"`(big_lambda v (lambda_ctuple vs rhs));
huffman@16401
    80
huffman@16401
    81
(* builds the expression <v1,v2,..,vn> *)
huffman@16401
    82
fun mk_ctuple [] = %%:"UU"
huffman@16401
    83
|   mk_ctuple (t::[]) = t
huffman@16401
    84
|   mk_ctuple (t::ts) = %%:"Cprod.cpair"`t`(mk_ctuple ts);
huffman@16387
    85
huffman@16387
    86
(*************************************************************************)
huffman@16402
    87
(************* fixed-point definitions and unfolding theorems ************)
huffman@16387
    88
(*************************************************************************)
huffman@16387
    89
huffman@16401
    90
fun add_fixdefs eqs thy =
huffman@16226
    91
  let
huffman@16401
    92
    val (lhss,rhss) = ListPair.unzip (map dest_eqs eqs);
huffman@16401
    93
    val fixpoint = %%:"Fix.fix"`lambda_ctuple lhss (mk_ctuple rhss);
huffman@16401
    94
    
huffman@16401
    95
    fun one_def (l as Const(n,T)) r =
huffman@16552
    96
          let val b = Sign.base_name n in (b, (b^"_def", l == r)) end
huffman@16552
    97
      | one_def _ _ = fixrec_err "fixdefs: lhs not of correct form";
huffman@16401
    98
    fun defs [] _ = []
huffman@16401
    99
      | defs (l::[]) r = [one_def l r]
huffman@16401
   100
      | defs (l::ls) r = one_def l (%%:"Cprod.cfst"`r) :: defs ls (%%:"Cprod.csnd"`r);
huffman@16401
   101
    val (names, pre_fixdefs) = ListPair.unzip (defs lhss fixpoint);
huffman@16401
   102
    
huffman@16628
   103
    val fixdefs = map (inferT_axm thy) pre_fixdefs;
haftmann@18358
   104
    val (fixdef_thms, thy') =
huffman@16401
   105
      PureThy.add_defs_i false (map Thm.no_attributes fixdefs) thy;
huffman@16401
   106
    val ctuple_fixdef_thm = foldr1 (fn (x,y) => cpair_equalI OF [x,y]) fixdef_thms;
huffman@16401
   107
    
wenzelm@17985
   108
    val ctuple_unfold = infer thy' (mk_trp (mk_ctuple lhss === mk_ctuple rhss));
wenzelm@17985
   109
    val ctuple_unfold_thm = standard (Goal.prove thy' [] [] ctuple_unfold
wenzelm@17985
   110
          (fn _ => EVERY [rtac (ctuple_fixdef_thm RS fix_eq2 RS trans) 1,
wenzelm@17985
   111
                    simp_tac (simpset_of thy') 1]));
huffman@16401
   112
    val ctuple_induct_thm =
huffman@16461
   113
          (space_implode "_" names ^ "_induct", ctuple_fixdef_thm RS def_fix_ind);
huffman@16401
   114
    
huffman@16401
   115
    fun unfolds [] thm = []
huffman@16461
   116
      | unfolds (n::[]) thm = [(n^"_unfold", thm)]
huffman@16401
   117
      | unfolds (n::ns) thm = let
huffman@16401
   118
          val thmL = thm RS cpair_eqD1;
huffman@16401
   119
          val thmR = thm RS cpair_eqD2;
huffman@16461
   120
        in (n^"_unfold", thmL) :: unfolds ns thmR end;
huffman@16461
   121
    val unfold_thms = unfolds names ctuple_unfold_thm;
huffman@16461
   122
    val thms = ctuple_induct_thm :: unfold_thms;
haftmann@18377
   123
    val (_, thy'') = PureThy.add_thms (map Thm.no_attributes thms) thy';
huffman@16226
   124
  in
huffman@16461
   125
    (thy'', names, fixdef_thms, map snd unfold_thms)
huffman@16401
   126
  end;
huffman@16226
   127
huffman@16387
   128
(*************************************************************************)
huffman@16387
   129
(*********** monadic notation and pattern matching compilation ***********)
huffman@16387
   130
(*************************************************************************)
huffman@16226
   131
huffman@16401
   132
fun add_names (Const(a,_), bs) = Sign.base_name a ins_string bs
huffman@16401
   133
  | add_names (Free(a,_) , bs) = a ins_string bs
huffman@16401
   134
  | add_names (f $ u     , bs) = add_names (f, add_names(u, bs))
huffman@16401
   135
  | add_names (Abs(a,_,t), bs) = add_names (t, a ins_string bs)
huffman@16401
   136
  | add_names (_         , bs) = bs;
huffman@16226
   137
huffman@16226
   138
fun add_terms ts xs = foldr add_names xs ts;
huffman@16226
   139
huffman@16226
   140
(* builds a monadic term for matching a constructor pattern *)
huffman@16387
   141
fun pre_build pat rhs vs taken =
huffman@16387
   142
  case pat of
huffman@16387
   143
    Const("Cfun.Rep_CFun",_)$f$(v as Free(n,T)) =>
huffman@16226
   144
      pre_build f rhs (v::vs) taken
huffman@16387
   145
  | Const("Cfun.Rep_CFun",_)$f$x =>
huffman@16226
   146
      let val (rhs', v, taken') = pre_build x rhs [] taken;
huffman@16387
   147
      in pre_build f rhs' (v::vs) taken' end
huffman@16387
   148
  | Const(c,T) =>
huffman@16226
   149
      let
huffman@16226
   150
        val n = variant taken "v";
huffman@16387
   151
        fun result_type (Type("Cfun.->",[_,T])) (x::xs) = result_type T xs
huffman@16226
   152
          | result_type T _ = T;
huffman@16226
   153
        val v = Free(n, result_type T vs);
huffman@16401
   154
        val m = "match_"^(extern_name(Sign.base_name c));
huffman@16401
   155
        val k = lambda_ctuple vs rhs;
huffman@16226
   156
      in
huffman@16387
   157
        (%%:"Fixrec.bind"`(%%:m`v)`k, v, n::taken)
huffman@16552
   158
      end
huffman@16552
   159
  | Free(n,_) => fixrec_err ("expected constructor, found free variable " ^ quote n)
huffman@16552
   160
  | _ => fixrec_err "pre_build: invalid pattern";
huffman@16226
   161
huffman@16226
   162
(* builds a monadic term for matching a function definition pattern *)
huffman@16226
   163
(* returns (name, arity, matcher) *)
huffman@16387
   164
fun building pat rhs vs taken =
huffman@16387
   165
  case pat of
huffman@16387
   166
    Const("Cfun.Rep_CFun", _)$f$(v as Free(n,T)) =>
huffman@16226
   167
      building f rhs (v::vs) taken
huffman@16387
   168
  | Const("Cfun.Rep_CFun", _)$f$x =>
huffman@16387
   169
      let val (rhs', v, taken') = pre_build x rhs [] taken;
huffman@16387
   170
      in building f rhs' (v::vs) taken' end
huffman@16552
   171
  | Const(name,_) => (name, length vs, big_lambdas vs rhs)
huffman@16552
   172
  | _ => fixrec_err "function is not declared as constant in theory";
huffman@16226
   173
huffman@16387
   174
fun match_eq eq = 
huffman@16552
   175
  let val (lhs,rhs) = dest_eqs eq;
huffman@16552
   176
  in building lhs (%%:"Fixrec.return"`rhs) [] (add_terms [eq] []) end;
huffman@16226
   177
huffman@16226
   178
(* returns the sum (using +++) of the terms in ms *)
huffman@16226
   179
(* also applies "run" to the result! *)
huffman@16226
   180
fun fatbar arity ms =
huffman@16226
   181
  let
huffman@16226
   182
    fun unLAM 0 t = t
huffman@16226
   183
      | unLAM n (_$Abs(_,_,t)) = unLAM (n-1) t
huffman@16552
   184
      | unLAM _ _ = fixrec_err "fatbar: internal error, not enough LAMs";
huffman@16226
   185
    fun reLAM 0 t = t
huffman@16552
   186
      | reLAM n t = reLAM (n-1) (%%:"Cfun.Abs_CFun" $ Abs("",dummyT,t));
huffman@16226
   187
    fun mplus (x,y) = %%:"Fixrec.mplus"`x`y;
huffman@16226
   188
    val msum = foldr1 mplus (map (unLAM arity) ms);
huffman@16226
   189
  in
huffman@16226
   190
    reLAM arity (%%:"Fixrec.run"`msum)
huffman@16226
   191
  end;
huffman@16226
   192
huffman@16387
   193
fun unzip3 [] = ([],[],[])
huffman@16387
   194
  | unzip3 ((x,y,z)::ts) =
huffman@16387
   195
      let val (xs,ys,zs) = unzip3 ts
huffman@16387
   196
      in (x::xs, y::ys, z::zs) end;
huffman@16226
   197
huffman@16387
   198
(* this is the pattern-matching compiler function *)
huffman@16387
   199
fun compile_pats eqs = 
huffman@16387
   200
  let
huffman@16387
   201
    val ((n::names),(a::arities),mats) = unzip3 (map match_eq eqs);
huffman@16387
   202
    val cname = if forall (fn x => n=x) names then n
huffman@16552
   203
          else fixrec_err "all equations in block must define the same function";
huffman@16387
   204
    val arity = if forall (fn x => a=x) arities then a
huffman@16552
   205
          else fixrec_err "all equations in block must have the same arity";
huffman@16387
   206
    val rhs = fatbar arity mats;
huffman@16387
   207
  in
huffman@16401
   208
    mk_trp (%%:cname === rhs)
huffman@16387
   209
  end;
huffman@16387
   210
huffman@16387
   211
(*************************************************************************)
huffman@16387
   212
(********************** Proving associated theorems **********************)
huffman@16387
   213
(*************************************************************************)
huffman@16387
   214
huffman@16552
   215
(* proves a block of pattern matching equations as theorems, using unfold *)
huffman@16552
   216
fun make_simps thy (unfold_thm, eqns) =
huffman@16226
   217
  let
wenzelm@17985
   218
    val tacs = [rtac (unfold_thm RS ssubst_lhs) 1, asm_simp_tac (simpset_of thy) 1];
wenzelm@17985
   219
    fun prove_term t = standard (Goal.prove thy [] [] t (K (EVERY tacs)));
huffman@16552
   220
    fun prove_eqn ((name, eqn_t), atts) = ((name, prove_term eqn_t), atts);
huffman@16401
   221
  in
huffman@16552
   222
    map prove_eqn eqns
huffman@16401
   223
  end;
huffman@16226
   224
huffman@16387
   225
(*************************************************************************)
huffman@16387
   226
(************************* Main fixrec function **************************)
huffman@16387
   227
(*************************************************************************)
huffman@16226
   228
huffman@16552
   229
fun gen_add_fixrec prep_prop prep_attrib strict blocks thy =
huffman@16226
   230
  let
huffman@16552
   231
    val eqns = List.concat blocks;
huffman@16552
   232
    val lengths = map length blocks;
huffman@16552
   233
    
huffman@16552
   234
    val ((names, srcss), strings) = apfst split_list (split_list eqns);
huffman@16552
   235
    val atts = map (map (prep_attrib thy)) srcss;
huffman@16552
   236
    val eqn_ts = map (prep_prop thy) strings;
huffman@16552
   237
    val rec_ts = map (fn eq => chead_of (fst (dest_eqs (Logic.strip_imp_concl eq)))
huffman@16628
   238
      handle TERM _ => fixrec_eq_err thy "not a proper equation" eq) eqn_ts;
huffman@16628
   239
    val (_, eqn_ts') = InductivePackage.unify_consts thy rec_ts eqn_ts;
huffman@16552
   240
    
huffman@16552
   241
    fun unconcat [] _ = []
huffman@16552
   242
      | unconcat (n::ns) xs = List.take (xs,n) :: unconcat ns (List.drop (xs,n));
huffman@16552
   243
    val pattern_blocks = unconcat lengths (map Logic.strip_imp_concl eqn_ts');
huffman@16628
   244
    val compiled_ts = map (infer thy o compile_pats) pattern_blocks;
huffman@16552
   245
    val (thy', cnames, fixdef_thms, unfold_thms) = add_fixdefs compiled_ts thy;
huffman@16226
   246
  in
huffman@16552
   247
    if strict then let (* only prove simp rules if strict = true *)
huffman@16552
   248
      val eqn_blocks = unconcat lengths ((names ~~ eqn_ts') ~~ atts);
huffman@16552
   249
      val simps = List.concat (map (make_simps thy') (unfold_thms ~~ eqn_blocks));
haftmann@18377
   250
      val (simp_thms, thy'') = PureThy.add_thms simps thy';
huffman@16552
   251
      
huffman@16552
   252
      val simp_names = map (fn name => name^"_simps") cnames;
wenzelm@18688
   253
      val simp_attribute = rpair [Attrib.theory Simplifier.simp_add];
huffman@16552
   254
      val simps' = map simp_attribute (simp_names ~~ unconcat lengths simp_thms);
huffman@16552
   255
    in
haftmann@18377
   256
      (snd o PureThy.add_thmss simps') thy''
huffman@16552
   257
    end
huffman@16552
   258
    else thy'
huffman@16226
   259
  end;
huffman@16226
   260
wenzelm@16488
   261
val add_fixrec = gen_add_fixrec Sign.read_prop Attrib.global_attribute;
wenzelm@16488
   262
val add_fixrec_i = gen_add_fixrec Sign.cert_prop (K I);
wenzelm@16488
   263
wenzelm@16488
   264
huffman@16387
   265
(*************************************************************************)
huffman@16387
   266
(******************************** Fixpat *********************************)
huffman@16387
   267
(*************************************************************************)
huffman@16226
   268
huffman@16552
   269
fun fix_pat thy t = 
huffman@16226
   270
  let
huffman@16387
   271
    val T = fastype_of t;
huffman@16401
   272
    val eq = mk_trp (HOLogic.eq_const T $ t $ Var (("x",0),T));
huffman@16461
   273
    val cname = case chead_of t of Const(c,_) => c | _ =>
huffman@16552
   274
              fixrec_err "function is not declared as constant in theory";
wenzelm@16488
   275
    val unfold_thm = PureThy.get_thm thy (Name (cname^"_unfold"));
wenzelm@17985
   276
    val simp = standard (Goal.prove thy [] [] eq
wenzelm@17985
   277
          (fn _ => EVERY [stac unfold_thm 1, simp_tac (simpset_of thy) 1]));
huffman@16552
   278
  in simp end;
huffman@16226
   279
huffman@16552
   280
fun gen_add_fixpat prep_term prep_attrib ((name, srcs), strings) thy =
huffman@16402
   281
  let
huffman@16552
   282
    val atts = map (prep_attrib thy) srcs;
huffman@16552
   283
    val ts = map (prep_term thy) strings;
huffman@16552
   284
    val simps = map (fix_pat thy) ts;
huffman@16552
   285
  in
haftmann@18377
   286
    (snd o PureThy.add_thmss [((name, simps), atts)]) thy
huffman@16552
   287
  end;
huffman@16226
   288
wenzelm@16488
   289
val add_fixpat = gen_add_fixpat Sign.read_term Attrib.global_attribute;
wenzelm@16488
   290
val add_fixpat_i = gen_add_fixpat Sign.cert_term (K I);
wenzelm@16488
   291
wenzelm@16488
   292
huffman@16387
   293
(*************************************************************************)
huffman@16387
   294
(******************************** Parsers ********************************)
huffman@16387
   295
(*************************************************************************)
huffman@16226
   296
wenzelm@17057
   297
local structure P = OuterParse and K = OuterKeyword in
huffman@16226
   298
huffman@16552
   299
val fixrec_eqn = P.opt_thm_name ":" -- P.prop;
huffman@16552
   300
huffman@16628
   301
val fixrec_strict = P.opt_keyword "permissive" >> not;
huffman@16552
   302
huffman@16552
   303
val fixrec_decl = fixrec_strict -- P.and_list1 (Scan.repeat1 fixrec_eqn);
huffman@16226
   304
huffman@16226
   305
(* this builds a parser for a new keyword, fixrec, whose functionality 
huffman@16226
   306
is defined by add_fixrec *)
huffman@16226
   307
val fixrecP =
huffman@16402
   308
  OuterSyntax.command "fixrec" "define recursive functions (HOLCF)" K.thy_decl
huffman@16552
   309
    (fixrec_decl >> (Toplevel.theory o uncurry add_fixrec));
huffman@16226
   310
huffman@16226
   311
(* fixpat parser *)
huffman@16552
   312
val fixpat_decl = P.opt_thm_name ":" -- Scan.repeat1 P.prop;
huffman@16226
   313
huffman@16226
   314
val fixpatP =
huffman@16402
   315
  OuterSyntax.command "fixpat" "define rewrites for fixrec functions" K.thy_decl
huffman@16226
   316
    (fixpat_decl >> (Toplevel.theory o add_fixpat));
huffman@16226
   317
huffman@16552
   318
val _ = OuterSyntax.add_parsers [fixrecP, fixpatP];
huffman@16226
   319
huffman@16226
   320
end; (* local structure *)
huffman@16226
   321
huffman@16226
   322
end; (* struct *)