Movatterモバイル変換


[0]ホーム

URL:


{-# LANGUAGE Unsafe #-}{-# LANGUAGE BangPatterns #-}{-# LANGUAGE MagicHash, UnboxedTuples, RankNTypes #-}{-# OPTIONS_HADDOCK hide #-}------------------------------------------------------------------------------- |-- Module      :  Control.Monad.ST.Lazy.Imp-- Copyright   :  (c) The University of Glasgow 2001-- License     :  BSD-style (see the file libraries/base/LICENSE)---- Maintainer  :  libraries@haskell.org-- Stability   :  provisional-- Portability :  non-portable (requires universal quantification for runST)---- This module presents an identical interface to "Control.Monad.ST",-- except that the monad delays evaluation of state operations until-- a value depending on them is required.-------------------------------------------------------------------------------moduleControl.Monad.ST.Lazy.Imp(-- * The 'ST' monadST,runST,fixST,-- * Converting between strict and lazy 'ST'strictToLazyST,lazyToStrictST,-- * Converting 'ST' To 'IO'RealWorld,stToIO,-- * Unsafe operationsunsafeInterleaveST,unsafeIOToST)whereimportControl.Monad.FiximportqualifiedControl.Monad.STasSTimportqualifiedControl.Monad.ST.UnsafeasSTimportqualifiedGHC.STasGHC.STimportGHC.BaseimportqualifiedControl.Monad.FailasFail-- | The lazy state-transformer monad.-- A computation of type @'ST' s a@ transforms an internal state indexed-- by @s@, and returns a value of type @a@.-- The @s@ parameter is either---- * an uninstantiated type variable (inside invocations of 'runST'), or---- * 'RealWorld' (inside invocations of 'stToIO').---- It serves to keep the internal states of different invocations of-- 'runST' separate from each other and from invocations of 'stToIO'.---- The '>>=' and '>>' operations are not strict in the state.  For example,---- @'runST' (writeSTRef _|_ v >>= readSTRef _|_ >> return 2) = 2@newtypeSTsa=ST{unST::States->(a,States)}-- A lifted state token. This can be imagined as a moment in the timeline-- of a lazy state thread. Forcing the token forces all delayed actions in-- the thread up until that moment to be performed.dataStates=S#(State#s){- Note [Lazy ST and multithreading]We used to imagine that passing a polymorphic state token was all that weneeded to keep state threads separate (see Launchbury and Peyton Jones, 1994:https://www.microsoft.com/en-us/research/publication/lazy-functional-state-threads/).But this breaks down in the face of concurrency (see #11760). Whereas a strictST computation runs to completion before producing anything, a value producedby running a lazy ST computation may contain a thunk that, when forced, willlead to further stateful computations. If such a thunk is entered by more thanone thread, then they may both read from and write to the same references andarrays, interfering with each other. To work around this, any time we lazilysuspend execution of a lazy ST computation, we bind the result pair to aNOINLINE binding (ensuring that it is not duplicated) and calculate thatpair using (unsafePerformIO . evaluate), ensuring that only one thread willenter the thunk. We still use lifted state tokens to actually drive execution,so in these cases we effectively deal with *two* state tokens: the liftedone we get from the previous computation, and the unlifted one we pull out ofthin air. -}{- Note [Lazy ST: not producing lazy pairs]The fixST and strictToLazyST functions used to construct functions thatproduced lazy pairs. Why don't we need that laziness? The ST type is keptabstract, so no one outside this module can ever get their hands on a (result,State s) pair. We ourselves never match on such pairs when performing STcomputations unless we also force one of their components. So no one should beable to detect the change. By refraining from producing such thunks (whichreference delayed ST computations), we avoid having to ask whether we have towrap them up with unsafePerformIO. See Note [Lazy ST and multithreading]. -}-- | This is a terrible hack to prevent a thunk from being entered twice.-- Simon Peyton Jones would very much like to be rid of it.noDup::a->anoDupa=runRW#(\s->casenoDuplicate#sof_->a)-- | @since 2.01instanceFunctor(STs)wherefmapfm=ST$\s->let-- See Note [Lazy ST and multithreading]{-# NOINLINEres#-}res=noDup(unSTms)(r,new_s)=resin(fr,new_s)x<$m=ST$\s->let{-# NOINLINEs'#-}-- See Note [Lazy ST and multithreading]s'=noDup(snd(unSTms))in(x,s')-- | @since 2.01instanceApplicative(STs)wherepurea=ST$\s->(a,s)fm<*>xm=ST$\s->let{-# NOINLINEres1#-}!res1=unSTfms!(f,s')=res1{-# NOINLINEres2#-}-- See Note [Lazy ST and multithreading]res2=noDup(unSTxms')(x,s'')=res2in(fx,s'')-- Why can we use a strict binding for res1? If someone-- forces the (f x, s'') pair, then they must need-- f or s''. To get s'', they need s'.liftA2fmn=ST$\s->let{-# NOINLINEres1#-}-- See Note [Lazy ST and multithreading]res1=noDup(unSTms)(x,s')=res1{-# NOINLINEres2#-}res2=noDup(unSTns')(y,s'')=res2in(fxy,s'')-- We don't get to be strict in liftA2, but we clear out a-- NOINLINE in comparison to the default definition, which may-- help the simplifier.m*>n=ST$\s->let{-# NOINLINEs'#-}-- See Note [Lazy ST and multithreading]s'=noDup(snd(unSTms))inunSTns'm<*n=ST$\s->let{-# NOINLINEres1#-}!res1=unSTms!(mr,s')=res1{-# NOINLINEs''#-}-- See Note [Lazy ST and multithreading]s''=noDup(snd(unSTns'))in(mr,s'')-- Why can we use a strict binding for res1? The same reason as-- in <*>. If someone demands the (mr, s'') pair, then they will-- force mr or s''. To get s'', they need s'.-- | @since 2.01instanceMonad(STs)wherefails=errorWithoutStackTraces(>>)=(*>)m>>=k=ST$\s->let-- See Note [Lazy ST and multithreading]{-# NOINLINEres#-}res=noDup(unSTms)(r,new_s)=resinunST(kr)new_s-- | @since 4.10instanceFail.MonadFail(STs)wherefails=errorWithoutStackTraces-- | Return the value computed by a state transformer computation.-- The @forall@ ensures that the internal state used by the 'ST'-- computation is inaccessible to the rest of the program.runST::(foralls.STsa)->arunST(STst)=runRW#(\s->casest(S#s)of(r,_)->r)-- | Allow the result of a state transformer computation to be used (lazily)-- inside the computation.-- Note that if @f@ is strict, @'fixST' f = _|_@.fixST::(a->STsa)->STsafixSTm=ST(\s->letq@(r,_s')=unST(mr)sinq)-- Why don't we need unsafePerformIO in fixST? We create a thunk, q,-- to perform a lazy state computation, and we pass a reference to that-- thunk, r, to m. Uh oh? No, I think it should be fine, because that thunk-- itself is demanded directly in the `let` body. See also-- Note [Lazy ST: not producing lazy pairs].-- | @since 2.01instanceMonadFix(STs)wheremfix=fixST-- ----------------------------------------------------------------------------- Strict <--> Lazy{-|Convert a strict 'ST' computation into a lazy one.  The strict statethread passed to 'strictToLazyST' is not performed until the result ofthe lazy state thread it returns is demanded.-}strictToLazyST::ST.STsa->STsastrictToLazyST(GHC.ST.STm)=ST$\(S#s)->casemsof(#s',a#)->(a,S#s')-- See Note [Lazy ST: not producing lazy pairs]{-| Convert a lazy 'ST' computation into a strict one.-}lazyToStrictST::STsa->ST.STsalazyToStrictST(STm)=GHC.ST.ST$\s->case(m(S#s))of(a,S#s')->(#s',a#)-- | A monad transformer embedding lazy state transformers in the 'IO'-- monad.  The 'RealWorld' parameter indicates that the internal state-- used by the 'ST' computation is a special one supplied by the 'IO'-- monad, and thus distinct from those used by invocations of 'runST'.stToIO::STRealWorlda->IOastToIO=ST.stToIO.lazyToStrictST-- ----------------------------------------------------------------------------- Strict <--> LazyunsafeInterleaveST::STsa->STsaunsafeInterleaveST=strictToLazyST.ST.unsafeInterleaveST.lazyToStrictSTunsafeIOToST::IOa->STsaunsafeIOToST=strictToLazyST.ST.unsafeIOToST

[8]ページ先頭

©2009-2025 Movatter.jp