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