src/HOL/Imperative_HOL/Heap_Monad.thy
author krauss
Mon May 23 10:58:21 2011 +0200 (2011-05-23)
changeset 42949 618adb3584e5
parent 41413 64cd30d6b0b8
child 43080 73a1d6a7ef1d
permissions -rw-r--r--
separate initializations for different modes of partial_function -- generation of induction rules will be non-uniform
     1 (*  Title:      HOL/Imperative_HOL/Heap_Monad.thy
     2     Author:     John Matthews, Galois Connections; Alexander Krauss, Lukas Bulwahn & Florian Haftmann, TU Muenchen
     3 *)
     4 
     5 header {* A monad with a polymorphic heap and primitive reasoning infrastructure *}
     6 
     7 theory Heap_Monad
     8 imports
     9   Heap
    10   "~~/src/HOL/Library/Monad_Syntax"
    11   "~~/src/HOL/Library/Code_Natural"
    12 begin
    13 
    14 subsection {* The monad *}
    15 
    16 subsubsection {* Monad construction *}
    17 
    18 text {* Monadic heap actions either produce values
    19   and transform the heap, or fail *}
    20 datatype 'a Heap = Heap "heap \<Rightarrow> ('a \<times> heap) option"
    21 
    22 lemma [code, code del]:
    23   "(Code_Evaluation.term_of :: 'a::typerep Heap \<Rightarrow> Code_Evaluation.term) = Code_Evaluation.term_of"
    24   ..
    25 
    26 primrec execute :: "'a Heap \<Rightarrow> heap \<Rightarrow> ('a \<times> heap) option" where
    27   [code del]: "execute (Heap f) = f"
    28 
    29 lemma Heap_cases [case_names succeed fail]:
    30   fixes f and h
    31   assumes succeed: "\<And>x h'. execute f h = Some (x, h') \<Longrightarrow> P"
    32   assumes fail: "execute f h = None \<Longrightarrow> P"
    33   shows P
    34   using assms by (cases "execute f h") auto
    35 
    36 lemma Heap_execute [simp]:
    37   "Heap (execute f) = f" by (cases f) simp_all
    38 
    39 lemma Heap_eqI:
    40   "(\<And>h. execute f h = execute g h) \<Longrightarrow> f = g"
    41     by (cases f, cases g) (auto simp: fun_eq_iff)
    42 
    43 ML {* structure Execute_Simps = Named_Thms(
    44   val name = "execute_simps"
    45   val description = "simplification rules for execute"
    46 ) *}
    47 
    48 setup Execute_Simps.setup
    49 
    50 lemma execute_Let [execute_simps]:
    51   "execute (let x = t in f x) = (let x = t in execute (f x))"
    52   by (simp add: Let_def)
    53 
    54 
    55 subsubsection {* Specialised lifters *}
    56 
    57 definition tap :: "(heap \<Rightarrow> 'a) \<Rightarrow> 'a Heap" where
    58   [code del]: "tap f = Heap (\<lambda>h. Some (f h, h))"
    59 
    60 lemma execute_tap [execute_simps]:
    61   "execute (tap f) h = Some (f h, h)"
    62   by (simp add: tap_def)
    63 
    64 definition heap :: "(heap \<Rightarrow> 'a \<times> heap) \<Rightarrow> 'a Heap" where
    65   [code del]: "heap f = Heap (Some \<circ> f)"
    66 
    67 lemma execute_heap [execute_simps]:
    68   "execute (heap f) = Some \<circ> f"
    69   by (simp add: heap_def)
    70 
    71 definition guard :: "(heap \<Rightarrow> bool) \<Rightarrow> (heap \<Rightarrow> 'a \<times> heap) \<Rightarrow> 'a Heap" where
    72   [code del]: "guard P f = Heap (\<lambda>h. if P h then Some (f h) else None)"
    73 
    74 lemma execute_guard [execute_simps]:
    75   "\<not> P h \<Longrightarrow> execute (guard P f) h = None"
    76   "P h \<Longrightarrow> execute (guard P f) h = Some (f h)"
    77   by (simp_all add: guard_def)
    78 
    79 
    80 subsubsection {* Predicate classifying successful computations *}
    81 
    82 definition success :: "'a Heap \<Rightarrow> heap \<Rightarrow> bool" where
    83   "success f h \<longleftrightarrow> execute f h \<noteq> None"
    84 
    85 lemma successI:
    86   "execute f h \<noteq> None \<Longrightarrow> success f h"
    87   by (simp add: success_def)
    88 
    89 lemma successE:
    90   assumes "success f h"
    91   obtains r h' where "r = fst (the (execute c h))"
    92     and "h' = snd (the (execute c h))"
    93     and "execute f h \<noteq> None"
    94   using assms by (simp add: success_def)
    95 
    96 ML {* structure Success_Intros = Named_Thms(
    97   val name = "success_intros"
    98   val description = "introduction rules for success"
    99 ) *}
   100 
   101 setup Success_Intros.setup
   102 
   103 lemma success_tapI [success_intros]:
   104   "success (tap f) h"
   105   by (rule successI) (simp add: execute_simps)
   106 
   107 lemma success_heapI [success_intros]:
   108   "success (heap f) h"
   109   by (rule successI) (simp add: execute_simps)
   110 
   111 lemma success_guardI [success_intros]:
   112   "P h \<Longrightarrow> success (guard P f) h"
   113   by (rule successI) (simp add: execute_guard)
   114 
   115 lemma success_LetI [success_intros]:
   116   "x = t \<Longrightarrow> success (f x) h \<Longrightarrow> success (let x = t in f x) h"
   117   by (simp add: Let_def)
   118 
   119 lemma success_ifI:
   120   "(c \<Longrightarrow> success t h) \<Longrightarrow> (\<not> c \<Longrightarrow> success e h) \<Longrightarrow>
   121     success (if c then t else e) h"
   122   by (simp add: success_def)
   123 
   124 
   125 subsubsection {* Predicate for a simple relational calculus *}
   126 
   127 text {*
   128   The @{text effect} predicate states that when a computation @{text c}
   129   runs with the heap @{text h} will result in return value @{text r}
   130   and a heap @{text "h'"}, i.e.~no exception occurs.
   131 *}  
   132 
   133 definition effect :: "'a Heap \<Rightarrow> heap \<Rightarrow> heap \<Rightarrow> 'a \<Rightarrow> bool" where
   134   effect_def: "effect c h h' r \<longleftrightarrow> execute c h = Some (r, h')"
   135 
   136 lemma effectI:
   137   "execute c h = Some (r, h') \<Longrightarrow> effect c h h' r"
   138   by (simp add: effect_def)
   139 
   140 lemma effectE:
   141   assumes "effect c h h' r"
   142   obtains "r = fst (the (execute c h))"
   143     and "h' = snd (the (execute c h))"
   144     and "success c h"
   145 proof (rule that)
   146   from assms have *: "execute c h = Some (r, h')" by (simp add: effect_def)
   147   then show "success c h" by (simp add: success_def)
   148   from * have "fst (the (execute c h)) = r" and "snd (the (execute c h)) = h'"
   149     by simp_all
   150   then show "r = fst (the (execute c h))"
   151     and "h' = snd (the (execute c h))" by simp_all
   152 qed
   153 
   154 lemma effect_success:
   155   "effect c h h' r \<Longrightarrow> success c h"
   156   by (simp add: effect_def success_def)
   157 
   158 lemma success_effectE:
   159   assumes "success c h"
   160   obtains r h' where "effect c h h' r"
   161   using assms by (auto simp add: effect_def success_def)
   162 
   163 lemma effect_deterministic:
   164   assumes "effect f h h' a"
   165     and "effect f h h'' b"
   166   shows "a = b" and "h' = h''"
   167   using assms unfolding effect_def by auto
   168 
   169 ML {* structure Crel_Intros = Named_Thms(
   170   val name = "effect_intros"
   171   val description = "introduction rules for effect"
   172 ) *}
   173 
   174 ML {* structure Crel_Elims = Named_Thms(
   175   val name = "effect_elims"
   176   val description = "elimination rules for effect"
   177 ) *}
   178 
   179 setup "Crel_Intros.setup #> Crel_Elims.setup"
   180 
   181 lemma effect_LetI [effect_intros]:
   182   assumes "x = t" "effect (f x) h h' r"
   183   shows "effect (let x = t in f x) h h' r"
   184   using assms by simp
   185 
   186 lemma effect_LetE [effect_elims]:
   187   assumes "effect (let x = t in f x) h h' r"
   188   obtains "effect (f t) h h' r"
   189   using assms by simp
   190 
   191 lemma effect_ifI:
   192   assumes "c \<Longrightarrow> effect t h h' r"
   193     and "\<not> c \<Longrightarrow> effect e h h' r"
   194   shows "effect (if c then t else e) h h' r"
   195   by (cases c) (simp_all add: assms)
   196 
   197 lemma effect_ifE:
   198   assumes "effect (if c then t else e) h h' r"
   199   obtains "c" "effect t h h' r"
   200     | "\<not> c" "effect e h h' r"
   201   using assms by (cases c) simp_all
   202 
   203 lemma effect_tapI [effect_intros]:
   204   assumes "h' = h" "r = f h"
   205   shows "effect (tap f) h h' r"
   206   by (rule effectI) (simp add: assms execute_simps)
   207 
   208 lemma effect_tapE [effect_elims]:
   209   assumes "effect (tap f) h h' r"
   210   obtains "h' = h" and "r = f h"
   211   using assms by (rule effectE) (auto simp add: execute_simps)
   212 
   213 lemma effect_heapI [effect_intros]:
   214   assumes "h' = snd (f h)" "r = fst (f h)"
   215   shows "effect (heap f) h h' r"
   216   by (rule effectI) (simp add: assms execute_simps)
   217 
   218 lemma effect_heapE [effect_elims]:
   219   assumes "effect (heap f) h h' r"
   220   obtains "h' = snd (f h)" and "r = fst (f h)"
   221   using assms by (rule effectE) (simp add: execute_simps)
   222 
   223 lemma effect_guardI [effect_intros]:
   224   assumes "P h" "h' = snd (f h)" "r = fst (f h)"
   225   shows "effect (guard P f) h h' r"
   226   by (rule effectI) (simp add: assms execute_simps)
   227 
   228 lemma effect_guardE [effect_elims]:
   229   assumes "effect (guard P f) h h' r"
   230   obtains "h' = snd (f h)" "r = fst (f h)" "P h"
   231   using assms by (rule effectE)
   232     (auto simp add: execute_simps elim!: successE, cases "P h", auto simp add: execute_simps)
   233 
   234 
   235 subsubsection {* Monad combinators *}
   236 
   237 definition return :: "'a \<Rightarrow> 'a Heap" where
   238   [code del]: "return x = heap (Pair x)"
   239 
   240 lemma execute_return [execute_simps]:
   241   "execute (return x) = Some \<circ> Pair x"
   242   by (simp add: return_def execute_simps)
   243 
   244 lemma success_returnI [success_intros]:
   245   "success (return x) h"
   246   by (rule successI) (simp add: execute_simps)
   247 
   248 lemma effect_returnI [effect_intros]:
   249   "h = h' \<Longrightarrow> effect (return x) h h' x"
   250   by (rule effectI) (simp add: execute_simps)
   251 
   252 lemma effect_returnE [effect_elims]:
   253   assumes "effect (return x) h h' r"
   254   obtains "r = x" "h' = h"
   255   using assms by (rule effectE) (simp add: execute_simps)
   256 
   257 definition raise :: "string \<Rightarrow> 'a Heap" where -- {* the string is just decoration *}
   258   [code del]: "raise s = Heap (\<lambda>_. None)"
   259 
   260 lemma execute_raise [execute_simps]:
   261   "execute (raise s) = (\<lambda>_. None)"
   262   by (simp add: raise_def)
   263 
   264 lemma effect_raiseE [effect_elims]:
   265   assumes "effect (raise x) h h' r"
   266   obtains "False"
   267   using assms by (rule effectE) (simp add: success_def execute_simps)
   268 
   269 definition bind :: "'a Heap \<Rightarrow> ('a \<Rightarrow> 'b Heap) \<Rightarrow> 'b Heap" where
   270   [code del]: "bind f g = Heap (\<lambda>h. case execute f h of
   271                   Some (x, h') \<Rightarrow> execute (g x) h'
   272                 | None \<Rightarrow> None)"
   273 
   274 setup {*
   275   Adhoc_Overloading.add_variant 
   276     @{const_name Monad_Syntax.bind} @{const_name Heap_Monad.bind}
   277 *}
   278 
   279 lemma execute_bind [execute_simps]:
   280   "execute f h = Some (x, h') \<Longrightarrow> execute (f \<guillemotright>= g) h = execute (g x) h'"
   281   "execute f h = None \<Longrightarrow> execute (f \<guillemotright>= g) h = None"
   282   by (simp_all add: bind_def)
   283 
   284 lemma execute_bind_case:
   285   "execute (f \<guillemotright>= g) h = (case (execute f h) of
   286     Some (x, h') \<Rightarrow> execute (g x) h' | None \<Rightarrow> None)"
   287   by (simp add: bind_def)
   288 
   289 lemma execute_bind_success:
   290   "success f h \<Longrightarrow> execute (f \<guillemotright>= g) h = execute (g (fst (the (execute f h)))) (snd (the (execute f h)))"
   291   by (cases f h rule: Heap_cases) (auto elim!: successE simp add: bind_def)
   292 
   293 lemma success_bind_executeI:
   294   "execute f h = Some (x, h') \<Longrightarrow> success (g x) h' \<Longrightarrow> success (f \<guillemotright>= g) h"
   295   by (auto intro!: successI elim!: successE simp add: bind_def)
   296 
   297 lemma success_bind_effectI [success_intros]:
   298   "effect f h h' x \<Longrightarrow> success (g x) h' \<Longrightarrow> success (f \<guillemotright>= g) h"
   299   by (auto simp add: effect_def success_def bind_def)
   300 
   301 lemma effect_bindI [effect_intros]:
   302   assumes "effect f h h' r" "effect (g r) h' h'' r'"
   303   shows "effect (f \<guillemotright>= g) h h'' r'"
   304   using assms
   305   apply (auto intro!: effectI elim!: effectE successE)
   306   apply (subst execute_bind, simp_all)
   307   done
   308 
   309 lemma effect_bindE [effect_elims]:
   310   assumes "effect (f \<guillemotright>= g) h h'' r'"
   311   obtains h' r where "effect f h h' r" "effect (g r) h' h'' r'"
   312   using assms by (auto simp add: effect_def bind_def split: option.split_asm)
   313 
   314 lemma execute_bind_eq_SomeI:
   315   assumes "execute f h = Some (x, h')"
   316     and "execute (g x) h' = Some (y, h'')"
   317   shows "execute (f \<guillemotright>= g) h = Some (y, h'')"
   318   using assms by (simp add: bind_def)
   319 
   320 lemma return_bind [simp]: "return x \<guillemotright>= f = f x"
   321   by (rule Heap_eqI) (simp add: execute_bind execute_simps)
   322 
   323 lemma bind_return [simp]: "f \<guillemotright>= return = f"
   324   by (rule Heap_eqI) (simp add: bind_def execute_simps split: option.splits)
   325 
   326 lemma bind_bind [simp]: "(f \<guillemotright>= g) \<guillemotright>= k = (f :: 'a Heap) \<guillemotright>= (\<lambda>x. g x \<guillemotright>= k)"
   327   by (rule Heap_eqI) (simp add: bind_def execute_simps split: option.splits)
   328 
   329 lemma raise_bind [simp]: "raise e \<guillemotright>= f = raise e"
   330   by (rule Heap_eqI) (simp add: execute_simps)
   331 
   332 
   333 subsection {* Generic combinators *}
   334 
   335 subsubsection {* Assertions *}
   336 
   337 definition assert :: "('a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a Heap" where
   338   "assert P x = (if P x then return x else raise ''assert'')"
   339 
   340 lemma execute_assert [execute_simps]:
   341   "P x \<Longrightarrow> execute (assert P x) h = Some (x, h)"
   342   "\<not> P x \<Longrightarrow> execute (assert P x) h = None"
   343   by (simp_all add: assert_def execute_simps)
   344 
   345 lemma success_assertI [success_intros]:
   346   "P x \<Longrightarrow> success (assert P x) h"
   347   by (rule successI) (simp add: execute_assert)
   348 
   349 lemma effect_assertI [effect_intros]:
   350   "P x \<Longrightarrow> h' = h \<Longrightarrow> r = x \<Longrightarrow> effect (assert P x) h h' r"
   351   by (rule effectI) (simp add: execute_assert)
   352  
   353 lemma effect_assertE [effect_elims]:
   354   assumes "effect (assert P x) h h' r"
   355   obtains "P x" "r = x" "h' = h"
   356   using assms by (rule effectE) (cases "P x", simp_all add: execute_assert success_def)
   357 
   358 lemma assert_cong [fundef_cong]:
   359   assumes "P = P'"
   360   assumes "\<And>x. P' x \<Longrightarrow> f x = f' x"
   361   shows "(assert P x >>= f) = (assert P' x >>= f')"
   362   by (rule Heap_eqI) (insert assms, simp add: assert_def)
   363 
   364 
   365 subsubsection {* Plain lifting *}
   366 
   367 definition lift :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b Heap" where
   368   "lift f = return o f"
   369 
   370 lemma lift_collapse [simp]:
   371   "lift f x = return (f x)"
   372   by (simp add: lift_def)
   373 
   374 lemma bind_lift:
   375   "(f \<guillemotright>= lift g) = (f \<guillemotright>= (\<lambda>x. return (g x)))"
   376   by (simp add: lift_def comp_def)
   377 
   378 
   379 subsubsection {* Iteration -- warning: this is rarely useful! *}
   380 
   381 primrec fold_map :: "('a \<Rightarrow> 'b Heap) \<Rightarrow> 'a list \<Rightarrow> 'b list Heap" where
   382   "fold_map f [] = return []"
   383 | "fold_map f (x # xs) = do {
   384      y \<leftarrow> f x;
   385      ys \<leftarrow> fold_map f xs;
   386      return (y # ys)
   387    }"
   388 
   389 lemma fold_map_append:
   390   "fold_map f (xs @ ys) = fold_map f xs \<guillemotright>= (\<lambda>xs. fold_map f ys \<guillemotright>= (\<lambda>ys. return (xs @ ys)))"
   391   by (induct xs) simp_all
   392 
   393 lemma execute_fold_map_unchanged_heap [execute_simps]:
   394   assumes "\<And>x. x \<in> set xs \<Longrightarrow> \<exists>y. execute (f x) h = Some (y, h)"
   395   shows "execute (fold_map f xs) h =
   396     Some (List.map (\<lambda>x. fst (the (execute (f x) h))) xs, h)"
   397 using assms proof (induct xs)
   398   case Nil show ?case by (simp add: execute_simps)
   399 next
   400   case (Cons x xs)
   401   from Cons.prems obtain y
   402     where y: "execute (f x) h = Some (y, h)" by auto
   403   moreover from Cons.prems Cons.hyps have "execute (fold_map f xs) h =
   404     Some (map (\<lambda>x. fst (the (execute (f x) h))) xs, h)" by auto
   405   ultimately show ?case by (simp, simp only: execute_bind(1), simp add: execute_simps)
   406 qed
   407 
   408 
   409 subsection {* Partial function definition setup *}
   410 
   411 definition Heap_ord :: "'a Heap \<Rightarrow> 'a Heap \<Rightarrow> bool" where
   412   "Heap_ord = img_ord execute (fun_ord option_ord)"
   413 
   414 definition Heap_lub :: "('a Heap \<Rightarrow> bool) \<Rightarrow> 'a Heap" where
   415   "Heap_lub = img_lub execute Heap (fun_lub (flat_lub None))"
   416 
   417 interpretation heap!: partial_function_definitions Heap_ord Heap_lub
   418 proof -
   419   have "partial_function_definitions (fun_ord option_ord) (fun_lub (flat_lub None))"
   420     by (rule partial_function_lift) (rule flat_interpretation)
   421   then have "partial_function_definitions (img_ord execute (fun_ord option_ord))
   422       (img_lub execute Heap (fun_lub (flat_lub None)))"
   423     by (rule partial_function_image) (auto intro: Heap_eqI)
   424   then show "partial_function_definitions Heap_ord Heap_lub"
   425     by (simp only: Heap_ord_def Heap_lub_def)
   426 qed
   427 
   428 declaration {* Partial_Function.init "heap" @{term heap.fixp_fun}
   429   @{term heap.mono_body} @{thm heap.fixp_rule_uc} *}
   430 
   431 
   432 abbreviation "mono_Heap \<equiv> monotone (fun_ord Heap_ord) Heap_ord"
   433 
   434 lemma Heap_ordI:
   435   assumes "\<And>h. execute x h = None \<or> execute x h = execute y h"
   436   shows "Heap_ord x y"
   437   using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def
   438   by blast
   439 
   440 lemma Heap_ordE:
   441   assumes "Heap_ord x y"
   442   obtains "execute x h = None" | "execute x h = execute y h"
   443   using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def
   444   by atomize_elim blast
   445 
   446 lemma bind_mono[partial_function_mono]:
   447   assumes mf: "mono_Heap B" and mg: "\<And>y. mono_Heap (\<lambda>f. C y f)"
   448   shows "mono_Heap (\<lambda>f. B f \<guillemotright>= (\<lambda>y. C y f))"
   449 proof (rule monotoneI)
   450   fix f g :: "'a \<Rightarrow> 'b Heap" assume fg: "fun_ord Heap_ord f g"
   451   from mf
   452   have 1: "Heap_ord (B f) (B g)" by (rule monotoneD) (rule fg)
   453   from mg
   454   have 2: "\<And>y'. Heap_ord (C y' f) (C y' g)" by (rule monotoneD) (rule fg)
   455 
   456   have "Heap_ord (B f \<guillemotright>= (\<lambda>y. C y f)) (B g \<guillemotright>= (\<lambda>y. C y f))"
   457     (is "Heap_ord ?L ?R")
   458   proof (rule Heap_ordI)
   459     fix h
   460     from 1 show "execute ?L h = None \<or> execute ?L h = execute ?R h"
   461       by (rule Heap_ordE[where h = h]) (auto simp: execute_bind_case)
   462   qed
   463   also
   464   have "Heap_ord (B g \<guillemotright>= (\<lambda>y'. C y' f)) (B g \<guillemotright>= (\<lambda>y'. C y' g))"
   465     (is "Heap_ord ?L ?R")
   466   proof (rule Heap_ordI)
   467     fix h
   468     show "execute ?L h = None \<or> execute ?L h = execute ?R h"
   469     proof (cases "execute (B g) h")
   470       case None
   471       then have "execute ?L h = None" by (auto simp: execute_bind_case)
   472       thus ?thesis ..
   473     next
   474       case Some
   475       then obtain r h' where "execute (B g) h = Some (r, h')"
   476         by (metis surjective_pairing)
   477       then have "execute ?L h = execute (C r f) h'"
   478         "execute ?R h = execute (C r g) h'"
   479         by (auto simp: execute_bind_case)
   480       with 2[of r] show ?thesis by (auto elim: Heap_ordE)
   481     qed
   482   qed
   483   finally (heap.leq_trans)
   484   show "Heap_ord (B f \<guillemotright>= (\<lambda>y. C y f)) (B g \<guillemotright>= (\<lambda>y'. C y' g))" .
   485 qed
   486 
   487 
   488 subsection {* Code generator setup *}
   489 
   490 subsubsection {* Logical intermediate layer *}
   491 
   492 definition raise' :: "String.literal \<Rightarrow> 'a Heap" where
   493   [code del]: "raise' s = raise (explode s)"
   494 
   495 lemma [code_post]: "raise' (STR s) = raise s"
   496 unfolding raise'_def by (simp add: STR_inverse)
   497 
   498 lemma raise_raise' [code_inline]:
   499   "raise s = raise' (STR s)"
   500   unfolding raise'_def by (simp add: STR_inverse)
   501 
   502 code_datatype raise' -- {* avoid @{const "Heap"} formally *}
   503 
   504 
   505 subsubsection {* SML and OCaml *}
   506 
   507 code_type Heap (SML "unit/ ->/ _")
   508 code_const bind (SML "!(fn/ f'_/ =>/ fn/ ()/ =>/ f'_/ (_/ ())/ ())")
   509 code_const return (SML "!(fn/ ()/ =>/ _)")
   510 code_const Heap_Monad.raise' (SML "!(raise/ Fail/ _)")
   511 
   512 code_type Heap (OCaml "unit/ ->/ _")
   513 code_const bind (OCaml "!(fun/ f'_/ ()/ ->/ f'_/ (_/ ())/ ())")
   514 code_const return (OCaml "!(fun/ ()/ ->/ _)")
   515 code_const Heap_Monad.raise' (OCaml "failwith")
   516 
   517 
   518 subsubsection {* Haskell *}
   519 
   520 text {* Adaption layer *}
   521 
   522 code_include Haskell "Heap"
   523 {*import qualified Control.Monad;
   524 import qualified Control.Monad.ST;
   525 import qualified Data.STRef;
   526 import qualified Data.Array.ST;
   527 
   528 import Natural;
   529 
   530 type RealWorld = Control.Monad.ST.RealWorld;
   531 type ST s a = Control.Monad.ST.ST s a;
   532 type STRef s a = Data.STRef.STRef s a;
   533 type STArray s a = Data.Array.ST.STArray s Natural a;
   534 
   535 newSTRef = Data.STRef.newSTRef;
   536 readSTRef = Data.STRef.readSTRef;
   537 writeSTRef = Data.STRef.writeSTRef;
   538 
   539 newArray :: Natural -> a -> ST s (STArray s a);
   540 newArray k = Data.Array.ST.newArray (0, k);
   541 
   542 newListArray :: [a] -> ST s (STArray s a);
   543 newListArray xs = Data.Array.ST.newListArray (0, (fromInteger . toInteger . length) xs) xs;
   544 
   545 newFunArray :: Natural -> (Natural -> a) -> ST s (STArray s a);
   546 newFunArray k f = Data.Array.ST.newListArray (0, k) (map f [0..k-1]);
   547 
   548 lengthArray :: STArray s a -> ST s Natural;
   549 lengthArray a = Control.Monad.liftM snd (Data.Array.ST.getBounds a);
   550 
   551 readArray :: STArray s a -> Natural -> ST s a;
   552 readArray = Data.Array.ST.readArray;
   553 
   554 writeArray :: STArray s a -> Natural -> a -> ST s ();
   555 writeArray = Data.Array.ST.writeArray;*}
   556 
   557 code_reserved Haskell Heap
   558 
   559 text {* Monad *}
   560 
   561 code_type Heap (Haskell "Heap.ST/ Heap.RealWorld/ _")
   562 code_monad bind Haskell
   563 code_const return (Haskell "return")
   564 code_const Heap_Monad.raise' (Haskell "error")
   565 
   566 
   567 subsubsection {* Scala *}
   568 
   569 code_include Scala "Heap"
   570 {*object Heap {
   571   def bind[A, B](f: Unit => A, g: A => Unit => B): Unit => B = (_: Unit) => g (f ()) ()
   572 }
   573 
   574 class Ref[A](x: A) {
   575   var value = x
   576 }
   577 
   578 object Ref {
   579   def apply[A](x: A): Ref[A] =
   580     new Ref[A](x)
   581   def lookup[A](r: Ref[A]): A =
   582     r.value
   583   def update[A](r: Ref[A], x: A): Unit =
   584     { r.value = x }
   585 }
   586 
   587 object Array {
   588   import collection.mutable.ArraySeq
   589   def alloc[A](n: Natural)(x: A): ArraySeq[A] =
   590     ArraySeq.fill(n.as_Int)(x)
   591   def make[A](n: Natural)(f: Natural => A): ArraySeq[A] =
   592     ArraySeq.tabulate(n.as_Int)((k: Int) => f(Natural(k)))
   593   def len[A](a: ArraySeq[A]): Natural =
   594     Natural(a.length)
   595   def nth[A](a: ArraySeq[A], n: Natural): A =
   596     a(n.as_Int)
   597   def upd[A](a: ArraySeq[A], n: Natural, x: A): Unit =
   598     a.update(n.as_Int, x)
   599   def freeze[A](a: ArraySeq[A]): List[A] =
   600     a.toList
   601 }
   602 *}
   603 
   604 code_reserved Scala Heap Ref Array
   605 
   606 code_type Heap (Scala "Unit/ =>/ _")
   607 code_const bind (Scala "Heap.bind")
   608 code_const return (Scala "('_: Unit)/ =>/ _")
   609 code_const Heap_Monad.raise' (Scala "!error((_))")
   610 
   611 
   612 subsubsection {* Target variants with less units *}
   613 
   614 setup {*
   615 
   616 let
   617 
   618 open Code_Thingol;
   619 
   620 fun imp_program naming =
   621 
   622   let
   623     fun is_const c = case lookup_const naming c
   624      of SOME c' => (fn c'' => c' = c'')
   625       | NONE => K false;
   626     val is_bind = is_const @{const_name bind};
   627     val is_return = is_const @{const_name return};
   628     val dummy_name = "";
   629     val dummy_case_term = IVar NONE;
   630     (*assumption: dummy values are not relevant for serialization*)
   631     val (unitt, unitT) = case lookup_const naming @{const_name Unity}
   632      of SOME unit' => (IConst (unit', (([], []), [])), the (lookup_tyco naming @{type_name unit}) `%% [])
   633       | NONE => error ("Must include " ^ @{const_name Unity} ^ " in generated constants.");
   634     fun dest_abs ((v, ty) `|=> t, _) = ((v, ty), t)
   635       | dest_abs (t, ty) =
   636           let
   637             val vs = fold_varnames cons t [];
   638             val v = Name.variant vs "x";
   639             val ty' = (hd o fst o unfold_fun) ty;
   640           in ((SOME v, ty'), t `$ IVar (SOME v)) end;
   641     fun force (t as IConst (c, _) `$ t') = if is_return c
   642           then t' else t `$ unitt
   643       | force t = t `$ unitt;
   644     fun tr_bind'' [(t1, _), (t2, ty2)] =
   645       let
   646         val ((v, ty), t) = dest_abs (t2, ty2);
   647       in ICase (((force t1, ty), [(IVar v, tr_bind' t)]), dummy_case_term) end
   648     and tr_bind' t = case unfold_app t
   649      of (IConst (c, (_, ty1 :: ty2 :: _)), [x1, x2]) => if is_bind c
   650           then tr_bind'' [(x1, ty1), (x2, ty2)]
   651           else force t
   652       | _ => force t;
   653     fun imp_monad_bind'' ts = (SOME dummy_name, unitT) `|=> ICase (((IVar (SOME dummy_name), unitT),
   654       [(unitt, tr_bind'' ts)]), dummy_case_term)
   655     fun imp_monad_bind' (const as (c, (_, tys))) ts = if is_bind c then case (ts, tys)
   656        of ([t1, t2], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)]
   657         | ([t1, t2, t3], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)] `$ t3
   658         | (ts, _) => imp_monad_bind (eta_expand 2 (const, ts))
   659       else IConst const `$$ map imp_monad_bind ts
   660     and imp_monad_bind (IConst const) = imp_monad_bind' const []
   661       | imp_monad_bind (t as IVar _) = t
   662       | imp_monad_bind (t as _ `$ _) = (case unfold_app t
   663          of (IConst const, ts) => imp_monad_bind' const ts
   664           | (t, ts) => imp_monad_bind t `$$ map imp_monad_bind ts)
   665       | imp_monad_bind (v_ty `|=> t) = v_ty `|=> imp_monad_bind t
   666       | imp_monad_bind (ICase (((t, ty), pats), t0)) = ICase
   667           (((imp_monad_bind t, ty),
   668             (map o pairself) imp_monad_bind pats),
   669               imp_monad_bind t0);
   670 
   671   in (Graph.map o K o map_terms_stmt) imp_monad_bind end;
   672 
   673 in
   674 
   675 Code_Target.extend_target ("SML_imp", ("SML", imp_program))
   676 #> Code_Target.extend_target ("OCaml_imp", ("OCaml", imp_program))
   677 #> Code_Target.extend_target ("Scala_imp", ("Scala", imp_program))
   678 
   679 end
   680 
   681 *}
   682 
   683 hide_const (open) Heap heap guard raise' fold_map
   684 
   685 end