
haftmann@37787: (*  Title:      HOL/Imperative_HOL/Heap_Monad.thy
haftmann@26170:     Author:     John Matthews, Galois Connections; Alexander Krauss, Lukas Bulwahn & Florian Haftmann, TU Muenchen
haftmann@26170: *)
haftmann@26170: 
haftmann@37771: header {* A monad with a polymorphic heap and primitive reasoning infrastructure *}
haftmann@26170: 
haftmann@26170: theory Heap_Monad
wenzelm@41413: imports
wenzelm@41413:   Heap
wenzelm@41413:   "~~/src/HOL/Library/Monad_Syntax"
haftmann@26170: begin
haftmann@26170: 
haftmann@26170: subsection {* The monad *}
haftmann@26170: 
haftmann@37758: subsubsection {* Monad construction *}
haftmann@26170: 
haftmann@26170: text {* Monadic heap actions either produce values
haftmann@26170:   and transform the heap, or fail *}
haftmann@37709: datatype 'a Heap = Heap "heap \<Rightarrow> ('a \<times> heap) option"
haftmann@26170: 
haftmann@40266: lemma [code, code del]:
haftmann@40266:   "(Code_Evaluation.term_of :: 'a::typerep Heap \<Rightarrow> Code_Evaluation.term) = Code_Evaluation.term_of"
haftmann@40266:   ..
haftmann@40266: 
haftmann@37709: primrec execute :: "'a Heap \<Rightarrow> heap \<Rightarrow> ('a \<times> heap) option" where
haftmann@37709:   [code del]: "execute (Heap f) = f"
haftmann@26170: 
haftmann@37758: lemma Heap_cases [case_names succeed fail]:
haftmann@37758:   fixes f and h
haftmann@37758:   assumes succeed: "\<And>x h'. execute f h = Some (x, h') \<Longrightarrow> P"
haftmann@37758:   assumes fail: "execute f h = None \<Longrightarrow> P"
haftmann@37758:   shows P
haftmann@37758:   using assms by (cases "execute f h") auto
haftmann@37758: 
haftmann@26170: lemma Heap_execute [simp]:
haftmann@26170:   "Heap (execute f) = f" by (cases f) simp_all
haftmann@26170: 
haftmann@26170: lemma Heap_eqI:
haftmann@26170:   "(\<And>h. execute f h = execute g h) \<Longrightarrow> f = g"
nipkow@39302:     by (cases f, cases g) (auto simp: fun_eq_iff)
haftmann@26170: 
wenzelm@45294: ML {* structure Execute_Simps = Named_Thms
wenzelm@45294: (
wenzelm@45294:   val name = @{binding execute_simps}
haftmann@37758:   val description = "simplification rules for execute"
haftmann@37758: ) *}
haftmann@37758: 
haftmann@37758: setup Execute_Simps.setup
haftmann@37758: 
haftmann@37787: lemma execute_Let [execute_simps]:
haftmann@37758:   "execute (let x = t in f x) = (let x = t in execute (f x))"
haftmann@37758:   by (simp add: Let_def)
haftmann@37758: 
haftmann@37758: 
haftmann@37758: subsubsection {* Specialised lifters *}
haftmann@37758: 
haftmann@37758: definition tap :: "(heap \<Rightarrow> 'a) \<Rightarrow> 'a Heap" where
haftmann@37758:   [code del]: "tap f = Heap (\<lambda>h. Some (f h, h))"
haftmann@37758: 
haftmann@37787: lemma execute_tap [execute_simps]:
haftmann@37758:   "execute (tap f) h = Some (f h, h)"
haftmann@37758:   by (simp add: tap_def)
haftmann@26170: 
haftmann@37709: definition heap :: "(heap \<Rightarrow> 'a \<times> heap) \<Rightarrow> 'a Heap" where
haftmann@37709:   [code del]: "heap f = Heap (Some \<circ> f)"
haftmann@26170: 
haftmann@37787: lemma execute_heap [execute_simps]:
haftmann@37709:   "execute (heap f) = Some \<circ> f"
haftmann@26170:   by (simp add: heap_def)
haftmann@26170: 
haftmann@37754: definition guard :: "(heap \<Rightarrow> bool) \<Rightarrow> (heap \<Rightarrow> 'a \<times> heap) \<Rightarrow> 'a Heap" where
haftmann@37754:   [code del]: "guard P f = Heap (\<lambda>h. if P h then Some (f h) else None)"
haftmann@37754: 
haftmann@37758: lemma execute_guard [execute_simps]:
haftmann@37754:   "\<not> P h \<Longrightarrow> execute (guard P f) h = None"
haftmann@37754:   "P h \<Longrightarrow> execute (guard P f) h = Some (f h)"
haftmann@37754:   by (simp_all add: guard_def)
haftmann@37754: 
haftmann@37758: 
haftmann@37758: subsubsection {* Predicate classifying successful computations *}
haftmann@37758: 
haftmann@37758: definition success :: "'a Heap \<Rightarrow> heap \<Rightarrow> bool" where
haftmann@37758:   "success f h \<longleftrightarrow> execute f h \<noteq> None"
haftmann@37758: 
haftmann@37758: lemma successI:
haftmann@37758:   "execute f h \<noteq> None \<Longrightarrow> success f h"
haftmann@37758:   by (simp add: success_def)
haftmann@37758: 
haftmann@37758: lemma successE:
haftmann@37758:   assumes "success f h"
haftmann@37771:   obtains r h' where "r = fst (the (execute c h))"
haftmann@37771:     and "h' = snd (the (execute c h))"
haftmann@37771:     and "execute f h \<noteq> None"
haftmann@37771:   using assms by (simp add: success_def)
haftmann@37758: 
wenzelm@45294: ML {* structure Success_Intros = Named_Thms
wenzelm@45294: (
wenzelm@45294:   val name = @{binding success_intros}
haftmann@37758:   val description = "introduction rules for success"
haftmann@37758: ) *}
haftmann@37758: 
haftmann@37758: setup Success_Intros.setup
haftmann@37758: 
haftmann@37787: lemma success_tapI [success_intros]:
haftmann@37758:   "success (tap f) h"
haftmann@37787:   by (rule successI) (simp add: execute_simps)
haftmann@37758: 
haftmann@37787: lemma success_heapI [success_intros]:
haftmann@37758:   "success (heap f) h"
haftmann@37787:   by (rule successI) (simp add: execute_simps)
haftmann@37758: 
haftmann@37758: lemma success_guardI [success_intros]:
haftmann@37758:   "P h \<Longrightarrow> success (guard P f) h"
haftmann@37758:   by (rule successI) (simp add: execute_guard)
haftmann@37758: 
haftmann@37758: lemma success_LetI [success_intros]:
haftmann@37758:   "x = t \<Longrightarrow> success (f x) h \<Longrightarrow> success (let x = t in f x) h"
haftmann@37758:   by (simp add: Let_def)
haftmann@37758: 
haftmann@37771: lemma success_ifI:
haftmann@37771:   "(c \<Longrightarrow> success t h) \<Longrightarrow> (\<not> c \<Longrightarrow> success e h) \<Longrightarrow>
haftmann@37771:     success (if c then t else e) h"
haftmann@37771:   by (simp add: success_def)
haftmann@37771: 
haftmann@37771: 
haftmann@37771: subsubsection {* Predicate for a simple relational calculus *}
haftmann@37771: 
haftmann@37771: text {*
haftmann@40671:   The @{text effect} predicate states that when a computation @{text c}
haftmann@37771:   runs with the heap @{text h} will result in return value @{text r}
haftmann@37771:   and a heap @{text "h'"}, i.e.~no exception occurs.
haftmann@37771: *}  
haftmann@37771: 
haftmann@40671: definition effect :: "'a Heap \<Rightarrow> heap \<Rightarrow> heap \<Rightarrow> 'a \<Rightarrow> bool" where
haftmann@40671:   effect_def: "effect c h h' r \<longleftrightarrow> execute c h = Some (r, h')"
haftmann@37771: 
haftmann@40671: lemma effectI:
haftmann@40671:   "execute c h = Some (r, h') \<Longrightarrow> effect c h h' r"
haftmann@40671:   by (simp add: effect_def)
haftmann@37771: 
haftmann@40671: lemma effectE:
haftmann@40671:   assumes "effect c h h' r"
haftmann@37771:   obtains "r = fst (the (execute c h))"
haftmann@37771:     and "h' = snd (the (execute c h))"
haftmann@37771:     and "success c h"
haftmann@37771: proof (rule that)
haftmann@40671:   from assms have *: "execute c h = Some (r, h')" by (simp add: effect_def)
haftmann@37771:   then show "success c h" by (simp add: success_def)
haftmann@37771:   from * have "fst (the (execute c h)) = r" and "snd (the (execute c h)) = h'"
haftmann@37771:     by simp_all
haftmann@37771:   then show "r = fst (the (execute c h))"
haftmann@37771:     and "h' = snd (the (execute c h))" by simp_all
haftmann@37771: qed
haftmann@37771: 
haftmann@40671: lemma effect_success:
haftmann@40671:   "effect c h h' r \<Longrightarrow> success c h"
haftmann@40671:   by (simp add: effect_def success_def)
haftmann@37771: 
haftmann@40671: lemma success_effectE:
haftmann@37771:   assumes "success c h"
haftmann@40671:   obtains r h' where "effect c h h' r"
haftmann@40671:   using assms by (auto simp add: effect_def success_def)
haftmann@37771: 
haftmann@40671: lemma effect_deterministic:
haftmann@40671:   assumes "effect f h h' a"
haftmann@40671:     and "effect f h h'' b"
haftmann@37771:   shows "a = b" and "h' = h''"
haftmann@40671:   using assms unfolding effect_def by auto
haftmann@37771: 
haftmann@46029: ML {* structure Effect_Intros = Named_Thms
wenzelm@45294: (
wenzelm@45294:   val name = @{binding effect_intros}
haftmann@40671:   val description = "introduction rules for effect"
haftmann@37771: ) *}
haftmann@37771: 
haftmann@46029: ML {* structure Effect_Elims = Named_Thms
wenzelm@45294: (
wenzelm@45294:   val name = @{binding effect_elims}
haftmann@40671:   val description = "elimination rules for effect"
haftmann@37771: ) *}
haftmann@37771: 
haftmann@46029: setup "Effect_Intros.setup #> Effect_Elims.setup"
haftmann@37771: 
haftmann@40671: lemma effect_LetI [effect_intros]:
haftmann@40671:   assumes "x = t" "effect (f x) h h' r"
haftmann@40671:   shows "effect (let x = t in f x) h h' r"
haftmann@37771:   using assms by simp
haftmann@37771: 
haftmann@40671: lemma effect_LetE [effect_elims]:
haftmann@40671:   assumes "effect (let x = t in f x) h h' r"
haftmann@40671:   obtains "effect (f t) h h' r"
haftmann@37771:   using assms by simp
haftmann@37771: 
haftmann@40671: lemma effect_ifI:
haftmann@40671:   assumes "c \<Longrightarrow> effect t h h' r"
haftmann@40671:     and "\<not> c \<Longrightarrow> effect e h h' r"
haftmann@40671:   shows "effect (if c then t else e) h h' r"
haftmann@37771:   by (cases c) (simp_all add: assms)
haftmann@37771: 
haftmann@40671: lemma effect_ifE:
haftmann@40671:   assumes "effect (if c then t else e) h h' r"
haftmann@40671:   obtains "c" "effect t h h' r"
haftmann@40671:     | "\<not> c" "effect e h h' r"
haftmann@37771:   using assms by (cases c) simp_all
haftmann@37771: 
haftmann@40671: lemma effect_tapI [effect_intros]:
haftmann@37771:   assumes "h' = h" "r = f h"
haftmann@40671:   shows "effect (tap f) h h' r"
haftmann@40671:   by (rule effectI) (simp add: assms execute_simps)
haftmann@37771: 
haftmann@40671: lemma effect_tapE [effect_elims]:
haftmann@40671:   assumes "effect (tap f) h h' r"
haftmann@37771:   obtains "h' = h" and "r = f h"
haftmann@40671:   using assms by (rule effectE) (auto simp add: execute_simps)
haftmann@37771: 
haftmann@40671: lemma effect_heapI [effect_intros]:
haftmann@37771:   assumes "h' = snd (f h)" "r = fst (f h)"
haftmann@40671:   shows "effect (heap f) h h' r"
haftmann@40671:   by (rule effectI) (simp add: assms execute_simps)
haftmann@37771: 
haftmann@40671: lemma effect_heapE [effect_elims]:
haftmann@40671:   assumes "effect (heap f) h h' r"
haftmann@37771:   obtains "h' = snd (f h)" and "r = fst (f h)"
haftmann@40671:   using assms by (rule effectE) (simp add: execute_simps)
haftmann@37771: 
haftmann@40671: lemma effect_guardI [effect_intros]:
haftmann@37771:   assumes "P h" "h' = snd (f h)" "r = fst (f h)"
haftmann@40671:   shows "effect (guard P f) h h' r"
haftmann@40671:   by (rule effectI) (simp add: assms execute_simps)
haftmann@37771: 
haftmann@40671: lemma effect_guardE [effect_elims]:
haftmann@40671:   assumes "effect (guard P f) h h' r"
haftmann@37771:   obtains "h' = snd (f h)" "r = fst (f h)" "P h"
haftmann@40671:   using assms by (rule effectE)
haftmann@37771:     (auto simp add: execute_simps elim!: successE, cases "P h", auto simp add: execute_simps)
haftmann@37771: 
haftmann@37758: 
haftmann@37758: subsubsection {* Monad combinators *}
haftmann@26170: 
haftmann@37709: definition return :: "'a \<Rightarrow> 'a Heap" where
haftmann@26170:   [code del]: "return x = heap (Pair x)"
haftmann@26170: 
haftmann@37787: lemma execute_return [execute_simps]:
haftmann@37709:   "execute (return x) = Some \<circ> Pair x"
haftmann@37787:   by (simp add: return_def execute_simps)
haftmann@26170: 
haftmann@37787: lemma success_returnI [success_intros]:
haftmann@37758:   "success (return x) h"
haftmann@37787:   by (rule successI) (simp add: execute_simps)
haftmann@37758: 
haftmann@40671: lemma effect_returnI [effect_intros]:
haftmann@40671:   "h = h' \<Longrightarrow> effect (return x) h h' x"
haftmann@40671:   by (rule effectI) (simp add: execute_simps)
haftmann@37771: 
haftmann@40671: lemma effect_returnE [effect_elims]:
haftmann@40671:   assumes "effect (return x) h h' r"
haftmann@37771:   obtains "r = x" "h' = h"
haftmann@40671:   using assms by (rule effectE) (simp add: execute_simps)
haftmann@37771: 
haftmann@37709: definition raise :: "string \<Rightarrow> 'a Heap" where -- {* the string is just decoration *}
haftmann@37709:   [code del]: "raise s = Heap (\<lambda>_. None)"
haftmann@26170: 
haftmann@37787: lemma execute_raise [execute_simps]:
haftmann@37709:   "execute (raise s) = (\<lambda>_. None)"
haftmann@26170:   by (simp add: raise_def)
haftmann@26170: 
haftmann@40671: lemma effect_raiseE [effect_elims]:
haftmann@40671:   assumes "effect (raise x) h h' r"
haftmann@37771:   obtains "False"
haftmann@40671:   using assms by (rule effectE) (simp add: success_def execute_simps)
haftmann@37771: 
krauss@37792: definition bind :: "'a Heap \<Rightarrow> ('a \<Rightarrow> 'b Heap) \<Rightarrow> 'b Heap" where
krauss@37792:   [code del]: "bind f g = Heap (\<lambda>h. case execute f h of
haftmann@37709:                   Some (x, h') \<Rightarrow> execute (g x) h'
haftmann@37709:                 | None \<Rightarrow> None)"
haftmann@37709: 
wenzelm@52622: adhoc_overloading
wenzelm@52622:   Monad_Syntax.bind Heap_Monad.bind
krauss@37792: 
haftmann@37758: lemma execute_bind [execute_simps]:
haftmann@37709:   "execute f h = Some (x, h') \<Longrightarrow> execute (f \<guillemotright>= g) h = execute (g x) h'"
haftmann@37709:   "execute f h = None \<Longrightarrow> execute (f \<guillemotright>= g) h = None"
haftmann@37756:   by (simp_all add: bind_def)
haftmann@37709: 
haftmann@38409: lemma execute_bind_case:
haftmann@38409:   "execute (f \<guillemotright>= g) h = (case (execute f h) of
haftmann@38409:     Some (x, h') \<Rightarrow> execute (g x) h' | None \<Rightarrow> None)"
haftmann@38409:   by (simp add: bind_def)
haftmann@38409: 
haftmann@37771: lemma execute_bind_success:
haftmann@37771:   "success f h \<Longrightarrow> execute (f \<guillemotright>= g) h = execute (g (fst (the (execute f h)))) (snd (the (execute f h)))"
haftmann@37771:   by (cases f h rule: Heap_cases) (auto elim!: successE simp add: bind_def)
haftmann@37771: 
haftmann@37771: lemma success_bind_executeI:
haftmann@37771:   "execute f h = Some (x, h') \<Longrightarrow> success (g x) h' \<Longrightarrow> success (f \<guillemotright>= g) h"
haftmann@37758:   by (auto intro!: successI elim!: successE simp add: bind_def)
haftmann@37758: 
haftmann@40671: lemma success_bind_effectI [success_intros]:
haftmann@40671:   "effect f h h' x \<Longrightarrow> success (g x) h' \<Longrightarrow> success (f \<guillemotright>= g) h"
haftmann@40671:   by (auto simp add: effect_def success_def bind_def)
haftmann@37771: 
haftmann@40671: lemma effect_bindI [effect_intros]:
haftmann@40671:   assumes "effect f h h' r" "effect (g r) h' h'' r'"
haftmann@40671:   shows "effect (f \<guillemotright>= g) h h'' r'"
haftmann@37771:   using assms
haftmann@40671:   apply (auto intro!: effectI elim!: effectE successE)
haftmann@37771:   apply (subst execute_bind, simp_all)
haftmann@37771:   done
haftmann@37771: 
haftmann@40671: lemma effect_bindE [effect_elims]:
haftmann@40671:   assumes "effect (f \<guillemotright>= g) h h'' r'"
haftmann@40671:   obtains h' r where "effect f h h' r" "effect (g r) h' h'' r'"
haftmann@40671:   using assms by (auto simp add: effect_def bind_def split: option.split_asm)
haftmann@37771: 
haftmann@37771: lemma execute_bind_eq_SomeI:
haftmann@37878:   assumes "execute f h = Some (x, h')"
haftmann@37878:     and "execute (g x) h' = Some (y, h'')"
haftmann@37878:   shows "execute (f \<guillemotright>= g) h = Some (y, h'')"
haftmann@37756:   using assms by (simp add: bind_def)
haftmann@37754: 
haftmann@37709: lemma return_bind [simp]: "return x \<guillemotright>= f = f x"
krauss@51485:   by (rule Heap_eqI) (simp add: execute_simps)
haftmann@37709: 
haftmann@37709: lemma bind_return [simp]: "f \<guillemotright>= return = f"
haftmann@37787:   by (rule Heap_eqI) (simp add: bind_def execute_simps split: option.splits)
haftmann@37709: 
haftmann@37828: lemma bind_bind [simp]: "(f \<guillemotright>= g) \<guillemotright>= k = (f :: 'a Heap) \<guillemotright>= (\<lambda>x. g x \<guillemotright>= k)"
haftmann@37787:   by (rule Heap_eqI) (simp add: bind_def execute_simps split: option.splits)
haftmann@37709: 
haftmann@37709: lemma raise_bind [simp]: "raise e \<guillemotright>= f = raise e"
haftmann@37787:   by (rule Heap_eqI) (simp add: execute_simps)
haftmann@37709: 
haftmann@26170: 
haftmann@37758: subsection {* Generic combinators *}
haftmann@26170: 
haftmann@37758: subsubsection {* Assertions *}
haftmann@26170: 
haftmann@37709: definition assert :: "('a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a Heap" where
haftmann@37709:   "assert P x = (if P x then return x else raise ''assert'')"
haftmann@28742: 
haftmann@37758: lemma execute_assert [execute_simps]:
haftmann@37754:   "P x \<Longrightarrow> execute (assert P x) h = Some (x, h)"
haftmann@37754:   "\<not> P x \<Longrightarrow> execute (assert P x) h = None"
haftmann@37787:   by (simp_all add: assert_def execute_simps)
haftmann@37754: 
haftmann@37758: lemma success_assertI [success_intros]:
haftmann@37758:   "P x \<Longrightarrow> success (assert P x) h"
haftmann@37758:   by (rule successI) (simp add: execute_assert)
haftmann@37758: 
haftmann@40671: lemma effect_assertI [effect_intros]:
haftmann@40671:   "P x \<Longrightarrow> h' = h \<Longrightarrow> r = x \<Longrightarrow> effect (assert P x) h h' r"
haftmann@40671:   by (rule effectI) (simp add: execute_assert)
haftmann@37771:  
haftmann@40671: lemma effect_assertE [effect_elims]:
haftmann@40671:   assumes "effect (assert P x) h h' r"
haftmann@37771:   obtains "P x" "r = x" "h' = h"
haftmann@40671:   using assms by (rule effectE) (cases "P x", simp_all add: execute_assert success_def)
haftmann@37771: 
haftmann@28742: lemma assert_cong [fundef_cong]:
haftmann@28742:   assumes "P = P'"
haftmann@28742:   assumes "\<And>x. P' x \<Longrightarrow> f x = f' x"
haftmann@28742:   shows "(assert P x >>= f) = (assert P' x >>= f')"
haftmann@37754:   by (rule Heap_eqI) (insert assms, simp add: assert_def)
haftmann@28742: 
haftmann@37758: 
haftmann@37758: subsubsection {* Plain lifting *}
haftmann@37758: 
haftmann@37754: definition lift :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b Heap" where
haftmann@37754:   "lift f = return o f"
haftmann@37709: 
haftmann@37754: lemma lift_collapse [simp]:
haftmann@37754:   "lift f x = return (f x)"
haftmann@37754:   by (simp add: lift_def)
haftmann@37709: 
haftmann@37754: lemma bind_lift:
haftmann@37754:   "(f \<guillemotright>= lift g) = (f \<guillemotright>= (\<lambda>x. return (g x)))"
haftmann@37754:   by (simp add: lift_def comp_def)
haftmann@37709: 
haftmann@37758: 
haftmann@37758: subsubsection {* Iteration -- warning: this is rarely useful! *}
haftmann@37758: 
haftmann@37756: primrec fold_map :: "('a \<Rightarrow> 'b Heap) \<Rightarrow> 'a list \<Rightarrow> 'b list Heap" where
haftmann@37756:   "fold_map f [] = return []"
krauss@37792: | "fold_map f (x # xs) = do {
haftmann@37709:      y \<leftarrow> f x;
haftmann@37756:      ys \<leftarrow> fold_map f xs;
haftmann@37709:      return (y # ys)
krauss@37792:    }"
haftmann@37709: 
haftmann@37756: lemma fold_map_append:
haftmann@37756:   "fold_map f (xs @ ys) = fold_map f xs \<guillemotright>= (\<lambda>xs. fold_map f ys \<guillemotright>= (\<lambda>ys. return (xs @ ys)))"
haftmann@37754:   by (induct xs) simp_all
haftmann@37754: 
haftmann@37758: lemma execute_fold_map_unchanged_heap [execute_simps]:
haftmann@37754:   assumes "\<And>x. x \<in> set xs \<Longrightarrow> \<exists>y. execute (f x) h = Some (y, h)"
haftmann@37756:   shows "execute (fold_map f xs) h =
haftmann@37754:     Some (List.map (\<lambda>x. fst (the (execute (f x) h))) xs, h)"
haftmann@37754: using assms proof (induct xs)
haftmann@37787:   case Nil show ?case by (simp add: execute_simps)
haftmann@37754: next
haftmann@37754:   case (Cons x xs)
haftmann@37754:   from Cons.prems obtain y
haftmann@37754:     where y: "execute (f x) h = Some (y, h)" by auto
haftmann@37756:   moreover from Cons.prems Cons.hyps have "execute (fold_map f xs) h =
haftmann@37754:     Some (map (\<lambda>x. fst (the (execute (f x) h))) xs, h)" by auto
haftmann@37787:   ultimately show ?case by (simp, simp only: execute_bind(1), simp add: execute_simps)
haftmann@37754: qed
haftmann@37754: 
haftmann@40267: 
haftmann@40267: subsection {* Partial function definition setup *}
haftmann@40267: 
haftmann@40267: definition Heap_ord :: "'a Heap \<Rightarrow> 'a Heap \<Rightarrow> bool" where
haftmann@40267:   "Heap_ord = img_ord execute (fun_ord option_ord)"
haftmann@40267: 
huffman@44174: definition Heap_lub :: "'a Heap set \<Rightarrow> 'a Heap" where
haftmann@40267:   "Heap_lub = img_lub execute Heap (fun_lub (flat_lub None))"
haftmann@40267: 
Andreas@54630: lemma Heap_lub_empty: "Heap_lub {} = Heap Map.empty"
Andreas@54630: by(simp add: Heap_lub_def img_lub_def fun_lub_def flat_lub_def)
Andreas@54630: 
krauss@51485: lemma heap_interpretation: "partial_function_definitions Heap_ord Heap_lub"
haftmann@40267: proof -
haftmann@40267:   have "partial_function_definitions (fun_ord option_ord) (fun_lub (flat_lub None))"
haftmann@40267:     by (rule partial_function_lift) (rule flat_interpretation)
haftmann@40267:   then have "partial_function_definitions (img_ord execute (fun_ord option_ord))
haftmann@40267:       (img_lub execute Heap (fun_lub (flat_lub None)))"
haftmann@40267:     by (rule partial_function_image) (auto intro: Heap_eqI)
haftmann@40267:   then show "partial_function_definitions Heap_ord Heap_lub"
haftmann@40267:     by (simp only: Heap_ord_def Heap_lub_def)
haftmann@40267: qed
haftmann@40267: 
krauss@51485: interpretation heap!: partial_function_definitions Heap_ord Heap_lub
Andreas@54630:   where "Heap_lub {} \<equiv> Heap Map.empty"
Andreas@54630: by (fact heap_interpretation)(simp add: Heap_lub_empty)
krauss@51485: 
krauss@51485: lemma heap_step_admissible: 
krauss@51485:   "option.admissible
krauss@51485:       (\<lambda>f:: 'a => ('b * 'c) option. \<forall>h h' r. f h = Some (r, h') \<longrightarrow> P x h h' r)"
Andreas@53361: proof (rule ccpo.admissibleI)
krauss@51485:   fix A :: "('a \<Rightarrow> ('b * 'c) option) set"
krauss@51485:   assume ch: "Complete_Partial_Order.chain option.le_fun A"
krauss@51485:     and IH: "\<forall>f\<in>A. \<forall>h h' r. f h = Some (r, h') \<longrightarrow> P x h h' r"
krauss@51485:   from ch have ch': "\<And>x. Complete_Partial_Order.chain option_ord {y. \<exists>f\<in>A. y = f x}" by (rule chain_fun)
krauss@51485:   show "\<forall>h h' r. option.lub_fun A h = Some (r, h') \<longrightarrow> P x h h' r"
krauss@51485:   proof (intro allI impI)
krauss@51485:     fix h h' r assume "option.lub_fun A h = Some (r, h')"
krauss@51485:     from flat_lub_in_chain[OF ch' this[unfolded fun_lub_def]]
krauss@51485:     have "Some (r, h') \<in> {y. \<exists>f\<in>A. y = f h}" by simp
krauss@51485:     then have "\<exists>f\<in>A. f h = Some (r, h')" by auto
krauss@51485:     with IH show "P x h h' r" by auto
krauss@51485:   qed
krauss@51485: qed
krauss@51485: 
krauss@51485: lemma admissible_heap: 
krauss@51485:   "heap.admissible (\<lambda>f. \<forall>x h h' r. effect (f x) h h' r \<longrightarrow> P x h h' r)"
krauss@51485: proof (rule admissible_fun[OF heap_interpretation])
krauss@51485:   fix x
krauss@51485:   show "ccpo.admissible Heap_lub Heap_ord (\<lambda>a. \<forall>h h' r. effect a h h' r \<longrightarrow> P x h h' r)"
krauss@51485:     unfolding Heap_ord_def Heap_lub_def
krauss@51485:   proof (intro admissible_image partial_function_lift flat_interpretation)
krauss@51485:     show "option.admissible ((\<lambda>a. \<forall>h h' r. effect a h h' r \<longrightarrow> P x h h' r) \<circ> Heap)"
krauss@51485:       unfolding comp_def effect_def execute.simps
krauss@51485:       by (rule heap_step_admissible)
krauss@51485:   qed (auto simp add: Heap_eqI)
krauss@51485: qed
krauss@51485: 
krauss@51485: lemma fixp_induct_heap:
krauss@51485:   fixes F :: "'c \<Rightarrow> 'c" and
krauss@51485:     U :: "'c \<Rightarrow> 'b \<Rightarrow> 'a Heap" and
krauss@51485:     C :: "('b \<Rightarrow> 'a Heap) \<Rightarrow> 'c" and
krauss@51485:     P :: "'b \<Rightarrow> heap \<Rightarrow> heap \<Rightarrow> 'a \<Rightarrow> bool"
krauss@51485:   assumes mono: "\<And>x. monotone (fun_ord Heap_ord) Heap_ord (\<lambda>f. U (F (C f)) x)"
krauss@51485:   assumes eq: "f \<equiv> C (ccpo.fixp (fun_lub Heap_lub) (fun_ord Heap_ord) (\<lambda>f. U (F (C f))))"
krauss@51485:   assumes inverse2: "\<And>f. U (C f) = f"
krauss@51485:   assumes step: "\<And>f x h h' r. (\<And>x h h' r. effect (U f x) h h' r \<Longrightarrow> P x h h' r) 
krauss@51485:     \<Longrightarrow> effect (U (F f) x) h h' r \<Longrightarrow> P x h h' r"
krauss@51485:   assumes defined: "effect (U f x) h h' r"
krauss@51485:   shows "P x h h' r"
krauss@51485:   using step defined heap.fixp_induct_uc[of U F C, OF mono eq inverse2 admissible_heap, of P]
Andreas@54630:   unfolding effect_def execute.simps
krauss@51485:   by blast
krauss@51485: 
krauss@42949: declaration {* Partial_Function.init "heap" @{term heap.fixp_fun}
krauss@52728:   @{term heap.mono_body} @{thm heap.fixp_rule_uc} @{thm heap.fixp_induct_uc}
krauss@52728:   (SOME @{thm fixp_induct_heap}) *}
krauss@42949: 
krauss@42949: 
haftmann@40267: abbreviation "mono_Heap \<equiv> monotone (fun_ord Heap_ord) Heap_ord"
haftmann@40267: 
haftmann@40267: lemma Heap_ordI:
haftmann@40267:   assumes "\<And>h. execute x h = None \<or> execute x h = execute y h"
haftmann@40267:   shows "Heap_ord x y"
haftmann@40267:   using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def
haftmann@40267:   by blast
haftmann@40267: 
haftmann@40267: lemma Heap_ordE:
haftmann@40267:   assumes "Heap_ord x y"
haftmann@40267:   obtains "execute x h = None" | "execute x h = execute y h"
haftmann@40267:   using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def
haftmann@40267:   by atomize_elim blast
haftmann@40267: 
haftmann@46029: lemma bind_mono [partial_function_mono]:
haftmann@40267:   assumes mf: "mono_Heap B" and mg: "\<And>y. mono_Heap (\<lambda>f. C y f)"
haftmann@40267:   shows "mono_Heap (\<lambda>f. B f \<guillemotright>= (\<lambda>y. C y f))"
haftmann@40267: proof (rule monotoneI)
haftmann@40267:   fix f g :: "'a \<Rightarrow> 'b Heap" assume fg: "fun_ord Heap_ord f g"
haftmann@40267:   from mf
haftmann@40267:   have 1: "Heap_ord (B f) (B g)" by (rule monotoneD) (rule fg)
haftmann@40267:   from mg
haftmann@40267:   have 2: "\<And>y'. Heap_ord (C y' f) (C y' g)" by (rule monotoneD) (rule fg)
haftmann@40267: 
haftmann@40267:   have "Heap_ord (B f \<guillemotright>= (\<lambda>y. C y f)) (B g \<guillemotright>= (\<lambda>y. C y f))"
haftmann@40267:     (is "Heap_ord ?L ?R")
haftmann@40267:   proof (rule Heap_ordI)
haftmann@40267:     fix h
haftmann@40267:     from 1 show "execute ?L h = None \<or> execute ?L h = execute ?R h"
haftmann@40267:       by (rule Heap_ordE[where h = h]) (auto simp: execute_bind_case)
haftmann@40267:   qed
haftmann@40267:   also
haftmann@40267:   have "Heap_ord (B g \<guillemotright>= (\<lambda>y'. C y' f)) (B g \<guillemotright>= (\<lambda>y'. C y' g))"
haftmann@40267:     (is "Heap_ord ?L ?R")
haftmann@40267:   proof (rule Heap_ordI)
haftmann@40267:     fix h
haftmann@40267:     show "execute ?L h = None \<or> execute ?L h = execute ?R h"
haftmann@40267:     proof (cases "execute (B g) h")
haftmann@40267:       case None
haftmann@40267:       then have "execute ?L h = None" by (auto simp: execute_bind_case)
haftmann@40267:       thus ?thesis ..
haftmann@40267:     next
haftmann@40267:       case Some
haftmann@40267:       then obtain r h' where "execute (B g) h = Some (r, h')"
haftmann@40267:         by (metis surjective_pairing)
haftmann@40267:       then have "execute ?L h = execute (C r f) h'"
haftmann@40267:         "execute ?R h = execute (C r g) h'"
haftmann@40267:         by (auto simp: execute_bind_case)
haftmann@40267:       with 2[of r] show ?thesis by (auto elim: Heap_ordE)
haftmann@40267:     qed
haftmann@40267:   qed
haftmann@40267:   finally (heap.leq_trans)
haftmann@40267:   show "Heap_ord (B f \<guillemotright>= (\<lambda>y. C y f)) (B g \<guillemotright>= (\<lambda>y'. C y' g))" .
haftmann@40267: qed
haftmann@40267: 
haftmann@40267: 
haftmann@26182: subsection {* Code generator setup *}
haftmann@26182: 
haftmann@26182: subsubsection {* Logical intermediate layer *}
haftmann@26182: 
bulwahn@39250: definition raise' :: "String.literal \<Rightarrow> 'a Heap" where
bulwahn@39250:   [code del]: "raise' s = raise (explode s)"
bulwahn@39250: 
haftmann@46029: lemma [code_abbrev]: "raise' (STR s) = raise s"
haftmann@46029:   unfolding raise'_def by (simp add: STR_inverse)
haftmann@26182: 
haftmann@46029: lemma raise_raise': (* FIXME delete candidate *)
haftmann@37709:   "raise s = raise' (STR s)"
bulwahn@39250:   unfolding raise'_def by (simp add: STR_inverse)
haftmann@26182: 
haftmann@37709: code_datatype raise' -- {* avoid @{const "Heap"} formally *}
haftmann@26182: 
haftmann@26182: 
haftmann@27707: subsubsection {* SML and OCaml *}
haftmann@26182: 
haftmann@52435: code_printing type_constructor Heap \<rightharpoonup> (SML) "(unit/ ->/ _)"
haftmann@52435: code_printing constant bind \<rightharpoonup> (SML) "!(fn/ f'_/ =>/ fn/ ()/ =>/ f'_/ (_/ ())/ ())"
haftmann@52435: code_printing constant return \<rightharpoonup> (SML) "!(fn/ ()/ =>/ _)"
haftmann@52435: code_printing constant Heap_Monad.raise' \<rightharpoonup> (SML) "!(raise/ Fail/ _)"
haftmann@26182: 
haftmann@52435: code_printing type_constructor Heap \<rightharpoonup> (OCaml) "(unit/ ->/ _)"
haftmann@52435: code_printing constant bind \<rightharpoonup> (OCaml) "!(fun/ f'_/ ()/ ->/ f'_/ (_/ ())/ ())"
haftmann@52435: code_printing constant return \<rightharpoonup> (OCaml) "!(fun/ ()/ ->/ _)"
haftmann@52435: code_printing constant Heap_Monad.raise' \<rightharpoonup> (OCaml) "failwith"
haftmann@27707: 
haftmann@37838: 
haftmann@37838: subsubsection {* Haskell *}
haftmann@37838: 
haftmann@37838: text {* Adaption layer *}
haftmann@37838: 
haftmann@37838: code_include Haskell "Heap"
haftmann@37838: {*import qualified Control.Monad;
haftmann@37838: import qualified Control.Monad.ST;
haftmann@37838: import qualified Data.STRef;
haftmann@37838: import qualified Data.Array.ST;
haftmann@37838: 
haftmann@37838: type RealWorld = Control.Monad.ST.RealWorld;
haftmann@37838: type ST s a = Control.Monad.ST.ST s a;
haftmann@37838: type STRef s a = Data.STRef.STRef s a;
haftmann@51143: type STArray s a = Data.Array.ST.STArray s Integer a;
haftmann@37838: 
haftmann@37838: newSTRef = Data.STRef.newSTRef;
haftmann@37838: readSTRef = Data.STRef.readSTRef;
haftmann@37838: writeSTRef = Data.STRef.writeSTRef;
haftmann@37838: 
haftmann@51143: newArray :: Integer -> a -> ST s (STArray s a);
haftmann@37838: newArray k = Data.Array.ST.newArray (0, k);
haftmann@37838: 
haftmann@37838: newListArray :: [a] -> ST s (STArray s a);
haftmann@37964: newListArray xs = Data.Array.ST.newListArray (0, (fromInteger . toInteger . length) xs) xs;
haftmann@37838: 
haftmann@51143: newFunArray :: Integer -> (Integer -> a) -> ST s (STArray s a);
haftmann@37838: newFunArray k f = Data.Array.ST.newListArray (0, k) (map f [0..k-1]);
haftmann@37838: 
haftmann@51143: lengthArray :: STArray s a -> ST s Integer;
haftmann@37838: lengthArray a = Control.Monad.liftM snd (Data.Array.ST.getBounds a);
haftmann@37838: 
haftmann@51143: readArray :: STArray s a -> Integer -> ST s a;
haftmann@37838: readArray = Data.Array.ST.readArray;
haftmann@37838: 
haftmann@51143: writeArray :: STArray s a -> Integer -> a -> ST s ();
haftmann@37838: writeArray = Data.Array.ST.writeArray;*}
haftmann@37838: 
haftmann@37838: code_reserved Haskell Heap
haftmann@37838: 
haftmann@37838: text {* Monad *}
haftmann@37838: 
haftmann@52435: code_printing type_constructor Heap \<rightharpoonup> (Haskell) "Heap.ST/ Heap.RealWorld/ _"
haftmann@37838: code_monad bind Haskell
haftmann@52435: code_printing constant return \<rightharpoonup> (Haskell) "return"
haftmann@52435: code_printing constant Heap_Monad.raise' \<rightharpoonup> (Haskell) "error"
haftmann@37838: 
haftmann@37838: 
haftmann@37838: subsubsection {* Scala *}
haftmann@37838: 
haftmann@37842: code_include Scala "Heap"
haftmann@38968: {*object Heap {
haftmann@38968:   def bind[A, B](f: Unit => A, g: A => Unit => B): Unit => B = (_: Unit) => g (f ()) ()
haftmann@38968: }
haftmann@37842: 
haftmann@37842: class Ref[A](x: A) {
haftmann@37842:   var value = x
haftmann@37842: }
haftmann@37842: 
haftmann@37842: object Ref {
haftmann@38771:   def apply[A](x: A): Ref[A] =
haftmann@38771:     new Ref[A](x)
haftmann@38771:   def lookup[A](r: Ref[A]): A =
haftmann@38771:     r.value
haftmann@38771:   def update[A](r: Ref[A], x: A): Unit =
haftmann@38771:     { r.value = x }
haftmann@37842: }
haftmann@37842: 
haftmann@37964: object Array {
haftmann@38968:   import collection.mutable.ArraySeq
haftmann@51143:   def alloc[A](n: BigInt)(x: A): ArraySeq[A] =
haftmann@51143:     ArraySeq.fill(n.toInt)(x)
haftmann@51143:   def make[A](n: BigInt)(f: BigInt => A): ArraySeq[A] =
haftmann@51143:     ArraySeq.tabulate(n.toInt)((k: Int) => f(BigInt(k)))
haftmann@51143:   def len[A](a: ArraySeq[A]): BigInt =
haftmann@51143:     BigInt(a.length)
haftmann@51143:   def nth[A](a: ArraySeq[A], n: BigInt): A =
haftmann@51143:     a(n.toInt)
haftmann@51143:   def upd[A](a: ArraySeq[A], n: BigInt, x: A): Unit =
haftmann@51143:     a.update(n.toInt, x)
haftmann@38771:   def freeze[A](a: ArraySeq[A]): List[A] =
haftmann@38771:     a.toList
haftmann@38968: }
haftmann@38968: *}
haftmann@37842: 
haftmann@38968: code_reserved Scala Heap Ref Array
haftmann@37838: 
haftmann@52435: code_printing type_constructor Heap \<rightharpoonup> (Scala) "(Unit/ =>/ _)"
haftmann@52435: code_printing constant bind \<rightharpoonup> (Scala) "Heap.bind"
haftmann@52435: code_printing constant return \<rightharpoonup> (Scala) "('_: Unit)/ =>/ _"
haftmann@52435: code_printing constant Heap_Monad.raise' \<rightharpoonup> (Scala) "!sys.error((_))"
haftmann@37838: 
haftmann@37838: 
haftmann@37838: subsubsection {* Target variants with less units *}
haftmann@37838: 
haftmann@31871: setup {*
haftmann@31871: 
haftmann@31871: let
haftmann@27707: 
haftmann@31871: open Code_Thingol;
haftmann@31871: 
haftmann@55147: val imp_program =
haftmann@31871:   let
haftmann@55147:     val is_bind = curry (op =) @{const_name bind};
haftmann@55147:     val is_return = curry (op =) @{const_name return};
haftmann@31893:     val dummy_name = "";
haftmann@31893:     val dummy_case_term = IVar NONE;
haftmann@31871:     (*assumption: dummy values are not relevant for serialization*)
haftmann@55147:     val unitT = @{type_name unit} `%% [];
haftmann@55147:     val unitt =
haftmann@55147:       IConst { sym = Code_Symbol.Constant @{const_name Unity}, typargs = [], dicts = [], dom = [],
haftmann@55147:         range = unitT, annotate = false };
haftmann@31871:     fun dest_abs ((v, ty) `|=> t, _) = ((v, ty), t)
haftmann@31871:       | dest_abs (t, ty) =
haftmann@31871:           let
haftmann@31871:             val vs = fold_varnames cons t [];
wenzelm@43324:             val v = singleton (Name.variant_list vs) "x";
haftmann@31871:             val ty' = (hd o fst o unfold_fun) ty;
haftmann@31893:           in ((SOME v, ty'), t `$ IVar (SOME v)) end;
haftmann@55147:     fun force (t as IConst { sym = Code_Symbol.Constant c, ... } `$ t') = if is_return c
haftmann@31871:           then t' else t `$ unitt
haftmann@31871:       | force t = t `$ unitt;
haftmann@38385:     fun tr_bind'' [(t1, _), (t2, ty2)] =
haftmann@31871:       let
haftmann@31871:         val ((v, ty), t) = dest_abs (t2, ty2);
haftmann@48072:       in ICase { term = force t1, typ = ty, clauses = [(IVar v, tr_bind' t)], primitive = dummy_case_term } end
haftmann@38385:     and tr_bind' t = case unfold_app t
haftmann@55147:      of (IConst { sym = Code_Symbol.Constant c, dom = ty1 :: ty2 :: _, ... }, [x1, x2]) => if is_bind c
haftmann@38386:           then tr_bind'' [(x1, ty1), (x2, ty2)]
haftmann@38386:           else force t
haftmann@38386:       | _ => force t;
haftmann@48072:     fun imp_monad_bind'' ts = (SOME dummy_name, unitT) `|=>
haftmann@48072:       ICase { term = IVar (SOME dummy_name), typ = unitT, clauses = [(unitt, tr_bind'' ts)], primitive = dummy_case_term }
haftmann@55147:     fun imp_monad_bind' (const as { sym = Code_Symbol.Constant c, dom = dom, ... }) ts = if is_bind c then case (ts, dom)
haftmann@31871:        of ([t1, t2], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)]
haftmann@31871:         | ([t1, t2, t3], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)] `$ t3
haftmann@31871:         | (ts, _) => imp_monad_bind (eta_expand 2 (const, ts))
haftmann@31871:       else IConst const `$$ map imp_monad_bind ts
haftmann@31871:     and imp_monad_bind (IConst const) = imp_monad_bind' const []
haftmann@31871:       | imp_monad_bind (t as IVar _) = t
haftmann@31871:       | imp_monad_bind (t as _ `$ _) = (case unfold_app t
haftmann@31871:          of (IConst const, ts) => imp_monad_bind' const ts
haftmann@31871:           | (t, ts) => imp_monad_bind t `$$ map imp_monad_bind ts)
haftmann@31871:       | imp_monad_bind (v_ty `|=> t) = v_ty `|=> imp_monad_bind t
haftmann@48072:       | imp_monad_bind (ICase { term = t, typ = ty, clauses = clauses, primitive = t0 }) =
haftmann@48072:           ICase { term = imp_monad_bind t, typ = ty,
haftmann@48072:             clauses = (map o pairself) imp_monad_bind clauses, primitive = imp_monad_bind t0 };
haftmann@28663: 
haftmann@55147:   in (Code_Symbol.Graph.map o K o map_terms_stmt) imp_monad_bind end;
haftmann@27707: 
haftmann@27707: in
haftmann@27707: 
haftmann@31871: Code_Target.extend_target ("SML_imp", ("SML", imp_program))
haftmann@31871: #> Code_Target.extend_target ("OCaml_imp", ("OCaml", imp_program))
haftmann@37838: #> Code_Target.extend_target ("Scala_imp", ("Scala", imp_program))
haftmann@27707: 
haftmann@27707: end
haftmann@31871: 
haftmann@27707: *}
haftmann@27707: 
haftmann@37758: hide_const (open) Heap heap guard raise' fold_map
haftmann@37724: 
haftmann@26170: end
haftmann@48072: 




