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