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