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