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