haftmann@26170: (* Title: HOL/Library/Heap_Monad.thy haftmann@26170: ID: $Id$ haftmann@26170: Author: John Matthews, Galois Connections; Alexander Krauss, Lukas Bulwahn & Florian Haftmann, TU Muenchen haftmann@26170: *) haftmann@26170: haftmann@26170: header {* A monad with a polymorphic heap *} haftmann@26170: haftmann@26170: theory Heap_Monad haftmann@26170: imports Heap haftmann@26170: begin haftmann@26170: haftmann@26170: subsection {* The monad *} haftmann@26170: haftmann@26170: subsubsection {* Monad combinators *} haftmann@26170: haftmann@26170: datatype exception = Exn haftmann@26170: haftmann@26170: text {* Monadic heap actions either produce values haftmann@26170: and transform the heap, or fail *} haftmann@26170: datatype 'a Heap = Heap "heap \ ('a + exception) \ heap" haftmann@26170: haftmann@26170: primrec haftmann@26170: execute :: "'a Heap \ heap \ ('a + exception) \ heap" where haftmann@26170: "execute (Heap f) = f" haftmann@26170: lemmas [code del] = execute.simps haftmann@26170: 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: "(\h. execute f h = execute g h) \ f = g" haftmann@26170: by (cases f, cases g) (auto simp: expand_fun_eq) haftmann@26170: haftmann@26170: lemma Heap_eqI': haftmann@26170: "(\h. (\x. execute (f x) h) = (\y. execute (g y) h)) \ f = g" haftmann@26170: by (auto simp: expand_fun_eq intro: Heap_eqI) haftmann@26170: haftmann@26170: lemma Heap_strip: "(\f. PROP P f) \ (\g. PROP P (Heap g))" haftmann@26170: proof haftmann@26170: fix g :: "heap \ ('a + exception) \ heap" haftmann@26170: assume "\f. PROP P f" haftmann@26170: then show "PROP P (Heap g)" . haftmann@26170: next haftmann@26170: fix f :: "'a Heap" haftmann@26170: assume assm: "\g. PROP P (Heap g)" haftmann@26170: then have "PROP P (Heap (execute f))" . haftmann@26170: then show "PROP P f" by simp haftmann@26170: qed haftmann@26170: haftmann@26170: definition haftmann@26170: heap :: "(heap \ 'a \ heap) \ 'a Heap" where haftmann@26170: [code del]: "heap f = Heap (\h. apfst Inl (f h))" haftmann@26170: haftmann@26170: lemma execute_heap [simp]: haftmann@26170: "execute (heap f) h = apfst Inl (f h)" haftmann@26170: by (simp add: heap_def) haftmann@26170: haftmann@26170: definition haftmann@26170: bindM :: "'a Heap \ ('a \ 'b Heap) \ 'b Heap" (infixl ">>=" 54) where haftmann@26170: [code del]: "f >>= g = Heap (\h. case execute f h of haftmann@26170: (Inl x, h') \ execute (g x) h' haftmann@26170: | r \ r)" haftmann@26170: haftmann@26170: notation haftmann@26170: bindM (infixl "\=" 54) haftmann@26170: haftmann@26170: abbreviation haftmann@26170: chainM :: "'a Heap \ 'b Heap \ 'b Heap" (infixl ">>" 54) where haftmann@26170: "f >> g \ f >>= (\_. g)" haftmann@26170: haftmann@26170: notation haftmann@26170: chainM (infixl "\" 54) haftmann@26170: haftmann@26170: definition haftmann@26170: return :: "'a \ 'a Heap" where haftmann@26170: [code del]: "return x = heap (Pair x)" haftmann@26170: haftmann@26170: lemma execute_return [simp]: haftmann@26170: "execute (return x) h = apfst Inl (x, h)" haftmann@26170: by (simp add: return_def) haftmann@26170: haftmann@26170: definition haftmann@26170: raise :: "string \ 'a Heap" where -- {* the string is just decoration *} haftmann@26170: [code del]: "raise s = Heap (Pair (Inr Exn))" haftmann@26170: haftmann@26170: notation (latex output) haftmann@26170: "raise" ("\<^raw:{\textsf{raise}}>") haftmann@26170: haftmann@26170: lemma execute_raise [simp]: haftmann@26170: "execute (raise s) h = (Inr Exn, h)" haftmann@26170: by (simp add: raise_def) haftmann@26170: haftmann@26170: haftmann@26170: subsubsection {* do-syntax *} haftmann@26170: haftmann@26170: text {* haftmann@26170: We provide a convenient do-notation for monadic expressions haftmann@26170: well-known from Haskell. @{const Let} is printed haftmann@26170: specially in do-expressions. haftmann@26170: *} haftmann@26170: haftmann@26170: nonterminals do_expr haftmann@26170: haftmann@26170: syntax haftmann@26170: "_do" :: "do_expr \ 'a" haftmann@26170: ("(do (_)//done)" [12] 100) haftmann@26170: "_bindM" :: "pttrn \ 'a \ do_expr \ do_expr" haftmann@26170: ("_ <- _;//_" [1000, 13, 12] 12) haftmann@26170: "_chainM" :: "'a \ do_expr \ do_expr" haftmann@26170: ("_;//_" [13, 12] 12) haftmann@26170: "_let" :: "pttrn \ 'a \ do_expr \ do_expr" haftmann@26170: ("let _ = _;//_" [1000, 13, 12] 12) haftmann@26170: "_nil" :: "'a \ do_expr" haftmann@26170: ("_" [12] 12) haftmann@26170: haftmann@26170: syntax (xsymbols) haftmann@26170: "_bindM" :: "pttrn \ 'a \ do_expr \ do_expr" haftmann@26170: ("_ \ _;//_" [1000, 13, 12] 12) haftmann@26170: syntax (latex output) haftmann@26170: "_do" :: "do_expr \ 'a" haftmann@26170: ("(\<^raw:{\textsf{do}}> (_))" [12] 100) haftmann@26170: "_let" :: "pttrn \ 'a \ do_expr \ do_expr" haftmann@26170: ("\<^raw:\textsf{let}> _ = _;//_" [1000, 13, 12] 12) haftmann@26170: notation (latex output) haftmann@26170: "return" ("\<^raw:{\textsf{return}}>") haftmann@26170: haftmann@26170: translations haftmann@28145: "_do f" => "f" haftmann@26170: "_bindM x f g" => "f \= (\x. g)" haftmann@26170: "_chainM f g" => "f \ g" haftmann@26170: "_let x t f" => "CONST Let t (\x. f)" haftmann@26170: "_nil f" => "f" haftmann@26170: haftmann@26170: print_translation {* haftmann@26170: let haftmann@26170: fun dest_abs_eta (Abs (abs as (_, ty, _))) = haftmann@26170: let haftmann@26170: val (v, t) = Syntax.variant_abs abs; haftmann@28145: in (Free (v, ty), t) end haftmann@26170: | dest_abs_eta t = haftmann@26170: let haftmann@26170: val (v, t) = Syntax.variant_abs ("", dummyT, t $ Bound 0); haftmann@28145: in (Free (v, dummyT), t) end; haftmann@26170: fun unfold_monad (Const (@{const_syntax bindM}, _) $ f $ g) = haftmann@26170: let haftmann@28145: val (v, g') = dest_abs_eta g; haftmann@28145: val vs = fold_aterms (fn Free (v, _) => insert (op =) v | _ => I) v []; haftmann@26170: val v_used = fold_aterms haftmann@28145: (fn Free (w, _) => (fn s => s orelse member (op =) vs w) | _ => I) g' false; haftmann@26170: in if v_used then haftmann@28145: Const ("_bindM", dummyT) $ v $ f $ unfold_monad g' haftmann@26170: else haftmann@26170: Const ("_chainM", dummyT) $ f $ unfold_monad g' haftmann@26170: end haftmann@26170: | unfold_monad (Const (@{const_syntax chainM}, _) $ f $ g) = haftmann@26170: Const ("_chainM", dummyT) $ f $ unfold_monad g haftmann@26170: | unfold_monad (Const (@{const_syntax Let}, _) $ f $ g) = haftmann@26170: let haftmann@28145: val (v, g') = dest_abs_eta g; haftmann@28145: in Const ("_let", dummyT) $ v $ f $ unfold_monad g' end haftmann@26170: | unfold_monad (Const (@{const_syntax Pair}, _) $ f) = haftmann@28145: Const (@{const_syntax return}, dummyT) $ f haftmann@26170: | unfold_monad f = f; haftmann@28145: fun contains_bindM (Const (@{const_syntax bindM}, _) $ _ $ _) = true haftmann@28145: | contains_bindM (Const (@{const_syntax Let}, _) $ _ $ Abs (_, _, t)) = haftmann@28145: contains_bindM t; haftmann@28145: fun bindM_monad_tr' (f::g::ts) = list_comb haftmann@28145: (Const ("_do", dummyT) $ unfold_monad (Const (@{const_syntax bindM}, dummyT) $ f $ g), ts); haftmann@28145: fun Let_monad_tr' (f :: (g as Abs (_, _, g')) :: ts) = if contains_bindM g' then list_comb haftmann@28145: (Const ("_do", dummyT) $ unfold_monad (Const (@{const_syntax Let}, dummyT) $ f $ g), ts) haftmann@28145: else raise Match; haftmann@28145: in [ haftmann@28145: (@{const_syntax bindM}, bindM_monad_tr'), haftmann@28145: (@{const_syntax Let}, Let_monad_tr') haftmann@28145: ] end; haftmann@26170: *} haftmann@26170: haftmann@26170: haftmann@26170: subsection {* Monad properties *} haftmann@26170: haftmann@26170: subsubsection {* Monad laws *} haftmann@26170: haftmann@26170: lemma return_bind: "return x \= f = f x" haftmann@26170: by (simp add: bindM_def return_def) haftmann@26170: haftmann@26170: lemma bind_return: "f \= return = f" haftmann@26170: proof (rule Heap_eqI) haftmann@26170: fix h haftmann@26170: show "execute (f \= return) h = execute f h" haftmann@26170: by (auto simp add: bindM_def return_def split: sum.splits prod.splits) haftmann@26170: qed haftmann@26170: haftmann@26170: lemma bind_bind: "(f \= g) \= h = f \= (\x. g x \= h)" haftmann@26170: by (rule Heap_eqI) (auto simp add: bindM_def split: split: sum.splits prod.splits) haftmann@26170: haftmann@26170: lemma bind_bind': "f \= (\x. g x \= h x) = f \= (\x. g x \= (\y. return (x, y))) \= (\(x, y). h x y)" haftmann@26170: by (rule Heap_eqI) (auto simp add: bindM_def split: split: sum.splits prod.splits) haftmann@26170: haftmann@26170: lemma raise_bind: "raise e \= f = raise e" haftmann@26170: by (simp add: raise_def bindM_def) haftmann@26170: haftmann@26170: haftmann@26170: lemmas monad_simp = return_bind bind_return bind_bind raise_bind haftmann@26170: haftmann@26170: haftmann@26170: subsection {* Generic combinators *} haftmann@26170: haftmann@26170: definition haftmann@26170: liftM :: "('a \ 'b) \ 'a \ 'b Heap" haftmann@26170: where haftmann@26170: "liftM f = return o f" haftmann@26170: haftmann@26170: definition haftmann@26170: compM :: "('a \ 'b Heap) \ ('b \ 'c Heap) \ 'a \ 'c Heap" (infixl ">>==" 54) haftmann@26170: where haftmann@26170: "(f >>== g) = (\x. f x \= g)" haftmann@26170: haftmann@26170: notation haftmann@26170: compM (infixl "\==" 54) haftmann@26170: haftmann@26170: lemma liftM_collapse: "liftM f x = return (f x)" haftmann@26170: by (simp add: liftM_def) haftmann@26170: haftmann@26170: lemma liftM_compM: "liftM f \== g = g o f" haftmann@26170: by (auto intro: Heap_eqI' simp add: expand_fun_eq liftM_def compM_def bindM_def) haftmann@26170: haftmann@26170: lemma compM_return: "f \== return = f" haftmann@26170: by (simp add: compM_def monad_simp) haftmann@26170: haftmann@26170: lemma compM_compM: "(f \== g) \== h = f \== (g \== h)" haftmann@26170: by (simp add: compM_def monad_simp) haftmann@26170: haftmann@26170: lemma liftM_bind: haftmann@26170: "(\x. liftM f x \= liftM g) = liftM (\x. g (f x))" haftmann@26170: by (rule Heap_eqI') (simp add: monad_simp liftM_def bindM_def) haftmann@26170: haftmann@26170: lemma liftM_comp: haftmann@26170: "liftM f o g = liftM (f o g)" haftmann@26170: by (rule Heap_eqI') (simp add: liftM_def) haftmann@26170: haftmann@26170: lemmas monad_simp' = monad_simp liftM_compM compM_return haftmann@26170: compM_compM liftM_bind liftM_comp haftmann@26170: haftmann@26170: primrec haftmann@26170: mapM :: "('a \ 'b Heap) \ 'a list \ 'b list Heap" haftmann@26170: where haftmann@26170: "mapM f [] = return []" haftmann@26170: | "mapM f (x#xs) = do y \ f x; haftmann@26170: ys \ mapM f xs; haftmann@26170: return (y # ys) haftmann@26170: done" haftmann@26170: haftmann@26170: primrec haftmann@26170: foldM :: "('a \ 'b \ 'b Heap) \ 'a list \ 'b \ 'b Heap" haftmann@26170: where haftmann@26170: "foldM f [] s = return s" haftmann@26170: | "foldM f (x#xs) s = f x s \= foldM f xs" haftmann@26170: haftmann@26170: hide (open) const heap execute haftmann@26170: haftmann@26182: haftmann@26182: subsection {* Code generator setup *} haftmann@26182: haftmann@26182: subsubsection {* Logical intermediate layer *} haftmann@26182: haftmann@26182: definition haftmann@26182: Fail :: "message_string \ exception" haftmann@26182: where haftmann@28562: [code del]: "Fail s = Exn" haftmann@26182: haftmann@26182: definition haftmann@26182: raise_exc :: "exception \ 'a Heap" haftmann@26182: where haftmann@28562: [code del]: "raise_exc e = raise []" haftmann@26182: haftmann@28562: lemma raise_raise_exc [code, code inline]: haftmann@26182: "raise s = raise_exc (Fail (STR s))" haftmann@26182: unfolding Fail_def raise_exc_def raise_def .. haftmann@26182: haftmann@26182: hide (open) const Fail raise_exc haftmann@26182: haftmann@26182: haftmann@27707: subsubsection {* SML and OCaml *} haftmann@26182: haftmann@26752: code_type Heap (SML "unit/ ->/ _") haftmann@26182: code_const Heap (SML "raise/ (Fail/ \"bare Heap\")") haftmann@27826: code_const "op \=" (SML "!(fn/ f'_/ =>/ fn/ ()/ =>/ f'_/ (_/ ())/ ())") haftmann@27707: code_const return (SML "!(fn/ ()/ =>/ _)") haftmann@26182: code_const "Heap_Monad.Fail" (SML "Fail") haftmann@27707: code_const "Heap_Monad.raise_exc" (SML "!(fn/ ()/ =>/ raise/ _)") haftmann@26182: haftmann@26182: code_type Heap (OCaml "_") haftmann@26182: code_const Heap (OCaml "failwith/ \"bare Heap\"") haftmann@27826: code_const "op \=" (OCaml "!(fun/ f'_/ ()/ ->/ f'_/ (_/ ())/ ())") haftmann@27707: code_const return (OCaml "!(fun/ ()/ ->/ _)") haftmann@26182: code_const "Heap_Monad.Fail" (OCaml "Failure") haftmann@27707: code_const "Heap_Monad.raise_exc" (OCaml "!(fun/ ()/ ->/ raise/ _)") haftmann@27707: haftmann@28663: setup {* let haftmann@28663: open Code_Thingol; haftmann@27707: haftmann@28663: fun lookup naming = the o Code_Thingol.lookup_const naming; haftmann@27707: haftmann@28663: fun imp_monad_bind'' bind' return' unit' ts = haftmann@28663: let haftmann@28663: val dummy_name = ""; haftmann@28663: val dummy_type = ITyVar dummy_name; haftmann@28663: val dummy_case_term = IVar dummy_name; haftmann@28663: (*assumption: dummy values are not relevant for serialization*) haftmann@28663: val unitt = IConst (unit', ([], [])); haftmann@28663: fun dest_abs ((v, ty) `|-> t, _) = ((v, ty), t) haftmann@28663: | dest_abs (t, ty) = haftmann@28663: let haftmann@28663: val vs = Code_Thingol.fold_varnames cons t []; haftmann@28663: val v = Name.variant vs "x"; haftmann@28663: val ty' = (hd o fst o Code_Thingol.unfold_fun) ty; haftmann@28663: in ((v, ty'), t `$ IVar v) end; haftmann@28663: fun force (t as IConst (c, _) `$ t') = if c = return' haftmann@28663: then t' else t `$ unitt haftmann@28663: | force t = t `$ unitt; haftmann@28663: fun tr_bind' [(t1, _), (t2, ty2)] = haftmann@28663: let haftmann@28663: val ((v, ty), t) = dest_abs (t2, ty2); haftmann@28663: in ICase (((force t1, ty), [(IVar v, tr_bind'' t)]), dummy_case_term) end haftmann@28663: and tr_bind'' t = case Code_Thingol.unfold_app t haftmann@28663: of (IConst (c, (_, ty1 :: ty2 :: _)), [x1, x2]) => if c = bind' haftmann@28663: then tr_bind' [(x1, ty1), (x2, ty2)] haftmann@28663: else force t haftmann@28663: | _ => force t; haftmann@28663: in (dummy_name, dummy_type) `|-> ICase (((IVar dummy_name, dummy_type), haftmann@28663: [(unitt, tr_bind' ts)]), dummy_case_term) end haftmann@28663: and imp_monad_bind' bind' return' unit' (const as (c, (_, tys))) ts = if c = bind' then case (ts, tys) haftmann@28663: of ([t1, t2], ty1 :: ty2 :: _) => imp_monad_bind'' bind' return' unit' [(t1, ty1), (t2, ty2)] haftmann@28663: | ([t1, t2, t3], ty1 :: ty2 :: _) => imp_monad_bind'' bind' return' unit' [(t1, ty1), (t2, ty2)] `$ t3 haftmann@28663: | (ts, _) => imp_monad_bind bind' return' unit' (eta_expand 2 (const, ts)) haftmann@28663: else IConst const `$$ map (imp_monad_bind bind' return' unit') ts haftmann@28663: and imp_monad_bind bind' return' unit' (IConst const) = imp_monad_bind' bind' return' unit' const [] haftmann@28663: | imp_monad_bind bind' return' unit' (t as IVar _) = t haftmann@28663: | imp_monad_bind bind' return' unit' (t as _ `$ _) = (case unfold_app t haftmann@28663: of (IConst const, ts) => imp_monad_bind' bind' return' unit' const ts haftmann@28663: | (t, ts) => imp_monad_bind bind' return' unit' t `$$ map (imp_monad_bind bind' return' unit') ts) haftmann@28663: | imp_monad_bind bind' return' unit' (v_ty `|-> t) = v_ty `|-> imp_monad_bind bind' return' unit' t haftmann@28663: | imp_monad_bind bind' return' unit' (ICase (((t, ty), pats), t0)) = ICase haftmann@28663: (((imp_monad_bind bind' return' unit' t, ty), (map o pairself) (imp_monad_bind bind' return' unit') pats), imp_monad_bind bind' return' unit' t0); haftmann@28663: haftmann@28663: fun imp_program naming = (Graph.map_nodes o map_terms_stmt) haftmann@28663: (imp_monad_bind (lookup naming @{const_name bindM}) haftmann@28663: (lookup naming @{const_name return}) haftmann@28663: (lookup naming @{const_name Unity})); haftmann@27707: haftmann@27707: in haftmann@27707: haftmann@28663: Code_Target.extend_target ("SML_imp", ("SML", imp_program)) haftmann@28663: #> Code_Target.extend_target ("OCaml_imp", ("OCaml", imp_program)) haftmann@27707: haftmann@27707: end haftmann@27707: *} haftmann@27707: haftmann@26182: haftmann@26182: code_reserved OCaml Failure raise haftmann@26182: haftmann@26182: haftmann@26182: subsubsection {* Haskell *} haftmann@26182: haftmann@26182: text {* Adaption layer *} haftmann@26182: haftmann@26182: code_include Haskell "STMonad" haftmann@26182: {*import qualified Control.Monad; haftmann@26182: import qualified Control.Monad.ST; haftmann@26182: import qualified Data.STRef; haftmann@26182: import qualified Data.Array.ST; haftmann@26182: haftmann@27695: type RealWorld = Control.Monad.ST.RealWorld; haftmann@26182: type ST s a = Control.Monad.ST.ST s a; haftmann@26182: type STRef s a = Data.STRef.STRef s a; haftmann@27673: type STArray s a = Data.Array.ST.STArray s Int a; haftmann@26182: haftmann@26182: runST :: (forall s. ST s a) -> a; haftmann@26182: runST s = Control.Monad.ST.runST s; haftmann@26182: haftmann@26182: newSTRef = Data.STRef.newSTRef; haftmann@26182: readSTRef = Data.STRef.readSTRef; haftmann@26182: writeSTRef = Data.STRef.writeSTRef; haftmann@26182: haftmann@27673: newArray :: (Int, Int) -> a -> ST s (STArray s a); haftmann@26182: newArray = Data.Array.ST.newArray; haftmann@26182: haftmann@27673: newListArray :: (Int, Int) -> [a] -> ST s (STArray s a); haftmann@26182: newListArray = Data.Array.ST.newListArray; haftmann@26182: haftmann@27673: lengthArray :: STArray s a -> ST s Int; haftmann@27673: lengthArray a = Control.Monad.liftM snd (Data.Array.ST.getBounds a); haftmann@26182: haftmann@27673: readArray :: STArray s a -> Int -> ST s a; haftmann@26182: readArray = Data.Array.ST.readArray; haftmann@26182: haftmann@27673: writeArray :: STArray s a -> Int -> a -> ST s (); haftmann@26182: writeArray = Data.Array.ST.writeArray;*} haftmann@26182: haftmann@27695: code_reserved Haskell RealWorld ST STRef Array haftmann@26182: runST haftmann@26182: newSTRef reasSTRef writeSTRef haftmann@27673: newArray newListArray lengthArray readArray writeArray haftmann@26182: haftmann@26182: text {* Monad *} haftmann@26182: haftmann@27695: code_type Heap (Haskell "ST/ RealWorld/ _") haftmann@27695: code_const Heap (Haskell "error/ \"bare Heap\"") haftmann@28145: code_monad "op \=" Haskell haftmann@26182: code_const return (Haskell "return") haftmann@26182: code_const "Heap_Monad.Fail" (Haskell "_") haftmann@26182: code_const "Heap_Monad.raise_exc" (Haskell "error") haftmann@26182: haftmann@26170: end