packages feed

base 4.8.2.0 → 4.22.0.0

raw patch · 508 files changed

Files

− Control/Applicative.hs
@@ -1,136 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE AutoDeriveTypeable #-}-{-# LANGUAGE DeriveGeneric #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE ScopedTypeVariables #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Applicative--- Copyright   :  Conor McBride and Ross Paterson 2005--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ This module describes a structure intermediate between a functor and--- a monad (technically, a strong lax monoidal functor).  Compared with--- monads, this interface lacks the full power of the binding operation--- '>>=', but------ * it has more instances.------ * it is sufficient for many uses, e.g. context-free parsing, or the---   'Data.Traversable.Traversable' class.------ * instances can perform analysis of computations before they are---   executed, and thus produce shared optimizations.------ This interface was introduced for parsers by Niklas R&#xF6;jemo, because--- it admits more sharing than the monadic interface.  The names here are--- mostly based on parsing work by Doaitse Swierstra.------ For more details, see--- <http://www.soi.city.ac.uk/~ross/papers/Applicative.html Applicative Programming with Effects>,--- by Conor McBride and Ross Paterson.--module Control.Applicative (-    -- * Applicative functors-    Applicative(..),-    -- * Alternatives-    Alternative(..),-    -- * Instances-    Const(..), WrappedMonad(..), WrappedArrow(..), ZipList(..),-    -- * Utility functions-    (<$>), (<$), (<**>),-    liftA, liftA2, liftA3,-    optional,-    ) where--import Control.Category hiding ((.), id)-import Control.Arrow-import Data.Maybe-import Data.Tuple-import Data.Eq-import Data.Ord-import Data.Foldable (Foldable(..))-import Data.Functor ((<$>))--import GHC.Base-import GHC.Generics-import GHC.List (repeat, zipWith)-import GHC.Read (Read(readsPrec), readParen, lex)-import GHC.Show (Show(showsPrec), showParen, showString)--newtype Const a b = Const { getConst :: a }-                  deriving (Generic, Generic1, Monoid, Eq, Ord)--instance Read a => Read (Const a b) where-    readsPrec d = readParen (d > 10)-        $ \r -> [(Const x,t) | ("Const", s) <- lex r, (x, t) <- readsPrec 11 s]--instance Show a => Show (Const a b) where-    showsPrec d (Const x) = showParen (d > 10) $-                            showString "Const " . showsPrec 11 x--instance Foldable (Const m) where-    foldMap _ _ = mempty--instance Functor (Const m) where-    fmap _ (Const v) = Const v--instance Monoid m => Applicative (Const m) where-    pure _ = Const mempty-    (<*>) = coerce (mappend :: m -> m -> m)--- This is pretty much the same as--- Const f <*> Const v = Const (f `mappend` v)--- but guarantees that mappend for Const a b will have the same arity--- as the one for a; it won't create a closure to raise the arity--- to 2.--newtype WrappedMonad m a = WrapMonad { unwrapMonad :: m a }-                         deriving (Generic, Generic1, Monad)--instance Monad m => Functor (WrappedMonad m) where-    fmap f (WrapMonad v) = WrapMonad (liftM f v)--instance Monad m => Applicative (WrappedMonad m) where-    pure = WrapMonad . return-    WrapMonad f <*> WrapMonad v = WrapMonad (f `ap` v)--instance MonadPlus m => Alternative (WrappedMonad m) where-    empty = WrapMonad mzero-    WrapMonad u <|> WrapMonad v = WrapMonad (u `mplus` v)--newtype WrappedArrow a b c = WrapArrow { unwrapArrow :: a b c }-                           deriving (Generic, Generic1)--instance Arrow a => Functor (WrappedArrow a b) where-    fmap f (WrapArrow a) = WrapArrow (a >>> arr f)--instance Arrow a => Applicative (WrappedArrow a b) where-    pure x = WrapArrow (arr (const x))-    WrapArrow f <*> WrapArrow v = WrapArrow (f &&& v >>> arr (uncurry id))--instance (ArrowZero a, ArrowPlus a) => Alternative (WrappedArrow a b) where-    empty = WrapArrow zeroArrow-    WrapArrow u <|> WrapArrow v = WrapArrow (u <+> v)---- | Lists, but with an 'Applicative' functor based on zipping, so that------ @f '<$>' 'ZipList' xs1 '<*>' ... '<*>' 'ZipList' xsn = 'ZipList' (zipWithn f xs1 ... xsn)@----newtype ZipList a = ZipList { getZipList :: [a] }-                  deriving (Show, Eq, Ord, Read, Functor, Generic, Generic1)--instance Applicative ZipList where-    pure x = ZipList (repeat x)-    ZipList fs <*> ZipList xs = ZipList (zipWith id fs xs)---- extra functions---- | One or none.-optional :: Alternative f => f a -> f (Maybe a)-optional v = Just <$> v <|> pure Nothing
− Control/Arrow.hs
@@ -1,372 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Arrow--- Copyright   :  (c) Ross Paterson 2002--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Basic arrow definitions, based on------  * /Generalising Monads to Arrows/, by John Hughes,---    /Science of Computer Programming/ 37, pp67-111, May 2000.------ plus a couple of definitions ('returnA' and 'loop') from------  * /A New Notation for Arrows/, by Ross Paterson, in /ICFP 2001/,---    Firenze, Italy, pp229-240.------ These papers and more information on arrows can be found at--- <http://www.haskell.org/arrows/>.--module Control.Arrow (-    -- * Arrows-    Arrow(..), Kleisli(..),-    -- ** Derived combinators-    returnA,-    (^>>), (>>^),-    (>>>), (<<<), -- reexported-    -- ** Right-to-left variants-    (<<^), (^<<),-    -- * Monoid operations-    ArrowZero(..), ArrowPlus(..),-    -- * Conditionals-    ArrowChoice(..),-    -- * Arrow application-    ArrowApply(..), ArrowMonad(..), leftApp,-    -- * Feedback-    ArrowLoop(..)-    ) where--import Data.Tuple ( fst, snd, uncurry )-import Data.Either-import Control.Monad.Fix-import Control.Category-import GHC.Base hiding ( (.), id )--infixr 5 <+>-infixr 3 ***-infixr 3 &&&-infixr 2 +++-infixr 2 |||-infixr 1 ^>>, >>^-infixr 1 ^<<, <<^---- | The basic arrow class.------ Instances should satisfy the following laws:------  * @'arr' id = 'id'@------  * @'arr' (f >>> g) = 'arr' f >>> 'arr' g@------  * @'first' ('arr' f) = 'arr' ('first' f)@------  * @'first' (f >>> g) = 'first' f >>> 'first' g@------  * @'first' f >>> 'arr' 'fst' = 'arr' 'fst' >>> f@------  * @'first' f >>> 'arr' ('id' *** g) = 'arr' ('id' *** g) >>> 'first' f@------  * @'first' ('first' f) >>> 'arr' 'assoc' = 'arr' 'assoc' >>> 'first' f@------ where------ > assoc ((a,b),c) = (a,(b,c))------ The other combinators have sensible default definitions,--- which may be overridden for efficiency.--class Category a => Arrow a where--    -- | Lift a function to an arrow.-    arr :: (b -> c) -> a b c--    -- | Send the first component of the input through the argument-    --   arrow, and copy the rest unchanged to the output.-    first :: a b c -> a (b,d) (c,d)--    -- | A mirror image of 'first'.-    ---    --   The default definition may be overridden with a more efficient-    --   version if desired.-    second :: a b c -> a (d,b) (d,c)-    second f = arr swap >>> first f >>> arr swap-      where-        swap :: (x,y) -> (y,x)-        swap ~(x,y) = (y,x)--    -- | Split the input between the two argument arrows and combine-    --   their output.  Note that this is in general not a functor.-    ---    --   The default definition may be overridden with a more efficient-    --   version if desired.-    (***) :: a b c -> a b' c' -> a (b,b') (c,c')-    f *** g = first f >>> second g--    -- | Fanout: send the input to both argument arrows and combine-    --   their output.-    ---    --   The default definition may be overridden with a more efficient-    --   version if desired.-    (&&&) :: a b c -> a b c' -> a b (c,c')-    f &&& g = arr (\b -> (b,b)) >>> f *** g--{-# RULES-"compose/arr"   forall f g .-                (arr f) . (arr g) = arr (f . g)-"first/arr"     forall f .-                first (arr f) = arr (first f)-"second/arr"    forall f .-                second (arr f) = arr (second f)-"product/arr"   forall f g .-                arr f *** arr g = arr (f *** g)-"fanout/arr"    forall f g .-                arr f &&& arr g = arr (f &&& g)-"compose/first" forall f g .-                (first f) . (first g) = first (f . g)-"compose/second" forall f g .-                (second f) . (second g) = second (f . g)- #-}---- Ordinary functions are arrows.--instance Arrow (->) where-    arr f = f-    first f = f *** id-    second f = id *** f---  (f *** g) ~(x,y) = (f x, g y)---  sorry, although the above defn is fully H'98, nhc98 can't parse it.-    (***) f g ~(x,y) = (f x, g y)---- | Kleisli arrows of a monad.-newtype Kleisli m a b = Kleisli { runKleisli :: a -> m b }--instance Monad m => Category (Kleisli m) where-    id = Kleisli return-    (Kleisli f) . (Kleisli g) = Kleisli (\b -> g b >>= f)--instance Monad m => Arrow (Kleisli m) where-    arr f = Kleisli (return . f)-    first (Kleisli f) = Kleisli (\ ~(b,d) -> f b >>= \c -> return (c,d))-    second (Kleisli f) = Kleisli (\ ~(d,b) -> f b >>= \c -> return (d,c))---- | The identity arrow, which plays the role of 'return' in arrow notation.-returnA :: Arrow a => a b b-returnA = arr id---- | Precomposition with a pure function.-(^>>) :: Arrow a => (b -> c) -> a c d -> a b d-f ^>> a = arr f >>> a---- | Postcomposition with a pure function.-(>>^) :: Arrow a => a b c -> (c -> d) -> a b d-a >>^ f = a >>> arr f---- | Precomposition with a pure function (right-to-left variant).-(<<^) :: Arrow a => a c d -> (b -> c) -> a b d-a <<^ f = a <<< arr f---- | Postcomposition with a pure function (right-to-left variant).-(^<<) :: Arrow a => (c -> d) -> a b c -> a b d-f ^<< a = arr f <<< a--class Arrow a => ArrowZero a where-    zeroArrow :: a b c--instance MonadPlus m => ArrowZero (Kleisli m) where-    zeroArrow = Kleisli (\_ -> mzero)---- | A monoid on arrows.-class ArrowZero a => ArrowPlus a where-    -- | An associative operation with identity 'zeroArrow'.-    (<+>) :: a b c -> a b c -> a b c--instance MonadPlus m => ArrowPlus (Kleisli m) where-    Kleisli f <+> Kleisli g = Kleisli (\x -> f x `mplus` g x)---- | Choice, for arrows that support it.  This class underlies the--- @if@ and @case@ constructs in arrow notation.------ Instances should satisfy the following laws:------  * @'left' ('arr' f) = 'arr' ('left' f)@------  * @'left' (f >>> g) = 'left' f >>> 'left' g@------  * @f >>> 'arr' 'Left' = 'arr' 'Left' >>> 'left' f@------  * @'left' f >>> 'arr' ('id' +++ g) = 'arr' ('id' +++ g) >>> 'left' f@------  * @'left' ('left' f) >>> 'arr' 'assocsum' = 'arr' 'assocsum' >>> 'left' f@------ where------ > assocsum (Left (Left x)) = Left x--- > assocsum (Left (Right y)) = Right (Left y)--- > assocsum (Right z) = Right (Right z)------ The other combinators have sensible default definitions, which may--- be overridden for efficiency.--class Arrow a => ArrowChoice a where--    -- | Feed marked inputs through the argument arrow, passing the-    --   rest through unchanged to the output.-    left :: a b c -> a (Either b d) (Either c d)--    -- | A mirror image of 'left'.-    ---    --   The default definition may be overridden with a more efficient-    --   version if desired.-    right :: a b c -> a (Either d b) (Either d c)-    right f = arr mirror >>> left f >>> arr mirror-      where-        mirror :: Either x y -> Either y x-        mirror (Left x) = Right x-        mirror (Right y) = Left y--    -- | Split the input between the two argument arrows, retagging-    --   and merging their outputs.-    --   Note that this is in general not a functor.-    ---    --   The default definition may be overridden with a more efficient-    --   version if desired.-    (+++) :: a b c -> a b' c' -> a (Either b b') (Either c c')-    f +++ g = left f >>> right g--    -- | Fanin: Split the input between the two argument arrows and-    --   merge their outputs.-    ---    --   The default definition may be overridden with a more efficient-    --   version if desired.-    (|||) :: a b d -> a c d -> a (Either b c) d-    f ||| g = f +++ g >>> arr untag-      where-        untag (Left x) = x-        untag (Right y) = y--{-# RULES-"left/arr"      forall f .-                left (arr f) = arr (left f)-"right/arr"     forall f .-                right (arr f) = arr (right f)-"sum/arr"       forall f g .-                arr f +++ arr g = arr (f +++ g)-"fanin/arr"     forall f g .-                arr f ||| arr g = arr (f ||| g)-"compose/left"  forall f g .-                left f . left g = left (f . g)-"compose/right" forall f g .-                right f . right g = right (f . g)- #-}--instance ArrowChoice (->) where-    left f = f +++ id-    right f = id +++ f-    f +++ g = (Left . f) ||| (Right . g)-    (|||) = either--instance Monad m => ArrowChoice (Kleisli m) where-    left f = f +++ arr id-    right f = arr id +++ f-    f +++ g = (f >>> arr Left) ||| (g >>> arr Right)-    Kleisli f ||| Kleisli g = Kleisli (either f g)---- | Some arrows allow application of arrow inputs to other inputs.--- Instances should satisfy the following laws:------  * @'first' ('arr' (\\x -> 'arr' (\\y -> (x,y)))) >>> 'app' = 'id'@------  * @'first' ('arr' (g >>>)) >>> 'app' = 'second' g >>> 'app'@------  * @'first' ('arr' (>>> h)) >>> 'app' = 'app' >>> h@------ Such arrows are equivalent to monads (see 'ArrowMonad').--class Arrow a => ArrowApply a where-    app :: a (a b c, b) c--instance ArrowApply (->) where-    app (f,x) = f x--instance Monad m => ArrowApply (Kleisli m) where-    app = Kleisli (\(Kleisli f, x) -> f x)---- | The 'ArrowApply' class is equivalent to 'Monad': any monad gives rise---   to a 'Kleisli' arrow, and any instance of 'ArrowApply' defines a monad.--newtype ArrowMonad a b = ArrowMonad (a () b)--instance Arrow a => Functor (ArrowMonad a) where-    fmap f (ArrowMonad m) = ArrowMonad $ m >>> arr f--instance Arrow a => Applicative (ArrowMonad a) where-   pure x = ArrowMonad (arr (const x))-   ArrowMonad f <*> ArrowMonad x = ArrowMonad (f &&& x >>> arr (uncurry id))--instance ArrowApply a => Monad (ArrowMonad a) where-    return x = ArrowMonad (arr (\_ -> x))-    ArrowMonad m >>= f = ArrowMonad $-        m >>> arr (\x -> let ArrowMonad h = f x in (h, ())) >>> app--instance ArrowPlus a => Alternative (ArrowMonad a) where-   empty = ArrowMonad zeroArrow-   ArrowMonad x <|> ArrowMonad y = ArrowMonad (x <+> y)--instance (ArrowApply a, ArrowPlus a) => MonadPlus (ArrowMonad a) where-   mzero = ArrowMonad zeroArrow-   ArrowMonad x `mplus` ArrowMonad y = ArrowMonad (x <+> y)---- | Any instance of 'ArrowApply' can be made into an instance of---   'ArrowChoice' by defining 'left' = 'leftApp'.--leftApp :: ArrowApply a => a b c -> a (Either b d) (Either c d)-leftApp f = arr ((\b -> (arr (\() -> b) >>> f >>> arr Left, ())) |||-             (\d -> (arr (\() -> d) >>> arr Right, ()))) >>> app---- | The 'loop' operator expresses computations in which an output value--- is fed back as input, although the computation occurs only once.--- It underlies the @rec@ value recursion construct in arrow notation.--- 'loop' should satisfy the following laws:------ [/extension/]---      @'loop' ('arr' f) = 'arr' (\\ b -> 'fst' ('fix' (\\ (c,d) -> f (b,d))))@------ [/left tightening/]---      @'loop' ('first' h >>> f) = h >>> 'loop' f@------ [/right tightening/]---      @'loop' (f >>> 'first' h) = 'loop' f >>> h@------ [/sliding/]---      @'loop' (f >>> 'arr' ('id' *** k)) = 'loop' ('arr' ('id' *** k) >>> f)@------ [/vanishing/]---      @'loop' ('loop' f) = 'loop' ('arr' unassoc >>> f >>> 'arr' assoc)@------ [/superposing/]---      @'second' ('loop' f) = 'loop' ('arr' assoc >>> 'second' f >>> 'arr' unassoc)@------ where------ > assoc ((a,b),c) = (a,(b,c))--- > unassoc (a,(b,c)) = ((a,b),c)----class Arrow a => ArrowLoop a where-    loop :: a (b,d) (c,d) -> a b c--instance ArrowLoop (->) where-    loop f b = let (c,d) = f (b,d) in c---- | Beware that for many monads (those for which the '>>=' operation--- is strict) this instance will /not/ satisfy the right-tightening law--- required by the 'ArrowLoop' class.-instance MonadFix m => ArrowLoop (Kleisli m) where-    loop (Kleisli f) = Kleisli (liftM fst . mfix . f')-      where f' x y = f (x, snd y)
− Control/Category.hs
@@ -1,64 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE GADTs #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE PolyKinds #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Category--- Copyright   :  (c) Ashley Yakeley 2007--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  ashley@semantic.org--- Stability   :  experimental--- Portability :  portable---- http://ghc.haskell.org/trac/ghc/ticket/1773--module Control.Category where--import qualified GHC.Base (id,(.))-import Data.Type.Coercion-import Data.Type.Equality-import GHC.Prim (coerce)--infixr 9 .-infixr 1 >>>, <<<---- | A class for categories.---   id and (.) must form a monoid.-class Category cat where-    -- | the identity morphism-    id :: cat a a--    -- | morphism composition-    (.) :: cat b c -> cat a b -> cat a c--{-# RULES-"identity/left" forall p .-                id . p = p-"identity/right"        forall p .-                p . id = p-"association"   forall p q r .-                (p . q) . r = p . (q . r)- #-}--instance Category (->) where-    id = GHC.Base.id-    (.) = (GHC.Base..)--instance Category (:~:) where-  id          = Refl-  Refl . Refl = Refl--instance Category Coercion where-  id = Coercion-  (.) Coercion = coerce---- | Right-to-left composition-(<<<) :: Category cat => cat b c -> cat a b -> cat a c-(<<<) = (.)---- | Left-to-right composition-(>>>) :: Category cat => cat a b -> cat b c -> cat a c-f >>> g = g . f
− Control/Concurrent.hs
@@ -1,661 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , MagicHash-           , UnboxedTuples-           , ScopedTypeVariables-  #-}-{-# OPTIONS_GHC -fno-warn-deprecations #-}--- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN--- and Control.Concurrent.SampleVar imports.---------------------------------------------------------------------------------- |--- Module      :  Control.Concurrent--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (concurrency)------ A common interface to a collection of useful concurrency--- abstractions.-----------------------------------------------------------------------------------module Control.Concurrent (-        -- * Concurrent Haskell--        -- $conc_intro--        -- * Basic concurrency operations--        ThreadId,-        myThreadId,--        forkIO,-        forkFinally,-        forkIOWithUnmask,-        killThread,-        throwTo,--        -- ** Threads with affinity-        forkOn,-        forkOnWithUnmask,-        getNumCapabilities,-        setNumCapabilities,-        threadCapability,--        -- * Scheduling--        -- $conc_scheduling-        yield,--        -- ** Blocking--        -- $blocking--        -- ** Waiting-        threadDelay,-        threadWaitRead,-        threadWaitWrite,-        threadWaitReadSTM,-        threadWaitWriteSTM,--        -- * Communication abstractions--        module Control.Concurrent.MVar,-        module Control.Concurrent.Chan,-        module Control.Concurrent.QSem,-        module Control.Concurrent.QSemN,--        -- * Bound Threads-        -- $boundthreads-        rtsSupportsBoundThreads,-        forkOS,-        isCurrentThreadBound,-        runInBoundThread,-        runInUnboundThread,--        -- * Weak references to ThreadIds-        mkWeakThreadId,--        -- * GHC's implementation of concurrency--        -- |This section describes features specific to GHC's-        -- implementation of Concurrent Haskell.--        -- ** Haskell threads and Operating System threads--        -- $osthreads--        -- ** Terminating the program--        -- $termination--        -- ** Pre-emption--        -- $preemption--        -- ** Deadlock--        -- $deadlock--    ) where--import Control.Exception.Base as Exception--import GHC.Conc hiding (threadWaitRead, threadWaitWrite,-                        threadWaitReadSTM, threadWaitWriteSTM)-import GHC.IO           ( unsafeUnmask )-import GHC.IORef        ( newIORef, readIORef, writeIORef )-import GHC.Base--import System.Posix.Types ( Fd )-import Foreign.StablePtr-import Foreign.C.Types--#ifdef mingw32_HOST_OS-import Foreign.C-import System.IO-import Data.Functor ( void )-#else-import qualified GHC.Conc-#endif--import Control.Concurrent.MVar-import Control.Concurrent.Chan-import Control.Concurrent.QSem-import Control.Concurrent.QSemN--{- $conc_intro--The concurrency extension for Haskell is described in the paper-/Concurrent Haskell/-<http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.--Concurrency is \"lightweight\", which means that both thread creation-and context switching overheads are extremely low.  Scheduling of-Haskell threads is done internally in the Haskell runtime system, and-doesn't make use of any operating system-supplied thread packages.--However, if you want to interact with a foreign library that expects your-program to use the operating system-supplied thread package, you can do so-by using 'forkOS' instead of 'forkIO'.--Haskell threads can communicate via 'MVar's, a kind of synchronised-mutable variable (see "Control.Concurrent.MVar").  Several common-concurrency abstractions can be built from 'MVar's, and these are-provided by the "Control.Concurrent" library.-In GHC, threads may also communicate via exceptions.--}--{- $conc_scheduling--    Scheduling may be either pre-emptive or co-operative,-    depending on the implementation of Concurrent Haskell (see below-    for information related to specific compilers).  In a co-operative-    system, context switches only occur when you use one of the-    primitives defined in this module.  This means that programs such-    as:--->   main = forkIO (write 'a') >> write 'b'->     where write c = putChar c >> write c--    will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,-    instead of some random interleaving of @a@s and @b@s.  In-    practice, cooperative multitasking is sufficient for writing-    simple graphical user interfaces.--}--{- $blocking-Different Haskell implementations have different characteristics with-regard to which operations block /all/ threads.--Using GHC without the @-threaded@ option, all foreign calls will block-all other Haskell threads in the system, although I\/O operations will-not.  With the @-threaded@ option, only foreign calls with the @unsafe@-attribute will block all other threads.---}---- | fork a thread and call the supplied function when the thread is about--- to terminate, with an exception or a returned value.  The function is--- called with asynchronous exceptions masked.------ > forkFinally action and_then =--- >   mask $ \restore ->--- >     forkIO $ try (restore action) >>= and_then------ This function is useful for informing the parent when a child--- terminates, for example.------ @since 4.6.0.0-forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId-forkFinally action and_then =-  mask $ \restore ->-    forkIO $ try (restore action) >>= and_then---- ------------------------------------------------------------------------------ Bound Threads--{- $boundthreads-   #boundthreads#--Support for multiple operating system threads and bound threads as described-below is currently only available in the GHC runtime system if you use the-/-threaded/ option when linking.--Other Haskell systems do not currently support multiple operating system threads.--A bound thread is a haskell thread that is /bound/ to an operating system-thread. While the bound thread is still scheduled by the Haskell run-time-system, the operating system thread takes care of all the foreign calls made-by the bound thread.--To a foreign library, the bound thread will look exactly like an ordinary-operating system thread created using OS functions like @pthread_create@-or @CreateThread@.--Bound threads can be created using the 'forkOS' function below. All foreign-exported functions are run in a bound thread (bound to the OS thread that-called the function). Also, the @main@ action of every Haskell program is-run in a bound thread.--Why do we need this? Because if a foreign library is called from a thread-created using 'forkIO', it won't have access to any /thread-local state/ --state variables that have specific values for each OS thread-(see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some-libraries (OpenGL, for example) will not work from a thread created using-'forkIO'. They work fine in threads created using 'forkOS' or when called-from @main@ or from a @foreign export@.--In terms of performance, 'forkOS' (aka bound) threads are much more-expensive than 'forkIO' (aka unbound) threads, because a 'forkOS'-thread is tied to a particular OS thread, whereas a 'forkIO' thread-can be run by any OS thread.  Context-switching between a 'forkOS'-thread and a 'forkIO' thread is many times more expensive than between-two 'forkIO' threads.--Note in particular that the main program thread (the thread running-@Main.main@) is always a bound thread, so for good concurrency-performance you should ensure that the main thread is not doing-repeated communication with other threads in the system.  Typically-this means forking subthreads to do the work using 'forkIO', and-waiting for the results in the main thread.---}---- | 'True' if bound threads are supported.--- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound'--- will always return 'False' and both 'forkOS' and 'runInBoundThread' will--- fail.-foreign import ccall rtsSupportsBoundThreads :: Bool---{- |-Like 'forkIO', this sparks off a new thread to run the 'IO'-computation passed as the first argument, and returns the 'ThreadId'-of the newly created thread.--However, 'forkOS' creates a /bound/ thread, which is necessary if you-need to call foreign (non-Haskell) libraries that make use of-thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads").--Using 'forkOS' instead of 'forkIO' makes no difference at all to the-scheduling behaviour of the Haskell runtime system.  It is a common-misconception that you need to use 'forkOS' instead of 'forkIO' to-avoid blocking all the Haskell threads when making a foreign call;-this isn't the case.  To allow foreign calls to be made without-blocking all the Haskell threads (with GHC), it is only necessary to-use the @-threaded@ option when linking your program, and to make sure-the foreign import is not marked @unsafe@.--}--forkOS :: IO () -> IO ThreadId--foreign export ccall forkOS_entry-    :: StablePtr (IO ()) -> IO ()--foreign import ccall "forkOS_entry" forkOS_entry_reimported-    :: StablePtr (IO ()) -> IO ()--forkOS_entry :: StablePtr (IO ()) -> IO ()-forkOS_entry stableAction = do-        action <- deRefStablePtr stableAction-        action--foreign import ccall forkOS_createThread-    :: StablePtr (IO ()) -> IO CInt--failNonThreaded :: IO a-failNonThreaded = fail $ "RTS doesn't support multiple OS threads "-                       ++"(use ghc -threaded when linking)"--forkOS action0-    | rtsSupportsBoundThreads = do-        mv <- newEmptyMVar-        b <- Exception.getMaskingState-        let-            -- async exceptions are masked in the child if they are masked-            -- in the parent, as for forkIO (see #1048). forkOS_createThread-            -- creates a thread with exceptions masked by default.-            action1 = case b of-                        Unmasked -> unsafeUnmask action0-                        MaskedInterruptible -> action0-                        MaskedUninterruptible -> uninterruptibleMask_ action0--            action_plus = Exception.catch action1 childHandler--        entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus)-        err <- forkOS_createThread entry-        when (err /= 0) $ fail "Cannot create OS thread."-        tid <- takeMVar mv-        freeStablePtr entry-        return tid-    | otherwise = failNonThreaded---- | Returns 'True' if the calling thread is /bound/, that is, if it is--- safe to use foreign libraries that rely on thread-local state from the--- calling thread.-isCurrentThreadBound :: IO Bool-isCurrentThreadBound = IO $ \ s# ->-    case isCurrentThreadBound# s# of-        (# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #)---{- |-Run the 'IO' computation passed as the first argument. If the calling thread-is not /bound/, a bound thread is created temporarily. @runInBoundThread@-doesn't finish until the 'IO' computation finishes.--You can wrap a series of foreign function calls that rely on thread-local state-with @runInBoundThread@ so that you can use them without knowing whether the-current thread is /bound/.--}-runInBoundThread :: IO a -> IO a--runInBoundThread action-    | rtsSupportsBoundThreads = do-        bound <- isCurrentThreadBound-        if bound-            then action-            else do-                ref <- newIORef undefined-                let action_plus = Exception.try action >>= writeIORef ref-                bracket (newStablePtr action_plus)-                        freeStablePtr-                        (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>=-                  unsafeResult-    | otherwise = failNonThreaded--{- |-Run the 'IO' computation passed as the first argument. If the calling thread-is /bound/, an unbound thread is created temporarily using 'forkIO'.-@runInBoundThread@ doesn't finish until the 'IO' computation finishes.--Use this function /only/ in the rare case that you have actually observed a-performance loss due to the use of bound threads. A program that-doesn't need its main thread to be bound and makes /heavy/ use of concurrency-(e.g. a web server), might want to wrap its @main@ action in-@runInUnboundThread@.--Note that exceptions which are thrown to the current thread are thrown in turn-to the thread that is executing the given computation. This ensures there's-always a way of killing the forked thread.--}-runInUnboundThread :: IO a -> IO a--runInUnboundThread action = do-  bound <- isCurrentThreadBound-  if bound-    then do-      mv <- newEmptyMVar-      mask $ \restore -> do-        tid <- forkIO $ Exception.try (restore action) >>= putMVar mv-        let wait = takeMVar mv `Exception.catch` \(e :: SomeException) ->-                     Exception.throwTo tid e >> wait-        wait >>= unsafeResult-    else action--unsafeResult :: Either SomeException a -> IO a-unsafeResult = either Exception.throwIO return---- ------------------------------------------------------------------------------ threadWaitRead/threadWaitWrite---- | Block the current thread until data is available to read on the--- given file descriptor (GHC only).------ This will throw an 'IOError' if the file descriptor was closed--- while this thread was blocked.  To safely close a file descriptor--- that has been used with 'threadWaitRead', use--- 'GHC.Conc.closeFdWith'.-threadWaitRead :: Fd -> IO ()-threadWaitRead fd-#ifdef mingw32_HOST_OS-  -- we have no IO manager implementing threadWaitRead on Windows.-  -- fdReady does the right thing, but we have to call it in a-  -- separate thread, otherwise threadWaitRead won't be interruptible,-  -- and this only works with -threaded.-  | threaded  = withThread (waitFd fd 0)-  | otherwise = case fd of-                  0 -> do _ <- hWaitForInput stdin (-1)-                          return ()-                        -- hWaitForInput does work properly, but we can only-                        -- do this for stdin since we know its FD.-                  _ -> error "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput"-#else-  = GHC.Conc.threadWaitRead fd-#endif---- | Block the current thread until data can be written to the--- given file descriptor (GHC only).------ This will throw an 'IOError' if the file descriptor was closed--- while this thread was blocked.  To safely close a file descriptor--- that has been used with 'threadWaitWrite', use--- 'GHC.Conc.closeFdWith'.-threadWaitWrite :: Fd -> IO ()-threadWaitWrite fd-#ifdef mingw32_HOST_OS-  | threaded  = withThread (waitFd fd 1)-  | otherwise = error "threadWaitWrite requires -threaded on Windows"-#else-  = GHC.Conc.threadWaitWrite fd-#endif---- | Returns an STM action that can be used to wait for data--- to read from a file descriptor. The second returned value--- is an IO action that can be used to deregister interest--- in the file descriptor.------ @since 4.7.0.0-threadWaitReadSTM :: Fd -> IO (STM (), IO ())-threadWaitReadSTM fd-#ifdef mingw32_HOST_OS-  | threaded = do v <- newTVarIO Nothing-                  mask_ $ void $ forkIO $ do result <- try (waitFd fd 0)-                                             atomically (writeTVar v $ Just result)-                  let waitAction = do result <- readTVar v-                                      case result of-                                        Nothing         -> retry-                                        Just (Right ()) -> return ()-                                        Just (Left e)   -> throwSTM (e :: IOException)-                  let killAction = return ()-                  return (waitAction, killAction)-  | otherwise = error "threadWaitReadSTM requires -threaded on Windows"-#else-  = GHC.Conc.threadWaitReadSTM fd-#endif---- | Returns an STM action that can be used to wait until data--- can be written to a file descriptor. The second returned value--- is an IO action that can be used to deregister interest--- in the file descriptor.------ @since 4.7.0.0-threadWaitWriteSTM :: Fd -> IO (STM (), IO ())-threadWaitWriteSTM fd-#ifdef mingw32_HOST_OS-  | threaded = do v <- newTVarIO Nothing-                  mask_ $ void $ forkIO $ do result <- try (waitFd fd 1)-                                             atomically (writeTVar v $ Just result)-                  let waitAction = do result <- readTVar v-                                      case result of-                                        Nothing         -> retry-                                        Just (Right ()) -> return ()-                                        Just (Left e)   -> throwSTM (e :: IOException)-                  let killAction = return ()-                  return (waitAction, killAction)-  | otherwise = error "threadWaitWriteSTM requires -threaded on Windows"-#else-  = GHC.Conc.threadWaitWriteSTM fd-#endif--#ifdef mingw32_HOST_OS-foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool--withThread :: IO a -> IO a-withThread io = do-  m <- newEmptyMVar-  _ <- mask_ $ forkIO $ try io >>= putMVar m-  x <- takeMVar m-  case x of-    Right a -> return a-    Left e  -> throwIO (e :: IOException)--waitFd :: Fd -> CInt -> IO ()-waitFd fd write = do-   throwErrnoIfMinus1_ "fdReady" $-        fdReady (fromIntegral fd) write iNFINITE 0--iNFINITE :: CInt-iNFINITE = 0xFFFFFFFF -- urgh--foreign import ccall safe "fdReady"-  fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt-#endif---- ------------------------------------------------------------------------------ More docs--{- $osthreads--      #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and-      are managed entirely by the GHC runtime.  Typically Haskell-      threads are an order of magnitude or two more efficient (in-      terms of both time and space) than operating system threads.--      The downside of having lightweight threads is that only one can-      run at a time, so if one thread blocks in a foreign call, for-      example, the other threads cannot continue.  The GHC runtime-      works around this by making use of full OS threads where-      necessary.  When the program is built with the @-threaded@-      option (to link against the multithreaded version of the-      runtime), a thread making a @safe@ foreign call will not block-      the other threads in the system; another OS thread will take-      over running Haskell threads until the original call returns.-      The runtime maintains a pool of these /worker/ threads so that-      multiple Haskell threads can be involved in external calls-      simultaneously.--      The "System.IO" library manages multiplexing in its own way.  On-      Windows systems it uses @safe@ foreign calls to ensure that-      threads doing I\/O operations don't block the whole runtime,-      whereas on Unix systems all the currently blocked I\/O requests-      are managed by a single thread (the /IO manager thread/) using-      a mechanism such as @epoll@ or @kqueue@, depending on what is-      provided by the host operating system.--      The runtime will run a Haskell thread using any of the available-      worker OS threads.  If you need control over which particular OS-      thread is used to run a given Haskell thread, perhaps because-      you need to call a foreign library that uses OS-thread-local-      state, then you need bound threads (see "Control.Concurrent#boundthreads").--      If you don't use the @-threaded@ option, then the runtime does-      not make use of multiple OS threads.  Foreign calls will block-      all other running Haskell threads until the call returns.  The-      "System.IO" library still does multiplexing, so there can be multiple-      threads doing I\/O, and this is handled internally by the runtime using-      @select@.--}--{- $termination--      In a standalone GHC program, only the main thread is-      required to terminate in order for the process to terminate.-      Thus all other forked threads will simply terminate at the same-      time as the main thread (the terminology for this kind of-      behaviour is \"daemonic threads\").--      If you want the program to wait for child threads to-      finish before exiting, you need to program this yourself.  A-      simple mechanism is to have each child thread write to an-      'MVar' when it completes, and have the main-      thread wait on all the 'MVar's before-      exiting:-->   myForkIO :: IO () -> IO (MVar ())->   myForkIO io = do->     mvar <- newEmptyMVar->     forkFinally io (\_ -> putMVar mvar ())->     return mvar--      Note that we use 'forkFinally' to make sure that the-      'MVar' is written to even if the thread dies or-      is killed for some reason.--      A better method is to keep a global list of all child-      threads which we should wait for at the end of the program:-->    children :: MVar [MVar ()]->    children = unsafePerformIO (newMVar [])->->    waitForChildren :: IO ()->    waitForChildren = do->      cs <- takeMVar children->      case cs of->        []   -> return ()->        m:ms -> do->           putMVar children ms->           takeMVar m->           waitForChildren->->    forkChild :: IO () -> IO ThreadId->    forkChild io = do->        mvar <- newEmptyMVar->        childs <- takeMVar children->        putMVar children (mvar:childs)->        forkFinally io (\_ -> putMVar mvar ())->->     main =->       later waitForChildren $->       ...--      The main thread principle also applies to calls to Haskell from-      outside, using @foreign export@.  When the @foreign export@ed-      function is invoked, it starts a new main thread, and it returns-      when this main thread terminates.  If the call causes new-      threads to be forked, they may remain in the system after the-      @foreign export@ed function has returned.--}--{- $preemption--      GHC implements pre-emptive multitasking: the execution of-      threads are interleaved in a random fashion.  More specifically,-      a thread may be pre-empted whenever it allocates some memory,-      which unfortunately means that tight loops which do no-      allocation tend to lock out other threads (this only seems to-      happen with pathological benchmark-style code, however).--      The rescheduling timer runs on a 20ms granularity by-      default, but this may be altered using the-      @-i\<n\>@ RTS option.  After a rescheduling-      \"tick\" the running thread is pre-empted as soon as-      possible.--      One final note: the-      @aaaa@ @bbbb@ example may not-      work too well on GHC (see Scheduling, above), due-      to the locking on a 'System.IO.Handle'.  Only one thread-      may hold the lock on a 'System.IO.Handle' at any one-      time, so if a reschedule happens while a thread is holding the-      lock, the other thread won't be able to run.  The upshot is that-      the switch from @aaaa@ to-      @bbbbb@ happens infrequently.  It can be-      improved by lowering the reschedule tick period.  We also have a-      patch that causes a reschedule whenever a thread waiting on a-      lock is woken up, but haven't found it to be useful for anything-      other than this example :-)--}--{- $deadlock--GHC attempts to detect when threads are deadlocked using the garbage-collector.  A thread that is not reachable (cannot be found by-following pointers from live objects) must be deadlocked, and in this-case the thread is sent an exception.  The exception is either-'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM',-'NonTermination', or 'Deadlock', depending on the way in which the-thread is deadlocked.--Note that this feature is intended for debugging, and should not be-relied on for the correct operation of your program.  There is no-guarantee that the garbage collector will be accurate enough to detect-your deadlock, and no guarantee that the garbage collector will run in-a timely enough manner.  Basically, the same caveats as for finalizers-apply to deadlock detection.--There is a subtle interaction between deadlock detection and-finalizers (as created by 'Foreign.Concurrent.newForeignPtr' or the-functions in "System.Mem.Weak"): if a thread is blocked waiting for a-finalizer to run, then the thread will be considered deadlocked and-sent an exception.  So preferably don't do this, but if you have no-alternative then it is possible to prevent the thread from being-considered deadlocked by making a 'StablePtr' pointing to it.  Don't-forget to release the 'StablePtr' later with 'freeStablePtr'.--}
− Control/Concurrent/Chan.hs
@@ -1,162 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP #-}-{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Concurrent.Chan--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (concurrency)------ Unbounded channels.-----------------------------------------------------------------------------------module Control.Concurrent.Chan-  ( -          -- * The 'Chan' type-        Chan,                   -- abstract--          -- * Operations-        newChan,-        writeChan,-        readChan,-        dupChan,-        unGetChan,-        isEmptyChan,--          -- * Stream interface-        getChanContents,-        writeList2Chan,-   ) where--import System.IO.Unsafe         ( unsafeInterleaveIO )-import Control.Concurrent.MVar-import Control.Exception (mask_)-import Data.Typeable--#define _UPK_(x) {-# UNPACK #-} !(x)---- A channel is represented by two @MVar@s keeping track of the two ends--- of the channel contents,i.e.,  the read- and write ends. Empty @MVar@s--- are used to handle consumers trying to read from an empty channel.---- |'Chan' is an abstract type representing an unbounded FIFO channel.-data Chan a- = Chan _UPK_(MVar (Stream a))-        _UPK_(MVar (Stream a)) -- Invariant: the Stream a is always an empty MVar-   deriving (Eq,Typeable)--type Stream a = MVar (ChItem a)--data ChItem a = ChItem a _UPK_(Stream a)-  -- benchmarks show that unboxing the MVar here is worthwhile, because-  -- although it leads to higher allocation, the channel data takes up-  -- less space and is therefore quicker to GC.---- See the Concurrent Haskell paper for a diagram explaining the--- how the different channel operations proceed.---- @newChan@ sets up the read and write end of a channel by initialising--- these two @MVar@s with an empty @MVar@.---- |Build and returns a new instance of 'Chan'.-newChan :: IO (Chan a)-newChan = do-   hole  <- newEmptyMVar-   readVar  <- newMVar hole-   writeVar <- newMVar hole-   return (Chan readVar writeVar)---- To put an element on a channel, a new hole at the write end is created.--- What was previously the empty @MVar@ at the back of the channel is then--- filled in with a new stream element holding the entered value and the--- new hole.---- |Write a value to a 'Chan'.-writeChan :: Chan a -> a -> IO ()-writeChan (Chan _ writeVar) val = do-  new_hole <- newEmptyMVar-  mask_ $ do-    old_hole <- takeMVar writeVar-    putMVar old_hole (ChItem val new_hole)-    putMVar writeVar new_hole---- The reason we don't simply do this:------    modifyMVar_ writeVar $ \old_hole -> do---      putMVar old_hole (ChItem val new_hole)---      return new_hole------ is because if an asynchronous exception is received after the 'putMVar'--- completes and before modifyMVar_ installs the new value, it will set the--- Chan's write end to a filled hole.---- |Read the next value from the 'Chan'.-readChan :: Chan a -> IO a-readChan (Chan readVar _) = do-  modifyMVarMasked readVar $ \read_end -> do -- Note [modifyMVarMasked]-    (ChItem val new_read_end) <- readMVar read_end-        -- Use readMVar here, not takeMVar,-        -- else dupChan doesn't work-    return (new_read_end, val)---- Note [modifyMVarMasked]--- This prevents a theoretical deadlock if an asynchronous exception--- happens during the readMVar while the MVar is empty.  In that case--- the read_end MVar will be left empty, and subsequent readers will--- deadlock.  Using modifyMVarMasked prevents this.  The deadlock can--- be reproduced, but only by expanding readMVar and inserting an--- artificial yield between its takeMVar and putMVar operations.----- |Duplicate a 'Chan': the duplicate channel begins empty, but data written to--- either channel from then on will be available from both.  Hence this creates--- a kind of broadcast channel, where data written by anyone is seen by--- everyone else.------ (Note that a duplicated channel is not equal to its original.--- So: @fmap (c /=) $ dupChan c@ returns @True@ for all @c@.)-dupChan :: Chan a -> IO (Chan a)-dupChan (Chan _ writeVar) = do-   hole       <- readMVar writeVar-   newReadVar <- newMVar hole-   return (Chan newReadVar writeVar)---- |Put a data item back onto a channel, where it will be the next item read.-unGetChan :: Chan a -> a -> IO ()-unGetChan (Chan readVar _) val = do-   new_read_end <- newEmptyMVar-   modifyMVar_ readVar $ \read_end -> do-     putMVar new_read_end (ChItem val read_end)-     return new_read_end-{-# DEPRECATED unGetChan "if you need this operation, use Control.Concurrent.STM.TChan instead.  See <http://ghc.haskell.org/trac/ghc/ticket/4154> for details" #-} -- deprecated in 7.0---- |Returns 'True' if the supplied 'Chan' is empty.-isEmptyChan :: Chan a -> IO Bool-isEmptyChan (Chan readVar writeVar) = do-   withMVar readVar $ \r -> do-     w <- readMVar writeVar-     let eq = r == w-     eq `seq` return eq-{-# DEPRECATED isEmptyChan "if you need this operation, use Control.Concurrent.STM.TChan instead.  See <http://ghc.haskell.org/trac/ghc/ticket/4154> for details" #-} -- deprecated in 7.0---- Operators for interfacing with functional streams.---- |Return a lazy list representing the contents of the supplied--- 'Chan', much like 'System.IO.hGetContents'.-getChanContents :: Chan a -> IO [a]-getChanContents ch-  = unsafeInterleaveIO (do-        x  <- readChan ch-        xs <- getChanContents ch-        return (x:xs)-    )---- |Write an entire list of items to a 'Chan'.-writeList2Chan :: Chan a -> [a] -> IO ()-writeList2Chan ch ls = sequence_ (map (writeChan ch) ls)
− Control/Concurrent/MVar.hs
@@ -1,274 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, UnboxedTuples, MagicHash #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Concurrent.MVar--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (concurrency)------ An @'MVar' t@ is mutable location that is either empty or contains a--- value of type @t@.  It has two fundamental operations: 'putMVar'--- which fills an 'MVar' if it is empty and blocks otherwise, and--- 'takeMVar' which empties an 'MVar' if it is full and blocks--- otherwise.  They can be used in multiple different ways:------   1. As synchronized mutable variables,------   2. As channels, with 'takeMVar' and 'putMVar' as receive and send, and------   3. As a binary semaphore @'MVar' ()@, with 'takeMVar' and 'putMVar' as---      wait and signal.------ They were introduced in the paper--- <http://research.microsoft.com/~simonpj/papers/concurrent-haskell.ps.gz "Concurrent Haskell">--- by Simon Peyton Jones, Andrew Gordon and Sigbjorn Finne, though--- some details of their implementation have since then changed (in--- particular, a put on a full 'MVar' used to error, but now merely--- blocks.)------ === Applicability------ 'MVar's offer more flexibility than 'IORef's, but less flexibility--- than 'STM'.  They are appropriate for building synchronization--- primitives and performing simple interthread communication; however--- they are very simple and susceptible to race conditions, deadlocks or--- uncaught exceptions.  Do not use them if you need perform larger--- atomic operations such as reading from multiple variables: use 'STM'--- instead.------ In particular, the "bigger" functions in this module ('readMVar',--- 'swapMVar', 'withMVar', 'modifyMVar_' and 'modifyMVar') are simply--- the composition of a 'takeMVar' followed by a 'putMVar' with--- exception safety.--- These only have atomicity guarantees if all other threads--- perform a 'takeMVar' before a 'putMVar' as well;  otherwise, they may--- block.------ === Fairness------ No thread can be blocked indefinitely on an 'MVar' unless another--- thread holds that 'MVar' indefinitely.  One usual implementation of--- this fairness guarantee is that threads blocked on an 'MVar' are--- served in a first-in-first-out fashion, but this is not guaranteed--- in the semantics.------ === Gotchas------ Like many other Haskell data structures, 'MVar's are lazy.  This--- means that if you place an expensive unevaluated thunk inside an--- 'MVar', it will be evaluated by the thread that consumes it, not the--- thread that produced it.  Be sure to 'evaluate' values to be placed--- in an 'MVar' to the appropriate normal form, or utilize a strict--- MVar provided by the strict-concurrency package.------ === Ordering------ 'MVar' operations are always observed to take place in the order--- they are written in the program, regardless of the memory model of--- the underlying machine.  This is in contrast to 'IORef' operations--- which may appear out-of-order to another thread in some cases.------ === Example------ Consider the following concurrent data structure, a skip channel.--- This is a channel for an intermittent source of high bandwidth--- information (for example, mouse movement events.)  Writing to the--- channel never blocks, and reading from the channel only returns the--- most recent value, or blocks if there are no new values.  Multiple--- readers are supported with a @dupSkipChan@ operation.------ A skip channel is a pair of 'MVar's. The first 'MVar' contains the--- current value, and a list of semaphores that need to be notified--- when it changes. The second 'MVar' is a semaphore for this particular--- reader: it is full if there is a value in the channel that this--- reader has not read yet, and empty otherwise.------ @---     data SkipChan a = SkipChan (MVar (a, [MVar ()])) (MVar ())------     newSkipChan :: IO (SkipChan a)---     newSkipChan = do---         sem <- newEmptyMVar---         main <- newMVar (undefined, [sem])---         return (SkipChan main sem)------     putSkipChan :: SkipChan a -> a -> IO ()---     putSkipChan (SkipChan main _) v = do---         (_, sems) <- takeMVar main---         putMVar main (v, [])---         mapM_ (\sem -> putMVar sem ()) sems------     getSkipChan :: SkipChan a -> IO a---     getSkipChan (SkipChan main sem) = do---         takeMVar sem---         (v, sems) <- takeMVar main---         putMVar main (v, sem:sems)---         return v------     dupSkipChan :: SkipChan a -> IO (SkipChan a)---     dupSkipChan (SkipChan main _) = do---         sem <- newEmptyMVar---         (v, sems) <- takeMVar main---         putMVar main (v, sem:sems)---         return (SkipChan main sem)--- @------ This example was adapted from the original Concurrent Haskell paper.--- For more examples of 'MVar's being used to build higher-level--- synchronization primitives, see 'Control.Concurrent.Chan' and--- 'Control.Concurrent.QSem'.-----------------------------------------------------------------------------------module Control.Concurrent.MVar-        (-          -- * @MVar@s-          MVar-        , newEmptyMVar-        , newMVar-        , takeMVar-        , putMVar-        , readMVar-        , swapMVar-        , tryTakeMVar-        , tryPutMVar-        , isEmptyMVar-        , withMVar-        , withMVarMasked-        , modifyMVar_-        , modifyMVar-        , modifyMVarMasked_-        , modifyMVarMasked-        , tryReadMVar-        , mkWeakMVar-        , addMVarFinalizer-    ) where--import GHC.MVar ( MVar(..), newEmptyMVar, newMVar, takeMVar, putMVar,-                  tryTakeMVar, tryPutMVar, isEmptyMVar, readMVar,-                  tryReadMVar-                )-import qualified GHC.MVar-import GHC.Weak-import GHC.Base--import Control.Exception.Base--{-|-  Take a value from an 'MVar', put a new value into the 'MVar' and-  return the value taken. This function is atomic only if there are-  no other producers for this 'MVar'.--}-swapMVar :: MVar a -> a -> IO a-swapMVar mvar new =-  mask_ $ do-    old <- takeMVar mvar-    putMVar mvar new-    return old--{-|-  'withMVar' is an exception-safe wrapper for operating on the contents-  of an 'MVar'.  This operation is exception-safe: it will replace the-  original contents of the 'MVar' if an exception is raised (see-  "Control.Exception").  However, it is only atomic if there are no-  other producers for this 'MVar'.--}-{-# INLINE withMVar #-}--- inlining has been reported to have dramatic effects; see--- http://www.haskell.org//pipermail/haskell/2006-May/017907.html-withMVar :: MVar a -> (a -> IO b) -> IO b-withMVar m io =-  mask $ \restore -> do-    a <- takeMVar m-    b <- restore (io a) `onException` putMVar m a-    putMVar m a-    return b--{-|-  Like 'withMVar', but the @IO@ action in the second argument is executed-  with asynchronous exceptions masked.--  @since 4.7.0.0--}-{-# INLINE withMVarMasked #-}-withMVarMasked :: MVar a -> (a -> IO b) -> IO b-withMVarMasked m io =-  mask_ $ do-    a <- takeMVar m-    b <- io a `onException` putMVar m a-    putMVar m a-    return b--{-|-  An exception-safe wrapper for modifying the contents of an 'MVar'.-  Like 'withMVar', 'modifyMVar' will replace the original contents of-  the 'MVar' if an exception is raised during the operation.  This-  function is only atomic if there are no other producers for this-  'MVar'.--}-{-# INLINE modifyMVar_ #-}-modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()-modifyMVar_ m io =-  mask $ \restore -> do-    a  <- takeMVar m-    a' <- restore (io a) `onException` putMVar m a-    putMVar m a'--{-|-  A slight variation on 'modifyMVar_' that allows a value to be-  returned (@b@) in addition to the modified value of the 'MVar'.--}-{-# INLINE modifyMVar #-}-modifyMVar :: MVar a -> (a -> IO (a,b)) -> IO b-modifyMVar m io =-  mask $ \restore -> do-    a      <- takeMVar m-    (a',b) <- restore (io a >>= evaluate) `onException` putMVar m a-    putMVar m a'-    return b--{-|-  Like 'modifyMVar_', but the @IO@ action in the second argument is executed with-  asynchronous exceptions masked.--  @since 4.6.0.0--}-{-# INLINE modifyMVarMasked_ #-}-modifyMVarMasked_ :: MVar a -> (a -> IO a) -> IO ()-modifyMVarMasked_ m io =-  mask_ $ do-    a  <- takeMVar m-    a' <- io a `onException` putMVar m a-    putMVar m a'--{-|-  Like 'modifyMVar', but the @IO@ action in the second argument is executed with-  asynchronous exceptions masked.--  @since 4.6.0.0--}-{-# INLINE modifyMVarMasked #-}-modifyMVarMasked :: MVar a -> (a -> IO (a,b)) -> IO b-modifyMVarMasked m io =-  mask_ $ do-    a      <- takeMVar m-    (a',b) <- (io a >>= evaluate) `onException` putMVar m a-    putMVar m a'-    return b--{-# DEPRECATED addMVarFinalizer "use 'mkWeakMVar' instead" #-} -- deprecated in 7.6-addMVarFinalizer :: MVar a -> IO () -> IO ()-addMVarFinalizer = GHC.MVar.addMVarFinalizer---- | Make a 'Weak' pointer to an 'MVar', using the second argument as--- a finalizer to run when 'MVar' is garbage-collected------ @since 4.6.0.0-mkWeakMVar :: MVar a -> IO () -> IO (Weak (MVar a))-mkWeakMVar m@(MVar m#) f = IO $ \s ->-  case mkWeak# m# m f s of (# s1, w #) -> (# s1, Weak w #)
− Control/Concurrent/QSem.hs
@@ -1,130 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE AutoDeriveTypeable, BangPatterns #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Concurrent.QSem--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (concurrency)------ Simple quantity semaphores.-----------------------------------------------------------------------------------module Control.Concurrent.QSem-        ( -- * Simple Quantity Semaphores-          QSem,         -- abstract-          newQSem,      -- :: Int  -> IO QSem-          waitQSem,     -- :: QSem -> IO ()-          signalQSem    -- :: QSem -> IO ()-        ) where--import Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar, tryTakeMVar-                          , putMVar, newMVar, tryPutMVar)-import Control.Exception-import Data.Maybe---- | 'QSem' is a quantity semaphore in which the resource is aqcuired--- and released in units of one. It provides guaranteed FIFO ordering--- for satisfying blocked `waitQSem` calls.------ The pattern------ >   bracket_ waitQSem signalQSem (...)------ is safe; it never loses a unit of the resource.----data QSem = QSem !(MVar (Int, [MVar ()], [MVar ()]))---- The semaphore state (i, xs, ys):------   i is the current resource value------   (xs,ys) is the queue of blocked threads, where the queue is---           given by xs ++ reverse ys.  We can enqueue new blocked threads---           by consing onto ys, and dequeue by removing from the head of xs.------ A blocked thread is represented by an empty (MVar ()).  To unblock--- the thread, we put () into the MVar.------ A thread can dequeue itself by also putting () into the MVar, which--- it must do if it receives an exception while blocked in waitQSem.--- This means that when unblocking a thread in signalQSem we must--- first check whether the MVar is already full; the MVar lock on the--- semaphore itself resolves race conditions between signalQSem and a--- thread attempting to dequeue itself.---- |Build a new 'QSem' with a supplied initial quantity.---  The initial quantity must be at least 0.-newQSem :: Int -> IO QSem-newQSem initial-  | initial < 0 = fail "newQSem: Initial quantity must be non-negative"-  | otherwise   = do-      sem <- newMVar (initial, [], [])-      return (QSem sem)---- |Wait for a unit to become available-waitQSem :: QSem -> IO ()-waitQSem (QSem m) =-  mask_ $ do-    (i,b1,b2) <- takeMVar m-    if i == 0-       then do-         b <- newEmptyMVar-         putMVar m (i, b1, b:b2)-         wait b-       else do-         let !z = i-1-         putMVar m (z, b1, b2)-         return ()-  where-    wait b = takeMVar b `onException` do-                (uninterruptibleMask_ $ do -- Note [signal uninterruptible]-                   (i,b1,b2) <- takeMVar m-                   r <- tryTakeMVar b-                   r' <- if isJust r-                            then signal (i,b1,b2)-                            else do putMVar b (); return (i,b1,b2)-                   putMVar m r')---- |Signal that a unit of the 'QSem' is available-signalQSem :: QSem -> IO ()-signalQSem (QSem m) =-  uninterruptibleMask_ $ do -- Note [signal uninterruptible]-    r <- takeMVar m-    r' <- signal r-    putMVar m r'---- Note [signal uninterruptible]------   If we have------      bracket waitQSem signalQSem (...)------   and an exception arrives at the signalQSem, then we must not lose---   the resource.  The signalQSem is masked by bracket, but taking---   the MVar might block, and so it would be interruptible.  Hence we---   need an uninterruptibleMask here.------   This isn't ideal: during high contention, some threads won't be---   interruptible.  The QSemSTM implementation has better behaviour---   here, but it performs much worse than this one in some---   benchmarks.--signal :: (Int,[MVar ()],[MVar ()]) -> IO (Int,[MVar ()],[MVar ()])-signal (i,a1,a2) =- if i == 0-   then loop a1 a2-   else let !z = i+1 in return (z, a1, a2)- where-   loop [] [] = return (1, [], [])-   loop [] b2 = loop (reverse b2) []-   loop (b:bs) b2 = do-     r <- tryPutMVar b ()-     if r then return (0, bs, b2)-          else loop bs b2
− Control/Concurrent/QSemN.hs
@@ -1,124 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE AutoDeriveTypeable, BangPatterns #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Concurrent.QSemN--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (concurrency)------ Quantity semaphores in which each thread may wait for an arbitrary--- \"amount\".-----------------------------------------------------------------------------------module Control.Concurrent.QSemN-        (  -- * General Quantity Semaphores-          QSemN,        -- abstract-          newQSemN,     -- :: Int   -> IO QSemN-          waitQSemN,    -- :: QSemN -> Int -> IO ()-          signalQSemN   -- :: QSemN -> Int -> IO ()-      ) where--import Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar, tryTakeMVar-                          , putMVar, newMVar-                          , tryPutMVar, isEmptyMVar)-import Data.Typeable-import Control.Exception-import Data.Maybe---- | 'QSemN' is a quantity semaphore in which the resource is aqcuired--- and released in units of one. It provides guaranteed FIFO ordering--- for satisfying blocked `waitQSemN` calls.------ The pattern------ >   bracket_ (waitQSemN n) (signalQSemN n) (...)------ is safe; it never loses any of the resource.----data QSemN = QSemN !(MVar (Int, [(Int, MVar ())], [(Int, MVar ())]))-  deriving Typeable---- The semaphore state (i, xs, ys):------   i is the current resource value------   (xs,ys) is the queue of blocked threads, where the queue is---           given by xs ++ reverse ys.  We can enqueue new blocked threads---           by consing onto ys, and dequeue by removing from the head of xs.------ A blocked thread is represented by an empty (MVar ()).  To unblock--- the thread, we put () into the MVar.------ A thread can dequeue itself by also putting () into the MVar, which--- it must do if it receives an exception while blocked in waitQSemN.--- This means that when unblocking a thread in signalQSemN we must--- first check whether the MVar is already full; the MVar lock on the--- semaphore itself resolves race conditions between signalQSemN and a--- thread attempting to dequeue itself.---- |Build a new 'QSemN' with a supplied initial quantity.---  The initial quantity must be at least 0.-newQSemN :: Int -> IO QSemN-newQSemN initial-  | initial < 0 = fail "newQSemN: Initial quantity must be non-negative"-  | otherwise   = do-      sem <- newMVar (initial, [], [])-      return (QSemN sem)---- |Wait for the specified quantity to become available-waitQSemN :: QSemN -> Int -> IO ()-waitQSemN (QSemN m) sz =-  mask_ $ do-    (i,b1,b2) <- takeMVar m-    let z = i-sz-    if z < 0-       then do-         b <- newEmptyMVar-         putMVar m (i, b1, (sz,b):b2)-         wait b-       else do-         putMVar m (z, b1, b2)-         return ()-  where-    wait b = do-        takeMVar b `onException`-                (uninterruptibleMask_ $ do -- Note [signal uninterruptible]-                   (i,b1,b2) <- takeMVar m-                   r <- tryTakeMVar b-                   r' <- if isJust r-                            then signal sz (i,b1,b2)-                            else do putMVar b (); return (i,b1,b2)-                   putMVar m r')---- |Signal that a given quantity is now available from the 'QSemN'.-signalQSemN :: QSemN -> Int -> IO ()-signalQSemN (QSemN m) sz = uninterruptibleMask_ $ do-  r <- takeMVar m-  r' <- signal sz r-  putMVar m r'--signal :: Int-       -> (Int,[(Int,MVar ())],[(Int,MVar ())])-       -> IO (Int,[(Int,MVar ())],[(Int,MVar ())])--signal sz0 (i,a1,a2) = loop (sz0 + i) a1 a2- where-   loop 0  bs b2 = return (0,  bs, b2)-   loop sz [] [] = return (sz, [], [])-   loop sz [] b2 = loop sz (reverse b2) []-   loop sz ((j,b):bs) b2-     | j > sz = do-       r <- isEmptyMVar b-       if r then return (sz, (j,b):bs, b2)-            else loop sz bs b2-     | otherwise = do-       r <- tryPutMVar b ()-       if r then loop (sz-j) bs b2-            else loop sz bs b2
− Control/Exception.hs
@@ -1,391 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, ExistentialQuantification #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Exception--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (extended exceptions)------ This module provides support for raising and catching both built-in--- and user-defined exceptions.------ In addition to exceptions thrown by 'IO' operations, exceptions may--- be thrown by pure code (imprecise exceptions) or by external events--- (asynchronous exceptions), but may only be caught in the 'IO' monad.--- For more details, see:------  * /A semantics for imprecise exceptions/, by Simon Peyton Jones,---    Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,---    in /PLDI'99/.------  * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton---    Jones, Andy Moran and John Reppy, in /PLDI'01/.------  * /An Extensible Dynamically-Typed Hierarchy of Exceptions/,---    by Simon Marlow, in /Haskell '06/.-----------------------------------------------------------------------------------module Control.Exception (--        -- * The Exception type-        SomeException(..),-        Exception(..),          -- class-        IOException,            -- instance Eq, Ord, Show, Typeable, Exception-        ArithException(..),     -- instance Eq, Ord, Show, Typeable, Exception-        ArrayException(..),     -- instance Eq, Ord, Show, Typeable, Exception-        AssertionFailed(..),-        SomeAsyncException(..),-        AsyncException(..),     -- instance Eq, Ord, Show, Typeable, Exception-        asyncExceptionToException, asyncExceptionFromException,--        NonTermination(..),-        NestedAtomically(..),-        BlockedIndefinitelyOnMVar(..),-        BlockedIndefinitelyOnSTM(..),-        AllocationLimitExceeded(..),-        Deadlock(..),-        NoMethodError(..),-        PatternMatchFail(..),-        RecConError(..),-        RecSelError(..),-        RecUpdError(..),-        ErrorCall(..),--        -- * Throwing exceptions-        throw,-        throwIO,-        ioError,-        throwTo,--        -- * Catching Exceptions--        -- $catching--        -- ** Catching all exceptions--        -- $catchall--        -- ** The @catch@ functions-        catch,-        catches, Handler(..),-        catchJust,--        -- ** The @handle@ functions-        handle,-        handleJust,--        -- ** The @try@ functions-        try,-        tryJust,--        -- ** The @evaluate@ function-        evaluate,--        -- ** The @mapException@ function-        mapException,--        -- * Asynchronous Exceptions--        -- $async--        -- ** Asynchronous exception control--        -- |The following functions allow a thread to control delivery of-        -- asynchronous exceptions during a critical region.--        mask,-        mask_,-        uninterruptibleMask,-        uninterruptibleMask_,-        MaskingState(..),-        getMaskingState,-        allowInterrupt,--        -- *** Applying @mask@ to an exception handler--        -- $block_handler--        -- *** Interruptible operations--        -- $interruptible--        -- * Assertions--        assert,--        -- * Utilities--        bracket,-        bracket_,-        bracketOnError,--        finally,-        onException,--  ) where--import Control.Exception.Base--import GHC.Base-import GHC.IO (unsafeUnmask)---- | You need this when using 'catches'.-data Handler a = forall e . Exception e => Handler (e -> IO a)--instance Functor Handler where-     fmap f (Handler h) = Handler (fmap f . h)--{- |-Sometimes you want to catch two different sorts of exception. You could-do something like--> f = expr `catch` \ (ex :: ArithException) -> handleArith ex->          `catch` \ (ex :: IOException)    -> handleIO    ex--However, there are a couple of problems with this approach. The first is-that having two exception handlers is inefficient. However, the more-serious issue is that the second exception handler will catch exceptions-in the first, e.g. in the example above, if @handleArith@ throws an-@IOException@ then the second exception handler will catch it.--Instead, we provide a function 'catches', which would be used thus:--> f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex),->                     Handler (\ (ex :: IOException)    -> handleIO    ex)]--}-catches :: IO a -> [Handler a] -> IO a-catches io handlers = io `catch` catchesHandler handlers--catchesHandler :: [Handler a] -> SomeException -> IO a-catchesHandler handlers e = foldr tryHandler (throw e) handlers-    where tryHandler (Handler handler) res-              = case fromException e of-                Just e' -> handler e'-                Nothing -> res---- -------------------------------------------------------------------------------- Catching exceptions--{- $catching--There are several functions for catching and examining-exceptions; all of them may only be used from within the-'IO' monad.--Here's a rule of thumb for deciding which catch-style function to-use:-- * If you want to do some cleanup in the event that an exception-   is raised, use 'finally', 'bracket' or 'onException'.-- * To recover after an exception and do something else, the best-   choice is to use one of the 'try' family.-- * ... unless you are recovering from an asynchronous exception, in which-   case use 'catch' or 'catchJust'.--The difference between using 'try' and 'catch' for recovery is that in-'catch' the handler is inside an implicit 'mask' (see \"Asynchronous-Exceptions\") which is important when catching asynchronous-exceptions, but when catching other kinds of exception it is-unnecessary.  Furthermore it is possible to accidentally stay inside-the implicit 'mask' by tail-calling rather than returning from the-handler, which is why we recommend using 'try' rather than 'catch' for-ordinary exception recovery.--A typical use of 'tryJust' for recovery looks like this:-->  do r <- tryJust (guard . isDoesNotExistError) $ getEnv "HOME"->     case r of->       Left  e    -> ...->       Right home -> ...---}---- -------------------------------------------------------------------------------- Asynchronous exceptions---- | When invoked inside 'mask', this function allows a masked--- asynchronous exception to be raised, if one exists.  It is--- equivalent to performing an interruptible operation (see--- #interruptible#), but does not involve any actual blocking.------ When called outside 'mask', or inside 'uninterruptibleMask', this--- function has no effect.------ @since 4.4.0.0-allowInterrupt :: IO ()-allowInterrupt = unsafeUnmask $ return ()--{- $async-- #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to-external influences, and can be raised at any point during execution.-'StackOverflow' and 'HeapOverflow' are two examples of-system-generated asynchronous exceptions.--The primary source of asynchronous exceptions, however, is-'throwTo':-->  throwTo :: ThreadId -> Exception -> IO ()--'throwTo' (also 'Control.Concurrent.killThread') allows one-running thread to raise an arbitrary exception in another thread.  The-exception is therefore asynchronous with respect to the target thread,-which could be doing anything at the time it receives the exception.-Great care should be taken with asynchronous exceptions; it is all too-easy to introduce race conditions by the over zealous use of-'throwTo'.--}--{- $block_handler-There\'s an implied 'mask' around every exception handler in a call-to one of the 'catch' family of functions.  This is because that is-what you want most of the time - it eliminates a common race condition-in starting an exception handler, because there may be no exception-handler on the stack to handle another exception if one arrives-immediately.  If asynchronous exceptions are masked on entering the-handler, though, we have time to install a new exception handler-before being interrupted.  If this weren\'t the default, one would have-to write something like-->      mask $ \restore ->->           catch (restore (...))->                 (\e -> handler)--If you need to unmask asynchronous exceptions again in the exception-handler, 'restore' can be used there too.--Note that 'try' and friends /do not/ have a similar default, because-there is no exception handler in this case.  Don't use 'try' for-recovering from an asynchronous exception.--}--{- $interruptible-- #interruptible#-Some operations are /interruptible/, which means that they can receive-asynchronous exceptions even in the scope of a 'mask'.  Any function-which may itself block is defined as interruptible; this includes-'Control.Concurrent.MVar.takeMVar'-(but not 'Control.Concurrent.MVar.tryTakeMVar'),-and most operations which perform-some I\/O with the outside world.  The reason for having-interruptible operations is so that we can write things like-->      mask $ \restore -> do->         a <- takeMVar m->         catch (restore (...))->               (\e -> ...)--if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,-then this particular-combination could lead to deadlock, because the thread itself would be-blocked in a state where it can\'t receive any asynchronous exceptions.-With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be-safe in the knowledge that the thread can receive exceptions right up-until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.-Similar arguments apply for other interruptible operations like-'System.IO.openFile'.--It is useful to think of 'mask' not as a way to completely prevent-asynchronous exceptions, but as a way to switch from asynchronous mode-to polling mode.  The main difficulty with asynchronous-exceptions is that they normally can occur anywhere, but within a-'mask' an asynchronous exception is only raised by operations that are-interruptible (or call other interruptible operations).  In many cases-these operations may themselves raise exceptions, such as I\/O errors,-so the caller will usually be prepared to handle exceptions arising from the-operation anyway.  To perfom an explicit poll for asynchronous exceptions-inside 'mask', use 'allowInterrupt'.--Sometimes it is too onerous to handle exceptions in the middle of a-critical piece of stateful code.  There are three ways to handle this-kind of situation:-- * Use STM.  Since a transaction is always either completely executed-   or not at all, transactions are a good way to maintain invariants-   over state in the presence of asynchronous (and indeed synchronous)-   exceptions.-- * Use 'mask', and avoid interruptible operations.  In order to do-   this, we have to know which operations are interruptible.  It is-   impossible to know for any given library function whether it might-   invoke an interruptible operation internally; so instead we give a-   list of guaranteed-not-to-be-interruptible operations below.-- * Use 'uninterruptibleMask'.  This is generally not recommended,-   unless you can guarantee that any interruptible operations invoked-   during the scope of 'uninterruptibleMask' can only ever block for-   a short time.  Otherwise, 'uninterruptibleMask' is a good way to-   make your program deadlock and be unresponsive to user interrupts.--The following operations are guaranteed not to be interruptible:-- * operations on 'IORef' from "Data.IORef"-- * STM transactions that do not use 'retry'-- * everything from the @Foreign@ modules-- * everything from @Control.Exception@ except for 'throwTo'-- * @tryTakeMVar@, @tryPutMVar@, @isEmptyMVar@-- * @takeMVar@ if the @MVar@ is definitely full, and conversely @putMVar@ if the @MVar@ is definitely empty-- * @newEmptyMVar@, @newMVar@-- * @forkIO@, @forkIOUnmasked@, @myThreadId@---}--{- $catchall--It is possible to catch all exceptions, by using the type 'SomeException':--> catch f (\e -> ... (e :: SomeException) ...)--HOWEVER, this is normally not what you want to do!--For example, suppose you want to read a file, but if it doesn't exist-then continue as if it contained \"\".  You might be tempted to just-catch all exceptions and return \"\" in the handler. However, this has-all sorts of undesirable consequences.  For example, if the user-presses control-C at just the right moment then the 'UserInterrupt'-exception will be caught, and the program will continue running under-the belief that the file contains \"\".  Similarly, if another thread-tries to kill the thread reading the file then the 'ThreadKilled'-exception will be ignored.--Instead, you should only catch exactly the exceptions that you really-want. In this case, this would likely be more specific than even-\"any IO exception\"; a permissions error would likely also want to be-handled differently. Instead, you would probably want something like:--> e <- tryJust (guard . isDoesNotExistError) (readFile f)-> let str = either (const "") id e--There are occassions when you really do need to catch any sort of-exception. However, in most cases this is just so you can do some-cleaning up; you aren't actually interested in the exception itself.-For example, if you open a file then you want to close it again,-whether processing the file executes normally or throws an exception.-However, in these cases you can use functions like 'bracket', 'finally'-and 'onException', which never actually pass you the exception, but-just call the cleanup functions at the appropriate points.--But sometimes you really do need to catch any exception, and actually-see what the exception is. One example is at the very top-level of a-program, you may wish to catch any exception, print it to a logfile or-the screen, and then exit gracefully. For these cases, you can use-'catch' (or one of the other exception-catching functions) with the-'SomeException' type.--}-
− Control/Exception/Base.hs
@@ -1,407 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash #-}-{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Exception.Base--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (extended exceptions)------ Extensible exceptions, except for multiple handlers.-----------------------------------------------------------------------------------module Control.Exception.Base (--        -- * The Exception type-        SomeException(..),-        Exception(..),-        IOException,-        ArithException(..),-        ArrayException(..),-        AssertionFailed(..),-        SomeAsyncException(..), AsyncException(..),-        asyncExceptionToException, asyncExceptionFromException,-        NonTermination(..),-        NestedAtomically(..),-        BlockedIndefinitelyOnMVar(..),-        BlockedIndefinitelyOnSTM(..),-        AllocationLimitExceeded(..),-        Deadlock(..),-        NoMethodError(..),-        PatternMatchFail(..),-        RecConError(..),-        RecSelError(..),-        RecUpdError(..),-        ErrorCall(..),--        -- * Throwing exceptions-        throwIO,-        throw,-        ioError,-        throwTo,--        -- * Catching Exceptions--        -- ** The @catch@ functions-        catch,-        catchJust,--        -- ** The @handle@ functions-        handle,-        handleJust,--        -- ** The @try@ functions-        try,-        tryJust,-        onException,--        -- ** The @evaluate@ function-        evaluate,--        -- ** The @mapException@ function-        mapException,--        -- * Asynchronous Exceptions--        -- ** Asynchronous exception control-        mask,-        mask_,-        uninterruptibleMask,-        uninterruptibleMask_,-        MaskingState(..),-        getMaskingState,--        -- * Assertions--        assert,--        -- * Utilities--        bracket,-        bracket_,-        bracketOnError,--        finally,--        -- * Calls for GHC runtime-        recSelError, recConError, irrefutPatError, runtimeError,-        nonExhaustiveGuardsError, patError, noMethodBindingError,-        absentError,-        nonTermination, nestedAtomically,-  ) where--import GHC.Base-import GHC.IO hiding (bracket,finally,onException)-import GHC.IO.Exception-import GHC.Exception-import GHC.Show--- import GHC.Exception hiding ( Exception )-import GHC.Conc.Sync--import Data.Dynamic-import Data.Either---------------------------------------------------------------------------------- Catching exceptions---- |This is the simplest of the exception-catching functions.  It--- takes a single argument, runs it, and if an exception is raised--- the \"handler\" is executed, with the value of the exception passed as an--- argument.  Otherwise, the result is returned as normal.  For example:------ >   catch (readFile f)--- >         (\e -> do let err = show (e :: IOException)--- >                   hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)--- >                   return "")------ Note that we have to give a type signature to @e@, or the program--- will not typecheck as the type is ambiguous. While it is possible--- to catch exceptions of any type, see the section \"Catching all--- exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.------ For catching exceptions in pure (non-'IO') expressions, see the--- function 'evaluate'.------ Note that due to Haskell\'s unspecified evaluation order, an--- expression may throw one of several possible exceptions: consider--- the expression @(error \"urk\") + (1 \`div\` 0)@.  Does--- the expression throw--- @ErrorCall \"urk\"@, or @DivideByZero@?------ The answer is \"it might throw either\"; the choice is--- non-deterministic. If you are catching any type of exception then you--- might catch either. If you are calling @catch@ with type--- @IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may--- get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@--- exception may be propogated further up. If you call it again, you--- might get a the opposite behaviour. This is ok, because 'catch' is an--- 'IO' computation.----catch   :: Exception e-        => IO a         -- ^ The computation to run-        -> (e -> IO a)  -- ^ Handler to invoke if an exception is raised-        -> IO a-catch = catchException---- | The function 'catchJust' is like 'catch', but it takes an extra--- argument which is an /exception predicate/, a function which--- selects which type of exceptions we\'re interested in.------ > catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)--- >           (readFile f)--- >           (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)--- >                     return "")------ Any other exceptions which are not matched by the predicate--- are re-raised, and may be caught by an enclosing--- 'catch', 'catchJust', etc.-catchJust-        :: Exception e-        => (e -> Maybe b)         -- ^ Predicate to select exceptions-        -> IO a                   -- ^ Computation to run-        -> (b -> IO a)            -- ^ Handler-        -> IO a-catchJust p a handler = catch a handler'-  where handler' e = case p e of-                        Nothing -> throwIO e-                        Just b  -> handler b---- | A version of 'catch' with the arguments swapped around; useful in--- situations where the code for the handler is shorter.  For example:------ >   do handle (\NonTermination -> exitWith (ExitFailure 1)) $--- >      ...-handle     :: Exception e => (e -> IO a) -> IO a -> IO a-handle     =  flip catch---- | A version of 'catchJust' with the arguments swapped around (see--- 'handle').-handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a-handleJust p =  flip (catchJust p)---------------------------------------------------------------------------------- 'mapException'---- | This function maps one exception into another as proposed in the--- paper \"A semantics for imprecise exceptions\".---- Notice that the usage of 'unsafePerformIO' is safe here.--mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a-mapException f v = unsafePerformIO (catch (evaluate v)-                                          (\x -> throwIO (f x)))---------------------------------------------------------------------------------- 'try' and variations.---- | Similar to 'catch', but returns an 'Either' result which is--- @('Right' a)@ if no exception of type @e@ was raised, or @('Left' ex)@--- if an exception of type @e@ was raised and its value is @ex@.--- If any other type of exception is raised than it will be propogated--- up to the next enclosing exception handler.------ >  try a = catch (Right `liftM` a) (return . Left)--try :: Exception e => IO a -> IO (Either e a)-try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))---- | A variant of 'try' that takes an exception predicate to select--- which exceptions are caught (c.f. 'catchJust').  If the exception--- does not match the predicate, it is re-thrown.-tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)-tryJust p a = do-  r <- try a-  case r of-        Right v -> return (Right v)-        Left  e -> case p e of-                        Nothing -> throwIO e-                        Just b  -> return (Left b)---- | Like 'finally', but only performs the final action if there was an--- exception raised by the computation.-onException :: IO a -> IO b -> IO a-onException io what = io `catch` \e -> do _ <- what-                                          throwIO (e :: SomeException)---------------------------------------------------------------------------------- Some Useful Functions---- | When you want to acquire a resource, do some work with it, and--- then release the resource, it is a good idea to use 'bracket',--- because 'bracket' will install the necessary exception handler to--- release the resource in the event that an exception is raised--- during the computation.  If an exception is raised, then 'bracket' will--- re-raise the exception (after performing the release).------ A common example is opening a file:------ > bracket--- >   (openFile "filename" ReadMode)--- >   (hClose)--- >   (\fileHandle -> do { ... })------ The arguments to 'bracket' are in this order so that we can partially apply--- it, e.g.:------ > withFile name mode = bracket (openFile name mode) hClose----bracket-        :: IO a         -- ^ computation to run first (\"acquire resource\")-        -> (a -> IO b)  -- ^ computation to run last (\"release resource\")-        -> (a -> IO c)  -- ^ computation to run in-between-        -> IO c         -- returns the value from the in-between computation-bracket before after thing =-  mask $ \restore -> do-    a <- before-    r <- restore (thing a) `onException` after a-    _ <- after a-    return r---- | A specialised variant of 'bracket' with just a computation to run--- afterward.----finally :: IO a         -- ^ computation to run first-        -> IO b         -- ^ computation to run afterward (even if an exception-                        -- was raised)-        -> IO a         -- returns the value from the first computation-a `finally` sequel =-  mask $ \restore -> do-    r <- restore a `onException` sequel-    _ <- sequel-    return r---- | A variant of 'bracket' where the return value from the first computation--- is not required.-bracket_ :: IO a -> IO b -> IO c -> IO c-bracket_ before after thing = bracket before (const after) (const thing)---- | Like 'bracket', but only performs the final action if there was an--- exception raised by the in-between computation.-bracketOnError-        :: IO a         -- ^ computation to run first (\"acquire resource\")-        -> (a -> IO b)  -- ^ computation to run last (\"release resource\")-        -> (a -> IO c)  -- ^ computation to run in-between-        -> IO c         -- returns the value from the in-between computation-bracketOnError before after thing =-  mask $ \restore -> do-    a <- before-    restore (thing a) `onException` after a----------- |A pattern match failed. The @String@ gives information about the--- source location of the pattern.-data PatternMatchFail = PatternMatchFail String deriving Typeable--instance Show PatternMatchFail where-    showsPrec _ (PatternMatchFail err) = showString err--instance Exception PatternMatchFail----------- |A record selector was applied to a constructor without the--- appropriate field. This can only happen with a datatype with--- multiple constructors, where some fields are in one constructor--- but not another. The @String@ gives information about the source--- location of the record selector.-data RecSelError = RecSelError String deriving Typeable--instance Show RecSelError where-    showsPrec _ (RecSelError err) = showString err--instance Exception RecSelError----------- |An uninitialised record field was used. The @String@ gives--- information about the source location where the record was--- constructed.-data RecConError = RecConError String deriving Typeable--instance Show RecConError where-    showsPrec _ (RecConError err) = showString err--instance Exception RecConError----------- |A record update was performed on a constructor without the--- appropriate field. This can only happen with a datatype with--- multiple constructors, where some fields are in one constructor--- but not another. The @String@ gives information about the source--- location of the record update.-data RecUpdError = RecUpdError String deriving Typeable--instance Show RecUpdError where-    showsPrec _ (RecUpdError err) = showString err--instance Exception RecUpdError----------- |A class method without a definition (neither a default definition,--- nor a definition in the appropriate instance) was called. The--- @String@ gives information about which method it was.-data NoMethodError = NoMethodError String deriving Typeable--instance Show NoMethodError where-    showsPrec _ (NoMethodError err) = showString err--instance Exception NoMethodError----------- |Thrown when the runtime system detects that the computation is--- guaranteed not to terminate. Note that there is no guarantee that--- the runtime system will notice whether any given computation is--- guaranteed to terminate or not.-data NonTermination = NonTermination deriving Typeable--instance Show NonTermination where-    showsPrec _ NonTermination = showString "<<loop>>"--instance Exception NonTermination----------- |Thrown when the program attempts to call @atomically@, from the @stm@--- package, inside another call to @atomically@.-data NestedAtomically = NestedAtomically deriving Typeable--instance Show NestedAtomically where-    showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"--instance Exception NestedAtomically---------recSelError, recConError, irrefutPatError, runtimeError,-  nonExhaustiveGuardsError, patError, noMethodBindingError,-  absentError-        :: Addr# -> a   -- All take a UTF8-encoded C string--recSelError              s = throw (RecSelError ("No match in record selector "-                                                 ++ unpackCStringUtf8# s))  -- No location info unfortunately-runtimeError             s = error (unpackCStringUtf8# s)                   -- No location info unfortunately-absentError              s = error ("Oops!  Entered absent arg " ++ unpackCStringUtf8# s)--nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))-irrefutPatError          s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))-recConError              s = throw (RecConError      (untangle s "Missing field in record construction"))-noMethodBindingError     s = throw (NoMethodError    (untangle s "No instance nor default method for class operation"))-patError                 s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))---- GHC's RTS calls this-nonTermination :: SomeException-nonTermination = toException NonTermination---- GHC's RTS calls this-nestedAtomically :: SomeException-nestedAtomically = toException NestedAtomically
− Control/Monad.hs
@@ -1,249 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ The 'Functor', 'Monad' and 'MonadPlus' classes,--- with some useful operations on monads.--module Control.Monad-    (-    -- * Functor and monad classes--      Functor(fmap)-    , Monad((>>=), (>>), return, fail)-    , MonadPlus(mzero, mplus)-    -- * Functions--    -- ** Naming conventions-    -- $naming--    -- ** Basic @Monad@ functions--    , mapM-    , mapM_-    , forM-    , forM_-    , sequence-    , sequence_-    , (=<<)-    , (>=>)-    , (<=<)-    , forever-    , void--    -- ** Generalisations of list functions--    , join-    , msum-    , mfilter-    , filterM-    , mapAndUnzipM-    , zipWithM-    , zipWithM_-    , foldM-    , foldM_-    , replicateM-    , replicateM_--    -- ** Conditional execution of monadic expressions--    , guard-    , when-    , unless--    -- ** Monadic lifting operators--    , liftM-    , liftM2-    , liftM3-    , liftM4-    , liftM5--    , ap--    -- ** Strict monadic functions--    , (<$!>)-    ) where--import Data.Foldable ( Foldable, sequence_, msum, mapM_, foldlM, forM_ )-import Data.Functor ( void )-import Data.Traversable ( forM, mapM, sequence )--import GHC.Base hiding ( mapM, sequence )-import GHC.List ( zipWith, unzip, replicate )---- -------------------------------------------------------------------------------- Functions mandated by the Prelude---- | @'guard' b@ is @'pure' ()@ if @b@ is 'True',--- and 'empty' if @b@ is 'False'.-guard           :: (Alternative f) => Bool -> f ()-guard True      =  pure ()-guard False     =  empty---- | This generalizes the list-based 'filter' function.--{-# INLINE filterM #-}-filterM          :: (Monad m) => (a -> m Bool) -> [a] -> m [a]-filterM p        = foldr go (return [])-  where-    go x r = do-      flg <- p x-      ys <- r-      return (if flg then x:ys else ys)--infixr 1 <=<, >=>---- | Left-to-right Kleisli composition of monads.-(>=>)       :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)-f >=> g     = \x -> f x >>= g---- | Right-to-left Kleisli composition of monads. @('>=>')@, with the arguments flipped-(<=<)       :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)-(<=<)       = flip (>=>)---- | @'forever' act@ repeats the action infinitely.-forever     :: (Monad m) => m a -> m b-{-# INLINE forever #-}-forever a   = let a' = a >> a' in a'--- Use explicit sharing here, as it is prevents a space leak regardless of--- optimizations.---- -------------------------------------------------------------------------------- Other monad functions---- | The 'mapAndUnzipM' function maps its first argument over a list, returning--- the result as a pair of lists. This function is mainly used with complicated--- data structures or a state-transforming monad.-mapAndUnzipM      :: (Monad m) => (a -> m (b,c)) -> [a] -> m ([b], [c])-{-# INLINE mapAndUnzipM #-}-mapAndUnzipM f xs =  sequence (map f xs) >>= return . unzip---- | The 'zipWithM' function generalizes 'zipWith' to arbitrary monads.-zipWithM          :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m [c]-{-# INLINE zipWithM #-}-zipWithM f xs ys  =  sequence (zipWith f xs ys)---- | 'zipWithM_' is the extension of 'zipWithM' which ignores the final result.-zipWithM_         :: (Monad m) => (a -> b -> m c) -> [a] -> [b] -> m ()-{-# INLINE zipWithM_ #-}-zipWithM_ f xs ys =  sequence_ (zipWith f xs ys)--{- | The 'foldM' function is analogous to 'foldl', except that its result is-encapsulated in a monad. Note that 'foldM' works from left-to-right over-the list arguments. This could be an issue where @('>>')@ and the `folded-function' are not commutative.--->       foldM f a1 [x1, x2, ..., xm]--==-->       do->         a2 <- f a1 x1->         a3 <- f a2 x2->         ...->         f am xm--If right-to-left evaluation is required, the input list should be reversed.--Note: 'foldM' is the same as 'foldlM'--}--foldM          :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b-{-# INLINEABLE foldM #-}-{-# SPECIALISE foldM :: (a -> b -> IO a) -> a -> [b] -> IO a #-}-{-# SPECIALISE foldM :: (a -> b -> Maybe a) -> a -> [b] -> Maybe a #-}-foldM          = foldlM---- | Like 'foldM', but discards the result.-foldM_         :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m ()-{-# INLINEABLE foldM_ #-}-{-# SPECIALISE foldM_ :: (a -> b -> IO a) -> a -> [b] -> IO () #-}-{-# SPECIALISE foldM_ :: (a -> b -> Maybe a) -> a -> [b] -> Maybe () #-}-foldM_ f a xs  = foldlM f a xs >> return ()---- | @'replicateM' n act@ performs the action @n@ times,--- gathering the results.-replicateM        :: (Monad m) => Int -> m a -> m [a]-{-# INLINEABLE replicateM #-}-{-# SPECIALISE replicateM :: Int -> IO a -> IO [a] #-}-{-# SPECIALISE replicateM :: Int -> Maybe a -> Maybe [a] #-}-replicateM n x    = sequence (replicate n x)---- | Like 'replicateM', but discards the result.-replicateM_       :: (Monad m) => Int -> m a -> m ()-{-# INLINEABLE replicateM_ #-}-{-# SPECIALISE replicateM_ :: Int -> IO a -> IO () #-}-{-# SPECIALISE replicateM_ :: Int -> Maybe a -> Maybe () #-}-replicateM_ n x   = sequence_ (replicate n x)---- | The reverse of 'when'.-unless            :: (Applicative f) => Bool -> f () -> f ()-{-# INLINEABLE unless #-}-{-# SPECIALISE unless :: Bool -> IO () -> IO () #-}-{-# SPECIALISE unless :: Bool -> Maybe () -> Maybe () #-}-unless p s        =  if p then pure () else s--infixl 4 <$!>---- | Strict version of 'Data.Functor.<$>'.------ @since 4.8.0.0-(<$!>) :: Monad m => (a -> b) -> m a -> m b-{-# INLINE (<$!>) #-}-f <$!> m = do-  x <- m-  let z = f x-  z `seq` return z----- -------------------------------------------------------------------------------- Other MonadPlus functions---- | Direct 'MonadPlus' equivalent of 'filter'--- @'filter'@ = @(mfilter:: (a -> Bool) -> [a] -> [a]@--- applicable to any 'MonadPlus', for example--- @mfilter odd (Just 1) == Just 1@--- @mfilter odd (Just 2) == Nothing@--mfilter :: (MonadPlus m) => (a -> Bool) -> m a -> m a-{-# INLINEABLE mfilter #-}-mfilter p ma = do-  a <- ma-  if p a then return a else mzero--{- $naming--The functions in this library use the following naming conventions:--* A postfix \'@M@\' always stands for a function in the Kleisli category:-  The monad type constructor @m@ is added to function results-  (modulo currying) and nowhere else.  So, for example,-->  filter  ::              (a ->   Bool) -> [a] ->   [a]->  filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]--* A postfix \'@_@\' changes the result type from @(m a)@ to @(m ())@.-  Thus, for example:-->  sequence  :: Monad m => [m a] -> m [a]->  sequence_ :: Monad m => [m a] -> m ()--* A prefix \'@m@\' generalizes an existing function to a monadic form.-  Thus, for example:-->  sum  :: Num a       => [a]   -> a->  msum :: MonadPlus m => [m a] -> m a---}
− Control/Monad/Fix.hs
@@ -1,83 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.Fix--- Copyright   :  (c) Andy Gill 2001,---                (c) Oregon Graduate Institute of Science and Technology, 2002--- License     :  BSD-style (see the file libraries/base/LICENSE)--- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Monadic fixpoints.------ For a detailed discussion, see Levent Erkok's thesis,--- /Value Recursion in Monadic Computations/, Oregon Graduate Institute, 2002.-----------------------------------------------------------------------------------module Control.Monad.Fix (-        MonadFix(mfix),-        fix-  ) where--import Data.Either-import Data.Function ( fix )-import Data.Maybe-import GHC.Base ( Monad, error, (.) )-import GHC.List ( head, tail )-import GHC.ST-import System.IO---- | Monads having fixed points with a \'knot-tying\' semantics.--- Instances of 'MonadFix' should satisfy the following laws:------ [/purity/]---      @'mfix' ('return' . h)  =  'return' ('fix' h)@------ [/left shrinking/ (or /tightening/)]---      @'mfix' (\\x -> a >>= \\y -> f x y)  =  a >>= \\y -> 'mfix' (\\x -> f x y)@------ [/sliding/]---      @'mfix' ('Control.Monad.liftM' h . f)  =  'Control.Monad.liftM' h ('mfix' (f . h))@,---      for strict @h@.------ [/nesting/]---      @'mfix' (\\x -> 'mfix' (\\y -> f x y))  =  'mfix' (\\x -> f x x)@------ This class is used in the translation of the recursive @do@ notation--- supported by GHC and Hugs.-class (Monad m) => MonadFix m where-        -- | The fixed point of a monadic computation.-        -- @'mfix' f@ executes the action @f@ only once, with the eventual-        -- output fed back as the input.  Hence @f@ should not be strict,-        -- for then @'mfix' f@ would diverge.-        mfix :: (a -> m a) -> m a---- Instances of MonadFix for Prelude monads--instance MonadFix Maybe where-    mfix f = let a = f (unJust a) in a-             where unJust (Just x) = x-                   unJust Nothing  = error "mfix Maybe: Nothing"--instance MonadFix [] where-    mfix f = case fix (f . head) of-               []    -> []-               (x:_) -> x : mfix (tail . f)--instance MonadFix IO where-    mfix = fixIO--instance MonadFix ((->) r) where-    mfix f = \ r -> let a = f a r in a--instance MonadFix (Either e) where-    mfix f = let a = f (unRight a) in a-             where unRight (Right x) = x-                   unRight (Left  _) = error "mfix Either: Left"--instance MonadFix (ST s) where-        mfix = fixST
− Control/Monad/Instances.hs
@@ -1,19 +0,0 @@-{-# LANGUAGE Safe #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.Instances--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ /This module is DEPRECATED and will be removed in the future!/------ 'Functor' and 'Monad' instances for @(->) r@ and--- 'Functor' instances for @(,) a@ and @'Either' a@.--module Control.Monad.Instances {-# DEPRECATED "This module now contains no instances and will be removed in the future" #-} -- deprecated in 7.8-    (Functor(..),Monad(..)) where
− Control/Monad/ST.hs
@@ -1,35 +0,0 @@-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.ST--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (requires universal quantification for runST)------ This library provides support for /strict/ state threads, as--- described in the PLDI \'94 paper by John Launchbury and Simon Peyton--- Jones /Lazy Functional State Threads/.------ References (variables) that can be used within the @ST@ monad are--- provided by "Data.STRef", and arrays are provided by--- "Data.Array.ST".---------------------------------------------------------------------------------module Control.Monad.ST (-        -- * The 'ST' Monad-        ST,             -- abstract, instance of Functor, Monad, Typeable.-        runST,-        fixST,--        -- * Converting 'ST' to 'IO'-        RealWorld,              -- abstract-        stToIO,-    ) where--import Control.Monad.ST.Imp-
− Control/Monad/ST/Imp.hs
@@ -1,38 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.ST.Imp--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (requires universal quantification for runST)------ This library provides support for /strict/ state threads, as--- described in the PLDI \'94 paper by John Launchbury and Simon Peyton--- Jones /Lazy Functional State Threads/.-----------------------------------------------------------------------------------module Control.Monad.ST.Imp (-        -- * The 'ST' Monad-        ST,             -- abstract, instance of Functor, Monad, Typeable.-        runST,-        fixST,--        -- * Converting 'ST' to 'IO'-        RealWorld,              -- abstract-        stToIO,--        -- * Unsafe operations-        unsafeInterleaveST,-        unsafeIOToST,-        unsafeSTToIO-    ) where--import GHC.ST           ( ST, runST, fixST, unsafeInterleaveST )-import GHC.Base         ( RealWorld )-import GHC.IO           ( stToIO, unsafeIOToST, unsafeSTToIO )
− Control/Monad/ST/Lazy.hs
@@ -1,34 +0,0 @@-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.ST.Lazy--- 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.-----------------------------------------------------------------------------------module Control.Monad.ST.Lazy (-        -- * The 'ST' monad-        ST,-        runST,-        fixST,--        -- * Converting between strict and lazy 'ST'-        strictToLazyST, lazyToStrictST,--        -- * Converting 'ST' To 'IO'-        RealWorld,-        stToIO,-    ) where--import Control.Monad.ST.Lazy.Imp-
− Control/Monad/ST/Lazy/Imp.hs
@@ -1,151 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# 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.-----------------------------------------------------------------------------------module Control.Monad.ST.Lazy.Imp (-        -- * The 'ST' monad-        ST,-        runST,-        fixST,--        -- * Converting between strict and lazy 'ST'-        strictToLazyST, lazyToStrictST,--        -- * Converting 'ST' To 'IO'-        RealWorld,-        stToIO,--        -- * Unsafe operations-        unsafeInterleaveST,-        unsafeIOToST-    ) where--import Control.Monad.Fix--import qualified Control.Monad.ST as ST-import qualified Control.Monad.ST.Unsafe as ST--import qualified GHC.ST as GHC.ST-import GHC.Base---- | 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 unstantiated 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@-newtype ST s a = ST (State s -> (a, State s))-data State s = S# (State# s)--instance Functor (ST s) where-    fmap f m = ST $ \ s ->-      let-       ST m_a = m-       (r,new_s) = m_a s-      in-      (f r,new_s)--instance Applicative (ST s) where-    pure = return-    (<*>) = ap--instance Monad (ST s) where--        return a = ST $ \ s -> (a,s)-        m >> k   =  m >>= \ _ -> k-        fail s   = error s--        (ST m) >>= k-         = ST $ \ s ->-           let-             (r,new_s) = m s-             ST k_a = k r-           in-           k_a new_s--{-# NOINLINE runST #-}--- | 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 :: (forall s. ST s a) -> a-runST st = case st of ST the_st -> let (r,_) = the_st (S# realWorld#) in 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 -> ST s a) -> ST s a-fixST m = ST (\ s -> -                let -                   ST m_r = m r-                   (r,s') = m_r s-                in-                   (r,s'))--instance MonadFix (ST s) where-        mfix = fixST---- ------------------------------------------------------------------------------ Strict <--> Lazy--{-|-Convert a strict 'ST' computation into a lazy one.  The strict state-thread passed to 'strictToLazyST' is not performed until the result of-the lazy state thread it returns is demanded.--}-strictToLazyST :: ST.ST s a -> ST s a-strictToLazyST m = ST $ \s ->-        let -           pr = case s of { S# s# -> GHC.ST.liftST m s# }-           r  = case pr of { GHC.ST.STret _ v -> v }-           s' = case pr of { GHC.ST.STret s2# _ -> S# s2# }-        in-        (r, s')--{-| -Convert a lazy 'ST' computation into a strict one.--}-lazyToStrictST :: ST s a -> ST.ST s a-lazyToStrictST (ST m) = 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 :: ST RealWorld a -> IO a-stToIO = ST.stToIO . lazyToStrictST---- ------------------------------------------------------------------------------ Strict <--> Lazy--unsafeInterleaveST :: ST s a -> ST s a-unsafeInterleaveST = strictToLazyST . ST.unsafeInterleaveST . lazyToStrictST--unsafeIOToST :: IO a -> ST s a-unsafeIOToST = strictToLazyST . ST.unsafeIOToST-
− Control/Monad/ST/Lazy/Safe.hs
@@ -1,36 +0,0 @@-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.ST.Lazy.Safe--- 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.------ Safe API only.-----------------------------------------------------------------------------------module Control.Monad.ST.Lazy.Safe {-# DEPRECATED "Safe is now the default, please use Control.Monad.ST.Lazy instead" #-} (-        -- * The 'ST' monad-        ST,-        runST,-        fixST,--        -- * Converting between strict and lazy 'ST'-        strictToLazyST, lazyToStrictST,--        -- * Converting 'ST' To 'IO'-        RealWorld,-        stToIO,-    ) where--import Control.Monad.ST.Lazy.Imp-
− Control/Monad/ST/Lazy/Unsafe.hs
@@ -1,28 +0,0 @@-{-# LANGUAGE Unsafe #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.ST.Lazy.Unsafe--- 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.------ Unsafe API.-----------------------------------------------------------------------------------module Control.Monad.ST.Lazy.Unsafe (-        -- * Unsafe operations-        unsafeInterleaveST,-        unsafeIOToST-    ) where--import Control.Monad.ST.Lazy.Imp-
− Control/Monad/ST/Safe.hs
@@ -1,33 +0,0 @@-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.ST.Safe--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (requires universal quantification for runST)------ This library provides support for /strict/ state threads, as--- described in the PLDI \'94 paper by John Launchbury and Simon Peyton--- Jones /Lazy Functional State Threads/.------ Safe API Only.-----------------------------------------------------------------------------------module Control.Monad.ST.Safe {-# DEPRECATED "Safe is now the default, please use Control.Monad.ST instead" #-} (-        -- * The 'ST' Monad-        ST,             -- abstract-        runST,-        fixST,--        -- * Converting 'ST' to 'IO'-        RealWorld,              -- abstract-        stToIO,-    ) where--import Control.Monad.ST.Imp-
− Control/Monad/ST/Strict.hs
@@ -1,22 +0,0 @@-{-# LANGUAGE Safe #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.ST.Strict--- 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)------ The strict ST monad (re-export of "Control.Monad.ST")-----------------------------------------------------------------------------------module Control.Monad.ST.Strict (-        module Control.Monad.ST-  ) where--import Control.Monad.ST-
− Control/Monad/ST/Unsafe.hs
@@ -1,29 +0,0 @@-{-# LANGUAGE Unsafe #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.ST.Unsafe--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (requires universal quantification for runST)------ This library provides support for /strict/ state threads, as--- described in the PLDI \'94 paper by John Launchbury and Simon Peyton--- Jones /Lazy Functional State Threads/.------ Unsafe API.-----------------------------------------------------------------------------------module Control.Monad.ST.Unsafe (-        -- * Unsafe operations-        unsafeInterleaveST,-        unsafeIOToST,-        unsafeSTToIO-    ) where--import Control.Monad.ST.Imp-
− Control/Monad/Zip.hs
@@ -1,55 +0,0 @@-{-# LANGUAGE Safe #-}---------------------------------------------------------------------------------- |--- Module      :  Control.Monad.Zip--- Copyright   :  (c) Nils Schweinsberg 2011,---                (c) George Giorgidze 2011---                (c) University Tuebingen 2011--- License     :  BSD-style (see the file libraries/base/LICENSE)--- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Monadic zipping (used for monad comprehensions)-----------------------------------------------------------------------------------module Control.Monad.Zip where--import Control.Monad (liftM)---- | `MonadZip` type class. Minimal definition: `mzip` or `mzipWith`------ Instances should satisfy the laws:------ * Naturality :------   > liftM (f *** g) (mzip ma mb) = mzip (liftM f ma) (liftM g mb)------ * Information Preservation:------   > liftM (const ()) ma = liftM (const ()) mb---   > ==>---   > munzip (mzip ma mb) = (ma, mb)----class Monad m => MonadZip m where-    {-# MINIMAL mzip | mzipWith #-}--    mzip :: m a -> m b -> m (a,b)-    mzip = mzipWith (,)--    mzipWith :: (a -> b -> c) -> m a -> m b -> m c-    mzipWith f ma mb = liftM (uncurry f) (mzip ma mb)--    munzip :: m (a,b) -> (m a, m b)-    munzip mab = (liftM fst mab, liftM snd mab)-    -- munzip is a member of the class because sometimes-    -- you can implement it more efficiently than the-    -- above default code.  See Trac #4370 comment by giorgidze--instance MonadZip [] where-    mzip     = zip-    mzipWith = zipWith-    munzip   = unzip-
− Data/Bifunctor.hs
@@ -1,101 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE CPP #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Bifunctor--- Copyright   :  (C) 2008-2014 Edward Kmett,--- License     :  BSD-style (see the file LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ @since 4.8.0.0------------------------------------------------------------------------------module Data.Bifunctor-  ( Bifunctor(..)-  ) where--import Control.Applicative  ( Const(..) )---- | Formally, the class 'Bifunctor' represents a bifunctor--- from @Hask@ -> @Hask@.------ Intuitively it is a bifunctor where both the first and second--- arguments are covariant.------ You can define a 'Bifunctor' by either defining 'bimap' or by--- defining both 'first' and 'second'.------ If you supply 'bimap', you should ensure that:------ @'bimap' 'id' 'id' ≡ 'id'@------ If you supply 'first' and 'second', ensure:------ @--- 'first' 'id' ≡ 'id'--- 'second' 'id' ≡ 'id'--- @------ If you supply both, you should also ensure:------ @'bimap' f g ≡ 'first' f '.' 'second' g@------ These ensure by parametricity:------ @--- 'bimap'  (f '.' g) (h '.' i) ≡ 'bimap' f h '.' 'bimap' g i--- 'first'  (f '.' g) ≡ 'first'  f '.' 'first'  g--- 'second' (f '.' g) ≡ 'second' f '.' 'second' g--- @------ @since 4.8.0.0-class Bifunctor p where-    {-# MINIMAL bimap | first, second #-}--    -- | Map over both arguments at the same time.-    ---    -- @'bimap' f g ≡ 'first' f '.' 'second' g@-    bimap :: (a -> b) -> (c -> d) -> p a c -> p b d-    bimap f g = first f . second g--    -- | Map covariantly over the first argument.-    ---    -- @'first' f ≡ 'bimap' f 'id'@-    first :: (a -> b) -> p a c -> p b c-    first f = bimap f id--    -- | Map covariantly over the second argument.-    ---    -- @'second' ≡ 'bimap' 'id'@-    second :: (b -> c) -> p a b -> p a c-    second = bimap id---instance Bifunctor (,) where-    bimap f g ~(a, b) = (f a, g b)--instance Bifunctor ((,,) x1) where-    bimap f g ~(x1, a, b) = (x1, f a, g b)--instance Bifunctor ((,,,) x1 x2) where-    bimap f g ~(x1, x2, a, b) = (x1, x2, f a, g b)--instance Bifunctor ((,,,,) x1 x2 x3) where-    bimap f g ~(x1, x2, x3, a, b) = (x1, x2, x3, f a, g b)--instance Bifunctor ((,,,,,) x1 x2 x3 x4) where-    bimap f g ~(x1, x2, x3, x4, a, b) = (x1, x2, x3, x4, f a, g b)--instance Bifunctor ((,,,,,,) x1 x2 x3 x4 x5) where-    bimap f g ~(x1, x2, x3, x4, x5, a, b) = (x1, x2, x3, x4, x5, f a, g b)---instance Bifunctor Either where-    bimap f _ (Left a) = Left (f a)-    bimap _ g (Right b) = Right (g b)--instance Bifunctor Const where-    bimap f _ (Const a) = Const (f a)
− Data/Bits.hs
@@ -1,667 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Bits--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ This module defines bitwise operations for signed and unsigned--- integers.  Instances of the class 'Bits' for the 'Int' and--- 'Integer' types are available from this module, and instances for--- explicitly sized integral types are available from the--- "Data.Int" and "Data.Word" modules.-----------------------------------------------------------------------------------module Data.Bits (-  Bits(-    (.&.), (.|.), xor,-    complement,-    shift,-    rotate,-    zeroBits,-    bit,-    setBit,-    clearBit,-    complementBit,-    testBit,-    bitSizeMaybe,-    bitSize,-    isSigned,-    shiftL, shiftR,-    unsafeShiftL, unsafeShiftR,-    rotateL, rotateR,-    popCount-  ),-  FiniteBits(-    finiteBitSize,-    countLeadingZeros,-    countTrailingZeros-  ),--  bitDefault,-  testBitDefault,-  popCountDefault,-  toIntegralSized- ) where---- Defines the @Bits@ class containing bit-based operations.--- See library document for details on the semantics of the--- individual operations.--#include "MachDeps.h"--#ifdef MIN_VERSION_integer_gmp-# define HAVE_INTEGER_GMP1 MIN_VERSION_integer_gmp(1,0,0)-#endif--import Data.Maybe-import GHC.Enum-import GHC.Num-import GHC.Base-import GHC.Real--#if HAVE_INTEGER_GMP1-import GHC.Integer.GMP.Internals (bitInteger, popCountInteger)-#endif--infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR`-infixl 7 .&.-infixl 6 `xor`-infixl 5 .|.--{-# DEPRECATED bitSize "Use 'bitSizeMaybe' or 'finiteBitSize' instead" #-} -- deprecated in 7.8---- | The 'Bits' class defines bitwise operations over integral types.------ * Bits are numbered from 0 with bit 0 being the least---   significant bit.-class Eq a => Bits a where-    {-# MINIMAL (.&.), (.|.), xor, complement,-                (shift | (shiftL, shiftR)),-                (rotate | (rotateL, rotateR)),-                bitSize, bitSizeMaybe, isSigned, testBit, bit, popCount #-}--    -- | Bitwise \"and\"-    (.&.) :: a -> a -> a--    -- | Bitwise \"or\"-    (.|.) :: a -> a -> a--    -- | Bitwise \"xor\"-    xor :: a -> a -> a--    {-| Reverse all the bits in the argument -}-    complement        :: a -> a--    {-| @'shift' x i@ shifts @x@ left by @i@ bits if @i@ is positive,-        or right by @-i@ bits otherwise.-        Right shifts perform sign extension on signed number types;-        i.e. they fill the top bits with 1 if the @x@ is negative-        and with 0 otherwise.--        An instance can define either this unified 'shift' or 'shiftL' and-        'shiftR', depending on which is more convenient for the type in-        question. -}-    shift             :: a -> Int -> a--    x `shift`   i | i<0       = x `shiftR` (-i)-                  | i>0       = x `shiftL` i-                  | otherwise = x--    {-| @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive,-        or right by @-i@ bits otherwise.--        For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'.--        An instance can define either this unified 'rotate' or 'rotateL' and-        'rotateR', depending on which is more convenient for the type in-        question. -}-    rotate            :: a -> Int -> a--    x `rotate`  i | i<0       = x `rotateR` (-i)-                  | i>0       = x `rotateL` i-                  | otherwise = x--    {--    -- Rotation can be implemented in terms of two shifts, but care is-    -- needed for negative values.  This suggested implementation assumes-    -- 2's-complement arithmetic.  It is commented out because it would-    -- require an extra context (Ord a) on the signature of 'rotate'.-    x `rotate`  i | i<0 && isSigned x && x<0-                         = let left = i+bitSize x in-                           ((x `shift` i) .&. complement ((-1) `shift` left))-                           .|. (x `shift` left)-                  | i<0  = (x `shift` i) .|. (x `shift` (i+bitSize x))-                  | i==0 = x-                  | i>0  = (x `shift` i) .|. (x `shift` (i-bitSize x))-    -}--    -- | 'zeroBits' is the value with all bits unset.-    ---    -- The following laws ought to hold (for all valid bit indices @/n/@):-    ---    --   * @'clearBit' 'zeroBits' /n/ == 'zeroBits'@-    --   * @'setBit'   'zeroBits' /n/ == 'bit' /n/@-    --   * @'testBit'  'zeroBits' /n/ == False@-    --   * @'popCount' 'zeroBits'   == 0@-    ---    -- This method uses @'clearBit' ('bit' 0) 0@ as its default-    -- implementation (which ought to be equivalent to 'zeroBits' for-    -- types which possess a 0th bit).-    ---    -- @since 4.7.0.0-    zeroBits :: a-    zeroBits = clearBit (bit 0) 0--    -- | @bit /i/@ is a value with the @/i/@th bit set and all other bits clear.-    ---    -- Can be implemented using `bitDefault' if @a@ is also an-    -- instance of 'Num'.-    ---    -- See also 'zeroBits'.-    bit               :: Int -> a--    -- | @x \`setBit\` i@ is the same as @x .|. bit i@-    setBit            :: a -> Int -> a--    -- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@-    clearBit          :: a -> Int -> a--    -- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@-    complementBit     :: a -> Int -> a--    -- | Return 'True' if the @n@th bit of the argument is 1-    ---    -- Can be implemented using `testBitDefault' if @a@ is also an-    -- instance of 'Num'.-    testBit           :: a -> Int -> Bool--    {-| Return the number of bits in the type of the argument.  The actual-        value of the argument is ignored.  Returns Nothing-        for types that do not have a fixed bitsize, like 'Integer'.--        @since 4.7.0.0-        -}-    bitSizeMaybe      :: a -> Maybe Int--    {-| Return the number of bits in the type of the argument.  The actual-        value of the argument is ignored.  The function 'bitSize' is-        undefined for types that do not have a fixed bitsize, like 'Integer'.-        -}-    bitSize           :: a -> Int--    {-| Return 'True' if the argument is a signed type.  The actual-        value of the argument is ignored -}-    isSigned          :: a -> Bool--    {-# INLINE setBit #-}-    {-# INLINE clearBit #-}-    {-# INLINE complementBit #-}-    x `setBit` i        = x .|. bit i-    x `clearBit` i      = x .&. complement (bit i)-    x `complementBit` i = x `xor` bit i--    {-| Shift the argument left by the specified number of bits-        (which must be non-negative).--        An instance can define either this and 'shiftR' or the unified-        'shift', depending on which is more convenient for the type in-        question. -}-    shiftL            :: a -> Int -> a-    {-# INLINE shiftL #-}-    x `shiftL`  i = x `shift`  i--    {-| Shift the argument left by the specified number of bits.  The-        result is undefined for negative shift amounts and shift amounts-        greater or equal to the 'bitSize'.--        Defaults to 'shiftL' unless defined explicitly by an instance.--        @since 4.5.0.0 -}-    unsafeShiftL            :: a -> Int -> a-    {-# INLINE unsafeShiftL #-}-    x `unsafeShiftL` i = x `shiftL` i--    {-| Shift the first argument right by the specified number of bits. The-        result is undefined for negative shift amounts and shift amounts-        greater or equal to the 'bitSize'.--        Right shifts perform sign extension on signed number types;-        i.e. they fill the top bits with 1 if the @x@ is negative-        and with 0 otherwise.--        An instance can define either this and 'shiftL' or the unified-        'shift', depending on which is more convenient for the type in-        question. -}-    shiftR            :: a -> Int -> a-    {-# INLINE shiftR #-}-    x `shiftR`  i = x `shift`  (-i)--    {-| Shift the first argument right by the specified number of bits, which-        must be non-negative an smaller than the number of bits in the type.--        Right shifts perform sign extension on signed number types;-        i.e. they fill the top bits with 1 if the @x@ is negative-        and with 0 otherwise.--        Defaults to 'shiftR' unless defined explicitly by an instance.--        @since 4.5.0.0 -}-    unsafeShiftR            :: a -> Int -> a-    {-# INLINE unsafeShiftR #-}-    x `unsafeShiftR` i = x `shiftR` i--    {-| Rotate the argument left by the specified number of bits-        (which must be non-negative).--        An instance can define either this and 'rotateR' or the unified-        'rotate', depending on which is more convenient for the type in-        question. -}-    rotateL           :: a -> Int -> a-    {-# INLINE rotateL #-}-    x `rotateL` i = x `rotate` i--    {-| Rotate the argument right by the specified number of bits-        (which must be non-negative).--        An instance can define either this and 'rotateL' or the unified-        'rotate', depending on which is more convenient for the type in-        question. -}-    rotateR           :: a -> Int -> a-    {-# INLINE rotateR #-}-    x `rotateR` i = x `rotate` (-i)--    {-| Return the number of set bits in the argument.  This number is-        known as the population count or the Hamming weight.--        Can be implemented using `popCountDefault' if @a@ is also an-        instance of 'Num'.--        @since 4.5.0.0 -}-    popCount          :: a -> Int---- |The 'FiniteBits' class denotes types with a finite, fixed number of bits.------ @since 4.7.0.0-class Bits b => FiniteBits b where-    -- | Return the number of bits in the type of the argument.-    -- The actual value of the argument is ignored. Moreover, 'finiteBitSize'-    -- is total, in contrast to the deprecated 'bitSize' function it replaces.-    ---    -- @-    -- 'finiteBitSize' = 'bitSize'-    -- 'bitSizeMaybe' = 'Just' . 'finiteBitSize'-    -- @-    ---    -- @since 4.7.0.0-    finiteBitSize :: b -> Int--    -- | Count number of zero bits preceding the most significant set bit.-    ---    -- @-    -- 'countLeadingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)-    -- @-    ---    -- 'countLeadingZeros' can be used to compute log base 2 via-    ---    -- @-    -- logBase2 x = 'finiteBitSize' x - 1 - 'countLeadingZeros' x-    -- @-    ---    -- Note: The default implementation for this method is intentionally-    -- naive. However, the instances provided for the primitive-    -- integral types are implemented using CPU specific machine-    -- instructions.-    ---    -- @since 4.8.0.0-    countLeadingZeros :: b -> Int-    countLeadingZeros x = (w-1) - go (w-1)-      where-        go i | i < 0       = i -- no bit set-             | testBit x i = i-             | otherwise   = go (i-1)--        w = finiteBitSize x--    -- | Count number of zero bits following the least significant set bit.-    ---    -- @-    -- 'countTrailingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)-    -- 'countTrailingZeros' . 'negate' = 'countTrailingZeros'-    -- @-    ---    -- The related-    -- <http://en.wikipedia.org/wiki/Find_first_set find-first-set operation>-    -- can be expressed in terms of 'countTrailingZeros' as follows-    ---    -- @-    -- findFirstSet x = 1 + 'countTrailingZeros' x-    -- @-    ---    -- Note: The default implementation for this method is intentionally-    -- naive. However, the instances provided for the primitive-    -- integral types are implemented using CPU specific machine-    -- instructions.-    ---    -- @since 4.8.0.0-    countTrailingZeros :: b -> Int-    countTrailingZeros x = go 0-      where-        go i | i >= w      = i-             | testBit x i = i-             | otherwise   = go (i+1)--        w = finiteBitSize x----- The defaults below are written with lambdas so that e.g.---     bit = bitDefault--- is fully applied, so inlining will happen---- | Default implementation for 'bit'.------ Note that: @bitDefault i = 1 `shiftL` i@------ @since 4.6.0.0-bitDefault :: (Bits a, Num a) => Int -> a-bitDefault = \i -> 1 `shiftL` i-{-# INLINE bitDefault #-}---- | Default implementation for 'testBit'.------ Note that: @testBitDefault x i = (x .&. bit i) /= 0@------ @since 4.6.0.0-testBitDefault ::  (Bits a, Num a) => a -> Int -> Bool-testBitDefault = \x i -> (x .&. bit i) /= 0-{-# INLINE testBitDefault #-}---- | Default implementation for 'popCount'.------ This implementation is intentionally naive. Instances are expected to provide--- an optimized implementation for their size.------ @since 4.6.0.0-popCountDefault :: (Bits a, Num a) => a -> Int-popCountDefault = go 0- where-   go !c 0 = c-   go c w = go (c+1) (w .&. (w - 1)) -- clear the least significant-{-# INLINABLE popCountDefault #-}----- Interpret 'Bool' as 1-bit bit-field; @since 4.7.0.0-instance Bits Bool where-    (.&.) = (&&)--    (.|.) = (||)--    xor = (/=)--    complement = not--    shift x 0 = x-    shift _ _ = False--    rotate x _ = x--    bit 0 = True-    bit _ = False--    testBit x 0 = x-    testBit _ _ = False--    bitSizeMaybe _ = Just 1--    bitSize _ = 1--    isSigned _ = False--    popCount False = 0-    popCount True  = 1--instance FiniteBits Bool where-    finiteBitSize _ = 1-    countTrailingZeros x = if x then 0 else 1-    countLeadingZeros  x = if x then 0 else 1--instance Bits Int where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    zeroBits = 0--    bit     = bitDefault--    testBit = testBitDefault--    (I# x#) .&.   (I# y#)          = I# (x# `andI#` y#)-    (I# x#) .|.   (I# y#)          = I# (x# `orI#`  y#)-    (I# x#) `xor` (I# y#)          = I# (x# `xorI#` y#)-    complement (I# x#)             = I# (notI# x#)-    (I# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)      = I# (x# `iShiftL#` i#)-        | otherwise                = I# (x# `iShiftRA#` negateInt# i#)-    (I# x#) `shiftL` (I# i#)       = I# (x# `iShiftL#` i#)-    (I# x#) `unsafeShiftL` (I# i#) = I# (x# `uncheckedIShiftL#` i#)-    (I# x#) `shiftR` (I# i#)       = I# (x# `iShiftRA#` i#)-    (I# x#) `unsafeShiftR` (I# i#) = I# (x# `uncheckedIShiftRA#` i#)--    {-# INLINE rotate #-}       -- See Note [Constant folding for rotate]-    (I# x#) `rotate` (I# i#) =-        I# ((x# `uncheckedIShiftL#` i'#) `orI#` (x# `uncheckedIShiftRL#` (wsib -# i'#)))-      where-        !i'# = i# `andI#` (wsib -# 1#)-        !wsib = WORD_SIZE_IN_BITS#   {- work around preprocessor problem (??) -}-    bitSizeMaybe i         = Just (finiteBitSize i)-    bitSize i              = finiteBitSize i--    popCount (I# x#) = I# (word2Int# (popCnt# (int2Word# x#)))--    isSigned _             = True--instance FiniteBits Int where-    finiteBitSize _ = WORD_SIZE_IN_BITS-    countLeadingZeros  (I# x#) = I# (word2Int# (clz# (int2Word# x#)))-    countTrailingZeros (I# x#) = I# (word2Int# (ctz# (int2Word# x#)))--instance Bits Word where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (W# x#) .&.   (W# y#)    = W# (x# `and#` y#)-    (W# x#) .|.   (W# y#)    = W# (x# `or#`  y#)-    (W# x#) `xor` (W# y#)    = W# (x# `xor#` y#)-    complement (W# x#)       = W# (x# `xor#` mb#)-        where !(W# mb#) = maxBound-    (W# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)      = W# (x# `shiftL#` i#)-        | otherwise                = W# (x# `shiftRL#` negateInt# i#)-    (W# x#) `shiftL` (I# i#)       = W# (x# `shiftL#` i#)-    (W# x#) `unsafeShiftL` (I# i#) = W# (x# `uncheckedShiftL#` i#)-    (W# x#) `shiftR` (I# i#)       = W# (x# `shiftRL#` i#)-    (W# x#) `unsafeShiftR` (I# i#) = W# (x# `uncheckedShiftRL#` i#)-    (W# x#) `rotate` (I# i#)-        | isTrue# (i'# ==# 0#) = W# x#-        | otherwise  = W# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (wsib -# i'#)))-        where-        !i'# = i# `andI#` (wsib -# 1#)-        !wsib = WORD_SIZE_IN_BITS#  {- work around preprocessor problem (??) -}-    bitSizeMaybe i           = Just (finiteBitSize i)-    bitSize i                = finiteBitSize i-    isSigned _               = False-    popCount (W# x#)         = I# (word2Int# (popCnt# x#))-    bit                      = bitDefault-    testBit                  = testBitDefault--instance FiniteBits Word where-    finiteBitSize _ = WORD_SIZE_IN_BITS-    countLeadingZeros  (W# x#) = I# (word2Int# (clz# x#))-    countTrailingZeros (W# x#) = I# (word2Int# (ctz# x#))--instance Bits Integer where-   (.&.) = andInteger-   (.|.) = orInteger-   xor = xorInteger-   complement = complementInteger-   shift x i@(I# i#) | i >= 0    = shiftLInteger x i#-                     | otherwise = shiftRInteger x (negateInt# i#)-   shiftL x i@(I# i#)-     | i < 0        = error "Bits.shiftL(Integer): negative shift"-     | otherwise    = shiftLInteger x i#-   shiftR x i@(I# i#)-     | i < 0        = error "Bits.shiftR(Integer): negative shift"-     | otherwise    = shiftRInteger x i#--   testBit x (I# i) = testBitInteger x i--   zeroBits   = 0--#if HAVE_INTEGER_GMP1-   bit (I# i#) = bitInteger i#-   popCount x  = I# (popCountInteger x)-#else-   bit        = bitDefault-   popCount   = popCountDefault-#endif--   rotate x i = shift x i   -- since an Integer never wraps around--   bitSizeMaybe _ = Nothing-   bitSize _  = error "Data.Bits.bitSize(Integer)"-   isSigned _ = True----------------------------------------------------------------------------------- | Attempt to convert an 'Integral' type @a@ to an 'Integral' type @b@ using--- the size of the types as measured by 'Bits' methods.------ A simpler version of this function is:------ > toIntegral :: (Integral a, Integral b) => a -> Maybe b--- > toIntegral x--- >   | toInteger x == y = Just (fromInteger y)--- >   | otherwise        = Nothing--- >   where--- >     y = toInteger x------ This version requires going through 'Integer', which can be inefficient.--- However, @toIntegralSized@ is optimized to allow GHC to statically determine--- the relative type sizes (as measured by 'bitSizeMaybe' and 'isSigned') and--- avoid going through 'Integer' for many types. (The implementation uses--- 'fromIntegral', which is itself optimized with rules for @base@ types but may--- go through 'Integer' for some type pairs.)------ @since 4.8.0.0--toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b-toIntegralSized x                 -- See Note [toIntegralSized optimization]-  | maybe True (<= x) yMinBound-  , maybe True (x <=) yMaxBound = Just y-  | otherwise                   = Nothing-  where-    y = fromIntegral x--    xWidth = bitSizeMaybe x-    yWidth = bitSizeMaybe y--    yMinBound-      | isBitSubType x y = Nothing-      | isSigned x, not (isSigned y) = Just 0-      | isSigned x, isSigned y-      , Just yW <- yWidth = Just (negate $ bit (yW-1)) -- Assumes sub-type-      | otherwise = Nothing--    yMaxBound-      | isBitSubType x y = Nothing-      | isSigned x, not (isSigned y)-      , Just xW <- xWidth, Just yW <- yWidth-      , xW <= yW+1 = Nothing -- Max bound beyond a's domain-      | Just yW <- yWidth = if isSigned y-                            then Just (bit (yW-1)-1)-                            else Just (bit yW-1)-      | otherwise = Nothing-{-# INLINEABLE toIntegralSized #-}---- | 'True' if the size of @a@ is @<=@ the size of @b@, where size is measured--- by 'bitSizeMaybe' and 'isSigned'.-isBitSubType :: (Bits a, Bits b) => a -> b -> Bool-isBitSubType x y-  -- Reflexive-  | xWidth == yWidth, xSigned == ySigned = True--  -- Every integer is a subset of 'Integer'-  | ySigned, Nothing == yWidth                  = True-  | not xSigned, not ySigned, Nothing == yWidth = True--  -- Sub-type relations between fixed-with types-  | xSigned == ySigned,   Just xW <- xWidth, Just yW <- yWidth = xW <= yW-  | not xSigned, ySigned, Just xW <- xWidth, Just yW <- yWidth = xW <  yW--  | otherwise = False-  where-    xWidth  = bitSizeMaybe x-    xSigned = isSigned     x--    yWidth  = bitSizeMaybe y-    ySigned = isSigned     y-{-# INLINE isBitSubType #-}--{-      Note [Constant folding for rotate]-        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The INLINE on the Int instance of rotate enables it to be constant-folded.  For example:-     sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int)-goes to:-   Main.$wfold =-     \ (ww_sO7 :: Int#) (ww1_sOb :: Int#) ->-       case ww1_sOb of wild_XM {-         __DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1);-         10000000 -> ww_sO7-whereas before it was left as a call to $wrotate.--All other Bits instances seem to inline well enough on their-own to enable constant folding; for example 'shift':-     sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int)- goes to:-     Main.$wfold =-       \ (ww_sOb :: Int#) (ww1_sOf :: Int#) ->-         case ww1_sOf of wild_XM {-           __DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1);-           10000000 -> ww_sOb-         }--}---- Note [toIntegralSized optimization]--- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--- The code in 'toIntegralSized' relies on GHC optimizing away statically--- decidable branches.------ If both integral types are statically known, GHC will be able optimize the--- code significantly (for @-O1@ and better).------ For instance (as of GHC 7.8.1) the following definitions:------ > w16_to_i32 = toIntegralSized :: Word16 -> Maybe Int32--- >--- > i16_to_w16 = toIntegralSized :: Int16 -> Maybe Word16------ are translated into the following (simplified) /GHC Core/ language:------ > w16_to_i32 = \x -> Just (case x of _ { W16# x# -> I32# (word2Int# x#) })--- >--- > i16_to_w16 = \x -> case eta of _--- >   { I16# b1 -> case tagToEnum# (<=# 0 b1) of _--- >       { False -> Nothing--- >       ; True -> Just (W16# (narrow16Word# (int2Word# b1)))--- >       }--- >   }
− Data/Bool.hs
@@ -1,61 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Bool--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ The 'Bool' type and related functions.-----------------------------------------------------------------------------------module Data.Bool (-   -- * Booleans-   Bool(..),-   -- ** Operations-   (&&),-   (||),-   not,-   otherwise,-   bool,-  ) where--import GHC.Base---- | Case analysis for the 'Bool' type. @'bool' x y p@ evaluates to @x@--- when @p@ is 'False', and evaluates to @y@ when @p@ is 'True'.------ This is equivalent to @if p then y else x@; that is, one can--- think of it as an if-then-else construct with its arguments--- reordered.------ @since 4.7.0.0------ ==== __Examples__------ Basic usage:------ >>> bool "foo" "bar" True--- "bar"--- >>> bool "foo" "bar" False--- "foo"------ Confirm that @'bool' x y p@ and @if p then y else x@ are--- equivalent:------ >>> let p = True; x = "bar"; y = "foo"--- >>> bool x y p == if p then y else x--- True--- >>> let p = False--- >>> bool x y p == if p then y else x--- True----bool :: a -> a -> Bool -> a-bool f _ False = f-bool _ t True  = t
− Data/Char.hs
@@ -1,497 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Char--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ The Char type and associated operations.-----------------------------------------------------------------------------------module Data.Char-    (-      Char--    -- * Character classification-    -- | Unicode characters are divided into letters, numbers, marks,-    -- punctuation, symbols, separators (including spaces) and others-    -- (including control characters).-    , isControl, isSpace-    , isLower, isUpper, isAlpha, isAlphaNum, isPrint-    , isDigit, isOctDigit, isHexDigit-    , isLetter, isMark, isNumber, isPunctuation, isSymbol, isSeparator--    -- ** Subranges-    , isAscii, isLatin1-    , isAsciiUpper, isAsciiLower--    -- ** Unicode general categories-    , GeneralCategory(..), generalCategory--    -- * Case conversion-    , toUpper, toLower, toTitle--    -- * Single digit characters-    , digitToInt-    , intToDigit--    -- * Numeric representations-    , ord-    , chr--    -- * String representations-    , showLitChar-    , lexLitChar-    , readLitChar-    ) where--import GHC.Base-import GHC.Arr (Ix)-import GHC.Char-import GHC.Real (fromIntegral)-import GHC.Show-import GHC.Read (Read, readLitChar, lexLitChar)-import GHC.Unicode-import GHC.Num-import GHC.Enum---- $setup--- Allow the use of Prelude in doctests.--- >>> import Prelude---- | Convert a single digit 'Char' to the corresponding 'Int'.  This--- function fails unless its argument satisfies 'isHexDigit', but--- recognises both upper- and lower-case hexadecimal digits (that--- is, @\'0\'@..@\'9\'@, @\'a\'@..@\'f\'@, @\'A\'@..@\'F\'@).------ ==== __Examples__------ Characters @\'0\'@ through @\'9\'@ are converted properly to--- @0..9@:------ >>> map digitToInt ['0'..'9']--- [0,1,2,3,4,5,6,7,8,9]------ Both upper- and lower-case @\'A\'@ through @\'F\'@ are converted--- as well, to @10..15@.------ >>> map digitToInt ['a'..'f']--- [10,11,12,13,14,15]--- >>> map digitToInt ['A'..'F']--- [10,11,12,13,14,15]------ Anything else throws an exception:------ >>> digitToInt 'G'--- *** Exception: Char.digitToInt: not a digit 'G'--- >>> digitToInt '♥'--- *** Exception: Char.digitToInt: not a digit '\9829'----digitToInt :: Char -> Int-digitToInt c-  | (fromIntegral dec::Word) <= 9 = dec-  | (fromIntegral hexl::Word) <= 5 = hexl + 10-  | (fromIntegral hexu::Word) <= 5 = hexu + 10-  | otherwise = error ("Char.digitToInt: not a digit " ++ show c) -- sigh-  where-    dec = ord c - ord '0'-    hexl = ord c - ord 'a'-    hexu = ord c - ord 'A'---- | Unicode General Categories (column 2 of the UnicodeData table) in--- the order they are listed in the Unicode standard (the Unicode--- Character Database, in particular).------ ==== __Examples__------ Basic usage:------ >>> :t OtherLetter--- OtherLetter :: GeneralCategory------ 'Eq' instance:------ >>> UppercaseLetter == UppercaseLetter--- True--- >>> UppercaseLetter == LowercaseLetter--- False------ 'Ord' instance:------ >>> NonSpacingMark <= MathSymbol--- True------ 'Enum' instance:------ >>> enumFromTo ModifierLetter SpacingCombiningMark--- [ModifierLetter,OtherLetter,NonSpacingMark,SpacingCombiningMark]------ 'Read' instance:------ >>> read "DashPunctuation" :: GeneralCategory--- DashPunctuation--- >>> read "17" :: GeneralCategory--- *** Exception: Prelude.read: no parse------ 'Show' instance:------ >>> show EnclosingMark--- "EnclosingMark"------ 'Bounded' instance:------ >>> minBound :: GeneralCategory--- UppercaseLetter--- >>> maxBound :: GeneralCategory--- NotAssigned------ 'Ix' instance:------  >>> import Data.Ix ( index )---  >>> index (OtherLetter,Control) FinalQuote---  12---  >>> index (OtherLetter,Control) Format---  *** Exception: Error in array index----data GeneralCategory-        = UppercaseLetter       -- ^ Lu: Letter, Uppercase-        | LowercaseLetter       -- ^ Ll: Letter, Lowercase-        | TitlecaseLetter       -- ^ Lt: Letter, Titlecase-        | ModifierLetter        -- ^ Lm: Letter, Modifier-        | OtherLetter           -- ^ Lo: Letter, Other-        | NonSpacingMark        -- ^ Mn: Mark, Non-Spacing-        | SpacingCombiningMark  -- ^ Mc: Mark, Spacing Combining-        | EnclosingMark         -- ^ Me: Mark, Enclosing-        | DecimalNumber         -- ^ Nd: Number, Decimal-        | LetterNumber          -- ^ Nl: Number, Letter-        | OtherNumber           -- ^ No: Number, Other-        | ConnectorPunctuation  -- ^ Pc: Punctuation, Connector-        | DashPunctuation       -- ^ Pd: Punctuation, Dash-        | OpenPunctuation       -- ^ Ps: Punctuation, Open-        | ClosePunctuation      -- ^ Pe: Punctuation, Close-        | InitialQuote          -- ^ Pi: Punctuation, Initial quote-        | FinalQuote            -- ^ Pf: Punctuation, Final quote-        | OtherPunctuation      -- ^ Po: Punctuation, Other-        | MathSymbol            -- ^ Sm: Symbol, Math-        | CurrencySymbol        -- ^ Sc: Symbol, Currency-        | ModifierSymbol        -- ^ Sk: Symbol, Modifier-        | OtherSymbol           -- ^ So: Symbol, Other-        | Space                 -- ^ Zs: Separator, Space-        | LineSeparator         -- ^ Zl: Separator, Line-        | ParagraphSeparator    -- ^ Zp: Separator, Paragraph-        | Control               -- ^ Cc: Other, Control-        | Format                -- ^ Cf: Other, Format-        | Surrogate             -- ^ Cs: Other, Surrogate-        | PrivateUse            -- ^ Co: Other, Private Use-        | NotAssigned           -- ^ Cn: Other, Not Assigned-        deriving (Eq, Ord, Enum, Read, Show, Bounded, Ix)---- | The Unicode general category of the character. This relies on the--- 'Enum' instance of 'GeneralCategory', which must remain in the--- same order as the categories are presented in the Unicode--- standard.------ ==== __Examples__------ Basic usage:------ >>> generalCategory 'a'--- LowercaseLetter--- >>> generalCategory 'A'--- UppercaseLetter--- >>> generalCategory '0'--- DecimalNumber--- >>> generalCategory '%'--- OtherPunctuation--- >>> generalCategory '♥'--- OtherSymbol--- >>> generalCategory '\31'--- Control--- >>> generalCategory ' '--- Space----generalCategory :: Char -> GeneralCategory-generalCategory c = toEnum $ fromIntegral $ wgencat $ fromIntegral $ ord c---- derived character classifiers---- | Selects alphabetic Unicode characters (lower-case, upper-case and--- title-case letters, plus letters of caseless scripts and--- modifiers letters). This function is equivalent to--- 'Data.Char.isAlpha'.------ This function returns 'True' if its argument has one of the--- following 'GeneralCategory's, or 'False' otherwise:------ * 'UppercaseLetter'--- * 'LowercaseLetter'--- * 'TitlecaseLetter'--- * 'ModifierLetter'--- * 'OtherLetter'------ These classes are defined in the--- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,--- part of the Unicode standard. The same document defines what is--- and is not a \"Letter\".------ ==== __Examples__------ Basic usage:------ >>> isLetter 'a'--- True--- >>> isLetter 'A'--- True--- >>> isLetter '0'--- False--- >>> isLetter '%'--- False--- >>> isLetter '♥'--- False--- >>> isLetter '\31'--- False------ Ensure that 'isLetter' and 'isAlpha' are equivalent.------ >>> let chars = [(chr 0)..]--- >>> let letters = map isLetter chars--- >>> let alphas = map isAlpha chars--- >>> letters == alphas--- True----isLetter :: Char -> Bool-isLetter c = case generalCategory c of-        UppercaseLetter         -> True-        LowercaseLetter         -> True-        TitlecaseLetter         -> True-        ModifierLetter          -> True-        OtherLetter             -> True-        _                       -> False---- | Selects Unicode mark characters, for example accents and the--- like, which combine with preceding characters.------ This function returns 'True' if its argument has one of the--- following 'GeneralCategory's, or 'False' otherwise:------ * 'NonSpacingMark'--- * 'SpacingCombiningMark'--- * 'EnclosingMark'------ These classes are defined in the--- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,--- part of the Unicode standard. The same document defines what is--- and is not a \"Mark\".------ ==== __Examples__------ Basic usage:------ >>> isMark 'a'--- False--- >>> isMark '0'--- False------ Combining marks such as accent characters usually need to follow--- another character before they become printable:------ >>> map isMark "ò"--- [False,True]------ Puns are not necessarily supported:------ >>> isMark '✓'--- False----isMark :: Char -> Bool-isMark c = case generalCategory c of-        NonSpacingMark          -> True-        SpacingCombiningMark    -> True-        EnclosingMark           -> True-        _                       -> False---- | Selects Unicode numeric characters, including digits from various--- scripts, Roman numerals, et cetera.------ This function returns 'True' if its argument has one of the--- following 'GeneralCategory's, or 'False' otherwise:------ * 'DecimalNumber'--- * 'LetterNumber'--- * 'OtherNumber'------ These classes are defined in the--- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,--- part of the Unicode standard. The same document defines what is--- and is not a \"Number\".------ ==== __Examples__------ Basic usage:------ >>> isNumber 'a'--- False--- >>> isNumber '%'--- False--- >>> isNumber '3'--- True------ ASCII @\'0\'@ through @\'9\'@ are all numbers:------ >>> and $ map isNumber ['0'..'9']--- True------ Unicode Roman numerals are \"numbers\" as well:------ >>> isNumber 'Ⅸ'--- True----isNumber :: Char -> Bool-isNumber c = case generalCategory c of-        DecimalNumber           -> True-        LetterNumber            -> True-        OtherNumber             -> True-        _                       -> False---- | Selects Unicode punctuation characters, including various kinds--- of connectors, brackets and quotes.------ This function returns 'True' if its argument has one of the--- following 'GeneralCategory's, or 'False' otherwise:------ * 'ConnectorPunctuation'--- * 'DashPunctuation'--- * 'OpenPunctuation'--- * 'ClosePunctuation'--- * 'InitialQuote'--- * 'FinalQuote'--- * 'OtherPunctuation'------ These classes are defined in the--- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,--- part of the Unicode standard. The same document defines what is--- and is not a \"Punctuation\".------ ==== __Examples__------ Basic usage:------ >>> isPunctuation 'a'--- False--- >>> isPunctuation '7'--- False--- >>> isPunctuation '♥'--- False--- >>> isPunctuation '"'--- True--- >>> isPunctuation '?'--- True--- >>> isPunctuation '—'--- True----isPunctuation :: Char -> Bool-isPunctuation c = case generalCategory c of-        ConnectorPunctuation    -> True-        DashPunctuation         -> True-        OpenPunctuation         -> True-        ClosePunctuation        -> True-        InitialQuote            -> True-        FinalQuote              -> True-        OtherPunctuation        -> True-        _                       -> False---- | Selects Unicode symbol characters, including mathematical and--- currency symbols.------ This function returns 'True' if its argument has one of the--- following 'GeneralCategory's, or 'False' otherwise:------ * 'MathSymbol'--- * 'CurrencySymbol'--- * 'ModifierSymbol'--- * 'OtherSymbol'------ These classes are defined in the--- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,--- part of the Unicode standard. The same document defines what is--- and is not a \"Symbol\".------ ==== __Examples__------ Basic usage:------ >>> isSymbol 'a'--- False--- >>> isSymbol '6'--- False--- >>> isSymbol '='--- True------ The definition of \"math symbol\" may be a little--- counter-intuitive depending on one's background:------ >>> isSymbol '+'--- True--- >>> isSymbol '-'--- False----isSymbol :: Char -> Bool-isSymbol c = case generalCategory c of-        MathSymbol              -> True-        CurrencySymbol          -> True-        ModifierSymbol          -> True-        OtherSymbol             -> True-        _                       -> False---- | Selects Unicode space and separator characters.------ This function returns 'True' if its argument has one of the--- following 'GeneralCategory's, or 'False' otherwise:------ * 'Space'--- * 'LineSeparator'--- * 'ParagraphSeparator'------ These classes are defined in the--- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,--- part of the Unicode standard. The same document defines what is--- and is not a \"Separator\".------ ==== __Examples__------ Basic usage:------ >>> isSeparator 'a'--- False--- >>> isSeparator '6'--- False--- >>> isSeparator ' '--- True------ Warning: newlines and tab characters are not considered--- separators.------ >>> isSeparator '\n'--- False--- >>> isSeparator '\t'--- False------ But some more exotic characters are (like HTML's @&nbsp;@):------ >>> isSeparator '\160'--- True----isSeparator :: Char -> Bool-isSeparator c = case generalCategory c of-        Space                   -> True-        LineSeparator           -> True-        ParagraphSeparator      -> True-        _                       -> False-
− Data/Coerce.hs
@@ -1,30 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Coerce--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Safe coercions between data types.------ More in-depth information can be found on the--- <https://ghc.haskell.org/trac/ghc/wiki/Roles Roles wiki page>------ @since 4.7.0.0--------------------------------------------------------------------------------module Data.Coerce-        ( -- * Safe coercions-          coerce, Coercible,-        ) where-import GHC.Prim (coerce)-import GHC.Types (Coercible)--import GHC.Base () -- for build ordering-
− Data/Complex.hs
@@ -1,188 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE AutoDeriveTypeable #-}-{-# LANGUAGE StandaloneDeriving #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Complex--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Complex numbers.-----------------------------------------------------------------------------------module Data.Complex-        (-        -- * Rectangular form-          Complex((:+))--        , realPart-        , imagPart-        -- * Polar form-        , mkPolar-        , cis-        , polar-        , magnitude-        , phase-        -- * Conjugate-        , conjugate--        )  where--import Data.Typeable-import Data.Data (Data)-import Foreign (Storable, castPtr, peek, poke, pokeElemOff, peekElemOff, sizeOf,-                alignment)--infix  6  :+---- -------------------------------------------------------------------------------- The Complex type---- | Complex numbers are an algebraic type.------ For a complex number @z@, @'abs' z@ is a number with the magnitude of @z@,--- but oriented in the positive real direction, whereas @'signum' z@--- has the phase of @z@, but unit magnitude.-data Complex a-  = !a :+ !a    -- ^ forms a complex number from its real and imaginary-                -- rectangular components.-        deriving (Eq, Show, Read, Data, Typeable)---- -------------------------------------------------------------------------------- Functions over Complex---- | Extracts the real part of a complex number.-realPart :: Complex a -> a-realPart (x :+ _) =  x---- | Extracts the imaginary part of a complex number.-imagPart :: Complex a -> a-imagPart (_ :+ y) =  y---- | The conjugate of a complex number.-{-# SPECIALISE conjugate :: Complex Double -> Complex Double #-}-conjugate        :: Num a => Complex a -> Complex a-conjugate (x:+y) =  x :+ (-y)---- | Form a complex number from polar components of magnitude and phase.-{-# SPECIALISE mkPolar :: Double -> Double -> Complex Double #-}-mkPolar          :: Floating a => a -> a -> Complex a-mkPolar r theta  =  r * cos theta :+ r * sin theta---- | @'cis' t@ is a complex value with magnitude @1@--- and phase @t@ (modulo @2*'pi'@).-{-# SPECIALISE cis :: Double -> Complex Double #-}-cis              :: Floating a => a -> Complex a-cis theta        =  cos theta :+ sin theta---- | The function 'polar' takes a complex number and--- returns a (magnitude, phase) pair in canonical form:--- the magnitude is nonnegative, and the phase in the range @(-'pi', 'pi']@;--- if the magnitude is zero, then so is the phase.-{-# SPECIALISE polar :: Complex Double -> (Double,Double) #-}-polar            :: (RealFloat a) => Complex a -> (a,a)-polar z          =  (magnitude z, phase z)---- | The nonnegative magnitude of a complex number.-{-# SPECIALISE magnitude :: Complex Double -> Double #-}-magnitude :: (RealFloat a) => Complex a -> a-magnitude (x:+y) =  scaleFloat k-                     (sqrt (sqr (scaleFloat mk x) + sqr (scaleFloat mk y)))-                    where k  = max (exponent x) (exponent y)-                          mk = - k-                          sqr z = z * z---- | The phase of a complex number, in the range @(-'pi', 'pi']@.--- If the magnitude is zero, then so is the phase.-{-# SPECIALISE phase :: Complex Double -> Double #-}-phase :: (RealFloat a) => Complex a -> a-phase (0 :+ 0)   = 0            -- SLPJ July 97 from John Peterson-phase (x:+y)     = atan2 y x----- -------------------------------------------------------------------------------- Instances of Complex--instance  (RealFloat a) => Num (Complex a)  where-    {-# SPECIALISE instance Num (Complex Float) #-}-    {-# SPECIALISE instance Num (Complex Double) #-}-    (x:+y) + (x':+y')   =  (x+x') :+ (y+y')-    (x:+y) - (x':+y')   =  (x-x') :+ (y-y')-    (x:+y) * (x':+y')   =  (x*x'-y*y') :+ (x*y'+y*x')-    negate (x:+y)       =  negate x :+ negate y-    abs z               =  magnitude z :+ 0-    signum (0:+0)       =  0-    signum z@(x:+y)     =  x/r :+ y/r  where r = magnitude z-    fromInteger n       =  fromInteger n :+ 0--instance  (RealFloat a) => Fractional (Complex a)  where-    {-# SPECIALISE instance Fractional (Complex Float) #-}-    {-# SPECIALISE instance Fractional (Complex Double) #-}-    (x:+y) / (x':+y')   =  (x*x''+y*y'') / d :+ (y*x''-x*y'') / d-                           where x'' = scaleFloat k x'-                                 y'' = scaleFloat k y'-                                 k   = - max (exponent x') (exponent y')-                                 d   = x'*x'' + y'*y''--    fromRational a      =  fromRational a :+ 0--instance  (RealFloat a) => Floating (Complex a) where-    {-# SPECIALISE instance Floating (Complex Float) #-}-    {-# SPECIALISE instance Floating (Complex Double) #-}-    pi             =  pi :+ 0-    exp (x:+y)     =  expx * cos y :+ expx * sin y-                      where expx = exp x-    log z          =  log (magnitude z) :+ phase z--    sqrt (0:+0)    =  0-    sqrt z@(x:+y)  =  u :+ (if y < 0 then -v else v)-                      where (u,v) = if x < 0 then (v',u') else (u',v')-                            v'    = abs y / (u'*2)-                            u'    = sqrt ((magnitude z + abs x) / 2)--    sin (x:+y)     =  sin x * cosh y :+ cos x * sinh y-    cos (x:+y)     =  cos x * cosh y :+ (- sin x * sinh y)-    tan (x:+y)     =  (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))-                      where sinx  = sin x-                            cosx  = cos x-                            sinhy = sinh y-                            coshy = cosh y--    sinh (x:+y)    =  cos y * sinh x :+ sin  y * cosh x-    cosh (x:+y)    =  cos y * cosh x :+ sin y * sinh x-    tanh (x:+y)    =  (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)-                      where siny  = sin y-                            cosy  = cos y-                            sinhx = sinh x-                            coshx = cosh x--    asin z@(x:+y)  =  y':+(-x')-                      where  (x':+y') = log (((-y):+x) + sqrt (1 - z*z))-    acos z         =  y'':+(-x'')-                      where (x'':+y'') = log (z + ((-y'):+x'))-                            (x':+y')   = sqrt (1 - z*z)-    atan z@(x:+y)  =  y':+(-x')-                      where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))--    asinh z        =  log (z + sqrt (1+z*z))-    acosh z        =  log (z + (z+1) * sqrt ((z-1)/(z+1)))-    atanh z        =  0.5 * log ((1.0+z) / (1.0-z))--instance Storable a => Storable (Complex a) where-    sizeOf a       = 2 * sizeOf (realPart a)-    alignment a    = alignment (realPart a)-    peek p           = do-                        q <- return $ castPtr p-                        r <- peek q-                        i <- peekElemOff q 1-                        return (r :+ i)-    poke p (r :+ i)  = do-                        q <-return $  (castPtr p)-                        poke q r-                        pokeElemOff q 1 i
− Data/Data.hs
@@ -1,1400 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE RankNTypes, ScopedTypeVariables, PolyKinds, StandaloneDeriving,-             AutoDeriveTypeable, TypeOperators, GADTs, FlexibleInstances #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Data--- Copyright   :  (c) The University of Glasgow, CWI 2001--2004--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (local universal quantification)------ \"Scrap your boilerplate\" --- Generic programming in Haskell.  See--- <http://www.haskell.org/haskellwiki/Research_papers/Generics#Scrap_your_boilerplate.21>.--- This module provides the 'Data' class with its primitives for--- generic programming, along with instances for many datatypes. It--- corresponds to a merge between the previous "Data.Generics.Basics"--- and almost all of "Data.Generics.Instances". The instances that are--- not present in this module were moved to the--- @Data.Generics.Instances@ module in the @syb@ package.------ For more information, please visit the new--- SYB wiki: <http://www.cs.uu.nl/wiki/bin/view/GenericProgramming/SYB>.-----------------------------------------------------------------------------------module Data.Data (--        -- * Module Data.Typeable re-exported for convenience-        module Data.Typeable,--        -- * The Data class for processing constructor applications-        Data(-                gfoldl,-                gunfold,-                toConstr,-                dataTypeOf,-                dataCast1,      -- mediate types and unary type constructors-                dataCast2,      -- mediate types and binary type constructors-                -- Generic maps defined in terms of gfoldl-                gmapT,-                gmapQ,-                gmapQl,-                gmapQr,-                gmapQi,-                gmapM,-                gmapMp,-                gmapMo-            ),--        -- * Datatype representations-        DataType,       -- abstract-        -- ** Constructors-        mkDataType,-        mkIntType,-        mkFloatType,-        mkCharType,-        mkNoRepType,-        -- ** Observers-        dataTypeName,-        DataRep(..),-        dataTypeRep,-        -- ** Convenience functions-        repConstr,-        isAlgType,-        dataTypeConstrs,-        indexConstr,-        maxConstrIndex,-        isNorepType,--        -- * Data constructor representations-        Constr,         -- abstract-        ConIndex,       -- alias for Int, start at 1-        Fixity(..),-        -- ** Constructors-        mkConstr,-        mkIntegralConstr,-        mkRealConstr,-        mkCharConstr,-        -- ** Observers-        constrType,-        ConstrRep(..),-        constrRep,-        constrFields,-        constrFixity,-        -- ** Convenience function: algebraic data types-        constrIndex,-        -- ** From strings to constructors and vice versa: all data types-        showConstr,-        readConstr,--        -- * Convenience functions: take type constructors apart-        tyconUQname,-        tyconModule,--        -- * Generic operations defined in terms of 'gunfold'-        fromConstr,-        fromConstrB,-        fromConstrM--  ) where-----------------------------------------------------------------------------------import Data.Either-import Data.Eq-import Data.Maybe-import Data.Ord-import Data.Typeable-import Data.Version( Version(..) )-import GHC.Base-import GHC.List-import GHC.Num-import GHC.Read-import GHC.Show-import Text.Read( reads )---- Imports for the instances-import Data.Int              -- So we can give Data instance for Int8, ...-import Data.Type.Coercion-import Data.Word             -- So we can give Data instance for Word8, ...-import GHC.Real              -- So we can give Data instance for Ratio---import GHC.IOBase            -- So we can give Data instance for IO, Handle-import GHC.Ptr               -- So we can give Data instance for Ptr-import GHC.ForeignPtr        -- So we can give Data instance for ForeignPtr---import GHC.Stable            -- So we can give Data instance for StablePtr---import GHC.ST                -- So we can give Data instance for ST---import GHC.Conc              -- So we can give Data instance for MVar & Co.-import GHC.Arr               -- So we can give Data instance for Array---------------------------------------------------------------------------------------      The Data class------------------------------------------------------------------------------------{- |-The 'Data' class comprehends a fundamental primitive 'gfoldl' for-folding over constructor applications, say terms. This primitive can-be instantiated in several ways to map over the immediate subterms-of a term; see the @gmap@ combinators later in this class.  Indeed, a-generic programmer does not necessarily need to use the ingenious gfoldl-primitive but rather the intuitive @gmap@ combinators.  The 'gfoldl'-primitive is completed by means to query top-level constructors, to-turn constructor representations into proper terms, and to list all-possible datatype constructors.  This completion allows us to serve-generic programming scenarios like read, show, equality, term generation.--The combinators 'gmapT', 'gmapQ', 'gmapM', etc are all provided with-default definitions in terms of 'gfoldl', leaving open the opportunity-to provide datatype-specific definitions.-(The inclusion of the @gmap@ combinators as members of class 'Data'-allows the programmer or the compiler to derive specialised, and maybe-more efficient code per datatype.  /Note/: 'gfoldl' is more higher-order-than the @gmap@ combinators.  This is subject to ongoing benchmarking-experiments.  It might turn out that the @gmap@ combinators will be-moved out of the class 'Data'.)--Conceptually, the definition of the @gmap@ combinators in terms of the-primitive 'gfoldl' requires the identification of the 'gfoldl' function-arguments.  Technically, we also need to identify the type constructor-@c@ for the construction of the result type from the folded term type.--In the definition of @gmapQ@/x/ combinators, we use phantom type-constructors for the @c@ in the type of 'gfoldl' because the result type-of a query does not involve the (polymorphic) type of the term argument.-In the definition of 'gmapQl' we simply use the plain constant type-constructor because 'gfoldl' is left-associative anyway and so it is-readily suited to fold a left-associative binary operation over the-immediate subterms.  In the definition of gmapQr, extra effort is-needed. We use a higher-order accumulation trick to mediate between-left-associative constructor application vs. right-associative binary-operation (e.g., @(:)@).  When the query is meant to compute a value-of type @r@, then the result type withing generic folding is @r -> r@.-So the result of folding is a function to which we finally pass the-right unit.--With the @-XDeriveDataTypeable@ option, GHC can generate instances of the-'Data' class automatically.  For example, given the declaration--> data T a b = C1 a b | C2 deriving (Typeable, Data)--GHC will generate an instance that is equivalent to--> instance (Data a, Data b) => Data (T a b) where->     gfoldl k z (C1 a b) = z C1 `k` a `k` b->     gfoldl k z C2       = z C2->->     gunfold k z c = case constrIndex c of->                         1 -> k (k (z C1))->                         2 -> z C2->->     toConstr (C1 _ _) = con_C1->     toConstr C2       = con_C2->->     dataTypeOf _ = ty_T->-> con_C1 = mkConstr ty_T "C1" [] Prefix-> con_C2 = mkConstr ty_T "C2" [] Prefix-> ty_T   = mkDataType "Module.T" [con_C1, con_C2]--This is suitable for datatypes that are exported transparently.---}--class Typeable a => Data a where--  -- | Left-associative fold operation for constructor applications.-  ---  -- The type of 'gfoldl' is a headache, but operationally it is a simple-  -- generalisation of a list fold.-  ---  -- The default definition for 'gfoldl' is @'const' 'id'@, which is-  -- suitable for abstract datatypes with no substructures.-  gfoldl  :: (forall d b. Data d => c (d -> b) -> d -> c b)-                -- ^ defines how nonempty constructor applications are-                -- folded.  It takes the folded tail of the constructor-                -- application and its head, i.e., an immediate subterm,-                -- and combines them in some way.-          -> (forall g. g -> c g)-                -- ^ defines how the empty constructor application is-                -- folded, like the neutral \/ start element for list-                -- folding.-          -> a-                -- ^ structure to be folded.-          -> c a-                -- ^ result, with a type defined in terms of @a@, but-                -- variability is achieved by means of type constructor-                -- @c@ for the construction of the actual result type.--  -- See the 'Data' instances in this file for an illustration of 'gfoldl'.--  gfoldl _ z = z--  -- | Unfolding constructor applications-  gunfold :: (forall b r. Data b => c (b -> r) -> c r)-          -> (forall r. r -> c r)-          -> Constr-          -> c a--  -- | Obtaining the constructor from a given datum.-  -- For proper terms, this is meant to be the top-level constructor.-  -- Primitive datatypes are here viewed as potentially infinite sets of-  -- values (i.e., constructors).-  toConstr   :: a -> Constr---  -- | The outer type constructor of the type-  dataTypeOf  :: a -> DataType---------------------------------------------------------------------------------------- Mediate types and type constructors------------------------------------------------------------------------------------  -- | Mediate types and unary type constructors.-  -- In 'Data' instances of the form @T a@, 'dataCast1' should be defined-  -- as 'gcast1'.-  ---  -- The default definition is @'const' 'Nothing'@, which is appropriate-  -- for non-unary type constructors.-  dataCast1 :: Typeable t-            => (forall d. Data d => c (t d))-            -> Maybe (c a)-  dataCast1 _ = Nothing--  -- | Mediate types and binary type constructors.-  -- In 'Data' instances of the form @T a b@, 'dataCast2' should be-  -- defined as 'gcast2'.-  ---  -- The default definition is @'const' 'Nothing'@, which is appropriate-  -- for non-binary type constructors.-  dataCast2 :: Typeable t-            => (forall d e. (Data d, Data e) => c (t d e))-            -> Maybe (c a)-  dataCast2 _ = Nothing----------------------------------------------------------------------------------------      Typical generic maps defined in terms of gfoldl-------------------------------------------------------------------------------------  -- | A generic transformation that maps over the immediate subterms-  ---  -- The default definition instantiates the type constructor @c@ in the-  -- type of 'gfoldl' to an identity datatype constructor, using the-  -- isomorphism pair as injection and projection.-  gmapT :: (forall b. Data b => b -> b) -> a -> a--  -- Use an identity datatype constructor ID (see below)-  -- to instantiate the type constructor c in the type of gfoldl,-  -- and perform injections ID and projections unID accordingly.-  ---  gmapT f x0 = unID (gfoldl k ID x0)-    where-      k :: Data d => ID (d->b) -> d -> ID b-      k (ID c) x = ID (c (f x))---  -- | A generic query with a left-associative binary operator-  gmapQl :: forall r r'. (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> a -> r-  gmapQl o r f = unCONST . gfoldl k z-    where-      k :: Data d => CONST r (d->b) -> d -> CONST r b-      k c x = CONST $ (unCONST c) `o` f x-      z :: g -> CONST r g-      z _   = CONST r--  -- | A generic query with a right-associative binary operator-  gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> a -> r-  gmapQr o r0 f x0 = unQr (gfoldl k (const (Qr id)) x0) r0-    where-      k :: Data d => Qr r (d->b) -> d -> Qr r b-      k (Qr c) x = Qr (\r -> c (f x `o` r))---  -- | A generic query that processes the immediate subterms and returns a list-  -- of results.  The list is given in the same order as originally specified-  -- in the declaration of the data constructors.-  gmapQ :: (forall d. Data d => d -> u) -> a -> [u]-  gmapQ f = gmapQr (:) [] f---  -- | A generic query that processes one child by index (zero-based)-  gmapQi :: forall u. Int -> (forall d. Data d => d -> u) -> a -> u-  gmapQi i f x = case gfoldl k z x of { Qi _ q -> fromJust q }-    where-      k :: Data d => Qi u (d -> b) -> d -> Qi u b-      k (Qi i' q) a = Qi (i'+1) (if i==i' then Just (f a) else q)-      z :: g -> Qi q g-      z _           = Qi 0 Nothing---  -- | A generic monadic transformation that maps over the immediate subterms-  ---  -- The default definition instantiates the type constructor @c@ in-  -- the type of 'gfoldl' to the monad datatype constructor, defining-  -- injection and projection using 'return' and '>>='.-  gmapM :: forall m. Monad m => (forall d. Data d => d -> m d) -> a -> m a--  -- Use immediately the monad datatype constructor-  -- to instantiate the type constructor c in the type of gfoldl,-  -- so injection and projection is done by return and >>=.-  ---  gmapM f = gfoldl k return-    where-      k :: Data d => m (d -> b) -> d -> m b-      k c x = do c' <- c-                 x' <- f x-                 return (c' x')---  -- | Transformation of at least one immediate subterm does not fail-  gmapMp :: forall m. MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a--{---The type constructor that we use here simply keeps track of the fact-if we already succeeded for an immediate subterm; see Mp below. To-this end, we couple the monadic computation with a Boolean.---}--  gmapMp f x = unMp (gfoldl k z x) >>= \(x',b) ->-                if b then return x' else mzero-    where-      z :: g -> Mp m g-      z g = Mp (return (g,False))-      k :: Data d => Mp m (d -> b) -> d -> Mp m b-      k (Mp c) y-        = Mp ( c >>= \(h, b) ->-                 (f y >>= \y' -> return (h y', True))-                 `mplus` return (h y, b)-             )--  -- | Transformation of one immediate subterm with success-  gmapMo :: forall m. MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a--{---We use the same pairing trick as for gmapMp,-i.e., we use an extra Bool component to keep track of the-fact whether an immediate subterm was processed successfully.-However, we cut of mapping over subterms once a first subterm-was transformed successfully.---}--  gmapMo f x = unMp (gfoldl k z x) >>= \(x',b) ->-                if b then return x' else mzero-    where-      z :: g -> Mp m g-      z g = Mp (return (g,False))-      k :: Data d => Mp m (d -> b) -> d -> Mp m b-      k (Mp c) y-        = Mp ( c >>= \(h,b) -> if b-                        then return (h y, b)-                        else (f y >>= \y' -> return (h y',True))-                             `mplus` return (h y, b)-             )----- | The identity type constructor needed for the definition of gmapT-newtype ID x = ID { unID :: x }----- | The constant type constructor needed for the definition of gmapQl-newtype CONST c a = CONST { unCONST :: c }----- | Type constructor for adding counters to queries-data Qi q a = Qi Int (Maybe q)----- | The type constructor used in definition of gmapQr-newtype Qr r a = Qr { unQr  :: r -> r }----- | The type constructor used in definition of gmapMp-newtype Mp m x = Mp { unMp :: m (x, Bool) }----------------------------------------------------------------------------------------      Generic unfolding--------------------------------------------------------------------------------------- | Build a term skeleton-fromConstr :: Data a => Constr -> a-fromConstr = fromConstrB (error "Data.Data.fromConstr")----- | Build a term and use a generic function for subterms-fromConstrB :: Data a-            => (forall d. Data d => d)-            -> Constr-            -> a-fromConstrB f = unID . gunfold k z- where-  k :: forall b r. Data b => ID (b -> r) -> ID r-  k c = ID (unID c f)--  z :: forall r. r -> ID r-  z = ID----- | Monadic variation on 'fromConstrB'-fromConstrM :: forall m a. (Monad m, Data a)-            => (forall d. Data d => m d)-            -> Constr-            -> m a-fromConstrM f = gunfold k z- where-  k :: forall b r. Data b => m (b -> r) -> m r-  k c = do { c' <- c; b <- f; return (c' b) }--  z :: forall r. r -> m r-  z = return----------------------------------------------------------------------------------------      Datatype and constructor representations------------------------------------------------------------------------------------------ | Representation of datatypes.--- A package of constructor representations with names of type and module.----data DataType = DataType-                        { tycon   :: String-                        , datarep :: DataRep-                        }--              deriving Show---- | Representation of constructors. Note that equality on constructors--- with different types may not work -- i.e. the constructors for 'False' and--- 'Nothing' may compare equal.-data Constr = Constr-                        { conrep    :: ConstrRep-                        , constring :: String-                        , confields :: [String] -- for AlgRep only-                        , confixity :: Fixity   -- for AlgRep only-                        , datatype  :: DataType-                        }--instance Show Constr where- show = constring----- | Equality of constructors-instance Eq Constr where-  c == c' = constrRep c == constrRep c'----- | Public representation of datatypes-data DataRep = AlgRep [Constr]-             | IntRep-             | FloatRep-             | CharRep-             | NoRep--            deriving (Eq,Show)--- The list of constructors could be an array, a balanced tree, or others.----- | Public representation of constructors-data ConstrRep = AlgConstr    ConIndex-               | IntConstr    Integer-               | FloatConstr  Rational-               | CharConstr   Char--               deriving (Eq,Show)----- | Unique index for datatype constructors,--- counting from 1 in the order they are given in the program text.-type ConIndex = Int----- | Fixity of constructors-data Fixity = Prefix-            | Infix     -- Later: add associativity and precedence--            deriving (Eq,Show)---------------------------------------------------------------------------------------      Observers for datatype representations--------------------------------------------------------------------------------------- | Gets the type constructor including the module-dataTypeName :: DataType -> String-dataTypeName = tycon------ | Gets the public presentation of a datatype-dataTypeRep :: DataType -> DataRep-dataTypeRep = datarep----- | Gets the datatype of a constructor-constrType :: Constr -> DataType-constrType = datatype----- | Gets the public presentation of constructors-constrRep :: Constr -> ConstrRep-constrRep = conrep----- | Look up a constructor by its representation-repConstr :: DataType -> ConstrRep -> Constr-repConstr dt cr =-      case (dataTypeRep dt, cr) of-        (AlgRep cs, AlgConstr i)      -> cs !! (i-1)-        (IntRep,    IntConstr i)      -> mkIntegralConstr dt i-        (FloatRep,  FloatConstr f)    -> mkRealConstr dt f-        (CharRep,   CharConstr c)     -> mkCharConstr dt c-        _ -> error "Data.Data.repConstr: The given ConstrRep does not fit to the given DataType."----------------------------------------------------------------------------------------      Representations of algebraic data types--------------------------------------------------------------------------------------- | Constructs an algebraic datatype-mkDataType :: String -> [Constr] -> DataType-mkDataType str cs = DataType-                        { tycon   = str-                        , datarep = AlgRep cs-                        }----- | Constructs a constructor-mkConstr :: DataType -> String -> [String] -> Fixity -> Constr-mkConstr dt str fields fix =-        Constr-                { conrep    = AlgConstr idx-                , constring = str-                , confields = fields-                , confixity = fix-                , datatype  = dt-                }-  where-    idx = head [ i | (c,i) <- dataTypeConstrs dt `zip` [1..],-                     showConstr c == str ]----- | Gets the constructors of an algebraic datatype-dataTypeConstrs :: DataType -> [Constr]-dataTypeConstrs dt = case datarep dt of-                        (AlgRep cons) -> cons-                        _ -> error $ "Data.Data.dataTypeConstrs is not supported for "-                                    ++ dataTypeName dt ++-                                    ", as it is not an algebraic data type."----- | Gets the field labels of a constructor.  The list of labels--- is returned in the same order as they were given in the original--- constructor declaration.-constrFields :: Constr -> [String]-constrFields = confields----- | Gets the fixity of a constructor-constrFixity :: Constr -> Fixity-constrFixity = confixity----------------------------------------------------------------------------------------      From strings to constr's and vice versa: all data types--------------------------------------------------------------------------------------- | Gets the string for a constructor-showConstr :: Constr -> String-showConstr = constring----- | Lookup a constructor via a string-readConstr :: DataType -> String -> Maybe Constr-readConstr dt str =-      case dataTypeRep dt of-        AlgRep cons -> idx cons-        IntRep      -> mkReadCon (\i -> (mkPrimCon dt str (IntConstr i)))-        FloatRep    -> mkReadCon ffloat-        CharRep     -> mkReadCon (\c -> (mkPrimCon dt str (CharConstr c)))-        NoRep       -> Nothing-  where--    -- Read a value and build a constructor-    mkReadCon :: Read t => (t -> Constr) -> Maybe Constr-    mkReadCon f = case (reads str) of-                    [(t,"")] -> Just (f t)-                    _ -> Nothing--    -- Traverse list of algebraic datatype constructors-    idx :: [Constr] -> Maybe Constr-    idx cons = let fit = filter ((==) str . showConstr) cons-                in if fit == []-                     then Nothing-                     else Just (head fit)--    ffloat :: Double -> Constr-    ffloat =  mkPrimCon dt str . FloatConstr . toRational--------------------------------------------------------------------------------------      Convenience funtions: algebraic data types--------------------------------------------------------------------------------------- | Test for an algebraic type-isAlgType :: DataType -> Bool-isAlgType dt = case datarep dt of-                 (AlgRep _) -> True-                 _ -> False----- | Gets the constructor for an index (algebraic datatypes only)-indexConstr :: DataType -> ConIndex -> Constr-indexConstr dt idx = case datarep dt of-                        (AlgRep cs) -> cs !! (idx-1)-                        _           -> error $ "Data.Data.indexConstr is not supported for "-                                               ++ dataTypeName dt ++-                                               ", as it is not an algebraic data type."----- | Gets the index of a constructor (algebraic datatypes only)-constrIndex :: Constr -> ConIndex-constrIndex con = case constrRep con of-                    (AlgConstr idx) -> idx-                    _ -> error $ "Data.Data.constrIndex is not supported for "-                                 ++ dataTypeName (constrType con) ++-                                 ", as it is not an algebraic data type."----- | Gets the maximum constructor index of an algebraic datatype-maxConstrIndex :: DataType -> ConIndex-maxConstrIndex dt = case dataTypeRep dt of-                        AlgRep cs -> length cs-                        _            -> error $ "Data.Data.maxConstrIndex is not supported for "-                                                 ++ dataTypeName dt ++-                                                 ", as it is not an algebraic data type."----------------------------------------------------------------------------------------      Representation of primitive types--------------------------------------------------------------------------------------- | Constructs the 'Int' type-mkIntType :: String -> DataType-mkIntType = mkPrimType IntRep----- | Constructs the 'Float' type-mkFloatType :: String -> DataType-mkFloatType = mkPrimType FloatRep----- | Constructs the 'Char' type-mkCharType :: String -> DataType-mkCharType = mkPrimType CharRep----- | Helper for 'mkIntType', 'mkFloatType'-mkPrimType :: DataRep -> String -> DataType-mkPrimType dr str = DataType-                        { tycon   = str-                        , datarep = dr-                        }----- Makes a constructor for primitive types-mkPrimCon :: DataType -> String -> ConstrRep -> Constr-mkPrimCon dt str cr = Constr-                        { datatype  = dt-                        , conrep    = cr-                        , constring = str-                        , confields = error "Data.Data.confields"-                        , confixity = error "Data.Data.confixity"-                        }--mkIntegralConstr :: (Integral a, Show a) => DataType -> a -> Constr-mkIntegralConstr dt i = case datarep dt of-                  IntRep -> mkPrimCon dt (show i) (IntConstr (toInteger  i))-                  _ -> error $ "Data.Data.mkIntegralConstr is not supported for "-                               ++ dataTypeName dt ++-                               ", as it is not an Integral data type."--mkRealConstr :: (Real a, Show a) => DataType -> a -> Constr-mkRealConstr dt f = case datarep dt of-                    FloatRep -> mkPrimCon dt (show f) (FloatConstr (toRational f))-                    _ -> error $ "Data.Data.mkRealConstr is not supported for "-                                 ++ dataTypeName dt ++-                                 ", as it is not an Real data type."---- | Makes a constructor for 'Char'.-mkCharConstr :: DataType -> Char -> Constr-mkCharConstr dt c = case datarep dt of-                   CharRep -> mkPrimCon dt (show c) (CharConstr c)-                   _ -> error $ "Data.Data.mkCharConstr is not supported for "-                                ++ dataTypeName dt ++-                                ", as it is not an Char data type."---------------------------------------------------------------------------------------      Non-representations for non-representable types--------------------------------------------------------------------------------------- | Constructs a non-representation for a non-representable type-mkNoRepType :: String -> DataType-mkNoRepType str = DataType-                        { tycon   = str-                        , datarep = NoRep-                        }---- | Test for a non-representable type-isNorepType :: DataType -> Bool-isNorepType dt = case datarep dt of-                   NoRep -> True-                   _ -> False----------------------------------------------------------------------------------------      Convenience for qualified type constructors--------------------------------------------------------------------------------------- | Gets the unqualified type constructor:--- drop *.*.*... before name----tyconUQname :: String -> String-tyconUQname x = let x' = dropWhile (not . (==) '.') x-                 in if x' == [] then x else tyconUQname (tail x')----- | Gets the module of a type constructor:--- take *.*.*... before name-tyconModule :: String -> String-tyconModule x = let (a,b) = break ((==) '.') x-                 in if b == ""-                      then b-                      else a ++ tyconModule' (tail b)-  where-    tyconModule' y = let y' = tyconModule y-                      in if y' == "" then "" else ('.':y')------------------------------------------------------------------------------------------------------------------------------------------------------------------------      Instances of the Data class for Prelude-like types.---      We define top-level definitions for representations.-------------------------------------------------------------------------------------falseConstr :: Constr-falseConstr  = mkConstr boolDataType "False" [] Prefix-trueConstr :: Constr-trueConstr   = mkConstr boolDataType "True"  [] Prefix--boolDataType :: DataType-boolDataType = mkDataType "Prelude.Bool" [falseConstr,trueConstr]--instance Data Bool where-  toConstr False = falseConstr-  toConstr True  = trueConstr-  gunfold _ z c  = case constrIndex c of-                     1 -> z False-                     2 -> z True-                     _ -> error $ "Data.Data.gunfold: Constructor "-                                  ++ show c-                                  ++ " is not of type Bool."-  dataTypeOf _ = boolDataType-----------------------------------------------------------------------------------charType :: DataType-charType = mkCharType "Prelude.Char"--instance Data Char where-  toConstr x = mkCharConstr charType x-  gunfold _ z c = case constrRep c of-                    (CharConstr x) -> z x-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Char."-  dataTypeOf _ = charType-----------------------------------------------------------------------------------floatType :: DataType-floatType = mkFloatType "Prelude.Float"--instance Data Float where-  toConstr = mkRealConstr floatType-  gunfold _ z c = case constrRep c of-                    (FloatConstr x) -> z (realToFrac x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Float."-  dataTypeOf _ = floatType-----------------------------------------------------------------------------------doubleType :: DataType-doubleType = mkFloatType "Prelude.Double"--instance Data Double where-  toConstr = mkRealConstr doubleType-  gunfold _ z c = case constrRep c of-                    (FloatConstr x) -> z (realToFrac x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Double."-  dataTypeOf _ = doubleType-----------------------------------------------------------------------------------intType :: DataType-intType = mkIntType "Prelude.Int"--instance Data Int where-  toConstr x = mkIntegralConstr intType x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Int."-  dataTypeOf _ = intType-----------------------------------------------------------------------------------integerType :: DataType-integerType = mkIntType "Prelude.Integer"--instance Data Integer where-  toConstr = mkIntegralConstr integerType-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z x-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Integer."-  dataTypeOf _ = integerType-----------------------------------------------------------------------------------int8Type :: DataType-int8Type = mkIntType "Data.Int.Int8"--instance Data Int8 where-  toConstr x = mkIntegralConstr int8Type x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Int8."-  dataTypeOf _ = int8Type-----------------------------------------------------------------------------------int16Type :: DataType-int16Type = mkIntType "Data.Int.Int16"--instance Data Int16 where-  toConstr x = mkIntegralConstr int16Type x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Int16."-  dataTypeOf _ = int16Type-----------------------------------------------------------------------------------int32Type :: DataType-int32Type = mkIntType "Data.Int.Int32"--instance Data Int32 where-  toConstr x = mkIntegralConstr int32Type x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Int32."-  dataTypeOf _ = int32Type-----------------------------------------------------------------------------------int64Type :: DataType-int64Type = mkIntType "Data.Int.Int64"--instance Data Int64 where-  toConstr x = mkIntegralConstr int64Type x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Int64."-  dataTypeOf _ = int64Type-----------------------------------------------------------------------------------wordType :: DataType-wordType = mkIntType "Data.Word.Word"--instance Data Word where-  toConstr x = mkIntegralConstr wordType x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Word"-  dataTypeOf _ = wordType-----------------------------------------------------------------------------------word8Type :: DataType-word8Type = mkIntType "Data.Word.Word8"--instance Data Word8 where-  toConstr x = mkIntegralConstr word8Type x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Word8."-  dataTypeOf _ = word8Type-----------------------------------------------------------------------------------word16Type :: DataType-word16Type = mkIntType "Data.Word.Word16"--instance Data Word16 where-  toConstr x = mkIntegralConstr word16Type x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Word16."-  dataTypeOf _ = word16Type-----------------------------------------------------------------------------------word32Type :: DataType-word32Type = mkIntType "Data.Word.Word32"--instance Data Word32 where-  toConstr x = mkIntegralConstr word32Type x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Word32."-  dataTypeOf _ = word32Type-----------------------------------------------------------------------------------word64Type :: DataType-word64Type = mkIntType "Data.Word.Word64"--instance Data Word64 where-  toConstr x = mkIntegralConstr word64Type x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Word64."-  dataTypeOf _ = word64Type-----------------------------------------------------------------------------------ratioConstr :: Constr-ratioConstr = mkConstr ratioDataType ":%" [] Infix--ratioDataType :: DataType-ratioDataType = mkDataType "GHC.Real.Ratio" [ratioConstr]--instance (Data a, Integral a) => Data (Ratio a) where-  gfoldl k z (a :% b) = z (%) `k` a `k` b-  toConstr _ = ratioConstr-  gunfold k z c | constrIndex c == 1 = k (k (z (%)))-  gunfold _ _ _ = error "Data.Data.gunfold(Ratio)"-  dataTypeOf _  = ratioDataType-----------------------------------------------------------------------------------nilConstr :: Constr-nilConstr    = mkConstr listDataType "[]" [] Prefix-consConstr :: Constr-consConstr   = mkConstr listDataType "(:)" [] Infix--listDataType :: DataType-listDataType = mkDataType "Prelude.[]" [nilConstr,consConstr]--instance Data a => Data [a] where-  gfoldl _ z []     = z []-  gfoldl f z (x:xs) = z (:) `f` x `f` xs-  toConstr []    = nilConstr-  toConstr (_:_) = consConstr-  gunfold k z c = case constrIndex c of-                    1 -> z []-                    2 -> k (k (z (:)))-                    _ -> error "Data.Data.gunfold(List)"-  dataTypeOf _ = listDataType-  dataCast1 f  = gcast1 f------- The gmaps are given as an illustration.--- This shows that the gmaps for lists are different from list maps.----  gmapT  _   []     = []-  gmapT  f   (x:xs) = (f x:f xs)-  gmapQ  _   []     = []-  gmapQ  f   (x:xs) = [f x,f xs]-  gmapM  _   []     = return []-  gmapM  f   (x:xs) = f x >>= \x' -> f xs >>= \xs' -> return (x':xs')-----------------------------------------------------------------------------------nothingConstr :: Constr-nothingConstr = mkConstr maybeDataType "Nothing" [] Prefix-justConstr :: Constr-justConstr    = mkConstr maybeDataType "Just"    [] Prefix--maybeDataType :: DataType-maybeDataType = mkDataType "Prelude.Maybe" [nothingConstr,justConstr]--instance Data a => Data (Maybe a) where-  gfoldl _ z Nothing  = z Nothing-  gfoldl f z (Just x) = z Just `f` x-  toConstr Nothing  = nothingConstr-  toConstr (Just _) = justConstr-  gunfold k z c = case constrIndex c of-                    1 -> z Nothing-                    2 -> k (z Just)-                    _ -> error "Data.Data.gunfold(Maybe)"-  dataTypeOf _ = maybeDataType-  dataCast1 f  = gcast1 f-----------------------------------------------------------------------------------ltConstr :: Constr-ltConstr         = mkConstr orderingDataType "LT" [] Prefix-eqConstr :: Constr-eqConstr         = mkConstr orderingDataType "EQ" [] Prefix-gtConstr :: Constr-gtConstr         = mkConstr orderingDataType "GT" [] Prefix--orderingDataType :: DataType-orderingDataType = mkDataType "Prelude.Ordering" [ltConstr,eqConstr,gtConstr]--instance Data Ordering where-  gfoldl _ z LT  = z LT-  gfoldl _ z EQ  = z EQ-  gfoldl _ z GT  = z GT-  toConstr LT  = ltConstr-  toConstr EQ  = eqConstr-  toConstr GT  = gtConstr-  gunfold _ z c = case constrIndex c of-                    1 -> z LT-                    2 -> z EQ-                    3 -> z GT-                    _ -> error "Data.Data.gunfold(Ordering)"-  dataTypeOf _ = orderingDataType-----------------------------------------------------------------------------------leftConstr :: Constr-leftConstr     = mkConstr eitherDataType "Left"  [] Prefix--rightConstr :: Constr-rightConstr    = mkConstr eitherDataType "Right" [] Prefix--eitherDataType :: DataType-eitherDataType = mkDataType "Prelude.Either" [leftConstr,rightConstr]--instance (Data a, Data b) => Data (Either a b) where-  gfoldl f z (Left a)   = z Left  `f` a-  gfoldl f z (Right a)  = z Right `f` a-  toConstr (Left _)  = leftConstr-  toConstr (Right _) = rightConstr-  gunfold k z c = case constrIndex c of-                    1 -> k (z Left)-                    2 -> k (z Right)-                    _ -> error "Data.Data.gunfold(Either)"-  dataTypeOf _ = eitherDataType-  dataCast2 f  = gcast2 f-----------------------------------------------------------------------------------tuple0Constr :: Constr-tuple0Constr = mkConstr tuple0DataType "()" [] Prefix--tuple0DataType :: DataType-tuple0DataType = mkDataType "Prelude.()" [tuple0Constr]--instance Data () where-  toConstr ()   = tuple0Constr-  gunfold _ z c | constrIndex c == 1 = z ()-  gunfold _ _ _ = error "Data.Data.gunfold(unit)"-  dataTypeOf _  = tuple0DataType-----------------------------------------------------------------------------------tuple2Constr :: Constr-tuple2Constr = mkConstr tuple2DataType "(,)" [] Infix--tuple2DataType :: DataType-tuple2DataType = mkDataType "Prelude.(,)" [tuple2Constr]--instance (Data a, Data b) => Data (a,b) where-  gfoldl f z (a,b) = z (,) `f` a `f` b-  toConstr (_,_) = tuple2Constr-  gunfold k z c | constrIndex c == 1 = k (k (z (,)))-  gunfold _ _ _ = error "Data.Data.gunfold(tup2)"-  dataTypeOf _  = tuple2DataType-  dataCast2 f   = gcast2 f-----------------------------------------------------------------------------------tuple3Constr :: Constr-tuple3Constr = mkConstr tuple3DataType "(,,)" [] Infix--tuple3DataType :: DataType-tuple3DataType = mkDataType "Prelude.(,,)" [tuple3Constr]--instance (Data a, Data b, Data c) => Data (a,b,c) where-  gfoldl f z (a,b,c) = z (,,) `f` a `f` b `f` c-  toConstr (_,_,_) = tuple3Constr-  gunfold k z c | constrIndex c == 1 = k (k (k (z (,,))))-  gunfold _ _ _ = error "Data.Data.gunfold(tup3)"-  dataTypeOf _  = tuple3DataType-----------------------------------------------------------------------------------tuple4Constr :: Constr-tuple4Constr = mkConstr tuple4DataType "(,,,)" [] Infix--tuple4DataType :: DataType-tuple4DataType = mkDataType "Prelude.(,,,)" [tuple4Constr]--instance (Data a, Data b, Data c, Data d)-         => Data (a,b,c,d) where-  gfoldl f z (a,b,c,d) = z (,,,) `f` a `f` b `f` c `f` d-  toConstr (_,_,_,_) = tuple4Constr-  gunfold k z c = case constrIndex c of-                    1 -> k (k (k (k (z (,,,)))))-                    _ -> error "Data.Data.gunfold(tup4)"-  dataTypeOf _ = tuple4DataType-----------------------------------------------------------------------------------tuple5Constr :: Constr-tuple5Constr = mkConstr tuple5DataType "(,,,,)" [] Infix--tuple5DataType :: DataType-tuple5DataType = mkDataType "Prelude.(,,,,)" [tuple5Constr]--instance (Data a, Data b, Data c, Data d, Data e)-         => Data (a,b,c,d,e) where-  gfoldl f z (a,b,c,d,e) = z (,,,,) `f` a `f` b `f` c `f` d `f` e-  toConstr (_,_,_,_,_) = tuple5Constr-  gunfold k z c = case constrIndex c of-                    1 -> k (k (k (k (k (z (,,,,))))))-                    _ -> error "Data.Data.gunfold(tup5)"-  dataTypeOf _ = tuple5DataType-----------------------------------------------------------------------------------tuple6Constr :: Constr-tuple6Constr = mkConstr tuple6DataType "(,,,,,)" [] Infix--tuple6DataType :: DataType-tuple6DataType = mkDataType "Prelude.(,,,,,)" [tuple6Constr]--instance (Data a, Data b, Data c, Data d, Data e, Data f)-         => Data (a,b,c,d,e,f) where-  gfoldl f z (a,b,c,d,e,f') = z (,,,,,) `f` a `f` b `f` c `f` d `f` e `f` f'-  toConstr (_,_,_,_,_,_) = tuple6Constr-  gunfold k z c = case constrIndex c of-                    1 -> k (k (k (k (k (k (z (,,,,,)))))))-                    _ -> error "Data.Data.gunfold(tup6)"-  dataTypeOf _ = tuple6DataType-----------------------------------------------------------------------------------tuple7Constr :: Constr-tuple7Constr = mkConstr tuple7DataType "(,,,,,,)" [] Infix--tuple7DataType :: DataType-tuple7DataType = mkDataType "Prelude.(,,,,,,)" [tuple7Constr]--instance (Data a, Data b, Data c, Data d, Data e, Data f, Data g)-         => Data (a,b,c,d,e,f,g) where-  gfoldl f z (a,b,c,d,e,f',g) =-    z (,,,,,,) `f` a `f` b `f` c `f` d `f` e `f` f' `f` g-  toConstr  (_,_,_,_,_,_,_) = tuple7Constr-  gunfold k z c = case constrIndex c of-                    1 -> k (k (k (k (k (k (k (z (,,,,,,))))))))-                    _ -> error "Data.Data.gunfold(tup7)"-  dataTypeOf _ = tuple7DataType-----------------------------------------------------------------------------------instance (Data a, Typeable a) => Data (Ptr a) where-  toConstr _   = error "Data.Data.toConstr(Ptr)"-  gunfold _ _  = error "Data.Data.gunfold(Ptr)"-  dataTypeOf _ = mkNoRepType "GHC.Ptr.Ptr"-  dataCast1 x  = gcast1 x----------------------------------------------------------------------------------instance (Data a, Typeable a) => Data (ForeignPtr a) where-  toConstr _   = error "Data.Data.toConstr(ForeignPtr)"-  gunfold _ _  = error "Data.Data.gunfold(ForeignPtr)"-  dataTypeOf _ = mkNoRepType "GHC.ForeignPtr.ForeignPtr"-  dataCast1 x  = gcast1 x----------------------------------------------------------------------------------- The Data instance for Array preserves data abstraction at the cost of--- inefficiency. We omit reflection services for the sake of data abstraction.-instance (Typeable a, Data a, Data b, Ix a) => Data (Array a b)- where-  gfoldl f z a = z (listArray (bounds a)) `f` (elems a)-  toConstr _   = error "Data.Data.toConstr(Array)"-  gunfold _ _  = error "Data.Data.gunfold(Array)"-  dataTypeOf _ = mkNoRepType "Data.Array.Array"-  dataCast2 x  = gcast2 x--------------------------------------------------------------------------------- Data instance for Proxy--proxyConstr :: Constr-proxyConstr = mkConstr proxyDataType "Proxy" [] Prefix--proxyDataType :: DataType-proxyDataType = mkDataType "Data.Proxy.Proxy" [proxyConstr]--instance (Data t) => Data (Proxy t) where-  gfoldl _ z Proxy  = z Proxy-  toConstr Proxy  = proxyConstr-  gunfold _ z c = case constrIndex c of-                    1 -> z Proxy-                    _ -> error "Data.Data.gunfold(Proxy)"-  dataTypeOf _ = proxyDataType-  dataCast1 f  = gcast1 f---------------------------------------------------------------------------- instance for (:~:)--reflConstr :: Constr-reflConstr = mkConstr equalityDataType "Refl" [] Prefix--equalityDataType :: DataType-equalityDataType = mkDataType "Data.Type.Equality.(:~:)" [reflConstr]--instance (a ~ b, Data a) => Data (a :~: b) where-  gfoldl _ z Refl = z Refl-  toConstr Refl   = reflConstr-  gunfold _ z c   = case constrIndex c of-                      1 -> z Refl-                      _ -> error "Data.Data.gunfold(:~:)"-  dataTypeOf _    = equalityDataType-  dataCast2 f     = gcast2 f---------------------------------------------------------------------------- instance for Coercion--coercionConstr :: Constr-coercionConstr = mkConstr equalityDataType "Coercion" [] Prefix--coercionDataType :: DataType-coercionDataType = mkDataType "Data.Type.Coercion.Coercion" [coercionConstr]--instance (Coercible a b, Data a, Data b) => Data (Coercion a b) where-  gfoldl _ z Coercion = z Coercion-  toConstr Coercion = coercionConstr-  gunfold _ z c   = case constrIndex c of-                      1 -> z Coercion-                      _ -> error "Data.Data.gunfold(Coercion)"-  dataTypeOf _    = coercionDataType-  dataCast2 f     = gcast2 f---------------------------------------------------------------------------- instance for Data.Version--versionConstr :: Constr-versionConstr = mkConstr versionDataType "Version" ["versionBranch","versionTags"] Prefix--versionDataType :: DataType-versionDataType = mkDataType "Data.Version.Version" [versionConstr]--instance Data Version where-  gfoldl k z (Version bs ts) = z Version `k` bs `k` ts-  toConstr (Version _ _) = versionConstr-  gunfold k z c = case constrIndex c of-                    1 -> k (k (z Version))-                    _ -> error "Data.Data.gunfold(Version)"-  dataTypeOf _  = versionDataType
− Data/Dynamic.hs
@@ -1,145 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Dynamic--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ The Dynamic interface provides basic support for dynamic types.--- --- Operations for injecting values of arbitrary type into--- a dynamically typed value, Dynamic, are provided, together--- with operations for converting dynamic values into a concrete--- (monomorphic) type.--- --------------------------------------------------------------------------------module Data.Dynamic-  (--        -- Module Data.Typeable re-exported for convenience-        module Data.Typeable,--        -- * The @Dynamic@ type-        Dynamic,        -- abstract, instance of: Show, Typeable--        -- * Converting to and from @Dynamic@-        toDyn,-        fromDyn,-        fromDynamic,-        -        -- * Applying functions of dynamic type-        dynApply,-        dynApp,-        dynTypeRep--  ) where---import Data.Typeable-import Data.Maybe-import Unsafe.Coerce--import GHC.Base-import GHC.Show-import GHC.Exception---------------------------------------------------------------------              The type Dynamic-------------------------------------------------------------------{-|-  A value of type 'Dynamic' is an object encapsulated together with its type.--  A 'Dynamic' may only represent a monomorphic value; an attempt to-  create a value of type 'Dynamic' from a polymorphically-typed-  expression will result in an ambiguity error (see 'toDyn').--  'Show'ing a value of type 'Dynamic' returns a pretty-printed representation-  of the object\'s type; useful for debugging.--}-data Dynamic = Dynamic TypeRep Obj-               deriving Typeable--instance Show Dynamic where-   -- the instance just prints the type representation.-   showsPrec _ (Dynamic t _) = -          showString "<<" . -          showsPrec 0 t   . -          showString ">>"---- here so that it isn't an orphan:-instance Exception Dynamic--type Obj = Any- -- Use GHC's primitive 'Any' type to hold the dynamically typed value.- --- -- In GHC's new eval/apply execution model this type must not look- -- like a data type.  If it did, GHC would use the constructor convention - -- when evaluating it, and this will go wrong if the object is really a - -- function.  Using Any forces GHC to use- -- a fallback convention for evaluating it that works for all types.---- | Converts an arbitrary value into an object of type 'Dynamic'.  ------ The type of the object must be an instance of 'Typeable', which--- ensures that only monomorphically-typed objects may be converted to--- 'Dynamic'.  To convert a polymorphic object into 'Dynamic', give it--- a monomorphic type signature.  For example:------ >    toDyn (id :: Int -> Int)----toDyn :: Typeable a => a -> Dynamic-toDyn v = Dynamic (typeOf v) (unsafeCoerce v)---- | Converts a 'Dynamic' object back into an ordinary Haskell value of--- the correct type.  See also 'fromDynamic'.-fromDyn :: Typeable a-        => Dynamic      -- ^ the dynamically-typed object-        -> a            -- ^ a default value -        -> a            -- ^ returns: the value of the first argument, if-                        -- it has the correct type, otherwise the value of-                        -- the second argument.-fromDyn (Dynamic t v) def-  | typeOf def == t = unsafeCoerce v-  | otherwise       = def---- | Converts a 'Dynamic' object back into an ordinary Haskell value of--- the correct type.  See also 'fromDyn'.-fromDynamic-        :: Typeable a-        => Dynamic      -- ^ the dynamically-typed object-        -> Maybe a      -- ^ returns: @'Just' a@, if the dynamically-typed-                        -- object has the correct type (and @a@ is its value), -                        -- or 'Nothing' otherwise.-fromDynamic (Dynamic t v) =-  case unsafeCoerce v of -    r | t == typeOf r -> Just r-      | otherwise     -> Nothing---- (f::(a->b)) `dynApply` (x::a) = (f a)::b-dynApply :: Dynamic -> Dynamic -> Maybe Dynamic-dynApply (Dynamic t1 f) (Dynamic t2 x) =-  case funResultTy t1 t2 of-    Just t3 -> Just (Dynamic t3 ((unsafeCoerce f) x))-    Nothing -> Nothing--dynApp :: Dynamic -> Dynamic -> Dynamic-dynApp f x = case dynApply f x of -             Just r -> r-             Nothing -> error ("Type error in dynamic application.\n" ++-                               "Can't apply function " ++ show f ++-                               " to argument " ++ show x)--dynTypeRep :: Dynamic -> TypeRep-dynTypeRep (Dynamic tr _) = tr -
− Data/Either.hs
@@ -1,297 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}-{-# LANGUAGE PolyKinds, DataKinds, TypeFamilies, TypeOperators, UndecidableInstances #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Either--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ The Either type, and associated operations.-----------------------------------------------------------------------------------module Data.Either (-   Either(..),-   either,-   lefts,-   rights,-   isLeft,-   isRight,-   partitionEithers,- ) where--import GHC.Base-import GHC.Show-import GHC.Read--import Data.Typeable-import Data.Type.Equality---- $setup--- Allow the use of some Prelude functions in doctests.--- >>> import Prelude ( (+), (*), length, putStrLn )--{---- just for testing-import Test.QuickCheck--}--{-|--The 'Either' type represents values with two possibilities: a value of-type @'Either' a b@ is either @'Left' a@ or @'Right' b@.--The 'Either' type is sometimes used to represent a value which is-either correct or an error; by convention, the 'Left' constructor is-used to hold an error value and the 'Right' constructor is used to-hold a correct value (mnemonic: \"right\" also means \"correct\").--==== __Examples__--The type @'Either' 'String' 'Int'@ is the type of values which can be either-a 'String' or an 'Int'. The 'Left' constructor can be used only on-'String's, and the 'Right' constructor can be used only on 'Int's:-->>> let s = Left "foo" :: Either String Int->>> s-Left "foo"->>> let n = Right 3 :: Either String Int->>> n-Right 3->>> :type s-s :: Either String Int->>> :type n-n :: Either String Int--The 'fmap' from our 'Functor' instance will ignore 'Left' values, but-will apply the supplied function to values contained in a 'Right':-->>> let s = Left "foo" :: Either String Int->>> let n = Right 3 :: Either String Int->>> fmap (*2) s-Left "foo"->>> fmap (*2) n-Right 6--The 'Monad' instance for 'Either' allows us to chain together multiple-actions which may fail, and fail overall if any of the individual-steps failed. First we'll write a function that can either parse an-'Int' from a 'Char', or fail.-->>> import Data.Char ( digitToInt, isDigit )->>> :{-    let parseEither :: Char -> Either String Int-        parseEither c-          | isDigit c = Right (digitToInt c)-          | otherwise = Left "parse error"->>> :}--The following should work, since both @\'1\'@ and @\'2\'@ can be-parsed as 'Int's.-->>> :{-    let parseMultiple :: Either String Int-        parseMultiple = do-          x <- parseEither '1'-          y <- parseEither '2'-          return (x + y)->>> :}-->>> parseMultiple-Right 3--But the following should fail overall, since the first operation where-we attempt to parse @\'m\'@ as an 'Int' will fail:-->>> :{-    let parseMultiple :: Either String Int-        parseMultiple = do-          x <- parseEither 'm'-          y <- parseEither '2'-          return (x + y)->>> :}-->>> parseMultiple-Left "parse error"---}-data  Either a b  =  Left a | Right b-  deriving (Eq, Ord, Read, Show, Typeable)--instance Functor (Either a) where-    fmap _ (Left x) = Left x-    fmap f (Right y) = Right (f y)--instance Applicative (Either e) where-    pure          = Right-    Left  e <*> _ = Left e-    Right f <*> r = fmap f r--instance Monad (Either e) where-    return = Right-    Left  l >>= _ = Left l-    Right r >>= k = k r---- | Case analysis for the 'Either' type.--- If the value is @'Left' a@, apply the first function to @a@;--- if it is @'Right' b@, apply the second function to @b@.------ ==== __Examples__------ We create two values of type @'Either' 'String' 'Int'@, one using the--- 'Left' constructor and another using the 'Right' constructor. Then--- we apply \"either\" the 'length' function (if we have a 'String')--- or the \"times-two\" function (if we have an 'Int'):------ >>> let s = Left "foo" :: Either String Int--- >>> let n = Right 3 :: Either String Int--- >>> either length (*2) s--- 3--- >>> either length (*2) n--- 6----either                  :: (a -> c) -> (b -> c) -> Either a b -> c-either f _ (Left x)     =  f x-either _ g (Right y)    =  g y----- | Extracts from a list of 'Either' all the 'Left' elements.--- All the 'Left' elements are extracted in order.------ ==== __Examples__------ Basic usage:------ >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]--- >>> lefts list--- ["foo","bar","baz"]----lefts   :: [Either a b] -> [a]-lefts x = [a | Left a <- x]---- | Extracts from a list of 'Either' all the 'Right' elements.--- All the 'Right' elements are extracted in order.------ ==== __Examples__------ Basic usage:------ >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]--- >>> rights list--- [3,7]----rights   :: [Either a b] -> [b]-rights x = [a | Right a <- x]---- | Partitions a list of 'Either' into two lists.--- All the 'Left' elements are extracted, in order, to the first--- component of the output.  Similarly the 'Right' elements are extracted--- to the second component of the output.------ ==== __Examples__------ Basic usage:------ >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]--- >>> partitionEithers list--- (["foo","bar","baz"],[3,7])------ The pair returned by @'partitionEithers' x@ should be the same--- pair as @('lefts' x, 'rights' x)@:------ >>> let list = [ Left "foo", Right 3, Left "bar", Right 7, Left "baz" ]--- >>> partitionEithers list == (lefts list, rights list)--- True----partitionEithers :: [Either a b] -> ([a],[b])-partitionEithers = foldr (either left right) ([],[])- where-  left  a ~(l, r) = (a:l, r)-  right a ~(l, r) = (l, a:r)---- | Return `True` if the given value is a `Left`-value, `False` otherwise.------ @since 4.7.0.0------ ==== __Examples__------ Basic usage:------ >>> isLeft (Left "foo")--- True--- >>> isLeft (Right 3)--- False------ Assuming a 'Left' value signifies some sort of error, we can use--- 'isLeft' to write a very simple error-reporting function that does--- absolutely nothing in the case of success, and outputs \"ERROR\" if--- any error occurred.------ This example shows how 'isLeft' might be used to avoid pattern--- matching when one does not care about the value contained in the--- constructor:------ >>> import Control.Monad ( when )--- >>> let report e = when (isLeft e) $ putStrLn "ERROR"--- >>> report (Right 1)--- >>> report (Left "parse error")--- ERROR----isLeft :: Either a b -> Bool-isLeft (Left  _) = True-isLeft (Right _) = False---- | Return `True` if the given value is a `Right`-value, `False` otherwise.------ @since 4.7.0.0------ ==== __Examples__------ Basic usage:------ >>> isRight (Left "foo")--- False--- >>> isRight (Right 3)--- True------ Assuming a 'Left' value signifies some sort of error, we can use--- 'isRight' to write a very simple reporting function that only--- outputs \"SUCCESS\" when a computation has succeeded.------ This example shows how 'isRight' might be used to avoid pattern--- matching when one does not care about the value contained in the--- constructor:------ >>> import Control.Monad ( when )--- >>> let report e = when (isRight e) $ putStrLn "SUCCESS"--- >>> report (Left "parse error")--- >>> report (Right 1)--- SUCCESS----isRight :: Either a b -> Bool-isRight (Left  _) = False-isRight (Right _) = True---- instance for the == Boolean type-level equality operator-type family EqEither a b where-  EqEither ('Left x)  ('Left y)  = x == y-  EqEither ('Right x) ('Right y) = x == y-  EqEither a         b           = 'False-type instance a == b = EqEither a b--{--{---------------------------------------------------------------------  Testing---------------------------------------------------------------------}-prop_partitionEithers :: [Either Int Int] -> Bool-prop_partitionEithers x =-  partitionEithers x == (lefts x, rights x)--}-
− Data/Eq.hs
@@ -1,22 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Eq--- Copyright   :  (c) The University of Glasgow 2005--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ Equality-----------------------------------------------------------------------------------module Data.Eq (-   Eq(..),- ) where--import GHC.Base
− Data/Fixed.hs
@@ -1,209 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE AutoDeriveTypeable #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Fixed--- Copyright   :  (c) Ashley Yakeley 2005, 2006, 2009--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  Ashley Yakeley <ashley@semantic.org>--- Stability   :  experimental--- Portability :  portable------ This module defines a \"Fixed\" type for fixed-precision arithmetic.--- The parameter to Fixed is any type that's an instance of HasResolution.--- HasResolution has a single method that gives the resolution of the Fixed type.------ This module also contains generalisations of div, mod, and divmod to work--- with any Real instance.-----------------------------------------------------------------------------------module Data.Fixed-(-    div',mod',divMod',--    Fixed(..), HasResolution(..),-    showFixed,-    E0,Uni,-    E1,Deci,-    E2,Centi,-    E3,Milli,-    E6,Micro,-    E9,Nano,-    E12,Pico-) where--import Data.Data-import GHC.Read-import Text.ParserCombinators.ReadPrec-import Text.Read.Lex--default () -- avoid any defaulting shenanigans---- | generalisation of 'div' to any instance of Real-div' :: (Real a,Integral b) => a -> a -> b-div' n d = floor ((toRational n) / (toRational d))---- | generalisation of 'divMod' to any instance of Real-divMod' :: (Real a,Integral b) => a -> a -> (b,a)-divMod' n d = (f,n - (fromIntegral f) * d) where-    f = div' n d---- | generalisation of 'mod' to any instance of Real-mod' :: (Real a) => a -> a -> a-mod' n d = n - (fromInteger f) * d where-    f = div' n d---- | The type parameter should be an instance of 'HasResolution'.-newtype Fixed a = MkFixed Integer -- ^ @since 4.7.0.0-        deriving (Eq,Ord)---- We do this because the automatically derived Data instance requires (Data a) context.--- Our manual instance has the more general (Typeable a) context.-tyFixed :: DataType-tyFixed = mkDataType "Data.Fixed.Fixed" [conMkFixed]-conMkFixed :: Constr-conMkFixed = mkConstr tyFixed "MkFixed" [] Prefix-instance (Typeable a) => Data (Fixed a) where-    gfoldl k z (MkFixed a) = k (z MkFixed) a-    gunfold k z _ = k (z MkFixed)-    dataTypeOf _ = tyFixed-    toConstr _ = conMkFixed--class HasResolution a where-    resolution :: p a -> Integer--withType :: (p a -> f a) -> f a-withType foo = foo undefined--withResolution :: (HasResolution a) => (Integer -> f a) -> f a-withResolution foo = withType (foo . resolution)--instance Enum (Fixed a) where-    succ (MkFixed a) = MkFixed (succ a)-    pred (MkFixed a) = MkFixed (pred a)-    toEnum = MkFixed . toEnum-    fromEnum (MkFixed a) = fromEnum a-    enumFrom (MkFixed a) = fmap MkFixed (enumFrom a)-    enumFromThen (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromThen a b)-    enumFromTo (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromTo a b)-    enumFromThenTo (MkFixed a) (MkFixed b) (MkFixed c) = fmap MkFixed (enumFromThenTo a b c)--instance (HasResolution a) => Num (Fixed a) where-    (MkFixed a) + (MkFixed b) = MkFixed (a + b)-    (MkFixed a) - (MkFixed b) = MkFixed (a - b)-    fa@(MkFixed a) * (MkFixed b) = MkFixed (div (a * b) (resolution fa))-    negate (MkFixed a) = MkFixed (negate a)-    abs (MkFixed a) = MkFixed (abs a)-    signum (MkFixed a) = fromInteger (signum a)-    fromInteger i = withResolution (\res -> MkFixed (i * res))--instance (HasResolution a) => Real (Fixed a) where-    toRational fa@(MkFixed a) = (toRational a) / (toRational (resolution fa))--instance (HasResolution a) => Fractional (Fixed a) where-    fa@(MkFixed a) / (MkFixed b) = MkFixed (div (a * (resolution fa)) b)-    recip fa@(MkFixed a) = MkFixed (div (res * res) a) where-        res = resolution fa-    fromRational r = withResolution (\res -> MkFixed (floor (r * (toRational res))))--instance (HasResolution a) => RealFrac (Fixed a) where-    properFraction a = (i,a - (fromIntegral i)) where-        i = truncate a-    truncate f = truncate (toRational f)-    round f = round (toRational f)-    ceiling f = ceiling (toRational f)-    floor f = floor (toRational f)--chopZeros :: Integer -> String-chopZeros 0 = ""-chopZeros a | mod a 10 == 0 = chopZeros (div a 10)-chopZeros a = show a---- only works for positive a-showIntegerZeros :: Bool -> Int -> Integer -> String-showIntegerZeros True _ 0 = ""-showIntegerZeros chopTrailingZeros digits a = replicate (digits - length s) '0' ++ s' where-    s = show a-    s' = if chopTrailingZeros then chopZeros a else s--withDot :: String -> String-withDot "" = ""-withDot s = '.':s---- | First arg is whether to chop off trailing zeros-showFixed :: (HasResolution a) => Bool -> Fixed a -> String-showFixed chopTrailingZeros fa@(MkFixed a) | a < 0 = "-" ++ (showFixed chopTrailingZeros (asTypeOf (MkFixed (negate a)) fa))-showFixed chopTrailingZeros fa@(MkFixed a) = (show i) ++ (withDot (showIntegerZeros chopTrailingZeros digits fracNum)) where-    res = resolution fa-    (i,d) = divMod a res-    -- enough digits to be unambiguous-    digits = ceiling (logBase 10 (fromInteger res) :: Double)-    maxnum = 10 ^ digits-    -- read floors, so show must ceil for `read . show = id` to hold. See #9240-    fracNum = divCeil (d * maxnum) res-    divCeil x y = (x + y - 1) `div` y--instance (HasResolution a) => Show (Fixed a) where-    show = showFixed False--instance (HasResolution a) => Read (Fixed a) where-    readPrec     = readNumber convertFixed-    readListPrec = readListPrecDefault-    readList     = readListDefault--convertFixed :: forall a . HasResolution a => Lexeme -> ReadPrec (Fixed a)-convertFixed (Number n)- | Just (i, f) <- numberToFixed e n =-    return (fromInteger i + (fromInteger f / (10 ^ e)))-    where r = resolution (undefined :: Fixed a)-          -- round 'e' up to help make the 'read . show == id' property-          -- possible also for cases where 'resolution' is not a-          -- power-of-10, such as e.g. when 'resolution = 128'-          e = ceiling (logBase 10 (fromInteger r) :: Double)-convertFixed _ = pfail--data E0-instance HasResolution E0 where-    resolution _ = 1--- | resolution of 1, this works the same as Integer-type Uni = Fixed E0--data E1-instance HasResolution E1 where-    resolution _ = 10--- | resolution of 10^-1 = .1-type Deci = Fixed E1--data E2-instance HasResolution E2 where-    resolution _ = 100--- | resolution of 10^-2 = .01, useful for many monetary currencies-type Centi = Fixed E2--data E3-instance HasResolution E3 where-    resolution _ = 1000--- | resolution of 10^-3 = .001-type Milli = Fixed E3--data E6-instance HasResolution E6 where-    resolution _ = 1000000--- | resolution of 10^-6 = .000001-type Micro = Fixed E6--data E9-instance HasResolution E9 where-    resolution _ = 1000000000--- | resolution of 10^-9 = .000000001-type Nano = Fixed E9--data E12-instance HasResolution E12 where-    resolution _ = 1000000000000--- | resolution of 10^-12 = .000000000001-type Pico = Fixed E12
− Data/Foldable.hs
@@ -1,477 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE ScopedTypeVariables #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Foldable--- Copyright   :  Ross Paterson 2005--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Class of data structures that can be folded to a summary value.-----------------------------------------------------------------------------------module Data.Foldable (-    -- * Folds-    Foldable(..),-    -- ** Special biased folds-    foldrM,-    foldlM,-    -- ** Folding actions-    -- *** Applicative actions-    traverse_,-    for_,-    sequenceA_,-    asum,-    -- *** Monadic actions-    mapM_,-    forM_,-    sequence_,-    msum,-    -- ** Specialized folds-    concat,-    concatMap,-    and,-    or,-    any,-    all,-    maximumBy,-    minimumBy,-    -- ** Searches-    notElem,-    find-    ) where--import Data.Bool-import Data.Either-import Data.Eq-import qualified GHC.List as List-import Data.Maybe-import Data.Monoid-import Data.Ord-import Data.Proxy--import GHC.Arr  ( Array(..), Ix(..), elems, numElements,-                  foldlElems, foldrElems,-                  foldlElems', foldrElems',-                  foldl1Elems, foldr1Elems)-import GHC.Base hiding ( foldr )-import GHC.Num  ( Num(..) )--infix  4 `elem`, `notElem`---- | Data structures that can be folded.------ For example, given a data type------ > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)------ a suitable instance would be------ > instance Foldable Tree where--- >    foldMap f Empty = mempty--- >    foldMap f (Leaf x) = f x--- >    foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r------ This is suitable even for abstract types, as the monoid is assumed--- to satisfy the monoid laws.  Alternatively, one could define @foldr@:------ > instance Foldable Tree where--- >    foldr f z Empty = z--- >    foldr f z (Leaf x) = f x z--- >    foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l------ @Foldable@ instances are expected to satisfy the following laws:------ > foldr f z t = appEndo (foldMap (Endo . f) t ) z------ > foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z------ > fold = foldMap id------ @sum@, @product@, @maximum@, and @minimum@ should all be essentially--- equivalent to @foldMap@ forms, such as------ > sum = getSum . foldMap Sum------ but may be less defined.------ If the type is also a 'Functor' instance, it should satisfy------ > foldMap f = fold . fmap f------ which implies that------ > foldMap f . fmap g = foldMap (f . g)--class Foldable t where-    {-# MINIMAL foldMap | foldr #-}--    -- | Combine the elements of a structure using a monoid.-    fold :: Monoid m => t m -> m-    fold = foldMap id--    -- | Map each element of the structure to a monoid,-    -- and combine the results.-    foldMap :: Monoid m => (a -> m) -> t a -> m-    foldMap f = foldr (mappend . f) mempty--    -- | Right-associative fold of a structure.-    ---    -- @'foldr' f z = 'Prelude.foldr' f z . 'toList'@-    foldr :: (a -> b -> b) -> b -> t a -> b-    foldr f z t = appEndo (foldMap (Endo #. f) t) z--    -- | Right-associative fold of a structure,-    -- but with strict application of the operator.-    foldr' :: (a -> b -> b) -> b -> t a -> b-    foldr' f z0 xs = foldl f' id xs z0-      where f' k x z = k $! f x z--    -- | Left-associative fold of a structure.-    ---    -- @'foldl' f z = 'Prelude.foldl' f z . 'toList'@-    foldl :: (b -> a -> b) -> b -> t a -> b-    foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z-    -- There's no point mucking around with coercions here,-    -- because flip forces us to build a new function anyway.--    -- | Left-associative fold of a structure.-    -- but with strict application of the operator.-    ---    -- @'foldl' f z = 'List.foldl'' f z . 'toList'@-    foldl' :: (b -> a -> b) -> b -> t a -> b-    foldl' f z0 xs = foldr f' id xs z0-      where f' x k z = k $! f z x--    -- | A variant of 'foldr' that has no base case,-    -- and thus may only be applied to non-empty structures.-    ---    -- @'foldr1' f = 'Prelude.foldr1' f . 'toList'@-    foldr1 :: (a -> a -> a) -> t a -> a-    foldr1 f xs = fromMaybe (error "foldr1: empty structure")-                    (foldr mf Nothing xs)-      where-        mf x m = Just (case m of-                         Nothing -> x-                         Just y  -> f x y)--    -- | A variant of 'foldl' that has no base case,-    -- and thus may only be applied to non-empty structures.-    ---    -- @'foldl1' f = 'Prelude.foldl1' f . 'toList'@-    foldl1 :: (a -> a -> a) -> t a -> a-    foldl1 f xs = fromMaybe (error "foldl1: empty structure")-                    (foldl mf Nothing xs)-      where-        mf m y = Just (case m of-                         Nothing -> y-                         Just x  -> f x y)--    -- | List of elements of a structure, from left to right.-    toList :: t a -> [a]-    {-# INLINE toList #-}-    toList t = build (\ c n -> foldr c n t)--    -- | Test whether the structure is empty. The default implementation is-    -- optimized for structures that are similar to cons-lists, because there-    -- is no general way to do better.-    null :: t a -> Bool-    null = foldr (\_ _ -> False) True--    -- | Returns the size/length of a finite structure as an 'Int'.  The-    -- default implementation is optimized for structures that are similar to-    -- cons-lists, because there is no general way to do better.-    length :: t a -> Int-    length = foldl' (\c _ -> c+1) 0--    -- | Does the element occur in the structure?-    elem :: Eq a => a -> t a -> Bool-    elem = any . (==)--    -- | The largest element of a non-empty structure.-    maximum :: forall a . Ord a => t a -> a-    maximum = fromMaybe (error "maximum: empty structure") .-       getMax . foldMap (Max #. (Just :: a -> Maybe a))--    -- | The least element of a non-empty structure.-    minimum :: forall a . Ord a => t a -> a-    minimum = fromMaybe (error "minimum: empty structure") .-       getMin . foldMap (Min #. (Just :: a -> Maybe a))--    -- | The 'sum' function computes the sum of the numbers of a structure.-    sum :: Num a => t a -> a-    sum = getSum #. foldMap Sum--    -- | The 'product' function computes the product of the numbers of a-    -- structure.-    product :: Num a => t a -> a-    product = getProduct #. foldMap Product---- instances for Prelude types--instance Foldable Maybe where-    foldr _ z Nothing = z-    foldr f z (Just x) = f x z--    foldl _ z Nothing = z-    foldl f z (Just x) = f z x--instance Foldable [] where-    elem    = List.elem-    foldl   = List.foldl-    foldl'  = List.foldl'-    foldl1  = List.foldl1-    foldr   = List.foldr-    foldr1  = List.foldr1-    length  = List.length-    maximum = List.maximum-    minimum = List.minimum-    null    = List.null-    product = List.product-    sum     = List.sum-    toList  = id--instance Foldable (Either a) where-    foldMap _ (Left _) = mempty-    foldMap f (Right y) = f y--    foldr _ z (Left _) = z-    foldr f z (Right y) = f y z--    length (Left _)  = 0-    length (Right _) = 1--    null             = isLeft--instance Foldable ((,) a) where-    foldMap f (_, y) = f y--    foldr f z (_, y) = f y z--instance Ix i => Foldable (Array i) where-    foldr = foldrElems-    foldl = foldlElems-    foldl' = foldlElems'-    foldr' = foldrElems'-    foldl1 = foldl1Elems-    foldr1 = foldr1Elems-    toList = elems-    length = numElements-    null a = numElements a == 0--instance Foldable Proxy where-    foldMap _ _ = mempty-    {-# INLINE foldMap #-}-    fold _ = mempty-    {-# INLINE fold #-}-    foldr _ z _ = z-    {-# INLINE foldr #-}-    foldl _ z _ = z-    {-# INLINE foldl #-}-    foldl1 _ _ = error "foldl1: Proxy"-    foldr1 _ _ = error "foldr1: Proxy"-    length _   = 0-    null _     = True-    elem _ _   = False-    sum _      = 0-    product _  = 1---- We don't export Max and Min because, as Edward Kmett pointed out to me,--- there are two reasonable ways to define them. One way is to use Maybe, as we--- do here; the other way is to impose a Bounded constraint on the Monoid--- instance. We may eventually want to add both versions, but we don't want to--- trample on anyone's toes by imposing Max = MaxMaybe.--newtype Max a = Max {getMax :: Maybe a}-newtype Min a = Min {getMin :: Maybe a}--instance Ord a => Monoid (Max a) where-  mempty = Max Nothing--  {-# INLINE mappend #-}-  m `mappend` Max Nothing = m-  Max Nothing `mappend` n = n-  (Max m@(Just x)) `mappend` (Max n@(Just y))-    | x >= y    = Max m-    | otherwise = Max n--instance Ord a => Monoid (Min a) where-  mempty = Min Nothing--  {-# INLINE mappend #-}-  m `mappend` Min Nothing = m-  Min Nothing `mappend` n = n-  (Min m@(Just x)) `mappend` (Min n@(Just y))-    | x <= y    = Min m-    | otherwise = Min n---- | Monadic fold over the elements of a structure,--- associating to the right, i.e. from right to left.-foldrM :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b-foldrM f z0 xs = foldl f' return xs z0-  where f' k x z = f x z >>= k---- | Monadic fold over the elements of a structure,--- associating to the left, i.e. from left to right.-foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b-foldlM f z0 xs = foldr f' return xs z0-  where f' x k z = f z x >>= k---- | Map each element of a structure to an action, evaluate these--- actions from left to right, and ignore the results. For a version--- that doesn't ignore the results see 'Data.Traversable.traverse'.-traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()-traverse_ f = foldr ((*>) . f) (pure ())---- | 'for_' is 'traverse_' with its arguments flipped. For a version--- that doesn't ignore the results see 'Data.Traversable.for'.------ >>> for_ [1..4] print--- 1--- 2--- 3--- 4-for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()-{-# INLINE for_ #-}-for_ = flip traverse_---- | Map each element of a structure to a monadic action, evaluate--- these actions from left to right, and ignore the results. For a--- version that doesn't ignore the results see--- 'Data.Traversable.mapM'.------ As of base 4.8.0.0, 'mapM_' is just 'traverse_', specialized to--- 'Monad'.-mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()-mapM_ f= foldr ((>>) . f) (return ())---- | 'forM_' is 'mapM_' with its arguments flipped. For a version that--- doesn't ignore the results see 'Data.Traversable.forM'.------ As of base 4.8.0.0, 'forM_' is just 'for_', specialized to 'Monad'.-forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()-{-# INLINE forM_ #-}-forM_ = flip mapM_---- | Evaluate each action in the structure from left to right, and--- ignore the results. For a version that doesn't ignore the results--- see 'Data.Traversable.sequenceA'.-sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f ()-sequenceA_ = foldr (*>) (pure ())---- | Evaluate each monadic action in the structure from left to right,--- and ignore the results. For a version that doesn't ignore the--- results see 'Data.Traversable.sequence'.------ As of base 4.8.0.0, 'sequence_' is just 'sequenceA_', specialized--- to 'Monad'.-sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()-sequence_ = foldr (>>) (return ())---- | The sum of a collection of actions, generalizing 'concat'.-asum :: (Foldable t, Alternative f) => t (f a) -> f a-{-# INLINE asum #-}-asum = foldr (<|>) empty---- | The sum of a collection of actions, generalizing 'concat'.--- As of base 4.8.0.0, 'msum' is just 'asum', specialized to 'MonadPlus'.-msum :: (Foldable t, MonadPlus m) => t (m a) -> m a-{-# INLINE msum #-}-msum = asum---- | The concatenation of all the elements of a container of lists.-concat :: Foldable t => t [a] -> [a]-concat xs = build (\c n -> foldr (\x y -> foldr c y x) n xs)-{-# INLINE concat #-}---- | Map a function over all the elements of a container and concatenate--- the resulting lists.-concatMap :: Foldable t => (a -> [b]) -> t a -> [b]-concatMap f xs = build (\c n -> foldr (\x b -> foldr c b (f x)) n xs)-{-# INLINE concatMap #-}---- These use foldr rather than foldMap to avoid repeated concatenation.---- | 'and' returns the conjunction of a container of Bools.  For the--- result to be 'True', the container must be finite; 'False', however,--- results from a 'False' value finitely far from the left end.-and :: Foldable t => t Bool -> Bool-and = getAll #. foldMap All---- | 'or' returns the disjunction of a container of Bools.  For the--- result to be 'False', the container must be finite; 'True', however,--- results from a 'True' value finitely far from the left end.-or :: Foldable t => t Bool -> Bool-or = getAny #. foldMap Any---- | Determines whether any element of the structure satisfies the predicate.-any :: Foldable t => (a -> Bool) -> t a -> Bool-any p = getAny #. foldMap (Any #. p)---- | Determines whether all elements of the structure satisfy the predicate.-all :: Foldable t => (a -> Bool) -> t a -> Bool-all p = getAll #. foldMap (All #. p)---- | The largest element of a non-empty structure with respect to the--- given comparison function.-maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a-maximumBy cmp = foldr1 max'-  where max' x y = case cmp x y of-                        GT -> x-                        _  -> y---- | The least element of a non-empty structure with respect to the--- given comparison function.-minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a-minimumBy cmp = foldr1 min'-  where min' x y = case cmp x y of-                        GT -> y-                        _  -> x---- | 'notElem' is the negation of 'elem'.-notElem :: (Foldable t, Eq a) => a -> t a -> Bool-notElem x = not . elem x---- | The 'find' function takes a predicate and a structure and returns--- the leftmost element of the structure matching the predicate, or--- 'Nothing' if there is no such element.-find :: Foldable t => (a -> Bool) -> t a -> Maybe a-find p = getFirst . foldMap (\ x -> First (if p x then Just x else Nothing))---- See Note [Function coercion]-(#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c)-(#.) _f = coerce-{-# INLINE (#.) #-}--{--Note [Function coercion]-~~~~~~~~~~~~~~~~~~~~~~~~--Several functions here use (#.) instead of (.) to avoid potential efficiency-problems relating to #7542. The problem, in a nutshell:--If N is a newtype constructor, then N x will always have the same-representation as x (something similar applies for a newtype deconstructor).-However, if f is a function,--N . f = \x -> N (f x)--This looks almost the same as f, but the eta expansion lifts it--the lhs could-be _|_, but the rhs never is. This can lead to very inefficient code.  Thus we-steal a technique from Shachaf and Edward Kmett and adapt it to the current-(rather clean) setting. Instead of using  N . f,  we use  N .## f, which is-just--coerce f `asTypeOf` (N . f)--That is, we just *pretend* that f has the right type, and thanks to the safety-of coerce, the type checker guarantees that nothing really goes wrong. We still-have to be a bit careful, though: remember that #. completely ignores the-*value* of its left operand.--}
− Data/Function.hs
@@ -1,100 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Function--- Copyright   :  Nils Anders Danielsson 2006---             ,  Alexander Berntsen     2014--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Simple combinators working solely on and with functions.-----------------------------------------------------------------------------------module Data.Function-  ( -- * "Prelude" re-exports-    id, const, (.), flip, ($)-    -- * Other combinators-  , (&)-  , fix-  , on-  ) where--import GHC.Base ( ($), (.), id, const, flip )--infixl 0 `on`-infixl 1 &---- | @'fix' f@ is the least fixed point of the function @f@,--- i.e. the least defined @x@ such that @f x = x@.-fix :: (a -> a) -> a-fix f = let x = f x in x---- | @(*) \`on\` f = \\x y -> f x * f y@.------ Typical usage: @'Data.List.sortBy' ('compare' \`on\` 'fst')@.------ Algebraic properties:------ * @(*) \`on\` 'id' = (*)@ (if @(*) &#x2209; {&#x22a5;, 'const' &#x22a5;}@)------ * @((*) \`on\` f) \`on\` g = (*) \`on\` (f . g)@------ * @'flip' on f . 'flip' on g = 'flip' on (g . f)@---- Proofs (so that I don't have to edit the test-suite):----   (*) `on` id--- =---   \x y -> id x * id y--- =---   \x y -> x * y--- = { If (*) /= _|_ or const _|_. }---   (*)----   (*) `on` f `on` g--- =---   ((*) `on` f) `on` g--- =---   \x y -> ((*) `on` f) (g x) (g y)--- =---   \x y -> (\x y -> f x * f y) (g x) (g y)--- =---   \x y -> f (g x) * f (g y)--- =---   \x y -> (f . g) x * (f . g) y--- =---   (*) `on` (f . g)--- =---   (*) `on` f . g----   flip on f . flip on g--- =---   (\h (*) -> (*) `on` h) f . (\h (*) -> (*) `on` h) g--- =---   (\(*) -> (*) `on` f) . (\(*) -> (*) `on` g)--- =---   \(*) -> (*) `on` g `on` f--- = { See above. }---   \(*) -> (*) `on` g . f--- =---   (\h (*) -> (*) `on` h) (g . f)--- =---   flip on (g . f)--on :: (b -> b -> c) -> (a -> b) -> a -> a -> c-(.*.) `on` f = \x y -> f x .*. f y----- | '&' is a reverse application operator.  This provides notational--- convenience.  Its precedence is one higher than that of the forward--- application operator '$', which allows '&' to be nested in '$'.------ @since 4.8.0.0-(&) :: a -> (a -> b) -> b-x & f = f x
− Data/Functor.hs
@@ -1,143 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Functor--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Functors: uniform action over a parameterized type, generalizing the--- 'Data.List.map' function on lists.--module Data.Functor-    (-      Functor(fmap),-      (<$),-      ($>),-      (<$>),-      void,-    ) where--import GHC.Base ( Functor(..), flip )---- $setup--- Allow the use of Prelude in doctests.--- >>> import Prelude--infixl 4 <$>---- | An infix synonym for 'fmap'.------ ==== __Examples__------ Convert from a @'Maybe' 'Int'@ to a @'Maybe' 'String'@ using 'show':------ >>> show <$> Nothing--- Nothing--- >>> show <$> Just 3--- Just "3"------ Convert from an @'Either' 'Int' 'Int'@ to an @'Either' 'Int'@--- 'String' using 'show':------ >>> show <$> Left 17--- Left 17--- >>> show <$> Right 17--- Right "17"------ Double each element of a list:------ >>> (*2) <$> [1,2,3]--- [2,4,6]------ Apply 'even' to the second element of a pair:------ >>> even <$> (2,2)--- (2,True)----(<$>) :: Functor f => (a -> b) -> f a -> f b-(<$>) = fmap--infixl 4 $>---- | Flipped version of '<$'.------ @since 4.7.0.0------ ==== __Examples__------ Replace the contents of a @'Maybe' 'Int'@ with a constant 'String':------ >>> Nothing $> "foo"--- Nothing--- >>> Just 90210 $> "foo"--- Just "foo"------ Replace the contents of an @'Either' 'Int' 'Int'@ with a constant--- 'String', resulting in an @'Either' 'Int' 'String'@:------ >>> Left 8675309 $> "foo"--- Left 8675309--- >>> Right 8675309 $> "foo"--- Right "foo"------ Replace each element of a list with a constant 'String':------ >>> [1,2,3] $> "foo"--- ["foo","foo","foo"]------ Replace the second element of a pair with a constant 'String':------ >>> (1,2) $> "foo"--- (1,"foo")----($>) :: Functor f => f a -> b -> f b-($>) = flip (<$)---- | @'void' value@ discards or ignores the result of evaluation, such--- as the return value of an 'System.IO.IO' action.------ ==== __Examples__------ Replace the contents of a @'Maybe' 'Int'@ with unit:------ >>> void Nothing--- Nothing--- >>> void (Just 3)--- Just ()------ Replace the contents of an @'Either' 'Int' 'Int'@ with unit,--- resulting in an @'Either' 'Int' '()'@:------ >>> void (Left 8675309)--- Left 8675309--- >>> void (Right 8675309)--- Right ()------ Replace every element of a list with unit:------ >>> void [1,2,3]--- [(),(),()]------ Replace the second element of a pair with unit:------ >>> void (1,2)--- (1,())------ Discard the result of an 'System.IO.IO' action:------ >>> mapM print [1,2]--- 1--- 2--- [(),()]--- >>> void $ mapM print [1,2]--- 1--- 2----void :: Functor f => f a -> f ()-void x = () <$ x
− Data/Functor/Identity.hs
@@ -1,104 +0,0 @@-{-# LANGUAGE AutoDeriveTypeable #-}-{-# LANGUAGE DeriveGeneric #-}-{-# LANGUAGE DeriveTraversable #-}-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Functor.Identity--- Copyright   :  (c) Andy Gill 2001,---                (c) Oregon Graduate Institute of Science and Technology 2001--- License     :  BSD-style (see the file LICENSE)------ Maintainer  :  ross@soi.city.ac.uk--- Stability   :  experimental--- Portability :  portable------ The identity functor and monad.------ This trivial type constructor serves two purposes:------ * It can be used with functions parameterized by functor or monad classes.------ * It can be used as a base monad to which a series of monad---   transformers may be applied to construct a composite monad.---   Most monad transformer modules include the special case of---   applying the transformer to 'Identity'.  For example, @State s@---   is an abbreviation for @StateT s 'Identity'@.------ @since 4.8.0.0--------------------------------------------------------------------------------module Data.Functor.Identity (-    Identity(..),-  ) where--import Control.Monad.Fix-import Control.Monad.Zip-import Data.Coerce-import Data.Data (Data)-import Data.Foldable-import GHC.Generics (Generic, Generic1)---- | Identity functor and monad. (a non-strict monad)------ @since 4.8.0.0-newtype Identity a = Identity { runIdentity :: a }-    deriving (Eq, Ord, Data, Traversable, Generic, Generic1)---- | This instance would be equivalent to the derived instances of the--- 'Identity' newtype if the 'runIdentity' field were removed-instance (Read a) => Read (Identity a) where-    readsPrec d = readParen (d > 10) $ \ r ->-        [(Identity x,t) | ("Identity",s) <- lex r, (x,t) <- readsPrec 11 s]---- | This instance would be equivalent to the derived instances of the--- 'Identity' newtype if the 'runIdentity' field were removed-instance (Show a) => Show (Identity a) where-    showsPrec d (Identity x) = showParen (d > 10) $-        showString "Identity " . showsPrec 11 x---- ------------------------------------------------------------------------------ Identity instances for Functor and Monad--instance Foldable Identity where-    foldMap                = coerce--    elem                   = (. runIdentity) #. (==)-    foldl                  = coerce-    foldl'                 = coerce-    foldl1 _               = runIdentity-    foldr f z (Identity x) = f x z-    foldr'                 = foldr-    foldr1 _               = runIdentity-    length _               = 1-    maximum                = runIdentity-    minimum                = runIdentity-    null _                 = False-    product                = runIdentity-    sum                    = runIdentity-    toList (Identity x)    = [x]--instance Functor Identity where-    fmap     = coerce--instance Applicative Identity where-    pure     = Identity-    (<*>)    = coerce--instance Monad Identity where-    return   = Identity-    m >>= k  = k (runIdentity m)--instance MonadFix Identity where-    mfix f   = Identity (fix (runIdentity . f))--instance MonadZip Identity where-    mzipWith = coerce-    munzip   = coerce---- | Internal (non-exported) 'Coercible' helper for 'elem'------ See Note [Function coercion] in "Data.Foldable" for more details.-(#.) :: Coercible b c => (b -> c) -> (a -> b) -> a -> c-(#.) _f = coerce
− Data/IORef.hs
@@ -1,162 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples #-}---------------------------------------------------------------------------------- |--- Module      :  Data.IORef--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Mutable references in the IO monad.-----------------------------------------------------------------------------------module Data.IORef-  ( -        -- * IORefs-        IORef,                -- abstract, instance of: Eq, Typeable-        newIORef,-        readIORef,-        writeIORef,-        modifyIORef,-        modifyIORef',-        atomicModifyIORef,-        atomicModifyIORef',-        atomicWriteIORef,--#if !defined(__PARALLEL_HASKELL__)-        mkWeakIORef,-#endif-        -- ** Memory Model--        -- $memmodel--        ) where--import GHC.Base-import GHC.STRef-import GHC.IORef hiding (atomicModifyIORef)-import qualified GHC.IORef-#if !defined(__PARALLEL_HASKELL__)-import GHC.Weak-#endif--#if !defined(__PARALLEL_HASKELL__)--- |Make a 'Weak' pointer to an 'IORef', using the second argument as a finalizer--- to run when 'IORef' is garbage-collected-mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a))-mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s ->-  case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #)-#endif---- |Mutate the contents of an 'IORef'.------ Be warned that 'modifyIORef' does not apply the function strictly.  This--- means if the program calls 'modifyIORef' many times, but seldomly uses the--- value, thunks will pile up in memory resulting in a space leak.  This is a--- common mistake made when using an IORef as a counter.  For example, the--- following will likely produce a stack overflow:------ >ref <- newIORef 0--- >replicateM_ 1000000 $ modifyIORef ref (+1)--- >readIORef ref >>= print------ To avoid this problem, use 'modifyIORef'' instead.-modifyIORef :: IORef a -> (a -> a) -> IO ()-modifyIORef ref f = readIORef ref >>= writeIORef ref . f---- |Strict version of 'modifyIORef'------ @since 4.6.0.0-modifyIORef' :: IORef a -> (a -> a) -> IO ()-modifyIORef' ref f = do-    x <- readIORef ref-    let x' = f x-    x' `seq` writeIORef ref x'---- |Atomically modifies the contents of an 'IORef'.------ This function is useful for using 'IORef' in a safe way in a multithreaded--- program.  If you only have one 'IORef', then using 'atomicModifyIORef' to--- access and modify it will prevent race conditions.------ Extending the atomicity to multiple 'IORef's is problematic, so it--- is recommended that if you need to do anything more complicated--- then using 'Control.Concurrent.MVar.MVar' instead is a good idea.------ 'atomicModifyIORef' does not apply the function strictly.  This is important--- to know even if all you are doing is replacing the value.  For example, this--- will leak memory:------ >ref <- newIORef '1'--- >forever $ atomicModifyIORef ref (\_ -> ('2', ()))------ Use 'atomicModifyIORef'' or 'atomicWriteIORef' to avoid this problem.----atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b-atomicModifyIORef = GHC.IORef.atomicModifyIORef---- | Strict version of 'atomicModifyIORef'.  This forces both the value stored--- in the 'IORef' as well as the value returned.------ @since 4.6.0.0-atomicModifyIORef' :: IORef a -> (a -> (a,b)) -> IO b-atomicModifyIORef' ref f = do-    b <- atomicModifyIORef ref $ \a ->-            case f a of-                v@(a',_) -> a' `seq` v-    b `seq` return b---- | Variant of 'writeIORef' with the \"barrier to reordering\" property that--- 'atomicModifyIORef' has.------ @since 4.6.0.0-atomicWriteIORef :: IORef a -> a -> IO ()-atomicWriteIORef ref a = do-    x <- atomicModifyIORef ref (\_ -> (a, ()))-    x `seq` return ()--{- $memmodel--  In a concurrent program, 'IORef' operations may appear out-of-order-  to another thread, depending on the memory model of the underlying-  processor architecture.  For example, on x86, loads can move ahead-  of stores, so in the following example:-->  maybePrint :: IORef Bool -> IORef Bool -> IO ()->  maybePrint myRef yourRef = do->    writeIORef myRef True->    yourVal <- readIORef yourRef->    unless yourVal $ putStrLn "critical section"->->  main :: IO ()->  main = do->    r1 <- newIORef False->    r2 <- newIORef False->    forkIO $ maybePrint r1 r2->    forkIO $ maybePrint r2 r1->    threadDelay 1000000--  it is possible that the string @"critical section"@ is printed-  twice, even though there is no interleaving of the operations of the-  two threads that allows that outcome.  The memory model of x86-  allows 'readIORef' to happen before the earlier 'writeIORef'.--  The implementation is required to ensure that reordering of memory-  operations cannot cause type-correct code to go wrong.  In-  particular, when inspecting the value read from an 'IORef', the-  memory writes that created that value must have occurred from the-  point of view of the current thread.--  'atomicModifyIORef' acts as a barrier to reordering.  Multiple-  'atomicModifyIORef' operations occur in strict program order.  An-  'atomicModifyIORef' is never observed to take place ahead of any-  earlier (in program order) 'IORef' operations, or after any later-  'IORef' operations.---}-
− Data/Int.hs
@@ -1,55 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Int--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Signed integer types-----------------------------------------------------------------------------------module Data.Int-  ( -        -- * Signed integer types-        Int,-        Int8, Int16, Int32, Int64,--        -- * Notes--        -- $notes-        ) where--import GHC.Base ( Int )-import GHC.Int  ( Int8, Int16, Int32, Int64 )--{- $notes--* All arithmetic is performed modulo 2^n, where @n@ is the number of-  bits in the type.--* For coercing between any two integer types, use 'Prelude.fromIntegral',-  which is specialized for all the common cases so should be fast-  enough.  Coercing word types (see "Data.Word") to and from integer-  types preserves representation, not sign.--* The rules that hold for 'Prelude.Enum' instances over a-  bounded type such as 'Int' (see the section of the-  Haskell report dealing with arithmetic sequences) also hold for the-  'Prelude.Enum' instances over the various-  'Int' types defined here.--* Right and left shifts by amounts greater than or equal to the width-  of the type result in either zero or -1, depending on the sign of-  the value being shifted.  This is contrary to the behaviour in C,-  which is undefined; a common interpretation is to truncate the shift-  count to the width of the type, for example @1 \<\< 32-  == 1@ in some C implementations.--}-
− Data/Ix.hs
@@ -1,64 +0,0 @@-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Ix--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ The 'Ix' class is used to map a contiguous subrange of values in--- type onto integers.  It is used primarily for array indexing--- (see the array package).  'Ix' uses row-major order.--- --------------------------------------------------------------------------------module Data.Ix-    (-    -- * The 'Ix' class-        Ix-          ( range-          , index-          , inRange-          , rangeSize-          )-    -- Ix instances:-    ---    --  Ix Char-    --  Ix Int-    --  Ix Integer-    --  Ix Bool-    --  Ix Ordering-    --  Ix ()-    --  (Ix a, Ix b) => Ix (a, b)-    --  ...--    -- * Deriving Instances of 'Ix'-    -- | Derived instance declarations for the class 'Ix' are only possible-    -- for enumerations (i.e. datatypes having only nullary constructors)-    -- and single-constructor datatypes, including arbitrarily large tuples,-    -- whose constituent types are instances of 'Ix'. -    -- -    -- * For an enumeration, the nullary constructors are assumed to be-    -- numbered left-to-right with the indices being 0 to n-1 inclusive. This-    -- is the same numbering defined by the 'Enum' class. For example, given-    -- the datatype: -    -- -    -- >        data Colour = Red | Orange | Yellow | Green | Blue | Indigo | Violet-    -- -    -- we would have: -    -- -    -- >        range   (Yellow,Blue)        ==  [Yellow,Green,Blue]-    -- >        index   (Yellow,Blue) Green  ==  1-    -- >        inRange (Yellow,Blue) Red    ==  False-    -- -    -- * For single-constructor datatypes, the derived instance declarations-    -- are as shown for tuples in chapter 19, section 2 of the Haskell 2010 report:-    -- <https://www.haskell.org/onlinereport/haskell2010/haskellch19.html>.--    ) where--import GHC.Arr
− Data/List.hs
@@ -1,241 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.List--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ Operations on lists.-----------------------------------------------------------------------------------module Data.List-   (-   -- * Basic functions--     (++)-   , head-   , last-   , tail-   , init-   , uncons-   , null-   , length--   -- * List transformations-   , map-   , reverse--   , intersperse-   , intercalate-   , transpose--   , subsequences-   , permutations--   -- * Reducing lists (folds)--   , foldl-   , foldl'-   , foldl1-   , foldl1'-   , foldr-   , foldr1--   -- ** Special folds--   , concat-   , concatMap-   , and-   , or-   , any-   , all-   , sum-   , product-   , maximum-   , minimum--   -- * Building lists--   -- ** Scans-   , scanl-   , scanl'-   , scanl1-   , scanr-   , scanr1--   -- ** Accumulating maps-   , mapAccumL-   , mapAccumR--   -- ** Infinite lists-   , iterate-   , repeat-   , replicate-   , cycle--   -- ** Unfolding-   , unfoldr--   -- * Sublists--   -- ** Extracting sublists-   , take-   , drop-   , splitAt--   , takeWhile-   , dropWhile-   , dropWhileEnd-   , span-   , break--   , stripPrefix--   , group--   , inits-   , tails--   -- ** Predicates-   , isPrefixOf-   , isSuffixOf-   , isInfixOf-   , isSubsequenceOf--   -- * Searching lists--   -- ** Searching by equality-   , elem-   , notElem-   , lookup--   -- ** Searching with a predicate-   , find-   , filter-   , partition--   -- * Indexing lists-   -- | These functions treat a list @xs@ as a indexed collection,-   -- with indices ranging from 0 to @'length' xs - 1@.--   , (!!)--   , elemIndex-   , elemIndices--   , findIndex-   , findIndices--   -- * Zipping and unzipping lists--   , zip-   , zip3-   , zip4, zip5, zip6, zip7--   , zipWith-   , zipWith3-   , zipWith4, zipWith5, zipWith6, zipWith7--   , unzip-   , unzip3-   , unzip4, unzip5, unzip6, unzip7--   -- * Special lists--   -- ** Functions on strings-   , lines-   , words-   , unlines-   , unwords--   -- ** \"Set\" operations--   , nub--   , delete-   , (\\)--   , union-   , intersect--   -- ** Ordered lists-   , sort-   , sortOn-   , insert--   -- * Generalized functions--   -- ** The \"@By@\" operations-   -- | By convention, overloaded functions have a non-overloaded-   -- counterpart whose name is suffixed with \`@By@\'.-   ---   -- It is often convenient to use these functions together with-   -- 'Data.Function.on', for instance @'sortBy' ('compare'-   -- \`on\` 'fst')@.--   -- *** User-supplied equality (replacing an @Eq@ context)-   -- | The predicate is assumed to define an equivalence.-   , nubBy-   , deleteBy-   , deleteFirstsBy-   , unionBy-   , intersectBy-   , groupBy--   -- *** User-supplied comparison (replacing an @Ord@ context)-   -- | The function is assumed to define a total ordering.-   , sortBy-   , insertBy-   , maximumBy-   , minimumBy--   -- ** The \"@generic@\" operations-   -- | The prefix \`@generic@\' indicates an overloaded function that-   -- is a generalized version of a "Prelude" function.--   , genericLength-   , genericTake-   , genericDrop-   , genericSplitAt-   , genericIndex-   , genericReplicate--   ) where--import Data.Foldable-import Data.Traversable--import Data.OldList hiding ( all, and, any, concat, concatMap, elem, find,-                             foldl, foldl1, foldl', foldr, foldr1, mapAccumL,-                             mapAccumR, maximum, maximumBy, minimum, minimumBy,-                             length, notElem, null, or, product, sum )--import GHC.Base ( Bool(..), Eq((==)), otherwise )---- | The 'isSubsequenceOf' function takes two lists and returns 'True' if the--- first list is a subsequence of the second list.------ @'isSubsequenceOf' x y@ is equivalent to @'elem' x ('subsequences' y)@.------ @since 4.8.0.0------ ==== __Examples__------ >>> isSubsequenceOf "GHC" "The Glorious Haskell Compiler"--- True--- >>> isSubsequenceOf ['a','d'..'z'] ['a'..'z']--- True--- >>> isSubsequenceOf [1..10] [10,9..0]--- False-isSubsequenceOf :: (Eq a) => [a] -> [a] -> Bool-isSubsequenceOf []    _                    = True-isSubsequenceOf _     []                   = False-isSubsequenceOf a@(x:a') (y:b) | x == y    = isSubsequenceOf a' b-                               | otherwise = isSubsequenceOf a b
− Data/Maybe.hs
@@ -1,300 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Maybe--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ The Maybe type, and associated operations.-----------------------------------------------------------------------------------module Data.Maybe-   (-     Maybe(Nothing,Just)--   , maybe--   , isJust-   , isNothing-   , fromJust-   , fromMaybe-   , listToMaybe-   , maybeToList-   , catMaybes-   , mapMaybe-   ) where--import GHC.Base---- $setup--- Allow the use of some Prelude functions in doctests.--- >>> import Prelude ( (*), odd, show, sum )---- ------------------------------------------------------------------------------ Functions over Maybe---- | The 'maybe' function takes a default value, a function, and a 'Maybe'--- value.  If the 'Maybe' value is 'Nothing', the function returns the--- default value.  Otherwise, it applies the function to the value inside--- the 'Just' and returns the result.------ ==== __Examples__------ Basic usage:------ >>> maybe False odd (Just 3)--- True------ >>> maybe False odd Nothing--- False------ Read an integer from a string using 'readMaybe'. If we succeed,--- return twice the integer; that is, apply @(*2)@ to it. If instead--- we fail to parse an integer, return @0@ by default:------ >>> import Text.Read ( readMaybe )--- >>> maybe 0 (*2) (readMaybe "5")--- 10--- >>> maybe 0 (*2) (readMaybe "")--- 0------ Apply 'show' to a @Maybe Int@. If we have @Just n@, we want to show--- the underlying 'Int' @n@. But if we have 'Nothing', we return the--- empty string instead of (for example) \"Nothing\":------ >>> maybe "" show (Just 5)--- "5"--- >>> maybe "" show Nothing--- ""----maybe :: b -> (a -> b) -> Maybe a -> b-maybe n _ Nothing  = n-maybe _ f (Just x) = f x---- | The 'isJust' function returns 'True' iff its argument is of the--- form @Just _@.------ ==== __Examples__------ Basic usage:------ >>> isJust (Just 3)--- True------ >>> isJust (Just ())--- True------ >>> isJust Nothing--- False------ Only the outer constructor is taken into consideration:------ >>> isJust (Just Nothing)--- True----isJust         :: Maybe a -> Bool-isJust Nothing = False-isJust _       = True---- | The 'isNothing' function returns 'True' iff its argument is 'Nothing'.------ ==== __Examples__------ Basic usage:------ >>> isNothing (Just 3)--- False------ >>> isNothing (Just ())--- False------ >>> isNothing Nothing--- True------ Only the outer constructor is taken into consideration:------ >>> isNothing (Just Nothing)--- False----isNothing         :: Maybe a -> Bool-isNothing Nothing = True-isNothing _       = False---- | The 'fromJust' function extracts the element out of a 'Just' and--- throws an error if its argument is 'Nothing'.------ ==== __Examples__------ Basic usage:------ >>> fromJust (Just 1)--- 1------ >>> 2 * (fromJust (Just 10))--- 20------ >>> 2 * (fromJust Nothing)--- *** Exception: Maybe.fromJust: Nothing----fromJust          :: Maybe a -> a-fromJust Nothing  = error "Maybe.fromJust: Nothing" -- yuck-fromJust (Just x) = x---- | The 'fromMaybe' function takes a default value and and 'Maybe'--- value.  If the 'Maybe' is 'Nothing', it returns the default values;--- otherwise, it returns the value contained in the 'Maybe'.------ ==== __Examples__------ Basic usage:------ >>> fromMaybe "" (Just "Hello, World!")--- "Hello, World!"------ >>> fromMaybe "" Nothing--- ""------ Read an integer from a string using 'readMaybe'. If we fail to--- parse an integer, we want to return @0@ by default:------ >>> import Text.Read ( readMaybe )--- >>> fromMaybe 0 (readMaybe "5")--- 5--- >>> fromMaybe 0 (readMaybe "")--- 0----fromMaybe     :: a -> Maybe a -> a-fromMaybe d x = case x of {Nothing -> d;Just v  -> v}---- | The 'maybeToList' function returns an empty list when given--- 'Nothing' or a singleton list when not given 'Nothing'.------ ==== __Examples__------ Basic usage:------ >>> maybeToList (Just 7)--- [7]------ >>> maybeToList Nothing--- []------ One can use 'maybeToList' to avoid pattern matching when combined--- with a function that (safely) works on lists:------ >>> import Text.Read ( readMaybe )--- >>> sum $ maybeToList (readMaybe "3")--- 3--- >>> sum $ maybeToList (readMaybe "")--- 0----maybeToList            :: Maybe a -> [a]-maybeToList  Nothing   = []-maybeToList  (Just x)  = [x]---- | The 'listToMaybe' function returns 'Nothing' on an empty list--- or @'Just' a@ where @a@ is the first element of the list.------ ==== __Examples__------ Basic usage:------ >>> listToMaybe []--- Nothing------ >>> listToMaybe [9]--- Just 9------ >>> listToMaybe [1,2,3]--- Just 1------ Composing 'maybeToList' with 'listToMaybe' should be the identity--- on singleton/empty lists:------ >>> maybeToList $ listToMaybe [5]--- [5]--- >>> maybeToList $ listToMaybe []--- []------ But not on lists with more than one element:------ >>> maybeToList $ listToMaybe [1,2,3]--- [1]----listToMaybe           :: [a] -> Maybe a-listToMaybe []        =  Nothing-listToMaybe (a:_)     =  Just a---- | The 'catMaybes' function takes a list of 'Maybe's and returns--- a list of all the 'Just' values.------ ==== __Examples__------ Basic usage:------ >>> catMaybes [Just 1, Nothing, Just 3]--- [1,3]------ When constructing a list of 'Maybe' values, 'catMaybes' can be used--- to return all of the \"success\" results (if the list is the result--- of a 'map', then 'mapMaybe' would be more appropriate):------ >>> import Text.Read ( readMaybe )--- >>> [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]--- [Just 1,Nothing,Just 3]--- >>> catMaybes $ [readMaybe x :: Maybe Int | x <- ["1", "Foo", "3"] ]--- [1,3]----catMaybes              :: [Maybe a] -> [a]-catMaybes ls = [x | Just x <- ls]---- | The 'mapMaybe' function is a version of 'map' which can throw--- out elements.  In particular, the functional argument returns--- something of type @'Maybe' b@.  If this is 'Nothing', no element--- is added on to the result list.  If it is @'Just' b@, then @b@ is--- included in the result list.------ ==== __Examples__------ Using @'mapMaybe' f x@ is a shortcut for @'catMaybes' $ 'map' f x@--- in most cases:------ >>> import Text.Read ( readMaybe )--- >>> let readMaybeInt = readMaybe :: String -> Maybe Int--- >>> mapMaybe readMaybeInt ["1", "Foo", "3"]--- [1,3]--- >>> catMaybes $ map readMaybeInt ["1", "Foo", "3"]--- [1,3]------ If we map the 'Just' constructor, the entire list should be returned:------ >>> mapMaybe Just [1,2,3]--- [1,2,3]----mapMaybe          :: (a -> Maybe b) -> [a] -> [b]-mapMaybe _ []     = []-mapMaybe f (x:xs) =- let rs = mapMaybe f xs in- case f x of-  Nothing -> rs-  Just r  -> r:rs-{-# NOINLINE [1] mapMaybe #-}--{-# RULES-"mapMaybe"     [~1] forall f xs. mapMaybe f xs-                    = build (\c n -> foldr (mapMaybeFB c f) n xs)-"mapMaybeList" [1]  forall f. foldr (mapMaybeFB (:) f) [] = mapMaybe f-  #-}--{-# NOINLINE [0] mapMaybeFB #-}-mapMaybeFB :: (b -> r -> r) -> (a -> Maybe b) -> a -> r -> r-mapMaybeFB cons f x next = case f x of-  Nothing -> next-  Just r -> cons r next
− Data/Monoid.hs
@@ -1,209 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE AutoDeriveTypeable #-}-{-# LANGUAGE DeriveGeneric #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE PolyKinds #-}-{-# LANGUAGE ScopedTypeVariables #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Monoid--- Copyright   :  (c) Andy Gill 2001,---                (c) Oregon Graduate Institute of Science and Technology, 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ A class for monoids (types with an associative binary operation that--- has an identity) with various general-purpose instances.-----------------------------------------------------------------------------------module Data.Monoid (-        -- * 'Monoid' typeclass-        Monoid(..),-        (<>),-        Dual(..),-        Endo(..),-        -- * 'Bool' wrappers-        All(..),-        Any(..),-        -- * 'Num' wrappers-        Sum(..),-        Product(..),-        -- * 'Maybe' wrappers-        -- $MaybeExamples-        First(..),-        Last(..),-        -- * 'Alternative' wrapper-        Alt (..)-  ) where---- Push down the module in the dependency hierarchy.-import GHC.Base hiding (Any)-import GHC.Enum-import GHC.Num-import GHC.Read-import GHC.Show-import GHC.Generics--{---- just for testing-import Data.Maybe-import Test.QuickCheck--- -}--infixr 6 <>---- | An infix synonym for 'mappend'.------ @since 4.5.0.0-(<>) :: Monoid m => m -> m -> m-(<>) = mappend-{-# INLINE (<>) #-}---- Monoid instances.---- | The dual of a 'Monoid', obtained by swapping the arguments of 'mappend'.-newtype Dual a = Dual { getDual :: a }-        deriving (Eq, Ord, Read, Show, Bounded, Generic, Generic1)--instance Monoid a => Monoid (Dual a) where-        mempty = Dual mempty-        Dual x `mappend` Dual y = Dual (y `mappend` x)---- | The monoid of endomorphisms under composition.-newtype Endo a = Endo { appEndo :: a -> a }-               deriving (Generic)--instance Monoid (Endo a) where-        mempty = Endo id-        Endo f `mappend` Endo g = Endo (f . g)---- | Boolean monoid under conjunction ('&&').-newtype All = All { getAll :: Bool }-        deriving (Eq, Ord, Read, Show, Bounded, Generic)--instance Monoid All where-        mempty = All True-        All x `mappend` All y = All (x && y)---- | Boolean monoid under disjunction ('||').-newtype Any = Any { getAny :: Bool }-        deriving (Eq, Ord, Read, Show, Bounded, Generic)--instance Monoid Any where-        mempty = Any False-        Any x `mappend` Any y = Any (x || y)---- | Monoid under addition.-newtype Sum a = Sum { getSum :: a }-        deriving (Eq, Ord, Read, Show, Bounded, Generic, Generic1, Num)--instance Num a => Monoid (Sum a) where-        mempty = Sum 0-        mappend = coerce ((+) :: a -> a -> a)---        Sum x `mappend` Sum y = Sum (x + y)---- | Monoid under multiplication.-newtype Product a = Product { getProduct :: a }-        deriving (Eq, Ord, Read, Show, Bounded, Generic, Generic1, Num)--instance Num a => Monoid (Product a) where-        mempty = Product 1-        mappend = coerce ((*) :: a -> a -> a)---        Product x `mappend` Product y = Product (x * y)---- $MaybeExamples--- To implement @find@ or @findLast@ on any 'Foldable':------ @--- findLast :: Foldable t => (a -> Bool) -> t a -> Maybe a--- findLast pred = getLast . foldMap (\x -> if pred x---                                            then Last (Just x)---                                            else Last Nothing)--- @------ Much of Data.Map's interface can be implemented with--- Data.Map.alter. Some of the rest can be implemented with a new--- @alterA@ function and either 'First' or 'Last':------ > alterA :: (Applicative f, Ord k) =>--- >           (Maybe a -> f (Maybe a)) -> k -> Map k a -> f (Map k a)--- >--- > instance Monoid a => Applicative ((,) a)  -- from Control.Applicative------ @--- insertLookupWithKey :: Ord k => (k -> v -> v -> v) -> k -> v---                     -> Map k v -> (Maybe v, Map k v)--- insertLookupWithKey combine key value =---   Arrow.first getFirst . alterA doChange key---   where---   doChange Nothing = (First Nothing, Just value)---   doChange (Just oldValue) =---     (First (Just oldValue),---      Just (combine key value oldValue))--- @----- | Maybe monoid returning the leftmost non-Nothing value.------ @'First' a@ is isomorphic to @'Alt' 'Maybe' a@, but precedes it--- historically.-newtype First a = First { getFirst :: Maybe a }-        deriving (Eq, Ord, Read, Show, Generic, Generic1,-                  Functor, Applicative, Monad)--instance Monoid (First a) where-        mempty = First Nothing-        First Nothing `mappend` r = r-        l `mappend` _             = l---- | Maybe monoid returning the rightmost non-Nothing value.------ @'Last' a@ is isomorphic to @'Dual' ('First' a)@, and thus to--- @'Dual' ('Alt' 'Maybe' a)@-newtype Last a = Last { getLast :: Maybe a }-        deriving (Eq, Ord, Read, Show, Generic, Generic1,-                  Functor, Applicative, Monad)--instance Monoid (Last a) where-        mempty = Last Nothing-        l `mappend` Last Nothing = l-        _ `mappend` r            = r---- | Monoid under '<|>'.------ @since 4.8.0.0-newtype Alt f a = Alt {getAlt :: f a}-  deriving (Generic, Generic1, Read, Show, Eq, Ord, Num, Enum,-            Monad, MonadPlus, Applicative, Alternative, Functor)--instance forall f a . Alternative f => Monoid (Alt f a) where-        mempty = Alt empty-        mappend = coerce ((<|>) :: f a -> f a -> f a)--{--{---------------------------------------------------------------------  Testing---------------------------------------------------------------------}-instance Arbitrary a => Arbitrary (Maybe a) where-  arbitrary = oneof [return Nothing, Just `fmap` arbitrary]--prop_mconcatMaybe :: [Maybe [Int]] -> Bool-prop_mconcatMaybe x =-  fromMaybe [] (mconcat x) == mconcat (catMaybes x)--prop_mconcatFirst :: [Maybe Int] -> Bool-prop_mconcatFirst x =-  getFirst (mconcat (map First x)) == listToMaybe (catMaybes x)-prop_mconcatLast :: [Maybe Int] -> Bool-prop_mconcatLast x =-  getLast (mconcat (map Last x)) == listLastToMaybe (catMaybes x)-        where listLastToMaybe [] = Nothing-              listLastToMaybe lst = Just (last lst)--- -}-
− Data/OldList.hs
@@ -1,1179 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, ScopedTypeVariables, MagicHash #-}---------------------------------------------------------------------------------- |--- Module      :  Data.List--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ Operations on lists.-----------------------------------------------------------------------------------module Data.OldList-   (-   -- * Basic functions--     (++)-   , head-   , last-   , tail-   , init-   , uncons-   , null-   , length--   -- * List transformations-   , map-   , reverse--   , intersperse-   , intercalate-   , transpose--   , subsequences-   , permutations--   -- * Reducing lists (folds)--   , foldl-   , foldl'-   , foldl1-   , foldl1'-   , foldr-   , foldr1--   -- ** Special folds--   , concat-   , concatMap-   , and-   , or-   , any-   , all-   , sum-   , product-   , maximum-   , minimum--   -- * Building lists--   -- ** Scans-   , scanl-   , scanl'-   , scanl1-   , scanr-   , scanr1--   -- ** Accumulating maps-   , mapAccumL-   , mapAccumR--   -- ** Infinite lists-   , iterate-   , repeat-   , replicate-   , cycle--   -- ** Unfolding-   , unfoldr--   -- * Sublists--   -- ** Extracting sublists-   , take-   , drop-   , splitAt--   , takeWhile-   , dropWhile-   , dropWhileEnd-   , span-   , break--   , stripPrefix--   , group--   , inits-   , tails--   -- ** Predicates-   , isPrefixOf-   , isSuffixOf-   , isInfixOf--   -- * Searching lists--   -- ** Searching by equality-   , elem-   , notElem-   , lookup--   -- ** Searching with a predicate-   , find-   , filter-   , partition--   -- * Indexing lists-   -- | These functions treat a list @xs@ as a indexed collection,-   -- with indices ranging from 0 to @'length' xs - 1@.--   , (!!)--   , elemIndex-   , elemIndices--   , findIndex-   , findIndices--   -- * Zipping and unzipping lists--   , zip-   , zip3-   , zip4, zip5, zip6, zip7--   , zipWith-   , zipWith3-   , zipWith4, zipWith5, zipWith6, zipWith7--   , unzip-   , unzip3-   , unzip4, unzip5, unzip6, unzip7--   -- * Special lists--   -- ** Functions on strings-   , lines-   , words-   , unlines-   , unwords--   -- ** \"Set\" operations--   , nub--   , delete-   , (\\)--   , union-   , intersect--   -- ** Ordered lists-   , sort-   , sortOn-   , insert--   -- * Generalized functions--   -- ** The \"@By@\" operations-   -- | By convention, overloaded functions have a non-overloaded-   -- counterpart whose name is suffixed with \`@By@\'.-   ---   -- It is often convenient to use these functions together with-   -- 'Data.Function.on', for instance @'sortBy' ('compare'-   -- \`on\` 'fst')@.--   -- *** User-supplied equality (replacing an @Eq@ context)-   -- | The predicate is assumed to define an equivalence.-   , nubBy-   , deleteBy-   , deleteFirstsBy-   , unionBy-   , intersectBy-   , groupBy--   -- *** User-supplied comparison (replacing an @Ord@ context)-   -- | The function is assumed to define a total ordering.-   , sortBy-   , insertBy-   , maximumBy-   , minimumBy--   -- ** The \"@generic@\" operations-   -- | The prefix \`@generic@\' indicates an overloaded function that-   -- is a generalized version of a "Prelude" function.--   , genericLength-   , genericTake-   , genericDrop-   , genericSplitAt-   , genericIndex-   , genericReplicate--   ) where--import Data.Maybe-import Data.Bits        ( (.&.) )-import Data.Char        ( isSpace )-import Data.Ord         ( comparing )-import Data.Tuple       ( fst, snd )--import GHC.Num-import GHC.Real-import GHC.List-import GHC.Base--infix 5 \\ -- comment to fool cpp: https://www.haskell.org/ghc/docs/latest/html/users_guide/options-phases.html#cpp-string-gaps---- -------------------------------------------------------------------------------- List functions---- | The 'dropWhileEnd' function drops the largest suffix of a list--- in which the given predicate holds for all elements.  For example:------ > dropWhileEnd isSpace "foo\n" == "foo"--- > dropWhileEnd isSpace "foo bar" == "foo bar"--- > dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined------ @since 4.5.0.0-dropWhileEnd :: (a -> Bool) -> [a] -> [a]-dropWhileEnd p = foldr (\x xs -> if p x && null xs then [] else x : xs) []---- | The 'stripPrefix' function drops the given prefix from a list.--- It returns 'Nothing' if the list did not start with the prefix--- given, or 'Just' the list after the prefix, if it does.------ > stripPrefix "foo" "foobar" == Just "bar"--- > stripPrefix "foo" "foo" == Just ""--- > stripPrefix "foo" "barfoo" == Nothing--- > stripPrefix "foo" "barfoobaz" == Nothing-stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]-stripPrefix [] ys = Just ys-stripPrefix (x:xs) (y:ys)- | x == y = stripPrefix xs ys-stripPrefix _ _ = Nothing---- | The 'elemIndex' function returns the index of the first element--- in the given list which is equal (by '==') to the query element,--- or 'Nothing' if there is no such element.-elemIndex       :: Eq a => a -> [a] -> Maybe Int-elemIndex x     = findIndex (x==)---- | The 'elemIndices' function extends 'elemIndex', by returning the--- indices of all elements equal to the query element, in ascending order.-elemIndices     :: Eq a => a -> [a] -> [Int]-elemIndices x   = findIndices (x==)---- | The 'find' function takes a predicate and a list and returns the--- first element in the list matching the predicate, or 'Nothing' if--- there is no such element.-find            :: (a -> Bool) -> [a] -> Maybe a-find p          = listToMaybe . filter p---- | The 'findIndex' function takes a predicate and a list and returns--- the index of the first element in the list satisfying the predicate,--- or 'Nothing' if there is no such element.-findIndex       :: (a -> Bool) -> [a] -> Maybe Int-findIndex p     = listToMaybe . findIndices p---- | The 'findIndices' function extends 'findIndex', by returning the--- indices of all elements satisfying the predicate, in ascending order.-findIndices      :: (a -> Bool) -> [a] -> [Int]-#ifdef USE_REPORT_PRELUDE-findIndices p xs = [ i | (x,i) <- zip xs [0..], p x]-#else--- Efficient definition, adapted from Data.Sequence-{-# INLINE findIndices #-}-findIndices p ls = build $ \c n ->-  let go x r k | p x       = I# k `c` r (k +# 1#)-               | otherwise = r (k +# 1#)-  in foldr go (\_ -> n) ls 0#-#endif  /* USE_REPORT_PRELUDE */---- | The 'isPrefixOf' function takes two lists and returns 'True'--- iff the first list is a prefix of the second.-isPrefixOf              :: (Eq a) => [a] -> [a] -> Bool-isPrefixOf [] _         =  True-isPrefixOf _  []        =  False-isPrefixOf (x:xs) (y:ys)=  x == y && isPrefixOf xs ys---- | The 'isSuffixOf' function takes two lists and returns 'True' iff--- the first list is a suffix of the second. The second list must be--- finite.-isSuffixOf              :: (Eq a) => [a] -> [a] -> Bool-ns `isSuffixOf` hs      = maybe False id $ do-      delta <- dropLengthMaybe ns hs-      return $ ns == dropLength delta hs-      -- Since dropLengthMaybe ns hs succeeded, we know that (if hs is finite)-      -- length ns + length delta = length hs-      -- so dropping the length of delta from hs will yield a suffix exactly-      -- the length of ns.---- A version of drop that drops the length of the first argument from the--- second argument. If xs is longer than ys, xs will not be traversed in its--- entirety.  dropLength is also generally faster than (drop . length)--- Both this and dropLengthMaybe could be written as folds over their first--- arguments, but this reduces clarity with no benefit to isSuffixOf.-dropLength :: [a] -> [b] -> [b]-dropLength [] y = y-dropLength _ [] = []-dropLength (_:x') (_:y') = dropLength x' y'---- A version of dropLength that returns Nothing if the second list runs out of--- elements before the first.-dropLengthMaybe :: [a] -> [b] -> Maybe [b]-dropLengthMaybe [] y = Just y-dropLengthMaybe _ [] = Nothing-dropLengthMaybe (_:x') (_:y') = dropLengthMaybe x' y'---- | The 'isInfixOf' function takes two lists and returns 'True'--- iff the first list is contained, wholly and intact,--- anywhere within the second.------ Example:------ >isInfixOf "Haskell" "I really like Haskell." == True--- >isInfixOf "Ial" "I really like Haskell." == False-isInfixOf               :: (Eq a) => [a] -> [a] -> Bool-isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)---- | /O(n^2)/. The 'nub' function removes duplicate elements from a list.--- In particular, it keeps only the first occurrence of each element.--- (The name 'nub' means \`essence\'.)--- It is a special case of 'nubBy', which allows the programmer to supply--- their own equality test.-nub                     :: (Eq a) => [a] -> [a]-nub                     =  nubBy (==)---- | The 'nubBy' function behaves just like 'nub', except it uses a--- user-supplied equality predicate instead of the overloaded '=='--- function.-nubBy                   :: (a -> a -> Bool) -> [a] -> [a]-#ifdef USE_REPORT_PRELUDE-nubBy eq []             =  []-nubBy eq (x:xs)         =  x : nubBy eq (filter (\ y -> not (eq x y)) xs)-#else--- stolen from HBC-nubBy eq l              = nubBy' l []-  where-    nubBy' [] _         = []-    nubBy' (y:ys) xs-       | elem_by eq y xs = nubBy' ys xs-       | otherwise       = y : nubBy' ys (y:xs)---- Not exported:--- Note that we keep the call to `eq` with arguments in the--- same order as in the reference (prelude) implementation,--- and that this order is different from how `elem` calls (==).--- See #2528, #3280 and #7913.--- 'xs' is the list of things we've seen so far,--- 'y' is the potential new element-elem_by :: (a -> a -> Bool) -> a -> [a] -> Bool-elem_by _  _ []         =  False-elem_by eq y (x:xs)     =  x `eq` y || elem_by eq y xs-#endif----- | 'delete' @x@ removes the first occurrence of @x@ from its list argument.--- For example,------ > delete 'a' "banana" == "bnana"------ It is a special case of 'deleteBy', which allows the programmer to--- supply their own equality test.--delete                  :: (Eq a) => a -> [a] -> [a]-delete                  =  deleteBy (==)---- | The 'deleteBy' function behaves like 'delete', but takes a--- user-supplied equality predicate.-deleteBy                :: (a -> a -> Bool) -> a -> [a] -> [a]-deleteBy _  _ []        = []-deleteBy eq x (y:ys)    = if x `eq` y then ys else y : deleteBy eq x ys---- | The '\\' function is list difference (non-associative).--- In the result of @xs@ '\\' @ys@, the first occurrence of each element of--- @ys@ in turn (if any) has been removed from @xs@.  Thus------ > (xs ++ ys) \\ xs == ys.------ It is a special case of 'deleteFirstsBy', which allows the programmer--- to supply their own equality test.--(\\)                    :: (Eq a) => [a] -> [a] -> [a]-(\\)                    =  foldl (flip delete)---- | The 'union' function returns the list union of the two lists.--- For example,------ > "dog" `union` "cow" == "dogcw"------ Duplicates, and elements of the first list, are removed from the--- the second list, but if the first list contains duplicates, so will--- the result.--- It is a special case of 'unionBy', which allows the programmer to supply--- their own equality test.--union                   :: (Eq a) => [a] -> [a] -> [a]-union                   = unionBy (==)---- | The 'unionBy' function is the non-overloaded version of 'union'.-unionBy                 :: (a -> a -> Bool) -> [a] -> [a] -> [a]-unionBy eq xs ys        =  xs ++ foldl (flip (deleteBy eq)) (nubBy eq ys) xs---- | The 'intersect' function takes the list intersection of two lists.--- For example,------ > [1,2,3,4] `intersect` [2,4,6,8] == [2,4]------ If the first list contains duplicates, so will the result.------ > [1,2,2,3,4] `intersect` [6,4,4,2] == [2,2,4]------ It is a special case of 'intersectBy', which allows the programmer to--- supply their own equality test. If the element is found in both the first--- and the second list, the element from the first list will be used.--intersect               :: (Eq a) => [a] -> [a] -> [a]-intersect               =  intersectBy (==)---- | The 'intersectBy' function is the non-overloaded version of 'intersect'.-intersectBy             :: (a -> a -> Bool) -> [a] -> [a] -> [a]-intersectBy _  [] _     =  []-intersectBy _  _  []    =  []-intersectBy eq xs ys    =  [x | x <- xs, any (eq x) ys]---- | The 'intersperse' function takes an element and a list and--- \`intersperses\' that element between the elements of the list.--- For example,------ > intersperse ',' "abcde" == "a,b,c,d,e"--intersperse             :: a -> [a] -> [a]-intersperse _   []      = []-intersperse sep (x:xs)  = x : prependToAll sep xs----- Not exported:--- We want to make every element in the 'intersperse'd list available--- as soon as possible to avoid space leaks. Experiments suggested that--- a separate top-level helper is more efficient than a local worker.-prependToAll            :: a -> [a] -> [a]-prependToAll _   []     = []-prependToAll sep (x:xs) = sep : x : prependToAll sep xs---- | 'intercalate' @xs xss@ is equivalent to @('concat' ('intersperse' xs xss))@.--- It inserts the list @xs@ in between the lists in @xss@ and concatenates the--- result.-intercalate :: [a] -> [[a]] -> [a]-intercalate xs xss = concat (intersperse xs xss)---- | The 'transpose' function transposes the rows and columns of its argument.--- For example,------ > transpose [[1,2,3],[4,5,6]] == [[1,4],[2,5],[3,6]]------ If some of the rows are shorter than the following rows, their elements are skipped:------ > transpose [[10,11],[20],[],[30,31,32]] == [[10,20,30],[11,31],[32]]--transpose               :: [[a]] -> [[a]]-transpose []             = []-transpose ([]   : xss)   = transpose xss-transpose ((x:xs) : xss) = (x : [h | (h:_) <- xss]) : transpose (xs : [ t | (_:t) <- xss])----- | The 'partition' function takes a predicate a list and returns--- the pair of lists of elements which do and do not satisfy the--- predicate, respectively; i.e.,------ > partition p xs == (filter p xs, filter (not . p) xs)--partition               :: (a -> Bool) -> [a] -> ([a],[a])-{-# INLINE partition #-}-partition p xs = foldr (select p) ([],[]) xs--select :: (a -> Bool) -> a -> ([a], [a]) -> ([a], [a])-select p x ~(ts,fs) | p x       = (x:ts,fs)-                    | otherwise = (ts, x:fs)---- | The 'mapAccumL' function behaves like a combination of 'map' and--- 'foldl'; it applies a function to each element of a list, passing--- an accumulating parameter from left to right, and returning a final--- value of this accumulator together with the new list.-mapAccumL :: (acc -> x -> (acc, y)) -- Function of elt of input list-                                    -- and accumulator, returning new-                                    -- accumulator and elt of result list-          -> acc            -- Initial accumulator-          -> [x]            -- Input list-          -> (acc, [y])     -- Final accumulator and result list-{-# NOINLINE [1] mapAccumL #-}-mapAccumL _ s []        =  (s, [])-mapAccumL f s (x:xs)    =  (s'',y:ys)-                           where (s', y ) = f s x-                                 (s'',ys) = mapAccumL f s' xs--{-# RULES-"mapAccumL" [~1] forall f s xs . mapAccumL f s xs = foldr (mapAccumLF f) pairWithNil xs s-"mapAccumLList" [1] forall f s xs . foldr (mapAccumLF f) pairWithNil xs s = mapAccumL f s xs- #-}--pairWithNil :: acc -> (acc, [y])-{-# INLINE [0] pairWithNil #-}-pairWithNil x = (x, [])--mapAccumLF :: (acc -> x -> (acc, y)) -> x -> (acc -> (acc, [y])) -> acc -> (acc, [y])-{-# INLINE [0] mapAccumLF #-}-mapAccumLF f = \x r -> oneShot (\s ->-                         let (s', y)   = f s x-                             (s'', ys) = r s'-                         in (s'', y:ys))-  -- See Note [Left folds via right fold]----- | The 'mapAccumR' function behaves like a combination of 'map' and--- 'foldr'; it applies a function to each element of a list, passing--- an accumulating parameter from right to left, and returning a final--- value of this accumulator together with the new list.-mapAccumR :: (acc -> x -> (acc, y))     -- Function of elt of input list-                                        -- and accumulator, returning new-                                        -- accumulator and elt of result list-            -> acc              -- Initial accumulator-            -> [x]              -- Input list-            -> (acc, [y])               -- Final accumulator and result list-mapAccumR _ s []        =  (s, [])-mapAccumR f s (x:xs)    =  (s'', y:ys)-                           where (s'',y ) = f s' x-                                 (s', ys) = mapAccumR f s xs---- | The 'insert' function takes an element and a list and inserts the--- element into the list at the first position where it is less--- than or equal to the next element.  In particular, if the list--- is sorted before the call, the result will also be sorted.--- It is a special case of 'insertBy', which allows the programmer to--- supply their own comparison function.-insert :: Ord a => a -> [a] -> [a]-insert e ls = insertBy (compare) e ls---- | The non-overloaded version of 'insert'.-insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]-insertBy _   x [] = [x]-insertBy cmp x ys@(y:ys')- = case cmp x y of-     GT -> y : insertBy cmp x ys'-     _  -> x : ys---- | The 'maximumBy' function takes a comparison function and a list--- and returns the greatest element of the list by the comparison function.--- The list must be finite and non-empty.-maximumBy               :: (a -> a -> Ordering) -> [a] -> a-maximumBy _ []          =  error "List.maximumBy: empty list"-maximumBy cmp xs        =  foldl1 maxBy xs-                        where-                           maxBy x y = case cmp x y of-                                       GT -> x-                                       _  -> y---- | The 'minimumBy' function takes a comparison function and a list--- and returns the least element of the list by the comparison function.--- The list must be finite and non-empty.-minimumBy               :: (a -> a -> Ordering) -> [a] -> a-minimumBy _ []          =  error "List.minimumBy: empty list"-minimumBy cmp xs        =  foldl1 minBy xs-                        where-                           minBy x y = case cmp x y of-                                       GT -> y-                                       _  -> x---- | The 'genericLength' function is an overloaded version of 'length'.  In--- particular, instead of returning an 'Int', it returns any type which is--- an instance of 'Num'.  It is, however, less efficient than 'length'.-genericLength           :: (Num i) => [a] -> i-{-# NOINLINE [1] genericLength #-}-genericLength []        =  0-genericLength (_:l)     =  1 + genericLength l--{-# RULES-  "genericLengthInt"     genericLength = (strictGenericLength :: [a] -> Int);-  "genericLengthInteger" genericLength = (strictGenericLength :: [a] -> Integer);- #-}--strictGenericLength     :: (Num i) => [b] -> i-strictGenericLength l   =  gl l 0-                        where-                           gl [] a     = a-                           gl (_:xs) a = let a' = a + 1 in a' `seq` gl xs a'---- | The 'genericTake' function is an overloaded version of 'take', which--- accepts any 'Integral' value as the number of elements to take.-genericTake             :: (Integral i) => i -> [a] -> [a]-genericTake n _ | n <= 0 = []-genericTake _ []        =  []-genericTake n (x:xs)    =  x : genericTake (n-1) xs---- | The 'genericDrop' function is an overloaded version of 'drop', which--- accepts any 'Integral' value as the number of elements to drop.-genericDrop             :: (Integral i) => i -> [a] -> [a]-genericDrop n xs | n <= 0 = xs-genericDrop _ []        =  []-genericDrop n (_:xs)    =  genericDrop (n-1) xs----- | The 'genericSplitAt' function is an overloaded version of 'splitAt', which--- accepts any 'Integral' value as the position at which to split.-genericSplitAt          :: (Integral i) => i -> [a] -> ([a], [a])-genericSplitAt n xs | n <= 0 =  ([],xs)-genericSplitAt _ []     =  ([],[])-genericSplitAt n (x:xs) =  (x:xs',xs'') where-    (xs',xs'') = genericSplitAt (n-1) xs---- | The 'genericIndex' function is an overloaded version of '!!', which--- accepts any 'Integral' value as the index.-genericIndex :: (Integral i) => [a] -> i -> a-genericIndex (x:_)  0 = x-genericIndex (_:xs) n- | n > 0     = genericIndex xs (n-1)- | otherwise = error "List.genericIndex: negative argument."-genericIndex _ _      = error "List.genericIndex: index too large."---- | The 'genericReplicate' function is an overloaded version of 'replicate',--- which accepts any 'Integral' value as the number of repetitions to make.-genericReplicate        :: (Integral i) => i -> a -> [a]-genericReplicate n x    =  genericTake n (repeat x)---- | The 'zip4' function takes four lists and returns a list of--- quadruples, analogous to 'zip'.-zip4                    :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]-zip4                    =  zipWith4 (,,,)---- | The 'zip5' function takes five lists and returns a list of--- five-tuples, analogous to 'zip'.-zip5                    :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]-zip5                    =  zipWith5 (,,,,)---- | The 'zip6' function takes six lists and returns a list of six-tuples,--- analogous to 'zip'.-zip6                    :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->-                              [(a,b,c,d,e,f)]-zip6                    =  zipWith6 (,,,,,)---- | The 'zip7' function takes seven lists and returns a list of--- seven-tuples, analogous to 'zip'.-zip7                    :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->-                              [g] -> [(a,b,c,d,e,f,g)]-zip7                    =  zipWith7 (,,,,,,)---- | The 'zipWith4' function takes a function which combines four--- elements, as well as four lists and returns a list of their point-wise--- combination, analogous to 'zipWith'.-zipWith4                :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]-zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)-                        =  z a b c d : zipWith4 z as bs cs ds-zipWith4 _ _ _ _ _      =  []---- | The 'zipWith5' function takes a function which combines five--- elements, as well as five lists and returns a list of their point-wise--- combination, analogous to 'zipWith'.-zipWith5                :: (a->b->c->d->e->f) ->-                           [a]->[b]->[c]->[d]->[e]->[f]-zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)-                        =  z a b c d e : zipWith5 z as bs cs ds es-zipWith5 _ _ _ _ _ _    = []---- | The 'zipWith6' function takes a function which combines six--- elements, as well as six lists and returns a list of their point-wise--- combination, analogous to 'zipWith'.-zipWith6                :: (a->b->c->d->e->f->g) ->-                           [a]->[b]->[c]->[d]->[e]->[f]->[g]-zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)-                        =  z a b c d e f : zipWith6 z as bs cs ds es fs-zipWith6 _ _ _ _ _ _ _  = []---- | The 'zipWith7' function takes a function which combines seven--- elements, as well as seven lists and returns a list of their point-wise--- combination, analogous to 'zipWith'.-zipWith7                :: (a->b->c->d->e->f->g->h) ->-                           [a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]-zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)-                   =  z a b c d e f g : zipWith7 z as bs cs ds es fs gs-zipWith7 _ _ _ _ _ _ _ _ = []---- | The 'unzip4' function takes a list of quadruples and returns four--- lists, analogous to 'unzip'.-unzip4                  :: [(a,b,c,d)] -> ([a],[b],[c],[d])-unzip4                  =  foldr (\(a,b,c,d) ~(as,bs,cs,ds) ->-                                        (a:as,b:bs,c:cs,d:ds))-                                 ([],[],[],[])---- | The 'unzip5' function takes a list of five-tuples and returns five--- lists, analogous to 'unzip'.-unzip5                  :: [(a,b,c,d,e)] -> ([a],[b],[c],[d],[e])-unzip5                  =  foldr (\(a,b,c,d,e) ~(as,bs,cs,ds,es) ->-                                        (a:as,b:bs,c:cs,d:ds,e:es))-                                 ([],[],[],[],[])---- | The 'unzip6' function takes a list of six-tuples and returns six--- lists, analogous to 'unzip'.-unzip6                  :: [(a,b,c,d,e,f)] -> ([a],[b],[c],[d],[e],[f])-unzip6                  =  foldr (\(a,b,c,d,e,f) ~(as,bs,cs,ds,es,fs) ->-                                        (a:as,b:bs,c:cs,d:ds,e:es,f:fs))-                                 ([],[],[],[],[],[])---- | The 'unzip7' function takes a list of seven-tuples and returns--- seven lists, analogous to 'unzip'.-unzip7          :: [(a,b,c,d,e,f,g)] -> ([a],[b],[c],[d],[e],[f],[g])-unzip7          =  foldr (\(a,b,c,d,e,f,g) ~(as,bs,cs,ds,es,fs,gs) ->-                                (a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs))-                         ([],[],[],[],[],[],[])----- | The 'deleteFirstsBy' function takes a predicate and two lists and--- returns the first list with the first occurrence of each element of--- the second list removed.-deleteFirstsBy          :: (a -> a -> Bool) -> [a] -> [a] -> [a]-deleteFirstsBy eq       =  foldl (flip (deleteBy eq))---- | The 'group' function takes a list and returns a list of lists such--- that the concatenation of the result is equal to the argument.  Moreover,--- each sublist in the result contains only equal elements.  For example,------ > group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]------ It is a special case of 'groupBy', which allows the programmer to supply--- their own equality test.-group                   :: Eq a => [a] -> [[a]]-group                   =  groupBy (==)---- | The 'groupBy' function is the non-overloaded version of 'group'.-groupBy                 :: (a -> a -> Bool) -> [a] -> [[a]]-groupBy _  []           =  []-groupBy eq (x:xs)       =  (x:ys) : groupBy eq zs-                           where (ys,zs) = span (eq x) xs---- | The 'inits' function returns all initial segments of the argument,--- shortest first.  For example,------ > inits "abc" == ["","a","ab","abc"]------ Note that 'inits' has the following strictness property:--- @inits (xs ++ _|_) = inits xs ++ _|_@------ In particular,--- @inits _|_ = [] : _|_@-inits                   :: [a] -> [[a]]-inits                   = map toListSB . scanl' snocSB emptySB-{-# NOINLINE inits #-}---- We do not allow inits to inline, because it plays havoc with Call Arity--- if it fuses with a consumer, and it would generally lead to serious--- loss of sharing if allowed to fuse with a producer.---- | The 'tails' function returns all final segments of the argument,--- longest first.  For example,------ > tails "abc" == ["abc", "bc", "c",""]------ Note that 'tails' has the following strictness property:--- @tails _|_ = _|_ : _|_@-tails                   :: [a] -> [[a]]-{-# INLINABLE tails #-}-tails lst               =  build (\c n ->-  let tailsGo xs = xs `c` case xs of-                             []      -> n-                             _ : xs' -> tailsGo xs'-  in tailsGo lst)---- | The 'subsequences' function returns the list of all subsequences of the argument.------ > subsequences "abc" == ["","a","b","ab","c","ac","bc","abc"]-subsequences            :: [a] -> [[a]]-subsequences xs         =  [] : nonEmptySubsequences xs---- | The 'nonEmptySubsequences' function returns the list of all subsequences of the argument,---   except for the empty list.------ > nonEmptySubsequences "abc" == ["a","b","ab","c","ac","bc","abc"]-nonEmptySubsequences         :: [a] -> [[a]]-nonEmptySubsequences []      =  []-nonEmptySubsequences (x:xs)  =  [x] : foldr f [] (nonEmptySubsequences xs)-  where f ys r = ys : (x : ys) : r----- | The 'permutations' function returns the list of all permutations of the argument.------ > permutations "abc" == ["abc","bac","cba","bca","cab","acb"]-permutations            :: [a] -> [[a]]-permutations xs0        =  xs0 : perms xs0 []-  where-    perms []     _  = []-    perms (t:ts) is = foldr interleave (perms ts (t:is)) (permutations is)-      where interleave    xs     r = let (_,zs) = interleave' id xs r in zs-            interleave' _ []     r = (ts, r)-            interleave' f (y:ys) r = let (us,zs) = interleave' (f . (y:)) ys r-                                     in  (y:us, f (t:y:us) : zs)------------------------------------------------------------------------------------ Quick Sort algorithm taken from HBC's QSort library.---- | The 'sort' function implements a stable sorting algorithm.--- It is a special case of 'sortBy', which allows the programmer to supply--- their own comparison function.-sort :: (Ord a) => [a] -> [a]---- | The 'sortBy' function is the non-overloaded version of 'sort'.-sortBy :: (a -> a -> Ordering) -> [a] -> [a]--#ifdef USE_REPORT_PRELUDE-sort = sortBy compare-sortBy cmp = foldr (insertBy cmp) []-#else--{--GHC's mergesort replaced by a better implementation, 24/12/2009.-This code originally contributed to the nhc12 compiler by Thomas Nordin-in 2002.  Rumoured to have been based on code by Lennart Augustsson, e.g.-    http://www.mail-archive.com/haskell@haskell.org/msg01822.html-and possibly to bear similarities to a 1982 paper by Richard O'Keefe:-"A smooth applicative merge sort".--Benchmarks show it to be often 2x the speed of the previous implementation.-Fixes ticket http://ghc.haskell.org/trac/ghc/ticket/2143--}--sort = sortBy compare-sortBy cmp = mergeAll . sequences-  where-    sequences (a:b:xs)-      | a `cmp` b == GT = descending b [a]  xs-      | otherwise       = ascending  b (a:) xs-    sequences xs = [xs]--    descending a as (b:bs)-      | a `cmp` b == GT = descending b (a:as) bs-    descending a as bs  = (a:as): sequences bs--    ascending a as (b:bs)-      | a `cmp` b /= GT = ascending b (\ys -> as (a:ys)) bs-    ascending a as bs   = as [a]: sequences bs--    mergeAll [x] = x-    mergeAll xs  = mergeAll (mergePairs xs)--    mergePairs (a:b:xs) = merge a b: mergePairs xs-    mergePairs xs       = xs--    merge as@(a:as') bs@(b:bs')-      | a `cmp` b == GT = b:merge as  bs'-      | otherwise       = a:merge as' bs-    merge [] bs         = bs-    merge as []         = as--{--sortBy cmp l = mergesort cmp l-sort l = mergesort compare l--Quicksort replaced by mergesort, 14/5/2002.--From: Ian Lynagh <igloo@earth.li>--I am curious as to why the List.sort implementation in GHC is a-quicksort algorithm rather than an algorithm that guarantees n log n-time in the worst case? I have attached a mergesort implementation along-with a few scripts to time it's performance, the results of which are-shown below (* means it didn't finish successfully - in all cases this-was due to a stack overflow).--If I heap profile the random_list case with only 10000 then I see-random_list peaks at using about 2.5M of memory, whereas in the same-program using List.sort it uses only 100k.--Input style     Input length     Sort data     Sort alg    User time-stdin           10000            random_list   sort        2.82-stdin           10000            random_list   mergesort   2.96-stdin           10000            sorted        sort        31.37-stdin           10000            sorted        mergesort   1.90-stdin           10000            revsorted     sort        31.21-stdin           10000            revsorted     mergesort   1.88-stdin           100000           random_list   sort        *-stdin           100000           random_list   mergesort   *-stdin           100000           sorted        sort        *-stdin           100000           sorted        mergesort   *-stdin           100000           revsorted     sort        *-stdin           100000           revsorted     mergesort   *-func            10000            random_list   sort        0.31-func            10000            random_list   mergesort   0.91-func            10000            sorted        sort        19.09-func            10000            sorted        mergesort   0.15-func            10000            revsorted     sort        19.17-func            10000            revsorted     mergesort   0.16-func            100000           random_list   sort        3.85-func            100000           random_list   mergesort   *-func            100000           sorted        sort        5831.47-func            100000           sorted        mergesort   2.23-func            100000           revsorted     sort        5872.34-func            100000           revsorted     mergesort   2.24--mergesort :: (a -> a -> Ordering) -> [a] -> [a]-mergesort cmp = mergesort' cmp . map wrap--mergesort' :: (a -> a -> Ordering) -> [[a]] -> [a]-mergesort' _   [] = []-mergesort' _   [xs] = xs-mergesort' cmp xss = mergesort' cmp (merge_pairs cmp xss)--merge_pairs :: (a -> a -> Ordering) -> [[a]] -> [[a]]-merge_pairs _   [] = []-merge_pairs _   [xs] = [xs]-merge_pairs cmp (xs:ys:xss) = merge cmp xs ys : merge_pairs cmp xss--merge :: (a -> a -> Ordering) -> [a] -> [a] -> [a]-merge _   [] ys = ys-merge _   xs [] = xs-merge cmp (x:xs) (y:ys)- = case x `cmp` y of-        GT -> y : merge cmp (x:xs)   ys-        _  -> x : merge cmp    xs (y:ys)--wrap :: a -> [a]-wrap x = [x]----OLDER: qsort version---- qsort is stable and does not concatenate.-qsort :: (a -> a -> Ordering) -> [a] -> [a] -> [a]-qsort _   []     r = r-qsort _   [x]    r = x:r-qsort cmp (x:xs) r = qpart cmp x xs [] [] r---- qpart partitions and sorts the sublists-qpart :: (a -> a -> Ordering) -> a -> [a] -> [a] -> [a] -> [a] -> [a]-qpart cmp x [] rlt rge r =-    -- rlt and rge are in reverse order and must be sorted with an-    -- anti-stable sorting-    rqsort cmp rlt (x:rqsort cmp rge r)-qpart cmp x (y:ys) rlt rge r =-    case cmp x y of-        GT -> qpart cmp x ys (y:rlt) rge r-        _  -> qpart cmp x ys rlt (y:rge) r---- rqsort is as qsort but anti-stable, i.e. reverses equal elements-rqsort :: (a -> a -> Ordering) -> [a] -> [a] -> [a]-rqsort _   []     r = r-rqsort _   [x]    r = x:r-rqsort cmp (x:xs) r = rqpart cmp x xs [] [] r--rqpart :: (a -> a -> Ordering) -> a -> [a] -> [a] -> [a] -> [a] -> [a]-rqpart cmp x [] rle rgt r =-    qsort cmp rle (x:qsort cmp rgt r)-rqpart cmp x (y:ys) rle rgt r =-    case cmp y x of-        GT -> rqpart cmp x ys rle (y:rgt) r-        _  -> rqpart cmp x ys (y:rle) rgt r--}--#endif /* USE_REPORT_PRELUDE */---- | Sort a list by comparing the results of a key function applied to each--- element.  @sortOn f@ is equivalent to @sortBy . comparing f@, but has the--- performance advantage of only evaluating @f@ once for each element in the--- input list.  This is called the decorate-sort-undecorate paradigm, or--- Schwartzian transform.------ @since 4.8.0.0-sortOn :: Ord b => (a -> b) -> [a] -> [a]-sortOn f =-  map snd . sortBy (comparing fst) . map (\x -> let y = f x in y `seq` (y, x))---- | The 'unfoldr' function is a \`dual\' to 'foldr': while 'foldr'--- reduces a list to a summary value, 'unfoldr' builds a list from--- a seed value.  The function takes the element and returns 'Nothing'--- if it is done producing the list or returns 'Just' @(a,b)@, in which--- case, @a@ is a prepended to the list and @b@ is used as the next--- element in a recursive call.  For example,------ > iterate f == unfoldr (\x -> Just (x, f x))------ In some cases, 'unfoldr' can undo a 'foldr' operation:------ > unfoldr f' (foldr f z xs) == xs------ if the following holds:------ > f' (f x y) = Just (x,y)--- > f' z       = Nothing------ A simple use of unfoldr:------ > unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10--- >  [10,9,8,7,6,5,4,3,2,1]------- Note [INLINE unfoldr]--- We treat unfoldr a little differently from some other forms for list fusion--- for two reasons:------ 1. We don't want to use a rule to rewrite a basic form to a fusible--- form because this would inline before constant floating. As Simon Peyton---- Jones and others have pointed out, this could reduce sharing in some cases--- where sharing is beneficial. Thus we simply INLINE it, which is, for--- example, how enumFromTo::Int becomes eftInt. Unfortunately, we don't seem--- to get enough of an inlining discount to get a version of eftInt based on--- unfoldr to inline as readily as the usual one. We know that all the Maybe--- nonsense will go away, but the compiler does not.------ 2. The benefit of inlining unfoldr is likely to be huge in many common cases,--- even apart from list fusion. In particular, inlining unfoldr often--- allows GHC to erase all the Maybes. This appears to be critical if unfoldr--- is to be used in high-performance code. A small increase in code size--- in the relatively rare cases when this does not happen looks like a very--- small price to pay.------ Doing a back-and-forth dance doesn't seem to accomplish anything if the--- final form has to be inlined in any case.--unfoldr :: (b -> Maybe (a, b)) -> b -> [a]--{-# INLINE unfoldr #-} -- See Note [INLINE unfoldr]-unfoldr f b0 = build (\c n ->-  let go b = case f b of-               Just (a, new_b) -> a `c` go new_b-               Nothing         -> n-  in go b0)---- -------------------------------------------------------------------------------- Functions on strings---- | 'lines' breaks a string up into a list of strings at newline--- characters.  The resulting strings do not contain newlines.-lines                   :: String -> [String]-lines ""                =  []--- Somehow GHC doesn't detect the selector thunks in the below code,--- so s' keeps a reference to the first line via the pair and we have--- a space leak (cf. #4334).--- So we need to make GHC see the selector thunks with a trick.-lines s                 =  cons (case break (== '\n') s of-                                    (l, s') -> (l, case s' of-                                                    []      -> []-                                                    _:s''   -> lines s''))-  where-    cons ~(h, t)        =  h : t---- | 'unlines' is an inverse operation to 'lines'.--- It joins lines, after appending a terminating newline to each.-unlines                 :: [String] -> String-#ifdef USE_REPORT_PRELUDE-unlines                 =  concatMap (++ "\n")-#else--- HBC version (stolen)--- here's a more efficient version-unlines [] = []-unlines (l:ls) = l ++ '\n' : unlines ls-#endif---- | 'words' breaks a string up into a list of words, which were delimited--- by white space.-words                   :: String -> [String]-{-# NOINLINE [1] words #-}-words s                 =  case dropWhile {-partain:Char.-}isSpace s of-                                "" -> []-                                s' -> w : words s''-                                      where (w, s'') =-                                             break {-partain:Char.-}isSpace s'--{-# RULES-"words" [~1] forall s . words s = build (\c n -> wordsFB c n s)-"wordsList" [1] wordsFB (:) [] = words- #-}-wordsFB :: ([Char] -> b -> b) -> b -> String -> b-{-# NOINLINE [0] wordsFB #-}-wordsFB c n = go-  where-    go s = case dropWhile isSpace s of-             "" -> n-             s' -> w `c` go s''-                   where (w, s'') = break isSpace s'---- | 'unwords' is an inverse operation to 'words'.--- It joins words with separating spaces.-unwords                 :: [String] -> String-#ifdef USE_REPORT_PRELUDE-unwords []              =  ""-unwords ws              =  foldr1 (\w s -> w ++ ' ':s) ws-#else--- Here's a lazier version that can get the last element of a--- _|_-terminated list.-{-# NOINLINE [1] unwords #-}-unwords []              =  ""-unwords (w:ws)          = w ++ go ws-  where-    go []     = ""-    go (v:vs) = ' ' : (v ++ go vs)---- In general, the foldr-based version is probably slightly worse--- than the HBC version, because it adds an extra space and then takes--- it back off again. But when it fuses, it reduces allocation. How much--- depends entirely on the average word length--it's most effective when--- the words are on the short side.-{-# RULES-"unwords" [~1] forall ws .-   unwords ws = tailUnwords (foldr unwordsFB "" ws)-"unwordsList" [1] forall ws .-   tailUnwords (foldr unwordsFB "" ws) = unwords ws- #-}--{-# INLINE [0] tailUnwords #-}-tailUnwords           :: String -> String-tailUnwords []        = []-tailUnwords (_:xs)    = xs--{-# INLINE [0] unwordsFB #-}-unwordsFB               :: String -> String -> String-unwordsFB w r           = ' ' : w ++ r-#endif--{- A "SnocBuilder" is a version of Chris Okasaki's banker's queue that supports-toListSB instead of uncons. In single-threaded use, its performance-characteristics are similar to John Hughes's functional difference lists, but-likely somewhat worse. In heavily persistent settings, however, it does much-better, because it takes advantage of sharing. The banker's queue guarantees-(amortized) O(1) snoc and O(1) uncons, meaning that we can think of toListSB as-an O(1) conversion to a list-like structure a constant factor slower than-normal lists--we pay the O(n) cost incrementally as we consume the list. Using-functional difference lists, on the other hand, we would have to pay the whole-cost up front for each output list. -}--{- We store a front list, a rear list, and the length of the queue.  Because we-only snoc onto the queue and never uncons, we know it's time to rotate when the-length of the queue plus 1 is a power of 2. Note that we rely on the value of-the length field only for performance.  In the unlikely event of overflow, the-performance will suffer but the semantics will remain correct.  -}--data SnocBuilder a = SnocBuilder {-# UNPACK #-} !Word [a] [a]--{- Smart constructor that rotates the builder when lp is one minus a power of-2. Does not rotate very small builders because doing so is not worth the-trouble. The lp < 255 test goes first because the power-of-2 test gives awful-branch prediction for very small n (there are 5 powers of 2 between 1 and-16). Putting the well-predicted lp < 255 test first avoids branching on the-power-of-2 test until powers of 2 have become sufficiently rare to be predicted-well. -}--{-# INLINE sb #-}-sb :: Word -> [a] -> [a] -> SnocBuilder a-sb lp f r-  | lp < 255 || (lp .&. (lp + 1)) /= 0 = SnocBuilder lp f r-  | otherwise                          = SnocBuilder lp (f ++ reverse r) []---- The empty builder--emptySB :: SnocBuilder a-emptySB = SnocBuilder 0 [] []---- Add an element to the end of a queue.--snocSB :: SnocBuilder a -> a -> SnocBuilder a-snocSB (SnocBuilder lp f r) x = sb (lp + 1) f (x:r)---- Convert a builder to a list--toListSB :: SnocBuilder a -> [a]-toListSB (SnocBuilder _ f r) = f ++ reverse r
− Data/Ord.hs
@@ -1,52 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Ord--- Copyright   :  (c) The University of Glasgow 2005--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ Orderings-----------------------------------------------------------------------------------module Data.Ord (-   Ord(..),-   Ordering(..),-   Down(..),-   comparing,- ) where--import GHC.Base-import GHC.Show-import GHC.Read---- | --- > comparing p x y = compare (p x) (p y)------ Useful combinator for use in conjunction with the @xxxBy@ family--- of functions from "Data.List", for example:------ >   ... sortBy (comparing fst) ...-comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering-comparing p x y = compare (p x) (p y)---- | The 'Down' type allows you to reverse sort order conveniently.  A value of type--- @'Down' a@ contains a value of type @a@ (represented as @'Down' a@).--- If @a@ has an @'Ord'@ instance associated with it then comparing two--- values thus wrapped will give you the opposite of their normal sort order.--- This is particularly useful when sorting in generalised list comprehensions,--- as in: @then sortWith by 'Down' x@------ Provides 'Show' and 'Read' instances (/since: 4.7.0.0/).------ @since 4.6.0.0-newtype Down a = Down a deriving (Eq, Show, Read)--instance Ord a => Ord (Down a) where-    compare (Down x) (Down y) = y `compare` x
− Data/Proxy.hs
@@ -1,104 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE PolyKinds #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Proxy--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Definition of a Proxy type (poly-kinded in GHC)------ @since 4.7.0.0--------------------------------------------------------------------------------module Data.Proxy-  (-        Proxy(..), asProxyTypeOf-      , KProxy(..)-  ) where--import GHC.Base-import GHC.Show-import GHC.Read-import GHC.Enum-import GHC.Arr---- | A concrete, poly-kinded proxy type-data Proxy t = Proxy---- | A concrete, promotable proxy type, for use at the kind level--- There are no instances for this because it is intended at the kind level only-data KProxy (t :: *) = KProxy---- It's common to use (undefined :: Proxy t) and (Proxy :: Proxy t)--- interchangeably, so all of these instances are hand-written to be--- lazy in Proxy arguments.--instance Eq (Proxy s) where-  _ == _ = True--instance Ord (Proxy s) where-  compare _ _ = EQ--instance Show (Proxy s) where-  showsPrec _ _ = showString "Proxy"--instance Read (Proxy s) where-  readsPrec d = readParen (d > 10) (\r -> [(Proxy, s) | ("Proxy",s) <- lex r ])--instance Enum (Proxy s) where-    succ _               = error "Proxy.succ"-    pred _               = error "Proxy.pred"-    fromEnum _           = 0-    toEnum 0             = Proxy-    toEnum _             = error "Proxy.toEnum: 0 expected"-    enumFrom _           = [Proxy]-    enumFromThen _ _     = [Proxy]-    enumFromThenTo _ _ _ = [Proxy]-    enumFromTo _ _       = [Proxy]--instance Ix (Proxy s) where-    range _           = [Proxy]-    index _ _         = 0-    inRange _ _       = True-    rangeSize _       = 1-    unsafeIndex _ _   = 0-    unsafeRangeSize _ = 1--instance Bounded (Proxy s) where-    minBound = Proxy-    maxBound = Proxy--instance Monoid (Proxy s) where-    mempty = Proxy-    mappend _ _ = Proxy-    mconcat _ = Proxy--instance Functor Proxy where-    fmap _ _ = Proxy-    {-# INLINE fmap #-}--instance Applicative Proxy where-    pure _ = Proxy-    {-# INLINE pure #-}-    _ <*> _ = Proxy-    {-# INLINE (<*>) #-}--instance Monad Proxy where-    return _ = Proxy-    {-# INLINE return #-}-    _ >>= _ = Proxy-    {-# INLINE (>>=) #-}---- | 'asProxyTypeOf' is a type-restricted version of 'const'.--- It is usually used as an infix operator, and its typing forces its first--- argument (which is usually overloaded) to have the same type as the tag--- of the second.-asProxyTypeOf :: a -> Proxy a -> a-asProxyTypeOf = const-{-# INLINE asProxyTypeOf #-}
− Data/Ratio.hs
@@ -1,73 +0,0 @@-{-# LANGUAGE Safe #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Ratio--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ Standard functions on rational numbers-----------------------------------------------------------------------------------module Data.Ratio-    ( Ratio-    , Rational-    , (%)-    , numerator-    , denominator-    , approxRational--  ) where--import GHC.Real         -- The basic defns for Ratio---- -------------------------------------------------------------------------------- approxRational---- | 'approxRational', applied to two real fractional numbers @x@ and @epsilon@,--- returns the simplest rational number within @epsilon@ of @x@.--- A rational number @y@ is said to be /simpler/ than another @y'@ if------ * @'abs' ('numerator' y) <= 'abs' ('numerator' y')@, and------ * @'denominator' y <= 'denominator' y'@.------ Any real interval contains a unique simplest rational;--- in particular, note that @0\/1@ is the simplest rational of all.---- Implementation details: Here, for simplicity, we assume a closed rational--- interval.  If such an interval includes at least one whole number, then--- the simplest rational is the absolutely least whole number.  Otherwise,--- the bounds are of the form q%1 + r%d and q%1 + r'%d', where abs r < d--- and abs r' < d', and the simplest rational is q%1 + the reciprocal of--- the simplest rational between d'%r' and d%r.--approxRational          :: (RealFrac a) => a -> a -> Rational-approxRational rat eps  =  simplest (rat-eps) (rat+eps)-        where simplest x y | y < x      =  simplest y x-                           | x == y     =  xr-                           | x > 0      =  simplest' n d n' d'-                           | y < 0      =  - simplest' (-n') d' (-n) d-                           | otherwise  =  0 :% 1-                                        where xr  = toRational x-                                              n   = numerator xr-                                              d   = denominator xr-                                              nd' = toRational y-                                              n'  = numerator nd'-                                              d'  = denominator nd'--              simplest' n d n' d'       -- assumes 0 < n%d < n'%d'-                        | r == 0     =  q :% 1-                        | q /= q'    =  (q+1) :% 1-                        | otherwise  =  (q*n''+d'') :% n''-                                     where (q,r)      =  quotRem n d-                                           (q',r')    =  quotRem n' d'-                                           nd''       =  simplest' d' r' d r-                                           n''        =  numerator nd''-                                           d''        =  denominator nd''-
− Data/STRef.hs
@@ -1,54 +0,0 @@-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  Data.STRef--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (uses Control.Monad.ST)------ Mutable references in the (strict) ST monad.-----------------------------------------------------------------------------------module Data.STRef (-        -- * STRefs-        STRef,          -- abstract-        newSTRef,-        readSTRef,-        writeSTRef,-        modifySTRef,-        modifySTRef'- ) where--import GHC.ST-import GHC.STRef---- | Mutate the contents of an 'STRef'.------ Be warned that 'modifySTRef' does not apply the function strictly.  This--- means if the program calls 'modifySTRef' many times, but seldomly uses the--- value, thunks will pile up in memory resulting in a space leak.  This is a--- common mistake made when using an STRef as a counter.  For example, the--- following will leak memory and likely produce a stack overflow:------ >print $ runST $ do--- >    ref <- newSTRef 0--- >    replicateM_ 1000000 $ modifySTRef ref (+1)--- >    readSTRef ref------ To avoid this problem, use 'modifySTRef'' instead.-modifySTRef :: STRef s a -> (a -> a) -> ST s ()-modifySTRef ref f = writeSTRef ref . f =<< readSTRef ref---- | Strict version of 'modifySTRef'------ @since 4.6.0.0-modifySTRef' :: STRef s a -> (a -> a) -> ST s ()-modifySTRef' ref f = do-    x <- readSTRef ref-    let x' = f x-    x' `seq` writeSTRef ref x'
− Data/STRef/Lazy.hs
@@ -1,38 +0,0 @@-{-# LANGUAGE Safe #-}---------------------------------------------------------------------------------- |--- Module      :  Data.STRef.Lazy--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (uses Control.Monad.ST.Lazy)------ Mutable references in the lazy ST monad.-----------------------------------------------------------------------------------module Data.STRef.Lazy (-        -- * STRefs-        ST.STRef,       -- abstract-        newSTRef,-        readSTRef,-        writeSTRef,-        modifySTRef- ) where--import Control.Monad.ST.Lazy-import qualified Data.STRef as ST--newSTRef    :: a -> ST s (ST.STRef s a)-readSTRef   :: ST.STRef s a -> ST s a-writeSTRef  :: ST.STRef s a -> a -> ST s ()-modifySTRef :: ST.STRef s a -> (a -> a) -> ST s ()--newSTRef        = strictToLazyST . ST.newSTRef-readSTRef       = strictToLazyST . ST.readSTRef-writeSTRef  r a = strictToLazyST (ST.writeSTRef r a)-modifySTRef r f = strictToLazyST (ST.modifySTRef r f)-
− Data/STRef/Strict.hs
@@ -1,22 +0,0 @@-{-# LANGUAGE Safe #-}---------------------------------------------------------------------------------- |--- Module      :  Data.STRef.Strict--- 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 (uses Control.Monad.ST.Strict)------ Mutable references in the (strict) ST monad (re-export of "Data.STRef")-----------------------------------------------------------------------------------module Data.STRef.Strict (-        module Data.STRef-  ) where--import Data.STRef-
− Data/String.hs
@@ -1,39 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, FlexibleInstances #-}---------------------------------------------------------------------------------- |--- Module      :  Data.String--- Copyright   :  (c) The University of Glasgow 2007--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ The @String@ type and associated operations.-----------------------------------------------------------------------------------module Data.String (-   String- , IsString(..)-- -- * Functions on strings- , lines- , words- , unlines- , unwords- ) where--import GHC.Base-import Data.List (lines, words, unlines, unwords)---- | Class for string-like datastructures; used by the overloaded string---   extension (-XOverloadedStrings in GHC).-class IsString a where-    fromString :: String -> a--instance IsString [Char] where-    fromString xs = xs-
− Data/Traversable.hs
@@ -1,284 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Traversable--- Copyright   :  Conor McBride and Ross Paterson 2005--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Class of data structures that can be traversed from left to right,--- performing an action on each element.------ See also------  * \"Applicative Programming with Effects\",---    by Conor McBride and Ross Paterson,---    /Journal of Functional Programming/ 18:1 (2008) 1-13, online at---    <http://www.soi.city.ac.uk/~ross/papers/Applicative.html>.------  * \"The Essence of the Iterator Pattern\",---    by Jeremy Gibbons and Bruno Oliveira,---    in /Mathematically-Structured Functional Programming/, 2006, online at---    <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>.------  * \"An Investigation of the Laws of Traversals\",---    by Mauro Jaskelioff and Ondrej Rypacek,---    in /Mathematically-Structured Functional Programming/, 2012, online at---    <http://arxiv.org/pdf/1202.2919>.-----------------------------------------------------------------------------------module Data.Traversable (-    -- * The 'Traversable' class-    Traversable(..),-    -- * Utility functions-    for,-    forM,-    mapAccumL,-    mapAccumR,-    -- * General definitions for superclass methods-    fmapDefault,-    foldMapDefault,-    ) where--import Control.Applicative ( Const(..) )-import Data.Either ( Either(..) )-import Data.Foldable ( Foldable )-import Data.Functor-import Data.Proxy ( Proxy(..) )--import GHC.Arr-import GHC.Base ( Applicative(..), Monad(..), Monoid, Maybe(..),-                  ($), (.), id, flip )-import qualified GHC.Base as Monad ( mapM )-import qualified GHC.List as List ( foldr )---- | Functors representing data structures that can be traversed from--- left to right.------ A definition of 'traverse' must satisfy the following laws:------ [/naturality/]---   @t . 'traverse' f = 'traverse' (t . f)@---   for every applicative transformation @t@------ [/identity/]---   @'traverse' Identity = Identity@------ [/composition/]---   @'traverse' (Compose . 'fmap' g . f) = Compose . 'fmap' ('traverse' g) . 'traverse' f@------ A definition of 'sequenceA' must satisfy the following laws:------ [/naturality/]---   @t . 'sequenceA' = 'sequenceA' . 'fmap' t@---   for every applicative transformation @t@------ [/identity/]---   @'sequenceA' . 'fmap' Identity = Identity@------ [/composition/]---   @'sequenceA' . 'fmap' Compose = Compose . 'fmap' 'sequenceA' . 'sequenceA'@------ where an /applicative transformation/ is a function------ @t :: (Applicative f, Applicative g) => f a -> g a@------ preserving the 'Applicative' operations, i.e.------  * @t ('pure' x) = 'pure' x@------  * @t (x '<*>' y) = t x '<*>' t y@------ and the identity functor @Identity@ and composition of functors @Compose@--- are defined as------ >   newtype Identity a = Identity a--- >--- >   instance Functor Identity where--- >     fmap f (Identity x) = Identity (f x)--- >--- >   instance Applicative Indentity where--- >     pure x = Identity x--- >     Identity f <*> Identity x = Identity (f x)--- >--- >   newtype Compose f g a = Compose (f (g a))--- >--- >   instance (Functor f, Functor g) => Functor (Compose f g) where--- >     fmap f (Compose x) = Compose (fmap (fmap f) x)--- >--- >   instance (Applicative f, Applicative g) => Applicative (Compose f g) where--- >     pure x = Compose (pure (pure x))--- >     Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)------ (The naturality law is implied by parametricity.)------ Instances are similar to 'Functor', e.g. given a data type------ > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)------ a suitable instance would be------ > instance Traversable Tree where--- >    traverse f Empty = pure Empty--- >    traverse f (Leaf x) = Leaf <$> f x--- >    traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r------ This is suitable even for abstract types, as the laws for '<*>'--- imply a form of associativity.------ The superclass instances should satisfy the following:------  * In the 'Functor' instance, 'fmap' should be equivalent to traversal---    with the identity applicative functor ('fmapDefault').------  * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be---    equivalent to traversal with a constant applicative functor---    ('foldMapDefault').----class (Functor t, Foldable t) => Traversable t where-    {-# MINIMAL traverse | sequenceA #-}--    -- | Map each element of a structure to an action, evaluate these actions-    -- from left to right, and collect the results. For a version that ignores-    -- the results see 'Data.Foldable.traverse_'.-    traverse :: Applicative f => (a -> f b) -> t a -> f (t b)-    traverse f = sequenceA . fmap f--    -- | Evaluate each action in the structure from left to right, and-    -- and collect the results. For a version that ignores the results-    -- see 'Data.Foldable.sequenceA_'.-    sequenceA :: Applicative f => t (f a) -> f (t a)-    sequenceA = traverse id--    -- | Map each element of a structure to a monadic action, evaluate-    -- these actions from left to right, and collect the results. For-    -- a version that ignores the results see 'Data.Foldable.mapM_'.-    mapM :: Monad m => (a -> m b) -> t a -> m (t b)-    mapM = traverse--    -- | Evaluate each monadic action in the structure from left to-    -- right, and collect the results. For a version that ignores the-    -- results see 'Data.Foldable.sequence_'.-    sequence :: Monad m => t (m a) -> m (t a)-    sequence = sequenceA---- instances for Prelude types--instance Traversable Maybe where-    traverse _ Nothing = pure Nothing-    traverse f (Just x) = Just <$> f x--instance Traversable [] where-    {-# INLINE traverse #-} -- so that traverse can fuse-    traverse f = List.foldr cons_f (pure [])-      where cons_f x ys = (:) <$> f x <*> ys--    mapM = Monad.mapM--instance Traversable (Either a) where-    traverse _ (Left x) = pure (Left x)-    traverse f (Right y) = Right <$> f y--instance Traversable ((,) a) where-    traverse f (x, y) = (,) x <$> f y--instance Ix i => Traversable (Array i) where-    traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr)--instance Traversable Proxy where-    traverse _ _ = pure Proxy-    {-# INLINE traverse #-}-    sequenceA _ = pure Proxy-    {-# INLINE sequenceA #-}-    mapM _ _ = return Proxy-    {-# INLINE mapM #-}-    sequence _ = return Proxy-    {-# INLINE sequence #-}--instance Traversable (Const m) where-    traverse _ (Const m) = pure $ Const m---- general functions---- | 'for' is 'traverse' with its arguments flipped. For a version--- that ignores the results see 'Data.Foldable.for_'.-for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)-{-# INLINE for #-}-for = flip traverse---- | 'forM' is 'mapM' with its arguments flipped. For a version that--- ignores the results see 'Data.Foldable.forM_'.-forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)-{-# INLINE forM #-}-forM = flip mapM---- left-to-right state transformer-newtype StateL s a = StateL { runStateL :: s -> (s, a) }--instance Functor (StateL s) where-    fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)--instance Applicative (StateL s) where-    pure x = StateL (\ s -> (s, x))-    StateL kf <*> StateL kv = StateL $ \ s ->-        let (s', f) = kf s-            (s'', v) = kv s'-        in (s'', f v)---- |The 'mapAccumL' function behaves like a combination of 'fmap'--- and 'foldl'; it applies a function to each element of a structure,--- passing an accumulating parameter from left to right, and returning--- a final value of this accumulator together with the new structure.-mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)-mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s---- right-to-left state transformer-newtype StateR s a = StateR { runStateR :: s -> (s, a) }--instance Functor (StateR s) where-    fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)--instance Applicative (StateR s) where-    pure x = StateR (\ s -> (s, x))-    StateR kf <*> StateR kv = StateR $ \ s ->-        let (s', v) = kv s-            (s'', f) = kf s'-        in (s'', f v)---- |The 'mapAccumR' function behaves like a combination of 'fmap'--- and 'foldr'; it applies a function to each element of a structure,--- passing an accumulating parameter from right to left, and returning--- a final value of this accumulator together with the new structure.-mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)-mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s---- | This function may be used as a value for `fmap` in a `Functor`---   instance, provided that 'traverse' is defined. (Using---   `fmapDefault` with a `Traversable` instance defined only by---   'sequenceA' will result in infinite recursion.)-fmapDefault :: Traversable t => (a -> b) -> t a -> t b-{-# INLINE fmapDefault #-}-fmapDefault f = getId . traverse (Id . f)---- | This function may be used as a value for `Data.Foldable.foldMap`--- in a `Foldable` instance.-foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m-foldMapDefault f = getConst . traverse (Const . f)---- local instances--newtype Id a = Id { getId :: a }--instance Functor Id where-    fmap f (Id x) = Id (f x)--instance Applicative Id where-    pure = Id-    Id f <*> Id x = Id (f x)-
− Data/Tuple.hs
@@ -1,51 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Tuple--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ The tuple data types, and associated functions.-----------------------------------------------------------------------------------module Data.Tuple-  ( fst-  , snd-  , curry-  , uncurry-  , swap-  ) where--import GHC.Base ()      -- Note [Depend on GHC.Tuple]--default ()              -- Double isn't available yet---- ------------------------------------------------------------------------------ Standard functions over tuples---- | Extract the first component of a pair.-fst                     :: (a,b) -> a-fst (x,_)               =  x---- | Extract the second component of a pair.-snd                     :: (a,b) -> b-snd (_,y)               =  y---- | 'curry' converts an uncurried function to a curried function.-curry                   :: ((a, b) -> c) -> a -> b -> c-curry f x y             =  f (x, y)---- | 'uncurry' converts a curried function to a function on pairs.-uncurry                 :: (a -> b -> c) -> ((a, b) -> c)-uncurry f p             =  f (fst p) (snd p)---- | Swap the components of a pair.-swap                    :: (a,b) -> (b,a)-swap (a,b)              = (b,a)
− Data/Type/Bool.hs
@@ -1,55 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds, NoImplicitPrelude,-             PolyKinds #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Type.Bool--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  not portable------ Basic operations on type-level Booleans.------ @since 4.7.0.0--------------------------------------------------------------------------------module Data.Type.Bool (-  If, type (&&), type (||), Not-  ) where--import Data.Bool---- This needs to be in base because (&&) is used in Data.Type.Equality.--- The other functions do not need to be in base, but seemed to be appropriate--- here.---- | Type-level "If". @If True a b@ ==> @a@; @If False a b@ ==> @b@-type family If cond tru fls where-  If 'True  tru fls = tru-  If 'False tru fls = fls---- | Type-level "and"-type family a && b where-  'False && a      = 'False-  'True  && a      = a-  a      && 'False = 'False-  a      && 'True  = a-  a      && a      = a-infixr 3 &&---- | Type-level "or"-type family a || b where-  'False || a      = a-  'True  || a      = 'True-  a      || 'False = a-  a      || 'True  = 'True-  a      || a      = a-infixr 2 ||---- | Type-level "not"-type family Not a where-  Not 'False = 'True-  Not 'True  = 'False
− Data/Type/Coercion.hs
@@ -1,101 +0,0 @@-{-# LANGUAGE DeriveGeneric       #-}-{-# LANGUAGE TypeOperators       #-}-{-# LANGUAGE TypeFamilies        #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE GADTs               #-}-{-# LANGUAGE FlexibleInstances   #-}-{-# LANGUAGE StandaloneDeriving  #-}-{-# LANGUAGE NoImplicitPrelude   #-}-{-# LANGUAGE PolyKinds           #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Type.Coercion--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  not portable------ Definition of representational equality ('Coercion').------ @since 4.7.0.0--------------------------------------------------------------------------------module Data.Type.Coercion-  ( Coercion(..)-  , coerceWith-  , sym-  , trans-  , repr-  , TestCoercion(..)-  ) where--import qualified Data.Type.Equality as Eq-import Data.Maybe-import GHC.Enum-import GHC.Show-import GHC.Read-import GHC.Base---- | Representational equality. If @Coercion a b@ is inhabited by some terminating--- value, then the type @a@ has the same underlying representation as the type @b@.------ To use this equality in practice, pattern-match on the @Coercion a b@ to get out--- the @Coercible a b@ instance, and then use 'coerce' to apply it.------ @since 4.7.0.0-data Coercion a b where-  Coercion :: Coercible a b => Coercion a b---- with credit to Conal Elliott for 'ty', Erik Hesselink & Martijn van--- Steenbergen for 'type-equality', Edward Kmett for 'eq', and Gabor Greif--- for 'type-eq'--newtype Sym a b = Sym { unsym :: Coercion b a }---- | Type-safe cast, using representational equality-coerceWith :: Coercion a b -> a -> b-coerceWith Coercion x = coerce x---- | Symmetry of representational equality-sym :: forall a b. Coercion a b -> Coercion b a-sym Coercion = unsym (coerce (Sym Coercion :: Sym a a))---- | Transitivity of representational equality-trans :: Coercion a b -> Coercion b c -> Coercion a c-trans c Coercion = coerce c---- | Convert propositional (nominal) equality to representational equality-repr :: (a Eq.:~: b) -> Coercion a b-repr Eq.Refl = Coercion--deriving instance Eq   (Coercion a b)-deriving instance Show (Coercion a b)-deriving instance Ord  (Coercion a b)--instance Coercible a b => Read (Coercion a b) where-  readsPrec d = readParen (d > 10) (\r -> [(Coercion, s) | ("Coercion",s) <- lex r ])--instance Coercible a b => Enum (Coercion a b) where-  toEnum 0 = Coercion-  toEnum _ = error "Data.Type.Coercion.toEnum: bad argument"--  fromEnum Coercion = 0--instance Coercible a b => Bounded (Coercion a b) where-  minBound = Coercion-  maxBound = Coercion---- | This class contains types where you can learn the equality of two types--- from information contained in /terms/. Typically, only singleton types should--- inhabit this class.-class TestCoercion f where-  -- | Conditionally prove the representational equality of @a@ and @b@.-  testCoercion :: f a -> f b -> Maybe (Coercion a b)--instance TestCoercion ((Eq.:~:) a) where-  testCoercion Eq.Refl Eq.Refl = Just Coercion--instance TestCoercion (Coercion a) where-  testCoercion c Coercion = Just $ coerce (sym c)
− Data/Type/Equality.hs
@@ -1,282 +0,0 @@-{-# LANGUAGE DeriveGeneric        #-}-{-# LANGUAGE TypeOperators        #-}-{-# LANGUAGE GADTs                #-}-{-# LANGUAGE FlexibleInstances    #-}-{-# LANGUAGE StandaloneDeriving   #-}-{-# LANGUAGE NoImplicitPrelude    #-}-{-# LANGUAGE PolyKinds            #-}-{-# LANGUAGE RankNTypes           #-}-{-# LANGUAGE DataKinds            #-}-{-# LANGUAGE TypeFamilies         #-}-{-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE ExplicitNamespaces   #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Type.Equality--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  not portable------ Definition of propositional equality @(:~:)@. Pattern-matching on a variable--- of type @(a :~: b)@ produces a proof that @a ~ b@.------ @since 4.7.0.0----------------------------------------------------------------------------------module Data.Type.Equality (-  -- * The equality type-  (:~:)(..),-  -  -- * Working with equality-  sym, trans, castWith, gcastWith, apply, inner, outer,--  -- * Inferring equality from other types-  TestEquality(..),--  -- * Boolean type-level equality-  type (==)-  ) where--import Data.Maybe-import GHC.Enum-import GHC.Show-import GHC.Read-import GHC.Base-import Data.Type.Bool--infix 4 :~:---- | Propositional equality. If @a :~: b@ is inhabited by some terminating--- value, then the type @a@ is the same as the type @b@. To use this equality--- in practice, pattern-match on the @a :~: b@ to get out the @Refl@ constructor;--- in the body of the pattern-match, the compiler knows that @a ~ b@.------ @since 4.7.0.0-data a :~: b where-  Refl :: a :~: a---- with credit to Conal Elliott for 'ty', Erik Hesselink & Martijn van--- Steenbergen for 'type-equality', Edward Kmett for 'eq', and Gabor Greif--- for 'type-eq'---- | Symmetry of equality-sym :: (a :~: b) -> (b :~: a)-sym Refl = Refl---- | Transitivity of equality-trans :: (a :~: b) -> (b :~: c) -> (a :~: c)-trans Refl Refl = Refl---- | Type-safe cast, using propositional equality-castWith :: (a :~: b) -> a -> b-castWith Refl x = x---- | Generalized form of type-safe cast using propositional equality-gcastWith :: (a :~: b) -> ((a ~ b) => r) -> r-gcastWith Refl x = x---- | Apply one equality to another, respectively-apply :: (f :~: g) -> (a :~: b) -> (f a :~: g b)-apply Refl Refl = Refl---- | Extract equality of the arguments from an equality of a applied types-inner :: (f a :~: g b) -> (a :~: b)-inner Refl = Refl---- | Extract equality of type constructors from an equality of applied types-outer :: (f a :~: g b) -> (f :~: g)-outer Refl = Refl--deriving instance Eq   (a :~: b)-deriving instance Show (a :~: b)-deriving instance Ord  (a :~: b)--instance a ~ b => Read (a :~: b) where-  readsPrec d = readParen (d > 10) (\r -> [(Refl, s) | ("Refl",s) <- lex r ])--instance a ~ b => Enum (a :~: b) where-  toEnum 0 = Refl-  toEnum _ = error "Data.Type.Equality.toEnum: bad argument"--  fromEnum Refl = 0--instance a ~ b => Bounded (a :~: b) where-  minBound = Refl-  maxBound = Refl---- | This class contains types where you can learn the equality of two types--- from information contained in /terms/. Typically, only singleton types should--- inhabit this class.-class TestEquality f where-  -- | Conditionally prove the equality of @a@ and @b@.-  testEquality :: f a -> f b -> Maybe (a :~: b)--instance TestEquality ((:~:) a) where-  testEquality Refl Refl = Just Refl---- | A type family to compute Boolean equality. Instances are provided--- only for /open/ kinds, such as @*@ and function kinds. Instances are--- also provided for datatypes exported from base. A poly-kinded instance--- is /not/ provided, as a recursive definition for algebraic kinds is--- generally more useful.-type family (a :: k) == (b :: k) :: Bool-infix 4 ==--{--This comment explains more about why a poly-kinded instance for (==) is-not provided. To be concrete, here would be the poly-kinded instance:--type family EqPoly (a :: k) (b :: k) where- EqPoly a a = True- EqPoly a b = False-type instance (a :: k) == (b :: k) = EqPoly a b--Note that this overlaps with every other instance -- if this were defined,-it would be the only instance for (==).--Now, consider-data Nat = Zero | Succ Nat--Suppose I want-foo :: (Succ n == Succ m) ~ True => ((n == m) :~: True)-foo = Refl--This would not type-check with the poly-kinded instance. `Succ n == Succ m`-quickly becomes `EqPoly (Succ n) (Succ m)` but then is stuck. We don't know-enough about `n` and `m` to reduce further.--On the other hand, consider this:--type family EqNat (a :: Nat) (b :: Nat) where- EqNat Zero     Zero     = True- EqNat (Succ n) (Succ m) = EqNat n m- EqNat n        m        = False-type instance (a :: Nat) == (b :: Nat) = EqNat a b--With this instance, `foo` type-checks fine. `Succ n == Succ m` becomes `EqNat-(Succ n) (Succ m)` which becomes `EqNat n m`. Thus, we can conclude `(n == m)-~ True` as desired.--So, the Nat-specific instance allows strictly more reductions, and is thus-preferable to the poly-kinded instance. But, if we introduce the poly-kinded-instance, we are barred from writing the Nat-specific instance, due to-overlap.--Even better than the current instance for * would be one that does this sort-of recursion for all datatypes, something like this:--type family EqStar (a :: *) (b :: *) where- EqStar Bool Bool = True- EqStar (a,b) (c,d) = a == c && b == d- EqStar (Maybe a) (Maybe b) = a == b- ...- EqStar a b = False--The problem is the (...) is extensible -- we would want to add new cases for-all datatypes in scope. This is not currently possible for closed type-families.--}---- all of the following closed type families are local to this module-type family EqStar (a :: *) (b :: *) where-  EqStar a a = 'True-  EqStar a b = 'False---- This looks dangerous, but it isn't. This allows == to be defined--- over arbitrary type constructors.-type family EqArrow (a :: k1 -> k2) (b :: k1 -> k2) where-  EqArrow a a = 'True-  EqArrow a b = 'False--type family EqBool a b where-  EqBool 'True  'True  = 'True-  EqBool 'False 'False = 'True-  EqBool a     b       = 'False--type family EqOrdering a b where-  EqOrdering 'LT 'LT = 'True-  EqOrdering 'EQ 'EQ = 'True-  EqOrdering 'GT 'GT = 'True-  EqOrdering a  b    = 'False--type EqUnit (a :: ()) (b :: ()) = 'True--type family EqList a b where-  EqList '[]        '[]        = 'True-  EqList (h1 ': t1) (h2 ': t2) = (h1 == h2) && (t1 == t2)-  EqList a          b          = 'False--type family EqMaybe a b where-  EqMaybe 'Nothing   'Nothing  = 'True-  EqMaybe ('Just x) ('Just y)  = x == y-  EqMaybe a        b           = 'False--type family Eq2 a b where-  Eq2 '(a1, b1) '(a2, b2) = a1 == a2 && b1 == b2--type family Eq3 a b where-  Eq3 '(a1, b1, c1) '(a2, b2, c2) = a1 == a2 && b1 == b2 && c1 == c2--type family Eq4 a b where-  Eq4 '(a1, b1, c1, d1) '(a2, b2, c2, d2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2--type family Eq5 a b where-  Eq5 '(a1, b1, c1, d1, e1) '(a2, b2, c2, d2, e2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2--type family Eq6 a b where-  Eq6 '(a1, b1, c1, d1, e1, f1) '(a2, b2, c2, d2, e2, f2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2--type family Eq7 a b where-  Eq7 '(a1, b1, c1, d1, e1, f1, g1) '(a2, b2, c2, d2, e2, f2, g2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2--type family Eq8 a b where-  Eq8 '(a1, b1, c1, d1, e1, f1, g1, h1) '(a2, b2, c2, d2, e2, f2, g2, h2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2--type family Eq9 a b where-  Eq9 '(a1, b1, c1, d1, e1, f1, g1, h1, i1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2--type family Eq10 a b where-  Eq10 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2--type family Eq11 a b where-  Eq11 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2--type family Eq12 a b where-  Eq12 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2--type family Eq13 a b where-  Eq13 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2 && m1 == m2--type family Eq14 a b where-  Eq14 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2 && m1 == m2 && n1 == n2--type family Eq15 a b where-  Eq15 '(a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1, o1) '(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2) = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 && h1 == h2 && i1 == i2 && j1 == j2 && k1 == k2 && l1 == l2 && m1 == m2 && n1 == n2 && o1 == o2---- these all look to be overlapping, but they are differentiated by their kinds-type instance a == b = EqStar a b-type instance a == b = EqArrow a b-type instance a == b = EqBool a b-type instance a == b = EqOrdering a b-type instance a == b = EqUnit a b-type instance a == b = EqList a b-type instance a == b = EqMaybe a b-type instance a == b = Eq2 a b-type instance a == b = Eq3 a b-type instance a == b = Eq4 a b-type instance a == b = Eq5 a b-type instance a == b = Eq6 a b-type instance a == b = Eq7 a b-type instance a == b = Eq8 a b-type instance a == b = Eq9 a b-type instance a == b = Eq10 a b-type instance a == b = Eq11 a b-type instance a == b = Eq12 a b-type instance a == b = Eq13 a b-type instance a == b = Eq14 a b-type instance a == b = Eq15 a b
− Data/Typeable.hs
@@ -1,130 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE GADTs #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE PolyKinds #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE TypeOperators #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Typeable--- Copyright   :  (c) The University of Glasgow, CWI 2001--2004--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ The 'Typeable' class reifies types to some extent by associating type--- representations to types. These type representations can be compared,--- and one can in turn define a type-safe cast operation. To this end,--- an unsafe cast is guarded by a test for type (representation)--- equivalence. The module "Data.Dynamic" uses Typeable for an--- implementation of dynamics. The module "Data.Data" uses Typeable--- and type-safe cast (but not dynamics) to support the \"Scrap your--- boilerplate\" style of generic programming.------ == Compatibility Notes------ Since GHC 7.8, 'Typeable' is poly-kinded. The changes required for this might--- break some old programs involving 'Typeable'. More details on this, including--- how to fix your code, can be found on the--- <https://ghc.haskell.org/trac/ghc/wiki/GhcKinds/PolyTypeable PolyTypeable wiki page>-----------------------------------------------------------------------------------module Data.Typeable-  (-        -- * The Typeable class-        Typeable,-        typeRep,--        -- * Propositional equality-        (:~:)(Refl),--        -- * For backwards compatibility-        typeOf, typeOf1, typeOf2, typeOf3, typeOf4, typeOf5, typeOf6, typeOf7,-        Typeable1, Typeable2, Typeable3, Typeable4, Typeable5, Typeable6,-        Typeable7,--        -- * Type-safe cast-        cast,-        eqT,-        gcast,                  -- a generalisation of cast--        -- * Generalized casts for higher-order kinds-        gcast1,                 -- :: ... => c (t a) -> Maybe (c (t' a))-        gcast2,                 -- :: ... => c (t a b) -> Maybe (c (t' a b))--        -- * A canonical proxy type-        Proxy (..),-        -        -- * Type representations-        TypeRep,        -- abstract, instance of: Eq, Show, Typeable-        typeRepFingerprint,-        rnfTypeRep,-        showsTypeRep,--        TyCon,          -- abstract, instance of: Eq, Show, Typeable-        tyConFingerprint,-        tyConString,-        tyConPackage,-        tyConModule,-        tyConName,-        rnfTyCon,--        -- * Construction of type representations-        -- mkTyCon,        -- :: String  -> TyCon-        mkTyCon3,       -- :: String  -> String -> String -> TyCon-        mkTyConApp,     -- :: TyCon   -> [TypeRep] -> TypeRep-        mkAppTy,        -- :: TypeRep -> TypeRep   -> TypeRep-        mkFunTy,        -- :: TypeRep -> TypeRep   -> TypeRep--        -- * Observation of type representations-        splitTyConApp,  -- :: TypeRep -> (TyCon, [TypeRep])-        funResultTy,    -- :: TypeRep -> TypeRep   -> Maybe TypeRep-        typeRepTyCon,   -- :: TypeRep -> TyCon-        typeRepArgs,    -- :: TypeRep -> [TypeRep]-  ) where--import Data.Typeable.Internal hiding (mkTyCon)-import Data.Type.Equality--import Unsafe.Coerce-import Data.Maybe-import GHC.Base---------------------------------------------------------------------              Type-safe cast--------------------------------------------------------------------- | The type-safe cast operation-cast :: forall a b. (Typeable a, Typeable b) => a -> Maybe b-cast x = if typeRep (Proxy :: Proxy a) == typeRep (Proxy :: Proxy b)-           then Just $ unsafeCoerce x-           else Nothing---- | Extract a witness of equality of two types------ @since 4.7.0.0-eqT :: forall a b. (Typeable a, Typeable b) => Maybe (a :~: b)-eqT = if typeRep (Proxy :: Proxy a) == typeRep (Proxy :: Proxy b)-      then Just $ unsafeCoerce Refl-      else Nothing---- | A flexible variation parameterised in a type constructor-gcast :: forall a b c. (Typeable a, Typeable b) => c a -> Maybe (c b)-gcast x = fmap (\Refl -> x) (eqT :: Maybe (a :~: b))---- | Cast over @k1 -> k2@-gcast1 :: forall c t t' a. (Typeable t, Typeable t')-       => c (t a) -> Maybe (c (t' a)) -gcast1 x = fmap (\Refl -> x) (eqT :: Maybe (t :~: t'))---- | Cast over @k1 -> k2 -> k3@-gcast2 :: forall c t t' a b. (Typeable t, Typeable t')-       => c (t a b) -> Maybe (c (t' a b)) -gcast2 x = fmap (\Refl -> x) (eqT :: Maybe (t :~: t'))-
− Data/Typeable/Internal.hs
@@ -1,350 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE BangPatterns #-}-{-# LANGUAGE CPP #-}-{-# LANGUAGE ConstraintKinds #-}-{-# LANGUAGE DataKinds #-}-{-# LANGUAGE DeriveDataTypeable #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE MagicHash #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE PolyKinds #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE StandaloneDeriving #-}-{-# LANGUAGE UndecidableInstances #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Typeable.Internal--- Copyright   :  (c) The University of Glasgow, CWI 2001--2011--- License     :  BSD-style (see the file libraries/base/LICENSE)------ The representations of the types TyCon and TypeRep, and the--- function mkTyCon which is used by derived instances of Typeable to--- construct a TyCon.-----------------------------------------------------------------------------------module Data.Typeable.Internal (-    Proxy (..),-    TypeRep(..),-    KindRep,-    Fingerprint(..),-    typeOf, typeOf1, typeOf2, typeOf3, typeOf4, typeOf5, typeOf6, typeOf7,-    Typeable1, Typeable2, Typeable3, Typeable4, Typeable5, Typeable6, Typeable7,-    TyCon(..),-    typeRep,-    mkTyCon,-    mkTyCon3,-    mkTyConApp,-    mkPolyTyConApp,-    mkAppTy,-    typeRepTyCon,-    Typeable(..),-    mkFunTy,-    splitTyConApp,-    splitPolyTyConApp,-    funResultTy,-    typeRepArgs,-    typeRepFingerprint,-    rnfTypeRep,-    showsTypeRep,-    tyConString,-    rnfTyCon,-    listTc, funTc,-    typeRepKinds,-    typeLitTypeRep-  ) where--import GHC.Base-import GHC.Word-import GHC.Show-import Data.Proxy--import GHC.Fingerprint.Type-import {-# SOURCE #-} GHC.Fingerprint-   -- loop: GHC.Fingerprint -> Foreign.Ptr -> Data.Typeable-   -- Better to break the loop here, because we want non-SOURCE imports-   -- of Data.Typeable as much as possible so we can optimise the derived-   -- instances.---- | A concrete representation of a (monomorphic) type.  'TypeRep'--- supports reasonably efficient equality.-data TypeRep = TypeRep {-# UNPACK #-} !Fingerprint TyCon [KindRep] [TypeRep]--type KindRep = TypeRep---- Compare keys for equality-instance Eq TypeRep where-  TypeRep x _ _ _ == TypeRep y _ _ _ = x == y--instance Ord TypeRep where-  TypeRep x _ _ _ <= TypeRep y _ _ _ = x <= y----- | An abstract representation of a type constructor.  'TyCon' objects can--- be built using 'mkTyCon'.-data TyCon = TyCon {-   tyConFingerprint :: {-# UNPACK #-} !Fingerprint, -- ^ @since 4.8.0.0-   tyConPackage :: String, -- ^ @since 4.5.0.0-   tyConModule  :: String, -- ^ @since 4.5.0.0-   tyConName    :: String  -- ^ @since 4.5.0.0- }--instance Eq TyCon where-  (TyCon t1 _ _ _) == (TyCon t2 _ _ _) = t1 == t2--instance Ord TyCon where-  (TyCon k1 _ _ _) <= (TyCon k2 _ _ _) = k1 <= k2------------------- Construction ----------------------#include "MachDeps.h"---- mkTyCon is an internal function to make it easier for GHC to--- generate derived instances.  GHC precomputes the MD5 hash for the--- TyCon and passes it as two separate 64-bit values to mkTyCon.  The--- TyCon for a derived Typeable instance will end up being statically--- allocated.--#if WORD_SIZE_IN_BITS < 64-mkTyCon :: Word64# -> Word64# -> String -> String -> String -> TyCon-#else-mkTyCon :: Word#   -> Word#   -> String -> String -> String -> TyCon-#endif-mkTyCon high# low# pkg modl name-  = TyCon (Fingerprint (W64# high#) (W64# low#)) pkg modl name---- | Applies a polymorhic type constructor to a sequence of kinds and types-mkPolyTyConApp :: TyCon -> [KindRep] -> [TypeRep] -> TypeRep-mkPolyTyConApp tc@(TyCon tc_k _ _ _) [] [] = TypeRep tc_k tc [] []-mkPolyTyConApp tc@(TyCon tc_k _ _ _) kinds types =-  TypeRep (fingerprintFingerprints (tc_k : arg_ks)) tc kinds types-  where-  arg_ks = [ k | TypeRep k _ _ _ <- kinds ++ types ]---- | Applies a monomorphic type constructor to a sequence of types-mkTyConApp  :: TyCon -> [TypeRep] -> TypeRep-mkTyConApp tc = mkPolyTyConApp tc []---- | A special case of 'mkTyConApp', which applies the function--- type constructor to a pair of types.-mkFunTy  :: TypeRep -> TypeRep -> TypeRep-mkFunTy f a = mkTyConApp funTc [f,a]---- | Splits a type constructor application.--- Note that if the type construcotr is polymorphic, this will--- not return the kinds that were used.--- See 'splitPolyTyConApp' if you need all parts.-splitTyConApp :: TypeRep -> (TyCon,[TypeRep])-splitTyConApp (TypeRep _ tc _ trs) = (tc,trs)---- | Split a type constructor application-splitPolyTyConApp :: TypeRep -> (TyCon,[KindRep],[TypeRep])-splitPolyTyConApp (TypeRep _ tc ks trs) = (tc,ks,trs)---- | Applies a type to a function type.  Returns: @'Just' u@ if the--- first argument represents a function of type @t -> u@ and the--- second argument represents a function of type @t@.  Otherwise,--- returns 'Nothing'.-funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep-funResultTy trFun trArg-  = case splitTyConApp trFun of-      (tc, [t1,t2]) | tc == funTc && t1 == trArg -> Just t2-      _ -> Nothing---- | Adds a TypeRep argument to a TypeRep.-mkAppTy :: TypeRep -> TypeRep -> TypeRep-mkAppTy (TypeRep _ tc ks trs) arg_tr = mkPolyTyConApp tc ks (trs ++ [arg_tr])-   -- Notice that we call mkTyConApp to construct the fingerprint from tc and-   -- the arg fingerprints.  Simply combining the current fingerprint with-   -- the new one won't give the same answer, but of course we want to-   -- ensure that a TypeRep of the same shape has the same fingerprint!-   -- See Trac #5962---- | Builds a 'TyCon' object representing a type constructor.  An--- implementation of "Data.Typeable" should ensure that the following holds:------ >  A==A' ^ B==B' ^ C==C' ==> mkTyCon A B C == mkTyCon A' B' C'--------mkTyCon3 :: String       -- ^ package name-         -> String       -- ^ module name-         -> String       -- ^ the name of the type constructor-         -> TyCon        -- ^ A unique 'TyCon' object-mkTyCon3 pkg modl name =-  TyCon (fingerprintString (pkg ++ (' ':modl) ++ (' ':name))) pkg modl name------------------- Observation ------------------------- | Observe the type constructor of a type representation-typeRepTyCon :: TypeRep -> TyCon-typeRepTyCon (TypeRep _ tc _ _) = tc---- | Observe the argument types of a type representation-typeRepArgs :: TypeRep -> [TypeRep]-typeRepArgs (TypeRep _ _ _ tys) = tys---- | Observe the argument kinds of a type representation-typeRepKinds :: TypeRep -> [KindRep]-typeRepKinds (TypeRep _ _ ks _) = ks---- | Observe string encoding of a type representation-{-# DEPRECATED tyConString "renamed to 'tyConName'; 'tyConModule' and 'tyConPackage' are also available." #-} -- deprecated in 7.4-tyConString :: TyCon   -> String-tyConString = tyConName---- | Observe the 'Fingerprint' of a type representation------ @since 4.8.0.0-typeRepFingerprint :: TypeRep -> Fingerprint-typeRepFingerprint (TypeRep fpr _ _ _) = fpr---------------------------------------------------------------------      The Typeable class and friends--------------------------------------------------------------------- | The class 'Typeable' allows a concrete representation of a type to--- be calculated.-class Typeable a where-  typeRep# :: Proxy# a -> TypeRep---- | Takes a value of type @a@ and returns a concrete representation--- of that type.------ @since 4.7.0.0-typeRep :: forall proxy a. Typeable a => proxy a -> TypeRep-typeRep _ = typeRep# (proxy# :: Proxy# a)-{-# INLINE typeRep #-}---- Keeping backwards-compatibility-typeOf :: forall a. Typeable a => a -> TypeRep-typeOf _ = typeRep (Proxy :: Proxy a)--typeOf1 :: forall t (a :: *). Typeable t => t a -> TypeRep-typeOf1 _ = typeRep (Proxy :: Proxy t)--typeOf2 :: forall t (a :: *) (b :: *). Typeable t => t a b -> TypeRep-typeOf2 _ = typeRep (Proxy :: Proxy t)--typeOf3 :: forall t (a :: *) (b :: *) (c :: *). Typeable t-        => t a b c -> TypeRep-typeOf3 _ = typeRep (Proxy :: Proxy t)--typeOf4 :: forall t (a :: *) (b :: *) (c :: *) (d :: *). Typeable t-        => t a b c d -> TypeRep-typeOf4 _ = typeRep (Proxy :: Proxy t)--typeOf5 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *). Typeable t-        => t a b c d e -> TypeRep-typeOf5 _ = typeRep (Proxy :: Proxy t)--typeOf6 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *).-                Typeable t => t a b c d e f -> TypeRep-typeOf6 _ = typeRep (Proxy :: Proxy t)--typeOf7 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *)-                (g :: *). Typeable t => t a b c d e f g -> TypeRep-typeOf7 _ = typeRep (Proxy :: Proxy t)--type Typeable1 (a :: * -> *)                               = Typeable a-type Typeable2 (a :: * -> * -> *)                          = Typeable a-type Typeable3 (a :: * -> * -> * -> *)                     = Typeable a-type Typeable4 (a :: * -> * -> * -> * -> *)                = Typeable a-type Typeable5 (a :: * -> * -> * -> * -> * -> *)           = Typeable a-type Typeable6 (a :: * -> * -> * -> * -> * -> * -> *)      = Typeable a-type Typeable7 (a :: * -> * -> * -> * -> * -> * -> * -> *) = Typeable a--{-# DEPRECATED Typeable1 "renamed to 'Typeable'" #-} -- deprecated in 7.8-{-# DEPRECATED Typeable2 "renamed to 'Typeable'" #-} -- deprecated in 7.8-{-# DEPRECATED Typeable3 "renamed to 'Typeable'" #-} -- deprecated in 7.8-{-# DEPRECATED Typeable4 "renamed to 'Typeable'" #-} -- deprecated in 7.8-{-# DEPRECATED Typeable5 "renamed to 'Typeable'" #-} -- deprecated in 7.8-{-# DEPRECATED Typeable6 "renamed to 'Typeable'" #-} -- deprecated in 7.8-{-# DEPRECATED Typeable7 "renamed to 'Typeable'" #-} -- deprecated in 7.8-------------------- Showing TypeReps ----------------------instance Show TypeRep where-  showsPrec p (TypeRep _ tycon kinds tys) =-    case tys of-      [] -> showsPrec p tycon-      [x]   | tycon == listTc -> showChar '[' . shows x . showChar ']'-      [a,r] | tycon == funTc  -> showParen (p > 8) $-                                 showsPrec 9 a .-                                 showString " -> " .-                                 showsPrec 8 r-      xs | isTupleTyCon tycon -> showTuple xs-         | otherwise         ->-            showParen (p > 9) $-            showsPrec p tycon .-            showChar ' '      .-            showArgs (showChar ' ') (kinds ++ tys)--showsTypeRep :: TypeRep -> ShowS-showsTypeRep = shows--instance Show TyCon where-  showsPrec _ t = showString (tyConName t)--isTupleTyCon :: TyCon -> Bool-isTupleTyCon (TyCon _ _ _ ('(':',':_)) = True-isTupleTyCon _                         = False---- | Helper to fully evaluate 'TypeRep' for use as @NFData(rnf)@ implementation------ @since 4.8.0.0-rnfTypeRep :: TypeRep -> ()-rnfTypeRep (TypeRep _ tyc krs tyrs) = rnfTyCon tyc `seq` go krs `seq` go tyrs-  where-    go [] = ()-    go (x:xs) = rnfTypeRep x `seq` go xs---- | Helper to fully evaluate 'TyCon' for use as @NFData(rnf)@ implementation------ @since 4.8.0.0-rnfTyCon :: TyCon -> ()-rnfTyCon (TyCon _ tcp tcm tcn) = go tcp `seq` go tcm `seq` go tcn-  where-    go [] = ()-    go (x:xs) = x `seq` go xs---- Some (Show.TypeRep) helpers:--showArgs :: Show a => ShowS -> [a] -> ShowS-showArgs _   []     = id-showArgs _   [a]    = showsPrec 10 a-showArgs sep (a:as) = showsPrec 10 a . sep . showArgs sep as--showTuple :: [TypeRep] -> ShowS-showTuple args = showChar '('-               . showArgs (showChar ',') args-               . showChar ')'--listTc :: TyCon-listTc = typeRepTyCon (typeOf [()])--funTc :: TyCon-funTc = typeRepTyCon (typeRep (Proxy :: Proxy (->)))------ | An internal function, to make representations for type literals.-typeLitTypeRep :: String -> TypeRep-typeLitTypeRep nm = rep-    where-    rep = mkTyConApp tc []-    tc = TyCon-           { tyConFingerprint = fingerprintString (mk pack modu nm)-           , tyConPackage  = pack-           , tyConModule   = modu-           , tyConName     = nm-           }-    pack = "base"-    modu = "GHC.TypeLits"-    mk a b c = a ++ " " ++ b ++ " " ++ c--
− Data/Unique.hs
@@ -1,72 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE MagicHash, AutoDeriveTypeable #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Unique--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable------ An abstract interface to a unique symbol generator.-----------------------------------------------------------------------------------module Data.Unique (-   -- * Unique objects-   Unique,-   newUnique,-   hashUnique- ) where--import System.IO.Unsafe (unsafePerformIO)--import GHC.Base-import GHC.Num-import Data.Typeable-import Data.IORef---- | An abstract unique object.  Objects of type 'Unique' may be--- compared for equality and ordering and hashed into 'Int'.-newtype Unique = Unique Integer deriving (Eq,Ord,Typeable)--uniqSource :: IORef Integer-uniqSource = unsafePerformIO (newIORef 0)-{-# NOINLINE uniqSource #-}---- | Creates a new object of type 'Unique'.  The value returned will--- not compare equal to any other value of type 'Unique' returned by--- previous calls to 'newUnique'.  There is no limit on the number of--- times 'newUnique' may be called.-newUnique :: IO Unique-newUnique = do-  r <- atomicModifyIORef' uniqSource $ \x -> let z = x+1 in (z,z)-  return (Unique r)---- SDM (18/3/2010): changed from MVar to STM.  This fixes---  1. there was no async exception protection---  2. there was a space leak (now new value is strict)---  3. using atomicModifyIORef would be slightly quicker, but can---     suffer from adverse scheduling issues (see #3838)---  4. also, the STM version is faster.---- SDM (30/4/2012): changed to IORef using atomicModifyIORef.  Reasons:---  1. STM version could not be used inside unsafePerformIO, if it---     happened to be poked inside an STM transaction.---  2. IORef version can be used with unsafeIOToSTM inside STM,---     because if the transaction retries then we just get a new---     Unique.---  3. IORef version is very slightly faster.---- IGL (08/06/2013): changed to using atomicModifyIORef' instead.---  This feels a little safer, from the point of view of not leaking---  memory, but the resulting core is identical.---- | Hashes a 'Unique' into an 'Int'.  Two 'Unique's may hash to the--- same value, although in practice this is unlikely.  The 'Int'--- returned makes a good hash key.-hashUnique :: Unique -> Int-hashUnique (Unique i) = I# (hashInteger i)
− Data/Version.hs
@@ -1,131 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE AutoDeriveTypeable #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Version--- Copyright   :  (c) The University of Glasgow 2004--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable (local universal quantification in ReadP)------ A general library for representation and manipulation of versions.------ Versioning schemes are many and varied, so the version--- representation provided by this library is intended to be a--- compromise between complete generality, where almost no common--- functionality could reasonably be provided, and fixing a particular--- versioning scheme, which would probably be too restrictive.------ So the approach taken here is to provide a representation which--- subsumes many of the versioning schemes commonly in use, and we--- provide implementations of 'Eq', 'Ord' and conversion to\/from 'String'--- which will be appropriate for some applications, but not all.-----------------------------------------------------------------------------------module Data.Version (-        -- * The @Version@ type-        Version(..),-        -- * A concrete representation of @Version@-        showVersion, parseVersion,-        -- * Constructor function-        makeVersion-  ) where--import Control.Monad    ( Monad(..), liftM )-import Data.Bool        ( (&&) )-import Data.Char        ( isDigit, isAlphaNum )-import Data.Eq-import Data.Int         ( Int )-import Data.List-import Data.Ord-import Data.String      ( String )-import Data.Typeable    ( Typeable )-import GHC.Read-import GHC.Show-import Text.ParserCombinators.ReadP-import Text.Read        ( read )--{- |-A 'Version' represents the version of a software entity.--An instance of 'Eq' is provided, which implements exact equality-modulo reordering of the tags in the 'versionTags' field.--An instance of 'Ord' is also provided, which gives lexicographic-ordering on the 'versionBranch' fields (i.e. 2.1 > 2.0, 1.2.3 > 1.2.2,-etc.).  This is expected to be sufficient for many uses, but note that-you may need to use a more specific ordering for your versioning-scheme.  For example, some versioning schemes may include pre-releases-which have tags @\"pre1\"@, @\"pre2\"@, and so on, and these would need to-be taken into account when determining ordering.  In some cases, date-ordering may be more appropriate, so the application would have to-look for @date@ tags in the 'versionTags' field and compare those.-The bottom line is, don't always assume that 'compare' and other 'Ord'-operations are the right thing for every 'Version'.--Similarly, concrete representations of versions may differ.  One-possible concrete representation is provided (see 'showVersion' and-'parseVersion'), but depending on the application a different concrete-representation may be more appropriate.--}-data Version =-  Version { versionBranch :: [Int],-                -- ^ The numeric branch for this version.  This reflects the-                -- fact that most software versions are tree-structured; there-                -- is a main trunk which is tagged with versions at various-                -- points (1,2,3...), and the first branch off the trunk after-                -- version 3 is 3.1, the second branch off the trunk after-                -- version 3 is 3.2, and so on.  The tree can be branched-                -- arbitrarily, just by adding more digits.-                ---                -- We represent the branch as a list of 'Int', so-                -- version 3.2.1 becomes [3,2,1].  Lexicographic ordering-                -- (i.e. the default instance of 'Ord' for @[Int]@) gives-                -- the natural ordering of branches.--           versionTags :: [String]  -- really a bag-                -- ^ A version can be tagged with an arbitrary list of strings.-                -- The interpretation of the list of tags is entirely dependent-                -- on the entity that this version applies to.-        }-  deriving (Read,Show,Typeable)-{-# DEPRECATED versionTags "See GHC ticket #2496" #-}--- TODO. Remove all references to versionTags in GHC 7.12 release.--instance Eq Version where-  v1 == v2  =  versionBranch v1 == versionBranch v2-                && sort (versionTags v1) == sort (versionTags v2)-                -- tags may be in any order--instance Ord Version where-  v1 `compare` v2 = versionBranch v1 `compare` versionBranch v2---- -------------------------------------------------------------------------------- A concrete representation of 'Version'---- | Provides one possible concrete representation for 'Version'.  For--- a version with 'versionBranch' @= [1,2,3]@ and 'versionTags'--- @= [\"tag1\",\"tag2\"]@, the output will be @1.2.3-tag1-tag2@.----showVersion :: Version -> String-showVersion (Version branch tags)-  = concat (intersperse "." (map show branch)) ++-     concatMap ('-':) tags---- | A parser for versions in the format produced by 'showVersion'.----parseVersion :: ReadP Version-parseVersion = do branch <- sepBy1 (liftM read (munch1 isDigit)) (char '.')-                  tags   <- many (char '-' >> munch1 isAlphaNum)-                  return Version{versionBranch=branch, versionTags=tags}---- | Construct tag-less 'Version'------ @since 4.8.0.0-makeVersion :: [Int] -> Version-makeVersion b = Version b []
− Data/Void.hs
@@ -1,74 +0,0 @@-{-# LANGUAGE AutoDeriveTypeable #-}-{-# LANGUAGE DeriveDataTypeable #-}-{-# LANGUAGE DeriveGeneric #-}-{-# LANGUAGE EmptyCase #-}-{-# LANGUAGE Safe #-}-{-# LANGUAGE StandaloneDeriving #-}---------------------------------------------------------------------------------- |--- Copyright   :  (C) 2008-2014 Edward Kmett--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  Edward Kmett <ekmett@gmail.com>--- Stability   :  provisional--- Portability :  portable------ A logically uninhabited data type, used to indicate that a given--- term should not exist.------ @since 4.8.0.0------------------------------------------------------------------------------module Data.Void-    ( Void-    , absurd-    , vacuous-    ) where--import Control.Exception-import Data.Data-import Data.Ix-import GHC.Generics---- | Uninhabited data type------ @since 4.8.0.0-data Void deriving (Generic)--deriving instance Data Void--instance Eq Void where-    _ == _ = True--instance Ord Void where-    compare _ _ = EQ---- | Reading a 'Void' value is always a parse error, considering--- 'Void' as a data type with no constructors.-instance Read Void where-    readsPrec _ _ = []--instance Show Void where-    showsPrec _ = absurd--instance Ix Void where-    range _     = []-    index _     = absurd-    inRange _   = absurd-    rangeSize _ = 0--instance Exception Void---- | Since 'Void' values logically don't exist, this witnesses the--- logical reasoning tool of \"ex falso quodlibet\".------ @since 4.8.0.0-absurd :: Void -> a-absurd a = case a of {}---- | If 'Void' is uninhabited then any 'Functor' that holds only--- values of type 'Void' is holding no values.------ @since 4.8.0.0-vacuous :: Functor f => f Void -> f a-vacuous = fmap absurd
− Data/Word.hs
@@ -1,60 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Data.Word--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Unsigned integer types.-----------------------------------------------------------------------------------module Data.Word-  (-        -- * Unsigned integral types--        Word,-        Word8, Word16, Word32, Word64,--        -- * byte swapping-        byteSwap16, byteSwap32, byteSwap64,--        -- * Notes--        -- $notes-        ) where--import GHC.Word--{- $notes--* All arithmetic is performed modulo 2^n, where n is the number of-  bits in the type.  One non-obvious consequence of this is that 'Prelude.negate'-  should /not/ raise an error on negative arguments.--* For coercing between any two integer types, use-  'Prelude.fromIntegral', which is specialized for all the-  common cases so should be fast enough.  Coercing word types to and-  from integer types preserves representation, not sign.--* An unbounded size unsigned integer type is available with-  'Numeric.Natural.Natural'.--* The rules that hold for 'Prelude.Enum' instances over a bounded type-  such as 'Prelude.Int' (see the section of the Haskell report dealing-  with arithmetic sequences) also hold for the 'Prelude.Enum' instances-  over the various 'Word' types defined here.--* Right and left shifts by amounts greater than or equal to the width-  of the type result in a zero result.  This is contrary to the-  behaviour in C, which is undefined; a common interpretation is to-  truncate the shift count to the width of the type, for example @1 \<\<-  32 == 1@ in some C implementations. --}-
− Debug/Trace.hs
@@ -1,289 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE MagicHash #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE UnboxedTuples #-}---------------------------------------------------------------------------------- |--- Module      :  Debug.Trace--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Functions for tracing and monitoring execution.------ These can be useful for investigating bugs or performance problems.--- They should /not/ be used in production code.-----------------------------------------------------------------------------------module Debug.Trace (-        -- * Tracing-        -- $tracing-        trace,-        traceId,-        traceShow,-        traceShowId,-        traceStack,-        traceIO,-        traceM,-        traceShowM,-        putTraceMsg,--        -- * Eventlog tracing-        -- $eventlog_tracing-        traceEvent,-        traceEventIO,--        -- * Execution phase markers-        -- $markers-        traceMarker,-        traceMarkerIO,-  ) where--import System.IO.Unsafe--import Foreign.C.String-import GHC.Base-import qualified GHC.Foreign-import GHC.IO.Encoding-import GHC.Ptr-import GHC.Show-import GHC.Stack-import Data.List---- $tracing------ The 'trace', 'traceShow' and 'traceIO' functions print messages to an output--- stream. They are intended for \"printf debugging\", that is: tracing the flow--- of execution and printing interesting values.------ All these functions evaluate the message completely before printing--- it; so if the message is not fully defined, none of it will be--- printed.------ The usual output stream is 'System.IO.stderr'. For Windows GUI applications--- (that have no stderr) the output is directed to the Windows debug console.--- Some implementations of these functions may decorate the string that\'s--- output to indicate that you\'re tracing.---- | The 'traceIO' function outputs the trace message from the IO monad.--- This sequences the output with respect to other IO actions.------ @since 4.5.0.0-traceIO :: String -> IO ()-traceIO msg = do-    withCString "%s\n" $ \cfmt -> do-     -- NB: debugBelch can't deal with null bytes, so filter them-     -- out so we don't accidentally truncate the message.  See Trac #9395-     let (nulls, msg') = partition (=='\0') msg-     withCString msg' $ \cmsg ->-      debugBelch cfmt cmsg-     when (not (null nulls)) $-       withCString "WARNING: previous trace message had null bytes" $ \cmsg ->-         debugBelch cfmt cmsg---- don't use debugBelch() directly, because we cannot call varargs functions--- using the FFI.-foreign import ccall unsafe "HsBase.h debugBelch2"-   debugBelch :: CString -> CString -> IO ()---- |-putTraceMsg :: String -> IO ()-putTraceMsg = traceIO-{-# DEPRECATED putTraceMsg "Use 'Debug.Trace.traceIO'" #-} -- deprecated in 7.4---{-# NOINLINE trace #-}-{-|-The 'trace' function outputs the trace message given as its first argument,-before returning the second argument as its result.--For example, this returns the value of @f x@ but first outputs the message.--> trace ("calling f with x = " ++ show x) (f x)--The 'trace' function should /only/ be used for debugging, or for monitoring-execution. The function is not referentially transparent: its type indicates-that it is a pure function but it has the side effect of outputting the-trace message.--}-trace :: String -> a -> a-trace string expr = unsafePerformIO $ do-    traceIO string-    return expr--{-|-Like 'trace' but returns the message instead of a third value.--@since 4.7.0.0--}-traceId :: String -> String-traceId a = trace a a--{-|-Like 'trace', but uses 'show' on the argument to convert it to a 'String'.--This makes it convenient for printing the values of interesting variables or-expressions inside a function. For example here we print the value of the-variables @x@ and @z@:--> f x y =->     traceShow (x, z) $ result->   where->     z = ...->     ...--}-traceShow :: (Show a) => a -> b -> b-traceShow = trace . show--{-|-Like 'traceShow' but returns the shown value instead of a third value.--@since 4.7.0.0--}-traceShowId :: (Show a) => a -> a-traceShowId a = trace (show a) a--{-|-Like 'trace' but returning unit in an arbitrary monad. Allows for convenient-use in do-notation. Note that the application of 'trace' is not an action in the-monad, as 'traceIO' is in the 'IO' monad.--> ... = do->   x <- ...->   traceM $ "x: " ++ show x->   y <- ...->   traceM $ "y: " ++ show y--@since 4.7.0.0--}-traceM :: (Monad m) => String -> m ()-traceM string = trace string $ return ()--{-|-Like 'traceM', but uses 'show' on the argument to convert it to a 'String'.--> ... = do->   x <- ...->   traceMShow $ x->   y <- ...->   traceMShow $ x + y--@since 4.7.0.0--}-traceShowM :: (Show a, Monad m) => a -> m ()-traceShowM = traceM . show---- | like 'trace', but additionally prints a call stack if one is--- available.------ In the current GHC implementation, the call stack is only--- availble if the program was compiled with @-prof@; otherwise--- 'traceStack' behaves exactly like 'trace'.  Entries in the call--- stack correspond to @SCC@ annotations, so it is a good idea to use--- @-fprof-auto@ or @-fprof-auto-calls@ to add SCC annotations automatically.------ @since 4.5.0.0-traceStack :: String -> a -> a-traceStack str expr = unsafePerformIO $ do-   traceIO str-   stack <- currentCallStack-   when (not (null stack)) $ traceIO (renderStack stack)-   return expr----- $eventlog_tracing------ Eventlog tracing is a performance profiling system. These functions emit--- extra events into the eventlog. In combination with eventlog profiling--- tools these functions can be used for monitoring execution and--- investigating performance problems.------ Currently only GHC provides eventlog profiling, see the GHC user guide for--- details on how to use it. These function exists for other Haskell--- implementations but no events are emitted. Note that the string message is--- always evaluated, whether or not profiling is available or enabled.--{-# NOINLINE traceEvent #-}--- | The 'traceEvent' function behaves like 'trace' with the difference that--- the message is emitted to the eventlog, if eventlog profiling is available--- and enabled at runtime.------ It is suitable for use in pure code. In an IO context use 'traceEventIO'--- instead.------ Note that when using GHC's SMP runtime, it is possible (but rare) to get--- duplicate events emitted if two CPUs simultaneously evaluate the same thunk--- that uses 'traceEvent'.------ @since 4.5.0.0-traceEvent :: String -> a -> a-traceEvent msg expr = unsafeDupablePerformIO $ do-    traceEventIO msg-    return expr---- | The 'traceEventIO' function emits a message to the eventlog, if eventlog--- profiling is available and enabled at runtime.------ Compared to 'traceEvent', 'traceEventIO' sequences the event with respect to--- other IO actions.------ @since 4.5.0.0-traceEventIO :: String -> IO ()-traceEventIO msg =-  GHC.Foreign.withCString utf8 msg $ \(Ptr p) -> IO $ \s ->-    case traceEvent# p s of s' -> (# s', () #)---- $markers------ When looking at a profile for the execution of a program we often want to--- be able to mark certain points or phases in the execution and see that--- visually in the profile.---- For example, a program might have several distinct phases with different--- performance or resource behaviour in each phase. To properly interpret the--- profile graph we really want to see when each phase starts and ends.------ Markers let us do this: we can annotate the program to emit a marker at--- an appropriate point during execution and then see that in a profile.------ Currently this feature is only supported in GHC by the eventlog tracing--- system, but in future it may also be supported by the heap profiling or--- other profiling tools. These function exists for other Haskell--- implementations but they have no effect. Note that the string message is--- always evaluated, whether or not profiling is available or enabled.--{-# NOINLINE traceMarker #-}--- | The 'traceMarker' function emits a marker to the eventlog, if eventlog--- profiling is available and enabled at runtime. The @String@ is the name of--- the marker. The name is just used in the profiling tools to help you keep--- clear which marker is which.------ This function is suitable for use in pure code. In an IO context use--- 'traceMarkerIO' instead.------ Note that when using GHC's SMP runtime, it is possible (but rare) to get--- duplicate events emitted if two CPUs simultaneously evaluate the same thunk--- that uses 'traceMarker'.------ @since 4.7.0.0-traceMarker :: String -> a -> a-traceMarker msg expr = unsafeDupablePerformIO $ do-    traceMarkerIO msg-    return expr---- | The 'traceMarkerIO' function emits a marker to the eventlog, if eventlog--- profiling is available and enabled at runtime.------ Compared to 'traceMarker', 'traceMarkerIO' sequences the event with respect to--- other IO actions.------ @since 4.7.0.0-traceMarkerIO :: String -> IO ()-traceMarkerIO msg =-  GHC.Foreign.withCString utf8 msg $ \(Ptr p) -> IO $ \s ->-    case traceMarker# p s of s' -> (# s', () #)
− Foreign.hs
@@ -1,38 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ A collection of data types, classes, and functions for interfacing--- with another programming language.-----------------------------------------------------------------------------------module Foreign-        ( module Data.Bits-        , module Data.Int-        , module Data.Word-        , module Foreign.Ptr-        , module Foreign.ForeignPtr-        , module Foreign.StablePtr-        , module Foreign.Storable-        , module Foreign.Marshal-        ) where--import Data.Bits-import Data.Int-import Data.Word-import Foreign.Ptr-import Foreign.ForeignPtr-import Foreign.StablePtr-import Foreign.Storable-import Foreign.Marshal-
− Foreign/C.hs
@@ -1,27 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.C--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ Bundles the C specific FFI library functionality-----------------------------------------------------------------------------------module Foreign.C-        ( module Foreign.C.Types-        , module Foreign.C.String-        , module Foreign.C.Error-        ) where--import Foreign.C.Types-import Foreign.C.String-import Foreign.C.Error-
− Foreign/C/Error.hs
@@ -1,575 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.C.Error--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ C-specific Marshalling support: Handling of C \"errno\" error codes.-----------------------------------------------------------------------------------module Foreign.C.Error (--  -- * Haskell representations of @errno@ values--  Errno(..),--  -- ** Common @errno@ symbols-  -- | Different operating systems and\/or C libraries often support-  -- different values of @errno@.  This module defines the common values,-  -- but due to the open definition of 'Errno' users may add definitions-  -- which are not predefined.-  eOK, e2BIG, eACCES, eADDRINUSE, eADDRNOTAVAIL, eADV, eAFNOSUPPORT, eAGAIN,-  eALREADY, eBADF, eBADMSG, eBADRPC, eBUSY, eCHILD, eCOMM, eCONNABORTED,-  eCONNREFUSED, eCONNRESET, eDEADLK, eDESTADDRREQ, eDIRTY, eDOM, eDQUOT,-  eEXIST, eFAULT, eFBIG, eFTYPE, eHOSTDOWN, eHOSTUNREACH, eIDRM, eILSEQ,-  eINPROGRESS, eINTR, eINVAL, eIO, eISCONN, eISDIR, eLOOP, eMFILE, eMLINK,-  eMSGSIZE, eMULTIHOP, eNAMETOOLONG, eNETDOWN, eNETRESET, eNETUNREACH,-  eNFILE, eNOBUFS, eNODATA, eNODEV, eNOENT, eNOEXEC, eNOLCK, eNOLINK,-  eNOMEM, eNOMSG, eNONET, eNOPROTOOPT, eNOSPC, eNOSR, eNOSTR, eNOSYS,-  eNOTBLK, eNOTCONN, eNOTDIR, eNOTEMPTY, eNOTSOCK, eNOTSUP, eNOTTY, eNXIO,-  eOPNOTSUPP, ePERM, ePFNOSUPPORT, ePIPE, ePROCLIM, ePROCUNAVAIL,-  ePROGMISMATCH, ePROGUNAVAIL, ePROTO, ePROTONOSUPPORT, ePROTOTYPE,-  eRANGE, eREMCHG, eREMOTE, eROFS, eRPCMISMATCH, eRREMOTE, eSHUTDOWN,-  eSOCKTNOSUPPORT, eSPIPE, eSRCH, eSRMNT, eSTALE, eTIME, eTIMEDOUT,-  eTOOMANYREFS, eTXTBSY, eUSERS, eWOULDBLOCK, eXDEV,--  -- ** 'Errno' functions-  isValidErrno,--  -- access to the current thread's "errno" value-  ---  getErrno,-  resetErrno,--  -- conversion of an "errno" value into IO error-  ---  errnoToIOError,--  -- throw current "errno" value-  ---  throwErrno,--  -- ** Guards for IO operations that may fail--  throwErrnoIf,-  throwErrnoIf_,-  throwErrnoIfRetry,-  throwErrnoIfRetry_,-  throwErrnoIfMinus1,-  throwErrnoIfMinus1_,-  throwErrnoIfMinus1Retry,-  throwErrnoIfMinus1Retry_,-  throwErrnoIfNull,-  throwErrnoIfNullRetry,--  throwErrnoIfRetryMayBlock,-  throwErrnoIfRetryMayBlock_,-  throwErrnoIfMinus1RetryMayBlock,-  throwErrnoIfMinus1RetryMayBlock_,-  throwErrnoIfNullRetryMayBlock,--  throwErrnoPath,-  throwErrnoPathIf,-  throwErrnoPathIf_,-  throwErrnoPathIfNull,-  throwErrnoPathIfMinus1,-  throwErrnoPathIfMinus1_,-) where----- this is were we get the CONST_XXX definitions from that configure--- calculated for us----#include "HsBaseConfig.h"--import Foreign.Ptr-import Foreign.C.Types-import Foreign.C.String-import Data.Functor            ( void )-import Data.Maybe--import GHC.IO-import GHC.IO.Exception-import GHC.IO.Handle.Types-import GHC.Num-import GHC.Base---- "errno" type--- ---------------- | Haskell representation for @errno@ values.--- The implementation is deliberately exposed, to allow users to add--- their own definitions of 'Errno' values.--newtype Errno = Errno CInt--instance Eq Errno where-  errno1@(Errno no1) == errno2@(Errno no2)-    | isValidErrno errno1 && isValidErrno errno2 = no1 == no2-    | otherwise                                  = False---- common "errno" symbols----eOK, e2BIG, eACCES, eADDRINUSE, eADDRNOTAVAIL, eADV, eAFNOSUPPORT, eAGAIN,-  eALREADY, eBADF, eBADMSG, eBADRPC, eBUSY, eCHILD, eCOMM, eCONNABORTED,-  eCONNREFUSED, eCONNRESET, eDEADLK, eDESTADDRREQ, eDIRTY, eDOM, eDQUOT,-  eEXIST, eFAULT, eFBIG, eFTYPE, eHOSTDOWN, eHOSTUNREACH, eIDRM, eILSEQ,-  eINPROGRESS, eINTR, eINVAL, eIO, eISCONN, eISDIR, eLOOP, eMFILE, eMLINK,-  eMSGSIZE, eMULTIHOP, eNAMETOOLONG, eNETDOWN, eNETRESET, eNETUNREACH,-  eNFILE, eNOBUFS, eNODATA, eNODEV, eNOENT, eNOEXEC, eNOLCK, eNOLINK,-  eNOMEM, eNOMSG, eNONET, eNOPROTOOPT, eNOSPC, eNOSR, eNOSTR, eNOSYS,-  eNOTBLK, eNOTCONN, eNOTDIR, eNOTEMPTY, eNOTSOCK, eNOTSUP, eNOTTY, eNXIO,-  eOPNOTSUPP, ePERM, ePFNOSUPPORT, ePIPE, ePROCLIM, ePROCUNAVAIL,-  ePROGMISMATCH, ePROGUNAVAIL, ePROTO, ePROTONOSUPPORT, ePROTOTYPE,-  eRANGE, eREMCHG, eREMOTE, eROFS, eRPCMISMATCH, eRREMOTE, eSHUTDOWN,-  eSOCKTNOSUPPORT, eSPIPE, eSRCH, eSRMNT, eSTALE, eTIME, eTIMEDOUT,-  eTOOMANYREFS, eTXTBSY, eUSERS, eWOULDBLOCK, eXDEV                    :: Errno------ the cCONST_XXX identifiers are cpp symbols whose value is computed by--- configure----eOK             = Errno 0-e2BIG           = Errno (CONST_E2BIG)-eACCES          = Errno (CONST_EACCES)-eADDRINUSE      = Errno (CONST_EADDRINUSE)-eADDRNOTAVAIL   = Errno (CONST_EADDRNOTAVAIL)-eADV            = Errno (CONST_EADV)-eAFNOSUPPORT    = Errno (CONST_EAFNOSUPPORT)-eAGAIN          = Errno (CONST_EAGAIN)-eALREADY        = Errno (CONST_EALREADY)-eBADF           = Errno (CONST_EBADF)-eBADMSG         = Errno (CONST_EBADMSG)-eBADRPC         = Errno (CONST_EBADRPC)-eBUSY           = Errno (CONST_EBUSY)-eCHILD          = Errno (CONST_ECHILD)-eCOMM           = Errno (CONST_ECOMM)-eCONNABORTED    = Errno (CONST_ECONNABORTED)-eCONNREFUSED    = Errno (CONST_ECONNREFUSED)-eCONNRESET      = Errno (CONST_ECONNRESET)-eDEADLK         = Errno (CONST_EDEADLK)-eDESTADDRREQ    = Errno (CONST_EDESTADDRREQ)-eDIRTY          = Errno (CONST_EDIRTY)-eDOM            = Errno (CONST_EDOM)-eDQUOT          = Errno (CONST_EDQUOT)-eEXIST          = Errno (CONST_EEXIST)-eFAULT          = Errno (CONST_EFAULT)-eFBIG           = Errno (CONST_EFBIG)-eFTYPE          = Errno (CONST_EFTYPE)-eHOSTDOWN       = Errno (CONST_EHOSTDOWN)-eHOSTUNREACH    = Errno (CONST_EHOSTUNREACH)-eIDRM           = Errno (CONST_EIDRM)-eILSEQ          = Errno (CONST_EILSEQ)-eINPROGRESS     = Errno (CONST_EINPROGRESS)-eINTR           = Errno (CONST_EINTR)-eINVAL          = Errno (CONST_EINVAL)-eIO             = Errno (CONST_EIO)-eISCONN         = Errno (CONST_EISCONN)-eISDIR          = Errno (CONST_EISDIR)-eLOOP           = Errno (CONST_ELOOP)-eMFILE          = Errno (CONST_EMFILE)-eMLINK          = Errno (CONST_EMLINK)-eMSGSIZE        = Errno (CONST_EMSGSIZE)-eMULTIHOP       = Errno (CONST_EMULTIHOP)-eNAMETOOLONG    = Errno (CONST_ENAMETOOLONG)-eNETDOWN        = Errno (CONST_ENETDOWN)-eNETRESET       = Errno (CONST_ENETRESET)-eNETUNREACH     = Errno (CONST_ENETUNREACH)-eNFILE          = Errno (CONST_ENFILE)-eNOBUFS         = Errno (CONST_ENOBUFS)-eNODATA         = Errno (CONST_ENODATA)-eNODEV          = Errno (CONST_ENODEV)-eNOENT          = Errno (CONST_ENOENT)-eNOEXEC         = Errno (CONST_ENOEXEC)-eNOLCK          = Errno (CONST_ENOLCK)-eNOLINK         = Errno (CONST_ENOLINK)-eNOMEM          = Errno (CONST_ENOMEM)-eNOMSG          = Errno (CONST_ENOMSG)-eNONET          = Errno (CONST_ENONET)-eNOPROTOOPT     = Errno (CONST_ENOPROTOOPT)-eNOSPC          = Errno (CONST_ENOSPC)-eNOSR           = Errno (CONST_ENOSR)-eNOSTR          = Errno (CONST_ENOSTR)-eNOSYS          = Errno (CONST_ENOSYS)-eNOTBLK         = Errno (CONST_ENOTBLK)-eNOTCONN        = Errno (CONST_ENOTCONN)-eNOTDIR         = Errno (CONST_ENOTDIR)-eNOTEMPTY       = Errno (CONST_ENOTEMPTY)-eNOTSOCK        = Errno (CONST_ENOTSOCK)-eNOTSUP         = Errno (CONST_ENOTSUP)--- ^ @since 4.7.0.0-eNOTTY          = Errno (CONST_ENOTTY)-eNXIO           = Errno (CONST_ENXIO)-eOPNOTSUPP      = Errno (CONST_EOPNOTSUPP)-ePERM           = Errno (CONST_EPERM)-ePFNOSUPPORT    = Errno (CONST_EPFNOSUPPORT)-ePIPE           = Errno (CONST_EPIPE)-ePROCLIM        = Errno (CONST_EPROCLIM)-ePROCUNAVAIL    = Errno (CONST_EPROCUNAVAIL)-ePROGMISMATCH   = Errno (CONST_EPROGMISMATCH)-ePROGUNAVAIL    = Errno (CONST_EPROGUNAVAIL)-ePROTO          = Errno (CONST_EPROTO)-ePROTONOSUPPORT = Errno (CONST_EPROTONOSUPPORT)-ePROTOTYPE      = Errno (CONST_EPROTOTYPE)-eRANGE          = Errno (CONST_ERANGE)-eREMCHG         = Errno (CONST_EREMCHG)-eREMOTE         = Errno (CONST_EREMOTE)-eROFS           = Errno (CONST_EROFS)-eRPCMISMATCH    = Errno (CONST_ERPCMISMATCH)-eRREMOTE        = Errno (CONST_ERREMOTE)-eSHUTDOWN       = Errno (CONST_ESHUTDOWN)-eSOCKTNOSUPPORT = Errno (CONST_ESOCKTNOSUPPORT)-eSPIPE          = Errno (CONST_ESPIPE)-eSRCH           = Errno (CONST_ESRCH)-eSRMNT          = Errno (CONST_ESRMNT)-eSTALE          = Errno (CONST_ESTALE)-eTIME           = Errno (CONST_ETIME)-eTIMEDOUT       = Errno (CONST_ETIMEDOUT)-eTOOMANYREFS    = Errno (CONST_ETOOMANYREFS)-eTXTBSY         = Errno (CONST_ETXTBSY)-eUSERS          = Errno (CONST_EUSERS)-eWOULDBLOCK     = Errno (CONST_EWOULDBLOCK)-eXDEV           = Errno (CONST_EXDEV)---- | Yield 'True' if the given 'Errno' value is valid on the system.--- This implies that the 'Eq' instance of 'Errno' is also system dependent--- as it is only defined for valid values of 'Errno'.----isValidErrno               :: Errno -> Bool------ the configure script sets all invalid "errno"s to -1----isValidErrno (Errno errno)  = errno /= -1----- access to the current thread's "errno" value--- ------------------------------------------------ | Get the current value of @errno@ in the current thread.----getErrno :: IO Errno---- We must call a C function to get the value of errno in general.  On--- threaded systems, errno is hidden behind a C macro so that each OS--- thread gets its own copy.-getErrno = do e <- get_errno; return (Errno e)-foreign import ccall unsafe "HsBase.h __hscore_get_errno" get_errno :: IO CInt---- | Reset the current thread\'s @errno@ value to 'eOK'.----resetErrno :: IO ()---- Again, setting errno has to be done via a C function.-resetErrno = set_errno 0-foreign import ccall unsafe "HsBase.h __hscore_set_errno" set_errno :: CInt -> IO ()---- throw current "errno" value--- ------------------------------- | Throw an 'IOError' corresponding to the current value of 'getErrno'.----throwErrno     :: String        -- ^ textual description of the error location-               -> IO a-throwErrno loc  =-  do-    errno <- getErrno-    ioError (errnoToIOError loc errno Nothing Nothing)----- guards for IO operations that may fail--- ------------------------------------------ | Throw an 'IOError' corresponding to the current value of 'getErrno'--- if the result value of the 'IO' action meets the given predicate.----throwErrnoIf    :: (a -> Bool)  -- ^ predicate to apply to the result value-                                -- of the 'IO' operation-                -> String       -- ^ textual description of the location-                -> IO a         -- ^ the 'IO' operation to be executed-                -> IO a-throwErrnoIf pred loc f  =-  do-    res <- f-    if pred res then throwErrno loc else return res---- | as 'throwErrnoIf', but discards the result of the 'IO' action after--- error handling.----throwErrnoIf_   :: (a -> Bool) -> String -> IO a -> IO ()-throwErrnoIf_ pred loc f  = void $ throwErrnoIf pred loc f---- | as 'throwErrnoIf', but retry the 'IO' action when it yields the--- error code 'eINTR' - this amounts to the standard retry loop for--- interrupted POSIX system calls.----throwErrnoIfRetry            :: (a -> Bool) -> String -> IO a -> IO a-throwErrnoIfRetry pred loc f  =-  do-    res <- f-    if pred res-      then do-        err <- getErrno-        if err == eINTR-          then throwErrnoIfRetry pred loc f-          else throwErrno loc-      else return res---- | as 'throwErrnoIfRetry', but additionally if the operation--- yields the error code 'eAGAIN' or 'eWOULDBLOCK', an alternative--- action is executed before retrying.----throwErrnoIfRetryMayBlock-                :: (a -> Bool)  -- ^ predicate to apply to the result value-                                -- of the 'IO' operation-                -> String       -- ^ textual description of the location-                -> IO a         -- ^ the 'IO' operation to be executed-                -> IO b         -- ^ action to execute before retrying if-                                -- an immediate retry would block-                -> IO a-throwErrnoIfRetryMayBlock pred loc f on_block  =-  do-    res <- f-    if pred res-      then do-        err <- getErrno-        if err == eINTR-          then throwErrnoIfRetryMayBlock pred loc f on_block-          else if err == eWOULDBLOCK || err == eAGAIN-                 then do _ <- on_block-                         throwErrnoIfRetryMayBlock pred loc f on_block-                 else throwErrno loc-      else return res---- | as 'throwErrnoIfRetry', but discards the result.----throwErrnoIfRetry_            :: (a -> Bool) -> String -> IO a -> IO ()-throwErrnoIfRetry_ pred loc f  = void $ throwErrnoIfRetry pred loc f---- | as 'throwErrnoIfRetryMayBlock', but discards the result.----throwErrnoIfRetryMayBlock_ :: (a -> Bool) -> String -> IO a -> IO b -> IO ()-throwErrnoIfRetryMayBlock_ pred loc f on_block-  = void $ throwErrnoIfRetryMayBlock pred loc f on_block---- | Throw an 'IOError' corresponding to the current value of 'getErrno'--- if the 'IO' action returns a result of @-1@.----throwErrnoIfMinus1 :: (Eq a, Num a) => String -> IO a -> IO a-throwErrnoIfMinus1  = throwErrnoIf (== -1)---- | as 'throwErrnoIfMinus1', but discards the result.----throwErrnoIfMinus1_ :: (Eq a, Num a) => String -> IO a -> IO ()-throwErrnoIfMinus1_  = throwErrnoIf_ (== -1)---- | Throw an 'IOError' corresponding to the current value of 'getErrno'--- if the 'IO' action returns a result of @-1@, but retries in case of--- an interrupted operation.----throwErrnoIfMinus1Retry :: (Eq a, Num a) => String -> IO a -> IO a-throwErrnoIfMinus1Retry  = throwErrnoIfRetry (== -1)---- | as 'throwErrnoIfMinus1', but discards the result.----throwErrnoIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO ()-throwErrnoIfMinus1Retry_  = throwErrnoIfRetry_ (== -1)---- | as 'throwErrnoIfMinus1Retry', but checks for operations that would block.----throwErrnoIfMinus1RetryMayBlock :: (Eq a, Num a)-                                => String -> IO a -> IO b -> IO a-throwErrnoIfMinus1RetryMayBlock  = throwErrnoIfRetryMayBlock (== -1)---- | as 'throwErrnoIfMinus1RetryMayBlock', but discards the result.----throwErrnoIfMinus1RetryMayBlock_ :: (Eq a, Num a)-                                 => String -> IO a -> IO b -> IO ()-throwErrnoIfMinus1RetryMayBlock_  = throwErrnoIfRetryMayBlock_ (== -1)---- | Throw an 'IOError' corresponding to the current value of 'getErrno'--- if the 'IO' action returns 'nullPtr'.----throwErrnoIfNull :: String -> IO (Ptr a) -> IO (Ptr a)-throwErrnoIfNull  = throwErrnoIf (== nullPtr)---- | Throw an 'IOError' corresponding to the current value of 'getErrno'--- if the 'IO' action returns 'nullPtr',--- but retry in case of an interrupted operation.----throwErrnoIfNullRetry :: String -> IO (Ptr a) -> IO (Ptr a)-throwErrnoIfNullRetry  = throwErrnoIfRetry (== nullPtr)---- | as 'throwErrnoIfNullRetry', but checks for operations that would block.----throwErrnoIfNullRetryMayBlock :: String -> IO (Ptr a) -> IO b -> IO (Ptr a)-throwErrnoIfNullRetryMayBlock  = throwErrnoIfRetryMayBlock (== nullPtr)---- | as 'throwErrno', but exceptions include the given path when appropriate.----throwErrnoPath :: String -> FilePath -> IO a-throwErrnoPath loc path =-  do-    errno <- getErrno-    ioError (errnoToIOError loc errno Nothing (Just path))---- | as 'throwErrnoIf', but exceptions include the given path when---   appropriate.----throwErrnoPathIf :: (a -> Bool) -> String -> FilePath -> IO a -> IO a-throwErrnoPathIf pred loc path f =-  do-    res <- f-    if pred res then throwErrnoPath loc path else return res---- | as 'throwErrnoIf_', but exceptions include the given path when---   appropriate.----throwErrnoPathIf_ :: (a -> Bool) -> String -> FilePath -> IO a -> IO ()-throwErrnoPathIf_ pred loc path f  = void $ throwErrnoPathIf pred loc path f---- | as 'throwErrnoIfNull', but exceptions include the given path when---   appropriate.----throwErrnoPathIfNull :: String -> FilePath -> IO (Ptr a) -> IO (Ptr a)-throwErrnoPathIfNull  = throwErrnoPathIf (== nullPtr)---- | as 'throwErrnoIfMinus1', but exceptions include the given path when---   appropriate.----throwErrnoPathIfMinus1 :: (Eq a, Num a) => String -> FilePath -> IO a -> IO a-throwErrnoPathIfMinus1 = throwErrnoPathIf (== -1)---- | as 'throwErrnoIfMinus1_', but exceptions include the given path when---   appropriate.----throwErrnoPathIfMinus1_ :: (Eq a, Num a) => String -> FilePath -> IO a -> IO ()-throwErrnoPathIfMinus1_  = throwErrnoPathIf_ (== -1)---- conversion of an "errno" value into IO error--- ------------------------------------------------ | Construct an 'IOError' based on the given 'Errno' value.--- The optional information can be used to improve the accuracy of--- error messages.----errnoToIOError  :: String       -- ^ the location where the error occurred-                -> Errno        -- ^ the error number-                -> Maybe Handle -- ^ optional handle associated with the error-                -> Maybe String -- ^ optional filename associated with the error-                -> IOError-errnoToIOError loc errno maybeHdl maybeName = unsafePerformIO $ do-    str <- strerror errno >>= peekCString-    return (IOError maybeHdl errType loc str (Just errno') maybeName)-    where-    Errno errno' = errno-    errType-        | errno == eOK             = OtherError-        | errno == e2BIG           = ResourceExhausted-        | errno == eACCES          = PermissionDenied-        | errno == eADDRINUSE      = ResourceBusy-        | errno == eADDRNOTAVAIL   = UnsupportedOperation-        | errno == eADV            = OtherError-        | errno == eAFNOSUPPORT    = UnsupportedOperation-        | errno == eAGAIN          = ResourceExhausted-        | errno == eALREADY        = AlreadyExists-        | errno == eBADF           = InvalidArgument-        | errno == eBADMSG         = InappropriateType-        | errno == eBADRPC         = OtherError-        | errno == eBUSY           = ResourceBusy-        | errno == eCHILD          = NoSuchThing-        | errno == eCOMM           = ResourceVanished-        | errno == eCONNABORTED    = OtherError-        | errno == eCONNREFUSED    = NoSuchThing-        | errno == eCONNRESET      = ResourceVanished-        | errno == eDEADLK         = ResourceBusy-        | errno == eDESTADDRREQ    = InvalidArgument-        | errno == eDIRTY          = UnsatisfiedConstraints-        | errno == eDOM            = InvalidArgument-        | errno == eDQUOT          = PermissionDenied-        | errno == eEXIST          = AlreadyExists-        | errno == eFAULT          = OtherError-        | errno == eFBIG           = PermissionDenied-        | errno == eFTYPE          = InappropriateType-        | errno == eHOSTDOWN       = NoSuchThing-        | errno == eHOSTUNREACH    = NoSuchThing-        | errno == eIDRM           = ResourceVanished-        | errno == eILSEQ          = InvalidArgument-        | errno == eINPROGRESS     = AlreadyExists-        | errno == eINTR           = Interrupted-        | errno == eINVAL          = InvalidArgument-        | errno == eIO             = HardwareFault-        | errno == eISCONN         = AlreadyExists-        | errno == eISDIR          = InappropriateType-        | errno == eLOOP           = InvalidArgument-        | errno == eMFILE          = ResourceExhausted-        | errno == eMLINK          = ResourceExhausted-        | errno == eMSGSIZE        = ResourceExhausted-        | errno == eMULTIHOP       = UnsupportedOperation-        | errno == eNAMETOOLONG    = InvalidArgument-        | errno == eNETDOWN        = ResourceVanished-        | errno == eNETRESET       = ResourceVanished-        | errno == eNETUNREACH     = NoSuchThing-        | errno == eNFILE          = ResourceExhausted-        | errno == eNOBUFS         = ResourceExhausted-        | errno == eNODATA         = NoSuchThing-        | errno == eNODEV          = UnsupportedOperation-        | errno == eNOENT          = NoSuchThing-        | errno == eNOEXEC         = InvalidArgument-        | errno == eNOLCK          = ResourceExhausted-        | errno == eNOLINK         = ResourceVanished-        | errno == eNOMEM          = ResourceExhausted-        | errno == eNOMSG          = NoSuchThing-        | errno == eNONET          = NoSuchThing-        | errno == eNOPROTOOPT     = UnsupportedOperation-        | errno == eNOSPC          = ResourceExhausted-        | errno == eNOSR           = ResourceExhausted-        | errno == eNOSTR          = InvalidArgument-        | errno == eNOSYS          = UnsupportedOperation-        | errno == eNOTBLK         = InvalidArgument-        | errno == eNOTCONN        = InvalidArgument-        | errno == eNOTDIR         = InappropriateType-        | errno == eNOTEMPTY       = UnsatisfiedConstraints-        | errno == eNOTSOCK        = InvalidArgument-        | errno == eNOTTY          = IllegalOperation-        | errno == eNXIO           = NoSuchThing-        | errno == eOPNOTSUPP      = UnsupportedOperation-        | errno == ePERM           = PermissionDenied-        | errno == ePFNOSUPPORT    = UnsupportedOperation-        | errno == ePIPE           = ResourceVanished-        | errno == ePROCLIM        = PermissionDenied-        | errno == ePROCUNAVAIL    = UnsupportedOperation-        | errno == ePROGMISMATCH   = ProtocolError-        | errno == ePROGUNAVAIL    = UnsupportedOperation-        | errno == ePROTO          = ProtocolError-        | errno == ePROTONOSUPPORT = ProtocolError-        | errno == ePROTOTYPE      = ProtocolError-        | errno == eRANGE          = UnsupportedOperation-        | errno == eREMCHG         = ResourceVanished-        | errno == eREMOTE         = IllegalOperation-        | errno == eROFS           = PermissionDenied-        | errno == eRPCMISMATCH    = ProtocolError-        | errno == eRREMOTE        = IllegalOperation-        | errno == eSHUTDOWN       = IllegalOperation-        | errno == eSOCKTNOSUPPORT = UnsupportedOperation-        | errno == eSPIPE          = UnsupportedOperation-        | errno == eSRCH           = NoSuchThing-        | errno == eSRMNT          = UnsatisfiedConstraints-        | errno == eSTALE          = ResourceVanished-        | errno == eTIME           = TimeExpired-        | errno == eTIMEDOUT       = TimeExpired-        | errno == eTOOMANYREFS    = ResourceExhausted-        | errno == eTXTBSY         = ResourceBusy-        | errno == eUSERS          = ResourceExhausted-        | errno == eWOULDBLOCK     = OtherError-        | errno == eXDEV           = UnsupportedOperation-        | otherwise                = OtherError--foreign import ccall unsafe "string.h" strerror :: Errno -> IO (Ptr CChar)-
− Foreign/C/String.hs
@@ -1,459 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.C.String--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ Utilities for primitive marshalling of C strings.------ The marshalling converts each Haskell character, representing a Unicode--- code point, to one or more bytes in a manner that, by default, is--- determined by the current locale.  As a consequence, no guarantees--- can be made about the relative length of a Haskell string and its--- corresponding C string, and therefore all the marshalling routines--- include memory allocation.  The translation between Unicode and the--- encoding of the current locale may be lossy.-----------------------------------------------------------------------------------module Foreign.C.String (   -- representation of strings in C-  -- * C strings--  CString,-  CStringLen,--  -- ** Using a locale-dependent encoding--  -- | These functions are different from their @CAString@ counterparts-  -- in that they will use an encoding determined by the current locale,-  -- rather than always assuming ASCII.--  -- conversion of C strings into Haskell strings-  ---  peekCString,-  peekCStringLen,--  -- conversion of Haskell strings into C strings-  ---  newCString,-  newCStringLen,--  -- conversion of Haskell strings into C strings using temporary storage-  ---  withCString,-  withCStringLen,--  charIsRepresentable,--  -- ** Using 8-bit characters--  -- | These variants of the above functions are for use with C libraries-  -- that are ignorant of Unicode.  These functions should be used with-  -- care, as a loss of information can occur.--  castCharToCChar,-  castCCharToChar,--  castCharToCUChar,-  castCUCharToChar,-  castCharToCSChar,-  castCSCharToChar,--  peekCAString,-  peekCAStringLen,-  newCAString,-  newCAStringLen,-  withCAString,-  withCAStringLen,--  -- * C wide strings--  -- | These variants of the above functions are for use with C libraries-  -- that encode Unicode using the C @wchar_t@ type in a system-dependent-  -- way.  The only encodings supported are-  ---  -- * UTF-32 (the C compiler defines @__STDC_ISO_10646__@), or-  ---  -- * UTF-16 (as used on Windows systems).--  CWString,-  CWStringLen,--  peekCWString,-  peekCWStringLen,-  newCWString,-  newCWStringLen,-  withCWString,-  withCWStringLen,--  ) where--import Foreign.Marshal.Array-import Foreign.C.Types-import Foreign.Ptr-import Foreign.Storable--import Data.Word--import GHC.Char-import GHC.List-import GHC.Real-import GHC.Num-import GHC.Base--import {-# SOURCE #-} GHC.IO.Encoding-import qualified GHC.Foreign as GHC---------------------------------------------------------------------------------- Strings---- representation of strings in C--- ---------------------------------- | A C string is a reference to an array of C characters terminated by NUL.-type CString    = Ptr CChar---- | A string with explicit length information in bytes instead of a--- terminating NUL (allowing NUL characters in the middle of the string).-type CStringLen = (Ptr CChar, Int)---- exported functions--- ------------------------ * the following routines apply the default conversion when converting the---   C-land character encoding into the Haskell-land character encoding---- | Marshal a NUL terminated C string into a Haskell string.----peekCString    :: CString -> IO String-peekCString s = getForeignEncoding >>= flip GHC.peekCString s---- | Marshal a C string with explicit length into a Haskell string.----peekCStringLen           :: CStringLen -> IO String-peekCStringLen s = getForeignEncoding >>= flip GHC.peekCStringLen s---- | Marshal a Haskell string into a NUL terminated C string.------ * the Haskell string may /not/ contain any NUL characters------ * new storage is allocated for the C string and must be---   explicitly freed using 'Foreign.Marshal.Alloc.free' or---   'Foreign.Marshal.Alloc.finalizerFree'.----newCString :: String -> IO CString-newCString s = getForeignEncoding >>= flip GHC.newCString s---- | Marshal a Haskell string into a C string (ie, character array) with--- explicit length information.------ * new storage is allocated for the C string and must be---   explicitly freed using 'Foreign.Marshal.Alloc.free' or---   'Foreign.Marshal.Alloc.finalizerFree'.----newCStringLen     :: String -> IO CStringLen-newCStringLen s = getForeignEncoding >>= flip GHC.newCStringLen s---- | Marshal a Haskell string into a NUL terminated C string using temporary--- storage.------ * the Haskell string may /not/ contain any NUL characters------ * the memory is freed when the subcomputation terminates (either---   normally or via an exception), so the pointer to the temporary---   storage must /not/ be used after this.----withCString :: String -> (CString -> IO a) -> IO a-withCString s f = getForeignEncoding >>= \enc -> GHC.withCString enc s f---- | Marshal a Haskell string into a C string (ie, character array)--- in temporary storage, with explicit length information.------ * the memory is freed when the subcomputation terminates (either---   normally or via an exception), so the pointer to the temporary---   storage must /not/ be used after this.----withCStringLen         :: String -> (CStringLen -> IO a) -> IO a-withCStringLen s f = getForeignEncoding >>= \enc -> GHC.withCStringLen enc s f---- -- | Determines whether a character can be accurately encoded in a 'CString'.--- -- Unrepresentable characters are converted to '?' or their nearest visual equivalent.-charIsRepresentable :: Char -> IO Bool-charIsRepresentable c = getForeignEncoding >>= flip GHC.charIsRepresentable c---- single byte characters--- ----------------------------   ** NOTE: These routines don't handle conversions! **---- | Convert a C byte, representing a Latin-1 character, to the corresponding--- Haskell character.-castCCharToChar :: CChar -> Char-castCCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8))---- | Convert a Haskell character to a C character.--- This function is only safe on the first 256 characters.-castCharToCChar :: Char -> CChar-castCharToCChar ch = fromIntegral (ord ch)---- | Convert a C @unsigned char@, representing a Latin-1 character, to--- the corresponding Haskell character.-castCUCharToChar :: CUChar -> Char-castCUCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8))---- | Convert a Haskell character to a C @unsigned char@.--- This function is only safe on the first 256 characters.-castCharToCUChar :: Char -> CUChar-castCharToCUChar ch = fromIntegral (ord ch)---- | Convert a C @signed char@, representing a Latin-1 character, to the--- corresponding Haskell character.-castCSCharToChar :: CSChar -> Char-castCSCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8))---- | Convert a Haskell character to a C @signed char@.--- This function is only safe on the first 256 characters.-castCharToCSChar :: Char -> CSChar-castCharToCSChar ch = fromIntegral (ord ch)---- | Marshal a NUL terminated C string into a Haskell string.----peekCAString    :: CString -> IO String-peekCAString cp = do-  l <- lengthArray0 nUL cp-  if l <= 0 then return "" else loop "" (l-1)-  where-    loop s i = do-        xval <- peekElemOff cp i-        let val = castCCharToChar xval-        val `seq` if i <= 0 then return (val:s) else loop (val:s) (i-1)---- | Marshal a C string with explicit length into a Haskell string.----peekCAStringLen           :: CStringLen -> IO String-peekCAStringLen (cp, len)-  | len <= 0  = return "" -- being (too?) nice.-  | otherwise = loop [] (len-1)-  where-    loop acc i = do-         xval <- peekElemOff cp i-         let val = castCCharToChar xval-           -- blow away the coercion ASAP.-         if (val `seq` (i == 0))-          then return (val:acc)-          else loop (val:acc) (i-1)---- | Marshal a Haskell string into a NUL terminated C string.------ * the Haskell string may /not/ contain any NUL characters------ * new storage is allocated for the C string and must be---   explicitly freed using 'Foreign.Marshal.Alloc.free' or---   'Foreign.Marshal.Alloc.finalizerFree'.----newCAString :: String -> IO CString-newCAString str = do-  ptr <- mallocArray0 (length str)-  let-        go [] n     = pokeElemOff ptr n nUL-        go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)-  go str 0-  return ptr---- | Marshal a Haskell string into a C string (ie, character array) with--- explicit length information.------ * new storage is allocated for the C string and must be---   explicitly freed using 'Foreign.Marshal.Alloc.free' or---   'Foreign.Marshal.Alloc.finalizerFree'.----newCAStringLen     :: String -> IO CStringLen-newCAStringLen str = do-  ptr <- mallocArray0 len-  let-        go [] n     = n `seq` return () -- make it strict in n-        go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)-  go str 0-  return (ptr, len)-  where-    len = length str---- | Marshal a Haskell string into a NUL terminated C string using temporary--- storage.------ * the Haskell string may /not/ contain any NUL characters------ * the memory is freed when the subcomputation terminates (either---   normally or via an exception), so the pointer to the temporary---   storage must /not/ be used after this.----withCAString :: String -> (CString -> IO a) -> IO a-withCAString str f =-  allocaArray0 (length str) $ \ptr ->-      let-        go [] n     = pokeElemOff ptr n nUL-        go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)-      in do-      go str 0-      f ptr---- | Marshal a Haskell string into a C string (ie, character array)--- in temporary storage, with explicit length information.------ * the memory is freed when the subcomputation terminates (either---   normally or via an exception), so the pointer to the temporary---   storage must /not/ be used after this.----withCAStringLen         :: String -> (CStringLen -> IO a) -> IO a-withCAStringLen str f    =-  allocaArray len $ \ptr ->-      let-        go [] n     = n `seq` return () -- make it strict in n-        go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)-      in do-      go str 0-      f (ptr,len)-  where-    len = length str---- auxiliary definitions--- -------------------------- C's end of string character----nUL :: CChar-nUL  = 0---- allocate an array to hold the list and pair it with the number of elements-newArrayLen        :: Storable a => [a] -> IO (Ptr a, Int)-newArrayLen xs      = do-  a <- newArray xs-  return (a, length xs)---------------------------------------------------------------------------------- Wide strings---- representation of wide strings in C--- --------------------------------------- | A C wide string is a reference to an array of C wide characters--- terminated by NUL.-type CWString    = Ptr CWchar---- | A wide character string with explicit length information in 'CWchar's--- instead of a terminating NUL (allowing NUL characters in the middle--- of the string).-type CWStringLen = (Ptr CWchar, Int)---- | Marshal a NUL terminated C wide string into a Haskell string.----peekCWString    :: CWString -> IO String-peekCWString cp  = do-  cs <- peekArray0 wNUL cp-  return (cWcharsToChars cs)---- | Marshal a C wide string with explicit length into a Haskell string.----peekCWStringLen           :: CWStringLen -> IO String-peekCWStringLen (cp, len)  = do-  cs <- peekArray len cp-  return (cWcharsToChars cs)---- | Marshal a Haskell string into a NUL terminated C wide string.------ * the Haskell string may /not/ contain any NUL characters------ * new storage is allocated for the C wide string and must---   be explicitly freed using 'Foreign.Marshal.Alloc.free' or---   'Foreign.Marshal.Alloc.finalizerFree'.----newCWString :: String -> IO CWString-newCWString  = newArray0 wNUL . charsToCWchars---- | Marshal a Haskell string into a C wide string (ie, wide character array)--- with explicit length information.------ * new storage is allocated for the C wide string and must---   be explicitly freed using 'Foreign.Marshal.Alloc.free' or---   'Foreign.Marshal.Alloc.finalizerFree'.----newCWStringLen     :: String -> IO CWStringLen-newCWStringLen str  = newArrayLen (charsToCWchars str)---- | Marshal a Haskell string into a NUL terminated C wide string using--- temporary storage.------ * the Haskell string may /not/ contain any NUL characters------ * the memory is freed when the subcomputation terminates (either---   normally or via an exception), so the pointer to the temporary---   storage must /not/ be used after this.----withCWString :: String -> (CWString -> IO a) -> IO a-withCWString  = withArray0 wNUL . charsToCWchars---- | Marshal a Haskell string into a C wide string (i.e. wide--- character array) in temporary storage, with explicit length--- information.------ * the memory is freed when the subcomputation terminates (either---   normally or via an exception), so the pointer to the temporary---   storage must /not/ be used after this.----withCWStringLen         :: String -> (CWStringLen -> IO a) -> IO a-withCWStringLen str f    =-  withArrayLen (charsToCWchars str) $ \ len ptr -> f (ptr, len)---- auxiliary definitions--- ------------------------wNUL :: CWchar-wNUL = 0--cWcharsToChars :: [CWchar] -> [Char]-charsToCWchars :: [Char] -> [CWchar]--#ifdef mingw32_HOST_OS---- On Windows, wchar_t is 16 bits wide and CWString uses the UTF-16 encoding.---- coding errors generate Chars in the surrogate range-cWcharsToChars = map chr . fromUTF16 . map fromIntegral- where-  fromUTF16 (c1:c2:wcs)-    | 0xd800 <= c1 && c1 <= 0xdbff && 0xdc00 <= c2 && c2 <= 0xdfff =-      ((c1 - 0xd800)*0x400 + (c2 - 0xdc00) + 0x10000) : fromUTF16 wcs-  fromUTF16 (c:wcs) = c : fromUTF16 wcs-  fromUTF16 [] = []--charsToCWchars = foldr utf16Char [] . map ord- where-  utf16Char c wcs-    | c < 0x10000 = fromIntegral c : wcs-    | otherwise   = let c' = c - 0x10000 in-                    fromIntegral (c' `div` 0x400 + 0xd800) :-                    fromIntegral (c' `mod` 0x400 + 0xdc00) : wcs--#else /* !mingw32_HOST_OS */--cWcharsToChars xs  = map castCWcharToChar xs-charsToCWchars xs  = map castCharToCWchar xs---- These conversions only make sense if __STDC_ISO_10646__ is defined--- (meaning that wchar_t is ISO 10646, aka Unicode)--castCWcharToChar :: CWchar -> Char-castCWcharToChar ch = chr (fromIntegral ch )--castCharToCWchar :: Char -> CWchar-castCharToCWchar ch = fromIntegral (ord ch)--#endif /* !mingw32_HOST_OS */-
− Foreign/C/Types.hs
@@ -1,259 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, GeneralizedNewtypeDeriving,-             AutoDeriveTypeable, StandaloneDeriving #-}-{-# OPTIONS_GHC -fno-warn-unused-binds #-}--- XXX -fno-warn-unused-binds stops us warning about unused constructors,--- but really we should just remove them if we don't want them---------------------------------------------------------------------------------- |--- Module      :  Foreign.C.Types--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ Mapping of C types to corresponding Haskell types.-----------------------------------------------------------------------------------module Foreign.C.Types-        ( -- * Representations of C types-          -- $ctypes--          -- ** Integral types-          -- | These types are are represented as @newtype@s of-          -- types in "Data.Int" and "Data.Word", and are instances of-          -- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',-          -- 'Prelude.Show', 'Prelude.Enum', 'Typeable', 'Storable',-          -- 'Prelude.Bounded', 'Prelude.Real', 'Prelude.Integral' and-          -- 'Bits'.-          CChar(..),    CSChar(..),   CUChar(..)-        , CShort(..),   CUShort(..),  CInt(..),      CUInt(..)-        , CLong(..),    CULong(..)-        , CPtrdiff(..), CSize(..),    CWchar(..),    CSigAtomic(..)-        , CLLong(..),   CULLong(..)-        , CIntPtr(..),  CUIntPtr(..), CIntMax(..),   CUIntMax(..)--          -- ** Numeric types-          -- | These types are represented as @newtype@s of basic-          -- foreign types, and are instances of-          -- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',-          -- 'Prelude.Show', 'Prelude.Enum', 'Typeable' and 'Storable'.-        , CClock(..),   CTime(..),    CUSeconds(..), CSUSeconds(..)--        -- extracted from CTime, because we don't want this comment in-        -- the Haskell language reports:--        -- | To convert 'CTime' to 'Data.Time.UTCTime', use the following:-        ---        -- > \t -> posixSecondsToUTCTime (realToFrac t :: POSIXTime)-        ----          -- ** Floating types-          -- | These types are are represented as @newtype@s of-          -- 'Prelude.Float' and 'Prelude.Double', and are instances of-          -- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',-          -- 'Prelude.Show', 'Prelude.Enum', 'Typeable', 'Storable',-          -- 'Prelude.Real', 'Prelude.Fractional', 'Prelude.Floating',-          -- 'Prelude.RealFrac' and 'Prelude.RealFloat'.-        , CFloat(..),   CDouble(..)-        -- XXX GHC doesn't support CLDouble yet-        -- , CLDouble(..)--          -- ** Other types--          -- Instances of: Eq and Storable-        , CFile,        CFpos,     CJmpBuf-        ) where--import Foreign.Storable-import Data.Bits        ( Bits(..), FiniteBits(..) )-import Data.Int         ( Int8,  Int16,  Int32,  Int64  )-import Data.Word        ( Word8, Word16, Word32, Word64 )-import Data.Typeable--import GHC.Base-import GHC.Float-import GHC.Enum-import GHC.Real-import GHC.Show-import GHC.Read-import GHC.Num--#include "HsBaseConfig.h"-#include "CTypes.h"---- | Haskell type representing the C @char@ type.-INTEGRAL_TYPE(CChar,HTYPE_CHAR)--- | Haskell type representing the C @signed char@ type.-INTEGRAL_TYPE(CSChar,HTYPE_SIGNED_CHAR)--- | Haskell type representing the C @unsigned char@ type.-INTEGRAL_TYPE(CUChar,HTYPE_UNSIGNED_CHAR)---- | Haskell type representing the C @short@ type.-INTEGRAL_TYPE(CShort,HTYPE_SHORT)--- | Haskell type representing the C @unsigned short@ type.-INTEGRAL_TYPE(CUShort,HTYPE_UNSIGNED_SHORT)---- | Haskell type representing the C @int@ type.-INTEGRAL_TYPE(CInt,HTYPE_INT)--- | Haskell type representing the C @unsigned int@ type.-INTEGRAL_TYPE(CUInt,HTYPE_UNSIGNED_INT)---- | Haskell type representing the C @long@ type.-INTEGRAL_TYPE(CLong,HTYPE_LONG)--- | Haskell type representing the C @unsigned long@ type.-INTEGRAL_TYPE(CULong,HTYPE_UNSIGNED_LONG)---- | Haskell type representing the C @long long@ type.-INTEGRAL_TYPE(CLLong,HTYPE_LONG_LONG)--- | Haskell type representing the C @unsigned long long@ type.-INTEGRAL_TYPE(CULLong,HTYPE_UNSIGNED_LONG_LONG)--{-# RULES-"fromIntegral/a->CChar"   fromIntegral = \x -> CChar   (fromIntegral x)-"fromIntegral/a->CSChar"  fromIntegral = \x -> CSChar  (fromIntegral x)-"fromIntegral/a->CUChar"  fromIntegral = \x -> CUChar  (fromIntegral x)-"fromIntegral/a->CShort"  fromIntegral = \x -> CShort  (fromIntegral x)-"fromIntegral/a->CUShort" fromIntegral = \x -> CUShort (fromIntegral x)-"fromIntegral/a->CInt"    fromIntegral = \x -> CInt    (fromIntegral x)-"fromIntegral/a->CUInt"   fromIntegral = \x -> CUInt   (fromIntegral x)-"fromIntegral/a->CLong"   fromIntegral = \x -> CLong   (fromIntegral x)-"fromIntegral/a->CULong"  fromIntegral = \x -> CULong  (fromIntegral x)-"fromIntegral/a->CLLong"  fromIntegral = \x -> CLLong  (fromIntegral x)-"fromIntegral/a->CULLong" fromIntegral = \x -> CULLong (fromIntegral x)--"fromIntegral/CChar->a"   fromIntegral = \(CChar   x) -> fromIntegral x-"fromIntegral/CSChar->a"  fromIntegral = \(CSChar  x) -> fromIntegral x-"fromIntegral/CUChar->a"  fromIntegral = \(CUChar  x) -> fromIntegral x-"fromIntegral/CShort->a"  fromIntegral = \(CShort  x) -> fromIntegral x-"fromIntegral/CUShort->a" fromIntegral = \(CUShort x) -> fromIntegral x-"fromIntegral/CInt->a"    fromIntegral = \(CInt    x) -> fromIntegral x-"fromIntegral/CUInt->a"   fromIntegral = \(CUInt   x) -> fromIntegral x-"fromIntegral/CLong->a"   fromIntegral = \(CLong   x) -> fromIntegral x-"fromIntegral/CULong->a"  fromIntegral = \(CULong  x) -> fromIntegral x-"fromIntegral/CLLong->a"  fromIntegral = \(CLLong  x) -> fromIntegral x-"fromIntegral/CULLong->a" fromIntegral = \(CULLong x) -> fromIntegral x- #-}---- | Haskell type representing the C @float@ type.-FLOATING_TYPE(CFloat,HTYPE_FLOAT)--- | Haskell type representing the C @double@ type.-FLOATING_TYPE(CDouble,HTYPE_DOUBLE)--- XXX GHC doesn't support CLDouble yet--{-# RULES-"realToFrac/a->CFloat"    realToFrac = \x -> CFloat   (realToFrac x)-"realToFrac/a->CDouble"   realToFrac = \x -> CDouble  (realToFrac x)--"realToFrac/CFloat->a"    realToFrac = \(CFloat   x) -> realToFrac x-"realToFrac/CDouble->a"   realToFrac = \(CDouble  x) -> realToFrac x- #-}---- GHC doesn't support CLDouble yet--- "realToFrac/a->CLDouble"  realToFrac = \x -> CLDouble (realToFrac x)--- "realToFrac/CLDouble->a"  realToFrac = \(CLDouble x) -> realToFrac x---- | Haskell type representing the C @ptrdiff_t@ type.-INTEGRAL_TYPE(CPtrdiff,HTYPE_PTRDIFF_T)--- | Haskell type representing the C @size_t@ type.-INTEGRAL_TYPE(CSize,HTYPE_SIZE_T)--- | Haskell type representing the C @wchar_t@ type.-INTEGRAL_TYPE(CWchar,HTYPE_WCHAR_T)--- | Haskell type representing the C @sig_atomic_t@ type.-INTEGRAL_TYPE(CSigAtomic,HTYPE_SIG_ATOMIC_T)--{-# RULES-"fromIntegral/a->CPtrdiff"   fromIntegral = \x -> CPtrdiff   (fromIntegral x)-"fromIntegral/a->CSize"      fromIntegral = \x -> CSize      (fromIntegral x)-"fromIntegral/a->CWchar"     fromIntegral = \x -> CWchar     (fromIntegral x)-"fromIntegral/a->CSigAtomic" fromIntegral = \x -> CSigAtomic (fromIntegral x)--"fromIntegral/CPtrdiff->a"   fromIntegral = \(CPtrdiff   x) -> fromIntegral x-"fromIntegral/CSize->a"      fromIntegral = \(CSize      x) -> fromIntegral x-"fromIntegral/CWchar->a"     fromIntegral = \(CWchar     x) -> fromIntegral x-"fromIntegral/CSigAtomic->a" fromIntegral = \(CSigAtomic x) -> fromIntegral x- #-}---- | Haskell type representing the C @clock_t@ type.-ARITHMETIC_TYPE(CClock,HTYPE_CLOCK_T)--- | Haskell type representing the C @time_t@ type.-ARITHMETIC_TYPE(CTime,HTYPE_TIME_T)--- | Haskell type representing the C @useconds_t@ type.------ @since 4.4.0.0-ARITHMETIC_TYPE(CUSeconds,HTYPE_USECONDS_T)--- | Haskell type representing the C @suseconds_t@ type.------ @since 4.4.0.0-ARITHMETIC_TYPE(CSUSeconds,HTYPE_SUSECONDS_T)---- FIXME: Implement and provide instances for Eq and Storable--- | Haskell type representing the C @FILE@ type.-data CFile = CFile--- | Haskell type representing the C @fpos_t@ type.-data CFpos = CFpos--- | Haskell type representing the C @jmp_buf@ type.-data CJmpBuf = CJmpBuf--INTEGRAL_TYPE(CIntPtr,HTYPE_INTPTR_T)-INTEGRAL_TYPE(CUIntPtr,HTYPE_UINTPTR_T)-INTEGRAL_TYPE(CIntMax,HTYPE_INTMAX_T)-INTEGRAL_TYPE(CUIntMax,HTYPE_UINTMAX_T)--{-# RULES-"fromIntegral/a->CIntPtr"  fromIntegral = \x -> CIntPtr  (fromIntegral x)-"fromIntegral/a->CUIntPtr" fromIntegral = \x -> CUIntPtr (fromIntegral x)-"fromIntegral/a->CIntMax"  fromIntegral = \x -> CIntMax  (fromIntegral x)-"fromIntegral/a->CUIntMax" fromIntegral = \x -> CUIntMax (fromIntegral x)- #-}---- C99 types which are still missing include:--- wint_t, wctrans_t, wctype_t--{- $ctypes--These types are needed to accurately represent C function prototypes,-in order to access C library interfaces in Haskell.  The Haskell system-is not required to represent those types exactly as C does, but the-following guarantees are provided concerning a Haskell type @CT@-representing a C type @t@:--* If a C function prototype has @t@ as an argument or result type, the-  use of @CT@ in the corresponding position in a foreign declaration-  permits the Haskell program to access the full range of values encoded-  by the C type; and conversely, any Haskell value for @CT@ has a valid-  representation in C.--* @'sizeOf' ('Prelude.undefined' :: CT)@ will yield the same value as-  @sizeof (t)@ in C.--* @'alignment' ('Prelude.undefined' :: CT)@ matches the alignment-  constraint enforced by the C implementation for @t@.--* The members 'peek' and 'poke' of the 'Storable' class map all values-  of @CT@ to the corresponding value of @t@ and vice versa.--* When an instance of 'Prelude.Bounded' is defined for @CT@, the values-  of 'Prelude.minBound' and 'Prelude.maxBound' coincide with @t_MIN@-  and @t_MAX@ in C.--* When an instance of 'Prelude.Eq' or 'Prelude.Ord' is defined for @CT@,-  the predicates defined by the type class implement the same relation-  as the corresponding predicate in C on @t@.--* When an instance of 'Prelude.Num', 'Prelude.Read', 'Prelude.Integral',-  'Prelude.Fractional', 'Prelude.Floating', 'Prelude.RealFrac', or-  'Prelude.RealFloat' is defined for @CT@, the arithmetic operations-  defined by the type class implement the same function as the-  corresponding arithmetic operations (if available) in C on @t@.--* When an instance of 'Bits' is defined for @CT@, the bitwise operation-  defined by the type class implement the same function as the-  corresponding bitwise operation in C on @t@.---}-
− Foreign/Concurrent.hs
@@ -1,51 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Concurrent--- Copyright   :  (c) The University of Glasgow 2003--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  non-portable (requires concurrency)------ FFI datatypes and operations that use or require concurrency (GHC only).-----------------------------------------------------------------------------------module Foreign.Concurrent-  (-        -- * Concurrency-based 'ForeignPtr' operations--        -- | These functions generalize their namesakes in the portable-        -- "Foreign.ForeignPtr" module by allowing arbitrary 'IO' actions-        -- as finalizers.  These finalizers necessarily run in a separate-        -- thread, cf. /Destructors, Finalizers and Synchronization/,-        -- by Hans Boehm, /POPL/, 2003.--        newForeignPtr,-        addForeignPtrFinalizer,-  ) where--import GHC.IO         ( IO )-import GHC.Ptr        ( Ptr )-import GHC.ForeignPtr ( ForeignPtr )-import qualified GHC.ForeignPtr--newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)--- ^Turns a plain memory reference into a foreign object by associating--- a finalizer - given by the monadic operation - with the reference.--- The finalizer will be executed after the last reference to the--- foreign object is dropped.  There is no guarantee of promptness, and--- in fact there is no guarantee that the finalizer will eventually--- run at all.-newForeignPtr = GHC.ForeignPtr.newConcForeignPtr--addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO ()--- ^This function adds a finalizer to the given 'ForeignPtr'.--- The finalizer will run after the last reference to the foreign object--- is dropped, but /before/ all previously registered finalizers for the--- same object.-addForeignPtrFinalizer = GHC.ForeignPtr.addForeignPtrConcFinalizer
− Foreign/ForeignPtr.hs
@@ -1,47 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.ForeignPtr--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ The 'ForeignPtr' type and operations.  This module is part of the--- Foreign Function Interface (FFI) and will usually be imported via--- the "Foreign" module.-----------------------------------------------------------------------------------module Foreign.ForeignPtr ( -        -- * Finalised data pointers-          ForeignPtr-        , FinalizerPtr-        , FinalizerEnvPtr--        -- ** Basic operations-        , newForeignPtr-        , newForeignPtr_-        , addForeignPtrFinalizer-        , newForeignPtrEnv-        , addForeignPtrFinalizerEnv-        , withForeignPtr-        , finalizeForeignPtr--        -- ** Low-level operations-        , touchForeignPtr-        , castForeignPtr--        -- ** Allocating managed memory-        , mallocForeignPtr-        , mallocForeignPtrBytes-        , mallocForeignPtrArray-        , mallocForeignPtrArray0-    ) where--import Foreign.ForeignPtr.Imp-
− Foreign/ForeignPtr/Imp.hs
@@ -1,120 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.ForeignPtr.Imp--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ The 'ForeignPtr' type and operations.  This module is part of the--- Foreign Function Interface (FFI) and will usually be imported via--- the "Foreign" module.-----------------------------------------------------------------------------------module Foreign.ForeignPtr.Imp-        ( -        -- * Finalised data pointers-          ForeignPtr-        , FinalizerPtr-        , FinalizerEnvPtr--        -- ** Basic operations-        , newForeignPtr-        , newForeignPtr_-        , addForeignPtrFinalizer-        , newForeignPtrEnv-        , addForeignPtrFinalizerEnv-        , withForeignPtr-        , finalizeForeignPtr--        -- ** Low-level operations-        , unsafeForeignPtrToPtr-        , touchForeignPtr-        , castForeignPtr--        -- ** Allocating managed memory-        , mallocForeignPtr-        , mallocForeignPtrBytes-        , mallocForeignPtrArray-        , mallocForeignPtrArray0-        ) -        where--import Foreign.Ptr-import Foreign.Storable ( Storable(sizeOf) )--import GHC.Base-import GHC.Num-import GHC.ForeignPtr--newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)--- ^Turns a plain memory reference into a foreign pointer, and--- associates a finalizer with the reference.  The finalizer will be--- executed after the last reference to the foreign object is dropped.--- There is no guarantee of promptness, however the finalizer will be--- executed before the program exits.-newForeignPtr finalizer p-  = do fObj <- newForeignPtr_ p-       addForeignPtrFinalizer finalizer fObj-       return fObj--withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b--- ^This is a way to look at the pointer living inside a--- foreign object.  This function takes a function which is--- applied to that pointer. The resulting 'IO' action is then--- executed. The foreign object is kept alive at least during--- the whole action, even if it is not used directly--- inside. Note that it is not safe to return the pointer from--- the action and use it after the action completes. All uses--- of the pointer should be inside the--- 'withForeignPtr' bracket.  The reason for--- this unsafeness is the same as for--- 'unsafeForeignPtrToPtr' below: the finalizer--- may run earlier than expected, because the compiler can only--- track usage of the 'ForeignPtr' object, not--- a 'Ptr' object made from it.------ This function is normally used for marshalling data to--- or from the object pointed to by the--- 'ForeignPtr', using the operations from the--- 'Storable' class.-withForeignPtr fo io-  = do r <- io (unsafeForeignPtrToPtr fo)-       touchForeignPtr fo-       return r---- | This variant of 'newForeignPtr' adds a finalizer that expects an--- environment in addition to the finalized pointer.  The environment--- that will be passed to the finalizer is fixed by the second argument to--- 'newForeignPtrEnv'.-newForeignPtrEnv ::-    FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)-newForeignPtrEnv finalizer env p-  = do fObj <- newForeignPtr_ p-       addForeignPtrFinalizerEnv finalizer env fObj-       return fObj---- | This function is similar to 'Foreign.Marshal.Array.mallocArray',--- but yields a memory area that has a finalizer attached that releases--- the memory area.  As with 'mallocForeignPtr', it is not guaranteed that--- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.-mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)-mallocForeignPtrArray  = doMalloc undefined-  where-    doMalloc            :: Storable b => b -> Int -> IO (ForeignPtr b)-    doMalloc dummy size  = mallocForeignPtrBytes (size * sizeOf dummy)---- | This function is similar to 'Foreign.Marshal.Array.mallocArray0',--- but yields a memory area that has a finalizer attached that releases--- the memory area.  As with 'mallocForeignPtr', it is not guaranteed that--- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.-mallocForeignPtrArray0      :: Storable a => Int -> IO (ForeignPtr a)-mallocForeignPtrArray0 size  = mallocForeignPtrArray (size + 1)-
− Foreign/ForeignPtr/Safe.hs
@@ -1,49 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.ForeignPtr.Safe--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ The 'ForeignPtr' type and operations.  This module is part of the--- Foreign Function Interface (FFI) and will usually be imported via--- the "Foreign" module.------ Safe API Only.-----------------------------------------------------------------------------------module Foreign.ForeignPtr.Safe {-# DEPRECATED "Safe is now the default, please use Foreign.ForeignPtr instead" #-} (-        -- * Finalised data pointers-          ForeignPtr-        , FinalizerPtr-        , FinalizerEnvPtr--        -- ** Basic operations-        , newForeignPtr-        , newForeignPtr_-        , addForeignPtrFinalizer-        , newForeignPtrEnv-        , addForeignPtrFinalizerEnv-        , withForeignPtr-        , finalizeForeignPtr--        -- ** Low-level operations-        , touchForeignPtr-        , castForeignPtr--        -- ** Allocating managed memory-        , mallocForeignPtr-        , mallocForeignPtrBytes-        , mallocForeignPtrArray-        , mallocForeignPtrArray0-    ) where--import Foreign.ForeignPtr.Imp-
− Foreign/ForeignPtr/Unsafe.hs
@@ -1,28 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.ForeignPtr.Unsafe--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ The 'ForeignPtr' type and operations.  This module is part of the--- Foreign Function Interface (FFI) and will usually be imported via--- the "Foreign" module.------ Unsafe API Only.-----------------------------------------------------------------------------------module Foreign.ForeignPtr.Unsafe (-        -- ** Unsafe low-level operations-        unsafeForeignPtrToPtr,-    ) where--import Foreign.ForeignPtr.Imp-
− Foreign/Marshal.hs
@@ -1,34 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Marshal--- Copyright   :  (c) The FFI task force 2003--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ Marshalling support-----------------------------------------------------------------------------------module Foreign.Marshal-        (-         -- | The module "Foreign.Marshal.Safe" re-exports the other modules in the-         -- @Foreign.Marshal@ hierarchy (except for @Foreign.Marshal.Unsafe@):-          module Foreign.Marshal.Alloc-        , module Foreign.Marshal.Array-        , module Foreign.Marshal.Error-        , module Foreign.Marshal.Pool-        , module Foreign.Marshal.Utils-        ) where--import Foreign.Marshal.Alloc-import Foreign.Marshal.Array-import Foreign.Marshal.Error-import Foreign.Marshal.Pool-import Foreign.Marshal.Utils-
− Foreign/Marshal/Alloc.hs
@@ -1,226 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Marshal.Alloc--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ The module "Foreign.Marshal.Alloc" provides operations to allocate and--- deallocate blocks of raw memory (i.e., unstructured chunks of memory--- outside of the area maintained by the Haskell storage manager).  These--- memory blocks are commonly used to pass compound data structures to--- foreign functions or to provide space in which compound result values--- are obtained from foreign functions.--- --- If any of the allocation functions fails, an exception is thrown.--- In some cases, memory exhaustion may mean the process is terminated.--- If 'free' or 'reallocBytes' is applied to a memory area--- that has been allocated with 'alloca' or 'allocaBytes', the--- behaviour is undefined.  Any further access to memory areas allocated with--- 'alloca' or 'allocaBytes', after the computation that was passed to--- the allocation function has terminated, leads to undefined behaviour.  Any--- further access to the memory area referenced by a pointer passed to--- 'realloc', 'reallocBytes', or 'free' entails undefined--- behaviour.--- --- All storage allocated by functions that allocate based on a /size in bytes/--- must be sufficiently aligned for any of the basic foreign types--- that fits into the newly allocated storage. All storage allocated by--- functions that allocate based on a specific type must be sufficiently--- aligned for that type. Array allocation routines need to obey the same--- alignment constraints for each array element.-----------------------------------------------------------------------------------module Foreign.Marshal.Alloc (-  -- * Memory allocation-  -- ** Local allocation-  alloca,-  allocaBytes,-  allocaBytesAligned,--  -- ** Dynamic allocation-  malloc,-  mallocBytes,--  calloc,-  callocBytes,--  realloc,-  reallocBytes,--  free,-  finalizerFree-) where--import Data.Maybe-import Foreign.C.Types          ( CSize(..) )-import Foreign.Storable         ( Storable(sizeOf,alignment) )-import Foreign.ForeignPtr       ( FinalizerPtr )-import GHC.IO.Exception-import GHC.Real-import GHC.Ptr-import GHC.Base---- exported functions--- ---------------------- |Allocate a block of memory that is sufficient to hold values of type--- @a@.  The size of the area allocated is determined by the 'sizeOf'--- method from the instance of 'Storable' for the appropriate type.------ The memory may be deallocated using 'free' or 'finalizerFree' when--- no longer required.----{-# INLINE malloc #-}-malloc :: Storable a => IO (Ptr a)-malloc  = doMalloc undefined-  where-    doMalloc       :: Storable b => b -> IO (Ptr b)-    doMalloc dummy  = mallocBytes (sizeOf dummy)---- |Like 'malloc' but memory is filled with bytes of value zero.----{-# INLINE calloc #-}-calloc :: Storable a => IO (Ptr a)-calloc = doCalloc undefined-  where-    doCalloc       :: Storable b => b -> IO (Ptr b)-    doCalloc dummy = callocBytes (sizeOf dummy)---- |Allocate a block of memory of the given number of bytes.--- The block of memory is sufficiently aligned for any of the basic--- foreign types that fits into a memory block of the allocated size.------ The memory may be deallocated using 'free' or 'finalizerFree' when--- no longer required.----mallocBytes      :: Int -> IO (Ptr a)-mallocBytes size  = failWhenNULL "malloc" (_malloc (fromIntegral size))---- |Llike 'mallocBytes' but memory is filled with bytes of value zero.----callocBytes :: Int -> IO (Ptr a)-callocBytes size = failWhenNULL "calloc" $ _calloc 1 (fromIntegral size)---- |@'alloca' f@ executes the computation @f@, passing as argument--- a pointer to a temporarily allocated block of memory sufficient to--- hold values of type @a@.------ The memory is freed when @f@ terminates (either normally or via an--- exception), so the pointer passed to @f@ must /not/ be used after this.----{-# INLINE alloca #-}-alloca :: Storable a => (Ptr a -> IO b) -> IO b-alloca  = doAlloca undefined-  where-    doAlloca       :: Storable a' => a' -> (Ptr a' -> IO b') -> IO b'-    doAlloca dummy  = allocaBytesAligned (sizeOf dummy) (alignment dummy)---- |@'allocaBytes' n f@ executes the computation @f@, passing as argument--- a pointer to a temporarily allocated block of memory of @n@ bytes.--- The block of memory is sufficiently aligned for any of the basic--- foreign types that fits into a memory block of the allocated size.------ The memory is freed when @f@ terminates (either normally or via an--- exception), so the pointer passed to @f@ must /not/ be used after this.----allocaBytes :: Int -> (Ptr a -> IO b) -> IO b-allocaBytes (I# size) action = IO $ \ s0 ->-     case newPinnedByteArray# size s0      of { (# s1, mbarr# #) ->-     case unsafeFreezeByteArray# mbarr# s1 of { (# s2, barr#  #) ->-     let addr = Ptr (byteArrayContents# barr#) in-     case action addr     of { IO action' ->-     case action' s2      of { (# s3, r #) ->-     case touch# barr# s3 of { s4 ->-     (# s4, r #)-  }}}}}--allocaBytesAligned :: Int -> Int -> (Ptr a -> IO b) -> IO b-allocaBytesAligned (I# size) (I# align) action = IO $ \ s0 ->-     case newAlignedPinnedByteArray# size align s0 of { (# s1, mbarr# #) ->-     case unsafeFreezeByteArray# mbarr# s1 of { (# s2, barr#  #) ->-     let addr = Ptr (byteArrayContents# barr#) in-     case action addr     of { IO action' ->-     case action' s2      of { (# s3, r #) ->-     case touch# barr# s3 of { s4 ->-     (# s4, r #)-  }}}}}---- |Resize a memory area that was allocated with 'malloc' or 'mallocBytes'--- to the size needed to store values of type @b@.  The returned pointer--- may refer to an entirely different memory area, but will be suitably--- aligned to hold values of type @b@.  The contents of the referenced--- memory area will be the same as of the original pointer up to the--- minimum of the original size and the size of values of type @b@.------ If the argument to 'realloc' is 'nullPtr', 'realloc' behaves like--- 'malloc'.----realloc :: Storable b => Ptr a -> IO (Ptr b)-realloc  = doRealloc undefined-  where-    doRealloc           :: Storable b' => b' -> Ptr a' -> IO (Ptr b')-    doRealloc dummy ptr  = let-                             size = fromIntegral (sizeOf dummy)-                           in-                           failWhenNULL "realloc" (_realloc ptr size)---- |Resize a memory area that was allocated with 'malloc' or 'mallocBytes'--- to the given size.  The returned pointer may refer to an entirely--- different memory area, but will be sufficiently aligned for any of the--- basic foreign types that fits into a memory block of the given size.--- The contents of the referenced memory area will be the same as of--- the original pointer up to the minimum of the original size and the--- given size.------ If the pointer argument to 'reallocBytes' is 'nullPtr', 'reallocBytes'--- behaves like 'malloc'.  If the requested size is 0, 'reallocBytes'--- behaves like 'free'.----reallocBytes          :: Ptr a -> Int -> IO (Ptr a)-reallocBytes ptr 0     = do free ptr; return nullPtr-reallocBytes ptr size  = -  failWhenNULL "realloc" (_realloc ptr (fromIntegral size))---- |Free a block of memory that was allocated with 'malloc',--- 'mallocBytes', 'realloc', 'reallocBytes', 'Foreign.Marshal.Utils.new'--- or any of the @new@/X/ functions in "Foreign.Marshal.Array" or--- "Foreign.C.String".----free :: Ptr a -> IO ()-free  = _free----- auxilliary routines--- ----------------------- asserts that the pointer returned from the action in the second argument is--- non-null----failWhenNULL :: String -> IO (Ptr a) -> IO (Ptr a)-failWhenNULL name f = do-   addr <- f-   if addr == nullPtr-      then ioError (IOError Nothing ResourceExhausted name -                                        "out of memory" Nothing Nothing)-      else return addr---- basic C routines needed for memory allocation----foreign import ccall unsafe "stdlib.h malloc"  _malloc  ::          CSize -> IO (Ptr a)-foreign import ccall unsafe "stdlib.h calloc"  _calloc  :: CSize -> CSize -> IO (Ptr a)-foreign import ccall unsafe "stdlib.h realloc" _realloc :: Ptr a -> CSize -> IO (Ptr b)-foreign import ccall unsafe "stdlib.h free"    _free    :: Ptr a -> IO ()---- | A pointer to a foreign function equivalent to 'free', which may be--- used as a finalizer (cf 'Foreign.ForeignPtr.ForeignPtr') for storage--- allocated with 'malloc', 'mallocBytes', 'realloc' or 'reallocBytes'.-foreign import ccall unsafe "stdlib.h &free" finalizerFree :: FinalizerPtr a-
− Foreign/Marshal/Array.hs
@@ -1,281 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Marshal.Array--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ Marshalling support: routines allocating, storing, and retrieving Haskell--- lists that are represented as arrays in the foreign language-----------------------------------------------------------------------------------module Foreign.Marshal.Array (-  -- * Marshalling arrays--  -- ** Allocation-  ---  mallocArray,-  mallocArray0,--  allocaArray,-  allocaArray0,--  reallocArray,-  reallocArray0,--  callocArray,-  callocArray0,--  -- ** Marshalling-  ---  peekArray,-  peekArray0,--  pokeArray,-  pokeArray0,--  -- ** Combined allocation and marshalling-  ---  newArray,-  newArray0,--  withArray,-  withArray0,--  withArrayLen,-  withArrayLen0,--  -- ** Copying--  -- | (argument order: destination, source)-  copyArray,-  moveArray,--  -- ** Finding the length-  ---  lengthArray0,--  -- ** Indexing-  ---  advancePtr,-) where--import Foreign.Ptr      (Ptr, plusPtr)-import Foreign.Storable (Storable(alignment,sizeOf,peekElemOff,pokeElemOff))-import Foreign.Marshal.Alloc (mallocBytes, callocBytes, allocaBytesAligned, reallocBytes)-import Foreign.Marshal.Utils (copyBytes, moveBytes)--import GHC.Num-import GHC.List-import GHC.Base---- allocation--- -------------- |Allocate storage for the given number of elements of a storable type--- (like 'Foreign.Marshal.Alloc.malloc', but for multiple elements).----mallocArray :: Storable a => Int -> IO (Ptr a)-mallocArray  = doMalloc undefined-  where-    doMalloc            :: Storable a' => a' -> Int -> IO (Ptr a')-    doMalloc dummy size  = mallocBytes (size * sizeOf dummy)---- |Like 'mallocArray', but add an extra position to hold a special--- termination element.----mallocArray0      :: Storable a => Int -> IO (Ptr a)-mallocArray0 size  = mallocArray (size + 1)---- |Like 'mallocArray', but allocated memory is filled with bytes of value zero.----callocArray :: Storable a => Int -> IO (Ptr a)-callocArray  = doCalloc undefined-  where-    doCalloc :: Storable a' => a' -> Int -> IO (Ptr a')-    doCalloc dummy size  = callocBytes (size * sizeOf dummy)---- |Like 'callocArray0', but allocated memory is filled with bytes of value--- zero.----callocArray0 :: Storable a => Int -> IO (Ptr a)-callocArray0 size  = callocArray (size + 1)---- |Temporarily allocate space for the given number of elements--- (like 'Foreign.Marshal.Alloc.alloca', but for multiple elements).----allocaArray :: Storable a => Int -> (Ptr a -> IO b) -> IO b-allocaArray  = doAlloca undefined-  where-    doAlloca            :: Storable a' => a' -> Int -> (Ptr a' -> IO b') -> IO b'-    doAlloca dummy size  = allocaBytesAligned (size * sizeOf dummy)-                                              (alignment dummy)---- |Like 'allocaArray', but add an extra position to hold a special--- termination element.----allocaArray0      :: Storable a => Int -> (Ptr a -> IO b) -> IO b-allocaArray0 size  = allocaArray (size + 1)-{-# INLINE allocaArray0 #-}-  -- needed to get allocaArray to inline into withCString, for unknown-  -- reasons --SDM 23/4/2010, see #4004 for benchmark---- |Adjust the size of an array----reallocArray :: Storable a => Ptr a -> Int -> IO (Ptr a)-reallocArray  = doRealloc undefined-  where-    doRealloc                :: Storable a' => a' -> Ptr a' -> Int -> IO (Ptr a')-    doRealloc dummy ptr size  = reallocBytes ptr (size * sizeOf dummy)---- |Adjust the size of an array including an extra position for the end marker.----reallocArray0          :: Storable a => Ptr a -> Int -> IO (Ptr a)-reallocArray0 ptr size  = reallocArray ptr (size + 1)----- marshalling--- --------------- |Convert an array of given length into a Haskell list.  The implementation--- is tail-recursive and so uses constant stack space.----peekArray          :: Storable a => Int -> Ptr a -> IO [a]-peekArray size ptr | size <= 0 = return []-                 | otherwise = f (size-1) []-  where-    f 0 acc = do e <- peekElemOff ptr 0; return (e:acc)-    f n acc = do e <- peekElemOff ptr n; f (n-1) (e:acc)-  --- |Convert an array terminated by the given end marker into a Haskell list----peekArray0            :: (Storable a, Eq a) => a -> Ptr a -> IO [a]-peekArray0 marker ptr  = do-  size <- lengthArray0 marker ptr-  peekArray size ptr---- |Write the list elements consecutive into memory----pokeArray :: Storable a => Ptr a -> [a] -> IO ()-pokeArray ptr vals0 = go vals0 0#-  where go [] _          = return ()-        go (val:vals) n# = do pokeElemOff ptr (I# n#) val; go vals (n# +# 1#)---- |Write the list elements consecutive into memory and terminate them with the--- given marker element----pokeArray0 :: Storable a => a -> Ptr a -> [a] -> IO ()-pokeArray0 marker ptr vals0 = go vals0 0#-  where go [] n#         = pokeElemOff ptr (I# n#) marker-        go (val:vals) n# = do pokeElemOff ptr (I# n#) val; go vals (n# +# 1#)---- combined allocation and marshalling--- --------------------------------------- |Write a list of storable elements into a newly allocated, consecutive--- sequence of storable values--- (like 'Foreign.Marshal.Utils.new', but for multiple elements).----newArray      :: Storable a => [a] -> IO (Ptr a)-newArray vals  = do-  ptr <- mallocArray (length vals)-  pokeArray ptr vals-  return ptr---- |Write a list of storable elements into a newly allocated, consecutive--- sequence of storable values, where the end is fixed by the given end marker----newArray0             :: Storable a => a -> [a] -> IO (Ptr a)-newArray0 marker vals  = do-  ptr <- mallocArray0 (length vals)-  pokeArray0 marker ptr vals-  return ptr---- |Temporarily store a list of storable values in memory--- (like 'Foreign.Marshal.Utils.with', but for multiple elements).----withArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b-withArray vals = withArrayLen vals . const---- |Like 'withArray', but the action gets the number of values--- as an additional parameter----withArrayLen :: Storable a => [a] -> (Int -> Ptr a -> IO b) -> IO b-withArrayLen vals f  =-  allocaArray len $ \ptr -> do-      pokeArray ptr vals-      res <- f len ptr-      return res-  where-    len = length vals---- |Like 'withArray', but a terminator indicates where the array ends----withArray0 :: Storable a => a -> [a] -> (Ptr a -> IO b) -> IO b-withArray0 marker vals = withArrayLen0 marker vals . const---- |Like 'withArrayLen', but a terminator indicates where the array ends----withArrayLen0 :: Storable a => a -> [a] -> (Int -> Ptr a -> IO b) -> IO b-withArrayLen0 marker vals f  =-  allocaArray0 len $ \ptr -> do-      pokeArray0 marker ptr vals-      res <- f len ptr-      return res-  where-    len = length vals----- copying (argument order: destination, source)--- ----------- |Copy the given number of elements from the second array (source) into the--- first array (destination); the copied areas may /not/ overlap----copyArray :: Storable a => Ptr a -> Ptr a -> Int -> IO ()-copyArray  = doCopy undefined-  where-    doCopy                     :: Storable a' => a' -> Ptr a' -> Ptr a' -> Int -> IO ()-    doCopy dummy dest src size  = copyBytes dest src (size * sizeOf dummy)---- |Copy the given number of elements from the second array (source) into the--- first array (destination); the copied areas /may/ overlap----moveArray :: Storable a => Ptr a -> Ptr a -> Int -> IO ()-moveArray  = doMove undefined-  where-    doMove                     :: Storable a' => a' -> Ptr a' -> Ptr a' -> Int -> IO ()-    doMove dummy dest src size  = moveBytes dest src (size * sizeOf dummy)----- finding the length--- ---------------------- |Return the number of elements in an array, excluding the terminator----lengthArray0            :: (Storable a, Eq a) => a -> Ptr a -> IO Int-lengthArray0 marker ptr  = loop 0-  where-    loop i = do-        val <- peekElemOff ptr i-        if val == marker then return i else loop (i+1)----- indexing--- ------------ |Advance a pointer into an array by the given number of elements----advancePtr :: Storable a => Ptr a -> Int -> Ptr a-advancePtr  = doAdvance undefined-  where-    doAdvance             :: Storable a' => a' -> Ptr a' -> Int -> Ptr a'-    doAdvance dummy ptr i  = ptr `plusPtr` (i * sizeOf dummy)-
− Foreign/Marshal/Error.hs
@@ -1,82 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Marshal.Error--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ Routines for testing return values and raising a 'userError' exception--- in case of values indicating an error state.-----------------------------------------------------------------------------------module Foreign.Marshal.Error (-  throwIf,-  throwIf_,-  throwIfNeg,-  throwIfNeg_,-  throwIfNull,--  -- Discard return value-  ---  void-) where--import Foreign.Ptr--#ifdef __HADDOCK__-import Data.Bool-import System.IO.Error-#endif-import GHC.Base-import GHC.Num-import GHC.IO.Exception---- exported functions--- ---------------------- |Execute an 'IO' action, throwing a 'userError' if the predicate yields--- 'True' when applied to the result returned by the 'IO' action.--- If no exception is raised, return the result of the computation.----throwIf :: (a -> Bool)  -- ^ error condition on the result of the 'IO' action-        -> (a -> String) -- ^ computes an error message from erroneous results-                        -- of the 'IO' action-        -> IO a         -- ^ the 'IO' action to be executed-        -> IO a-throwIf pred msgfct act  = -  do-    res <- act-    (if pred res then ioError . userError . msgfct else return) res---- |Like 'throwIf', but discarding the result----throwIf_                 :: (a -> Bool) -> (a -> String) -> IO a -> IO ()-throwIf_ pred msgfct act  = void $ throwIf pred msgfct act---- |Guards against negative result values----throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a-throwIfNeg  = throwIf (< 0)---- |Like 'throwIfNeg', but discarding the result----throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()-throwIfNeg_  = throwIf_ (< 0)---- |Guards against null pointers----throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)-throwIfNull  = throwIf (== nullPtr) . const---- |Discard the return value of an 'IO' action----void     :: IO a -> IO ()-void act  = act >> return ()-{-# DEPRECATED void "use 'Control.Monad.void' instead" #-} -- deprecated in 7.6
− Foreign/Marshal/Pool.hs
@@ -1,198 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}------------------------------------------------------------------------------------- |--- Module      :  Foreign.Marshal.Pool--- Copyright   :  (c) Sven Panne 2002-2004--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  sven.panne@aedion.de--- Stability   :  provisional--- Portability :  portable------ This module contains support for pooled memory management. Under this scheme,--- (re-)allocations belong to a given pool, and everything in a pool is--- deallocated when the pool itself is deallocated. This is useful when--- 'Foreign.Marshal.Alloc.alloca' with its implicit allocation and deallocation--- is not flexible enough, but explicit uses of 'Foreign.Marshal.Alloc.malloc'--- and 'free' are too awkward.--------------------------------------------------------------------------------------module Foreign.Marshal.Pool (-   -- * Pool management-   Pool,-   newPool,-   freePool,-   withPool,--   -- * (Re-)Allocation within a pool-   pooledMalloc,-   pooledMallocBytes,--   pooledRealloc,-   pooledReallocBytes,--   pooledMallocArray,-   pooledMallocArray0,--   pooledReallocArray,-   pooledReallocArray0,--   -- * Combined allocation and marshalling-   pooledNew,-   pooledNewArray,-   pooledNewArray0-) where--import GHC.Base              ( Int, Monad(..), (.), liftM, not )-import GHC.Err               ( undefined )-import GHC.Exception         ( throw )-import GHC.IO                ( IO, mask, catchAny )-import GHC.IORef             ( IORef, newIORef, readIORef, writeIORef )-import GHC.List              ( elem, length )-import GHC.Num               ( Num(..) )--import Data.OldList          ( delete )-import Foreign.Marshal.Alloc ( mallocBytes, reallocBytes, free )-import Foreign.Marshal.Array ( pokeArray, pokeArray0 )-import Foreign.Marshal.Error ( throwIf )-import Foreign.Ptr           ( Ptr, castPtr )-import Foreign.Storable      ( Storable(sizeOf, poke) )-------------------------------------------------------------------------------------- To avoid non-H2010 stuff like existentially quantified data constructors, we--- simply use pointers to () below. Not very nice, but...---- | A memory pool.--newtype Pool = Pool (IORef [Ptr ()])---- | Allocate a fresh memory pool.--newPool :: IO Pool-newPool = liftM Pool (newIORef [])---- | Deallocate a memory pool and everything which has been allocated in the--- pool itself.--freePool :: Pool -> IO ()-freePool (Pool pool) = readIORef pool >>= freeAll-   where freeAll []     = return ()-         freeAll (p:ps) = free p >> freeAll ps---- | Execute an action with a fresh memory pool, which gets automatically--- deallocated (including its contents) after the action has finished.--withPool :: (Pool -> IO b) -> IO b-withPool act =   -- ATTENTION: cut-n-paste from Control.Exception below!-   mask (\restore -> do-      pool <- newPool-      val <- catchAny-                (restore (act pool))-                (\e -> do freePool pool; throw e)-      freePool pool-      return val)-------------------------------------------------------------------------------------- | Allocate space for storable type in the given pool. The size of the area--- allocated is determined by the 'sizeOf' method from the instance of--- 'Storable' for the appropriate type.--pooledMalloc :: Storable a => Pool -> IO (Ptr a)-pooledMalloc = pm undefined-  where-    pm           :: Storable a' => a' -> Pool -> IO (Ptr a')-    pm dummy pool = pooledMallocBytes pool (sizeOf dummy)---- | Allocate the given number of bytes of storage in the pool.--pooledMallocBytes :: Pool -> Int -> IO (Ptr a)-pooledMallocBytes (Pool pool) size = do-   ptr <- mallocBytes size-   ptrs <- readIORef pool-   writeIORef pool (ptr:ptrs)-   return (castPtr ptr)---- | Adjust the storage area for an element in the pool to the given size of--- the required type.--pooledRealloc :: Storable a => Pool -> Ptr a -> IO (Ptr a)-pooledRealloc = pr undefined-  where-    pr               :: Storable a' => a' -> Pool -> Ptr a' -> IO (Ptr a')-    pr dummy pool ptr = pooledReallocBytes pool ptr (sizeOf dummy)---- | Adjust the storage area for an element in the pool to the given size.--pooledReallocBytes :: Pool -> Ptr a -> Int -> IO (Ptr a)-pooledReallocBytes (Pool pool) ptr size = do-   let cPtr = castPtr ptr-   _ <- throwIf (not . (cPtr `elem`)) (\_ -> "pointer not in pool") (readIORef pool)-   newPtr <- reallocBytes cPtr size-   ptrs <- readIORef pool-   writeIORef pool (newPtr : delete cPtr ptrs)-   return (castPtr newPtr)---- | Allocate storage for the given number of elements of a storable type in the--- pool.--pooledMallocArray :: Storable a => Pool -> Int -> IO (Ptr a)-pooledMallocArray = pma undefined-  where-    pma                :: Storable a' => a' -> Pool -> Int -> IO (Ptr a')-    pma dummy pool size = pooledMallocBytes pool (size * sizeOf dummy)---- | Allocate storage for the given number of elements of a storable type in the--- pool, but leave room for an extra element to signal the end of the array.--pooledMallocArray0 :: Storable a => Pool -> Int -> IO (Ptr a)-pooledMallocArray0 pool size =-   pooledMallocArray pool (size + 1)---- | Adjust the size of an array in the given pool.--pooledReallocArray :: Storable a => Pool -> Ptr a -> Int -> IO (Ptr a)-pooledReallocArray = pra undefined-  where-    pra                ::  Storable a' => a' -> Pool -> Ptr a' -> Int -> IO (Ptr a')-    pra dummy pool ptr size  = pooledReallocBytes pool ptr (size * sizeOf dummy)---- | Adjust the size of an array with an end marker in the given pool.--pooledReallocArray0 :: Storable a => Pool -> Ptr a -> Int -> IO (Ptr a)-pooledReallocArray0 pool ptr size =-   pooledReallocArray pool ptr (size + 1)-------------------------------------------------------------------------------------- | Allocate storage for a value in the given pool and marshal the value into--- this storage.--pooledNew :: Storable a => Pool -> a -> IO (Ptr a)-pooledNew pool val = do-   ptr <- pooledMalloc pool-   poke ptr val-   return ptr---- | Allocate consecutive storage for a list of values in the given pool and--- marshal these values into it.--pooledNewArray :: Storable a => Pool -> [a] -> IO (Ptr a)-pooledNewArray pool vals = do-   ptr <- pooledMallocArray pool (length vals)-   pokeArray ptr vals-   return ptr---- | Allocate consecutive storage for a list of values in the given pool and--- marshal these values into it, terminating the end with the given marker.--pooledNewArray0 :: Storable a => Pool -> a -> [a] -> IO (Ptr a)-pooledNewArray0 pool marker vals = do-   ptr <- pooledMallocArray0 pool (length vals)-   pokeArray0 marker ptr vals-   return ptr-
− Foreign/Marshal/Safe.hs
@@ -1,36 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Marshal.Safe--- Copyright   :  (c) The FFI task force 2003--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ Marshalling support------ Safe API Only.-----------------------------------------------------------------------------------module Foreign.Marshal.Safe {-# DEPRECATED "Safe is now the default, please use Foreign.Marshal instead" #-}-        (-         -- | The module "Foreign.Marshal.Safe" re-exports the other modules in the-         -- @Foreign.Marshal@ hierarchy:-          module Foreign.Marshal.Alloc-        , module Foreign.Marshal.Array-        , module Foreign.Marshal.Error-        , module Foreign.Marshal.Pool-        , module Foreign.Marshal.Utils-        ) where--import Foreign.Marshal.Alloc-import Foreign.Marshal.Array-import Foreign.Marshal.Error-import Foreign.Marshal.Pool-import Foreign.Marshal.Utils-
− Foreign/Marshal/Unsafe.hs
@@ -1,45 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Marshal.Unsafe--- Copyright   :  (c) The FFI task force 2003--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ Marshalling support. Unsafe API.-----------------------------------------------------------------------------------module Foreign.Marshal.Unsafe (-        -- * Unsafe functions-        unsafeLocalState-    ) where--import GHC.IO--{- |-Sometimes an external entity is a pure function, except that it passes-arguments and/or results via pointers.  The function-@unsafeLocalState@ permits the packaging of such entities as pure-functions.  --The only IO operations allowed in the IO action passed to-@unsafeLocalState@ are (a) local allocation (@alloca@, @allocaBytes@-and derived operations such as @withArray@ and @withCString@), and (b)-pointer operations (@Foreign.Storable@ and @Foreign.Ptr@) on the-pointers to local storage, and (c) foreign functions whose only-observable effect is to read and/or write the locally allocated-memory.  Passing an IO operation that does not obey these rules-results in undefined behaviour.--It is expected that this operation will be-replaced in a future revision of Haskell.--}-unsafeLocalState :: IO a -> a-unsafeLocalState = unsafeDupablePerformIO-
− Foreign/Marshal/Utils.hs
@@ -1,187 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Marshal.Utils--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ Utilities for primitive marshaling-----------------------------------------------------------------------------------module Foreign.Marshal.Utils (-  -- * General marshalling utilities--  -- ** Combined allocation and marshalling-  ---  with,-  new,--  -- ** Marshalling of Boolean values (non-zero corresponds to 'True')-  ---  fromBool,-  toBool,--  -- ** Marshalling of Maybe values-  ---  maybeNew,-  maybeWith,-  maybePeek,--  -- ** Marshalling lists of storable objects-  ---  withMany,--  -- ** Haskellish interface to memcpy and memmove-  -- | (argument order: destination, source)-  ---  copyBytes,-  moveBytes,--  -- ** Filling up memory area with required values-  ---  fillBytes,-) where--import Data.Maybe-import Foreign.Ptr              ( Ptr, nullPtr )-import Foreign.Storable         ( Storable(poke) )-import Foreign.C.Types          ( CSize(..), CInt(..) )-import Foreign.Marshal.Alloc    ( malloc, alloca )-import Data.Word                ( Word8 )--import GHC.Real                 ( fromIntegral )-import GHC.Num-import GHC.Base---- combined allocation and marshalling--- --------------------------------------- |Allocate a block of memory and marshal a value into it--- (the combination of 'malloc' and 'poke').--- The size of the area allocated is determined by the 'Foreign.Storable.sizeOf'--- method from the instance of 'Storable' for the appropriate type.------ The memory may be deallocated using 'Foreign.Marshal.Alloc.free' or--- 'Foreign.Marshal.Alloc.finalizerFree' when no longer required.----new     :: Storable a => a -> IO (Ptr a)-new val  = -  do -    ptr <- malloc-    poke ptr val-    return ptr---- |@'with' val f@ executes the computation @f@, passing as argument--- a pointer to a temporarily allocated block of memory into which--- @val@ has been marshalled (the combination of 'alloca' and 'poke').------ The memory is freed when @f@ terminates (either normally or via an--- exception), so the pointer passed to @f@ must /not/ be used after this.----with       :: Storable a => a -> (Ptr a -> IO b) -> IO b-with val f  =-  alloca $ \ptr -> do-    poke ptr val-    res <- f ptr-    return res----- marshalling of Boolean values (non-zero corresponds to 'True')--- --------------------------------- |Convert a Haskell 'Bool' to its numeric representation----fromBool       :: Num a => Bool -> a-fromBool False  = 0-fromBool True   = 1---- |Convert a Boolean in numeric representation to a Haskell value----toBool :: (Eq a, Num a) => a -> Bool-toBool  = (/= 0)----- marshalling of Maybe values--- ------------------------------- |Allocate storage and marshal a storable value wrapped into a 'Maybe'------ * the 'nullPtr' is used to represent 'Nothing'----maybeNew :: (      a -> IO (Ptr b))-         -> (Maybe a -> IO (Ptr b))-maybeNew  = maybe (return nullPtr)---- |Converts a @withXXX@ combinator into one marshalling a value wrapped--- into a 'Maybe', using 'nullPtr' to represent 'Nothing'.----maybeWith :: (      a -> (Ptr b -> IO c) -> IO c) -          -> (Maybe a -> (Ptr b -> IO c) -> IO c)-maybeWith  = maybe ($ nullPtr)---- |Convert a peek combinator into a one returning 'Nothing' if applied to a--- 'nullPtr' ----maybePeek                           :: (Ptr a -> IO b) -> Ptr a -> IO (Maybe b)-maybePeek peek ptr | ptr == nullPtr  = return Nothing-                   | otherwise       = do a <- peek ptr; return (Just a)----- marshalling lists of storable objects--- ----------------------------------------- |Replicates a @withXXX@ combinator over a list of objects, yielding a list of--- marshalled objects----withMany :: (a -> (b -> res) -> res)  -- withXXX combinator for one object-         -> [a]                       -- storable objects-         -> ([b] -> res)              -- action on list of marshalled obj.s-         -> res-withMany _       []     f = f []-withMany withFoo (x:xs) f = withFoo x $ \x' ->-                              withMany withFoo xs (\xs' -> f (x':xs'))----- Haskellish interface to memcpy and memmove--- ---------------------------------------------- |Copies the given number of bytes from the second area (source) into the--- first (destination); the copied areas may /not/ overlap----copyBytes               :: Ptr a -> Ptr a -> Int -> IO ()-copyBytes dest src size  = do _ <- memcpy dest src (fromIntegral size)-                              return ()---- |Copies the given number of bytes from the second area (source) into the--- first (destination); the copied areas /may/ overlap----moveBytes               :: Ptr a -> Ptr a -> Int -> IO ()-moveBytes dest src size  = do _ <- memmove dest src (fromIntegral size)-                              return ()---- Filling up memory area with required values--- ----------------------------------------------- |Fill a given number of bytes in memory area with a byte value.------ @since 4.8.0.0-fillBytes               :: Ptr a -> Word8 -> Int -> IO ()-fillBytes dest char size = do-  _ <- memset dest (fromIntegral char) (fromIntegral size)-  return ()---- auxilliary routines--- ----------------------- |Basic C routines needed for memory copying----foreign import ccall unsafe "string.h" memcpy  :: Ptr a -> Ptr a -> CSize -> IO (Ptr a)-foreign import ccall unsafe "string.h" memmove :: Ptr a -> Ptr a -> CSize -> IO (Ptr a)-foreign import ccall unsafe "string.h" memset  :: Ptr a -> CInt  -> CSize -> IO (Ptr a)
− Foreign/Ptr.hs
@@ -1,100 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, GeneralizedNewtypeDeriving,-             AutoDeriveTypeable, StandaloneDeriving #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Ptr--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ This module provides typed pointers to foreign data.  It is part--- of the Foreign Function Interface (FFI) and will normally be--- imported via the "Foreign" module.-----------------------------------------------------------------------------------module Foreign.Ptr (--    -- * Data pointers--    Ptr,-    nullPtr,-    castPtr,-    plusPtr,-    alignPtr,-    minusPtr,--    -- * Function pointers--    FunPtr,-    nullFunPtr,-    castFunPtr,-    castFunPtrToPtr,-    castPtrToFunPtr,--    freeHaskellFunPtr,-    -- Free the function pointer created by foreign export dynamic.--    -- * Integral types with lossless conversion to and from pointers-    IntPtr,-    ptrToIntPtr,-    intPtrToPtr,-    WordPtr,-    ptrToWordPtr,-    wordPtrToPtr- ) where--import GHC.Ptr-import GHC.Base-import GHC.Num-import GHC.Read-import GHC.Real-import GHC.Show-import GHC.Enum--import Data.Bits-import Data.Typeable-import Foreign.Storable ( Storable(..) )---- | Release the storage associated with the given 'FunPtr', which--- must have been obtained from a wrapper stub.  This should be called--- whenever the return value from a foreign import wrapper function is--- no longer required; otherwise, the storage it uses will leak.-foreign import ccall unsafe "freeHaskellFunctionPtr"-    freeHaskellFunPtr :: FunPtr a -> IO ()--#include "HsBaseConfig.h"-#include "CTypes.h"---- | An unsigned integral type that can be losslessly converted to and from--- @Ptr@. This type is also compatible with the C99 type @uintptr_t@, and--- can be marshalled to and from that type safely.-INTEGRAL_TYPE(WordPtr,Word)-        -- Word and Int are guaranteed pointer-sized in GHC---- | A signed integral type that can be losslessly converted to and from--- @Ptr@.  This type is also compatible with the C99 type @intptr_t@, and--- can be marshalled to and from that type safely.-INTEGRAL_TYPE(IntPtr,Int)-        -- Word and Int are guaranteed pointer-sized in GHC---- | casts a @Ptr@ to a @WordPtr@-ptrToWordPtr :: Ptr a -> WordPtr-ptrToWordPtr (Ptr a#) = WordPtr (W# (int2Word# (addr2Int# a#)))---- | casts a @WordPtr@ to a @Ptr@-wordPtrToPtr :: WordPtr -> Ptr a-wordPtrToPtr (WordPtr (W# w#)) = Ptr (int2Addr# (word2Int# w#))---- | casts a @Ptr@ to an @IntPtr@-ptrToIntPtr :: Ptr a -> IntPtr-ptrToIntPtr (Ptr a#) = IntPtr (I# (addr2Int# a#))---- | casts an @IntPtr@ to a @Ptr@-intPtrToPtr :: IntPtr -> Ptr a-intPtrToPtr (IntPtr (I# i#)) = Ptr (int2Addr# i#)
− Foreign/Safe.hs
@@ -1,40 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Safe--- Copyright   :  (c) The FFI task force 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ A collection of data types, classes, and functions for interfacing--- with another programming language.------ Safe API Only.-----------------------------------------------------------------------------------module Foreign.Safe {-# DEPRECATED "Safe is now the default, please use Foreign instead" #-}-        ( module Data.Bits-        , module Data.Int-        , module Data.Word-        , module Foreign.Ptr-        , module Foreign.ForeignPtr-        , module Foreign.StablePtr-        , module Foreign.Storable-        , module Foreign.Marshal-        ) where--import Data.Bits-import Data.Int-import Data.Word-import Foreign.Ptr-import Foreign.ForeignPtr-import Foreign.StablePtr-import Foreign.Storable-import Foreign.Marshal-
− Foreign/StablePtr.hs
@@ -1,47 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.StablePtr--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ This module is part of the Foreign Function Interface (FFI) and will usually--- be imported via the module "Foreign".------------------------------------------------------------------------------------module Foreign.StablePtr-        ( -- * Stable references to Haskell values-          StablePtr          -- abstract-        , newStablePtr-        , deRefStablePtr-        , freeStablePtr-        , castStablePtrToPtr-        , castPtrToStablePtr-        , -- ** The C-side interface--          -- $cinterface-        ) where--import GHC.Stable---- $cinterface------ The following definition is available to C programs inter-operating with--- Haskell code when including the header @HsFFI.h@.------ > typedef void *HsStablePtr;  /* C representation of a StablePtr */------ Note that no assumptions may be made about the values representing stable--- pointers.  In fact, they need not even be valid memory addresses.  The only--- guarantee provided is that if they are passed back to Haskell land, the--- function 'deRefStablePtr' will be able to reconstruct the--- Haskell value referred to by the stable pointer.-
− Foreign/Storable.hs
@@ -1,254 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, ScopedTypeVariables, BangPatterns #-}---------------------------------------------------------------------------------- |--- Module      :  Foreign.Storable--- Copyright   :  (c) The FFI task force 2001--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  ffi@haskell.org--- Stability   :  provisional--- Portability :  portable------ The module "Foreign.Storable" provides most elementary support for--- marshalling and is part of the language-independent portion of the--- Foreign Function Interface (FFI), and will normally be imported via--- the "Foreign" module.-----------------------------------------------------------------------------------module Foreign.Storable-        ( Storable(-             sizeOf,-             alignment,-             peekElemOff,-             pokeElemOff,-             peekByteOff,-             pokeByteOff,-             peek,-             poke)-        ) where---#include "MachDeps.h"-#include "HsBaseConfig.h"--import GHC.Storable-import GHC.Stable       ( StablePtr )-import GHC.Num-import GHC.Int-import GHC.Word-import GHC.Ptr-import GHC.Base-import GHC.Fingerprint.Type-import Data.Bits-import GHC.Real--{- |-The member functions of this class facilitate writing values of-primitive types to raw memory (which may have been allocated with the-above mentioned routines) and reading values from blocks of raw-memory.  The class, furthermore, includes support for computing the-storage requirements and alignment restrictions of storable types.--Memory addresses are represented as values of type @'Ptr' a@, for some-@a@ which is an instance of class 'Storable'.  The type argument to-'Ptr' helps provide some valuable type safety in FFI code (you can\'t-mix pointers of different types without an explicit cast), while-helping the Haskell type system figure out which marshalling method is-needed for a given pointer.--All marshalling between Haskell and a foreign language ultimately-boils down to translating Haskell data structures into the binary-representation of a corresponding data structure of the foreign-language and vice versa.  To code this marshalling in Haskell, it is-necessary to manipulate primitive data types stored in unstructured-memory blocks.  The class 'Storable' facilitates this manipulation on-all types for which it is instantiated, which are the standard basic-types of Haskell, the fixed size @Int@ types ('Int8', 'Int16',-'Int32', 'Int64'), the fixed size @Word@ types ('Word8', 'Word16',-'Word32', 'Word64'), 'StablePtr', all types from "Foreign.C.Types",-as well as 'Ptr'.--}--class Storable a where-   {-# MINIMAL sizeOf, alignment,-               (peek | peekElemOff | peekByteOff),-               (poke | pokeElemOff | pokeByteOff) #-}--   sizeOf      :: a -> Int-   -- ^ Computes the storage requirements (in bytes) of the argument.-   -- The value of the argument is not used.--   alignment   :: a -> Int-   -- ^ Computes the alignment constraint of the argument.  An-   -- alignment constraint @x@ is fulfilled by any address divisible-   -- by @x@.  The value of the argument is not used.--   peekElemOff :: Ptr a -> Int      -> IO a-   -- ^       Read a value from a memory area regarded as an array-   --         of values of the same kind.  The first argument specifies-   --         the start address of the array and the second the index into-   --         the array (the first element of the array has index-   --         @0@).  The following equality holds,-   -- -   -- > peekElemOff addr idx = IOExts.fixIO $ \result ->-   -- >   peek (addr `plusPtr` (idx * sizeOf result))-   ---   --         Note that this is only a specification, not-   --         necessarily the concrete implementation of the-   --         function.--   pokeElemOff :: Ptr a -> Int -> a -> IO ()-   -- ^       Write a value to a memory area regarded as an array of-   --         values of the same kind.  The following equality holds:-   -- -   -- > pokeElemOff addr idx x = -   -- >   poke (addr `plusPtr` (idx * sizeOf x)) x--   peekByteOff :: Ptr b -> Int      -> IO a-   -- ^       Read a value from a memory location given by a base-   --         address and offset.  The following equality holds:-   ---   -- > peekByteOff addr off = peek (addr `plusPtr` off)--   pokeByteOff :: Ptr b -> Int -> a -> IO ()-   -- ^       Write a value to a memory location given by a base-   --         address and offset.  The following equality holds:-   ---   -- > pokeByteOff addr off x = poke (addr `plusPtr` off) x-  -   peek        :: Ptr a      -> IO a-   -- ^ Read a value from the given memory location.-   ---   --  Note that the peek and poke functions might require properly-   --  aligned addresses to function correctly.  This is architecture-   --  dependent; thus, portable code should ensure that when peeking or-   --  poking values of some type @a@, the alignment-   --  constraint for @a@, as given by the function-   --  'alignment' is fulfilled.--   poke        :: Ptr a -> a -> IO ()-   -- ^ Write the given value to the given memory location.  Alignment-   -- restrictions might apply; see 'peek'.- -   -- circular default instances-   peekElemOff = peekElemOff_ undefined-      where peekElemOff_ :: a -> Ptr a -> Int -> IO a-            peekElemOff_ undef ptr off = peekByteOff ptr (off * sizeOf undef)-   pokeElemOff ptr off val = pokeByteOff ptr (off * sizeOf val) val--   peekByteOff ptr off = peek (ptr `plusPtr` off)-   pokeByteOff ptr off = poke (ptr `plusPtr` off)--   peek ptr = peekElemOff ptr 0-   poke ptr = pokeElemOff ptr 0---- System-dependent, but rather obvious instances--instance Storable Bool where-   sizeOf _          = sizeOf (undefined::HTYPE_INT)-   alignment _       = alignment (undefined::HTYPE_INT)-   peekElemOff p i   = liftM (/= (0::HTYPE_INT)) $ peekElemOff (castPtr p) i-   pokeElemOff p i x = pokeElemOff (castPtr p) i (if x then 1 else 0::HTYPE_INT)--#define STORABLE(T,size,align,read,write)       \-instance Storable (T) where {                   \-    sizeOf    _ = size;                         \-    alignment _ = align;                        \-    peekElemOff = read;                         \-    pokeElemOff = write }--STORABLE(Char,SIZEOF_INT32,ALIGNMENT_INT32,-         readWideCharOffPtr,writeWideCharOffPtr)--STORABLE(Int,SIZEOF_HSINT,ALIGNMENT_HSINT,-         readIntOffPtr,writeIntOffPtr)--STORABLE(Word,SIZEOF_HSWORD,ALIGNMENT_HSWORD,-         readWordOffPtr,writeWordOffPtr)--STORABLE((Ptr a),SIZEOF_HSPTR,ALIGNMENT_HSPTR,-         readPtrOffPtr,writePtrOffPtr)--STORABLE((FunPtr a),SIZEOF_HSFUNPTR,ALIGNMENT_HSFUNPTR,-         readFunPtrOffPtr,writeFunPtrOffPtr)--STORABLE((StablePtr a),SIZEOF_HSSTABLEPTR,ALIGNMENT_HSSTABLEPTR,-         readStablePtrOffPtr,writeStablePtrOffPtr)--STORABLE(Float,SIZEOF_HSFLOAT,ALIGNMENT_HSFLOAT,-         readFloatOffPtr,writeFloatOffPtr)--STORABLE(Double,SIZEOF_HSDOUBLE,ALIGNMENT_HSDOUBLE,-         readDoubleOffPtr,writeDoubleOffPtr)--STORABLE(Word8,SIZEOF_WORD8,ALIGNMENT_WORD8,-         readWord8OffPtr,writeWord8OffPtr)--STORABLE(Word16,SIZEOF_WORD16,ALIGNMENT_WORD16,-         readWord16OffPtr,writeWord16OffPtr)--STORABLE(Word32,SIZEOF_WORD32,ALIGNMENT_WORD32,-         readWord32OffPtr,writeWord32OffPtr)--STORABLE(Word64,SIZEOF_WORD64,ALIGNMENT_WORD64,-         readWord64OffPtr,writeWord64OffPtr)--STORABLE(Int8,SIZEOF_INT8,ALIGNMENT_INT8,-         readInt8OffPtr,writeInt8OffPtr)--STORABLE(Int16,SIZEOF_INT16,ALIGNMENT_INT16,-         readInt16OffPtr,writeInt16OffPtr)--STORABLE(Int32,SIZEOF_INT32,ALIGNMENT_INT32,-         readInt32OffPtr,writeInt32OffPtr)--STORABLE(Int64,SIZEOF_INT64,ALIGNMENT_INT64,-         readInt64OffPtr,writeInt64OffPtr)--instance (Storable a, Integral a) => Storable (Ratio a) where-    sizeOf _    = 2 * sizeOf (undefined :: a)-    alignment _ = alignment (undefined :: a )-    peek p           = do-                        q <- return $ castPtr p-                        r <- peek q-                        i <- peekElemOff q 1-                        return (r % i)-    poke p (r :% i)  = do-                        q <-return $  (castPtr p)-                        poke q r-                        pokeElemOff q 1 i---- XXX: here to avoid orphan instance in GHC.Fingerprint-instance Storable Fingerprint where-  sizeOf _ = 16-  alignment _ = 8-  peek = peekFingerprint-  poke = pokeFingerprint---- peek/poke in fixed BIG-endian 128-bit format-peekFingerprint :: Ptr Fingerprint -> IO Fingerprint-peekFingerprint p0 = do-      let peekW64 :: Ptr Word8 -> Int -> Word64 -> IO Word64-          peekW64 _  0  !i = return i-          peekW64 !p !n !i = do-                w8 <- peek p-                peekW64 (p `plusPtr` 1) (n-1) -                    ((i `shiftL` 8) .|. fromIntegral w8)--      high <- peekW64 (castPtr p0) 8 0-      low  <- peekW64 (castPtr p0 `plusPtr` 8) 8 0-      return (Fingerprint high low)--pokeFingerprint :: Ptr Fingerprint -> Fingerprint -> IO ()-pokeFingerprint p0 (Fingerprint high low) = do-      let pokeW64 :: Ptr Word8 -> Int -> Word64 -> IO ()-          pokeW64 _ 0  _  = return ()-          pokeW64 p !n !i = do-                pokeElemOff p (n-1) (fromIntegral i)-                pokeW64 p (n-1) (i `shiftR` 8)--      pokeW64 (castPtr p0) 8 high-      pokeW64 (castPtr p0 `plusPtr` 8) 8 low
− GHC/Arr.hs
@@ -1,899 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples, RoleAnnotations #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Arr--- Copyright   :  (c) The University of Glasgow, 1994-2000--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ GHC\'s array implementation.-----------------------------------------------------------------------------------module GHC.Arr (-        Ix(..), Array(..), STArray(..),--        indexError, hopelessIndexError,-        arrEleBottom, array, listArray,-        (!), safeRangeSize, negRange, safeIndex, badSafeIndex,-        bounds, numElements, numElementsSTArray, indices, elems,-        assocs, accumArray, adjust, (//), accum,-        amap, ixmap,-        eqArray, cmpArray, cmpIntArray,-        newSTArray, boundsSTArray,-        readSTArray, writeSTArray,-        freezeSTArray, thawSTArray,-        foldlElems, foldlElems', foldl1Elems,-        foldrElems, foldrElems', foldr1Elems,--        -- * Unsafe operations-        fill, done,-        unsafeArray, unsafeArray',-        lessSafeIndex, unsafeAt, unsafeReplace,-        unsafeAccumArray, unsafeAccumArray', unsafeAccum,-        unsafeReadSTArray, unsafeWriteSTArray,-        unsafeFreezeSTArray, unsafeThawSTArray,-    ) where--import GHC.Enum-import GHC.Num-import GHC.ST-import GHC.Base-import GHC.List-import GHC.Real( fromIntegral )-import GHC.Show--infixl 9  !, //--default ()---- | The 'Ix' class is used to map a contiguous subrange of values in--- a type onto integers.  It is used primarily for array indexing--- (see the array package).------ The first argument @(l,u)@ of each of these operations is a pair--- specifying the lower and upper bounds of a contiguous subrange of values.------ An implementation is entitled to assume the following laws about these--- operations:------ * @'inRange' (l,u) i == 'elem' i ('range' (l,u))@ @ @------ * @'range' (l,u) '!!' 'index' (l,u) i == i@, when @'inRange' (l,u) i@------ * @'map' ('index' (l,u)) ('range' (l,u))) == [0..'rangeSize' (l,u)-1]@ @ @------ * @'rangeSize' (l,u) == 'length' ('range' (l,u))@ @ @----class (Ord a) => Ix a where-    {-# MINIMAL range, (index | unsafeIndex), inRange #-}--    -- | The list of values in the subrange defined by a bounding pair.-    range               :: (a,a) -> [a]-    -- | The position of a subscript in the subrange.-    index               :: (a,a) -> a -> Int-    -- | Like 'index', but without checking that the value is in range.-    unsafeIndex         :: (a,a) -> a -> Int-    -- | Returns 'True' the given subscript lies in the range defined-    -- the bounding pair.-    inRange             :: (a,a) -> a -> Bool-    -- | The size of the subrange defined by a bounding pair.-    rangeSize           :: (a,a) -> Int-    -- | like 'rangeSize', but without checking that the upper bound is-    -- in range.-    unsafeRangeSize     :: (a,a) -> Int--        -- Must specify one of index, unsafeIndex--        -- 'index' is typically over-ridden in instances, with essentially-        -- the same code, but using indexError instead of hopelessIndexError-        -- Reason: we have 'Show' at the instances-    {-# INLINE index #-}  -- See Note [Inlining index]-    index b i | inRange b i = unsafeIndex b i-              | otherwise   = hopelessIndexError--    unsafeIndex b i = index b i--    rangeSize b@(_l,h) | inRange b h = unsafeIndex b h + 1-                       | otherwise   = 0        -- This case is only here to-                                                -- check for an empty range-        -- NB: replacing (inRange b h) by (l <= h) fails for-        --     tuples.  E.g.  (1,2) <= (2,1) but the range is empty--    unsafeRangeSize b@(_l,h) = unsafeIndex b h + 1--{--Note that the following is NOT right-        rangeSize (l,h) | l <= h    = index b h + 1-                        | otherwise = 0--Because it might be the case that l<h, but the range-is nevertheless empty.  Consider-        ((1,2),(2,1))-Here l<h, but the second index ranges from 2..1 and-hence is empty---Note [Inlining index]-~~~~~~~~~~~~~~~~~~~~~-We inline the 'index' operation,-- * Partly because it generates much faster code-   (although bigger); see Trac #1216-- * Partly because it exposes the bounds checks to the simplifier which-   might help a big.--If you make a per-instance index method, you may consider inlining it.--Note [Double bounds-checking of index values]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-When you index an array, a!x, there are two possible bounds checks we might make:--  (A) Check that (inRange (bounds a) x) holds.--      (A) is checked in the method for 'index'--  (B) Check that (index (bounds a) x) lies in the range 0..n,-      where n is the size of the underlying array--      (B) is checked in the top-level function (!), in safeIndex.--Of course it *should* be the case that (A) holds iff (B) holds, but that-is a property of the particular instances of index, bounds, and inRange,-so GHC cannot guarantee it.-- * If you do (A) and not (B), then you might get a seg-fault,-   by indexing at some bizarre location.  Trac #1610-- * If you do (B) but not (A), you may get no complaint when you index-   an array out of its semantic bounds.  Trac #2120--At various times we have had (A) and not (B), or (B) and not (A); both-led to complaints.  So now we implement *both* checks (Trac #2669).--For 1-d, 2-d, and 3-d arrays of Int we have specialised instances to avoid this.--Note [Out-of-bounds error messages]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The default method for 'index' generates hoplelessIndexError, because-Ix doesn't have Show as a superclass.  For particular base types we-can do better, so we override the default method for index.--}---- Abstract these errors from the relevant index functions so that--- the guts of the function will be small enough to inline.--{-# NOINLINE indexError #-}-indexError :: Show a => (a,a) -> a -> String -> b-indexError rng i tp-  = error (showString "Ix{" . showString tp . showString "}.index: Index " .-           showParen True (showsPrec 0 i) .-           showString " out of range " $-           showParen True (showsPrec 0 rng) "")--hopelessIndexError :: Int -- Try to use 'indexError' instead!-hopelessIndexError = error "Error in array index"-------------------------------------------------------------------------instance  Ix Char  where-    {-# INLINE range #-}-    range (m,n) = [m..n]--    {-# INLINE unsafeIndex #-}-    unsafeIndex (m,_n) i = fromEnum i - fromEnum m--    {-# INLINE index #-}  -- See Note [Out-of-bounds error messages]-                          -- and Note [Inlining index]-    index b i | inRange b i =  unsafeIndex b i-              | otherwise   =  indexError b i "Char"--    inRange (m,n) i     =  m <= i && i <= n-------------------------------------------------------------------------instance  Ix Int  where-    {-# INLINE range #-}-        -- The INLINE stops the build in the RHS from getting inlined,-        -- so that callers can fuse with the result of range-    range (m,n) = [m..n]--    {-# INLINE unsafeIndex #-}-    unsafeIndex (m,_n) i = i - m--    {-# INLINE index #-}  -- See Note [Out-of-bounds error messages]-                          -- and Note [Inlining index]-    index b i | inRange b i =  unsafeIndex b i-              | otherwise   =  indexError b i "Int"--    {-# INLINE inRange #-}-    inRange (I# m,I# n) (I# i) =  isTrue# (m <=# i) && isTrue# (i <=# n)--instance Ix Word where-    range (m,n)         = [m..n]-    unsafeIndex (m,_) i = fromIntegral (i - m)-    inRange (m,n) i     = m <= i && i <= n-------------------------------------------------------------------------instance  Ix Integer  where-    {-# INLINE range #-}-    range (m,n) = [m..n]--    {-# INLINE unsafeIndex #-}-    unsafeIndex (m,_n) i   = fromInteger (i - m)--    {-# INLINE index #-}  -- See Note [Out-of-bounds error messages]-                          -- and Note [Inlining index]-    index b i | inRange b i =  unsafeIndex b i-              | otherwise   =  indexError b i "Integer"--    inRange (m,n) i     =  m <= i && i <= n-------------------------------------------------------------------------instance Ix Bool where -- as derived-    {-# INLINE range #-}-    range (m,n) = [m..n]--    {-# INLINE unsafeIndex #-}-    unsafeIndex (l,_) i = fromEnum i - fromEnum l--    {-# INLINE index #-}  -- See Note [Out-of-bounds error messages]-                          -- and Note [Inlining index]-    index b i | inRange b i =  unsafeIndex b i-              | otherwise   =  indexError b i "Bool"--    inRange (l,u) i = fromEnum i >= fromEnum l && fromEnum i <= fromEnum u-------------------------------------------------------------------------instance Ix Ordering where -- as derived-    {-# INLINE range #-}-    range (m,n) = [m..n]--    {-# INLINE unsafeIndex #-}-    unsafeIndex (l,_) i = fromEnum i - fromEnum l--    {-# INLINE index #-}  -- See Note [Out-of-bounds error messages]-                          -- and Note [Inlining index]-    index b i | inRange b i =  unsafeIndex b i-              | otherwise   =  indexError b i "Ordering"--    inRange (l,u) i = fromEnum i >= fromEnum l && fromEnum i <= fromEnum u-------------------------------------------------------------------------instance Ix () where-    {-# INLINE range #-}-    range   ((), ())    = [()]-    {-# INLINE unsafeIndex #-}-    unsafeIndex   ((), ()) () = 0-    {-# INLINE inRange #-}-    inRange ((), ()) () = True--    {-# INLINE index #-}  -- See Note [Inlining index]-    index b i = unsafeIndex b i-------------------------------------------------------------------------instance (Ix a, Ix b) => Ix (a, b) where -- as derived-    {-# SPECIALISE instance Ix (Int,Int) #-}--    {-# INLINE range #-}-    range ((l1,l2),(u1,u2)) =-      [ (i1,i2) | i1 <- range (l1,u1), i2 <- range (l2,u2) ]--    {-# INLINE unsafeIndex #-}-    unsafeIndex ((l1,l2),(u1,u2)) (i1,i2) =-      unsafeIndex (l1,u1) i1 * unsafeRangeSize (l2,u2) + unsafeIndex (l2,u2) i2--    {-# INLINE inRange #-}-    inRange ((l1,l2),(u1,u2)) (i1,i2) =-      inRange (l1,u1) i1 && inRange (l2,u2) i2--    -- Default method for index-------------------------------------------------------------------------instance  (Ix a1, Ix a2, Ix a3) => Ix (a1,a2,a3)  where-    {-# SPECIALISE instance Ix (Int,Int,Int) #-}--    range ((l1,l2,l3),(u1,u2,u3)) =-        [(i1,i2,i3) | i1 <- range (l1,u1),-                      i2 <- range (l2,u2),-                      i3 <- range (l3,u3)]--    unsafeIndex ((l1,l2,l3),(u1,u2,u3)) (i1,i2,i3) =-      unsafeIndex (l3,u3) i3 + unsafeRangeSize (l3,u3) * (-      unsafeIndex (l2,u2) i2 + unsafeRangeSize (l2,u2) * (-      unsafeIndex (l1,u1) i1))--    inRange ((l1,l2,l3),(u1,u2,u3)) (i1,i2,i3) =-      inRange (l1,u1) i1 && inRange (l2,u2) i2 &&-      inRange (l3,u3) i3--    -- Default method for index-------------------------------------------------------------------------instance  (Ix a1, Ix a2, Ix a3, Ix a4) => Ix (a1,a2,a3,a4)  where-    range ((l1,l2,l3,l4),(u1,u2,u3,u4)) =-      [(i1,i2,i3,i4) | i1 <- range (l1,u1),-                       i2 <- range (l2,u2),-                       i3 <- range (l3,u3),-                       i4 <- range (l4,u4)]--    unsafeIndex ((l1,l2,l3,l4),(u1,u2,u3,u4)) (i1,i2,i3,i4) =-      unsafeIndex (l4,u4) i4 + unsafeRangeSize (l4,u4) * (-      unsafeIndex (l3,u3) i3 + unsafeRangeSize (l3,u3) * (-      unsafeIndex (l2,u2) i2 + unsafeRangeSize (l2,u2) * (-      unsafeIndex (l1,u1) i1)))--    inRange ((l1,l2,l3,l4),(u1,u2,u3,u4)) (i1,i2,i3,i4) =-      inRange (l1,u1) i1 && inRange (l2,u2) i2 &&-      inRange (l3,u3) i3 && inRange (l4,u4) i4--    -- Default method for index--instance  (Ix a1, Ix a2, Ix a3, Ix a4, Ix a5) => Ix (a1,a2,a3,a4,a5)  where-    range ((l1,l2,l3,l4,l5),(u1,u2,u3,u4,u5)) =-      [(i1,i2,i3,i4,i5) | i1 <- range (l1,u1),-                          i2 <- range (l2,u2),-                          i3 <- range (l3,u3),-                          i4 <- range (l4,u4),-                          i5 <- range (l5,u5)]--    unsafeIndex ((l1,l2,l3,l4,l5),(u1,u2,u3,u4,u5)) (i1,i2,i3,i4,i5) =-      unsafeIndex (l5,u5) i5 + unsafeRangeSize (l5,u5) * (-      unsafeIndex (l4,u4) i4 + unsafeRangeSize (l4,u4) * (-      unsafeIndex (l3,u3) i3 + unsafeRangeSize (l3,u3) * (-      unsafeIndex (l2,u2) i2 + unsafeRangeSize (l2,u2) * (-      unsafeIndex (l1,u1) i1))))--    inRange ((l1,l2,l3,l4,l5),(u1,u2,u3,u4,u5)) (i1,i2,i3,i4,i5) =-      inRange (l1,u1) i1 && inRange (l2,u2) i2 &&-      inRange (l3,u3) i3 && inRange (l4,u4) i4 &&-      inRange (l5,u5) i5--    -- Default method for index---- | The type of immutable non-strict (boxed) arrays--- with indices in @i@ and elements in @e@.-data Array i e-   = Array            !i         -- the lower bound, l-                      !i         -- the upper bound, u-       {-# UNPACK #-} !Int       -- A cache of (rangeSize (l,u))-                                 -- used to make sure an index is-                                 -- really in range-                      (Array# e) -- The actual elements---- | Mutable, boxed, non-strict arrays in the 'ST' monad.  The type--- arguments are as follows:------  * @s@: the state variable argument for the 'ST' type------  * @i@: the index type of the array (should be an instance of 'Ix')------  * @e@: the element type of the array.----data STArray s i e-  = STArray           !i               -- the lower bound, l-                      !i               -- the upper bound, u-      {-# UNPACK #-}  !Int             -- A cache of (rangeSize (l,u))-                                       -- used to make sure an index is-                                       -- really in range-                   (MutableArray# s e) -- The actual elements-        -- No Ix context for STArray.  They are stupid,-        -- and force an Ix context on the equality instance.---- Index types should have nominal role, because of Ix class. See also #9220.-type role Array nominal representational-type role STArray nominal nominal representational---- Just pointer equality on mutable arrays:-instance Eq (STArray s i e) where-    STArray _ _ _ arr1# == STArray _ _ _ arr2# =-        isTrue# (sameMutableArray# arr1# arr2#)--------------------------------------------------------------------------- Operations on immutable arrays--{-# NOINLINE arrEleBottom #-}-arrEleBottom :: a-arrEleBottom = error "(Array.!): undefined array element"---- | Construct an array with the specified bounds and containing values--- for given indices within these bounds.------ The array is undefined (i.e. bottom) if any index in the list is--- out of bounds.  The Haskell 2010 Report further specifies that if any--- two associations in the list have the same index, the value at that--- index is undefined (i.e. bottom).  However in GHC's implementation,--- the value at such an index is the value part of the last association--- with that index in the list.------ Because the indices must be checked for these errors, 'array' is--- strict in the bounds argument and in the indices of the association--- list, but non-strict in the values.  Thus, recurrences such as the--- following are possible:------ > a = array (1,100) ((1,1) : [(i, i * a!(i-1)) | i <- [2..100]])------ Not every index within the bounds of the array need appear in the--- association list, but the values associated with indices that do not--- appear will be undefined (i.e. bottom).------ If, in any dimension, the lower bound is greater than the upper bound,--- then the array is legal, but empty.  Indexing an empty array always--- gives an array-bounds error, but 'bounds' still yields the bounds--- with which the array was constructed.-{-# INLINE array #-}-array :: Ix i-        => (i,i)        -- ^ a pair of /bounds/, each of the index type-                        -- of the array.  These bounds are the lowest and-                        -- highest indices in the array, in that order.-                        -- For example, a one-origin vector of length-                        -- '10' has bounds '(1,10)', and a one-origin '10'-                        -- by '10' matrix has bounds '((1,1),(10,10))'.-        -> [(i, e)]     -- ^ a list of /associations/ of the form-                        -- (/index/, /value/).  Typically, this list will-                        -- be expressed as a comprehension.  An-                        -- association '(i, x)' defines the value of-                        -- the array at index 'i' to be 'x'.-        -> Array i e-array (l,u) ies-    = let n = safeRangeSize (l,u)-      in unsafeArray' (l,u) n-                      [(safeIndex (l,u) n i, e) | (i, e) <- ies]--{-# INLINE unsafeArray #-}-unsafeArray :: Ix i => (i,i) -> [(Int, e)] -> Array i e-unsafeArray b ies = unsafeArray' b (rangeSize b) ies--{-# INLINE unsafeArray' #-}-unsafeArray' :: Ix i => (i,i) -> Int -> [(Int, e)] -> Array i e-unsafeArray' (l,u) n@(I# n#) ies = runST (ST $ \s1# ->-    case newArray# n# arrEleBottom s1# of-        (# s2#, marr# #) ->-            foldr (fill marr#) (done l u n marr#) ies s2#)--{-# INLINE fill #-}-fill :: MutableArray# s e -> (Int, e) -> STRep s a -> STRep s a--- NB: put the \s after the "=" so that 'fill'---     inlines when applied to three args-fill marr# (I# i#, e) next- = \s1# -> case writeArray# marr# i# e s1# of-             s2# -> next s2#--{-# INLINE done #-}-done :: Ix i => i -> i -> Int -> MutableArray# s e -> STRep s (Array i e)--- See NB on 'fill'--- Make sure it is strict in 'n'-done l u n@(I# _) marr#-  = \s1# -> case unsafeFreezeArray# marr# s1# of-              (# s2#, arr# #) -> (# s2#, Array l u n arr# #)---- | Construct an array from a pair of bounds and a list of values in--- index order.-{-# INLINE listArray #-}-listArray :: Ix i => (i,i) -> [e] -> Array i e-listArray (l,u) es = runST (ST $ \s1# ->-    case safeRangeSize (l,u)            of { n@(I# n#) ->-    case newArray# n# arrEleBottom s1#  of { (# s2#, marr# #) ->-      let-        go y r = \ i# s3# ->-            case writeArray# marr# i# y s3# of-              s4# -> if (isTrue# (i# ==# n# -# 1#))-                     then s4#-                     else r (i# +# 1#) s4#-      in-        done l u n marr# (-          if n == 0-          then s2#-          else foldr go (\_ s# -> s#) es 0# s2#)}})---- | The value at the given index in an array.-{-# INLINE (!) #-}-(!) :: Ix i => Array i e -> i -> e-arr@(Array l u n _) ! i = unsafeAt arr $ safeIndex (l,u) n i--{-# INLINE safeRangeSize #-}-safeRangeSize :: Ix i => (i, i) -> Int-safeRangeSize (l,u) = let r = rangeSize (l, u)-                      in if r < 0 then negRange-                                  else r---- Don't inline this error message everywhere!!-negRange :: Int   -- Uninformative, but Ix does not provide Show-negRange = error "Negative range size"--{-# INLINE[1] safeIndex #-}--- See Note [Double bounds-checking of index values]--- Inline *after* (!) so the rules can fire--- Make sure it is strict in n-safeIndex :: Ix i => (i, i) -> Int -> i -> Int-safeIndex (l,u) n@(I# _) i-  | (0 <= i') && (i' < n) = i'-  | otherwise             = badSafeIndex i' n-  where-    i' = index (l,u) i---- See Note [Double bounds-checking of index values]-{-# RULES-"safeIndex/I"       safeIndex = lessSafeIndex :: (Int,Int) -> Int -> Int -> Int-"safeIndex/(I,I)"   safeIndex = lessSafeIndex :: ((Int,Int),(Int,Int)) -> Int -> (Int,Int) -> Int-"safeIndex/(I,I,I)" safeIndex = lessSafeIndex :: ((Int,Int,Int),(Int,Int,Int)) -> Int -> (Int,Int,Int) -> Int-  #-}--lessSafeIndex :: Ix i => (i, i) -> Int -> i -> Int--- See Note [Double bounds-checking of index values]--- Do only (A), the semantic check-lessSafeIndex (l,u) _ i = index (l,u) i---- Don't inline this long error message everywhere!!-badSafeIndex :: Int -> Int -> Int-badSafeIndex i' n = error ("Error in array index; " ++ show i' ++-                        " not in range [0.." ++ show n ++ ")")--{-# INLINE unsafeAt #-}-unsafeAt :: Ix i => Array i e -> Int -> e-unsafeAt (Array _ _ _ arr#) (I# i#) =-    case indexArray# arr# i# of (# e #) -> e---- | The bounds with which an array was constructed.-{-# INLINE bounds #-}-bounds :: Ix i => Array i e -> (i,i)-bounds (Array l u _ _) = (l,u)---- | The number of elements in the array.-{-# INLINE numElements #-}-numElements :: Ix i => Array i e -> Int-numElements (Array _ _ n _) = n---- | The list of indices of an array in ascending order.-{-# INLINE indices #-}-indices :: Ix i => Array i e -> [i]-indices (Array l u _ _) = range (l,u)---- | The list of elements of an array in index order.-{-# INLINE elems #-}-elems :: Ix i => Array i e -> [e]-elems arr@(Array _ _ n _) =-    [unsafeAt arr i | i <- [0 .. n - 1]]---- | A right fold over the elements-{-# INLINABLE foldrElems #-}-foldrElems :: Ix i => (a -> b -> b) -> b -> Array i a -> b-foldrElems f b0 = \ arr@(Array _ _ n _) ->-  let-    go i | i == n    = b0-         | otherwise = f (unsafeAt arr i) (go (i+1))-  in go 0---- | A left fold over the elements-{-# INLINABLE foldlElems #-}-foldlElems :: Ix i => (b -> a -> b) -> b -> Array i a -> b-foldlElems f b0 = \ arr@(Array _ _ n _) ->-  let-    go i | i == (-1) = b0-         | otherwise = f (go (i-1)) (unsafeAt arr i)-  in go (n-1)---- | A strict right fold over the elements-{-# INLINABLE foldrElems' #-}-foldrElems' :: Ix i => (a -> b -> b) -> b -> Array i a -> b-foldrElems' f b0 = \ arr@(Array _ _ n _) ->-  let-    go i a | i == (-1) = a-           | otherwise = go (i-1) (f (unsafeAt arr i) $! a)-  in go (n-1) b0---- | A strict left fold over the elements-{-# INLINABLE foldlElems' #-}-foldlElems' :: Ix i => (b -> a -> b) -> b -> Array i a -> b-foldlElems' f b0 = \ arr@(Array _ _ n _) ->-  let-    go i a | i == n    = a-           | otherwise = go (i+1) (a `seq` f a (unsafeAt arr i))-  in go 0 b0---- | A left fold over the elements with no starting value-{-# INLINABLE foldl1Elems #-}-foldl1Elems :: Ix i => (a -> a -> a) -> Array i a -> a-foldl1Elems f = \ arr@(Array _ _ n _) ->-  let-    go i | i == 0    = unsafeAt arr 0-         | otherwise = f (go (i-1)) (unsafeAt arr i)-  in-    if n == 0 then error "foldl1: empty Array" else go (n-1)---- | A right fold over the elements with no starting value-{-# INLINABLE foldr1Elems #-}-foldr1Elems :: Ix i => (a -> a -> a) -> Array i a -> a-foldr1Elems f = \ arr@(Array _ _ n _) ->-  let-    go i | i == n-1  = unsafeAt arr i-         | otherwise = f (unsafeAt arr i) (go (i + 1))-  in-    if n == 0 then error "foldr1: empty Array" else go 0---- | The list of associations of an array in index order.-{-# INLINE assocs #-}-assocs :: Ix i => Array i e -> [(i, e)]-assocs arr@(Array l u _ _) =-    [(i, arr ! i) | i <- range (l,u)]---- | The 'accumArray' function deals with repeated indices in the association--- list using an /accumulating function/ which combines the values of--- associations with the same index.--- For example, given a list of values of some index type, @hist@--- produces a histogram of the number of occurrences of each index within--- a specified range:------ > hist :: (Ix a, Num b) => (a,a) -> [a] -> Array a b--- > hist bnds is = accumArray (+) 0 bnds [(i, 1) | i<-is, inRange bnds i]------ If the accumulating function is strict, then 'accumArray' is strict in--- the values, as well as the indices, in the association list.  Thus,--- unlike ordinary arrays built with 'array', accumulated arrays should--- not in general be recursive.-{-# INLINE accumArray #-}-accumArray :: Ix i-        => (e -> a -> e)        -- ^ accumulating function-        -> e                    -- ^ initial value-        -> (i,i)                -- ^ bounds of the array-        -> [(i, a)]             -- ^ association list-        -> Array i e-accumArray f initial (l,u) ies =-    let n = safeRangeSize (l,u)-    in unsafeAccumArray' f initial (l,u) n-                         [(safeIndex (l,u) n i, e) | (i, e) <- ies]--{-# INLINE unsafeAccumArray #-}-unsafeAccumArray :: Ix i => (e -> a -> e) -> e -> (i,i) -> [(Int, a)] -> Array i e-unsafeAccumArray f initial b ies = unsafeAccumArray' f initial b (rangeSize b) ies--{-# INLINE unsafeAccumArray' #-}-unsafeAccumArray' :: Ix i => (e -> a -> e) -> e -> (i,i) -> Int -> [(Int, a)] -> Array i e-unsafeAccumArray' f initial (l,u) n@(I# n#) ies = runST (ST $ \s1# ->-    case newArray# n# initial s1#          of { (# s2#, marr# #) ->-    foldr (adjust f marr#) (done l u n marr#) ies s2# })--{-# INLINE adjust #-}-adjust :: (e -> a -> e) -> MutableArray# s e -> (Int, a) -> STRep s b -> STRep s b--- See NB on 'fill'-adjust f marr# (I# i#, new) next-  = \s1# -> case readArray# marr# i# s1# of-                (# s2#, old #) ->-                    case writeArray# marr# i# (f old new) s2# of-                        s3# -> next s3#---- | Constructs an array identical to the first argument except that it has--- been updated by the associations in the right argument.--- For example, if @m@ is a 1-origin, @n@ by @n@ matrix, then------ > m//[((i,i), 0) | i <- [1..n]]------ is the same matrix, except with the diagonal zeroed.------ Repeated indices in the association list are handled as for 'array':--- Haskell 2010 specifies that the resulting array is undefined (i.e. bottom),--- but GHC's implementation uses the last association for each index.-{-# INLINE (//) #-}-(//) :: Ix i => Array i e -> [(i, e)] -> Array i e-arr@(Array l u n _) // ies =-    unsafeReplace arr [(safeIndex (l,u) n i, e) | (i, e) <- ies]--{-# INLINE unsafeReplace #-}-unsafeReplace :: Ix i => Array i e -> [(Int, e)] -> Array i e-unsafeReplace arr ies = runST (do-    STArray l u n marr# <- thawSTArray arr-    ST (foldr (fill marr#) (done l u n marr#) ies))---- | @'accum' f@ takes an array and an association list and accumulates--- pairs from the list into the array with the accumulating function @f@.--- Thus 'accumArray' can be defined using 'accum':------ > accumArray f z b = accum f (array b [(i, z) | i <- range b])----{-# INLINE accum #-}-accum :: Ix i => (e -> a -> e) -> Array i e -> [(i, a)] -> Array i e-accum f arr@(Array l u n _) ies =-    unsafeAccum f arr [(safeIndex (l,u) n i, e) | (i, e) <- ies]--{-# INLINE unsafeAccum #-}-unsafeAccum :: Ix i => (e -> a -> e) -> Array i e -> [(Int, a)] -> Array i e-unsafeAccum f arr ies = runST (do-    STArray l u n marr# <- thawSTArray arr-    ST (foldr (adjust f marr#) (done l u n marr#) ies))--{-# INLINE [1] amap #-}-amap :: Ix i => (a -> b) -> Array i a -> Array i b-amap f arr@(Array l u n@(I# n#) _) = runST (ST $ \s1# ->-    case newArray# n# arrEleBottom s1# of-        (# s2#, marr# #) ->-          let go i s#-                | i == n    = done l u n marr# s#-                | otherwise = fill marr# (i, f (unsafeAt arr i)) (go (i+1)) s#-          in go 0 s2# )--{--amap was originally defined like this:-- amap f arr@(Array l u n _) =-     unsafeArray' (l,u) n [(i, f (unsafeAt arr i)) | i <- [0 .. n - 1]]--There are two problems:--1. The enumFromTo implementation produces (spurious) code for the impossible-case of n<0 that ends up duplicating the array freezing code.--2. This implementation relies on list fusion for efficiency. In order to-implement the amap/coerce rule, we need to delay inlining amap until simplifier-phase 1, which is when the eftIntList rule kicks in and makes that impossible.--}----- See Breitner, Eisenberg, Peyton Jones, and Weirich, "Safe Zero-cost--- Coercions for Haskell", section 6.5:---   http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/coercible.pdf-{-# RULES-"amap/coerce" amap coerce = coerce- #-}---- Second functor law:-{-# RULES-"amap/amap" forall f g a . amap f (amap g a) = amap (f . g) a- #-}---- | 'ixmap' allows for transformations on array indices.--- It may be thought of as providing function composition on the right--- with the mapping that the original array embodies.------ A similar transformation of array values may be achieved using 'fmap'--- from the 'Array' instance of the 'Functor' class.-{-# INLINE ixmap #-}-ixmap :: (Ix i, Ix j) => (i,i) -> (i -> j) -> Array j e -> Array i e-ixmap (l,u) f arr =-    array (l,u) [(i, arr ! f i) | i <- range (l,u)]--{-# INLINE eqArray #-}-eqArray :: (Ix i, Eq e) => Array i e -> Array i e -> Bool-eqArray arr1@(Array l1 u1 n1 _) arr2@(Array l2 u2 n2 _) =-    if n1 == 0 then n2 == 0 else-    l1 == l2 && u1 == u2 &&-    and [unsafeAt arr1 i == unsafeAt arr2 i | i <- [0 .. n1 - 1]]--{-# INLINE [1] cmpArray #-}-cmpArray :: (Ix i, Ord e) => Array i e -> Array i e -> Ordering-cmpArray arr1 arr2 = compare (assocs arr1) (assocs arr2)--{-# INLINE cmpIntArray #-}-cmpIntArray :: Ord e => Array Int e -> Array Int e -> Ordering-cmpIntArray arr1@(Array l1 u1 n1 _) arr2@(Array l2 u2 n2 _) =-    if n1 == 0 then-        if n2 == 0 then EQ else LT-    else if n2 == 0 then GT-    else case compare l1 l2 of-             EQ    -> foldr cmp (compare u1 u2) [0 .. (n1 `min` n2) - 1]-             other -> other-  where-    cmp i rest = case compare (unsafeAt arr1 i) (unsafeAt arr2 i) of-        EQ    -> rest-        other -> other--{-# RULES "cmpArray/Int" cmpArray = cmpIntArray #-}--------------------------------------------------------------------------- Array instances--instance Ix i => Functor (Array i) where-    fmap = amap--instance (Ix i, Eq e) => Eq (Array i e) where-    (==) = eqArray--instance (Ix i, Ord e) => Ord (Array i e) where-    compare = cmpArray--instance (Ix a, Show a, Show b) => Show (Array a b) where-    showsPrec p a =-        showParen (p > appPrec) $-        showString "array " .-        showsPrec appPrec1 (bounds a) .-        showChar ' ' .-        showsPrec appPrec1 (assocs a)-        -- Precedence of 'array' is the precedence of application---- The Read instance is in GHC.Read--------------------------------------------------------------------------- Operations on mutable arrays--{--Idle ADR question: What's the tradeoff here between flattening these-datatypes into @STArray ix ix (MutableArray# s elt)@ and using-it as is?  As I see it, the former uses slightly less heap and-provides faster access to the individual parts of the bounds while the-code used has the benefit of providing a ready-made @(lo, hi)@ pair as-required by many array-related functions.  Which wins? Is the-difference significant (probably not).--Idle AJG answer: When I looked at the outputted code (though it was 2-years ago) it seems like you often needed the tuple, and we build-it frequently. Now we've got the overloading specialiser things-might be different, though.--}--{-# INLINE newSTArray #-}-newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)-newSTArray (l,u) initial = ST $ \s1# ->-    case safeRangeSize (l,u)            of { n@(I# n#) ->-    case newArray# n# initial s1#       of { (# s2#, marr# #) ->-    (# s2#, STArray l u n marr# #) }}--{-# INLINE boundsSTArray #-}-boundsSTArray :: STArray s i e -> (i,i)-boundsSTArray (STArray l u _ _) = (l,u)--{-# INLINE numElementsSTArray #-}-numElementsSTArray :: STArray s i e -> Int-numElementsSTArray (STArray _ _ n _) = n--{-# INLINE readSTArray #-}-readSTArray :: Ix i => STArray s i e -> i -> ST s e-readSTArray marr@(STArray l u n _) i =-    unsafeReadSTArray marr (safeIndex (l,u) n i)--{-# INLINE unsafeReadSTArray #-}-unsafeReadSTArray :: Ix i => STArray s i e -> Int -> ST s e-unsafeReadSTArray (STArray _ _ _ marr#) (I# i#)-    = ST $ \s1# -> readArray# marr# i# s1#--{-# INLINE writeSTArray #-}-writeSTArray :: Ix i => STArray s i e -> i -> e -> ST s ()-writeSTArray marr@(STArray l u n _) i e =-    unsafeWriteSTArray marr (safeIndex (l,u) n i) e--{-# INLINE unsafeWriteSTArray #-}-unsafeWriteSTArray :: Ix i => STArray s i e -> Int -> e -> ST s ()-unsafeWriteSTArray (STArray _ _ _ marr#) (I# i#) e = ST $ \s1# ->-    case writeArray# marr# i# e s1# of-        s2# -> (# s2#, () #)--------------------------------------------------------------------------- Moving between mutable and immutable--freezeSTArray :: Ix i => STArray s i e -> ST s (Array i e)-freezeSTArray (STArray l u n@(I# n#) marr#) = ST $ \s1# ->-    case newArray# n# arrEleBottom s1#  of { (# s2#, marr'# #) ->-    let copy i# s3# | isTrue# (i# ==# n#) = s3#-                    | otherwise =-            case readArray# marr# i# s3# of { (# s4#, e #) ->-            case writeArray# marr'# i# e s4# of { s5# ->-            copy (i# +# 1#) s5# }} in-    case copy 0# s2#                    of { s3# ->-    case unsafeFreezeArray# marr'# s3#  of { (# s4#, arr# #) ->-    (# s4#, Array l u n arr# #) }}}--{-# INLINE unsafeFreezeSTArray #-}-unsafeFreezeSTArray :: Ix i => STArray s i e -> ST s (Array i e)-unsafeFreezeSTArray (STArray l u n marr#) = ST $ \s1# ->-    case unsafeFreezeArray# marr# s1#   of { (# s2#, arr# #) ->-    (# s2#, Array l u n arr# #) }--thawSTArray :: Ix i => Array i e -> ST s (STArray s i e)-thawSTArray (Array l u n@(I# n#) arr#) = ST $ \s1# ->-    case newArray# n# arrEleBottom s1#  of { (# s2#, marr# #) ->-    let copy i# s3# | isTrue# (i# ==# n#) = s3#-                    | otherwise =-            case indexArray# arr# i#    of { (# e #) ->-            case writeArray# marr# i# e s3# of { s4# ->-            copy (i# +# 1#) s4# }} in-    case copy 0# s2#                    of { s3# ->-    (# s3#, STArray l u n marr# #) }}--{-# INLINE unsafeThawSTArray #-}-unsafeThawSTArray :: Ix i => Array i e -> ST s (STArray s i e)-unsafeThawSTArray (Array l u n arr#) = ST $ \s1# ->-    case unsafeThawArray# arr# s1#      of { (# s2#, marr# #) ->-    (# s2#, STArray l u n marr# #) }
− GHC/Base.hs
@@ -1,1199 +0,0 @@-{--The overall structure of the GHC Prelude is a bit tricky.--  a) We want to avoid "orphan modules", i.e. ones with instance-        decls that don't belong either to a tycon or a class-        defined in the same module--  b) We want to avoid giant modules--So the rough structure is as follows, in (linearised) dependency order---GHC.Prim        Has no implementation.  It defines built-in things, and-                by importing it you bring them into scope.-                The source file is GHC.Prim.hi-boot, which is just-                copied to make GHC.Prim.hi--GHC.Base        Classes: Eq, Ord, Functor, Monad-                Types:   list, (), Int, Bool, Ordering, Char, String--Data.Tuple      Types: tuples, plus instances for GHC.Base classes--GHC.Show        Class: Show, plus instances for GHC.Base/GHC.Tup types--GHC.Enum        Class: Enum,  plus instances for GHC.Base/GHC.Tup types--Data.Maybe      Type: Maybe, plus instances for GHC.Base classes--GHC.List        List functions--GHC.Num         Class: Num, plus instances for Int-                Type:  Integer, plus instances for all classes so far (Eq, Ord, Num, Show)--                Integer is needed here because it is mentioned in the signature-                of 'fromInteger' in class Num--GHC.Real        Classes: Real, Integral, Fractional, RealFrac-                         plus instances for Int, Integer-                Types:  Ratio, Rational-                        plus intances for classes so far--                Rational is needed here because it is mentioned in the signature-                of 'toRational' in class Real--GHC.ST  The ST monad, instances and a few helper functions--Ix              Classes: Ix, plus instances for Int, Bool, Char, Integer, Ordering, tuples--GHC.Arr         Types: Array, MutableArray, MutableVar--                Arrays are used by a function in GHC.Float--GHC.Float       Classes: Floating, RealFloat-                Types:   Float, Double, plus instances of all classes so far--                This module contains everything to do with floating point.-                It is a big module (900 lines)-                With a bit of luck, many modules can be compiled without ever reading GHC.Float.hi---Other Prelude modules are much easier with fewer complex dependencies.--}--{-# LANGUAGE Unsafe #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , BangPatterns-           , ExplicitForAll-           , MagicHash-           , UnboxedTuples-           , ExistentialQuantification-           , RankNTypes-  #-}--- -fno-warn-orphans is needed for things like:--- Orphan rule: "x# -# x#" ALWAYS forall x# :: Int# -# x# x# = 0-{-# OPTIONS_GHC -fno-warn-orphans #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Base--- Copyright   :  (c) The University of Glasgow, 1992-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ Basic data types and classes.-----------------------------------------------------------------------------------#include "MachDeps.h"--module GHC.Base-        (-        module GHC.Base,-        module GHC.Classes,-        module GHC.CString,-        module GHC.Magic,-        module GHC.Types,-        module GHC.Prim,        -- Re-export GHC.Prim and [boot] GHC.Err,-                                -- to avoid lots of people having to-        module GHC.Err          -- import it explicitly-  )-        where--import GHC.Types-import GHC.Classes-import GHC.CString-import GHC.Magic-import GHC.Prim-import GHC.Err-import {-# SOURCE #-} GHC.IO (failIO)--import GHC.Tuple ()     -- Note [Depend on GHC.Tuple]-import GHC.Integer ()   -- Note [Depend on GHC.Integer]--infixr 9  .-infixr 5  ++-infixl 4  <$-infixl 1  >>, >>=-infixr 1  =<<-infixr 0  $, $!--infixl 4 <*>, <*, *>, <**>--default ()              -- Double isn't available yet--{--Note [Depend on GHC.Integer]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The Integer type is special because TidyPgm uses-GHC.Integer.Type.mkInteger to construct Integer literal values-Currently it reads the interface file whether or not the current-module *has* any Integer literals, so it's important that-GHC.Integer.Type (in patckage integer-gmp or integer-simple) is-compiled before any other module.  (There's a hack in GHC to disable-this for packages ghc-prim, integer-gmp, integer-simple, which aren't-allowed to contain any Integer literals.)--Likewise we implicitly need Integer when deriving things like Eq-instances.--The danger is that if the build system doesn't know about the dependency-on Integer, it'll compile some base module before GHC.Integer.Type,-resulting in:-  Failed to load interface for ‘GHC.Integer.Type’-    There are files missing in the ‘integer-gmp’ package,--Bottom line: we make GHC.Base depend on GHC.Integer; and everything-else either depends on GHC.Base, or does not have NoImplicitPrelude-(and hence depends on Prelude).--Note [Depend on GHC.Tuple]-~~~~~~~~~~~~~~~~~~~~~~~~~~-Similarly, tuple syntax (or ()) creates an implicit dependency on-GHC.Tuple, so we use the same rule as for Integer --- see Note [Depend on-GHC.Integer] --- to explain this to the build system.  We make GHC.Base-depend on GHC.Tuple, and everything else depends on GHC.Base or Prelude.--}--#if 0--- for use when compiling GHC.Base itself doesn't work-data  Bool  =  False | True-data Ordering = LT | EQ | GT-data Char = C# Char#-type  String = [Char]-data Int = I# Int#-data  ()  =  ()-data [] a = MkNil--not True = False-(&&) True True = True-otherwise = True--build = error "urk"-foldr = error "urk"-#endif---- | The 'Maybe' type encapsulates an optional value.  A value of type--- @'Maybe' a@ either contains a value of type @a@ (represented as @'Just' a@),--- or it is empty (represented as 'Nothing').  Using 'Maybe' is a good way to--- deal with errors or exceptional cases without resorting to drastic--- measures such as 'error'.------ The 'Maybe' type is also a monad.  It is a simple kind of error--- monad, where all errors are represented by 'Nothing'.  A richer--- error monad can be built using the 'Data.Either.Either' type.----data  Maybe a  =  Nothing | Just a-  deriving (Eq, Ord)---- | The class of monoids (types with an associative binary operation that--- has an identity).  Instances should satisfy the following laws:------  * @mappend mempty x = x@------  * @mappend x mempty = x@------  * @mappend x (mappend y z) = mappend (mappend x y) z@------  * @mconcat = 'foldr' mappend mempty@------ The method names refer to the monoid of lists under concatenation,--- but there are many other instances.------ Some types can be viewed as a monoid in more than one way,--- e.g. both addition and multiplication on numbers.--- In such cases we often define @newtype@s and make those instances--- of 'Monoid', e.g. 'Sum' and 'Product'.--class Monoid a where-        mempty  :: a-        -- ^ Identity of 'mappend'-        mappend :: a -> a -> a-        -- ^ An associative operation-        mconcat :: [a] -> a--        -- ^ Fold a list using the monoid.-        -- For most types, the default definition for 'mconcat' will be-        -- used, but the function is included in the class definition so-        -- that an optimized version can be provided for specific types.--        mconcat = foldr mappend mempty--instance Monoid [a] where-        {-# INLINE mempty #-}-        mempty  = []-        {-# INLINE mappend #-}-        mappend = (++)-        {-# INLINE mconcat #-}-        mconcat xss = [x | xs <- xss, x <- xs]--- See Note: [List comprehensions and inlining]--{--Note: [List comprehensions and inlining]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The list monad operations are traditionally described in terms of concatMap:--xs >>= f = concatMap f xs--Similarly, mconcat for lists is just concat. Here in Base, however, we don't-have concatMap, and we'll refrain from adding it here so it won't have to be-hidden in imports. Instead, we use GHC's list comprehension desugaring-mechanism to define mconcat and the Applicative and Monad instances for lists.-We mark them INLINE because the inliner is not generally too keen to inline-build forms such as the ones these desugar to without our insistence.  Defining-these using list comprehensions instead of foldr has an additional potential-benefit, as described in compiler/deSugar/DsListComp.lhs: if optimizations-needed to make foldr/build forms efficient are turned off, we'll get reasonably-efficient translations anyway.--}--instance Monoid b => Monoid (a -> b) where-        mempty _ = mempty-        mappend f g x = f x `mappend` g x--instance Monoid () where-        -- Should it be strict?-        mempty        = ()-        _ `mappend` _ = ()-        mconcat _     = ()--instance (Monoid a, Monoid b) => Monoid (a,b) where-        mempty = (mempty, mempty)-        (a1,b1) `mappend` (a2,b2) =-                (a1 `mappend` a2, b1 `mappend` b2)--instance (Monoid a, Monoid b, Monoid c) => Monoid (a,b,c) where-        mempty = (mempty, mempty, mempty)-        (a1,b1,c1) `mappend` (a2,b2,c2) =-                (a1 `mappend` a2, b1 `mappend` b2, c1 `mappend` c2)--instance (Monoid a, Monoid b, Monoid c, Monoid d) => Monoid (a,b,c,d) where-        mempty = (mempty, mempty, mempty, mempty)-        (a1,b1,c1,d1) `mappend` (a2,b2,c2,d2) =-                (a1 `mappend` a2, b1 `mappend` b2,-                 c1 `mappend` c2, d1 `mappend` d2)--instance (Monoid a, Monoid b, Monoid c, Monoid d, Monoid e) =>-                Monoid (a,b,c,d,e) where-        mempty = (mempty, mempty, mempty, mempty, mempty)-        (a1,b1,c1,d1,e1) `mappend` (a2,b2,c2,d2,e2) =-                (a1 `mappend` a2, b1 `mappend` b2, c1 `mappend` c2,-                 d1 `mappend` d2, e1 `mappend` e2)---- lexicographical ordering-instance Monoid Ordering where-        mempty         = EQ-        LT `mappend` _ = LT-        EQ `mappend` y = y-        GT `mappend` _ = GT---- | Lift a semigroup into 'Maybe' forming a 'Monoid' according to--- <http://en.wikipedia.org/wiki/Monoid>: \"Any semigroup @S@ may be--- turned into a monoid simply by adjoining an element @e@ not in @S@--- and defining @e*e = e@ and @e*s = s = s*e@ for all @s ∈ S@.\" Since--- there is no \"Semigroup\" typeclass providing just 'mappend', we--- use 'Monoid' instead.-instance Monoid a => Monoid (Maybe a) where-  mempty = Nothing-  Nothing `mappend` m = m-  m `mappend` Nothing = m-  Just m1 `mappend` Just m2 = Just (m1 `mappend` m2)--instance Monoid a => Applicative ((,) a) where-    pure x = (mempty, x)-    (u, f) <*> (v, x) = (u `mappend` v, f x)---{- | The 'Functor' class is used for types that can be mapped over.-Instances of 'Functor' should satisfy the following laws:--> fmap id  ==  id-> fmap (f . g)  ==  fmap f . fmap g--The instances of 'Functor' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'-satisfy these laws.--}--class  Functor f  where-    fmap        :: (a -> b) -> f a -> f b--    -- | Replace all locations in the input with the same value.-    -- The default definition is @'fmap' . 'const'@, but this may be-    -- overridden with a more efficient version.-    (<$)        :: a -> f b -> f a-    (<$)        =  fmap . const---- | A functor with application, providing operations to------ * embed pure expressions ('pure'), and------ * sequence computations and combine their results ('<*>').------ A minimal complete definition must include implementations of these--- functions satisfying the following laws:------ [/identity/]------      @'pure' 'id' '<*>' v = v@------ [/composition/]------      @'pure' (.) '<*>' u '<*>' v '<*>' w = u '<*>' (v '<*>' w)@------ [/homomorphism/]------      @'pure' f '<*>' 'pure' x = 'pure' (f x)@------ [/interchange/]------      @u '<*>' 'pure' y = 'pure' ('$' y) '<*>' u@------ The other methods have the following default definitions, which may--- be overridden with equivalent specialized implementations:------   * @u '*>' v = 'pure' ('const' 'id') '<*>' u '<*>' v@------   * @u '<*' v = 'pure' 'const' '<*>' u '<*>' v@------ As a consequence of these laws, the 'Functor' instance for @f@ will satisfy------   * @'fmap' f x = 'pure' f '<*>' x@------ If @f@ is also a 'Monad', it should satisfy------   * @'pure' = 'return'@------   * @('<*>') = 'ap'@------ (which implies that 'pure' and '<*>' satisfy the applicative functor laws).--class Functor f => Applicative f where-    -- | Lift a value.-    pure :: a -> f a--    -- | Sequential application.-    (<*>) :: f (a -> b) -> f a -> f b--    -- | Sequence actions, discarding the value of the first argument.-    (*>) :: f a -> f b -> f b-    a1 *> a2 = (id <$ a1) <*> a2-    -- This is essentially the same as liftA2 (const id), but if the-    -- Functor instance has an optimized (<$), we want to use that instead.--    -- | Sequence actions, discarding the value of the second argument.-    (<*) :: f a -> f b -> f a-    (<*) = liftA2 const---- | A variant of '<*>' with the arguments reversed.-(<**>) :: Applicative f => f a -> f (a -> b) -> f b-(<**>) = liftA2 (flip ($))---- | Lift a function to actions.--- This function may be used as a value for `fmap` in a `Functor` instance.-liftA :: Applicative f => (a -> b) -> f a -> f b-liftA f a = pure f <*> a--- Caution: since this may be used for `fmap`, we can't use the obvious--- definition of liftA = fmap.---- | Lift a binary function to actions.-liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c-liftA2 f a b = fmap f a <*> b---- | Lift a ternary function to actions.-liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d-liftA3 f a b c = fmap f a <*> b <*> c---{-# INLINEABLE liftA #-}-{-# SPECIALISE liftA :: (a1->r) -> IO a1 -> IO r #-}-{-# SPECIALISE liftA :: (a1->r) -> Maybe a1 -> Maybe r #-}-{-# INLINEABLE liftA2 #-}-{-# SPECIALISE liftA2 :: (a1->a2->r) -> IO a1 -> IO a2 -> IO r #-}-{-# SPECIALISE liftA2 :: (a1->a2->r) -> Maybe a1 -> Maybe a2 -> Maybe r #-}-{-# INLINEABLE liftA3 #-}-{-# SPECIALISE liftA3 :: (a1->a2->a3->r) -> IO a1 -> IO a2 -> IO a3 -> IO r #-}-{-# SPECIALISE liftA3 :: (a1->a2->a3->r) ->-                                Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe r #-}---- | The 'join' function is the conventional monad join operator. It--- is used to remove one level of monadic structure, projecting its--- bound argument into the outer level.-join              :: (Monad m) => m (m a) -> m a-join x            =  x >>= id--{- | The 'Monad' class defines the basic operations over a /monad/,-a concept from a branch of mathematics known as /category theory/.-From the perspective of a Haskell programmer, however, it is best to-think of a monad as an /abstract datatype/ of actions.-Haskell's @do@ expressions provide a convenient syntax for writing-monadic expressions.--Instances of 'Monad' should satisfy the following laws:--* @'return' a '>>=' k  =  k a@-* @m '>>=' 'return'  =  m@-* @m '>>=' (\x -> k x '>>=' h)  =  (m '>>=' k) '>>=' h@--Furthermore, the 'Monad' and 'Applicative' operations should relate as follows:--* @'pure' = 'return'@-* @('<*>') = 'ap'@--The above laws imply:--* @'fmap' f xs  =  xs '>>=' 'return' . f@-* @('>>') = ('*>')@--and that 'pure' and ('<*>') satisfy the applicative functor laws.--The instances of 'Monad' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'-defined in the "Prelude" satisfy these laws.--}-class Applicative m => Monad m where-    -- | Sequentially compose two actions, passing any value produced-    -- by the first as an argument to the second.-    (>>=)       :: forall a b. m a -> (a -> m b) -> m b--    -- | Sequentially compose two actions, discarding any value produced-    -- by the first, like sequencing operators (such as the semicolon)-    -- in imperative languages.-    (>>)        :: forall a b. m a -> m b -> m b-    m >> k = m >>= \_ -> k -- See Note [Recursive bindings for Applicative/Monad]-    {-# INLINE (>>) #-}--    -- | Inject a value into the monadic type.-    return      :: a -> m a-    return      = pure--    -- | Fail with a message.  This operation is not part of the-    -- mathematical definition of a monad, but is invoked on pattern-match-    -- failure in a @do@ expression.-    fail        :: String -> m a-    fail s      = error s--{- Note [Recursive bindings for Applicative/Monad]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--The original Applicative/Monad proposal stated that after-implementation, the designated implementation of (>>) would become--  (>>) :: forall a b. m a -> m b -> m b-  (>>) = (*>)--by default. You might be inclined to change this to reflect the stated-proposal, but you really shouldn't! Why? Because people tend to define-such instances the /other/ way around: in particular, it is perfectly-legitimate to define an instance of Applicative (*>) in terms of (>>),-which would lead to an infinite loop for the default implementation of-Monad! And people do this in the wild.--This turned into a nasty bug that was tricky to track down, and rather-than eliminate it everywhere upstream, it's easier to just retain the-original default.---}---- | Same as '>>=', but with the arguments interchanged.-{-# SPECIALISE (=<<) :: (a -> [b]) -> [a] -> [b] #-}-(=<<)           :: Monad m => (a -> m b) -> m a -> m b-f =<< x         = x >>= f---- | Conditional execution of 'Applicative' expressions. For example,------ > when debug (putStrLn "Debugging")------ will output the string @Debugging@ if the Boolean value @debug@--- is 'True', and otherwise do nothing.-when      :: (Applicative f) => Bool -> f () -> f ()-{-# INLINEABLE when #-}-{-# SPECIALISE when :: Bool -> IO () -> IO () #-}-{-# SPECIALISE when :: Bool -> Maybe () -> Maybe () #-}-when p s  = if p then s else pure ()---- | Evaluate each action in the sequence from left to right,--- and collect the results.-sequence :: Monad m => [m a] -> m [a]-{-# INLINE sequence #-}-sequence = mapM id--- Note: [sequence and mapM]---- | @'mapM' f@ is equivalent to @'sequence' . 'map' f@.-mapM :: Monad m => (a -> m b) -> [a] -> m [b]-{-# INLINE mapM #-}-mapM f as = foldr k (return []) as-            where-              k a r = do { x <- f a; xs <- r; return (x:xs) }--{--Note: [sequence and mapM]-~~~~~~~~~~~~~~~~~~~~~~~~~-Originally, we defined--mapM f = sequence . map f--This relied on list fusion to produce efficient code for mapM, and led to-excessive allocation in cryptarithm2. Defining--sequence = mapM id--relies only on inlining a tiny function (id) and beta reduction, which tends to-be a more reliable aspect of simplification. Indeed, this does not lead to-similar problems in nofib.--}---- | Promote a function to a monad.-liftM   :: (Monad m) => (a1 -> r) -> m a1 -> m r-liftM f m1              = do { x1 <- m1; return (f x1) }---- | Promote a function to a monad, scanning the monadic arguments from--- left to right.  For example,------ >    liftM2 (+) [0,1] [0,2] = [0,2,1,3]--- >    liftM2 (+) (Just 1) Nothing = Nothing----liftM2  :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r-liftM2 f m1 m2          = do { x1 <- m1; x2 <- m2; return (f x1 x2) }---- | Promote a function to a monad, scanning the monadic arguments from--- left to right (cf. 'liftM2').-liftM3  :: (Monad m) => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r-liftM3 f m1 m2 m3       = do { x1 <- m1; x2 <- m2; x3 <- m3; return (f x1 x2 x3) }---- | Promote a function to a monad, scanning the monadic arguments from--- left to right (cf. 'liftM2').-liftM4  :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r-liftM4 f m1 m2 m3 m4    = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; return (f x1 x2 x3 x4) }---- | Promote a function to a monad, scanning the monadic arguments from--- left to right (cf. 'liftM2').-liftM5  :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r-liftM5 f m1 m2 m3 m4 m5 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; x5 <- m5; return (f x1 x2 x3 x4 x5) }--{-# INLINEABLE liftM #-}-{-# SPECIALISE liftM :: (a1->r) -> IO a1 -> IO r #-}-{-# SPECIALISE liftM :: (a1->r) -> Maybe a1 -> Maybe r #-}-{-# INLINEABLE liftM2 #-}-{-# SPECIALISE liftM2 :: (a1->a2->r) -> IO a1 -> IO a2 -> IO r #-}-{-# SPECIALISE liftM2 :: (a1->a2->r) -> Maybe a1 -> Maybe a2 -> Maybe r #-}-{-# INLINEABLE liftM3 #-}-{-# SPECIALISE liftM3 :: (a1->a2->a3->r) -> IO a1 -> IO a2 -> IO a3 -> IO r #-}-{-# SPECIALISE liftM3 :: (a1->a2->a3->r) -> Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe r #-}-{-# INLINEABLE liftM4 #-}-{-# SPECIALISE liftM4 :: (a1->a2->a3->a4->r) -> IO a1 -> IO a2 -> IO a3 -> IO a4 -> IO r #-}-{-# SPECIALISE liftM4 :: (a1->a2->a3->a4->r) -> Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe a4 -> Maybe r #-}-{-# INLINEABLE liftM5 #-}-{-# SPECIALISE liftM5 :: (a1->a2->a3->a4->a5->r) -> IO a1 -> IO a2 -> IO a3 -> IO a4 -> IO a5 -> IO r #-}-{-# SPECIALISE liftM5 :: (a1->a2->a3->a4->a5->r) -> Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe a4 -> Maybe a5 -> Maybe r #-}--{- | In many situations, the 'liftM' operations can be replaced by uses of-'ap', which promotes function application.-->       return f `ap` x1 `ap` ... `ap` xn--is equivalent to-->       liftMn f x1 x2 ... xn---}--ap                :: (Monad m) => m (a -> b) -> m a -> m b-ap m1 m2          = do { x1 <- m1; x2 <- m2; return (x1 x2) }--- Since many Applicative instances define (<*>) = ap, we--- cannot define ap = (<*>)-{-# INLINEABLE ap #-}-{-# SPECIALISE ap :: IO (a -> b) -> IO a -> IO b #-}-{-# SPECIALISE ap :: Maybe (a -> b) -> Maybe a -> Maybe b #-}---- instances for Prelude types--instance Functor ((->) r) where-    fmap = (.)--instance Applicative ((->) a) where-    pure = const-    (<*>) f g x = f x (g x)--instance Monad ((->) r) where-    return = const-    f >>= k = \ r -> k (f r) r--instance Functor ((,) a) where-    fmap f (x,y) = (x, f y)---instance  Functor Maybe  where-    fmap _ Nothing       = Nothing-    fmap f (Just a)      = Just (f a)--instance Applicative Maybe where-    pure = Just--    Just f  <*> m       = fmap f m-    Nothing <*> _m      = Nothing--    Just _m1 *> m2      = m2-    Nothing  *> _m2     = Nothing--instance  Monad Maybe  where-    (Just x) >>= k      = k x-    Nothing  >>= _      = Nothing--    (>>) = (*>)--    return              = Just-    fail _              = Nothing---- -------------------------------------------------------------------------------- The Alternative class definition--infixl 3 <|>---- | A monoid on applicative functors.------ If defined, 'some' and 'many' should be the least solutions--- of the equations:------ * @some v = (:) '<$>' v '<*>' many v@------ * @many v = some v '<|>' 'pure' []@-class Applicative f => Alternative f where-    -- | The identity of '<|>'-    empty :: f a-    -- | An associative binary operation-    (<|>) :: f a -> f a -> f a--    -- | One or more.-    some :: f a -> f [a]-    some v = some_v-      where-        many_v = some_v <|> pure []-        some_v = (fmap (:) v) <*> many_v--    -- | Zero or more.-    many :: f a -> f [a]-    many v = many_v-      where-        many_v = some_v <|> pure []-        some_v = (fmap (:) v) <*> many_v---instance Alternative Maybe where-    empty = Nothing-    Nothing <|> r = r-    l       <|> _ = l---- -------------------------------------------------------------------------------- The MonadPlus class definition---- | Monads that also support choice and failure.-class (Alternative m, Monad m) => MonadPlus m where-   -- | the identity of 'mplus'.  It should also satisfy the equations-   ---   -- > mzero >>= f  =  mzero-   -- > v >> mzero   =  mzero-   ---   mzero :: m a-   mzero = empty--   -- | an associative operation-   mplus :: m a -> m a -> m a-   mplus = (<|>)--instance MonadPlus Maybe--------------------------------------------------- The list type--instance Functor [] where-    {-# INLINE fmap #-}-    fmap = map---- See Note: [List comprehensions and inlining]-instance Applicative [] where-    {-# INLINE pure #-}-    pure x    = [x]-    {-# INLINE (<*>) #-}-    fs <*> xs = [f x | f <- fs, x <- xs]-    {-# INLINE (*>) #-}-    xs *> ys  = [y | _ <- xs, y <- ys]---- See Note: [List comprehensions and inlining]-instance Monad []  where-    {-# INLINE (>>=) #-}-    xs >>= f             = [y | x <- xs, y <- f x]-    {-# INLINE (>>) #-}-    (>>) = (*>)-    {-# INLINE return #-}-    return x            = [x]-    {-# INLINE fail #-}-    fail _              = []--instance Alternative [] where-    empty = []-    (<|>) = (++)--instance MonadPlus []--{--A few list functions that appear here because they are used here.-The rest of the prelude list functions are in GHC.List.--}---------------------------------------------------      foldr/build/augment--------------------------------------------------- | 'foldr', applied to a binary operator, a starting value (typically--- the right-identity of the operator), and a list, reduces the list--- using the binary operator, from right to left:------ > foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)--foldr            :: (a -> b -> b) -> b -> [a] -> b--- foldr _ z []     =  z--- foldr f z (x:xs) =  f x (foldr f z xs)-{-# INLINE [0] foldr #-}--- Inline only in the final stage, after the foldr/cons rule has had a chance--- Also note that we inline it when it has *two* parameters, which are the--- ones we are keen about specialising!-foldr k z = go-          where-            go []     = z-            go (y:ys) = y `k` go ys---- | A list producer that can be fused with 'foldr'.--- This function is merely------ >    build g = g (:) []------ but GHC's simplifier will transform an expression of the form--- @'foldr' k z ('build' g)@, which may arise after inlining, to @g k z@,--- which avoids producing an intermediate list.--build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]-{-# INLINE [1] build #-}-        -- The INLINE is important, even though build is tiny,-        -- because it prevents [] getting inlined in the version that-        -- appears in the interface file.  If [] *is* inlined, it-        -- won't match with [] appearing in rules in an importing module.-        ---        -- The "1" says to inline in phase 1--build g = g (:) []---- | A list producer that can be fused with 'foldr'.--- This function is merely------ >    augment g xs = g (:) xs------ but GHC's simplifier will transform an expression of the form--- @'foldr' k z ('augment' g xs)@, which may arise after inlining, to--- @g k ('foldr' k z xs)@, which avoids producing an intermediate list.--augment :: forall a. (forall b. (a->b->b) -> b -> b) -> [a] -> [a]-{-# INLINE [1] augment #-}-augment g xs = g (:) xs--{-# RULES-"fold/build"    forall k z (g::forall b. (a->b->b) -> b -> b) .-                foldr k z (build g) = g k z--"foldr/augment" forall k z xs (g::forall b. (a->b->b) -> b -> b) .-                foldr k z (augment g xs) = g k (foldr k z xs)--"foldr/id"                        foldr (:) [] = \x  -> x-"foldr/app"     [1] forall ys. foldr (:) ys = \xs -> xs ++ ys-        -- Only activate this from phase 1, because that's-        -- when we disable the rule that expands (++) into foldr---- The foldr/cons rule looks nice, but it can give disastrously--- bloated code when commpiling---      array (a,b) [(1,2), (2,2), (3,2), ...very long list... ]--- i.e. when there are very very long literal lists--- So I've disabled it for now. We could have special cases--- for short lists, I suppose.--- "foldr/cons" forall k z x xs. foldr k z (x:xs) = k x (foldr k z xs)--"foldr/single"  forall k z x. foldr k z [x] = k x z-"foldr/nil"     forall k z.   foldr k z []  = z--"foldr/cons/build" forall k z x (g::forall b. (a->b->b) -> b -> b) .-                           foldr k z (x:build g) = k x (g k z)--"augment/build" forall (g::forall b. (a->b->b) -> b -> b)-                       (h::forall b. (a->b->b) -> b -> b) .-                       augment g (build h) = build (\c n -> g c (h c n))-"augment/nil"   forall (g::forall b. (a->b->b) -> b -> b) .-                        augment g [] = build g- #-}---- This rule is true, but not (I think) useful:---      augment g (augment h t) = augment (\cn -> g c (h c n)) t---------------------------------------------------              map--------------------------------------------------- | 'map' @f xs@ is the list obtained by applying @f@ to each element--- of @xs@, i.e.,------ > map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]--- > map f [x1, x2, ...] == [f x1, f x2, ...]--map :: (a -> b) -> [a] -> [b]-{-# NOINLINE [1] map #-}    -- We want the RULE to fire first.-                            -- It's recursive, so won't inline anyway,-                            -- but saying so is more explicit-map _ []     = []-map f (x:xs) = f x : map f xs---- Note eta expanded-mapFB ::  (elt -> lst -> lst) -> (a -> elt) -> a -> lst -> lst-{-# INLINE [0] mapFB #-}-mapFB c f = \x ys -> c (f x) ys---- The rules for map work like this.------ Up to (but not including) phase 1, we use the "map" rule to--- rewrite all saturated applications of map with its build/fold--- form, hoping for fusion to happen.--- In phase 1 and 0, we switch off that rule, inline build, and--- switch on the "mapList" rule, which rewrites the foldr/mapFB--- thing back into plain map.------ It's important that these two rules aren't both active at once--- (along with build's unfolding) else we'd get an infinite loop--- in the rules.  Hence the activation control below.------ The "mapFB" rule optimises compositions of map.------ This same pattern is followed by many other functions:--- e.g. append, filter, iterate, repeat, etc.--{-# RULES-"map"       [~1] forall f xs.   map f xs                = build (\c n -> foldr (mapFB c f) n xs)-"mapList"   [1]  forall f.      foldr (mapFB (:) f) []  = map f-"mapFB"     forall c f g.       mapFB (mapFB c f) g     = mapFB c (f.g)-  #-}---- See Breitner, Eisenberg, Peyton Jones, and Weirich, "Safe Zero-cost--- Coercions for Haskell", section 6.5:---   http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/coercible.pdf--{-# RULES "map/coerce" [1] map coerce = coerce #-}----------------------------------------------------              append--------------------------------------------------- | Append two lists, i.e.,------ > [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]--- > [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]------ If the first list is not finite, the result is the first list.--(++) :: [a] -> [a] -> [a]-{-# NOINLINE [1] (++) #-}    -- We want the RULE to fire first.-                             -- It's recursive, so won't inline anyway,-                             -- but saying so is more explicit-(++) []     ys = ys-(++) (x:xs) ys = x : xs ++ ys--{-# RULES-"++"    [~1] forall xs ys. xs ++ ys = augment (\c n -> foldr c n xs) ys-  #-}----- |'otherwise' is defined as the value 'True'.  It helps to make--- guards more readable.  eg.------ >  f x | x < 0     = ...--- >      | otherwise = ...-otherwise               :: Bool-otherwise               =  True--------------------------------------------------- Type Char and String--------------------------------------------------- | A 'String' is a list of characters.  String constants in Haskell are values--- of type 'String'.----type String = [Char]--unsafeChr :: Int -> Char-unsafeChr (I# i#) = C# (chr# i#)---- | The 'Prelude.fromEnum' method restricted to the type 'Data.Char.Char'.-ord :: Char -> Int-ord (C# c#) = I# (ord# c#)---- | This 'String' equality predicate is used when desugaring--- pattern-matches against strings.-eqString :: String -> String -> Bool-eqString []       []       = True-eqString (c1:cs1) (c2:cs2) = c1 == c2 && cs1 `eqString` cs2-eqString _        _        = False--{-# RULES "eqString" (==) = eqString #-}--- eqString also has a BuiltInRule in PrelRules.lhs:---      eqString (unpackCString# (Lit s1)) (unpackCString# (Lit s2) = s1==s2---------------------------------------------------- 'Int' related definitions-------------------------------------------------maxInt, minInt :: Int--{- Seems clumsy. Should perhaps put minInt and MaxInt directly into MachDeps.h -}-#if WORD_SIZE_IN_BITS == 31-minInt  = I# (-0x40000000#)-maxInt  = I# 0x3FFFFFFF#-#elif WORD_SIZE_IN_BITS == 32-minInt  = I# (-0x80000000#)-maxInt  = I# 0x7FFFFFFF#-#else-minInt  = I# (-0x8000000000000000#)-maxInt  = I# 0x7FFFFFFFFFFFFFFF#-#endif--------------------------------------------------- The function type--------------------------------------------------- | Identity function.-id                      :: a -> a-id x                    =  x---- Assertion function.  This simply ignores its boolean argument.--- The compiler may rewrite it to @('assertError' line)@.---- | If the first argument evaluates to 'True', then the result is the--- second argument.  Otherwise an 'AssertionFailed' exception is raised,--- containing a 'String' with the source file and line number of the--- call to 'assert'.------ Assertions can normally be turned on or off with a compiler flag--- (for GHC, assertions are normally on unless optimisation is turned on--- with @-O@ or the @-fignore-asserts@--- option is given).  When assertions are turned off, the first--- argument to 'assert' is ignored, and the second argument is--- returned as the result.----      SLPJ: in 5.04 etc 'assert' is in GHC.Prim,---      but from Template Haskell onwards it's simply---      defined here in Base.lhs-assert :: Bool -> a -> a-assert _pred r = r--breakpoint :: a -> a-breakpoint r = r--breakpointCond :: Bool -> a -> a-breakpointCond _ r = r--data Opaque = forall a. O a---- | Constant function.-const                   :: a -> b -> a-const x _               =  x---- | Function composition.-{-# INLINE (.) #-}--- Make sure it has TWO args only on the left, so that it inlines--- when applied to two functions, even if there is no final argument-(.)    :: (b -> c) -> (a -> b) -> a -> c-(.) f g = \x -> f (g x)---- | @'flip' f@ takes its (first) two arguments in the reverse order of @f@.-flip                    :: (a -> b -> c) -> b -> a -> c-flip f x y              =  f y x---- | Application operator.  This operator is redundant, since ordinary--- application @(f x)@ means the same as @(f '$' x)@. However, '$' has--- low, right-associative binding precedence, so it sometimes allows--- parentheses to be omitted; for example:------ >     f $ g $ h x  =  f (g (h x))------ It is also useful in higher-order situations, such as @'map' ('$' 0) xs@,--- or @'Data.List.zipWith' ('$') fs xs@.-{-# INLINE ($) #-}-($)                     :: (a -> b) -> a -> b-f $ x                   =  f x---- | Strict (call-by-value) application operator. It takes a function and an--- argument, evaluates the argument to weak head normal form (WHNF), then calls--- the function with that value.--($!)                    :: (a -> b) -> a -> b-f $! x                  = let !vx = x in f vx  -- see #2273---- | @'until' p f@ yields the result of applying @f@ until @p@ holds.-until                   :: (a -> Bool) -> (a -> a) -> a -> a-until p f = go-  where-    go x | p x          = x-         | otherwise    = go (f x)---- | 'asTypeOf' is a type-restricted version of 'const'.  It is usually--- used as an infix operator, and its typing forces its first argument--- (which is usually overloaded) to have the same type as the second.-asTypeOf                :: a -> a -> a-asTypeOf                =  const--------------------------------------------------- Functor/Applicative/Monad instances for IO-------------------------------------------------instance  Functor IO where-   fmap f x = x >>= (return . f)--instance Applicative IO where-    pure = return-    (<*>) = ap--instance  Monad IO  where-    {-# INLINE return #-}-    {-# INLINE (>>)   #-}-    {-# INLINE (>>=)  #-}-    m >> k    = m >>= \ _ -> k-    return    = returnIO-    (>>=)     = bindIO-    fail s    = failIO s--returnIO :: a -> IO a-returnIO x = IO $ \ s -> (# s, x #)--bindIO :: IO a -> (a -> IO b) -> IO b-bindIO (IO m) k = IO $ \ s -> case m s of (# new_s, a #) -> unIO (k a) new_s--thenIO :: IO a -> IO b -> IO b-thenIO (IO m) k = IO $ \ s -> case m s of (# new_s, _ #) -> unIO k new_s--unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))-unIO (IO a) = a--{- |-Returns the 'tag' of a constructor application; this function is used-by the deriving code for Eq, Ord and Enum.--The primitive dataToTag# requires an evaluated constructor application-as its argument, so we provide getTag as a wrapper that performs the-evaluation before calling dataToTag#.  We could have dataToTag#-evaluate its argument, but we prefer to do it this way because (a)-dataToTag# can be an inline primop if it doesn't need to do any-evaluation, and (b) we want to expose the evaluation to the-simplifier, because it might be possible to eliminate the evaluation-in the case when the argument is already known to be evaluated.--}-{-# INLINE getTag #-}-getTag :: a -> Int#-getTag !x = dataToTag# x--------------------------------------------------- Numeric primops--------------------------------------------------- Definitions of the boxed PrimOps; these will be--- used in the case of partial applications, etc.--{-# INLINE quotInt #-}-{-# INLINE remInt #-}--quotInt, remInt, divInt, modInt :: Int -> Int -> Int-(I# x) `quotInt`  (I# y) = I# (x `quotInt#` y)-(I# x) `remInt`   (I# y) = I# (x `remInt#`  y)-(I# x) `divInt`   (I# y) = I# (x `divInt#`  y)-(I# x) `modInt`   (I# y) = I# (x `modInt#`  y)--quotRemInt :: Int -> Int -> (Int, Int)-(I# x) `quotRemInt` (I# y) = case x `quotRemInt#` y of-                             (# q, r #) ->-                                 (I# q, I# r)--divModInt :: Int -> Int -> (Int, Int)-(I# x) `divModInt` (I# y) = case x `divModInt#` y of-                            (# q, r #) -> (I# q, I# r)--divModInt# :: Int# -> Int# -> (# Int#, Int# #)-x# `divModInt#` y#- | isTrue# (x# ># 0#) && isTrue# (y# <# 0#) =-                                    case (x# -# 1#) `quotRemInt#` y# of-                                      (# q, r #) -> (# q -# 1#, r +# y# +# 1# #)- | isTrue# (x# <# 0#) && isTrue# (y# ># 0#) =-                                    case (x# +# 1#) `quotRemInt#` y# of-                                      (# q, r #) -> (# q -# 1#, r +# y# -# 1# #)- | otherwise                                =-                                    x# `quotRemInt#` y#---- Wrappers for the shift operations.  The uncheckedShift# family are--- undefined when the amount being shifted by is greater than the size--- in bits of Int#, so these wrappers perform a check and return--- either zero or -1 appropriately.------ Note that these wrappers still produce undefined results when the--- second argument (the shift amount) is negative.---- | Shift the argument left by the specified number of bits--- (which must be non-negative).-shiftL# :: Word# -> Int# -> Word#-a `shiftL#` b   | isTrue# (b >=# WORD_SIZE_IN_BITS#) = 0##-                | otherwise                          = a `uncheckedShiftL#` b---- | Shift the argument right by the specified number of bits--- (which must be non-negative).--- The "RL" means "right, logical" (as opposed to RA for arithmetic)--- (although an arithmetic right shift wouldn't make sense for Word#)-shiftRL# :: Word# -> Int# -> Word#-a `shiftRL#` b  | isTrue# (b >=# WORD_SIZE_IN_BITS#) = 0##-                | otherwise                          = a `uncheckedShiftRL#` b---- | Shift the argument left by the specified number of bits--- (which must be non-negative).-iShiftL# :: Int# -> Int# -> Int#-a `iShiftL#` b  | isTrue# (b >=# WORD_SIZE_IN_BITS#) = 0#-                | otherwise                          = a `uncheckedIShiftL#` b---- | Shift the argument right (signed) by the specified number of bits--- (which must be non-negative).--- The "RA" means "right, arithmetic" (as opposed to RL for logical)-iShiftRA# :: Int# -> Int# -> Int#-a `iShiftRA#` b | isTrue# (b >=# WORD_SIZE_IN_BITS#) = if isTrue# (a <# 0#)-                                                          then (-1#)-                                                          else 0#-                | otherwise                          = a `uncheckedIShiftRA#` b---- | Shift the argument right (unsigned) by the specified number of bits--- (which must be non-negative).--- The "RL" means "right, logical" (as opposed to RA for arithmetic)-iShiftRL# :: Int# -> Int# -> Int#-a `iShiftRL#` b | isTrue# (b >=# WORD_SIZE_IN_BITS#) = 0#-                | otherwise                          = a `uncheckedIShiftRL#` b---- Rules for C strings (the functions themselves are now in GHC.CString)-{-# RULES-"unpack"       [~1] forall a   . unpackCString# a             = build (unpackFoldrCString# a)-"unpack-list"  [1]  forall a   . unpackFoldrCString# a (:) [] = unpackCString# a-"unpack-append"     forall a n . unpackFoldrCString# a (:) n  = unpackAppendCString# a n---- There's a built-in rule (in PrelRules.lhs) for---      unpackFoldr "foo" c (unpackFoldr "baz" c n)  =  unpackFoldr "foobaz" c n--  #-}---#ifdef __HADDOCK__--- | A special argument for the 'Control.Monad.ST.ST' type constructor,--- indexing a state embedded in the 'Prelude.IO' monad by--- 'Control.Monad.ST.stToIO'.-data RealWorld-#endif
− GHC/Char.hs
@@ -1,15 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash #-}--module GHC.Char (chr) where--import GHC.Base-import GHC.Show---- | The 'Prelude.toEnum' method restricted to the type 'Data.Char.Char'.-chr :: Int -> Char-chr i@(I# i#)- | isTrue# (int2Word# i# `leWord#` 0x10FFFF##) = C# (chr# i#)- | otherwise-    = error ("Prelude.chr: bad argument: " ++ showSignedInt (I# 9#) i "")-
− GHC/Conc.hs
@@ -1,119 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE CPP, NoImplicitPrelude #-}-{-# OPTIONS_GHC -fno-warn-missing-signatures #-}-{-# OPTIONS_HADDOCK not-home #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Conc--- Copyright   :  (c) The University of Glasgow, 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ Basic concurrency stuff.------------------------------------------------------------------------------------- No: #hide, because bits of this module are exposed by the stm package.--- However, we don't want this module to be the home location for the--- bits it exports, we'd rather have Control.Concurrent and the other--- higher level modules be the home.  Hence: #not-home--module GHC.Conc-        ( ThreadId(..)--        -- * Forking and suchlike-        , forkIO-        , forkIOWithUnmask-        , forkOn-        , forkOnWithUnmask-        , numCapabilities-        , getNumCapabilities-        , setNumCapabilities-        , getNumProcessors-        , numSparks-        , childHandler-        , myThreadId-        , killThread-        , throwTo-        , par-        , pseq-        , runSparks-        , yield-        , labelThread-        , mkWeakThreadId--        , ThreadStatus(..), BlockReason(..)-        , threadStatus-        , threadCapability--        -- * Waiting-        , threadDelay-        , registerDelay-        , threadWaitRead-        , threadWaitWrite-        , threadWaitReadSTM-        , threadWaitWriteSTM-        , closeFdWith--        -- * Allocation counter and limit-        , setAllocationCounter-        , getAllocationCounter-        , enableAllocationLimit-        , disableAllocationLimit--        -- * TVars-        , STM(..)-        , atomically-        , retry-        , orElse-        , throwSTM-        , catchSTM-        , alwaysSucceeds-        , always-        , TVar(..)-        , newTVar-        , newTVarIO-        , readTVar-        , readTVarIO-        , writeTVar-        , unsafeIOToSTM--        -- * Miscellaneous-        , withMVar-#ifdef mingw32_HOST_OS-        , asyncRead-        , asyncWrite-        , asyncDoProc--        , asyncReadBA-        , asyncWriteBA-#endif--#ifndef mingw32_HOST_OS-        , Signal, HandlerFun, setHandler, runHandlers-#endif--        , ensureIOManagerIsRunning-        , ioManagerCapabilitiesChanged--#ifdef mingw32_HOST_OS-        , ConsoleEvent(..)-        , win32ConsoleHandler-        , toWin32ConsoleEvent-#endif-        , setUncaughtExceptionHandler-        , getUncaughtExceptionHandler--        , reportError, reportStackOverflow-        ) where--import GHC.Conc.IO-import GHC.Conc.Sync--#ifndef mingw32_HOST_OS-import GHC.Conc.Signal-#endif
− GHC/Conc/IO.hs
@@ -1,203 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , MagicHash-           , UnboxedTuples-  #-}-{-# OPTIONS_GHC -fno-warn-missing-signatures #-}-{-# OPTIONS_HADDOCK not-home #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Conc.IO--- Copyright   :  (c) The University of Glasgow, 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ Basic concurrency stuff.------------------------------------------------------------------------------------- No: #hide, because bits of this module are exposed by the stm package.--- However, we don't want this module to be the home location for the--- bits it exports, we'd rather have Control.Concurrent and the other--- higher level modules be the home.  Hence: #not-home--module GHC.Conc.IO-        ( ensureIOManagerIsRunning-        , ioManagerCapabilitiesChanged--        -- * Waiting-        , threadDelay-        , registerDelay-        , threadWaitRead-        , threadWaitWrite-        , threadWaitReadSTM-        , threadWaitWriteSTM-        , closeFdWith--#ifdef mingw32_HOST_OS-        , asyncRead-        , asyncWrite-        , asyncDoProc--        , asyncReadBA-        , asyncWriteBA--        , ConsoleEvent(..)-        , win32ConsoleHandler-        , toWin32ConsoleEvent-#endif-        ) where--import Foreign-import GHC.Base-import GHC.Conc.Sync as Sync-import GHC.Real ( fromIntegral )-import System.Posix.Types--#ifdef mingw32_HOST_OS-import qualified GHC.Conc.Windows as Windows-import GHC.Conc.Windows (asyncRead, asyncWrite, asyncDoProc, asyncReadBA,-                         asyncWriteBA, ConsoleEvent(..), win32ConsoleHandler,-                         toWin32ConsoleEvent)-#else-import qualified GHC.Event.Thread as Event-#endif--ensureIOManagerIsRunning :: IO ()-#ifndef mingw32_HOST_OS-ensureIOManagerIsRunning = Event.ensureIOManagerIsRunning-#else-ensureIOManagerIsRunning = Windows.ensureIOManagerIsRunning-#endif--ioManagerCapabilitiesChanged :: IO ()-#ifndef mingw32_HOST_OS-ioManagerCapabilitiesChanged = Event.ioManagerCapabilitiesChanged-#else-ioManagerCapabilitiesChanged = return ()-#endif---- | Block the current thread until data is available to read on the--- given file descriptor (GHC only).------ This will throw an 'IOError' if the file descriptor was closed--- while this thread was blocked.  To safely close a file descriptor--- that has been used with 'threadWaitRead', use 'closeFdWith'.-threadWaitRead :: Fd -> IO ()-threadWaitRead fd-#ifndef mingw32_HOST_OS-  | threaded  = Event.threadWaitRead fd-#endif-  | otherwise = IO $ \s ->-        case fromIntegral fd of { I# fd# ->-        case waitRead# fd# s of { s' -> (# s', () #)-        }}---- | Block the current thread until data can be written to the--- given file descriptor (GHC only).------ This will throw an 'IOError' if the file descriptor was closed--- while this thread was blocked.  To safely close a file descriptor--- that has been used with 'threadWaitWrite', use 'closeFdWith'.-threadWaitWrite :: Fd -> IO ()-threadWaitWrite fd-#ifndef mingw32_HOST_OS-  | threaded  = Event.threadWaitWrite fd-#endif-  | otherwise = IO $ \s ->-        case fromIntegral fd of { I# fd# ->-        case waitWrite# fd# s of { s' -> (# s', () #)-        }}---- | Returns an STM action that can be used to wait for data--- to read from a file descriptor. The second returned value--- is an IO action that can be used to deregister interest--- in the file descriptor.-threadWaitReadSTM :: Fd -> IO (Sync.STM (), IO ())-threadWaitReadSTM fd -#ifndef mingw32_HOST_OS-  | threaded  = Event.threadWaitReadSTM fd-#endif-  | otherwise = do-      m <- Sync.newTVarIO False-      _ <- Sync.forkIO $ do-        threadWaitRead fd-        Sync.atomically $ Sync.writeTVar m True-      let waitAction = do b <- Sync.readTVar m-                          if b then return () else retry-      let killAction = return ()-      return (waitAction, killAction)---- | Returns an STM action that can be used to wait until data--- can be written to a file descriptor. The second returned value--- is an IO action that can be used to deregister interest--- in the file descriptor.-threadWaitWriteSTM :: Fd -> IO (Sync.STM (), IO ())-threadWaitWriteSTM fd -#ifndef mingw32_HOST_OS-  | threaded  = Event.threadWaitWriteSTM fd-#endif-  | otherwise = do-      m <- Sync.newTVarIO False-      _ <- Sync.forkIO $ do-        threadWaitWrite fd-        Sync.atomically $ Sync.writeTVar m True-      let waitAction = do b <- Sync.readTVar m-                          if b then return () else retry-      let killAction = return ()-      return (waitAction, killAction)---- | Close a file descriptor in a concurrency-safe way (GHC only).  If--- you are using 'threadWaitRead' or 'threadWaitWrite' to perform--- blocking I\/O, you /must/ use this function to close file--- descriptors, or blocked threads may not be woken.------ Any threads that are blocked on the file descriptor via--- 'threadWaitRead' or 'threadWaitWrite' will be unblocked by having--- IO exceptions thrown.-closeFdWith :: (Fd -> IO ()) -- ^ Low-level action that performs the real close.-            -> Fd            -- ^ File descriptor to close.-            -> IO ()-closeFdWith close fd-#ifndef mingw32_HOST_OS-  | threaded  = Event.closeFdWith close fd-#endif-  | otherwise = close fd---- | Suspends the current thread for a given number of microseconds--- (GHC only).------ There is no guarantee that the thread will be rescheduled promptly--- when the delay has expired, but the thread will never continue to--- run /earlier/ than specified.----threadDelay :: Int -> IO ()-threadDelay time-#ifdef mingw32_HOST_OS-  | threaded  = Windows.threadDelay time-#else-  | threaded  = Event.threadDelay time-#endif-  | otherwise = IO $ \s ->-        case time of { I# time# ->-        case delay# time# s of { s' -> (# s', () #)-        }}---- | Set the value of returned TVar to True after a given number of--- microseconds. The caveats associated with threadDelay also apply.----registerDelay :: Int -> IO (TVar Bool)-registerDelay usecs-#ifdef mingw32_HOST_OS-  | threaded = Windows.registerDelay usecs-#else-  | threaded = Event.registerDelay usecs-#endif-  | otherwise = error "registerDelay: requires -threaded"--foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
− GHC/Conc/Signal.hs
@@ -1,99 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}--module GHC.Conc.Signal-        ( Signal-        , HandlerFun-        , setHandler-        , runHandlers-        , runHandlersPtr-        ) where--import Control.Concurrent.MVar (MVar, newMVar, withMVar)-import Data.Dynamic (Dynamic)-import Foreign.C.Types (CInt)-import Foreign.ForeignPtr (ForeignPtr, newForeignPtr)-import Foreign.StablePtr (castPtrToStablePtr, castStablePtrToPtr,-                          deRefStablePtr, freeStablePtr, newStablePtr)-import Foreign.Ptr (Ptr, castPtr)-import Foreign.Marshal.Alloc (finalizerFree)-import GHC.Arr (inRange)-import GHC.Base-import GHC.Conc.Sync (forkIO)-import GHC.IO (mask_, unsafePerformIO)-import GHC.IOArray (IOArray, boundsIOArray, newIOArray,-                    unsafeReadIOArray, unsafeWriteIOArray)-import GHC.Real (fromIntegral)-import GHC.Word (Word8)----------------------------------------------------------------------------- Signal handling--type Signal = CInt--maxSig :: Int-maxSig = 64--type HandlerFun = ForeignPtr Word8 -> IO ()---- Lock used to protect concurrent access to signal_handlers.  Symptom--- of this race condition is GHC bug #1922, although that bug was on--- Windows a similar bug also exists on Unix.-signal_handlers :: MVar (IOArray Int (Maybe (HandlerFun,Dynamic)))-signal_handlers = unsafePerformIO $ do-  arr <- newIOArray (0, maxSig) Nothing-  m <- newMVar arr-  sharedCAF m getOrSetGHCConcSignalSignalHandlerStore-{-# NOINLINE signal_handlers #-}--foreign import ccall unsafe "getOrSetGHCConcSignalSignalHandlerStore"-  getOrSetGHCConcSignalSignalHandlerStore :: Ptr a -> IO (Ptr a)--setHandler :: Signal -> Maybe (HandlerFun, Dynamic)-           -> IO (Maybe (HandlerFun, Dynamic))-setHandler sig handler = do-  let int = fromIntegral sig-  withMVar signal_handlers $ \arr ->-    if not (inRange (boundsIOArray arr) int)-      then error "GHC.Conc.setHandler: signal out of range"-      else do old <- unsafeReadIOArray arr int-              unsafeWriteIOArray arr int handler-              return old--runHandlers :: ForeignPtr Word8 -> Signal -> IO ()-runHandlers p_info sig = do-  let int = fromIntegral sig-  withMVar signal_handlers $ \arr ->-    if not (inRange (boundsIOArray arr) int)-      then return ()-      else do handler <- unsafeReadIOArray arr int-              case handler of-                Nothing -> return ()-                Just (f,_)  -> do _ <- forkIO (f p_info)-                                  return ()---- It is our responsibility to free the memory buffer, so we create a--- foreignPtr.-runHandlersPtr :: Ptr Word8 -> Signal -> IO ()-runHandlersPtr p s = do-  fp <- newForeignPtr finalizerFree p-  runHandlers fp s---- Machinery needed to ensure that we only have one copy of certain--- CAFs in this module even when the base package is present twice, as--- it is when base is dynamically loaded into GHCi.  The RTS keeps--- track of the single true value of the CAF, so even when the CAFs in--- the dynamically-loaded base package are reverted, nothing bad--- happens.----sharedCAF :: a -> (Ptr a -> IO (Ptr a)) -> IO a-sharedCAF a get_or_set =-  mask_ $ do-    stable_ref <- newStablePtr a-    let ref = castPtr (castStablePtrToPtr stable_ref)-    ref2 <- get_or_set ref-    if ref == ref2-      then return a-      else do freeStablePtr stable_ref-              deRefStablePtr (castPtrToStablePtr (castPtr ref2))-
− GHC/Conc/Sync.hs
@@ -1,897 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , BangPatterns-           , MagicHash-           , UnboxedTuples-           , UnliftedFFITypes-           , DeriveDataTypeable-           , StandaloneDeriving-           , RankNTypes-  #-}-{-# OPTIONS_GHC -fno-warn-missing-signatures #-}-{-# OPTIONS_HADDOCK not-home #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Conc.Sync--- Copyright   :  (c) The University of Glasgow, 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ Basic concurrency stuff.------------------------------------------------------------------------------------- No: #hide, because bits of this module are exposed by the stm package.--- However, we don't want this module to be the home location for the--- bits it exports, we'd rather have Control.Concurrent and the other--- higher level modules be the home.  Hence:---- #not-home-module GHC.Conc.Sync-        ( ThreadId(..)--        -- * Forking and suchlike-        , forkIO-        , forkIOWithUnmask-        , forkOn-        , forkOnWithUnmask-        , numCapabilities-        , getNumCapabilities-        , setNumCapabilities-        , getNumProcessors-        , numSparks-        , childHandler-        , myThreadId-        , killThread-        , throwTo-        , par-        , pseq-        , runSparks-        , yield-        , labelThread-        , mkWeakThreadId--        , ThreadStatus(..), BlockReason(..)-        , threadStatus-        , threadCapability--        -- * Allocation counter and quota-        , setAllocationCounter-        , getAllocationCounter-        , enableAllocationLimit-        , disableAllocationLimit--        -- * TVars-        , STM(..)-        , atomically-        , retry-        , orElse-        , throwSTM-        , catchSTM-        , alwaysSucceeds-        , always-        , TVar(..)-        , newTVar-        , newTVarIO-        , readTVar-        , readTVarIO-        , writeTVar-        , unsafeIOToSTM--        -- * Miscellaneous-        , withMVar-        , modifyMVar_--        , setUncaughtExceptionHandler-        , getUncaughtExceptionHandler--        , reportError, reportStackOverflow--        , sharedCAF-        ) where--import Foreign-import Foreign.C--#ifndef mingw32_HOST_OS-import Data.Dynamic-#else-import Data.Typeable-#endif-import Data.Maybe--import GHC.Base-import {-# SOURCE #-} GHC.IO.Handle ( hFlush )-import {-# SOURCE #-} GHC.IO.Handle.FD ( stdout )-import GHC.IO-import GHC.IO.Encoding.UTF8-import GHC.IO.Exception-import GHC.Exception-import qualified GHC.Foreign-import GHC.IORef-import GHC.MVar-import GHC.Ptr-import GHC.Real         ( fromIntegral )-import GHC.Show         ( Show(..), showString )-import GHC.Weak--infixr 0 `par`, `pseq`---------------------------------------------------------------------------------- 'ThreadId', 'par', and 'fork'--------------------------------------------------------------------------------data ThreadId = ThreadId ThreadId# deriving( Typeable )--- ToDo: data ThreadId = ThreadId (Weak ThreadId#)--- But since ThreadId# is unlifted, the Weak type must use open--- type variables.-{- ^-A 'ThreadId' is an abstract type representing a handle to a thread.-'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where-the 'Ord' instance implements an arbitrary total ordering over-'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued-'ThreadId' to string form; showing a 'ThreadId' value is occasionally-useful when debugging or diagnosing the behaviour of a concurrent-program.--/Note/: in GHC, if you have a 'ThreadId', you essentially have-a pointer to the thread itself.  This means the thread itself can\'t be-garbage collected until you drop the 'ThreadId'.-This misfeature will hopefully be corrected at a later date.---}--instance Show ThreadId where-   showsPrec d t =-        showString "ThreadId " .-        showsPrec d (getThreadId (id2TSO t))--foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt--id2TSO :: ThreadId -> ThreadId#-id2TSO (ThreadId t) = t--foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt--- Returns -1, 0, 1--cmpThread :: ThreadId -> ThreadId -> Ordering-cmpThread t1 t2 =-   case cmp_thread (id2TSO t1) (id2TSO t2) of-      -1 -> LT-      0  -> EQ-      _  -> GT -- must be 1--instance Eq ThreadId where-   t1 == t2 =-      case t1 `cmpThread` t2 of-         EQ -> True-         _  -> False--instance Ord ThreadId where-   compare = cmpThread---- | Every thread has an allocation counter that tracks how much--- memory has been allocated by the thread.  The counter is--- initialized to zero, and 'setAllocationCounter' sets the current--- value.  The allocation counter counts *down*, so in the absence of--- a call to 'setAllocationCounter' its value is the negation of the--- number of bytes of memory allocated by the thread.------ There are two things that you can do with this counter:------ * Use it as a simple profiling mechanism, with---   'getAllocationCounter'.------ * Use it as a resource limit.  See 'enableAllocationLimit'.------ Allocation accounting is accurate only to about 4Kbytes.------ @since 4.8.0.0-setAllocationCounter :: Int64 -> IO ()-setAllocationCounter i = do-  ThreadId t <- myThreadId-  rts_setThreadAllocationCounter t i---- | Return the current value of the allocation counter for the--- current thread.------ @since 4.8.0.0-getAllocationCounter :: IO Int64-getAllocationCounter = do-  ThreadId t <- myThreadId-  rts_getThreadAllocationCounter t---- | Enables the allocation counter to be treated as a limit for the--- current thread.  When the allocation limit is enabled, if the--- allocation counter counts down below zero, the thread will be sent--- the 'AllocationLimitExceeded' asynchronous exception.  When this--- happens, the counter is reinitialised (by default--- to 100K, but tunable with the @+RTS -xq@ option) so that it can handle--- the exception and perform any necessary clean up.  If it exhausts--- this additional allowance, another 'AllocationLimitExceeded' exception--- is sent, and so forth.------ Note that memory allocation is unrelated to /live memory/, also--- known as /heap residency/.  A thread can allocate a large amount of--- memory and retain anything between none and all of it.  It is--- better to think of the allocation limit as a limit on--- /CPU time/, rather than a limit on memory.------ Compared to using timeouts, allocation limits don't count time--- spent blocked or in foreign calls.------ @since 4.8.0.0-enableAllocationLimit :: IO ()-enableAllocationLimit = do-  ThreadId t <- myThreadId-  rts_enableThreadAllocationLimit t---- | Disable allocation limit processing for the current thread.------ @since 4.8.0.0-disableAllocationLimit :: IO ()-disableAllocationLimit = do-  ThreadId t <- myThreadId-  rts_disableThreadAllocationLimit t---- We cannot do these operations safely on another thread, because on--- a 32-bit machine we cannot do atomic operations on a 64-bit value.--- Therefore, we only expose APIs that allow getting and setting the--- limit of the current thread.-foreign import ccall unsafe "rts_setThreadAllocationCounter"-  rts_setThreadAllocationCounter :: ThreadId# -> Int64 -> IO ()--foreign import ccall unsafe "rts_getThreadAllocationCounter"-  rts_getThreadAllocationCounter :: ThreadId# -> IO Int64--foreign import ccall unsafe "rts_enableThreadAllocationLimit"-  rts_enableThreadAllocationLimit :: ThreadId# -> IO ()--foreign import ccall unsafe "rts_disableThreadAllocationLimit"-  rts_disableThreadAllocationLimit :: ThreadId# -> IO ()--{- |-Creates a new thread to run the 'IO' computation passed as the-first argument, and returns the 'ThreadId' of the newly created-thread.--The new thread will be a lightweight, /unbound/ thread.  Foreign calls-made by this thread are not guaranteed to be made by any particular OS-thread; if you need foreign calls to be made by a particular OS-thread, then use 'Control.Concurrent.forkOS' instead.--The new thread inherits the /masked/ state of the parent (see-'Control.Exception.mask').--The newly created thread has an exception handler that discards the-exceptions 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', and-'ThreadKilled', and passes all other exceptions to the uncaught-exception handler.--}-forkIO :: IO () -> IO ThreadId-forkIO action = IO $ \ s ->-   case (fork# action_plus s) of (# s1, tid #) -> (# s1, ThreadId tid #)- where-  action_plus = catchException action childHandler---- | Like 'forkIO', but the child thread is passed a function that can--- be used to unmask asynchronous exceptions.  This function is--- typically used in the following way------ >  ... mask_ $ forkIOWithUnmask $ \unmask ->--- >                 catch (unmask ...) handler------ so that the exception handler in the child thread is established--- with asynchronous exceptions masked, meanwhile the main body of--- the child thread is executed in the unmasked state.------ Note that the unmask function passed to the child thread should--- only be used in that thread; the behaviour is undefined if it is--- invoked in a different thread.------ @since 4.4.0.0-forkIOWithUnmask :: ((forall a . IO a -> IO a) -> IO ()) -> IO ThreadId-forkIOWithUnmask io = forkIO (io unsafeUnmask)--{- |-Like 'forkIO', but lets you specify on which capability the thread-should run.  Unlike a `forkIO` thread, a thread created by `forkOn`-will stay on the same capability for its entire lifetime (`forkIO`-threads can migrate between capabilities according to the scheduling-policy).  `forkOn` is useful for overriding the scheduling policy when-you know in advance how best to distribute the threads.--The `Int` argument specifies a /capability number/ (see-'getNumCapabilities').  Typically capabilities correspond to physical-processors, but the exact behaviour is implementation-dependent.  The-value passed to 'forkOn' is interpreted modulo the total number of-capabilities as returned by 'getNumCapabilities'.--GHC note: the number of capabilities is specified by the @+RTS -N@-option when the program is started.  Capabilities can be fixed to-actual processor cores with @+RTS -qa@ if the underlying operating-system supports that, although in practice this is usually unnecessary-(and may actually degrade performance in some cases - experimentation-is recommended).--@since 4.4.0.0--}-forkOn :: Int -> IO () -> IO ThreadId-forkOn (I# cpu) action = IO $ \ s ->-   case (forkOn# cpu action_plus s) of (# s1, tid #) -> (# s1, ThreadId tid #)- where-  action_plus = catchException action childHandler---- | Like 'forkIOWithUnmask', but the child thread is pinned to the--- given CPU, as with 'forkOn'.------ @since 4.4.0.0-forkOnWithUnmask :: Int -> ((forall a . IO a -> IO a) -> IO ()) -> IO ThreadId-forkOnWithUnmask cpu io = forkOn cpu (io unsafeUnmask)---- | the value passed to the @+RTS -N@ flag.  This is the number of--- Haskell threads that can run truly simultaneously at any given--- time, and is typically set to the number of physical processor cores on--- the machine.------ Strictly speaking it is better to use 'getNumCapabilities', because--- the number of capabilities might vary at runtime.----numCapabilities :: Int-numCapabilities = unsafePerformIO $ getNumCapabilities--{- |-Returns the number of Haskell threads that can run truly-simultaneously (on separate physical processors) at any given time.  To change-this value, use 'setNumCapabilities'.--@since 4.4.0.0--}-getNumCapabilities :: IO Int-getNumCapabilities = do-   n <- peek enabled_capabilities-   return (fromIntegral n)--{- |-Set the number of Haskell threads that can run truly simultaneously-(on separate physical processors) at any given time.  The number-passed to `forkOn` is interpreted modulo this value.  The initial-value is given by the @+RTS -N@ runtime flag.--This is also the number of threads that will participate in parallel-garbage collection.  It is strongly recommended that the number of-capabilities is not set larger than the number of physical processor-cores, and it may often be beneficial to leave one or more cores free-to avoid contention with other processes in the machine.--@since 4.5.0.0--}-setNumCapabilities :: Int -> IO ()-setNumCapabilities i = c_setNumCapabilities (fromIntegral i)--foreign import ccall safe "setNumCapabilities"-  c_setNumCapabilities :: CUInt -> IO ()---- | Returns the number of CPUs that the machine has------ @since 4.5.0.0-getNumProcessors :: IO Int-getNumProcessors = fmap fromIntegral c_getNumberOfProcessors--foreign import ccall unsafe "getNumberOfProcessors"-  c_getNumberOfProcessors :: IO CUInt---- | Returns the number of sparks currently in the local spark pool-numSparks :: IO Int-numSparks = IO $ \s -> case numSparks# s of (# s', n #) -> (# s', I# n #)--foreign import ccall "&enabled_capabilities" enabled_capabilities :: Ptr CInt--childHandler :: SomeException -> IO ()-childHandler err = catchException (real_handler err) childHandler--real_handler :: SomeException -> IO ()-real_handler se-  | Just BlockedIndefinitelyOnMVar <- fromException se  =  return ()-  | Just BlockedIndefinitelyOnSTM  <- fromException se  =  return ()-  | Just ThreadKilled              <- fromException se  =  return ()-  | Just StackOverflow             <- fromException se  =  reportStackOverflow-  | otherwise                                           =  reportError se--{- | 'killThread' raises the 'ThreadKilled' exception in the given-thread (GHC only).--> killThread tid = throwTo tid ThreadKilled---}-killThread :: ThreadId -> IO ()-killThread tid = throwTo tid ThreadKilled--{- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).--Exception delivery synchronizes between the source and target thread:-'throwTo' does not return until the exception has been raised in the-target thread. The calling thread can thus be certain that the target-thread has received the exception.  Exception delivery is also atomic-with respect to other exceptions. Atomicity is a useful property to have-when dealing with race conditions: e.g. if there are two threads that-can kill each other, it is guaranteed that only one of the threads-will get to kill the other.--Whatever work the target thread was doing when the exception was-raised is not lost: the computation is suspended until required by-another thread.--If the target thread is currently making a foreign call, then the-exception will not be raised (and hence 'throwTo' will not return)-until the call has completed.  This is the case regardless of whether-the call is inside a 'mask' or not.  However, in GHC a foreign call-can be annotated as @interruptible@, in which case a 'throwTo' will-cause the RTS to attempt to cause the call to return; see the GHC-documentation for more details.--Important note: the behaviour of 'throwTo' differs from that described in-the paper \"Asynchronous exceptions in Haskell\"-(<http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm>).-In the paper, 'throwTo' is non-blocking; but the library implementation adopts-a more synchronous design in which 'throwTo' does not return until the exception-is received by the target thread.  The trade-off is discussed in Section 9 of the paper.-Like any blocking operation, 'throwTo' is therefore interruptible (see Section 5.3 of-the paper).  Unlike other interruptible operations, however, 'throwTo'-is /always/ interruptible, even if it does not actually block.--There is no guarantee that the exception will be delivered promptly,-although the runtime will endeavour to ensure that arbitrary-delays don't occur.  In GHC, an exception can only be raised when a-thread reaches a /safe point/, where a safe point is where memory-allocation occurs.  Some loops do not perform any memory allocation-inside the loop and therefore cannot be interrupted by a 'throwTo'.--If the target of 'throwTo' is the calling thread, then the behaviour-is the same as 'Control.Exception.throwIO', except that the exception-is thrown as an asynchronous exception.  This means that if there is-an enclosing pure computation, which would be the case if the current-IO operation is inside 'unsafePerformIO' or 'unsafeInterleaveIO', that-computation is not permanently replaced by the exception, but is-suspended as if it had received an asynchronous exception.--Note that if 'throwTo' is called with the current thread as the-target, the exception will be thrown even if the thread is currently-inside 'mask' or 'uninterruptibleMask'.-  -}-throwTo :: Exception e => ThreadId -> e -> IO ()-throwTo (ThreadId tid) ex = IO $ \ s ->-   case (killThread# tid (toException ex) s) of s1 -> (# s1, () #)---- | Returns the 'ThreadId' of the calling thread (GHC only).-myThreadId :: IO ThreadId-myThreadId = IO $ \s ->-   case (myThreadId# s) of (# s1, tid #) -> (# s1, ThreadId tid #)----- |The 'yield' action allows (forces, in a co-operative multitasking--- implementation) a context-switch to any other currently runnable--- threads (if any), and is occasionally useful when implementing--- concurrency abstractions.-yield :: IO ()-yield = IO $ \s ->-   case (yield# s) of s1 -> (# s1, () #)--{- | 'labelThread' stores a string as identifier for this thread if-you built a RTS with debugging support. This identifier will be used in-the debugging output to make distinction of different threads easier-(otherwise you only have the thread state object\'s address in the heap).--Other applications like the graphical Concurrent Haskell Debugger-(<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload-'labelThread' for their purposes as well.--}--labelThread :: ThreadId -> String -> IO ()-labelThread (ThreadId t) str =-    GHC.Foreign.withCString utf8 str $ \(Ptr p) ->-    IO $ \ s ->-     case labelThread# t p s of s1 -> (# s1, () #)----      Nota Bene: 'pseq' used to be 'seq'---                 but 'seq' is now defined in PrelGHC------ "pseq" is defined a bit weirdly (see below)------ The reason for the strange "lazy" call is that--- it fools the compiler into thinking that pseq  and par are non-strict in--- their second argument (even if it inlines pseq at the call site).--- If it thinks pseq is strict in "y", then it often evaluates--- "y" before "x", which is totally wrong.--{-# INLINE pseq  #-}-pseq :: a -> b -> b-pseq  x y = x `seq` lazy y--{-# INLINE par  #-}-par :: a -> b -> b-par  x y = case (par# x) of { _ -> lazy y }---- | Internal function used by the RTS to run sparks.-runSparks :: IO ()-runSparks = IO loop-  where loop s = case getSpark# s of-                   (# s', n, p #) ->-                      if isTrue# (n ==# 0#)-                      then (# s', () #)-                      else p `seq` loop s'--data BlockReason-  = BlockedOnMVar-        -- ^blocked on 'MVar'-  {- possibly (see 'threadstatus' below):-  | BlockedOnMVarRead-        -- ^blocked on reading an empty 'MVar'-  -}-  | BlockedOnBlackHole-        -- ^blocked on a computation in progress by another thread-  | BlockedOnException-        -- ^blocked in 'throwTo'-  | BlockedOnSTM-        -- ^blocked in 'retry' in an STM transaction-  | BlockedOnForeignCall-        -- ^currently in a foreign call-  | BlockedOnOther-        -- ^blocked on some other resource.  Without @-threaded@,-        -- I\/O and 'threadDelay' show up as 'BlockedOnOther', with @-threaded@-        -- they show up as 'BlockedOnMVar'.-  deriving (Eq,Ord,Show)---- | The current status of a thread-data ThreadStatus-  = ThreadRunning-        -- ^the thread is currently runnable or running-  | ThreadFinished-        -- ^the thread has finished-  | ThreadBlocked  BlockReason-        -- ^the thread is blocked on some resource-  | ThreadDied-        -- ^the thread received an uncaught exception-  deriving (Eq,Ord,Show)--threadStatus :: ThreadId -> IO ThreadStatus-threadStatus (ThreadId t) = IO $ \s ->-   case threadStatus# t s of-    (# s', stat, _cap, _locked #) -> (# s', mk_stat (I# stat) #)-   where-        -- NB. keep these in sync with includes/rts/Constants.h-     mk_stat 0  = ThreadRunning-     mk_stat 1  = ThreadBlocked BlockedOnMVar-     mk_stat 2  = ThreadBlocked BlockedOnBlackHole-     mk_stat 6  = ThreadBlocked BlockedOnSTM-     mk_stat 10 = ThreadBlocked BlockedOnForeignCall-     mk_stat 11 = ThreadBlocked BlockedOnForeignCall-     mk_stat 12 = ThreadBlocked BlockedOnException-     mk_stat 14 = ThreadBlocked BlockedOnMVar -- possibly: BlockedOnMVarRead-     -- NB. these are hardcoded in rts/PrimOps.cmm-     mk_stat 16 = ThreadFinished-     mk_stat 17 = ThreadDied-     mk_stat _  = ThreadBlocked BlockedOnOther---- | returns the number of the capability on which the thread is currently--- running, and a boolean indicating whether the thread is locked to--- that capability or not.  A thread is locked to a capability if it--- was created with @forkOn@.------ @since 4.4.0.0-threadCapability :: ThreadId -> IO (Int, Bool)-threadCapability (ThreadId t) = IO $ \s ->-   case threadStatus# t s of-     (# s', _, cap#, locked# #) -> (# s', (I# cap#, isTrue# (locked# /=# 0#)) #)---- | make a weak pointer to a 'ThreadId'.  It can be important to do--- this if you want to hold a reference to a 'ThreadId' while still--- allowing the thread to receive the @BlockedIndefinitely@ family of--- exceptions (e.g. 'BlockedIndefinitelyOnMVar').  Holding a normal--- 'ThreadId' reference will prevent the delivery of--- @BlockedIndefinitely@ exceptions because the reference could be--- used as the target of 'throwTo' at any time, which would unblock--- the thread.------ Holding a @Weak ThreadId@, on the other hand, will not prevent the--- thread from receiving @BlockedIndefinitely@ exceptions.  It is--- still possible to throw an exception to a @Weak ThreadId@, but the--- caller must use @deRefWeak@ first to determine whether the thread--- still exists.------ @since 4.6.0.0-mkWeakThreadId :: ThreadId -> IO (Weak ThreadId)-mkWeakThreadId t@(ThreadId t#) = IO $ \s ->-   case mkWeakNoFinalizer# t# t s of-      (# s1, w #) -> (# s1, Weak w #)----------------------------------------------------------------------------------- Transactional heap operations---------------------------------------------------------------------------------- TVars are shared memory locations which support atomic memory--- transactions.---- |A monad supporting atomic memory transactions.-newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))-                deriving Typeable--unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))-unSTM (STM a) = a--instance  Functor STM where-   fmap f x = x >>= (return . f)--instance Applicative STM where-  pure = return-  (<*>) = ap--instance  Monad STM  where-    {-# INLINE return #-}-    {-# INLINE (>>)   #-}-    {-# INLINE (>>=)  #-}-    m >> k      = thenSTM m k-    return x    = returnSTM x-    m >>= k     = bindSTM m k--bindSTM :: STM a -> (a -> STM b) -> STM b-bindSTM (STM m) k = STM ( \s ->-  case m s of-    (# new_s, a #) -> unSTM (k a) new_s-  )--thenSTM :: STM a -> STM b -> STM b-thenSTM (STM m) k = STM ( \s ->-  case m s of-    (# new_s, _ #) -> unSTM k new_s-  )--returnSTM :: a -> STM a-returnSTM x = STM (\s -> (# s, x #))--instance Alternative STM where-  empty = retry-  (<|>) = orElse--instance MonadPlus STM where-  mzero = empty-  mplus = (<|>)---- | Unsafely performs IO in the STM monad.  Beware: this is a highly--- dangerous thing to do.------   * The STM implementation will often run transactions multiple---     times, so you need to be prepared for this if your IO has any---     side effects.------   * The STM implementation will abort transactions that are known to---     be invalid and need to be restarted.  This may happen in the middle---     of `unsafeIOToSTM`, so make sure you don't acquire any resources---     that need releasing (exception handlers are ignored when aborting---     the transaction).  That includes doing any IO using Handles, for---     example.  Getting this wrong will probably lead to random deadlocks.------   * The transaction may have seen an inconsistent view of memory when---     the IO runs.  Invariants that you expect to be true throughout---     your program may not be true inside a transaction, due to the---     way transactions are implemented.  Normally this wouldn't be visible---     to the programmer, but using `unsafeIOToSTM` can expose it.----unsafeIOToSTM :: IO a -> STM a-unsafeIOToSTM (IO m) = STM m---- |Perform a series of STM actions atomically.------ You cannot use 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'.--- Any attempt to do so will result in a runtime error.  (Reason: allowing--- this would effectively allow a transaction inside a transaction, depending--- on exactly when the thunk is evaluated.)------ However, see 'newTVarIO', which can be called inside 'unsafePerformIO',--- and which allows top-level TVars to be allocated.--atomically :: STM a -> IO a-atomically (STM m) = IO (\s -> (atomically# m) s )---- |Retry execution of the current memory transaction because it has seen--- values in TVars which mean that it should not continue (e.g. the TVars--- represent a shared buffer that is now empty).  The implementation may--- block the thread until one of the TVars that it has read from has been--- udpated. (GHC only)-retry :: STM a-retry = STM $ \s# -> retry# s#---- |Compose two alternative STM actions (GHC only).  If the first action--- completes without retrying then it forms the result of the orElse.--- Otherwise, if the first action retries, then the second action is--- tried in its place.  If both actions retry then the orElse as a--- whole retries.-orElse :: STM a -> STM a -> STM a-orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s---- | A variant of 'throw' that can only be used within the 'STM' monad.------ Throwing an exception in @STM@ aborts the transaction and propagates the--- exception.------ Although 'throwSTM' has a type that is an instance of the type of 'throw', the--- two functions are subtly different:------ > throw e    `seq` x  ===> throw e--- > throwSTM e `seq` x  ===> x------ The first example will cause the exception @e@ to be raised,--- whereas the second one won\'t.  In fact, 'throwSTM' will only cause--- an exception to be raised when it is used within the 'STM' monad.--- The 'throwSTM' variant should be used in preference to 'throw' to--- raise an exception within the 'STM' monad because it guarantees--- ordering with respect to other 'STM' operations, whereas 'throw'--- does not.-throwSTM :: Exception e => e -> STM a-throwSTM e = STM $ raiseIO# (toException e)---- |Exception handling within STM actions.-catchSTM :: Exception e => STM a -> (e -> STM a) -> STM a-catchSTM (STM m) handler = STM $ catchSTM# m handler'-    where-      handler' e = case fromException e of-                     Just e' -> unSTM (handler e')-                     Nothing -> raiseIO# e---- | Low-level primitive on which always and alwaysSucceeds are built.--- checkInv differs form these in that (i) the invariant is not--- checked when checkInv is called, only at the end of this and--- subsequent transcations, (ii) the invariant failure is indicated--- by raising an exception.-checkInv :: STM a -> STM ()-checkInv (STM m) = STM (\s -> (check# m) s)---- | alwaysSucceeds adds a new invariant that must be true when passed--- to alwaysSucceeds, at the end of the current transaction, and at--- the end of every subsequent transaction.  If it fails at any--- of those points then the transaction violating it is aborted--- and the exception raised by the invariant is propagated.-alwaysSucceeds :: STM a -> STM ()-alwaysSucceeds i = do ( i >> retry ) `orElse` ( return () )-                      checkInv i---- | always is a variant of alwaysSucceeds in which the invariant is--- expressed as an STM Bool action that must return True.  Returning--- False or raising an exception are both treated as invariant failures.-always :: STM Bool -> STM ()-always i = alwaysSucceeds ( do v <- i-                               if (v) then return () else ( error "Transactional invariant violation" ) )---- |Shared memory locations that support atomic memory transactions.-data TVar a = TVar (TVar# RealWorld a)-              deriving Typeable--instance Eq (TVar a) where-        (TVar tvar1#) == (TVar tvar2#) = isTrue# (sameTVar# tvar1# tvar2#)---- |Create a new TVar holding a value supplied-newTVar :: a -> STM (TVar a)-newTVar val = STM $ \s1# ->-    case newTVar# val s1# of-         (# s2#, tvar# #) -> (# s2#, TVar tvar# #)---- |@IO@ version of 'newTVar'.  This is useful for creating top-level--- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using--- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't--- possible.-newTVarIO :: a -> IO (TVar a)-newTVarIO val = IO $ \s1# ->-    case newTVar# val s1# of-         (# s2#, tvar# #) -> (# s2#, TVar tvar# #)---- |Return the current value stored in a TVar.--- This is equivalent to------ >  readTVarIO = atomically . readTVar------ but works much faster, because it doesn't perform a complete--- transaction, it just reads the current value of the 'TVar'.-readTVarIO :: TVar a -> IO a-readTVarIO (TVar tvar#) = IO $ \s# -> readTVarIO# tvar# s#---- |Return the current value stored in a TVar-readTVar :: TVar a -> STM a-readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#---- |Write the supplied value into a TVar-writeTVar :: TVar a -> a -> STM ()-writeTVar (TVar tvar#) val = STM $ \s1# ->-    case writeTVar# tvar# val s1# of-         s2# -> (# s2#, () #)---------------------------------------------------------------------------------- MVar utilities--------------------------------------------------------------------------------withMVar :: MVar a -> (a -> IO b) -> IO b-withMVar m io =-  mask $ \restore -> do-    a <- takeMVar m-    b <- catchAny (restore (io a))-            (\e -> do putMVar m a; throw e)-    putMVar m a-    return b--modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()-modifyMVar_ m io =-  mask $ \restore -> do-    a <- takeMVar m-    a' <- catchAny (restore (io a))-            (\e -> do putMVar m a; throw e)-    putMVar m a'-    return ()---------------------------------------------------------------------------------- Thread waiting---------------------------------------------------------------------------------- Machinery needed to ensureb that we only have one copy of certain--- CAFs in this module even when the base package is present twice, as--- it is when base is dynamically loaded into GHCi.  The RTS keeps--- track of the single true value of the CAF, so even when the CAFs in--- the dynamically-loaded base package are reverted, nothing bad--- happens.----sharedCAF :: a -> (Ptr a -> IO (Ptr a)) -> IO a-sharedCAF a get_or_set =-   mask_ $ do-     stable_ref <- newStablePtr a-     let ref = castPtr (castStablePtrToPtr stable_ref)-     ref2 <- get_or_set ref-     if ref==ref2-        then return a-        else do freeStablePtr stable_ref-                deRefStablePtr (castPtrToStablePtr (castPtr ref2))--reportStackOverflow :: IO ()-reportStackOverflow = do-     ThreadId tid <- myThreadId-     callStackOverflowHook tid--reportError :: SomeException -> IO ()-reportError ex = do-   handler <- getUncaughtExceptionHandler-   handler ex---- SUP: Are the hooks allowed to re-enter Haskell land?  If so, remove--- the unsafe below.-foreign import ccall unsafe "stackOverflow"-        callStackOverflowHook :: ThreadId# -> IO ()--{-# NOINLINE uncaughtExceptionHandler #-}-uncaughtExceptionHandler :: IORef (SomeException -> IO ())-uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)-   where-      defaultHandler :: SomeException -> IO ()-      defaultHandler se@(SomeException ex) = do-         (hFlush stdout) `catchAny` (\ _ -> return ())-         let msg = case cast ex of-               Just Deadlock -> "no threads to run:  infinite loop or deadlock?"-               _ -> case cast ex of-                    Just (ErrorCall s) -> s-                    _                  -> showsPrec 0 se ""-         withCString "%s" $ \cfmt ->-          withCString msg $ \cmsg ->-            errorBelch cfmt cmsg---- don't use errorBelch() directly, because we cannot call varargs functions--- using the FFI.-foreign import ccall unsafe "HsBase.h errorBelch2"-   errorBelch :: CString -> CString -> IO ()--setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()-setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler--getUncaughtExceptionHandler :: IO (SomeException -> IO ())-getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler
− GHC/Conc/Windows.hs
@@ -1,339 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples,-             AutoDeriveTypeable #-}-{-# OPTIONS_GHC -fno-warn-missing-signatures #-}-{-# OPTIONS_HADDOCK not-home #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Conc.Windows--- Copyright   :  (c) The University of Glasgow, 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ Windows I/O manager------------------------------------------------------------------------------------- #not-home-module GHC.Conc.Windows-       ( ensureIOManagerIsRunning--       -- * Waiting-       , threadDelay-       , registerDelay--       -- * Miscellaneous-       , asyncRead-       , asyncWrite-       , asyncDoProc--       , asyncReadBA-       , asyncWriteBA--       , ConsoleEvent(..)-       , win32ConsoleHandler-       , toWin32ConsoleEvent-       ) where--import Data.Bits (shiftR)-import Data.Typeable-import GHC.Base-import GHC.Conc.Sync-import GHC.Enum (Enum)-import GHC.IO (unsafePerformIO)-import GHC.IORef-import GHC.MVar-import GHC.Num (Num(..))-import GHC.Ptr-import GHC.Read (Read)-import GHC.Real (div, fromIntegral)-import GHC.Show (Show)-import GHC.Word (Word32, Word64)-import GHC.Windows--#ifdef mingw32_HOST_OS-# if defined(i386_HOST_ARCH)-#  define WINDOWS_CCONV stdcall-# elif defined(x86_64_HOST_ARCH)-#  define WINDOWS_CCONV ccall-# else-#  error Unknown mingw32 arch-# endif-#endif---- ------------------------------------------------------------------------------- Thread waiting---- Note: threadWaitRead and threadWaitWrite aren't really functional--- on Win32, but left in there because lib code (still) uses them (the manner--- in which they're used doesn't cause problems on a Win32 platform though.)--asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)-asyncRead  (I# fd) (I# isSock) (I# len) (Ptr buf) =-  IO $ \s -> case asyncRead# fd isSock len buf s of-               (# s', len#, err# #) -> (# s', (I# len#, I# err#) #)--asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int)-asyncWrite  (I# fd) (I# isSock) (I# len) (Ptr buf) =-  IO $ \s -> case asyncWrite# fd isSock len buf s of-               (# s', len#, err# #) -> (# s', (I# len#, I# err#) #)--asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int-asyncDoProc (FunPtr proc) (Ptr param) =-    -- the 'length' value is ignored; simplifies implementation of-    -- the async*# primops to have them all return the same result.-  IO $ \s -> case asyncDoProc# proc param s  of-               (# s', _len#, err# #) -> (# s', I# err# #)---- to aid the use of these primops by the IO Handle implementation,--- provide the following convenience funs:---- this better be a pinned byte array!-asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)-asyncReadBA fd isSock len off bufB =-  asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)--asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int)-asyncWriteBA fd isSock len off bufB =-  asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off)---- ------------------------------------------------------------------------------- Threaded RTS implementation of threadDelay---- | Suspends the current thread for a given number of microseconds--- (GHC only).------ There is no guarantee that the thread will be rescheduled promptly--- when the delay has expired, but the thread will never continue to--- run /earlier/ than specified.----threadDelay :: Int -> IO ()-threadDelay time-  | threaded  = waitForDelayEvent time-  | otherwise = IO $ \s ->-        case time of { I# time# ->-        case delay# time# s of { s' -> (# s', () #)-        }}---- | Set the value of returned TVar to True after a given number of--- microseconds. The caveats associated with threadDelay also apply.----registerDelay :: Int -> IO (TVar Bool)-registerDelay usecs-  | threaded = waitForDelayEventSTM usecs-  | otherwise = error "registerDelay: requires -threaded"--foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool--waitForDelayEvent :: Int -> IO ()-waitForDelayEvent usecs = do-  m <- newEmptyMVar-  target <- calculateTarget usecs-  atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ()))-  prodServiceThread-  takeMVar m---- Delays for use in STM-waitForDelayEventSTM :: Int -> IO (TVar Bool)-waitForDelayEventSTM usecs = do-   t <- atomically $ newTVar False-   target <- calculateTarget usecs-   atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ()))-   prodServiceThread-   return t--calculateTarget :: Int -> IO USecs-calculateTarget usecs = do-    now <- getMonotonicUSec-    return $ now + (fromIntegral usecs)--data DelayReq-  = Delay    {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ())-  | DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool)--{-# NOINLINE pendingDelays #-}-pendingDelays :: IORef [DelayReq]-pendingDelays = unsafePerformIO $ do-   m <- newIORef []-   sharedCAF m getOrSetGHCConcWindowsPendingDelaysStore--foreign import ccall unsafe "getOrSetGHCConcWindowsPendingDelaysStore"-    getOrSetGHCConcWindowsPendingDelaysStore :: Ptr a -> IO (Ptr a)--{-# NOINLINE ioManagerThread #-}-ioManagerThread :: MVar (Maybe ThreadId)-ioManagerThread = unsafePerformIO $ do-   m <- newMVar Nothing-   sharedCAF m getOrSetGHCConcWindowsIOManagerThreadStore--foreign import ccall unsafe "getOrSetGHCConcWindowsIOManagerThreadStore"-    getOrSetGHCConcWindowsIOManagerThreadStore :: Ptr a -> IO (Ptr a)--ensureIOManagerIsRunning :: IO ()-ensureIOManagerIsRunning-  | threaded  = startIOManagerThread-  | otherwise = return ()--startIOManagerThread :: IO ()-startIOManagerThread = do-  modifyMVar_ ioManagerThread $ \old -> do-    let create = do t <- forkIO ioManager; return (Just t)-    case old of-      Nothing -> create-      Just t  -> do-        s <- threadStatus t-        case s of-          ThreadFinished -> create-          ThreadDied     -> create-          _other         -> return (Just t)--insertDelay :: DelayReq -> [DelayReq] -> [DelayReq]-insertDelay d [] = [d]-insertDelay d1 ds@(d2 : rest)-  | delayTime d1 <= delayTime d2 = d1 : ds-  | otherwise                    = d2 : insertDelay d1 rest--delayTime :: DelayReq -> USecs-delayTime (Delay t _) = t-delayTime (DelaySTM t _) = t--type USecs = Word64-type NSecs = Word64--foreign import ccall unsafe "getMonotonicNSec"-  getMonotonicNSec :: IO NSecs--getMonotonicUSec :: IO USecs-getMonotonicUSec = fmap (`div` 1000) getMonotonicNSec--{-# NOINLINE prodding #-}-prodding :: IORef Bool-prodding = unsafePerformIO $ do-   r <- newIORef False-   sharedCAF r getOrSetGHCConcWindowsProddingStore--foreign import ccall unsafe "getOrSetGHCConcWindowsProddingStore"-    getOrSetGHCConcWindowsProddingStore :: Ptr a -> IO (Ptr a)--prodServiceThread :: IO ()-prodServiceThread = do-  -- NB. use atomicModifyIORef here, otherwise there are race-  -- conditions in which prodding is left at True but the server is-  -- blocked in select().-  was_set <- atomicModifyIORef prodding $ \b -> (True,b)-  when (not was_set) wakeupIOManager---- ------------------------------------------------------------------------------- Windows IO manager thread--ioManager :: IO ()-ioManager = do-  wakeup <- c_getIOManagerEvent-  service_loop wakeup []--service_loop :: HANDLE          -- read end of pipe-             -> [DelayReq]      -- current delay requests-             -> IO ()--service_loop wakeup old_delays = do-  -- pick up new delay requests-  new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a))-  let  delays = foldr insertDelay old_delays new_delays--  now <- getMonotonicUSec-  (delays', timeout) <- getDelay now delays--  r <- c_WaitForSingleObject wakeup timeout-  case r of-    0xffffffff -> do throwGetLastError "service_loop"-    0 -> do-        r2 <- c_readIOManagerEvent-        exit <--              case r2 of-                _ | r2 == io_MANAGER_WAKEUP -> return False-                _ | r2 == io_MANAGER_DIE    -> return True-                0 -> return False -- spurious wakeup-                _ -> do start_console_handler (r2 `shiftR` 1); return False-        when (not exit) $ service_cont wakeup delays'--    _other -> service_cont wakeup delays' -- probably timeout--service_cont :: HANDLE -> [DelayReq] -> IO ()-service_cont wakeup delays = do-  r <- atomicModifyIORef prodding (\_ -> (False,False))-  r `seq` return () -- avoid space leak-  service_loop wakeup delays---- must agree with rts/win32/ThrIOManager.c-io_MANAGER_WAKEUP, io_MANAGER_DIE :: Word32-io_MANAGER_WAKEUP = 0xffffffff-io_MANAGER_DIE    = 0xfffffffe--data ConsoleEvent- = ControlC- | Break- | Close-    -- these are sent to Services only.- | Logoff- | Shutdown- deriving (Eq, Ord, Enum, Show, Read, Typeable)--start_console_handler :: Word32 -> IO ()-start_console_handler r =-  case toWin32ConsoleEvent r of-     Just x  -> withMVar win32ConsoleHandler $ \handler -> do-                    _ <- forkIO (handler x)-                    return ()-     Nothing -> return ()--toWin32ConsoleEvent :: (Eq a, Num a) => a -> Maybe ConsoleEvent-toWin32ConsoleEvent ev =-   case ev of-       0 {- CTRL_C_EVENT-}        -> Just ControlC-       1 {- CTRL_BREAK_EVENT-}    -> Just Break-       2 {- CTRL_CLOSE_EVENT-}    -> Just Close-       5 {- CTRL_LOGOFF_EVENT-}   -> Just Logoff-       6 {- CTRL_SHUTDOWN_EVENT-} -> Just Shutdown-       _ -> Nothing--win32ConsoleHandler :: MVar (ConsoleEvent -> IO ())-win32ConsoleHandler = unsafePerformIO (newMVar (error "win32ConsoleHandler"))--wakeupIOManager :: IO ()-wakeupIOManager = c_sendIOManagerEvent io_MANAGER_WAKEUP---- Walk the queue of pending delays, waking up any that have passed--- and return the smallest delay to wait for.  The queue of pending--- delays is kept ordered.-getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD)-getDelay _   [] = return ([], iNFINITE)-getDelay now all@(d : rest)-  = case d of-     Delay time m | now >= time -> do-        putMVar m ()-        getDelay now rest-     DelaySTM time t | now >= time -> do-        atomically $ writeTVar t True-        getDelay now rest-     _otherwise ->-        -- delay is in millisecs for WaitForSingleObject-        let micro_seconds = delayTime d - now-            milli_seconds = (micro_seconds + 999) `div` 1000-        in return (all, fromIntegral milli_seconds)--foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c)-  c_getIOManagerEvent :: IO HANDLE--foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c)-  c_readIOManagerEvent :: IO Word32--foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c)-  c_sendIOManagerEvent :: Word32 -> IO ()--foreign import WINDOWS_CCONV "WaitForSingleObject"-   c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD-
− GHC/ConsoleHandler.hs
@@ -1,162 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE CPP #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.ConsoleHandler--- Copyright   :  (c) The University of Glasgow--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ NB. the contents of this module are only available on Windows.------ Installing Win32 console handlers.--- --------------------------------------------------------------------------------module GHC.ConsoleHandler-#if !defined(mingw32_HOST_OS) && !defined(__HADDOCK__)-        where--import GHC.Base ()  -- dummy dependency-#else /* whole file */-        ( Handler(..)-        , installHandler-        , ConsoleEvent(..)-        , flushConsole-        ) where--{--#include "rts/Signals.h"--Note: this #include is inside a Haskell comment-      but it brings into scope some #defines-      that are used by CPP below (eg STG_SIG_DFL).-      Having it in a comment means that there's no-      danger that C-like crap will be misunderstood-      by GHC--}--import GHC.Base-import Foreign-import Foreign.C-import GHC.IO.FD-import GHC.IO.Exception-import GHC.IO.Handle.Types-import GHC.IO.Handle.Internals-import GHC.Conc-import Control.Concurrent.MVar-import Data.Typeable--data Handler- = Default- | Ignore- | Catch (ConsoleEvent -> IO ())---- | Allows Windows console events to be caught and handled.  To--- handle a console event, call 'installHandler' passing the--- appropriate 'Handler' value.  When the event is received, if the--- 'Handler' value is @Catch f@, then a new thread will be spawned by--- the system to execute @f e@, where @e@ is the 'ConsoleEvent' that--- was received.------ Note that console events can only be received by an application--- running in a Windows console.  Certain environments that look like consoles--- do not support console events, these include:------  * Cygwin shells with @CYGWIN=tty@ set (if you don't set @CYGWIN=tty@,---    then a Cygwin shell behaves like a Windows console).---  * Cygwin xterm and rxvt windows---  * MSYS rxvt windows------ In order for your application to receive console events, avoid running--- it in one of these environments.----installHandler :: Handler -> IO Handler-installHandler handler-  | threaded =-    modifyMVar win32ConsoleHandler $ \old_h -> do-      (new_h,rc) <--        case handler of-          Default -> do-            r <- rts_installHandler STG_SIG_DFL nullPtr-            return (no_handler, r)-          Ignore  -> do-            r <- rts_installHandler STG_SIG_IGN nullPtr-            return (no_handler, r)-          Catch h -> do-            r <- rts_installHandler STG_SIG_HAN nullPtr-            return (h, r)-      prev_handler <--        case rc of-          STG_SIG_DFL -> return Default-          STG_SIG_IGN -> return Ignore-          STG_SIG_HAN -> return (Catch old_h)-          _           -> error "installHandler: Bad threaded rc value"-      return (new_h, prev_handler)--  | otherwise =-  alloca $ \ p_sp -> do-   rc <--    case handler of-     Default -> rts_installHandler STG_SIG_DFL p_sp-     Ignore  -> rts_installHandler STG_SIG_IGN p_sp-     Catch h -> do-        v <- newStablePtr (toHandler h)-        poke p_sp v-        rts_installHandler STG_SIG_HAN p_sp-   case rc of-     STG_SIG_DFL -> return Default-     STG_SIG_IGN -> return Ignore-     STG_SIG_HAN -> do-        osptr <- peek p_sp-        oldh  <- deRefStablePtr osptr-         -- stable pointer is no longer in use, free it.-        freeStablePtr osptr-        return (Catch (\ ev -> oldh (fromConsoleEvent ev)))-     _           -> error "installHandler: Bad non-threaded rc value"-  where-   fromConsoleEvent ev =-     case ev of-       ControlC -> 0 {- CTRL_C_EVENT-}-       Break    -> 1 {- CTRL_BREAK_EVENT-}-       Close    -> 2 {- CTRL_CLOSE_EVENT-}-       Logoff   -> 5 {- CTRL_LOGOFF_EVENT-}-       Shutdown -> 6 {- CTRL_SHUTDOWN_EVENT-}--   toHandler hdlr ev = do-      case toWin32ConsoleEvent ev of-         -- see rts/win32/ConsoleHandler.c for comments as to why-         -- rts_ConsoleHandlerDone is called here.-        Just x  -> hdlr x >> rts_ConsoleHandlerDone ev-        Nothing -> return () -- silently ignore..--   no_handler = error "win32ConsoleHandler"--foreign import ccall "rtsSupportsBoundThreads" threaded :: Bool--foreign import ccall unsafe "RtsExternal.h rts_InstallConsoleEvent" -  rts_installHandler :: CInt -> Ptr (StablePtr (CInt -> IO ())) -> IO CInt-foreign import ccall unsafe "RtsExternal.h rts_ConsoleHandlerDone"-  rts_ConsoleHandlerDone :: CInt -> IO ()---flushConsole :: Handle -> IO ()-flushConsole h =-  wantReadableHandle_ "flushConsole" h $ \ Handle__{haDevice=dev} ->-    case cast dev of-      Nothing -> ioException $-                    IOError (Just h) IllegalOperation "flushConsole"-                        "handle is not a file descriptor" Nothing Nothing-      Just fd -> do-        throwErrnoIfMinus1Retry_ "flushConsole" $-           flush_console_fd (fdFD fd)--foreign import ccall unsafe "consUtils.h flush_input_console__"-        flush_console_fd :: CInt -> IO CInt--#endif /* mingw32_HOST_OS */
− GHC/Constants.hs
@@ -1,10 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}--module GHC.Constants where---- TODO: This used to include HaskellConstants.hs, but that has now gone.--- We probably want to include the constants in platformConstants somehow--- instead.--import GHC.Base () -- dummy dependency
− GHC/Desugar.hs
@@ -1,41 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude-           , RankNTypes-           , ExistentialQuantification-  #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Desugar--- Copyright   :  (c) The University of Glasgow, 2007--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ Support code for desugaring in GHC--- --------------------------------------------------------------------------------module GHC.Desugar ((>>>), AnnotationWrapper(..), toAnnotationWrapper) where--import Control.Arrow    (Arrow(..))-import Control.Category ((.))-import Data.Data        (Data)---- A version of Control.Category.>>> overloaded on Arrow-(>>>) :: forall arr. Arrow arr => forall a b c. arr a b -> arr b c -> arr a c--- NB: the type of this function is the "shape" that GHC expects---     in tcInstClassOp.  So don't put all the foralls at the front!  ---     Yes, this is a bit grotesque, but heck it works and the whole---     arrows stuff needs reworking anyway!-f >>> g = g . f---- A wrapper data type that lets the typechecker get at the appropriate dictionaries for an annotation-data AnnotationWrapper = forall a. (Data a) => AnnotationWrapper a--toAnnotationWrapper :: (Data a) => a -> AnnotationWrapper-toAnnotationWrapper what = AnnotationWrapper what-
− GHC/Enum.hs
@@ -1,731 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Enum--- Copyright   :  (c) The University of Glasgow, 1992-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ The 'Enum' and 'Bounded' classes.-----------------------------------------------------------------------------------#include "MachDeps.h"--module GHC.Enum(-        Bounded(..), Enum(..),-        boundedEnumFrom, boundedEnumFromThen,-        toEnumError, fromEnumError, succError, predError,--        -- Instances for Bounded and Enum: (), Char, Int--   ) where--import GHC.Base hiding ( many )-import GHC.Char-import GHC.Integer-import GHC.Num-import GHC.Show-default ()              -- Double isn't available yet---- | The 'Bounded' class is used to name the upper and lower limits of a--- type.  'Ord' is not a superclass of 'Bounded' since types that are not--- totally ordered may also have upper and lower bounds.------ The 'Bounded' class may be derived for any enumeration type;--- 'minBound' is the first constructor listed in the @data@ declaration--- and 'maxBound' is the last.--- 'Bounded' may also be derived for single-constructor datatypes whose--- constituent types are in 'Bounded'.--class  Bounded a  where-    minBound, maxBound :: a---- | Class 'Enum' defines operations on sequentially ordered types.------ The @enumFrom@... methods are used in Haskell's translation of--- arithmetic sequences.------ Instances of 'Enum' may be derived for any enumeration type (types--- whose constructors have no fields).  The nullary constructors are--- assumed to be numbered left-to-right by 'fromEnum' from @0@ through @n-1@.--- See Chapter 10 of the /Haskell Report/ for more details.------ For any type that is an instance of class 'Bounded' as well as 'Enum',--- the following should hold:------ * The calls @'succ' 'maxBound'@ and @'pred' 'minBound'@ should result in---   a runtime error.------ * 'fromEnum' and 'toEnum' should give a runtime error if the---   result value is not representable in the result type.---   For example, @'toEnum' 7 :: 'Bool'@ is an error.------ * 'enumFrom' and 'enumFromThen' should be defined with an implicit bound,---   thus:------ >    enumFrom     x   = enumFromTo     x maxBound--- >    enumFromThen x y = enumFromThenTo x y bound--- >      where--- >        bound | fromEnum y >= fromEnum x = maxBound--- >              | otherwise                = minBound----class  Enum a   where-    -- | the successor of a value.  For numeric types, 'succ' adds 1.-    succ                :: a -> a-    -- | the predecessor of a value.  For numeric types, 'pred' subtracts 1.-    pred                :: a -> a-    -- | Convert from an 'Int'.-    toEnum              :: Int -> a-    -- | Convert to an 'Int'.-    -- It is implementation-dependent what 'fromEnum' returns when-    -- applied to a value that is too large to fit in an 'Int'.-    fromEnum            :: a -> Int--    -- | Used in Haskell's translation of @[n..]@.-    enumFrom            :: a -> [a]-    -- | Used in Haskell's translation of @[n,n'..]@.-    enumFromThen        :: a -> a -> [a]-    -- | Used in Haskell's translation of @[n..m]@.-    enumFromTo          :: a -> a -> [a]-    -- | Used in Haskell's translation of @[n,n'..m]@.-    enumFromThenTo      :: a -> a -> a -> [a]--    succ                   = toEnum . (+ 1)  . fromEnum-    pred                   = toEnum . (subtract 1) . fromEnum-    enumFrom x             = map toEnum [fromEnum x ..]-    enumFromThen x y       = map toEnum [fromEnum x, fromEnum y ..]-    enumFromTo x y         = map toEnum [fromEnum x .. fromEnum y]-    enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y]---- Default methods for bounded enumerations-boundedEnumFrom :: (Enum a, Bounded a) => a -> [a]-boundedEnumFrom n = map toEnum [fromEnum n .. fromEnum (maxBound `asTypeOf` n)]--boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a]-boundedEnumFromThen n1 n2-  | i_n2 >= i_n1  = map toEnum [i_n1, i_n2 .. fromEnum (maxBound `asTypeOf` n1)]-  | otherwise     = map toEnum [i_n1, i_n2 .. fromEnum (minBound `asTypeOf` n1)]-  where-    i_n1 = fromEnum n1-    i_n2 = fromEnum n2----------------------------------------------------------------------------- Helper functions---------------------------------------------------------------------------{-# NOINLINE toEnumError #-}-toEnumError :: (Show a) => String -> Int -> (a,a) -> b-toEnumError inst_ty i bnds =-    error $ "Enum.toEnum{" ++ inst_ty ++ "}: tag (" ++-            show i ++-            ") is outside of bounds " ++-            show bnds--{-# NOINLINE fromEnumError #-}-fromEnumError :: (Show a) => String -> a -> b-fromEnumError inst_ty x =-    error $ "Enum.fromEnum{" ++ inst_ty ++ "}: value (" ++-            show x ++-            ") is outside of Int's bounds " ++-            show (minBound::Int, maxBound::Int)--{-# NOINLINE succError #-}-succError :: String -> a-succError inst_ty =-    error $ "Enum.succ{" ++ inst_ty ++ "}: tried to take `succ' of maxBound"--{-# NOINLINE predError #-}-predError :: String -> a-predError inst_ty =-    error $ "Enum.pred{" ++ inst_ty ++ "}: tried to take `pred' of minBound"----------------------------------------------------------------------------- Tuples---------------------------------------------------------------------------instance Bounded () where-    minBound = ()-    maxBound = ()--instance Enum () where-    succ _      = error "Prelude.Enum.().succ: bad argument"-    pred _      = error "Prelude.Enum.().pred: bad argument"--    toEnum x | x == 0    = ()-             | otherwise = error "Prelude.Enum.().toEnum: bad argument"--    fromEnum () = 0-    enumFrom ()         = [()]-    enumFromThen () ()  = let many = ():many in many-    enumFromTo () ()    = [()]-    enumFromThenTo () () () = let many = ():many in many---- Report requires instances up to 15-instance (Bounded a, Bounded b) => Bounded (a,b) where-   minBound = (minBound, minBound)-   maxBound = (maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c) => Bounded (a,b,c) where-   minBound = (minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a,b,c,d) where-   minBound = (minBound, minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e) => Bounded (a,b,c,d,e) where-   minBound = (minBound, minBound, minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f)-        => Bounded (a,b,c,d,e,f) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g)-        => Bounded (a,b,c,d,e,f,g) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,-          Bounded h)-        => Bounded (a,b,c,d,e,f,g,h) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,-          Bounded h, Bounded i)-        => Bounded (a,b,c,d,e,f,g,h,i) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,-               minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,-               maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,-          Bounded h, Bounded i, Bounded j)-        => Bounded (a,b,c,d,e,f,g,h,i,j) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,-               minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,-               maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,-          Bounded h, Bounded i, Bounded j, Bounded k)-        => Bounded (a,b,c,d,e,f,g,h,i,j,k) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,-               minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,-               maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,-          Bounded h, Bounded i, Bounded j, Bounded k, Bounded l)-        => Bounded (a,b,c,d,e,f,g,h,i,j,k,l) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,-               minBound, minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,-               maxBound, maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,-          Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m)-        => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,-               minBound, minBound, minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,-               maxBound, maxBound, maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,-          Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n)-        => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,-               minBound, minBound, minBound, minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,-               maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)--instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,-          Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n, Bounded o)-        => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where-   minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,-               minBound, minBound, minBound, minBound, minBound, minBound, minBound)-   maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,-               maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)----------------------------------------------------------------------------- Bool---------------------------------------------------------------------------instance Bounded Bool where-  minBound = False-  maxBound = True--instance Enum Bool where-  succ False = True-  succ True  = error "Prelude.Enum.Bool.succ: bad argument"--  pred True  = False-  pred False  = error "Prelude.Enum.Bool.pred: bad argument"--  toEnum n | n == 0    = False-           | n == 1    = True-           | otherwise = error "Prelude.Enum.Bool.toEnum: bad argument"--  fromEnum False = 0-  fromEnum True  = 1--  -- Use defaults for the rest-  enumFrom     = boundedEnumFrom-  enumFromThen = boundedEnumFromThen----------------------------------------------------------------------------- Ordering---------------------------------------------------------------------------instance Bounded Ordering where-  minBound = LT-  maxBound = GT--instance Enum Ordering where-  succ LT = EQ-  succ EQ = GT-  succ GT = error "Prelude.Enum.Ordering.succ: bad argument"--  pred GT = EQ-  pred EQ = LT-  pred LT = error "Prelude.Enum.Ordering.pred: bad argument"--  toEnum n | n == 0 = LT-           | n == 1 = EQ-           | n == 2 = GT-  toEnum _ = error "Prelude.Enum.Ordering.toEnum: bad argument"--  fromEnum LT = 0-  fromEnum EQ = 1-  fromEnum GT = 2--  -- Use defaults for the rest-  enumFrom     = boundedEnumFrom-  enumFromThen = boundedEnumFromThen----------------------------------------------------------------------------- Char---------------------------------------------------------------------------instance  Bounded Char  where-    minBound =  '\0'-    maxBound =  '\x10FFFF'--instance  Enum Char  where-    succ (C# c#)-       | isTrue# (ord# c# /=# 0x10FFFF#) = C# (chr# (ord# c# +# 1#))-       | otherwise             = error ("Prelude.Enum.Char.succ: bad argument")-    pred (C# c#)-       | isTrue# (ord# c# /=# 0#) = C# (chr# (ord# c# -# 1#))-       | otherwise                = error ("Prelude.Enum.Char.pred: bad argument")--    toEnum   = chr-    fromEnum = ord--    {-# INLINE enumFrom #-}-    enumFrom (C# x) = eftChar (ord# x) 0x10FFFF#-        -- Blarg: technically I guess enumFrom isn't strict!--    {-# INLINE enumFromTo #-}-    enumFromTo (C# x) (C# y) = eftChar (ord# x) (ord# y)--    {-# INLINE enumFromThen #-}-    enumFromThen (C# x1) (C# x2) = efdChar (ord# x1) (ord# x2)--    {-# INLINE enumFromThenTo #-}-    enumFromThenTo (C# x1) (C# x2) (C# y) = efdtChar (ord# x1) (ord# x2) (ord# y)--{-# RULES-"eftChar"       [~1] forall x y.        eftChar x y       = build (\c n -> eftCharFB c n x y)-"efdChar"       [~1] forall x1 x2.      efdChar x1 x2     = build (\ c n -> efdCharFB c n x1 x2)-"efdtChar"      [~1] forall x1 x2 l.    efdtChar x1 x2 l  = build (\ c n -> efdtCharFB c n x1 x2 l)-"eftCharList"   [1]  eftCharFB  (:) [] = eftChar-"efdCharList"   [1]  efdCharFB  (:) [] = efdChar-"efdtCharList"  [1]  efdtCharFB (:) [] = efdtChar- #-}----- We can do better than for Ints because we don't--- have hassles about arithmetic overflow at maxBound-{-# INLINE [0] eftCharFB #-}-eftCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a-eftCharFB c n x0 y = go x0-                 where-                    go x | isTrue# (x ># y) = n-                         | otherwise        = C# (chr# x) `c` go (x +# 1#)--{-# NOINLINE [1] eftChar #-}-eftChar :: Int# -> Int# -> String-eftChar x y | isTrue# (x ># y ) = []-            | otherwise         = C# (chr# x) : eftChar (x +# 1#) y----- For enumFromThenTo we give up on inlining-{-# NOINLINE [0] efdCharFB #-}-efdCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a-efdCharFB c n x1 x2-  | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta 0x10FFFF#-  | otherwise              = go_dn_char_fb c n x1 delta 0#-  where-    !delta = x2 -# x1--{-# NOINLINE [1] efdChar #-}-efdChar :: Int# -> Int# -> String-efdChar x1 x2-  | isTrue# (delta >=# 0#) = go_up_char_list x1 delta 0x10FFFF#-  | otherwise              = go_dn_char_list x1 delta 0#-  where-    !delta = x2 -# x1--{-# NOINLINE [0] efdtCharFB #-}-efdtCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a-efdtCharFB c n x1 x2 lim-  | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta lim-  | otherwise              = go_dn_char_fb c n x1 delta lim-  where-    !delta = x2 -# x1--{-# NOINLINE [1] efdtChar #-}-efdtChar :: Int# -> Int# -> Int# -> String-efdtChar x1 x2 lim-  | isTrue# (delta >=# 0#) = go_up_char_list x1 delta lim-  | otherwise              = go_dn_char_list x1 delta lim-  where-    !delta = x2 -# x1--go_up_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a-go_up_char_fb c n x0 delta lim-  = go_up x0-  where-    go_up x | isTrue# (x ># lim) = n-            | otherwise          = C# (chr# x) `c` go_up (x +# delta)--go_dn_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a-go_dn_char_fb c n x0 delta lim-  = go_dn x0-  where-    go_dn x | isTrue# (x <# lim) = n-            | otherwise          = C# (chr# x) `c` go_dn (x +# delta)--go_up_char_list :: Int# -> Int# -> Int# -> String-go_up_char_list x0 delta lim-  = go_up x0-  where-    go_up x | isTrue# (x ># lim) = []-            | otherwise          = C# (chr# x) : go_up (x +# delta)--go_dn_char_list :: Int# -> Int# -> Int# -> String-go_dn_char_list x0 delta lim-  = go_dn x0-  where-    go_dn x | isTrue# (x <# lim) = []-            | otherwise          = C# (chr# x) : go_dn (x +# delta)------------------------------------------------------------------------------ Int---------------------------------------------------------------------------{--Be careful about these instances.-        (a) remember that you have to count down as well as up e.g. [13,12..0]-        (b) be careful of Int overflow-        (c) remember that Int is bounded, so [1..] terminates at maxInt--}--instance  Bounded Int where-    minBound =  minInt-    maxBound =  maxInt--instance  Enum Int  where-    succ x-       | x == maxBound  = error "Prelude.Enum.succ{Int}: tried to take `succ' of maxBound"-       | otherwise      = x + 1-    pred x-       | x == minBound  = error "Prelude.Enum.pred{Int}: tried to take `pred' of minBound"-       | otherwise      = x - 1--    toEnum   x = x-    fromEnum x = x--    {-# INLINE enumFrom #-}-    enumFrom (I# x) = eftInt x maxInt#-        where !(I# maxInt#) = maxInt-        -- Blarg: technically I guess enumFrom isn't strict!--    {-# INLINE enumFromTo #-}-    enumFromTo (I# x) (I# y) = eftInt x y--    {-# INLINE enumFromThen #-}-    enumFromThen (I# x1) (I# x2) = efdInt x1 x2--    {-# INLINE enumFromThenTo #-}-    enumFromThenTo (I# x1) (I# x2) (I# y) = efdtInt x1 x2 y----------------------------------------------------------- eftInt and eftIntFB deal with [a..b], which is the--- most common form, so we take a lot of care--- In particular, we have rules for deforestation--{-# RULES-"eftInt"        [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)-"eftIntList"    [1] eftIntFB  (:) [] = eftInt- #-}--{-# NOINLINE [1] eftInt #-}-eftInt :: Int# -> Int# -> [Int]--- [x1..x2]-eftInt x0 y | isTrue# (x0 ># y) = []-            | otherwise         = go x0-               where-                 go x = I# x : if isTrue# (x ==# y)-                               then []-                               else go (x +# 1#)--{-# INLINE [0] eftIntFB #-}-eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r-eftIntFB c n x0 y | isTrue# (x0 ># y) = n-                  | otherwise         = go x0-                 where-                   go x = I# x `c` if isTrue# (x ==# y)-                                   then n-                                   else go (x +# 1#)-                        -- Watch out for y=maxBound; hence ==, not >-        -- Be very careful not to have more than one "c"-        -- so that when eftInfFB is inlined we can inline-        -- whatever is bound to "c"----------------------------------------------------------- efdInt and efdtInt deal with [a,b..] and [a,b..c].--- The code is more complicated because of worries about Int overflow.--{-# RULES-"efdtInt"       [~1] forall x1 x2 y.-                     efdtInt x1 x2 y = build (\ c n -> efdtIntFB c n x1 x2 y)-"efdtIntUpList" [1]  efdtIntFB (:) [] = efdtInt- #-}--efdInt :: Int# -> Int# -> [Int]--- [x1,x2..maxInt]-efdInt x1 x2- | isTrue# (x2 >=# x1) = case maxInt of I# y -> efdtIntUp x1 x2 y- | otherwise           = case minInt of I# y -> efdtIntDn x1 x2 y--{-# NOINLINE [1] efdtInt #-}-efdtInt :: Int# -> Int# -> Int# -> [Int]--- [x1,x2..y]-efdtInt x1 x2 y- | isTrue# (x2 >=# x1) = efdtIntUp x1 x2 y- | otherwise           = efdtIntDn x1 x2 y--{-# INLINE [0] efdtIntFB #-}-efdtIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r-efdtIntFB c n x1 x2 y- | isTrue# (x2 >=# x1) = efdtIntUpFB c n x1 x2 y- | otherwise           = efdtIntDnFB c n x1 x2 y---- Requires x2 >= x1-efdtIntUp :: Int# -> Int# -> Int# -> [Int]-efdtIntUp x1 x2 y    -- Be careful about overflow!- | isTrue# (y <# x2) = if isTrue# (y <# x1) then [] else [I# x1]- | otherwise = -- Common case: x1 <= x2 <= y-               let !delta = x2 -# x1 -- >= 0-                   !y' = y -# delta  -- x1 <= y' <= y; hence y' is representable--                   -- Invariant: x <= y-                   -- Note that: z <= y' => z + delta won't overflow-                   -- so we are guaranteed not to overflow if/when we recurse-                   go_up x | isTrue# (x ># y') = [I# x]-                           | otherwise         = I# x : go_up (x +# delta)-               in I# x1 : go_up x2---- Requires x2 >= x1-efdtIntUpFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r-efdtIntUpFB c n x1 x2 y    -- Be careful about overflow!- | isTrue# (y <# x2) = if isTrue# (y <# x1) then n else I# x1 `c` n- | otherwise = -- Common case: x1 <= x2 <= y-               let !delta = x2 -# x1 -- >= 0-                   !y' = y -# delta  -- x1 <= y' <= y; hence y' is representable--                   -- Invariant: x <= y-                   -- Note that: z <= y' => z + delta won't overflow-                   -- so we are guaranteed not to overflow if/when we recurse-                   go_up x | isTrue# (x ># y') = I# x `c` n-                           | otherwise         = I# x `c` go_up (x +# delta)-               in I# x1 `c` go_up x2---- Requires x2 <= x1-efdtIntDn :: Int# -> Int# -> Int# -> [Int]-efdtIntDn x1 x2 y    -- Be careful about underflow!- | isTrue# (y ># x2) = if isTrue# (y ># x1) then [] else [I# x1]- | otherwise = -- Common case: x1 >= x2 >= y-               let !delta = x2 -# x1 -- <= 0-                   !y' = y -# delta  -- y <= y' <= x1; hence y' is representable--                   -- Invariant: x >= y-                   -- Note that: z >= y' => z + delta won't underflow-                   -- so we are guaranteed not to underflow if/when we recurse-                   go_dn x | isTrue# (x <# y') = [I# x]-                           | otherwise         = I# x : go_dn (x +# delta)-   in I# x1 : go_dn x2---- Requires x2 <= x1-efdtIntDnFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r-efdtIntDnFB c n x1 x2 y    -- Be careful about underflow!- | isTrue# (y ># x2) = if isTrue# (y ># x1) then n else I# x1 `c` n- | otherwise = -- Common case: x1 >= x2 >= y-               let !delta = x2 -# x1 -- <= 0-                   !y' = y -# delta  -- y <= y' <= x1; hence y' is representable--                   -- Invariant: x >= y-                   -- Note that: z >= y' => z + delta won't underflow-                   -- so we are guaranteed not to underflow if/when we recurse-                   go_dn x | isTrue# (x <# y') = I# x `c` n-                           | otherwise         = I# x `c` go_dn (x +# delta)-               in I# x1 `c` go_dn x2------------------------------------------------------------------------------ Word---------------------------------------------------------------------------instance Bounded Word where-    minBound = 0--    -- use unboxed literals for maxBound, because GHC doesn't optimise-    -- (fromInteger 0xffffffff :: Word).-#if WORD_SIZE_IN_BITS == 32-    maxBound = W# (int2Word# 0xFFFFFFFF#)-#elif WORD_SIZE_IN_BITS == 64-    maxBound = W# (int2Word# 0xFFFFFFFFFFFFFFFF#)-#else-#error Unhandled value for WORD_SIZE_IN_BITS-#endif--instance Enum Word where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Word"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Word"-    toEnum i@(I# i#)-        | i >= 0        = W# (int2Word# i#)-        | otherwise     = toEnumError "Word" i (minBound::Word, maxBound::Word)-    fromEnum x@(W# x#)-        | x <= maxIntWord = I# (word2Int# x#)-        | otherwise       = fromEnumError "Word" x--    enumFrom n             = map integerToWordX [wordToIntegerX n .. wordToIntegerX (maxBound :: Word)]-    enumFromTo n1 n2       = map integerToWordX [wordToIntegerX n1 .. wordToIntegerX n2]-    enumFromThenTo n1 n2 m = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX m]-    enumFromThen n1 n2     = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX limit]-      where-         limit :: Word-         limit  | n2 >= n1  = maxBound-                | otherwise = minBound--maxIntWord :: Word--- The biggest word representable as an Int-maxIntWord = W# (case maxInt of I# i -> int2Word# i)---- For some reason integerToWord and wordToInteger (GHC.Integer.Type)--- work over Word#-integerToWordX :: Integer -> Word-integerToWordX i = W# (integerToWord i)--wordToIntegerX :: Word -> Integer-wordToIntegerX (W# x#) = wordToInteger x#----------------------------------------------------------------------------- Integer---------------------------------------------------------------------------instance  Enum Integer  where-    succ x               = x + 1-    pred x               = x - 1-    toEnum (I# n)        = smallInteger n-    fromEnum n           = I# (integerToInt n)--    {-# INLINE enumFrom #-}-    {-# INLINE enumFromThen #-}-    {-# INLINE enumFromTo #-}-    {-# INLINE enumFromThenTo #-}-    enumFrom x             = enumDeltaInteger   x 1-    enumFromThen x y       = enumDeltaInteger   x (y-x)-    enumFromTo x lim       = enumDeltaToInteger x 1     lim-    enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim--{-# RULES-"enumDeltaInteger"      [~1] forall x y.  enumDeltaInteger x y     = build (\c _ -> enumDeltaIntegerFB c x y)-"efdtInteger"           [~1] forall x y l.enumDeltaToInteger x y l = build (\c n -> enumDeltaToIntegerFB c n x y l)-"enumDeltaInteger"      [1] enumDeltaIntegerFB   (:)    = enumDeltaInteger-"enumDeltaToInteger"    [1] enumDeltaToIntegerFB (:) [] = enumDeltaToInteger- #-}--{-# NOINLINE [0] enumDeltaIntegerFB #-}-enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b-enumDeltaIntegerFB c x d = x `seq` (x `c` enumDeltaIntegerFB c (x+d) d)--{-# NOINLINE [1] enumDeltaInteger #-}-enumDeltaInteger :: Integer -> Integer -> [Integer]-enumDeltaInteger x d = x `seq` (x : enumDeltaInteger (x+d) d)--- strict accumulator, so---     head (drop 1000000 [1 .. ]--- works--{-# NOINLINE [0] enumDeltaToIntegerFB #-}--- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire-enumDeltaToIntegerFB :: (Integer -> a -> a) -> a-                     -> Integer -> Integer -> Integer -> a-enumDeltaToIntegerFB c n x delta lim-  | delta >= 0 = up_fb c n x delta lim-  | otherwise  = dn_fb c n x delta lim--{-# RULES-"enumDeltaToInteger1"   [0] forall c n x . enumDeltaToIntegerFB c n x 1 = up_fb c n x 1- #-}--- This rule ensures that in the common case (delta = 1), we do not do the check here,--- and also that we have the chance to inline up_fb, which would allow the constructor to be--- inlined and good things to happen.--- We do not do it for Int this way because hand-tuned code already exists, and--- the special case varies more from the general case, due to the issue of overflows.--{-# NOINLINE [1] enumDeltaToInteger #-}-enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer]-enumDeltaToInteger x delta lim-  | delta >= 0 = up_list x delta lim-  | otherwise  = dn_list x delta lim--up_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a-up_fb c n x0 delta lim = go (x0 :: Integer)-                      where-                        go x | x > lim   = n-                             | otherwise = x `c` go (x+delta)-dn_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a-dn_fb c n x0 delta lim = go (x0 :: Integer)-                      where-                        go x | x < lim   = n-                             | otherwise = x `c` go (x+delta)--up_list :: Integer -> Integer -> Integer -> [Integer]-up_list x0 delta lim = go (x0 :: Integer)-                    where-                        go x | x > lim   = []-                             | otherwise = x : go (x+delta)-dn_list :: Integer -> Integer -> Integer -> [Integer]-dn_list x0 delta lim = go (x0 :: Integer)-                    where-                        go x | x < lim   = []-                             | otherwise = x : go (x+delta)
− GHC/Environment.hs
@@ -1,62 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE CPP #-}--module GHC.Environment (getFullArgs) where--import Foreign-import Foreign.C-import GHC.Base-import GHC.Real ( fromIntegral )--#ifdef mingw32_HOST_OS-import GHC.IO (finally)-import GHC.Windows--# if defined(i386_HOST_ARCH)-#  define WINDOWS_CCONV stdcall-# elif defined(x86_64_HOST_ARCH)-#  define WINDOWS_CCONV ccall-# else-#  error Unknown mingw32 arch-# endif---- Ignore the arguments to hs_init on Windows for the sake of Unicode compat-getFullArgs :: IO [String]-getFullArgs = do-    p_arg_string <- c_GetCommandLine-    alloca $ \p_argc -> do-     p_argv <- c_CommandLineToArgv p_arg_string p_argc-     if p_argv == nullPtr-      then throwGetLastError "getFullArgs"-      else flip finally (c_LocalFree p_argv) $ do-       argc <- peek p_argc-       p_argvs <- peekArray (fromIntegral argc) p_argv-       mapM peekCWString p_argvs--foreign import WINDOWS_CCONV unsafe "windows.h GetCommandLineW"-    c_GetCommandLine :: IO (Ptr CWString)--foreign import WINDOWS_CCONV unsafe "windows.h CommandLineToArgvW"-    c_CommandLineToArgv :: Ptr CWString -> Ptr CInt -> IO (Ptr CWString)--foreign import WINDOWS_CCONV unsafe "Windows.h LocalFree"-    c_LocalFree :: Ptr a -> IO (Ptr a)-#else-import GHC.IO.Encoding-import GHC.Num-import qualified GHC.Foreign as GHC--getFullArgs :: IO [String]-getFullArgs =-  alloca $ \ p_argc ->-  alloca $ \ p_argv -> do-   getFullProgArgv p_argc p_argv-   p    <- fromIntegral `liftM` peek p_argc-   argv <- peek p_argv-   enc <- getFileSystemEncoding-   peekArray (p - 1) (advancePtr argv 1) >>= mapM (GHC.peekCString enc)--foreign import ccall unsafe "getFullProgArgv"-    getFullProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()-#endif
− GHC/Err.hs
@@ -1,47 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Err--- Copyright   :  (c) The University of Glasgow, 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ The "GHC.Err" module defines the code for the wired-in error functions,--- which have a special type in the compiler (with \"open tyvars\").------ We cannot define these functions in a module where they might be used--- (e.g., "GHC.Base"), because the magical wired-in type will get confused--- with what the typechecker figures out.-----------------------------------------------------------------------------------module GHC.Err( absentErr, error, undefined ) where-import GHC.CString ()-import GHC.Types-import GHC.Prim-import GHC.Integer ()   -- Make sure Integer is compiled first-                        -- because GHC depends on it in a wired-in way-                        -- so the build system doesn't see the dependency-import {-# SOURCE #-} GHC.Exception( errorCallException )---- | 'error' stops execution and displays an error message.-error :: [Char] -> a-error s = raise# (errorCallException s)---- | A special case of 'error'.--- It is expected that compilers will recognize this and insert error--- messages which are more appropriate to the context in which 'undefined'--- appears.-undefined :: a-undefined =  error "Prelude.undefined"---- | Used for compiler-generated error message;--- encoding saves bytes of string junk.-absentErr :: a-absentErr = error "Oops! The program has entered an `absent' argument!\n"
− GHC/Event.hs
@@ -1,46 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---- ------------------------------------------------------------------------------- | This module provides scalable event notification for file--- descriptors and timeouts.------ This module should be considered GHC internal.------ ------------------------------------------------------------------------------module GHC.Event-    ( -- * Types-      EventManager-    , TimerManager--      -- * Creation-    , getSystemEventManager-    , new-    , getSystemTimerManager--      -- * Registering interest in I/O events-    , Event-    , evtRead-    , evtWrite-    , IOCallback-    , FdKey(keyFd)-    , Lifetime(..)-    , registerFd-    , unregisterFd-    , unregisterFd_-    , closeFd--      -- * Registering interest in timeout events-    , TimeoutCallback-    , TimeoutKey-    , registerTimeout-    , updateTimeout-    , unregisterTimeout-    ) where--import GHC.Event.Manager-import GHC.Event.TimerManager (TimeoutCallback, TimeoutKey, registerTimeout,-                               updateTimeout, unregisterTimeout, TimerManager)-import GHC.Event.Thread (getSystemEventManager, getSystemTimerManager)-
− GHC/Event/Arr.hs
@@ -1,32 +0,0 @@-{-# LANGUAGE MagicHash, NoImplicitPrelude, UnboxedTuples #-}--module GHC.Event.Arr-    (-      Arr(..)-    , new-    , size-    , read-    , write-    ) where--import GHC.Base (($))-import GHC.Prim (MutableArray#, RealWorld, newArray#, readArray#,-                 sizeofMutableArray#, writeArray#)-import GHC.Types (IO(..), Int(..))--data Arr a = Arr (MutableArray# RealWorld a)--new :: a -> Int -> IO (Arr a)-new defval (I# n#) = IO $ \s0# ->-  case newArray# n# defval s0# of (# s1#, marr# #) -> (# s1#, Arr marr# #)--size :: Arr a -> Int-size (Arr a) = I# (sizeofMutableArray# a)--read :: Arr a -> Int -> IO a-read (Arr a) (I# n#) = IO $ \s0# ->-  case readArray# a n# s0# of (# s1#, val #) -> (# s1#, val #)--write :: Arr a -> Int -> a -> IO ()-write (Arr a) (I# n#) val = IO $ \s0# ->-  case writeArray# a n# val s0# of s1# -> (# s1#, () #)
− GHC/Event/Array.hs
@@ -1,312 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE BangPatterns, CPP, NoImplicitPrelude #-}--module GHC.Event.Array-    (-      Array-    , capacity-    , clear-    , concat-    , copy-    , duplicate-    , empty-    , ensureCapacity-    , findIndex-    , forM_-    , length-    , loop-    , new-    , removeAt-    , snoc-    , unsafeLoad-    , unsafeRead-    , unsafeWrite-    , useAsPtr-    ) where--import Data.Bits ((.|.), shiftR)-import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)-import Data.Maybe-import Foreign.C.Types (CSize(..))-import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)-import Foreign.Ptr (Ptr, nullPtr, plusPtr)-import Foreign.Storable (Storable(..))-import GHC.Base hiding (empty)-import GHC.ForeignPtr (mallocPlainForeignPtrBytes, newForeignPtr_)-import GHC.Num (Num(..))-import GHC.Real (fromIntegral)-import GHC.Show (show)--#include "MachDeps.h"--#define BOUNDS_CHECKING 1--#if defined(BOUNDS_CHECKING)--- This fugly hack is brought by GHC's apparent reluctance to deal--- with MagicHash and UnboxedTuples when inferring types. Eek!-#define CHECK_BOUNDS(_func_,_len_,_k_) \-if (_k_) < 0 || (_k_) >= (_len_) then error ("GHC.Event.Array." ++ (_func_) ++ ": bounds error, index " ++ show (_k_) ++ ", capacity " ++ show (_len_)) else-#else-#define CHECK_BOUNDS(_func_,_len_,_k_)-#endif---- Invariant: size <= capacity-newtype Array a = Array (IORef (AC a))---- The actual array content.-data AC a = AC-    !(ForeignPtr a)  -- Elements-    !Int      -- Number of elements (length)-    !Int      -- Maximum number of elements (capacity)--empty :: IO (Array a)-empty = do-  p <- newForeignPtr_ nullPtr-  Array `fmap` newIORef (AC p 0 0)--allocArray :: Storable a => Int -> IO (ForeignPtr a)-allocArray n = allocHack undefined- where-  allocHack :: Storable a => a -> IO (ForeignPtr a)-  allocHack dummy = mallocPlainForeignPtrBytes (n * sizeOf dummy)--reallocArray :: Storable a => ForeignPtr a -> Int -> Int -> IO (ForeignPtr a)-reallocArray p newSize oldSize = reallocHack undefined p- where-  reallocHack :: Storable a => a -> ForeignPtr a -> IO (ForeignPtr a)-  reallocHack dummy src = do-      let size = sizeOf dummy-      dst <- mallocPlainForeignPtrBytes (newSize * size)-      withForeignPtr src $ \s ->-        when (s /= nullPtr && oldSize > 0) .-          withForeignPtr dst $ \d -> do-            _ <- memcpy d s (fromIntegral (oldSize * size))-            return ()-      return dst--new :: Storable a => Int -> IO (Array a)-new c = do-    es <- allocArray cap-    fmap Array (newIORef (AC es 0 cap))-  where-    cap = firstPowerOf2 c--duplicate :: Storable a => Array a -> IO (Array a)-duplicate a = dupHack undefined a- where-  dupHack :: Storable b => b -> Array b -> IO (Array b)-  dupHack dummy (Array ref) = do-    AC es len cap <- readIORef ref-    ary <- allocArray cap-    withForeignPtr ary $ \dest ->-      withForeignPtr es $ \src -> do-        _ <- memcpy dest src (fromIntegral (len * sizeOf dummy))-        return ()-    Array `fmap` newIORef (AC ary len cap)--length :: Array a -> IO Int-length (Array ref) = do-    AC _ len _ <- readIORef ref-    return len--capacity :: Array a -> IO Int-capacity (Array ref) = do-    AC _ _ cap <- readIORef ref-    return cap--unsafeRead :: Storable a => Array a -> Int -> IO a-unsafeRead (Array ref) ix = do-    AC es _ cap <- readIORef ref-    CHECK_BOUNDS("unsafeRead",cap,ix)-      withForeignPtr es $ \p ->-        peekElemOff p ix--unsafeWrite :: Storable a => Array a -> Int -> a -> IO ()-unsafeWrite (Array ref) ix a = do-    ac <- readIORef ref-    unsafeWrite' ac ix a--unsafeWrite' :: Storable a => AC a -> Int -> a -> IO ()-unsafeWrite' (AC es _ cap) ix a = do-    CHECK_BOUNDS("unsafeWrite'",cap,ix)-      withForeignPtr es $ \p ->-        pokeElemOff p ix a--unsafeLoad :: Storable a => Array a -> (Ptr a -> Int -> IO Int) -> IO Int-unsafeLoad (Array ref) load = do-    AC es _ cap <- readIORef ref-    len' <- withForeignPtr es $ \p -> load p cap-    writeIORef ref (AC es len' cap)-    return len'--ensureCapacity :: Storable a => Array a -> Int -> IO ()-ensureCapacity (Array ref) c = do-    ac@(AC _ _ cap) <- readIORef ref-    ac'@(AC _ _ cap') <- ensureCapacity' ac c-    when (cap' /= cap) $-      writeIORef ref ac'--ensureCapacity' :: Storable a => AC a -> Int -> IO (AC a)-ensureCapacity' ac@(AC es len cap) c = do-    if c > cap-      then do-        es' <- reallocArray es cap' cap-        return (AC es' len cap')-      else-        return ac-  where-    cap' = firstPowerOf2 c--useAsPtr :: Array a -> (Ptr a -> Int -> IO b) -> IO b-useAsPtr (Array ref) f = do-    AC es len _ <- readIORef ref-    withForeignPtr es $ \p -> f p len--snoc :: Storable a => Array a -> a -> IO ()-snoc (Array ref) e = do-    ac@(AC _ len _) <- readIORef ref-    let len' = len + 1-    ac'@(AC es _ cap) <- ensureCapacity' ac len'-    unsafeWrite' ac' len e-    writeIORef ref (AC es len' cap)--clear :: Storable a => Array a -> IO ()-clear (Array ref) = do-  atomicModifyIORef' ref $ \(AC es _ cap) ->-        (AC es 0 cap, ())--forM_ :: Storable a => Array a -> (a -> IO ()) -> IO ()-forM_ ary g = forHack ary g undefined-  where-    forHack :: Storable b => Array b -> (b -> IO ()) -> b -> IO ()-    forHack (Array ref) f dummy = do-      AC es len _ <- readIORef ref-      let size = sizeOf dummy-          offset = len * size-      withForeignPtr es $ \p -> do-        let go n | n >= offset = return ()-                 | otherwise = do-              f =<< peek (p `plusPtr` n)-              go (n + size)-        go 0--loop :: Storable a => Array a -> b -> (b -> a -> IO (b,Bool)) -> IO ()-loop ary z g = loopHack ary z g undefined-  where-    loopHack :: Storable b => Array b -> c -> (c -> b -> IO (c,Bool)) -> b-             -> IO ()-    loopHack (Array ref) y f dummy = do-      AC es len _ <- readIORef ref-      let size = sizeOf dummy-          offset = len * size-      withForeignPtr es $ \p -> do-        let go n k-                | n >= offset = return ()-                | otherwise = do-                      (k',cont) <- f k =<< peek (p `plusPtr` n)-                      when cont $ go (n + size) k'-        go 0 y--findIndex :: Storable a => (a -> Bool) -> Array a -> IO (Maybe (Int,a))-findIndex = findHack undefined- where-  findHack :: Storable b => b -> (b -> Bool) -> Array b -> IO (Maybe (Int,b))-  findHack dummy p (Array ref) = do-    AC es len _ <- readIORef ref-    let size   = sizeOf dummy-        offset = len * size-    withForeignPtr es $ \ptr ->-      let go !n !i-            | n >= offset = return Nothing-            | otherwise = do-                val <- peek (ptr `plusPtr` n)-                if p val-                  then return $ Just (i, val)-                  else go (n + size) (i + 1)-      in  go 0 0--concat :: Storable a => Array a -> Array a -> IO ()-concat (Array d) (Array s) = do-  da@(AC _ dlen _) <- readIORef d-  sa@(AC _ slen _) <- readIORef s-  writeIORef d =<< copy' da dlen sa 0 slen---- | Copy part of the source array into the destination array. The--- destination array is resized if not large enough.-copy :: Storable a => Array a -> Int -> Array a -> Int -> Int -> IO ()-copy (Array d) dstart (Array s) sstart maxCount = do-  da <- readIORef d-  sa <- readIORef s-  writeIORef d =<< copy' da dstart sa sstart maxCount---- | Copy part of the source array into the destination array. The--- destination array is resized if not large enough.-copy' :: Storable a => AC a -> Int -> AC a -> Int -> Int -> IO (AC a)-copy' d dstart s sstart maxCount = copyHack d s undefined- where-  copyHack :: Storable b => AC b -> AC b -> b -> IO (AC b)-  copyHack dac@(AC _ oldLen _) (AC src slen _) dummy = do-    when (maxCount < 0 || dstart < 0 || dstart > oldLen || sstart < 0 ||-          sstart > slen) $ error "copy: bad offsets or lengths"-    let size = sizeOf dummy-        count = min maxCount (slen - sstart)-    if count == 0-      then return dac-      else do-        AC dst dlen dcap <- ensureCapacity' dac (dstart + count)-        withForeignPtr dst $ \dptr ->-          withForeignPtr src $ \sptr -> do-            _ <- memcpy (dptr `plusPtr` (dstart * size))-                        (sptr `plusPtr` (sstart * size))-                        (fromIntegral (count * size))-            return $ AC dst (max dlen (dstart + count)) dcap--removeAt :: Storable a => Array a -> Int -> IO ()-removeAt a i = removeHack a undefined- where-  removeHack :: Storable b => Array b -> b -> IO ()-  removeHack (Array ary) dummy = do-    AC fp oldLen cap <- readIORef ary-    when (i < 0 || i >= oldLen) $ error "removeAt: invalid index"-    let size   = sizeOf dummy-        newLen = oldLen - 1-    when (newLen > 0 && i < newLen) .-      withForeignPtr fp $ \ptr -> do-        _ <- memmove (ptr `plusPtr` (size * i))-                     (ptr `plusPtr` (size * (i+1)))-                     (fromIntegral (size * (newLen-i)))-        return ()-    writeIORef ary (AC fp newLen cap)--{-The firstPowerOf2 function works by setting all bits on the right-hand-side of the most significant flagged bit to 1, and then incrementing-the entire value at the end so it "rolls over" to the nearest power of-two.--}---- | Computes the next-highest power of two for a particular integer,--- @n@.  If @n@ is already a power of two, returns @n@.  If @n@ is--- zero, returns zero, even though zero is not a power of two.-firstPowerOf2 :: Int -> Int-firstPowerOf2 !n =-    let !n1 = n - 1-        !n2 = n1 .|. (n1 `shiftR` 1)-        !n3 = n2 .|. (n2 `shiftR` 2)-        !n4 = n3 .|. (n3 `shiftR` 4)-        !n5 = n4 .|. (n4 `shiftR` 8)-        !n6 = n5 .|. (n5 `shiftR` 16)-#if WORD_SIZE_IN_BITS == 32-    in n6 + 1-#elif WORD_SIZE_IN_BITS == 64-        !n7 = n6 .|. (n6 `shiftR` 32)-    in n7 + 1-#else-# error firstPowerOf2 not defined on this architecture-#endif--foreign import ccall unsafe "string.h memcpy"-    memcpy :: Ptr a -> Ptr a -> CSize -> IO (Ptr a)--foreign import ccall unsafe "string.h memmove"-    memmove :: Ptr a -> Ptr a -> CSize -> IO (Ptr a)-
− GHC/Event/Clock.hsc
@@ -1,17 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}--module GHC.Event.Clock (getMonotonicTime) where--import GHC.Base-import GHC.Real-import Data.Word---- | Return monotonic time in seconds, since some unspecified starting point-getMonotonicTime :: IO Double-getMonotonicTime = do w <- getMonotonicNSec-                      return (fromIntegral w / 1000000000)--foreign import ccall unsafe "getMonotonicNSec"-    getMonotonicNSec :: IO Word64-
− GHC/Event/Control.hs
@@ -1,210 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , ScopedTypeVariables-           , BangPatterns-  #-}--module GHC.Event.Control-    (-    -- * Managing the IO manager-      Signal-    , ControlMessage(..)-    , Control-    , newControl-    , closeControl-    -- ** Control message reception-    , readControlMessage-    -- *** File descriptors-    , controlReadFd-    , controlWriteFd-    , wakeupReadFd-    -- ** Control message sending-    , sendWakeup-    , sendDie-    -- * Utilities-    , setNonBlockingFD-    ) where--#include "EventConfig.h"--import Foreign.ForeignPtr (ForeignPtr)-import GHC.Base-import GHC.Conc.Signal (Signal)-import GHC.Real (fromIntegral)-import GHC.Show (Show)-import GHC.Word (Word8)-import Foreign.C.Error (throwErrnoIfMinus1_)-import Foreign.C.Types (CInt(..), CSize(..))-import Foreign.ForeignPtr (mallocForeignPtrBytes, withForeignPtr)-import Foreign.Marshal (alloca, allocaBytes)-import Foreign.Marshal.Array (allocaArray)-import Foreign.Ptr (castPtr)-import Foreign.Storable (peek, peekElemOff, poke)-import System.Posix.Internals (c_close, c_pipe, c_read, c_write,-                               setCloseOnExec, setNonBlockingFD)-import System.Posix.Types (Fd)--#if defined(HAVE_EVENTFD)-import Foreign.C.Error (throwErrnoIfMinus1)-import Foreign.C.Types (CULLong(..))-#else-import Foreign.C.Error (eAGAIN, eWOULDBLOCK, getErrno, throwErrno)-#endif--data ControlMessage = CMsgWakeup-                    | CMsgDie-                    | CMsgSignal {-# UNPACK #-} !(ForeignPtr Word8)-                                 {-# UNPACK #-} !Signal-    deriving (Eq, Show)---- | The structure used to tell the IO manager thread what to do.-data Control = W {-      controlReadFd  :: {-# UNPACK #-} !Fd-    , controlWriteFd :: {-# UNPACK #-} !Fd-#if defined(HAVE_EVENTFD)-    , controlEventFd :: {-# UNPACK #-} !Fd-#else-    , wakeupReadFd   :: {-# UNPACK #-} !Fd-    , wakeupWriteFd  :: {-# UNPACK #-} !Fd-#endif-    , didRegisterWakeupFd :: !Bool-    } deriving (Show)--#if defined(HAVE_EVENTFD)-wakeupReadFd :: Control -> Fd-wakeupReadFd = controlEventFd-{-# INLINE wakeupReadFd #-}-#endif---- | Create the structure (usually a pipe) used for waking up the IO--- manager thread from another thread.-newControl :: Bool -> IO Control-newControl shouldRegister = allocaArray 2 $ \fds -> do-  let createPipe = do-        throwErrnoIfMinus1_ "pipe" $ c_pipe fds-        rd <- peekElemOff fds 0-        wr <- peekElemOff fds 1-        -- The write end must be non-blocking, since we may need to-        -- poke the event manager from a signal handler.-        setNonBlockingFD wr True-        setCloseOnExec rd-        setCloseOnExec wr-        return (rd, wr)-  (ctrl_rd, ctrl_wr) <- createPipe-#if defined(HAVE_EVENTFD)-  ev <- throwErrnoIfMinus1 "eventfd" $ c_eventfd 0 0-  setNonBlockingFD ev True-  setCloseOnExec ev-  when shouldRegister $ c_setIOManagerWakeupFd ev-#else-  (wake_rd, wake_wr) <- createPipe-  when shouldRegister $ c_setIOManagerWakeupFd wake_wr-#endif-  return W { controlReadFd  = fromIntegral ctrl_rd-           , controlWriteFd = fromIntegral ctrl_wr-#if defined(HAVE_EVENTFD)-           , controlEventFd = fromIntegral ev-#else-           , wakeupReadFd   = fromIntegral wake_rd-           , wakeupWriteFd  = fromIntegral wake_wr-#endif-           , didRegisterWakeupFd = shouldRegister-           }---- | Close the control structure used by the IO manager thread.--- N.B. If this Control is the Control whose wakeup file was registered with--- the RTS, then *BEFORE* the wakeup file is closed, we must call--- c_setIOManagerWakeupFd (-1), so that the RTS does not try to use the wakeup--- file after it has been closed.-closeControl :: Control -> IO ()-closeControl w = do-  _ <- c_close . fromIntegral . controlReadFd $ w-  _ <- c_close . fromIntegral . controlWriteFd $ w-  when (didRegisterWakeupFd w) $ c_setIOManagerWakeupFd (-1)-#if defined(HAVE_EVENTFD)-  _ <- c_close . fromIntegral . controlEventFd $ w-#else-  _ <- c_close . fromIntegral . wakeupReadFd $ w-  _ <- c_close . fromIntegral . wakeupWriteFd $ w-#endif-  return ()--io_MANAGER_WAKEUP, io_MANAGER_DIE :: Word8-io_MANAGER_WAKEUP = 0xff-io_MANAGER_DIE    = 0xfe--foreign import ccall "__hscore_sizeof_siginfo_t"-    sizeof_siginfo_t :: CSize--readControlMessage :: Control -> Fd -> IO ControlMessage-readControlMessage ctrl fd-    | fd == wakeupReadFd ctrl = allocaBytes wakeupBufferSize $ \p -> do-                    throwErrnoIfMinus1_ "readWakeupMessage" $-                      c_read (fromIntegral fd) p (fromIntegral wakeupBufferSize)-                    return CMsgWakeup-    | otherwise =-        alloca $ \p -> do-            throwErrnoIfMinus1_ "readControlMessage" $-                c_read (fromIntegral fd) p 1-            s <- peek p-            case s of-                -- Wakeup messages shouldn't be sent on the control-                -- file descriptor but we handle them anyway.-                _ | s == io_MANAGER_WAKEUP -> return CMsgWakeup-                _ | s == io_MANAGER_DIE    -> return CMsgDie-                _ -> do  -- Signal-                    fp <- mallocForeignPtrBytes (fromIntegral sizeof_siginfo_t)-                    withForeignPtr fp $ \p_siginfo -> do-                        r <- c_read (fromIntegral fd) (castPtr p_siginfo)-                             sizeof_siginfo_t-                        when (r /= fromIntegral sizeof_siginfo_t) $-                            error "failed to read siginfo_t"-                        let !s' = fromIntegral s-                        return $ CMsgSignal fp s'--  where wakeupBufferSize =-#if defined(HAVE_EVENTFD)-            8-#else-            4096-#endif--sendWakeup :: Control -> IO ()-#if defined(HAVE_EVENTFD)-sendWakeup c =-  throwErrnoIfMinus1_ "sendWakeup" $-  c_eventfd_write (fromIntegral (controlEventFd c)) 1-#else-sendWakeup c = do-  n <- sendMessage (wakeupWriteFd c) CMsgWakeup-  case n of-    _ | n /= -1   -> return ()-      | otherwise -> do-                   errno <- getErrno-                   when (errno /= eAGAIN && errno /= eWOULDBLOCK) $-                     throwErrno "sendWakeup"-#endif--sendDie :: Control -> IO ()-sendDie c = throwErrnoIfMinus1_ "sendDie" $-            sendMessage (controlWriteFd c) CMsgDie--sendMessage :: Fd -> ControlMessage -> IO Int-sendMessage fd msg = alloca $ \p -> do-  case msg of-    CMsgWakeup        -> poke p io_MANAGER_WAKEUP-    CMsgDie           -> poke p io_MANAGER_DIE-    CMsgSignal _fp _s -> error "Signals can only be sent from within the RTS"-  fromIntegral `fmap` c_write (fromIntegral fd) p 1--#if defined(HAVE_EVENTFD)-foreign import ccall unsafe "sys/eventfd.h eventfd"-   c_eventfd :: CInt -> CInt -> IO CInt--foreign import ccall unsafe "sys/eventfd.h eventfd_write"-   c_eventfd_write :: CInt -> CULLong -> IO CInt-#endif--foreign import ccall unsafe "setIOManagerWakeupFd"-   c_setIOManagerWakeupFd :: CInt -> IO ()
− GHC/Event/EPoll.hsc
@@ -1,239 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE GeneralizedNewtypeDeriving-           , NoImplicitPrelude-           , BangPatterns-  #-}---------------------------------------------------------------------------------- |--- A binding to the epoll I/O event notification facility------ epoll is a variant of poll that can be used either as an edge-triggered or--- a level-triggered interface and scales well to large numbers of watched file--- descriptors.------ epoll decouples monitor an fd from the process of registering it.-----------------------------------------------------------------------------------module GHC.Event.EPoll-    (-      new-    , available-    ) where--import qualified GHC.Event.Internal as E--#include "EventConfig.h"-#if !defined(HAVE_EPOLL)-import GHC.Base--new :: IO E.Backend-new = error "EPoll back end not implemented for this platform"--available :: Bool-available = False-{-# INLINE available #-}-#else--#include <sys/epoll.h>--import Data.Bits (Bits, FiniteBits, (.|.), (.&.))-import Data.Word (Word32)-import Foreign.C.Error (eNOENT, getErrno, throwErrno,-                        throwErrnoIfMinus1, throwErrnoIfMinus1_)-import Foreign.C.Types (CInt(..))-import Foreign.Marshal.Utils (with)-import Foreign.Ptr (Ptr)-import Foreign.Storable (Storable(..))-import GHC.Base-import GHC.Num (Num(..))-import GHC.Real (ceiling, fromIntegral)-import GHC.Show (Show)-import System.Posix.Internals (c_close)-import System.Posix.Internals (setCloseOnExec)-import System.Posix.Types (Fd(..))--import qualified GHC.Event.Array    as A-import           GHC.Event.Internal (Timeout(..))--available :: Bool-available = True-{-# INLINE available #-}--data EPoll = EPoll {-      epollFd     :: {-# UNPACK #-} !EPollFd-    , epollEvents :: {-# UNPACK #-} !(A.Array Event)-    }---- | Create a new epoll backend.-new :: IO E.Backend-new = do-  epfd <- epollCreate-  evts <- A.new 64-  let !be = E.backend poll modifyFd modifyFdOnce delete (EPoll epfd evts)-  return be--delete :: EPoll -> IO ()-delete be = do-  _ <- c_close . fromEPollFd . epollFd $ be-  return ()---- | Change the set of events we are interested in for a given file--- descriptor.-modifyFd :: EPoll -> Fd -> E.Event -> E.Event -> IO Bool-modifyFd ep fd oevt nevt =-  with (Event (fromEvent nevt) fd) $ \evptr -> do-    epollControl (epollFd ep) op fd evptr-    return True-  where op | oevt == mempty = controlOpAdd-           | nevt == mempty = controlOpDelete-           | otherwise      = controlOpModify--modifyFdOnce :: EPoll -> Fd -> E.Event -> IO Bool-modifyFdOnce ep fd evt =-  do let !ev = fromEvent evt .|. epollOneShot-     res <- with (Event ev fd) $-            epollControl_ (epollFd ep) controlOpModify fd-     if res == 0-       then return True-       else do err <- getErrno-               if err == eNOENT-                 then with (Event ev fd) $ \evptr -> do-                        epollControl (epollFd ep) controlOpAdd fd evptr-                        return True-                 else throwErrno "modifyFdOnce"---- | Select a set of file descriptors which are ready for I/O--- operations and call @f@ for all ready file descriptors, passing the--- events that are ready.-poll :: EPoll                     -- ^ state-     -> Maybe Timeout             -- ^ timeout in milliseconds-     -> (Fd -> E.Event -> IO ())  -- ^ I/O callback-     -> IO Int-poll ep mtimeout f = do-  let events = epollEvents ep-      fd = epollFd ep--  -- Will return zero if the system call was interupted, in which case-  -- we just return (and try again later.)-  n <- A.unsafeLoad events $ \es cap -> case mtimeout of-    Just timeout -> epollWait fd es cap $ fromTimeout timeout-    Nothing      -> epollWaitNonBlock fd es cap--  when (n > 0) $ do-    A.forM_ events $ \e -> f (eventFd e) (toEvent (eventTypes e))-    cap <- A.capacity events-    when (cap == n) $ A.ensureCapacity events (2 * cap)-  return n--newtype EPollFd = EPollFd {-      fromEPollFd :: CInt-    } deriving (Eq, Show)--data Event = Event {-      eventTypes :: EventType-    , eventFd    :: Fd-    } deriving (Show)--instance Storable Event where-    sizeOf    _ = #size struct epoll_event-    alignment _ = alignment (undefined :: CInt)--    peek ptr = do-        ets <- #{peek struct epoll_event, events} ptr-        ed  <- #{peek struct epoll_event, data.fd}   ptr-        let !ev = Event (EventType ets) ed-        return ev--    poke ptr e = do-        #{poke struct epoll_event, events} ptr (unEventType $ eventTypes e)-        #{poke struct epoll_event, data.fd}   ptr (eventFd e)--newtype ControlOp = ControlOp CInt--#{enum ControlOp, ControlOp- , controlOpAdd    = EPOLL_CTL_ADD- , controlOpModify = EPOLL_CTL_MOD- , controlOpDelete = EPOLL_CTL_DEL- }--newtype EventType = EventType {-      unEventType :: Word32-    } deriving (Show, Eq, Num, Bits, FiniteBits)--#{enum EventType, EventType- , epollIn  = EPOLLIN- , epollOut = EPOLLOUT- , epollErr = EPOLLERR- , epollHup = EPOLLHUP- , epollOneShot = EPOLLONESHOT- }---- | Create a new epoll context, returning a file descriptor associated with the context.--- The fd may be used for subsequent calls to this epoll context.------ The size parameter to epoll_create is a hint about the expected number of handles.------ The file descriptor returned from epoll_create() should be destroyed via--- a call to close() after polling is finished----epollCreate :: IO EPollFd-epollCreate = do-  fd <- throwErrnoIfMinus1 "epollCreate" $-        c_epoll_create 256 -- argument is ignored-  setCloseOnExec fd-  let !epollFd' = EPollFd fd-  return epollFd'--epollControl :: EPollFd -> ControlOp -> Fd -> Ptr Event -> IO ()-epollControl epfd op fd event =-    throwErrnoIfMinus1_ "epollControl" $ epollControl_ epfd op fd event--epollControl_ :: EPollFd -> ControlOp -> Fd -> Ptr Event -> IO CInt-epollControl_ (EPollFd epfd) (ControlOp op) (Fd fd) event =-    c_epoll_ctl epfd op fd event--epollWait :: EPollFd -> Ptr Event -> Int -> Int -> IO Int-epollWait (EPollFd epfd) events numEvents timeout =-    fmap fromIntegral .-    E.throwErrnoIfMinus1NoRetry "epollWait" $-    c_epoll_wait epfd events (fromIntegral numEvents) (fromIntegral timeout)--epollWaitNonBlock :: EPollFd -> Ptr Event -> Int -> IO Int-epollWaitNonBlock (EPollFd epfd) events numEvents =-  fmap fromIntegral .-  E.throwErrnoIfMinus1NoRetry "epollWaitNonBlock" $-  c_epoll_wait_unsafe epfd events (fromIntegral numEvents) 0--fromEvent :: E.Event -> EventType-fromEvent e = remap E.evtRead  epollIn .|.-              remap E.evtWrite epollOut-  where remap evt to-            | e `E.eventIs` evt = to-            | otherwise         = 0--toEvent :: EventType -> E.Event-toEvent e = remap (epollIn  .|. epollErr .|. epollHup) E.evtRead `mappend`-            remap (epollOut .|. epollErr .|. epollHup) E.evtWrite-  where remap evt to-            | e .&. evt /= 0 = to-            | otherwise      = mempty--fromTimeout :: Timeout -> Int-fromTimeout Forever     = -1-fromTimeout (Timeout s) = ceiling $ 1000 * s--foreign import ccall unsafe "sys/epoll.h epoll_create"-    c_epoll_create :: CInt -> IO CInt--foreign import ccall unsafe "sys/epoll.h epoll_ctl"-    c_epoll_ctl :: CInt -> CInt -> CInt -> Ptr Event -> IO CInt--foreign import ccall safe "sys/epoll.h epoll_wait"-    c_epoll_wait :: CInt -> Ptr Event -> CInt -> CInt -> IO CInt--foreign import ccall unsafe "sys/epoll.h epoll_wait"-    c_epoll_wait_unsafe :: CInt -> Ptr Event -> CInt -> CInt -> IO CInt-#endif /* defined(HAVE_EPOLL) */-
− GHC/Event/IntTable.hs
@@ -1,145 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE BangPatterns, NoImplicitPrelude, RecordWildCards #-}-{-# OPTIONS_GHC -fno-warn-name-shadowing #-}--module GHC.Event.IntTable-    (-      IntTable-    , new-    , lookup-    , insertWith-    , reset-    , delete-    , updateWith-    ) where--import Data.Bits ((.&.), shiftL, shiftR)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.Maybe (Maybe(..), isJust, isNothing)-import Foreign.ForeignPtr (ForeignPtr, mallocForeignPtr, withForeignPtr)-import Foreign.Storable (peek, poke)-import GHC.Base (Monad(..), (=<<), ($), const, liftM, otherwise, when)-import GHC.Classes (Eq(..), Ord(..))-import GHC.Event.Arr (Arr)-import GHC.Num (Num(..))-import GHC.Prim (seq)-import GHC.Types (Bool(..), IO(..), Int(..))-import qualified GHC.Event.Arr as Arr---- A very simple chained integer-keyed mutable hash table. We use--- power-of-two sizing, grow at a load factor of 0.75, and never--- shrink. The "hash function" is the identity function.--newtype IntTable a = IntTable (IORef (IT a))--data IT a = IT {-      tabArr  :: {-# UNPACK #-} !(Arr (Bucket a))-    , tabSize :: {-# UNPACK #-} !(ForeignPtr Int)-    }--data Bucket a = Empty-              | Bucket {-      bucketKey   :: {-# UNPACK #-} !Int-    , bucketValue :: a-    , bucketNext  :: Bucket a-    }--lookup :: Int -> IntTable a -> IO (Maybe a)-lookup k (IntTable ref) = do-  let go Bucket{..}-        | bucketKey == k = return (Just bucketValue)-        | otherwise      = go bucketNext-      go _ = return Nothing-  it@IT{..} <- readIORef ref-  go =<< Arr.read tabArr (indexOf k it)--new :: Int -> IO (IntTable a)-new capacity = IntTable `liftM` (newIORef =<< new_ capacity)--new_ :: Int -> IO (IT a)-new_ capacity = do-  arr <- Arr.new Empty capacity-  size <- mallocForeignPtr-  withForeignPtr size $ \ptr -> poke ptr 0-  return IT { tabArr = arr-            , tabSize = size-            }--grow :: IT a -> IORef (IT a) -> Int -> IO ()-grow oldit ref size = do-  newit <- new_ (Arr.size (tabArr oldit) `shiftL` 1)-  let copySlot n !i-        | n == size = return ()-        | otherwise = do-          let copyBucket !m Empty          = copySlot m (i+1)-              copyBucket  m bkt@Bucket{..} = do-                let idx = indexOf bucketKey newit-                next <- Arr.read (tabArr newit) idx-                Arr.write (tabArr newit) idx bkt { bucketNext = next }-                copyBucket (m+1) bucketNext-          copyBucket n =<< Arr.read (tabArr oldit) i-  copySlot 0 0-  withForeignPtr (tabSize newit) $ \ptr -> poke ptr size-  writeIORef ref newit---- | @insertWith f k v table@ inserts @k@ into @table@ with value @v@.--- If @k@ already appears in @table@ with value @v0@, the value is updated--- to @f v0 v@ and @Just v0@ is returned.-insertWith :: (a -> a -> a) -> Int -> a -> IntTable a -> IO (Maybe a)-insertWith f k v inttable@(IntTable ref) = do-  it@IT{..} <- readIORef ref-  let idx = indexOf k it-      go seen bkt@Bucket{..}-        | bucketKey == k = do-          let !v' = f v bucketValue-              !next = seen <> bucketNext-              Empty        <> bs = bs-              b@Bucket{..} <> bs = b { bucketNext = bucketNext <> bs }-          Arr.write tabArr idx (Bucket k v' next)-          return (Just bucketValue)-        | otherwise = go bkt { bucketNext = seen } bucketNext-      go seen _ = withForeignPtr tabSize $ \ptr -> do-        size <- peek ptr-        if size + 1 >= Arr.size tabArr - (Arr.size tabArr `shiftR` 2)-          then grow it ref size >> insertWith f k v inttable-          else do-            v `seq` Arr.write tabArr idx (Bucket k v seen)-            poke ptr (size + 1)-            return Nothing-  go Empty =<< Arr.read tabArr idx-{-# INLINABLE insertWith #-}---- | Used to undo the effect of a prior insertWith.-reset :: Int -> Maybe a -> IntTable a -> IO ()-reset k (Just v) tbl = insertWith const k v tbl >> return ()-reset k Nothing  tbl = delete k tbl >> return ()--indexOf :: Int -> IT a -> Int-indexOf k IT{..} = k .&. (Arr.size tabArr - 1)---- | Remove the given key from the table and return its associated value.-delete :: Int -> IntTable a -> IO (Maybe a)-delete k t = updateWith (const Nothing) k t--updateWith :: (a -> Maybe a) -> Int -> IntTable a -> IO (Maybe a)-updateWith f k (IntTable ref) = do-  it@IT{..} <- readIORef ref-  let idx = indexOf k it-      go changed bkt@Bucket{..}-        | bucketKey == k =-            let fbv = f bucketValue-                !nb = case fbv of-                        Just val -> bkt { bucketValue = val }-                        Nothing  -> bucketNext-            in (fbv, Just bucketValue, nb)-        | otherwise = case go changed bucketNext of-                        (fbv, ov, nb) -> (fbv, ov, bkt { bucketNext = nb })-      go _ e = (Nothing, Nothing, e)-  (fbv, oldVal, newBucket) <- go False `liftM` Arr.read tabArr idx-  when (isJust oldVal) $ do-    Arr.write tabArr idx newBucket-    when (isNothing fbv) $-      withForeignPtr tabSize $ \ptr -> do-        size <- peek ptr-        poke ptr (size - 1)-  return oldVal
− GHC/Event/Internal.hs
@@ -1,209 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE ExistentialQuantification, NoImplicitPrelude #-}--module GHC.Event.Internal-    (-    -- * Event back end-      Backend-    , backend-    , delete-    , poll-    , modifyFd-    , modifyFdOnce-    -- * Event type-    , Event-    , evtRead-    , evtWrite-    , evtClose-    , eventIs-    -- * Lifetimes-    , Lifetime(..)-    , EventLifetime-    , eventLifetime-    , elLifetime-    , elEvent-    -- * Timeout type-    , Timeout(..)-    -- * Helpers-    , throwErrnoIfMinus1NoRetry-    ) where--import Data.Bits ((.|.), (.&.))-import Data.OldList (foldl', filter, intercalate, null)-import Foreign.C.Error (eINTR, getErrno, throwErrno)-import System.Posix.Types (Fd)-import GHC.Base-import GHC.Num (Num(..))-import GHC.Show (Show(..))---- | An I\/O event.-newtype Event = Event Int-    deriving (Eq)--evtNothing :: Event-evtNothing = Event 0-{-# INLINE evtNothing #-}---- | Data is available to be read.-evtRead :: Event-evtRead = Event 1-{-# INLINE evtRead #-}---- | The file descriptor is ready to accept a write.-evtWrite :: Event-evtWrite = Event 2-{-# INLINE evtWrite #-}---- | Another thread closed the file descriptor.-evtClose :: Event-evtClose = Event 4-{-# INLINE evtClose #-}--eventIs :: Event -> Event -> Bool-eventIs (Event a) (Event b) = a .&. b /= 0--instance Show Event where-    show e = '[' : (intercalate "," . filter (not . null) $-                    [evtRead `so` "evtRead",-                     evtWrite `so` "evtWrite",-                     evtClose `so` "evtClose"]) ++ "]"-        where ev `so` disp | e `eventIs` ev = disp-                           | otherwise      = ""--instance Monoid Event where-    mempty  = evtNothing-    mappend = evtCombine-    mconcat = evtConcat--evtCombine :: Event -> Event -> Event-evtCombine (Event a) (Event b) = Event (a .|. b)-{-# INLINE evtCombine #-}--evtConcat :: [Event] -> Event-evtConcat = foldl' evtCombine evtNothing-{-# INLINE evtConcat #-}---- | The lifetime of an event registration.------ @since 4.8.1.0-data Lifetime = OneShot   -- ^ the registration will be active for only one-                          -- event-              | MultiShot -- ^ the registration will trigger multiple times-              deriving (Show, Eq)---- | The longer of two lifetimes.-elSupremum :: Lifetime -> Lifetime -> Lifetime-elSupremum OneShot OneShot = OneShot-elSupremum _       _       = MultiShot-{-# INLINE elSupremum #-}---- | @mappend@ == @elSupremum@-instance Monoid Lifetime where-    mempty = OneShot-    mappend = elSupremum---- | A pair of an event and lifetime------ Here we encode the event in the bottom three bits and the lifetime--- in the fourth bit.-newtype EventLifetime = EL Int-                      deriving (Show, Eq)--instance Monoid EventLifetime where-    mempty = EL 0-    EL a `mappend` EL b = EL (a .|. b)--eventLifetime :: Event -> Lifetime -> EventLifetime-eventLifetime (Event e) l = EL (e .|. lifetimeBit l)-  where-    lifetimeBit OneShot   = 0-    lifetimeBit MultiShot = 8-{-# INLINE eventLifetime #-}--elLifetime :: EventLifetime -> Lifetime-elLifetime (EL x) = if x .&. 8 == 0 then OneShot else MultiShot-{-# INLINE elLifetime #-}--elEvent :: EventLifetime -> Event-elEvent (EL x) = Event (x .&. 0x7)-{-# INLINE elEvent #-}---- | A type alias for timeouts, specified in seconds.-data Timeout = Timeout {-# UNPACK #-} !Double-             | Forever-               deriving (Show)---- | Event notification backend.-data Backend = forall a. Backend {-      _beState :: !a--    -- | Poll backend for new events.  The provided callback is called-    -- once per file descriptor with new events.-    , _bePoll :: a                          -- backend state-              -> Maybe Timeout              -- timeout in milliseconds ('Nothing' for non-blocking poll)-              -> (Fd -> Event -> IO ())     -- I/O callback-              -> IO Int--    -- | Register, modify, or unregister interest in the given events-    -- on the given file descriptor.-    , _beModifyFd :: a-                  -> Fd       -- file descriptor-                  -> Event    -- old events to watch for ('mempty' for new)-                  -> Event    -- new events to watch for ('mempty' to delete)-                  -> IO Bool--    -- | Register interest in new events on a given file descriptor, set-    -- to be deactivated after the first event.-    , _beModifyFdOnce :: a-                         -> Fd    -- file descriptor-                         -> Event -- new events to watch-                         -> IO Bool--    , _beDelete :: a -> IO ()-    }--backend :: (a -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int)-        -> (a -> Fd -> Event -> Event -> IO Bool)-        -> (a -> Fd -> Event -> IO Bool)-        -> (a -> IO ())-        -> a-        -> Backend-backend bPoll bModifyFd bModifyFdOnce bDelete state =-  Backend state bPoll bModifyFd bModifyFdOnce bDelete-{-# INLINE backend #-}--poll :: Backend -> Maybe Timeout -> (Fd -> Event -> IO ()) -> IO Int-poll (Backend bState bPoll _ _ _) = bPoll bState-{-# INLINE poll #-}---- | Returns 'True' if the modification succeeded.--- Returns 'False' if this backend does not support--- event notifications on this type of file.-modifyFd :: Backend -> Fd -> Event -> Event -> IO Bool-modifyFd (Backend bState _ bModifyFd _ _) = bModifyFd bState-{-# INLINE modifyFd #-}---- | Returns 'True' if the modification succeeded.--- Returns 'False' if this backend does not support--- event notifications on this type of file.-modifyFdOnce :: Backend -> Fd -> Event -> IO Bool-modifyFdOnce (Backend bState _ _ bModifyFdOnce _) = bModifyFdOnce bState-{-# INLINE modifyFdOnce #-}--delete :: Backend -> IO ()-delete (Backend bState _ _ _ bDelete) = bDelete bState-{-# INLINE delete #-}---- | Throw an 'IOError' corresponding to the current value of--- 'getErrno' if the result value of the 'IO' action is -1 and--- 'getErrno' is not 'eINTR'.  If the result value is -1 and--- 'getErrno' returns 'eINTR' 0 is returned.  Otherwise the result--- value is returned.-throwErrnoIfMinus1NoRetry :: (Eq a, Num a) => String -> IO a -> IO a-throwErrnoIfMinus1NoRetry loc f = do-    res <- f-    if res == -1-        then do-            err <- getErrno-            if err == eINTR then return 0 else throwErrno loc-        else return res
− GHC/Event/KQueue.hsc
@@ -1,294 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CApiFFI-           , GeneralizedNewtypeDeriving-           , NoImplicitPrelude-           , RecordWildCards-           , BangPatterns-  #-}--module GHC.Event.KQueue-    (-      new-    , available-    ) where--import qualified GHC.Event.Internal as E--#include "EventConfig.h"-#if !defined(HAVE_KQUEUE)-import GHC.Base--new :: IO E.Backend-new = error "KQueue back end not implemented for this platform"--available :: Bool-available = False-{-# INLINE available #-}-#else--import Data.Bits (Bits(..), FiniteBits(..))-import Data.Word (Word16, Word32)-import Foreign.C.Error (throwErrnoIfMinus1, eINTR, eINVAL,-                        eNOTSUP, getErrno, throwErrno)-import Foreign.C.Types-import Foreign.Marshal.Alloc (alloca)-import Foreign.Ptr (Ptr, nullPtr)-import Foreign.Storable (Storable(..))-import GHC.Base-import GHC.Enum (toEnum)-import GHC.Num (Num(..))-import GHC.Real (ceiling, floor, fromIntegral)-import GHC.Show (Show(show))-import GHC.Event.Internal (Timeout(..))-import System.Posix.Internals (c_close)-import System.Posix.Types (Fd(..))-import qualified GHC.Event.Array as A--#if defined(netbsd_HOST_OS)-import Data.Int (Int64)-#endif--#include <sys/types.h>-#include <sys/event.h>-#include <sys/time.h>---- Handle brokenness on some BSD variants, notably OS X up to at least--- 10.6.  If NOTE_EOF isn't available, we have no way to receive a--- notification from the kernel when we reach EOF on a plain file.-#ifndef NOTE_EOF-# define NOTE_EOF 0-#endif--available :: Bool-available = True-{-# INLINE available #-}----------------------------------------------------------------------------- Exported interface--data KQueue = KQueue {-      kqueueFd     :: {-# UNPACK #-} !KQueueFd-    , kqueueEvents :: {-# UNPACK #-} !(A.Array Event)-    }--new :: IO E.Backend-new = do-  kqfd <- kqueue-  events <- A.new 64-  let !be = E.backend poll modifyFd modifyFdOnce delete (KQueue kqfd events)-  return be--delete :: KQueue -> IO ()-delete kq = do-  _ <- c_close . fromKQueueFd . kqueueFd $ kq-  return ()--modifyFd :: KQueue -> Fd -> E.Event -> E.Event -> IO Bool-modifyFd kq fd oevt nevt-  | nevt == mempty = do-      let !ev = event fd (toFilter oevt) flagDelete noteEOF-      kqueueControl (kqueueFd kq) ev-  | otherwise      = do-      let !ev = event fd (toFilter nevt) flagAdd noteEOF-      kqueueControl (kqueueFd kq) ev--toFilter :: E.Event -> Filter-toFilter evt-  | evt `E.eventIs` E.evtRead = filterRead-  | otherwise                 = filterWrite--modifyFdOnce :: KQueue -> Fd -> E.Event -> IO Bool-modifyFdOnce kq fd evt = do-    let !ev = event fd (toFilter evt) (flagAdd .|. flagOneshot) noteEOF-    kqueueControl (kqueueFd kq) ev--poll :: KQueue-     -> Maybe Timeout-     -> (Fd -> E.Event -> IO ())-     -> IO Int-poll kq mtimeout f = do-    let events = kqueueEvents kq-        fd = kqueueFd kq--    n <- A.unsafeLoad events $ \es cap -> case mtimeout of-      Just timeout -> kqueueWait fd es cap $ fromTimeout timeout-      Nothing      -> kqueueWaitNonBlock fd es cap--    when (n > 0) $ do-        A.forM_ events $ \e -> f (fromIntegral (ident e)) (toEvent (filter e))-        cap <- A.capacity events-        when (n == cap) $ A.ensureCapacity events (2 * cap)-    return n---------------------------------------------------------------------------- FFI binding--newtype KQueueFd = KQueueFd {-      fromKQueueFd :: CInt-    } deriving (Eq, Show)--data Event = KEvent {-      ident  :: {-# UNPACK #-} !CUIntPtr-    , filter :: {-# UNPACK #-} !Filter-    , flags  :: {-# UNPACK #-} !Flag-    , fflags :: {-# UNPACK #-} !FFlag-#ifdef netbsd_HOST_OS-    , data_  :: {-# UNPACK #-} !Int64-#else-    , data_  :: {-# UNPACK #-} !CIntPtr-#endif-    , udata  :: {-# UNPACK #-} !(Ptr ())-    } deriving Show--event :: Fd -> Filter -> Flag -> FFlag -> Event-event fd filt flag fflag = KEvent (fromIntegral fd) filt flag fflag 0 nullPtr--instance Storable Event where-    sizeOf _ = #size struct kevent-    alignment _ = alignment (undefined :: CInt)--    peek ptr = do-        ident'  <- #{peek struct kevent, ident} ptr-        filter' <- #{peek struct kevent, filter} ptr-        flags'  <- #{peek struct kevent, flags} ptr-        fflags' <- #{peek struct kevent, fflags} ptr-        data'   <- #{peek struct kevent, data} ptr-        udata'  <- #{peek struct kevent, udata} ptr-        let !ev = KEvent ident' (Filter filter') (Flag flags') fflags' data'-                         udata'-        return ev--    poke ptr ev = do-        #{poke struct kevent, ident} ptr (ident ev)-        #{poke struct kevent, filter} ptr (filter ev)-        #{poke struct kevent, flags} ptr (flags ev)-        #{poke struct kevent, fflags} ptr (fflags ev)-        #{poke struct kevent, data} ptr (data_ ev)-        #{poke struct kevent, udata} ptr (udata ev)--newtype FFlag = FFlag Word32-    deriving (Eq, Show, Storable)--#{enum FFlag, FFlag- , noteEOF = NOTE_EOF- }--#if SIZEOF_KEV_FLAGS == 4 /* kevent.flag: uint32_t or uint16_t. */-newtype Flag = Flag Word32-#else-newtype Flag = Flag Word16-#endif-    deriving (Bits, FiniteBits, Eq, Num, Show, Storable)--#{enum Flag, Flag- , flagAdd     = EV_ADD- , flagDelete  = EV_DELETE- , flagOneshot = EV_ONESHOT- }--#if SIZEOF_KEV_FILTER == 4 /*kevent.filter: uint32_t or uint16_t. */-newtype Filter = Filter Word32-#else-newtype Filter = Filter Word16-#endif-    deriving (Bits, FiniteBits, Eq, Num, Show, Storable)--filterRead :: Filter-filterRead = Filter (#const EVFILT_READ)-filterWrite :: Filter-filterWrite  = Filter (#const EVFILT_WRITE)--data TimeSpec = TimeSpec {-      tv_sec  :: {-# UNPACK #-} !CTime-    , tv_nsec :: {-# UNPACK #-} !CLong-    }--instance Storable TimeSpec where-    sizeOf _ = #size struct timespec-    alignment _ = alignment (undefined :: CInt)--    peek ptr = do-        tv_sec'  <- #{peek struct timespec, tv_sec} ptr-        tv_nsec' <- #{peek struct timespec, tv_nsec} ptr-        let !ts = TimeSpec tv_sec' tv_nsec'-        return ts--    poke ptr ts = do-        #{poke struct timespec, tv_sec} ptr (tv_sec ts)-        #{poke struct timespec, tv_nsec} ptr (tv_nsec ts)--kqueue :: IO KQueueFd-kqueue = KQueueFd `fmap` throwErrnoIfMinus1 "kqueue" c_kqueue--kqueueControl :: KQueueFd -> Event -> IO Bool-kqueueControl kfd ev =-    withTimeSpec (TimeSpec 0 0) $ \tp ->-        withEvent ev $ \evp -> do-            res <- kevent False kfd evp 1 nullPtr 0 tp-            if res == -1-              then do-               err <- getErrno-               case err of-                 _ | err == eINTR  -> return True-                 _ | err == eINVAL -> return False-                 _ | err == eNOTSUP -> return False-                 _                 -> throwErrno "kevent"-              else return True--kqueueWait :: KQueueFd -> Ptr Event -> Int -> TimeSpec -> IO Int-kqueueWait fd es cap tm =-    fmap fromIntegral $ E.throwErrnoIfMinus1NoRetry "kevent" $-    withTimeSpec tm $ kevent True fd nullPtr 0 es cap--kqueueWaitNonBlock :: KQueueFd -> Ptr Event -> Int -> IO Int-kqueueWaitNonBlock fd es cap =-    fmap fromIntegral $ E.throwErrnoIfMinus1NoRetry "kevent" $-    withTimeSpec (TimeSpec 0 0) $ kevent False fd nullPtr 0 es cap---- TODO: We cannot retry on EINTR as the timeout would be wrong.--- Perhaps we should just return without calling any callbacks.-kevent :: Bool -> KQueueFd -> Ptr Event -> Int -> Ptr Event -> Int -> Ptr TimeSpec-       -> IO CInt-kevent safe k chs chlen evs evlen ts-  | safe      = c_kevent k chs (fromIntegral chlen) evs (fromIntegral evlen) ts-  | otherwise = c_kevent_unsafe k chs (fromIntegral chlen) evs (fromIntegral evlen) ts--withEvent :: Event -> (Ptr Event -> IO a) -> IO a-withEvent ev f = alloca $ \ptr -> poke ptr ev >> f ptr--withTimeSpec :: TimeSpec -> (Ptr TimeSpec -> IO a) -> IO a-withTimeSpec ts f-  | tv_sec ts < 0 = f nullPtr-  | otherwise     = alloca $ \ptr -> poke ptr ts >> f ptr--fromTimeout :: Timeout -> TimeSpec-fromTimeout Forever     = TimeSpec (-1) (-1)-fromTimeout (Timeout s) = TimeSpec (toEnum sec) (toEnum nanosec)-  where-    sec :: Int-    sec     = floor s--    nanosec :: Int-    nanosec = ceiling $ (s - fromIntegral sec) * 1000000000--toEvent :: Filter -> E.Event-toEvent (Filter f)-  | f == (#const EVFILT_READ) = E.evtRead-  | f == (#const EVFILT_WRITE) = E.evtWrite-  | otherwise = error $ "toEvent: unknown filter " ++ show f--foreign import ccall unsafe "kqueue"-    c_kqueue :: IO CInt--#if defined(HAVE_KEVENT)-foreign import capi safe "sys/event.h kevent"-    c_kevent :: KQueueFd -> Ptr Event -> CInt -> Ptr Event -> CInt-             -> Ptr TimeSpec -> IO CInt--foreign import ccall unsafe "kevent"-    c_kevent_unsafe :: KQueueFd -> Ptr Event -> CInt -> Ptr Event -> CInt-                    -> Ptr TimeSpec -> IO CInt-#else-#error no kevent system call available!?-#endif--#endif /* defined(HAVE_KQUEUE) */
− GHC/Event/Manager.hs
@@ -1,515 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE BangPatterns-           , CPP-           , ExistentialQuantification-           , NoImplicitPrelude-           , RecordWildCards-           , TypeSynonymInstances-           , FlexibleInstances-  #-}---- |--- The event manager supports event notification on fds. Each fd may--- have multiple callbacks registered, each listening for a different--- set of events. Registrations may be automatically deactivated after--- the occurrence of an event ("one-shot mode") or active until--- explicitly unregistered.------ If an fd has only one-shot registrations then we use one-shot--- polling if available. Otherwise we use multi-shot polling.--module GHC.Event.Manager-    ( -- * Types-      EventManager--      -- * Creation-    , new-    , newWith-    , newDefaultBackend--      -- * Running-    , finished-    , loop-    , step-    , shutdown-    , release-    , cleanup-    , wakeManager--      -- * State-    , callbackTableVar-    , emControl--      -- * Registering interest in I/O events-    , Lifetime (..)-    , Event-    , evtRead-    , evtWrite-    , IOCallback-    , FdKey(keyFd)-    , FdData-    , registerFd-    , unregisterFd_-    , unregisterFd-    , closeFd-    , closeFd_-    ) where--#include "EventConfig.h"----------------------------------------------------------------------------- Imports--import Control.Concurrent.MVar (MVar, newMVar, putMVar,-                                tryPutMVar, takeMVar, withMVar)-import Control.Exception (onException)-import Data.Bits ((.&.))-import Data.Foldable (forM_)-import Data.Functor (void)-import Data.IORef (IORef, atomicModifyIORef', mkWeakIORef, newIORef, readIORef,-                   writeIORef)-import Data.Maybe (maybe)-import Data.OldList (partition)-import GHC.Arr (Array, (!), listArray)-import GHC.Base-import GHC.Conc.Sync (yield)-import GHC.List (filter, replicate)-import GHC.Num (Num(..))-import GHC.Real (fromIntegral)-import GHC.Show (Show(..))-import GHC.Event.Control-import GHC.Event.IntTable (IntTable)-import GHC.Event.Internal (Backend, Event, evtClose, evtRead, evtWrite,-                           Lifetime(..), EventLifetime, Timeout(..))-import GHC.Event.Unique (Unique, UniqueSource, newSource, newUnique)-import System.Posix.Types (Fd)--import qualified GHC.Event.IntTable as IT-import qualified GHC.Event.Internal as I--#if defined(HAVE_KQUEUE)-import qualified GHC.Event.KQueue as KQueue-#elif defined(HAVE_EPOLL)-import qualified GHC.Event.EPoll  as EPoll-#elif defined(HAVE_POLL)-import qualified GHC.Event.Poll   as Poll-#else-# error not implemented for this operating system-#endif----------------------------------------------------------------------------- Types--data FdData = FdData {-      fdKey       :: {-# UNPACK #-} !FdKey-    , fdEvents    :: {-# UNPACK #-} !EventLifetime-    , _fdCallback :: !IOCallback-    }---- | A file descriptor registration cookie.-data FdKey = FdKey {-      keyFd     :: {-# UNPACK #-} !Fd-    , keyUnique :: {-# UNPACK #-} !Unique-    } deriving (Eq, Show)---- | Callback invoked on I/O events.-type IOCallback = FdKey -> Event -> IO ()--data State = Created-           | Running-           | Dying-           | Releasing-           | Finished-             deriving (Eq, Show)---- | The event manager state.-data EventManager = EventManager-    { emBackend      :: !Backend-    , emFds          :: {-# UNPACK #-} !(Array Int (MVar (IntTable [FdData])))-    , emState        :: {-# UNPACK #-} !(IORef State)-    , emUniqueSource :: {-# UNPACK #-} !UniqueSource-    , emControl      :: {-# UNPACK #-} !Control-    , emLock         :: {-# UNPACK #-} !(MVar ())-    }---- must be power of 2-callbackArraySize :: Int-callbackArraySize = 32--hashFd :: Fd -> Int-hashFd fd = fromIntegral fd .&. (callbackArraySize - 1)-{-# INLINE hashFd #-}--callbackTableVar :: EventManager -> Fd -> MVar (IntTable [FdData])-callbackTableVar mgr fd = emFds mgr ! hashFd fd-{-# INLINE callbackTableVar #-}--haveOneShot :: Bool-{-# INLINE haveOneShot #-}-#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)-haveOneShot = False-#elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE)-haveOneShot = True-#else-haveOneShot = False-#endif---------------------------------------------------------------------------- Creation--handleControlEvent :: EventManager -> Fd -> Event -> IO ()-handleControlEvent mgr fd _evt = do-  msg <- readControlMessage (emControl mgr) fd-  case msg of-    CMsgWakeup      -> return ()-    CMsgDie         -> writeIORef (emState mgr) Finished-    _               -> return ()--newDefaultBackend :: IO Backend-#if defined(HAVE_KQUEUE)-newDefaultBackend = KQueue.new-#elif defined(HAVE_EPOLL)-newDefaultBackend = EPoll.new-#elif defined(HAVE_POLL)-newDefaultBackend = Poll.new-#else-newDefaultBackend = error "no back end for this platform"-#endif---- | Create a new event manager.-new :: IO EventManager-new = newWith =<< newDefaultBackend---- | Create a new 'EventManager' with the given polling backend.-newWith :: Backend -> IO EventManager-newWith be = do-  iofds <- fmap (listArray (0, callbackArraySize-1)) $-           replicateM callbackArraySize (newMVar =<< IT.new 8)-  ctrl <- newControl False-  state <- newIORef Created-  us <- newSource-  _ <- mkWeakIORef state $ do-               st <- atomicModifyIORef' state $ \s -> (Finished, s)-               when (st /= Finished) $ do-                 I.delete be-                 closeControl ctrl-  lockVar <- newMVar ()-  let mgr = EventManager { emBackend = be-                         , emFds = iofds-                         , emState = state-                         , emUniqueSource = us-                         , emControl = ctrl-                         , emLock = lockVar-                         }-  registerControlFd mgr (controlReadFd ctrl) evtRead-  registerControlFd mgr (wakeupReadFd ctrl) evtRead-  return mgr-  where-    replicateM n x = sequence (replicate n x)--failOnInvalidFile :: String -> Fd -> IO Bool -> IO ()-failOnInvalidFile loc fd m = do-  ok <- m-  when (not ok) $-    let msg = "Failed while attempting to modify registration of file " ++-              show fd ++ " at location " ++ loc-    in error msg--registerControlFd :: EventManager -> Fd -> Event -> IO ()-registerControlFd mgr fd evs =-  failOnInvalidFile "registerControlFd" fd $-  I.modifyFd (emBackend mgr) fd mempty evs---- | Asynchronously shuts down the event manager, if running.-shutdown :: EventManager -> IO ()-shutdown mgr = do-  state <- atomicModifyIORef' (emState mgr) $ \s -> (Dying, s)-  when (state == Running) $ sendDie (emControl mgr)---- | Asynchronously tell the thread executing the event--- manager loop to exit.-release :: EventManager -> IO ()-release EventManager{..} = do-  state <- atomicModifyIORef' emState $ \s -> (Releasing, s)-  when (state == Running) $ sendWakeup emControl--finished :: EventManager -> IO Bool-finished mgr = (== Finished) `liftM` readIORef (emState mgr)--cleanup :: EventManager -> IO ()-cleanup EventManager{..} = do-  writeIORef emState Finished-  void $ tryPutMVar emLock ()-  I.delete emBackend-  closeControl emControl----------------------------------------------------------------------------- Event loop---- | Start handling events.  This function loops until told to stop,--- using 'shutdown'.------ /Note/: This loop can only be run once per 'EventManager', as it--- closes all of its control resources when it finishes.-loop :: EventManager -> IO ()-loop mgr@EventManager{..} = do-  void $ takeMVar emLock-  state <- atomicModifyIORef' emState $ \s -> case s of-    Created -> (Running, s)-    Releasing -> (Running, s)-    _       -> (s, s)-  case state of-    Created   -> go `onException` cleanup mgr-    Releasing -> go `onException` cleanup mgr-    Dying     -> cleanup mgr-    -- While a poll loop is never forked when the event manager is in the-    -- 'Finished' state, its state could read 'Finished' once the new thread-    -- actually runs.  This is not an error, just an unfortunate race condition-    -- in Thread.restartPollLoop.  See #8235-    Finished  -> return ()-    _         -> do cleanup mgr-                    error $ "GHC.Event.Manager.loop: state is already " ++-                            show state- where-  go = do state <- step mgr-          case state of-            Running   -> yield >> go-            Releasing -> putMVar emLock ()-            _         -> cleanup mgr---- | To make a step, we first do a non-blocking poll, in case--- there are already events ready to handle. This improves performance--- because we can make an unsafe foreign C call, thereby avoiding--- forcing the current Task to release the Capability and forcing a context switch.--- If the poll fails to find events, we yield, putting the poll loop thread at--- end of the Haskell run queue. When it comes back around, we do one more--- non-blocking poll, in case we get lucky and have ready events.--- If that also returns no events, then we do a blocking poll.-step :: EventManager -> IO State-step mgr@EventManager{..} = do-  waitForIO-  state <- readIORef emState-  state `seq` return state-  where-    waitForIO = do-      n1 <- I.poll emBackend Nothing (onFdEvent mgr)-      when (n1 <= 0) $ do-        yield-        n2 <- I.poll emBackend Nothing (onFdEvent mgr)-        when (n2 <= 0) $ do-          _ <- I.poll emBackend (Just Forever) (onFdEvent mgr)-          return ()----------------------------------------------------------------------------- Registering interest in I/O events---- | Register interest in the given events, without waking the event--- manager thread.  The 'Bool' return value indicates whether the--- event manager ought to be woken.-registerFd_ :: EventManager -> IOCallback -> Fd -> Event -> Lifetime-            -> IO (FdKey, Bool)-registerFd_ mgr@(EventManager{..}) cb fd evs lt = do-  u <- newUnique emUniqueSource-  let fd'  = fromIntegral fd-      reg  = FdKey fd u-      el = I.eventLifetime evs lt-      !fdd = FdData reg el cb-  (modify,ok) <- withMVar (callbackTableVar mgr fd) $ \tbl -> do-    oldFdd <- IT.insertWith (++) fd' [fdd] tbl-    let prevEvs :: EventLifetime-        prevEvs = maybe mempty eventsOf oldFdd--        el' :: EventLifetime-        el' = prevEvs `mappend` el-    case I.elLifetime el' of-      -- All registrations want one-shot semantics and this is supported-      OneShot | haveOneShot -> do-        ok <- I.modifyFdOnce emBackend fd (I.elEvent el')-        if ok-          then return (False, True)-          else IT.reset fd' oldFdd tbl >> return (False, False)--      -- We don't want or don't support one-shot semantics-      _ -> do-        let modify = prevEvs /= el'-        ok <- if modify-              then let newEvs = I.elEvent el'-                       oldEvs = I.elEvent prevEvs-                   in I.modifyFd emBackend fd oldEvs newEvs-              else return True-        if ok-          then return (modify, True)-          else IT.reset fd' oldFdd tbl >> return (False, False)-  -- this simulates behavior of old IO manager:-  -- i.e. just call the callback if the registration fails.-  when (not ok) (cb reg evs)-  return (reg,modify)-{-# INLINE registerFd_ #-}---- | @registerFd mgr cb fd evs lt@ registers interest in the events @evs@--- on the file descriptor @fd@ for lifetime @lt@. @cb@ is called for--- each event that occurs.  Returns a cookie that can be handed to--- 'unregisterFd'.-registerFd :: EventManager -> IOCallback -> Fd -> Event -> Lifetime -> IO FdKey-registerFd mgr cb fd evs lt = do-  (r, wake) <- registerFd_ mgr cb fd evs lt-  when wake $ wakeManager mgr-  return r-{-# INLINE registerFd #-}--{--    Building GHC with parallel IO manager on Mac freezes when-    compiling the dph libraries in the phase 2. As workaround, we-    don't use oneshot and we wake up an IO manager on Mac every time-    when we register an event.--    For more information, please read:-        http://ghc.haskell.org/trac/ghc/ticket/7651--}--- | Wake up the event manager.-wakeManager :: EventManager -> IO ()-#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)-wakeManager mgr = sendWakeup (emControl mgr)-#elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE)-wakeManager _ = return ()-#else-wakeManager mgr = sendWakeup (emControl mgr)-#endif--eventsOf :: [FdData] -> EventLifetime-eventsOf [fdd] = fdEvents fdd-eventsOf fdds  = mconcat $ map fdEvents fdds---- | Drop a previous file descriptor registration, without waking the--- event manager thread.  The return value indicates whether the event--- manager ought to be woken.-unregisterFd_ :: EventManager -> FdKey -> IO Bool-unregisterFd_ mgr@(EventManager{..}) (FdKey fd u) =-  withMVar (callbackTableVar mgr fd) $ \tbl -> do-    let dropReg = nullToNothing . filter ((/= u) . keyUnique . fdKey)-        fd' = fromIntegral fd-        pairEvents :: [FdData] -> IO (EventLifetime, EventLifetime)-        pairEvents prev = do-          r <- maybe mempty eventsOf `fmap` IT.lookup fd' tbl-          return (eventsOf prev, r)-    (oldEls, newEls) <- IT.updateWith dropReg fd' tbl >>=-                        maybe (return (mempty, mempty)) pairEvents-    let modify = oldEls /= newEls-    when modify $ failOnInvalidFile "unregisterFd_" fd $-      case I.elLifetime newEls of-        OneShot | I.elEvent newEls /= mempty, haveOneShot ->-          I.modifyFdOnce emBackend fd (I.elEvent newEls)-        _ ->-          I.modifyFd emBackend fd (I.elEvent oldEls) (I.elEvent newEls)-    return modify---- | Drop a previous file descriptor registration.-unregisterFd :: EventManager -> FdKey -> IO ()-unregisterFd mgr reg = do-  wake <- unregisterFd_ mgr reg-  when wake $ wakeManager mgr---- | Close a file descriptor in a race-safe way.-closeFd :: EventManager -> (Fd -> IO ()) -> Fd -> IO ()-closeFd mgr close fd = do-  fds <- withMVar (callbackTableVar mgr fd) $ \tbl -> do-    prev <- IT.delete (fromIntegral fd) tbl-    case prev of-      Nothing  -> close fd >> return []-      Just fds -> do-        let oldEls = eventsOf fds-        when (I.elEvent oldEls /= mempty) $ do-          _ <- I.modifyFd (emBackend mgr) fd (I.elEvent oldEls) mempty-          wakeManager mgr-        close fd-        return fds-  forM_ fds $ \(FdData reg el cb) -> cb reg (I.elEvent el `mappend` evtClose)---- | Close a file descriptor in a race-safe way.--- It assumes the caller will update the callback tables and that the caller--- holds the callback table lock for the fd. It must hold this lock because--- this command executes a backend command on the fd.-closeFd_ :: EventManager-            -> IntTable [FdData]-            -> Fd-            -> IO (IO ())-closeFd_ mgr tbl fd = do-  prev <- IT.delete (fromIntegral fd) tbl-  case prev of-    Nothing  -> return (return ())-    Just fds -> do-      let oldEls = eventsOf fds-      when (oldEls /= mempty) $ do-        _ <- I.modifyFd (emBackend mgr) fd (I.elEvent oldEls) mempty-        wakeManager mgr-      return $-        forM_ fds $ \(FdData reg el cb) ->-          cb reg (I.elEvent el `mappend` evtClose)----------------------------------------------------------------------------- Utilities---- | Call the callbacks corresponding to the given file descriptor.-onFdEvent :: EventManager -> Fd -> Event -> IO ()-onFdEvent mgr fd evs-  | fd == controlReadFd (emControl mgr) || fd == wakeupReadFd (emControl mgr) =-    handleControlEvent mgr fd evs--  | otherwise = do-    fdds <- withMVar (callbackTableVar mgr fd) $ \tbl ->-        IT.delete (fromIntegral fd) tbl >>= maybe (return []) (selectCallbacks tbl)-    forM_ fdds $ \(FdData reg _ cb) -> cb reg evs-  where-    -- | Here we look through the list of registrations for the fd of interest-    -- and sort out which match the events that were triggered. We,-    ---    --   1. re-arm the fd as appropriate-    --   2. reinsert registrations that weren't triggered and multishot-    --      registrations-    --   3. return a list containing the callbacks that should be invoked.-    selectCallbacks :: IntTable [FdData] -> [FdData] -> IO [FdData]-    selectCallbacks tbl fdds = do-        let -- figure out which registrations have been triggered-            matches :: FdData -> Bool-            matches fd' = evs `I.eventIs` I.elEvent (fdEvents fd')-            (triggered, notTriggered) = partition matches fdds--            -- sort out which registrations we need to retain-            isMultishot :: FdData -> Bool-            isMultishot fd' = I.elLifetime (fdEvents fd') == MultiShot-            saved = notTriggered ++ filter isMultishot triggered--            savedEls = eventsOf saved-            allEls = eventsOf fdds--        -- Reinsert multishot registrations.-        -- We deleted the table entry for this fd above so we there isn't a preexisting entry-        _ <- IT.insertWith (\_ _ -> saved) (fromIntegral fd) saved tbl--        case I.elLifetime allEls of-          -- we previously armed the fd for multiple shots, no need to rearm-          MultiShot | allEls == savedEls ->-            return ()--          -- either we previously registered for one shot or the-          -- events of interest have changed, we must re-arm-          _ ->-            case I.elLifetime savedEls of-              OneShot | haveOneShot ->-                -- if there are no saved events and we registered with one-shot-                -- semantics then there is no need to re-arm-                unless (OneShot == I.elLifetime allEls-                        && mempty == I.elEvent savedEls) $ do-                  void $ I.modifyFdOnce (emBackend mgr) fd (I.elEvent savedEls)-              _ ->-                -- we need to re-arm with multi-shot semantics-                void $ I.modifyFd (emBackend mgr) fd-                                  (I.elEvent allEls) (I.elEvent savedEls)--        return triggered--nullToNothing :: [a] -> Maybe [a]-nullToNothing []       = Nothing-nullToNothing xs@(_:_) = Just xs--unless :: Monad m => Bool -> m () -> m ()-unless p = when (not p)
− GHC/Event/PSQ.hs
@@ -1,484 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE BangPatterns, NoImplicitPrelude #-}---- Copyright (c) 2008, Ralf Hinze--- All rights reserved.------ Redistribution and use in source and binary forms, with or without--- modification, are permitted provided that the following conditions--- are met:------     * Redistributions of source code must retain the above---       copyright notice, this list of conditions and the following---       disclaimer.------     * Redistributions in binary form must reproduce the above---       copyright notice, this list of conditions and the following---       disclaimer in the documentation and/or other materials---       provided with the distribution.------     * The names of the contributors may not be used to endorse or---       promote products derived from this software without specific---       prior written permission.------ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS--- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT--- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS--- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE--- COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,--- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES--- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR--- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)--- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,--- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)--- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED--- OF THE POSSIBILITY OF SUCH DAMAGE.---- | A /priority search queue/ (henceforth /queue/) efficiently--- supports the operations of both a search tree and a priority queue.--- An 'Elem'ent is a product of a key, a priority, and a--- value. Elements can be inserted, deleted, modified and queried in--- logarithmic time, and the element with the least priority can be--- retrieved in constant time.  A queue can be built from a list of--- elements, sorted by keys, in linear time.------ This implementation is due to Ralf Hinze with some modifications by--- Scott Dillard and Johan Tibell.------ * Hinze, R., /A Simple Implementation Technique for Priority Search--- Queues/, ICFP 2001, pp. 110-121------ <http://citeseer.ist.psu.edu/hinze01simple.html>-module GHC.Event.PSQ-    (-    -- * Binding Type-    Elem(..)-    , Key-    , Prio--    -- * Priority Search Queue Type-    , PSQ--    -- * Query-    , size-    , null-    , lookup--    -- * Construction-    , empty-    , singleton--    -- * Insertion-    , insert--    -- * Delete/Update-    , delete-    , adjust--    -- * Conversion-    , toList-    , toAscList-    , toDescList-    , fromList--    -- * Min-    , findMin-    , deleteMin-    , minView-    , atMost-    ) where--import GHC.Base hiding (empty)-import GHC.Num (Num(..))-import GHC.Show (Show(showsPrec))-import GHC.Event.Unique (Unique)---- | @E k p@ binds the key @k@ with the priority @p@.-data Elem a = E-    { key   :: {-# UNPACK #-} !Key-    , prio  :: {-# UNPACK #-} !Prio-    , value :: a-    } deriving (Eq, Show)----------------------------------------------------------------------------- | A mapping from keys @k@ to priorites @p@.--type Prio = Double-type Key = Unique--data PSQ a = Void-           | Winner {-# UNPACK #-} !(Elem a)-                    !(LTree a)-                    {-# UNPACK #-} !Key  -- max key-           deriving (Eq, Show)---- | /O(1)/ The number of elements in a queue.-size :: PSQ a -> Int-size Void            = 0-size (Winner _ lt _) = 1 + size' lt---- | /O(1)/ True if the queue is empty.-null :: PSQ a -> Bool-null Void           = True-null (Winner _ _ _) = False---- | /O(log n)/ The priority and value of a given key, or Nothing if--- the key is not bound.-lookup :: Key -> PSQ a -> Maybe (Prio, a)-lookup k q = case tourView q of-    Null -> Nothing-    Single (E k' p v)-        | k == k'   -> Just (p, v)-        | otherwise -> Nothing-    tl `Play` tr-        | k <= maxKey tl -> lookup k tl-        | otherwise      -> lookup k tr----------------------------------------------------------------------------- Construction--empty :: PSQ a-empty = Void---- | /O(1)/ Build a queue with one element.-singleton :: Key -> Prio -> a -> PSQ a-singleton k p v = Winner (E k p v) Start k----------------------------------------------------------------------------- Insertion---- | /O(log n)/ Insert a new key, priority and value in the queue.  If--- the key is already present in the queue, the associated priority--- and value are replaced with the supplied priority and value.-insert :: Key -> Prio -> a -> PSQ a -> PSQ a-insert k p v q = case q of-    Void -> singleton k p v-    Winner (E k' p' v') Start _ -> case compare k k' of-        LT -> singleton k  p  v  `play` singleton k' p' v'-        EQ -> singleton k  p  v-        GT -> singleton k' p' v' `play` singleton k  p  v-    Winner e (RLoser _ e' tl m tr) m'-        | k <= m    -> insert k p v (Winner e tl m) `play` (Winner e' tr m')-        | otherwise -> (Winner e tl m) `play` insert k p v (Winner e' tr m')-    Winner e (LLoser _ e' tl m tr) m'-        | k <= m    -> insert k p v (Winner e' tl m) `play` (Winner e tr m')-        | otherwise -> (Winner e' tl m) `play` insert k p v (Winner e tr m')----------------------------------------------------------------------------- Delete/Update---- | /O(log n)/ Delete a key and its priority and value from the--- queue.  When the key is not a member of the queue, the original--- queue is returned.-delete :: Key -> PSQ a -> PSQ a-delete k q = case q of-    Void -> empty-    Winner (E k' p v) Start _-        | k == k'   -> empty-        | otherwise -> singleton k' p v-    Winner e (RLoser _ e' tl m tr) m'-        | k <= m    -> delete k (Winner e tl m) `play` (Winner e' tr m')-        | otherwise -> (Winner e tl m) `play` delete k (Winner e' tr m')-    Winner e (LLoser _ e' tl m tr) m'-        | k <= m    -> delete k (Winner e' tl m) `play` (Winner e tr m')-        | otherwise -> (Winner e' tl m) `play` delete k (Winner e tr m')---- | /O(log n)/ Update a priority at a specific key with the result--- of the provided function.  When the key is not a member of the--- queue, the original queue is returned.-adjust :: (Prio -> Prio) -> Key -> PSQ a -> PSQ a-adjust f k q0 =  go q0-  where-    go q = case q of-        Void -> empty-        Winner (E k' p v) Start _-            | k == k'   -> singleton k' (f p) v-            | otherwise -> singleton k' p v-        Winner e (RLoser _ e' tl m tr) m'-            | k <= m    -> go (Winner e tl m) `unsafePlay` (Winner e' tr m')-            | otherwise -> (Winner e tl m) `unsafePlay` go (Winner e' tr m')-        Winner e (LLoser _ e' tl m tr) m'-            | k <= m    -> go (Winner e' tl m) `unsafePlay` (Winner e tr m')-            | otherwise -> (Winner e' tl m) `unsafePlay` go (Winner e tr m')-{-# INLINE adjust #-}----------------------------------------------------------------------------- Conversion---- | /O(n*log n)/ Build a queue from a list of key/priority/value--- tuples.  If the list contains more than one priority and value for--- the same key, the last priority and value for the key is retained.-fromList :: [Elem a] -> PSQ a-fromList = foldr (\(E k p v) q -> insert k p v q) empty---- | /O(n)/ Convert to a list of key/priority/value tuples.-toList :: PSQ a -> [Elem a]-toList = toAscList---- | /O(n)/ Convert to an ascending list.-toAscList :: PSQ a -> [Elem a]-toAscList q  = seqToList (toAscLists q)--toAscLists :: PSQ a -> Sequ (Elem a)-toAscLists q = case tourView q of-    Null         -> emptySequ-    Single e     -> singleSequ e-    tl `Play` tr -> toAscLists tl <> toAscLists tr---- | /O(n)/ Convert to a descending list.-toDescList :: PSQ a -> [ Elem a ]-toDescList q = seqToList (toDescLists q)--toDescLists :: PSQ a -> Sequ (Elem a)-toDescLists q = case tourView q of-    Null         -> emptySequ-    Single e     -> singleSequ e-    tl `Play` tr -> toDescLists tr <> toDescLists tl----------------------------------------------------------------------------- Min---- | /O(1)/ The element with the lowest priority.-findMin :: PSQ a -> Maybe (Elem a)-findMin Void           = Nothing-findMin (Winner e _ _) = Just e---- | /O(log n)/ Delete the element with the lowest priority.  Returns--- an empty queue if the queue is empty.-deleteMin :: PSQ a -> PSQ a-deleteMin Void           = Void-deleteMin (Winner _ t m) = secondBest t m---- | /O(log n)/ Retrieve the binding with the least priority, and the--- rest of the queue stripped of that binding.-minView :: PSQ a -> Maybe (Elem a, PSQ a)-minView Void           = Nothing-minView (Winner e t m) = Just (e, secondBest t m)--secondBest :: LTree a -> Key -> PSQ a-secondBest Start _                 = Void-secondBest (LLoser _ e tl m tr) m' = Winner e tl m `play` secondBest tr m'-secondBest (RLoser _ e tl m tr) m' = secondBest tl m `play` Winner e tr m'---- | /O(r*(log n - log r))/ Return a list of elements ordered by--- key whose priorities are at most @pt@.-atMost :: Prio -> PSQ a -> ([Elem a], PSQ a)-atMost pt q = let (sequ, q') = atMosts pt q-              in (seqToList sequ, q')--atMosts :: Prio -> PSQ a -> (Sequ (Elem a), PSQ a)-atMosts !pt q = case q of-    (Winner e _ _)-        | prio e > pt -> (emptySequ, q)-    Void              -> (emptySequ, Void)-    Winner e Start _  -> (singleSequ e, Void)-    Winner e (RLoser _ e' tl m tr) m' ->-        let (sequ, q')   = atMosts pt (Winner e tl m)-            (sequ', q'') = atMosts pt (Winner e' tr m')-        in (sequ <> sequ', q' `play` q'')-    Winner e (LLoser _ e' tl m tr) m' ->-        let (sequ, q')   = atMosts pt (Winner e' tl m)-            (sequ', q'') = atMosts pt (Winner e tr m')-        in (sequ <> sequ', q' `play` q'')----------------------------------------------------------------------------- Loser tree--type Size = Int--data LTree a = Start-             | LLoser {-# UNPACK #-} !Size-                      {-# UNPACK #-} !(Elem a)-                      !(LTree a)-                      {-# UNPACK #-} !Key  -- split key-                      !(LTree a)-             | RLoser {-# UNPACK #-} !Size-                      {-# UNPACK #-} !(Elem a)-                      !(LTree a)-                      {-# UNPACK #-} !Key  -- split key-                      !(LTree a)-             deriving (Eq, Show)--size' :: LTree a -> Size-size' Start              = 0-size' (LLoser s _ _ _ _) = s-size' (RLoser s _ _ _ _) = s--left, right :: LTree a -> LTree a--left Start                = moduleError "left" "empty loser tree"-left (LLoser _ _ tl _ _ ) = tl-left (RLoser _ _ tl _ _ ) = tl--right Start                = moduleError "right" "empty loser tree"-right (LLoser _ _ _  _ tr) = tr-right (RLoser _ _ _  _ tr) = tr--maxKey :: PSQ a -> Key-maxKey Void           = moduleError "maxKey" "empty queue"-maxKey (Winner _ _ m) = m--lloser, rloser :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-lloser k p v tl m tr = LLoser (1 + size' tl + size' tr) (E k p v) tl m tr-rloser k p v tl m tr = RLoser (1 + size' tl + size' tr) (E k p v) tl m tr----------------------------------------------------------------------------- Balancing---- | Balance factor-omega :: Int-omega = 4--lbalance, rbalance :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a--lbalance k p v l m r-    | size' l + size' r < 2     = lloser        k p v l m r-    | size' r > omega * size' l = lbalanceLeft  k p v l m r-    | size' l > omega * size' r = lbalanceRight k p v l m r-    | otherwise                 = lloser        k p v l m r--rbalance k p v l m r-    | size' l + size' r < 2     = rloser        k p v l m r-    | size' r > omega * size' l = rbalanceLeft  k p v l m r-    | size' l > omega * size' r = rbalanceRight k p v l m r-    | otherwise                 = rloser        k p v l m r--lbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-lbalanceLeft  k p v l m r-    | size' (left r) < size' (right r) = lsingleLeft  k p v l m r-    | otherwise                        = ldoubleLeft  k p v l m r--lbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-lbalanceRight k p v l m r-    | size' (left l) > size' (right l) = lsingleRight k p v l m r-    | otherwise                        = ldoubleRight k p v l m r--rbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-rbalanceLeft  k p v l m r-    | size' (left r) < size' (right r) = rsingleLeft  k p v l m r-    | otherwise                        = rdoubleLeft  k p v l m r--rbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-rbalanceRight k p v l m r-    | size' (left l) > size' (right l) = rsingleRight k p v l m r-    | otherwise                        = rdoubleRight k p v l m r--lsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-lsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3)-    | p1 <= p2  = lloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3-    | otherwise = lloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3-lsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =-    rloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3-lsingleLeft _ _ _ _ _ _ = moduleError "lsingleLeft" "malformed tree"--rsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-rsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =-    rloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3-rsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =-    rloser k2 p2 v2 (rloser k1 p1 v1 t1 m1 t2) m2 t3-rsingleLeft _ _ _ _ _ _ = moduleError "rsingleLeft" "malformed tree"--lsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-lsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =-    lloser k2 p2 v2 t1 m1 (lloser k1 p1 v1 t2 m2 t3)-lsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =-    lloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)-lsingleRight _ _ _ _ _ _ = moduleError "lsingleRight" "malformed tree"--rsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-rsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =-    lloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)-rsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3-    | p1 <= p2  = rloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)-    | otherwise = rloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)-rsingleRight _ _ _ _ _ _ = moduleError "rsingleRight" "malformed tree"--ldoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-ldoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =-    lsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)-ldoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =-    lsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)-ldoubleLeft _ _ _ _ _ _ = moduleError "ldoubleLeft" "malformed tree"--ldoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-ldoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =-    lsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3-ldoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =-    lsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3-ldoubleRight _ _ _ _ _ _ = moduleError "ldoubleRight" "malformed tree"--rdoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-rdoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =-    rsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)-rdoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =-    rsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)-rdoubleLeft _ _ _ _ _ _ = moduleError "rdoubleLeft" "malformed tree"--rdoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a-rdoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =-    rsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3-rdoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =-    rsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3-rdoubleRight _ _ _ _ _ _ = moduleError "rdoubleRight" "malformed tree"---- | Take two pennants and returns a new pennant that is the union of--- the two with the precondition that the keys in the first tree are--- strictly smaller than the keys in the second tree.-play :: PSQ a -> PSQ a -> PSQ a-Void `play` t' = t'-t `play` Void  = t-Winner e@(E k p v) t m `play` Winner e'@(E k' p' v') t' m'-    | p <= p'   = Winner e (rbalance k' p' v' t m t') m'-    | otherwise = Winner e' (lbalance k p v t m t') m'-{-# INLINE play #-}---- | A version of 'play' that can be used if the shape of the tree has--- not changed or if the tree is known to be balanced.-unsafePlay :: PSQ a -> PSQ a -> PSQ a-Void `unsafePlay` t' =  t'-t `unsafePlay` Void  =  t-Winner e@(E k p v) t m `unsafePlay` Winner e'@(E k' p' v') t' m'-    | p <= p'   = Winner e (rloser k' p' v' t m t') m'-    | otherwise = Winner e' (lloser k p v t m t') m'-{-# INLINE unsafePlay #-}--data TourView a = Null-                | Single {-# UNPACK #-} !(Elem a)-                | (PSQ a) `Play` (PSQ a)--tourView :: PSQ a -> TourView a-tourView Void               = Null-tourView (Winner e Start _) = Single e-tourView (Winner e (RLoser _ e' tl m tr) m') =-    Winner e tl m `Play` Winner e' tr m'-tourView (Winner e (LLoser _ e' tl m tr) m') =-    Winner e' tl m `Play` Winner e tr m'----------------------------------------------------------------------------- Utility functions--moduleError :: String -> String -> a-moduleError fun msg = error ("GHC.Event.PSQ." ++ fun ++ ':' : ' ' : msg)-{-# NOINLINE moduleError #-}----------------------------------------------------------------------------- Hughes's efficient sequence type--newtype Sequ a = Sequ ([a] -> [a])--emptySequ :: Sequ a-emptySequ = Sequ (\as -> as)--singleSequ :: a -> Sequ a-singleSequ a = Sequ (\as -> a : as)--(<>) :: Sequ a -> Sequ a -> Sequ a-Sequ x1 <> Sequ x2 = Sequ (\as -> x1 (x2 as))-infixr 5 <>--seqToList :: Sequ a -> [a]-seqToList (Sequ x) = x []--instance Show a => Show (Sequ a) where-    showsPrec d a = showsPrec d (seqToList a)-
− GHC/Event/Poll.hsc
@@ -1,211 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE GeneralizedNewtypeDeriving-           , NoImplicitPrelude-           , BangPatterns-  #-}--module GHC.Event.Poll-    (-      new-    , available-    ) where--#include "EventConfig.h"--#if !defined(HAVE_POLL_H)-import GHC.Base-import qualified GHC.Event.Internal as E--new :: IO E.Backend-new = error "Poll back end not implemented for this platform"--available :: Bool-available = False-{-# INLINE available #-}-#else-#include <poll.h>--import Control.Concurrent.MVar (MVar, newMVar, swapMVar)-import Data.Bits (Bits, FiniteBits, (.|.), (.&.))-import Data.Word-import Foreign.C.Types (CInt(..), CShort(..))-import Foreign.Ptr (Ptr)-import Foreign.Storable (Storable(..))-import GHC.Base-import GHC.Conc.Sync (withMVar)-import GHC.Enum (maxBound)-import GHC.Num (Num(..))-import GHC.Real (ceiling, fromIntegral)-import GHC.Show (Show)-import System.Posix.Types (Fd(..))--import qualified GHC.Event.Array as A-import qualified GHC.Event.Internal as E--available :: Bool-available = True-{-# INLINE available #-}--data Poll = Poll {-      pollChanges :: {-# UNPACK #-} !(MVar (A.Array PollFd))-    , pollFd      :: {-# UNPACK #-} !(A.Array PollFd)-    }--new :: IO E.Backend-new = E.backend poll modifyFd modifyFdOnce (\_ -> return ()) `liftM`-      liftM2 Poll (newMVar =<< A.empty) A.empty--modifyFd :: Poll -> Fd -> E.Event -> E.Event -> IO Bool-modifyFd p fd oevt nevt =-  withMVar (pollChanges p) $ \ary -> do-    A.snoc ary $ PollFd fd (fromEvent nevt) (fromEvent oevt)-    return True--modifyFdOnce :: Poll -> Fd -> E.Event -> IO Bool-modifyFdOnce = error "modifyFdOnce not supported in Poll backend"--reworkFd :: Poll -> PollFd -> IO ()-reworkFd p (PollFd fd npevt opevt) = do-  let ary = pollFd p-  if opevt == 0-    then A.snoc ary $ PollFd fd npevt 0-    else do-      found <- A.findIndex ((== fd) . pfdFd) ary-      case found of-        Nothing        -> error "reworkFd: event not found"-        Just (i,_)-          | npevt /= 0 -> A.unsafeWrite ary i $ PollFd fd npevt 0-          | otherwise  -> A.removeAt ary i--poll :: Poll-     -> Maybe E.Timeout-     -> (Fd -> E.Event -> IO ())-     -> IO Int-poll p mtout f = do-  let a = pollFd p-  mods <- swapMVar (pollChanges p) =<< A.empty-  A.forM_ mods (reworkFd p)-  n <- A.useAsPtr a $ \ptr len ->-    E.throwErrnoIfMinus1NoRetry "c_poll" $-    case mtout of-      Just tout ->-        c_pollLoop ptr (fromIntegral len) (fromTimeout tout)-      Nothing   ->-        c_poll_unsafe ptr (fromIntegral len) 0-  when (n /= 0) $ do-    A.loop a 0 $ \i e -> do-      let r = pfdRevents e-      if r /= 0-        then do f (pfdFd e) (toEvent r)-                let i' = i + 1-                return (i', i' == n)-        else return (i, True)-  return (fromIntegral n)-  where-    -- The poll timeout is specified as an Int, but c_poll takes a CInt. These-    -- can't be safely coerced as on many systems (e.g. x86_64) CInt has a-    -- maxBound of (2^32 - 1), even though Int may have a significantly higher-    -- bound.-    ---    -- This function deals with timeouts greater than maxBound :: CInt, by-    -- looping until c_poll returns a non-zero value (0 indicates timeout-    -- expired) OR the full timeout has passed.-    c_pollLoop :: Ptr PollFd -> (#type nfds_t) -> Int -> IO CInt-    c_pollLoop ptr len tout-        | isShortTimeout = c_poll ptr len (fromIntegral tout)-        | otherwise = do-            result <- c_poll ptr len (fromIntegral maxPollTimeout)-            if result == 0-               then c_pollLoop ptr len (fromIntegral (tout - maxPollTimeout))-               else return result-        where-          -- maxPollTimeout is smaller than 0 IFF Int is smaller than CInt.-          -- This means any possible Int input to poll can be safely directly-          -- converted to CInt.-          isShortTimeout = tout <= maxPollTimeout || maxPollTimeout < 0--    -- We need to account for 3 cases:-    --     1. Int and CInt are of equal size.-    --     2. Int is larger than CInt-    --     3. Int is smaller than CInt-    ---    -- In case 1, the value of maxPollTimeout will be the maxBound of Int.-    ---    -- In case 2, the value of maxPollTimeout will be the maxBound of CInt,-    -- which is the largest value accepted by c_poll. This will result in-    -- c_pollLoop recursing if the provided timeout is larger.-    ---    -- In case 3, "fromIntegral (maxBound :: CInt) :: Int" will result in a-    -- negative Int. This will cause isShortTimeout to be true and result in-    -- the timeout being directly converted to a CInt.-    maxPollTimeout :: Int-    maxPollTimeout = fromIntegral (maxBound :: CInt)--fromTimeout :: E.Timeout -> Int-fromTimeout E.Forever     = -1-fromTimeout (E.Timeout s) = ceiling $ 1000 * s--data PollFd = PollFd {-      pfdFd      :: {-# UNPACK #-} !Fd-    , pfdEvents  :: {-# UNPACK #-} !Event-    , pfdRevents :: {-# UNPACK #-} !Event-    } deriving (Show)--newtype Event = Event CShort-    deriving (Eq, Show, Num, Storable, Bits, FiniteBits)---- We have to duplicate the whole enum like this in order for the--- hsc2hs cross-compilation mode to work-#ifdef POLLRDHUP-#{enum Event, Event- , pollIn    = POLLIN- , pollOut   = POLLOUT- , pollRdHup = POLLRDHUP- , pollErr   = POLLERR- , pollHup   = POLLHUP- }-#else-#{enum Event, Event- , pollIn    = POLLIN- , pollOut   = POLLOUT- , pollErr   = POLLERR- , pollHup   = POLLHUP- }-#endif--fromEvent :: E.Event -> Event-fromEvent e = remap E.evtRead  pollIn .|.-              remap E.evtWrite pollOut-  where remap evt to-            | e `E.eventIs` evt = to-            | otherwise         = 0--toEvent :: Event -> E.Event-toEvent e = remap (pollIn .|. pollErr .|. pollHup)  E.evtRead `mappend`-            remap (pollOut .|. pollErr .|. pollHup) E.evtWrite-  where remap evt to-            | e .&. evt /= 0 = to-            | otherwise      = mempty--instance Storable PollFd where-    sizeOf _    = #size struct pollfd-    alignment _ = alignment (undefined :: CInt)--    peek ptr = do-      fd <- #{peek struct pollfd, fd} ptr-      events <- #{peek struct pollfd, events} ptr-      revents <- #{peek struct pollfd, revents} ptr-      let !pollFd' = PollFd fd events revents-      return pollFd'--    poke ptr p = do-      #{poke struct pollfd, fd} ptr (pfdFd p)-      #{poke struct pollfd, events} ptr (pfdEvents p)-      #{poke struct pollfd, revents} ptr (pfdRevents p)--foreign import ccall safe "poll.h poll"-    c_poll :: Ptr PollFd -> (#type nfds_t) -> CInt -> IO CInt--foreign import ccall unsafe "poll.h poll"-    c_poll_unsafe :: Ptr PollFd -> (#type nfds_t) -> CInt -> IO CInt-#endif /* defined(HAVE_POLL_H) */
− GHC/Event/Thread.hs
@@ -1,362 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE BangPatterns, NoImplicitPrelude #-}--module GHC.Event.Thread-    ( getSystemEventManager-    , getSystemTimerManager-    , ensureIOManagerIsRunning-    , ioManagerCapabilitiesChanged-    , threadWaitRead-    , threadWaitWrite-    , threadWaitReadSTM-    , threadWaitWriteSTM-    , closeFdWith-    , threadDelay-    , registerDelay-    , blockedOnBadFD -- used by RTS-    ) where--import Control.Exception (finally, SomeException, toException)-import Data.Foldable (forM_, mapM_, sequence_)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.Tuple (snd)-import Foreign.C.Error (eBADF, errnoToIOError)-import Foreign.C.Types (CInt(..), CUInt(..))-import Foreign.Ptr (Ptr)-import GHC.Base-import GHC.List (zipWith, zipWith3)-import GHC.Conc.Sync (TVar, ThreadId, ThreadStatus(..), atomically, forkIO,-                      labelThread, modifyMVar_, withMVar, newTVar, sharedCAF,-                      getNumCapabilities, threadCapability, myThreadId, forkOn,-                      threadStatus, writeTVar, newTVarIO, readTVar, retry,throwSTM,STM)-import GHC.IO (mask_, onException)-import GHC.IO.Exception (ioError)-import GHC.IOArray (IOArray, newIOArray, readIOArray, writeIOArray,-                    boundsIOArray)-import GHC.MVar (MVar, newEmptyMVar, newMVar, putMVar, takeMVar)-import GHC.Event.Control (controlWriteFd)-import GHC.Event.Internal (eventIs, evtClose)-import GHC.Event.Manager (Event, EventManager, evtRead, evtWrite, loop,-                             new, registerFd, unregisterFd_)-import qualified GHC.Event.Manager as M-import qualified GHC.Event.TimerManager as TM-import GHC.Num ((-), (+))-import GHC.Real (fromIntegral)-import GHC.Show (showSignedInt)-import System.IO.Unsafe (unsafePerformIO)-import System.Posix.Types (Fd)---- | Suspends the current thread for a given number of microseconds--- (GHC only).------ There is no guarantee that the thread will be rescheduled promptly--- when the delay has expired, but the thread will never continue to--- run /earlier/ than specified.-threadDelay :: Int -> IO ()-threadDelay usecs = mask_ $ do-  mgr <- getSystemTimerManager-  m <- newEmptyMVar-  reg <- TM.registerTimeout mgr usecs (putMVar m ())-  takeMVar m `onException` TM.unregisterTimeout mgr reg---- | Set the value of returned TVar to True after a given number of--- microseconds. The caveats associated with threadDelay also apply.----registerDelay :: Int -> IO (TVar Bool)-registerDelay usecs = do-  t <- atomically $ newTVar False-  mgr <- getSystemTimerManager-  _ <- TM.registerTimeout mgr usecs . atomically $ writeTVar t True-  return t---- | Block the current thread until data is available to read from the--- given file descriptor.------ This will throw an 'IOError' if the file descriptor was closed--- while this thread was blocked.  To safely close a file descriptor--- that has been used with 'threadWaitRead', use 'closeFdWith'.-threadWaitRead :: Fd -> IO ()-threadWaitRead = threadWait evtRead-{-# INLINE threadWaitRead #-}---- | Block the current thread until the given file descriptor can--- accept data to write.------ This will throw an 'IOError' if the file descriptor was closed--- while this thread was blocked.  To safely close a file descriptor--- that has been used with 'threadWaitWrite', use 'closeFdWith'.-threadWaitWrite :: Fd -> IO ()-threadWaitWrite = threadWait evtWrite-{-# INLINE threadWaitWrite #-}---- | Close a file descriptor in a concurrency-safe way.------ Any threads that are blocked on the file descriptor via--- 'threadWaitRead' or 'threadWaitWrite' will be unblocked by having--- IO exceptions thrown.-closeFdWith :: (Fd -> IO ())        -- ^ Action that performs the close.-            -> Fd                   -- ^ File descriptor to close.-            -> IO ()-closeFdWith close fd = do-  eventManagerArray <- readIORef eventManager-  let (low, high) = boundsIOArray eventManagerArray-  mgrs <- flip mapM [low..high] $ \i -> do-    Just (_,!mgr) <- readIOArray eventManagerArray i-    return mgr-  mask_ $ do-    tables <- flip mapM mgrs $ \mgr -> takeMVar $ M.callbackTableVar mgr fd-    cbApps <- zipWithM (\mgr table -> M.closeFd_ mgr table fd) mgrs tables-    close fd `finally` sequence_ (zipWith3 finish mgrs tables cbApps)-  where-    finish mgr table cbApp = putMVar (M.callbackTableVar mgr fd) table >> cbApp-    zipWithM f xs ys = sequence (zipWith f xs ys)--threadWait :: Event -> Fd -> IO ()-threadWait evt fd = mask_ $ do-  m <- newEmptyMVar-  mgr <- getSystemEventManager_-  reg <- registerFd mgr (\_ e -> putMVar m e) fd evt M.OneShot-  evt' <- takeMVar m `onException` unregisterFd_ mgr reg-  if evt' `eventIs` evtClose-    then ioError $ errnoToIOError "threadWait" eBADF Nothing Nothing-    else return ()---- used at least by RTS in 'select()' IO manager backend-blockedOnBadFD :: SomeException-blockedOnBadFD = toException $ errnoToIOError "awaitEvent" eBADF Nothing Nothing--threadWaitSTM :: Event -> Fd -> IO (STM (), IO ())-threadWaitSTM evt fd = mask_ $ do-  m <- newTVarIO Nothing-  mgr <- getSystemEventManager_-  reg <- registerFd mgr (\_ e -> atomically (writeTVar m (Just e))) fd evt M.OneShot-  let waitAction =-        do mevt <- readTVar m-           case mevt of-             Nothing -> retry-             Just evt' ->-               if evt' `eventIs` evtClose-               then throwSTM $ errnoToIOError "threadWaitSTM" eBADF Nothing Nothing-               else return ()-  return (waitAction, unregisterFd_ mgr reg >> return ())---- | Allows a thread to use an STM action to wait for a file descriptor to be readable.--- The STM action will retry until the file descriptor has data ready.--- The second element of the return value pair is an IO action that can be used--- to deregister interest in the file descriptor.------ The STM action will throw an 'IOError' if the file descriptor was closed--- while the STM action is being executed.  To safely close a file descriptor--- that has been used with 'threadWaitReadSTM', use 'closeFdWith'.-threadWaitReadSTM :: Fd -> IO (STM (), IO ())-threadWaitReadSTM = threadWaitSTM evtRead-{-# INLINE threadWaitReadSTM #-}---- | Allows a thread to use an STM action to wait until a file descriptor can accept a write.--- The STM action will retry while the file until the given file descriptor can accept a write.--- The second element of the return value pair is an IO action that can be used to deregister--- interest in the file descriptor.------ The STM action will throw an 'IOError' if the file descriptor was closed--- while the STM action is being executed.  To safely close a file descriptor--- that has been used with 'threadWaitWriteSTM', use 'closeFdWith'.-threadWaitWriteSTM :: Fd -> IO (STM (), IO ())-threadWaitWriteSTM = threadWaitSTM evtWrite-{-# INLINE threadWaitWriteSTM #-}----- | Retrieve the system event manager for the capability on which the--- calling thread is running.------ This function always returns 'Just' the current thread's event manager--- when using the threaded RTS and 'Nothing' otherwise.-getSystemEventManager :: IO (Maybe EventManager)-getSystemEventManager = do-  t <- myThreadId-  (cap, _) <- threadCapability t-  eventManagerArray <- readIORef eventManager-  mmgr <- readIOArray eventManagerArray cap-  return $ fmap snd mmgr--getSystemEventManager_ :: IO EventManager-getSystemEventManager_ = do-  Just mgr <- getSystemEventManager-  return mgr-{-# INLINE getSystemEventManager_ #-}--foreign import ccall unsafe "getOrSetSystemEventThreadEventManagerStore"-    getOrSetSystemEventThreadEventManagerStore :: Ptr a -> IO (Ptr a)--eventManager :: IORef (IOArray Int (Maybe (ThreadId, EventManager)))-eventManager = unsafePerformIO $ do-    numCaps <- getNumCapabilities-    eventManagerArray <- newIOArray (0, numCaps - 1) Nothing-    em <- newIORef eventManagerArray-    sharedCAF em getOrSetSystemEventThreadEventManagerStore-{-# NOINLINE eventManager #-}--numEnabledEventManagers :: IORef Int-numEnabledEventManagers = unsafePerformIO $ do-  newIORef 0-{-# NOINLINE numEnabledEventManagers #-}--foreign import ccall unsafe "getOrSetSystemEventThreadIOManagerThreadStore"-    getOrSetSystemEventThreadIOManagerThreadStore :: Ptr a -> IO (Ptr a)---- | The ioManagerLock protects the 'eventManager' value:--- Only one thread at a time can start or shutdown event managers.-{-# NOINLINE ioManagerLock #-}-ioManagerLock :: MVar ()-ioManagerLock = unsafePerformIO $ do-   m <- newMVar ()-   sharedCAF m getOrSetSystemEventThreadIOManagerThreadStore--getSystemTimerManager :: IO TM.TimerManager-getSystemTimerManager = do-  Just mgr <- readIORef timerManager-  return mgr--foreign import ccall unsafe "getOrSetSystemTimerThreadEventManagerStore"-    getOrSetSystemTimerThreadEventManagerStore :: Ptr a -> IO (Ptr a)--timerManager :: IORef (Maybe TM.TimerManager)-timerManager = unsafePerformIO $ do-    em <- newIORef Nothing-    sharedCAF em getOrSetSystemTimerThreadEventManagerStore-{-# NOINLINE timerManager #-}--foreign import ccall unsafe "getOrSetSystemTimerThreadIOManagerThreadStore"-    getOrSetSystemTimerThreadIOManagerThreadStore :: Ptr a -> IO (Ptr a)--{-# NOINLINE timerManagerThreadVar #-}-timerManagerThreadVar :: MVar (Maybe ThreadId)-timerManagerThreadVar = unsafePerformIO $ do-   m <- newMVar Nothing-   sharedCAF m getOrSetSystemTimerThreadIOManagerThreadStore--ensureIOManagerIsRunning :: IO ()-ensureIOManagerIsRunning-  | not threaded = return ()-  | otherwise = do-      startIOManagerThreads-      startTimerManagerThread--startIOManagerThreads :: IO ()-startIOManagerThreads =-  withMVar ioManagerLock $ \_ -> do-    eventManagerArray <- readIORef eventManager-    let (_, high) = boundsIOArray eventManagerArray-    mapM_ (startIOManagerThread eventManagerArray) [0..high]-    writeIORef numEnabledEventManagers (high+1)--show_int :: Int -> String-show_int i = showSignedInt 0 i ""--restartPollLoop :: EventManager -> Int -> IO ThreadId-restartPollLoop mgr i = do-  M.release mgr-  !t <- forkOn i $ loop mgr-  labelThread t ("IOManager on cap " ++ show_int i)-  return t--startIOManagerThread :: IOArray Int (Maybe (ThreadId, EventManager))-                        -> Int-                        -> IO ()-startIOManagerThread eventManagerArray i = do-  let create = do-        !mgr <- new-        !t <- forkOn i $ do-                c_setIOManagerControlFd-                  (fromIntegral i)-                  (fromIntegral $ controlWriteFd $ M.emControl mgr)-                loop mgr-        labelThread t ("IOManager on cap " ++ show_int i)-        writeIOArray eventManagerArray i (Just (t,mgr))-  old <- readIOArray eventManagerArray i-  case old of-    Nothing     -> create-    Just (t,em) -> do-      s <- threadStatus t-      case s of-        ThreadFinished -> create-        ThreadDied     -> do-          -- Sanity check: if the thread has died, there is a chance-          -- that event manager is still alive. This could happend during-          -- the fork, for example. In this case we should clean up-          -- open pipes and everything else related to the event manager.-          -- See #4449-          c_setIOManagerControlFd (fromIntegral i) (-1)-          M.cleanup em-          create-        _other         -> return ()--startTimerManagerThread :: IO ()-startTimerManagerThread = modifyMVar_ timerManagerThreadVar $ \old -> do-  let create = do-        !mgr <- TM.new-        c_setTimerManagerControlFd-          (fromIntegral $ controlWriteFd $ TM.emControl mgr)-        writeIORef timerManager $ Just mgr-        !t <- forkIO $ TM.loop mgr-        labelThread t "TimerManager"-        return $ Just t-  case old of-    Nothing            -> create-    st@(Just t) -> do-      s <- threadStatus t-      case s of-        ThreadFinished -> create-        ThreadDied     -> do-          -- Sanity check: if the thread has died, there is a chance-          -- that event manager is still alive. This could happend during-          -- the fork, for example. In this case we should clean up-          -- open pipes and everything else related to the event manager.-          -- See #4449-          mem <- readIORef timerManager-          _ <- case mem of-                 Nothing -> return ()-                 Just em -> do c_setTimerManagerControlFd (-1)-                               TM.cleanup em-          create-        _other         -> return st--foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool--ioManagerCapabilitiesChanged :: IO ()-ioManagerCapabilitiesChanged = do-  withMVar ioManagerLock $ \_ -> do-    new_n_caps <- getNumCapabilities-    numEnabled <- readIORef numEnabledEventManagers-    writeIORef numEnabledEventManagers new_n_caps-    eventManagerArray <- readIORef eventManager-    let (_, high) = boundsIOArray eventManagerArray-    let old_n_caps = high + 1-    if new_n_caps > old_n_caps-      then do new_eventManagerArray <- newIOArray (0, new_n_caps - 1) Nothing--              -- copy the existing values into the new array:-              forM_ [0..high] $ \i -> do-                Just (tid,mgr) <- readIOArray eventManagerArray i-                if i < numEnabled-                  then writeIOArray new_eventManagerArray i (Just (tid,mgr))-                  else do tid' <- restartPollLoop mgr i-                          writeIOArray new_eventManagerArray i (Just (tid',mgr))--              -- create new IO managers for the new caps:-              forM_ [old_n_caps..new_n_caps-1] $-                startIOManagerThread new_eventManagerArray--              -- update the event manager array reference:-              writeIORef eventManager new_eventManagerArray-      else when (new_n_caps > numEnabled) $-            forM_ [numEnabled..new_n_caps-1] $ \i -> do-              Just (_,mgr) <- readIOArray eventManagerArray i-              tid <- restartPollLoop mgr i-              writeIOArray eventManagerArray i (Just (tid,mgr))---- Used to tell the RTS how it can send messages to the I/O manager.-foreign import ccall unsafe "setIOManagerControlFd"-   c_setIOManagerControlFd :: CUInt -> CInt -> IO ()--foreign import ccall unsafe "setTimerManagerControlFd"-   c_setTimerManagerControlFd :: CInt -> IO ()
− GHC/Event/TimerManager.hs
@@ -1,243 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE BangPatterns-           , CPP-           , ExistentialQuantification-           , NoImplicitPrelude-           , TypeSynonymInstances-           , FlexibleInstances-  #-}--module GHC.Event.TimerManager-    ( -- * Types-      TimerManager--      -- * Creation-    , new-    , newWith-    , newDefaultBackend-    , emControl--      -- * Running-    , finished-    , loop-    , step-    , shutdown-    , cleanup-    , wakeManager--      -- * Registering interest in timeout events-    , TimeoutCallback-    , TimeoutKey-    , registerTimeout-    , updateTimeout-    , unregisterTimeout-    ) where--#include "EventConfig.h"----------------------------------------------------------------------------- Imports--import Control.Exception (finally)-import Data.Foldable (sequence_)-import Data.IORef (IORef, atomicModifyIORef', mkWeakIORef, newIORef, readIORef,-                   writeIORef)-import GHC.Base-import GHC.Conc.Signal (runHandlers)-import GHC.Num (Num(..))-import GHC.Real ((/), fromIntegral )-import GHC.Show (Show(..))-import GHC.Event.Clock (getMonotonicTime)-import GHC.Event.Control-import GHC.Event.Internal (Backend, Event, evtRead, Timeout(..))-import GHC.Event.Unique (Unique, UniqueSource, newSource, newUnique)-import System.Posix.Types (Fd)--import qualified GHC.Event.Internal as I-import qualified GHC.Event.PSQ as Q--#if defined(HAVE_POLL)-import qualified GHC.Event.Poll   as Poll-#else-# error not implemented for this operating system-#endif----------------------------------------------------------------------------- Types---- | A timeout registration cookie.-newtype TimeoutKey   = TK Unique-    deriving (Eq)---- | Callback invoked on timeout events.-type TimeoutCallback = IO ()--data State = Created-           | Running-           | Dying-           | Finished-             deriving (Eq, Show)---- | A priority search queue, with timeouts as priorities.-type TimeoutQueue = Q.PSQ TimeoutCallback---- | An edit to apply to a 'TimeoutQueue'.-type TimeoutEdit = TimeoutQueue -> TimeoutQueue---- | The event manager state.-data TimerManager = TimerManager-    { emBackend      :: !Backend-    , emTimeouts     :: {-# UNPACK #-} !(IORef TimeoutQueue)-    , emState        :: {-# UNPACK #-} !(IORef State)-    , emUniqueSource :: {-# UNPACK #-} !UniqueSource-    , emControl      :: {-# UNPACK #-} !Control-    }----------------------------------------------------------------------------- Creation--handleControlEvent :: TimerManager -> Fd -> Event -> IO ()-handleControlEvent mgr fd _evt = do-  msg <- readControlMessage (emControl mgr) fd-  case msg of-    CMsgWakeup      -> return ()-    CMsgDie         -> writeIORef (emState mgr) Finished-    CMsgSignal fp s -> runHandlers fp s--newDefaultBackend :: IO Backend-#if defined(HAVE_POLL)-newDefaultBackend = Poll.new-#else-newDefaultBackend = error "no back end for this platform"-#endif---- | Create a new event manager.-new :: IO TimerManager-new = newWith =<< newDefaultBackend--newWith :: Backend -> IO TimerManager-newWith be = do-  timeouts <- newIORef Q.empty-  ctrl <- newControl True-  state <- newIORef Created-  us <- newSource-  _ <- mkWeakIORef state $ do-               st <- atomicModifyIORef' state $ \s -> (Finished, s)-               when (st /= Finished) $ do-                 I.delete be-                 closeControl ctrl-  let mgr = TimerManager { emBackend = be-                         , emTimeouts = timeouts-                         , emState = state-                         , emUniqueSource = us-                         , emControl = ctrl-                         }-  _ <- I.modifyFd be (controlReadFd ctrl) mempty evtRead-  _ <- I.modifyFd be (wakeupReadFd ctrl) mempty evtRead-  return mgr---- | Asynchronously shuts down the event manager, if running.-shutdown :: TimerManager -> IO ()-shutdown mgr = do-  state <- atomicModifyIORef' (emState mgr) $ \s -> (Dying, s)-  when (state == Running) $ sendDie (emControl mgr)--finished :: TimerManager -> IO Bool-finished mgr = (== Finished) `liftM` readIORef (emState mgr)--cleanup :: TimerManager -> IO ()-cleanup mgr = do-  writeIORef (emState mgr) Finished-  I.delete (emBackend mgr)-  closeControl (emControl mgr)----------------------------------------------------------------------------- Event loop---- | Start handling events.  This function loops until told to stop,--- using 'shutdown'.------ /Note/: This loop can only be run once per 'TimerManager', as it--- closes all of its control resources when it finishes.-loop :: TimerManager -> IO ()-loop mgr = do-  state <- atomicModifyIORef' (emState mgr) $ \s -> case s of-    Created -> (Running, s)-    _       -> (s, s)-  case state of-    Created -> go `finally` cleanup mgr-    Dying   -> cleanup mgr-    _       -> do cleanup mgr-                  error $ "GHC.Event.Manager.loop: state is already " ++-                      show state- where-  go = do running <- step mgr-          when running go--step :: TimerManager -> IO Bool-step mgr = do-  timeout <- mkTimeout-  _ <- I.poll (emBackend mgr) (Just timeout) (handleControlEvent mgr)-  state <- readIORef (emState mgr)-  state `seq` return (state == Running)- where--  -- | Call all expired timer callbacks and return the time to the-  -- next timeout.-  mkTimeout :: IO Timeout-  mkTimeout = do-      now <- getMonotonicTime-      (expired, timeout) <- atomicModifyIORef' (emTimeouts mgr) $ \tq ->-           let (expired, tq') = Q.atMost now tq-               timeout = case Q.minView tq' of-                 Nothing             -> Forever-                 Just (Q.E _ t _, _) ->-                     -- This value will always be positive since the call-                     -- to 'atMost' above removed any timeouts <= 'now'-                     let t' = t - now in t' `seq` Timeout t'-           in (tq', (expired, timeout))-      sequence_ $ map Q.value expired-      return timeout---- | Wake up the event manager.-wakeManager :: TimerManager -> IO ()-wakeManager mgr = sendWakeup (emControl mgr)----------------------------------------------------------------------------- Registering interest in timeout events---- | Register a timeout in the given number of microseconds.  The--- returned 'TimeoutKey' can be used to later unregister or update the--- timeout.  The timeout is automatically unregistered after the given--- time has passed.-registerTimeout :: TimerManager -> Int -> TimeoutCallback -> IO TimeoutKey-registerTimeout mgr us cb = do-  !key <- newUnique (emUniqueSource mgr)-  if us <= 0 then cb-    else do-      now <- getMonotonicTime-      let expTime = fromIntegral us / 1000000.0 + now--      editTimeouts mgr (Q.insert key expTime cb)-      wakeManager mgr-  return $ TK key---- | Unregister an active timeout.-unregisterTimeout :: TimerManager -> TimeoutKey -> IO ()-unregisterTimeout mgr (TK key) = do-  editTimeouts mgr (Q.delete key)-  wakeManager mgr---- | Update an active timeout to fire in the given number of--- microseconds.-updateTimeout :: TimerManager -> TimeoutKey -> Int -> IO ()-updateTimeout mgr (TK key) us = do-  now <- getMonotonicTime-  let expTime = fromIntegral us / 1000000.0 + now--  editTimeouts mgr (Q.adjust (const expTime) key)-  wakeManager mgr--editTimeouts :: TimerManager -> TimeoutEdit -> IO ()-editTimeouts mgr g = atomicModifyIORef' (emTimeouts mgr) $ \tq -> (g tq, ())-
− GHC/Event/Unique.hs
@@ -1,43 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving, NoImplicitPrelude #-}--module GHC.Event.Unique-    (-      UniqueSource-    , Unique(..)-    , newSource-    , newUnique-    ) where--import Data.Int (Int64)-import GHC.Base-import GHC.Conc.Sync (TVar, atomically, newTVarIO, readTVar, writeTVar)-import GHC.Num (Num(..))-import GHC.Show (Show(..))---- We used to use IORefs here, but Simon switched us to STM when we--- found that our use of atomicModifyIORef was subject to a severe RTS--- performance problem when used in a tight loop from multiple--- threads: http://ghc.haskell.org/trac/ghc/ticket/3838------ There seems to be no performance cost to using a TVar instead.--newtype UniqueSource = US (TVar Int64)--newtype Unique = Unique { asInt64 :: Int64 }-    deriving (Eq, Ord, Num)--instance Show Unique where-    show = show . asInt64--newSource :: IO UniqueSource-newSource = US `fmap` newTVarIO 0--newUnique :: UniqueSource -> IO Unique-newUnique (US ref) = atomically $ do-  u <- readTVar ref-  let !u' = u+1-  writeTVar ref u'-  return $ Unique u'-{-# INLINE newUnique #-}-
− GHC/Exception.hs
@@ -1,197 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude-           , ExistentialQuantification-           , MagicHash-           , DeriveDataTypeable-  #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Exception--- Copyright   :  (c) The University of Glasgow, 1998-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ Exceptions and exception-handling functions.-----------------------------------------------------------------------------------module GHC.Exception-       ( Exception(..)    -- Class-       , throw-       , SomeException(..), ErrorCall(..), ArithException(..)-       , divZeroException, overflowException, ratioZeroDenomException-       , errorCallException-       ) where--import Data.Maybe-import Data.Typeable (Typeable, cast)-   -- loop: Data.Typeable -> GHC.Err -> GHC.Exception-import GHC.Base-import GHC.Show--{- |-The @SomeException@ type is the root of the exception type hierarchy.-When an exception of type @e@ is thrown, behind the scenes it is-encapsulated in a @SomeException@.--}-data SomeException = forall e . Exception e => SomeException e-    deriving Typeable--instance Show SomeException where-    showsPrec p (SomeException e) = showsPrec p e--{- |-Any type that you wish to throw or catch as an exception must be an-instance of the @Exception@ class. The simplest case is a new exception-type directly below the root:--> data MyException = ThisException | ThatException->     deriving (Show, Typeable)->-> instance Exception MyException--The default method definitions in the @Exception@ class do what we need-in this case. You can now throw and catch @ThisException@ and-@ThatException@ as exceptions:--@-*Main> throw ThisException \`catch\` \\e -> putStrLn (\"Caught \" ++ show (e :: MyException))-Caught ThisException-@--In more complicated examples, you may wish to define a whole hierarchy-of exceptions:--> ----------------------------------------------------------------------> -- Make the root exception type for all the exceptions in a compiler->-> data SomeCompilerException = forall e . Exception e => SomeCompilerException e->     deriving Typeable->-> instance Show SomeCompilerException where->     show (SomeCompilerException e) = show e->-> instance Exception SomeCompilerException->-> compilerExceptionToException :: Exception e => e -> SomeException-> compilerExceptionToException = toException . SomeCompilerException->-> compilerExceptionFromException :: Exception e => SomeException -> Maybe e-> compilerExceptionFromException x = do->     SomeCompilerException a <- fromException x->     cast a->-> ----------------------------------------------------------------------> -- Make a subhierarchy for exceptions in the frontend of the compiler->-> data SomeFrontendException = forall e . Exception e => SomeFrontendException e->     deriving Typeable->-> instance Show SomeFrontendException where->     show (SomeFrontendException e) = show e->-> instance Exception SomeFrontendException where->     toException = compilerExceptionToException->     fromException = compilerExceptionFromException->-> frontendExceptionToException :: Exception e => e -> SomeException-> frontendExceptionToException = toException . SomeFrontendException->-> frontendExceptionFromException :: Exception e => SomeException -> Maybe e-> frontendExceptionFromException x = do->     SomeFrontendException a <- fromException x->     cast a->-> ----------------------------------------------------------------------> -- Make an exception type for a particular frontend compiler exception->-> data MismatchedParentheses = MismatchedParentheses->     deriving (Typeable, Show)->-> instance Exception MismatchedParentheses where->     toException   = frontendExceptionToException->     fromException = frontendExceptionFromException--We can now catch a @MismatchedParentheses@ exception as-@MismatchedParentheses@, @SomeFrontendException@ or-@SomeCompilerException@, but not other types, e.g. @IOException@:--@-*Main> throw MismatchedParentheses `catch` \e -> putStrLn (\"Caught \" ++ show (e :: MismatchedParentheses))-Caught MismatchedParentheses-*Main> throw MismatchedParentheses `catch` \e -> putStrLn (\"Caught \" ++ show (e :: SomeFrontendException))-Caught MismatchedParentheses-*Main> throw MismatchedParentheses `catch` \e -> putStrLn (\"Caught \" ++ show (e :: SomeCompilerException))-Caught MismatchedParentheses-*Main> throw MismatchedParentheses `catch` \e -> putStrLn (\"Caught \" ++ show (e :: IOException))-*** Exception: MismatchedParentheses-@---}-class (Typeable e, Show e) => Exception e where-    toException   :: e -> SomeException-    fromException :: SomeException -> Maybe e--    toException = SomeException-    fromException (SomeException e) = cast e--    -- | Render this exception value in a human-friendly manner.-    ---    -- Default implementation: @'show'@.-    ---    -- @since 4.8.0.0-    displayException :: e -> String-    displayException = show--instance Exception SomeException where-    toException se = se-    fromException = Just-    displayException (SomeException e) = displayException e---- | Throw an exception.  Exceptions may be thrown from purely--- functional code, but may only be caught within the 'IO' monad.-throw :: Exception e => e -> a-throw e = raise# (toException e)---- |This is thrown when the user calls 'error'. The @String@ is the--- argument given to 'error'.-newtype ErrorCall = ErrorCall String-    deriving (Eq, Ord, Typeable)--instance Exception ErrorCall--instance Show ErrorCall where-    showsPrec _ (ErrorCall err) = showString err--errorCallException :: String -> SomeException-errorCallException s = toException (ErrorCall s)---- |Arithmetic exceptions.-data ArithException-  = Overflow-  | Underflow-  | LossOfPrecision-  | DivideByZero-  | Denormal-  | RatioZeroDenominator -- ^ @since 4.6.0.0-  deriving (Eq, Ord, Typeable)--divZeroException, overflowException, ratioZeroDenomException  :: SomeException-divZeroException        = toException DivideByZero-overflowException       = toException Overflow-ratioZeroDenomException = toException RatioZeroDenominator--instance Exception ArithException--instance Show ArithException where-  showsPrec _ Overflow        = showString "arithmetic overflow"-  showsPrec _ Underflow       = showString "arithmetic underflow"-  showsPrec _ LossOfPrecision = showString "loss of precision"-  showsPrec _ DivideByZero    = showString "divide by zero"-  showsPrec _ Denormal        = showString "denormal"-  showsPrec _ RatioZeroDenominator = showString "Ratio has zero denominator"
− GHC/Exception.hs-boot
@@ -1,34 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}--{--This SOURCE-imported hs-boot module cuts a big dependency loop:--         GHC.Exception-imports  Data.Maybe-imports  GHC.Base-imports  GHC.Err-imports  {-# SOURCE #-} GHC.Exception--More dramatically--         GHC.Exception-imports  Data.Typeable-imports  Data.Typeable.Internals-imports  GHC.Arr (fingerprint representation etc)-imports  GHC.Real-imports  {-# SOURCE #-} GHC.Exception--However, GHC.Exceptions loop-breaking exports are all nice,-well-behaved, non-bottom values.  The clients use 'raise#'-to get a visibly-bottom value.--}--module GHC.Exception ( SomeException, errorCallException,-                       divZeroException, overflowException, ratioZeroDenomException-    ) where-import GHC.Types( Char )--data SomeException-divZeroException, overflowException, ratioZeroDenomException  :: SomeException-errorCallException :: [Char] -> SomeException
− GHC/Exts.hs
@@ -1,186 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE MagicHash, UnboxedTuples, AutoDeriveTypeable, TypeFamilies,-             MultiParamTypeClasses, FlexibleInstances, NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Exts--- Copyright   :  (c) The University of Glasgow 2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ GHC Extensions: this is the Approved Way to get at GHC-specific extensions.------ Note: no other base module should import this module.--------------------------------------------------------------------------------module GHC.Exts-       (-        -- * Representations of some basic types-        Int(..),Word(..),Float(..),Double(..),-        Char(..),-        Ptr(..), FunPtr(..),--        -- * The maximum tuple size-        maxTupleSize,--        -- * Primitive operations-        module GHC.Prim,-        shiftL#, shiftRL#, iShiftL#, iShiftRA#, iShiftRL#,-        uncheckedShiftL64#, uncheckedShiftRL64#,-        uncheckedIShiftL64#, uncheckedIShiftRA64#,-        isTrue#,--        -- * Fusion-        build, augment,--        -- * Overloaded string literals-        IsString(..),--        -- * Debugging-        breakpoint, breakpointCond,--        -- * Ids with special behaviour-        lazy, inline,--        -- * Safe coercions-        ---        -- | These are available from the /Trustworthy/ module "Data.Coerce" as well-        ---        -- @since 4.7.0.0-        Data.Coerce.coerce, Data.Coerce.Coercible,--        -- * Transform comprehensions-        Down(..), groupWith, sortWith, the,--        -- * Event logging-        traceEvent,--        -- * SpecConstr annotations-        SpecConstrAnnotation(..),--        -- * The call stack-        currentCallStack,--        -- * The Constraint kind-        Constraint,--        -- * Overloaded lists-        IsList(..)-       ) where--import GHC.Prim hiding (coerce, Constraint)-import GHC.Base hiding (coerce) -- implicitly comes from GHC.Prim-import GHC.Word-import GHC.Int-import GHC.Ptr-import GHC.Stack--import qualified Data.Coerce-import Data.String-import Data.OldList-import Data.Data-import Data.Ord-import Data.Version ( Version(..), makeVersion )-import qualified Debug.Trace---- XXX This should really be in Data.Tuple, where the definitions are-maxTupleSize :: Int-maxTupleSize = 62---- | 'the' ensures that all the elements of the list are identical--- and then returns that unique element-the :: Eq a => [a] -> a-the (x:xs)-  | all (x ==) xs = x-  | otherwise     = error "GHC.Exts.the: non-identical elements"-the []            = error "GHC.Exts.the: empty list"---- | The 'sortWith' function sorts a list of elements using the--- user supplied function to project something out of each element-sortWith :: Ord b => (a -> b) -> [a] -> [a]-sortWith f = sortBy (\x y -> compare (f x) (f y))---- | The 'groupWith' function uses the user supplied function which--- projects an element out of every list element in order to first sort the--- input list and then to form groups by equality on these projected elements-{-# INLINE groupWith #-}-groupWith :: Ord b => (a -> b) -> [a] -> [[a]]-groupWith f xs = build (\c n -> groupByFB c n (\x y -> f x == f y) (sortWith f xs))--groupByFB :: ([a] -> lst -> lst) -> lst -> (a -> a -> Bool) -> [a] -> lst-groupByFB c n eq xs0 = groupByFBCore xs0-  where groupByFBCore [] = n-        groupByFBCore (x:xs) = c (x:ys) (groupByFBCore zs)-            where (ys, zs) = span (eq x) xs----- -------------------------------------------------------------------------------- tracing--traceEvent :: String -> IO ()-traceEvent = Debug.Trace.traceEventIO-{-# DEPRECATED traceEvent "Use 'Debug.Trace.traceEvent' or 'Debug.Trace.traceEventIO'" #-} -- deprecated in 7.4---{- **********************************************************************-*                                                                       *-*              SpecConstr annotation                                    *-*                                                                       *-********************************************************************** -}---- Annotating a type with NoSpecConstr will make SpecConstr--- not specialise for arguments of that type.---- This data type is defined here, rather than in the SpecConstr module--- itself, so that importing it doesn't force stupidly linking the--- entire ghc package at runtime--data SpecConstrAnnotation = NoSpecConstr | ForceSpecConstr-                deriving( Data, Typeable, Eq )---{- **********************************************************************-*                                                                       *-*              The IsList class                                         *-*                                                                       *-********************************************************************** -}---- | The 'IsList' class and its methods are intended to be used in---   conjunction with the OverloadedLists extension.------ @since 4.7.0.0-class IsList l where-  -- | The 'Item' type function returns the type of items of the structure-  --   @l@.-  type Item l--  -- | The 'fromList' function constructs the structure @l@ from the given-  --   list of @Item l@-  fromList  :: [Item l] -> l--  -- | The 'fromListN' function takes the input list's length as a hint. Its-  --   behaviour should be equivalent to 'fromList'. The hint can be used to-  --   construct the structure @l@ more efficiently compared to 'fromList'. If-  --   the given hint does not equal to the input list's length the behaviour of-  --   'fromListN' is not specified.-  fromListN :: Int -> [Item l] -> l-  fromListN _ = fromList--  -- | The 'toList' function extracts a list of @Item l@ from the structure @l@.-  --   It should satisfy fromList . toList = id.-  toList :: l -> [Item l]--instance IsList [a] where-  type (Item [a]) = a-  fromList = id-  toList = id---- | @since 4.8.0.0-instance IsList Version where-  type (Item Version) = Int-  fromList = makeVersion-  toList = versionBranch
− GHC/Fingerprint.hs
@@ -1,114 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , BangPatterns-  #-}---- ----------------------------------------------------------------------------------  (c) The University of Glasgow 2006------ Fingerprints for recompilation checking and ABI versioning, and--- implementing fast comparison of Typeable.------ ------------------------------------------------------------------------------module GHC.Fingerprint (-        Fingerprint(..), fingerprint0,-        fingerprintData,-        fingerprintString,-        fingerprintFingerprints,-        getFileHash-   ) where--import GHC.IO-import GHC.Base-import GHC.Num-import GHC.List-import GHC.Real-import GHC.Show-import Foreign-import Foreign.C-import System.IO--import GHC.Fingerprint.Type---- for SIZEOF_STRUCT_MD5CONTEXT:-#include "HsBaseConfig.h"---- XXX instance Storable Fingerprint--- defined in Foreign.Storable to avoid orphan instance--fingerprint0 :: Fingerprint-fingerprint0 = Fingerprint 0 0--fingerprintFingerprints :: [Fingerprint] -> Fingerprint-fingerprintFingerprints fs = unsafeDupablePerformIO $-  withArrayLen fs $ \len p -> do-    fingerprintData (castPtr p) (len * sizeOf (head fs))--fingerprintData :: Ptr Word8 -> Int -> IO Fingerprint-fingerprintData buf len = do-  allocaBytes SIZEOF_STRUCT_MD5CONTEXT $ \pctxt -> do-    c_MD5Init pctxt-    c_MD5Update pctxt buf (fromIntegral len)-    allocaBytes 16 $ \pdigest -> do-      c_MD5Final pdigest pctxt-      peek (castPtr pdigest :: Ptr Fingerprint)---- This is duplicated in compiler/utils/Fingerprint.hsc-fingerprintString :: String -> Fingerprint-fingerprintString str = unsafeDupablePerformIO $-  withArrayLen word8s $ \len p ->-     fingerprintData p len-    where word8s = concatMap f str-          f c = let w32 :: Word32-                    w32 = fromIntegral (ord c)-                in [fromIntegral (w32 `shiftR` 24),-                    fromIntegral (w32 `shiftR` 16),-                    fromIntegral (w32 `shiftR` 8),-                    fromIntegral w32]---- | Computes the hash of a given file.--- This function loops over the handle, running in constant memory.------ @since 4.7.0.0-getFileHash :: FilePath -> IO Fingerprint-getFileHash path = withBinaryFile path ReadMode $ \h -> do-  allocaBytes SIZEOF_STRUCT_MD5CONTEXT $ \pctxt -> do-    c_MD5Init pctxt--    processChunks h (\buf size -> c_MD5Update pctxt buf (fromIntegral size))--    allocaBytes 16 $ \pdigest -> do-      c_MD5Final pdigest pctxt-      peek (castPtr pdigest :: Ptr Fingerprint)--  where-    _BUFSIZE = 4096--    -- | Loop over _BUFSIZE sized chunks read from the handle,-    -- passing the callback a block of bytes and its size.-    processChunks :: Handle -> (Ptr Word8 -> Int -> IO ()) -> IO ()-    processChunks h f = allocaBytes _BUFSIZE $ \arrPtr ->--      let loop = do-            count <- hGetBuf h arrPtr _BUFSIZE-            eof <- hIsEOF h-            when (count /= _BUFSIZE && not eof) $ error $-              "GHC.Fingerprint.getFileHash: only read " ++ show count ++ " bytes"--            f arrPtr count--            when (not eof) loop--      in loop--data MD5Context--foreign import ccall unsafe "__hsbase_MD5Init"-   c_MD5Init   :: Ptr MD5Context -> IO ()-foreign import ccall unsafe "__hsbase_MD5Update"-   c_MD5Update :: Ptr MD5Context -> Ptr Word8 -> CInt -> IO ()-foreign import ccall unsafe "__hsbase_MD5Final"-   c_MD5Final  :: Ptr Word8 -> Ptr MD5Context -> IO ()
− GHC/Fingerprint.hs-boot
@@ -1,14 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}--module GHC.Fingerprint (-        fingerprintString,-        fingerprintFingerprints-  ) where--import GHC.Base-import GHC.Fingerprint.Type--fingerprintFingerprints :: [Fingerprint] -> Fingerprint-fingerprintString :: String -> Fingerprint-
− GHC/Fingerprint/Type.hs
@@ -1,33 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---- ----------------------------------------------------------------------------------  (c) The University of Glasgow 2006------ Fingerprints for recompilation checking and ABI versioning, and--- implementing fast comparison of Typeable.------ ------------------------------------------------------------------------------module GHC.Fingerprint.Type (Fingerprint(..)) where--import GHC.Base-import GHC.List (length, replicate)-import GHC.Num-import GHC.Show-import GHC.Word-import Numeric (showHex)---- Using 128-bit MD5 fingerprints for now.--data Fingerprint = Fingerprint {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64-  deriving (Eq, Ord)--instance Show Fingerprint where-  show (Fingerprint w1 w2) = hex16 w1 ++ hex16 w2-    where-      -- | Formats a 64 bit number as 16 digits hex.-      hex16 :: Word64 -> String-      hex16 i = let hex = showHex i ""-                 in replicate (16 - length hex) '0' ++ hex
− GHC/Float.hs
@@ -1,1153 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , MagicHash-           , UnboxedTuples-  #-}--- We believe we could deorphan this module, by moving lots of things--- around, but we haven't got there yet:-{-# OPTIONS_GHC -fno-warn-orphans #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Float--- Copyright   :  (c) The University of Glasgow 1994-2002---                Portions obtained from hbc (c) Lennart Augusstson--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The types 'Float' and 'Double', and the classes 'Floating' and 'RealFloat'.-----------------------------------------------------------------------------------#include "ieee-flpt.h"--module GHC.Float( module GHC.Float, Float(..), Double(..), Float#, Double#-                , double2Int, int2Double, float2Int, int2Float )-    where--import Data.Maybe--import Data.Bits-import GHC.Base-import GHC.List-import GHC.Enum-import GHC.Show-import GHC.Num-import GHC.Real-import GHC.Arr-import GHC.Float.RealFracMethods-import GHC.Float.ConversionUtils-import GHC.Integer.Logarithms ( integerLogBase# )-import GHC.Integer.Logarithms.Internals--infixr 8  **----------------------------------------------------------------------------- Standard numeric classes----------------------------------------------------------------------------- | Trigonometric and hyperbolic functions and related functions.-class  (Fractional a) => Floating a  where-    pi                  :: a-    exp, log, sqrt      :: a -> a-    (**), logBase       :: a -> a -> a-    sin, cos, tan       :: a -> a-    asin, acos, atan    :: a -> a-    sinh, cosh, tanh    :: a -> a-    asinh, acosh, atanh :: a -> a--    {-# INLINE (**) #-}-    {-# INLINE logBase #-}-    {-# INLINE sqrt #-}-    {-# INLINE tan #-}-    {-# INLINE tanh #-}-    x ** y              =  exp (log x * y)-    logBase x y         =  log y / log x-    sqrt x              =  x ** 0.5-    tan  x              =  sin  x / cos  x-    tanh x              =  sinh x / cosh x---- | Efficient, machine-independent access to the components of a--- floating-point number.-class  (RealFrac a, Floating a) => RealFloat a  where-    -- | a constant function, returning the radix of the representation-    -- (often @2@)-    floatRadix          :: a -> Integer-    -- | a constant function, returning the number of digits of-    -- 'floatRadix' in the significand-    floatDigits         :: a -> Int-    -- | a constant function, returning the lowest and highest values-    -- the exponent may assume-    floatRange          :: a -> (Int,Int)-    -- | The function 'decodeFloat' applied to a real floating-point-    -- number returns the significand expressed as an 'Integer' and an-    -- appropriately scaled exponent (an 'Int').  If @'decodeFloat' x@-    -- yields @(m,n)@, then @x@ is equal in value to @m*b^^n@, where @b@-    -- is the floating-point radix, and furthermore, either @m@ and @n@-    -- are both zero or else @b^(d-1) <= 'abs' m < b^d@, where @d@ is-    -- the value of @'floatDigits' x@.-    -- In particular, @'decodeFloat' 0 = (0,0)@. If the type-    -- contains a negative zero, also @'decodeFloat' (-0.0) = (0,0)@.-    -- /The result of/ @'decodeFloat' x@ /is unspecified if either of/-    -- @'isNaN' x@ /or/ @'isInfinite' x@ /is/ 'True'.-    decodeFloat         :: a -> (Integer,Int)-    -- | 'encodeFloat' performs the inverse of 'decodeFloat' in the-    -- sense that for finite @x@ with the exception of @-0.0@,-    -- @'uncurry' 'encodeFloat' ('decodeFloat' x) = x@.-    -- @'encodeFloat' m n@ is one of the two closest representable-    -- floating-point numbers to @m*b^^n@ (or @&#177;Infinity@ if overflow-    -- occurs); usually the closer, but if @m@ contains too many bits,-    -- the result may be rounded in the wrong direction.-    encodeFloat         :: Integer -> Int -> a-    -- | 'exponent' corresponds to the second component of 'decodeFloat'.-    -- @'exponent' 0 = 0@ and for finite nonzero @x@,-    -- @'exponent' x = snd ('decodeFloat' x) + 'floatDigits' x@.-    -- If @x@ is a finite floating-point number, it is equal in value to-    -- @'significand' x * b ^^ 'exponent' x@, where @b@ is the-    -- floating-point radix.-    -- The behaviour is unspecified on infinite or @NaN@ values.-    exponent            :: a -> Int-    -- | The first component of 'decodeFloat', scaled to lie in the open-    -- interval (@-1@,@1@), either @0.0@ or of absolute value @>= 1\/b@,-    -- where @b@ is the floating-point radix.-    -- The behaviour is unspecified on infinite or @NaN@ values.-    significand         :: a -> a-    -- | multiplies a floating-point number by an integer power of the radix-    scaleFloat          :: Int -> a -> a-    -- | 'True' if the argument is an IEEE \"not-a-number\" (NaN) value-    isNaN               :: a -> Bool-    -- | 'True' if the argument is an IEEE infinity or negative infinity-    isInfinite          :: a -> Bool-    -- | 'True' if the argument is too small to be represented in-    -- normalized format-    isDenormalized      :: a -> Bool-    -- | 'True' if the argument is an IEEE negative zero-    isNegativeZero      :: a -> Bool-    -- | 'True' if the argument is an IEEE floating point number-    isIEEE              :: a -> Bool-    -- | a version of arctangent taking two real floating-point arguments.-    -- For real floating @x@ and @y@, @'atan2' y x@ computes the angle-    -- (from the positive x-axis) of the vector from the origin to the-    -- point @(x,y)@.  @'atan2' y x@ returns a value in the range [@-pi@,-    -- @pi@].  It follows the Common Lisp semantics for the origin when-    -- signed zeroes are supported.  @'atan2' y 1@, with @y@ in a type-    -- that is 'RealFloat', should return the same value as @'atan' y@.-    -- A default definition of 'atan2' is provided, but implementors-    -- can provide a more accurate implementation.-    atan2               :: a -> a -> a---    exponent x          =  if m == 0 then 0 else n + floatDigits x-                           where (m,n) = decodeFloat x--    significand x       =  encodeFloat m (negate (floatDigits x))-                           where (m,_) = decodeFloat x--    scaleFloat 0 x      =  x-    scaleFloat k x-      | isFix           =  x-      | otherwise       =  encodeFloat m (n + clamp b k)-                           where (m,n) = decodeFloat x-                                 (l,h) = floatRange x-                                 d     = floatDigits x-                                 b     = h - l + 4*d-                                 -- n+k may overflow, which would lead-                                 -- to wrong results, hence we clamp the-                                 -- scaling parameter.-                                 -- If n + k would be larger than h,-                                 -- n + clamp b k must be too, simliar-                                 -- for smaller than l - d.-                                 -- Add a little extra to keep clear-                                 -- from the boundary cases.-                                 isFix = x == 0 || isNaN x || isInfinite x--    atan2 y x-      | x > 0            =  atan (y/x)-      | x == 0 && y > 0  =  pi/2-      | x <  0 && y > 0  =  pi + atan (y/x)-      |(x <= 0 && y < 0)            ||-       (x <  0 && isNegativeZero y) ||-       (isNegativeZero x && isNegativeZero y)-                         = -atan2 (-y) x-      | y == 0 && (x < 0 || isNegativeZero x)-                          =  pi    -- must be after the previous test on zero y-      | x==0 && y==0      =  y     -- must be after the other double zero tests-      | otherwise         =  x + y -- x or y is a NaN, return a NaN (via +)----------------------------------------------------------------------------- Float---------------------------------------------------------------------------instance  Num Float  where-    (+)         x y     =  plusFloat x y-    (-)         x y     =  minusFloat x y-    negate      x       =  negateFloat x-    (*)         x y     =  timesFloat x y-    abs x    | x == 0    = 0 -- handles (-0.0)-             | x >  0    = x-             | otherwise = negateFloat x-    signum x | x > 0     = 1-             | x < 0     = negateFloat 1-             | otherwise = x -- handles 0.0, (-0.0), and NaN--    {-# INLINE fromInteger #-}-    fromInteger i = F# (floatFromInteger i)--instance  Real Float  where-    toRational (F# x#)  =-        case decodeFloat_Int# x# of-          (# m#, e# #)-            | isTrue# (e# >=# 0#)                               ->-                    (smallInteger m# `shiftLInteger` e#) :% 1-            | isTrue# ((int2Word# m# `and#` 1##) `eqWord#` 0##) ->-                    case elimZerosInt# m# (negateInt# e#) of-                      (# n, d# #) -> n :% shiftLInteger 1 d#-            | otherwise                                         ->-                    smallInteger m# :% shiftLInteger 1 (negateInt# e#)--instance  Fractional Float  where-    (/) x y             =  divideFloat x y-    {-# INLINE fromRational #-}-    fromRational (n:%d) = rationalToFloat n d-    recip x             =  1.0 / x--rationalToFloat :: Integer -> Integer -> Float-{-# NOINLINE [1] rationalToFloat #-}-rationalToFloat n 0-    | n == 0        = 0/0-    | n < 0         = (-1)/0-    | otherwise     = 1/0-rationalToFloat n d-    | n == 0        = encodeFloat 0 0-    | n < 0         = -(fromRat'' minEx mantDigs (-n) d)-    | otherwise     = fromRat'' minEx mantDigs n d-      where-        minEx       = FLT_MIN_EXP-        mantDigs    = FLT_MANT_DIG---- RULES for Integer and Int-{-# RULES-"properFraction/Float->Integer"     properFraction = properFractionFloatInteger-"truncate/Float->Integer"           truncate = truncateFloatInteger-"floor/Float->Integer"              floor = floorFloatInteger-"ceiling/Float->Integer"            ceiling = ceilingFloatInteger-"round/Float->Integer"              round = roundFloatInteger-"properFraction/Float->Int"         properFraction = properFractionFloatInt-"truncate/Float->Int"               truncate = float2Int-"floor/Float->Int"                  floor = floorFloatInt-"ceiling/Float->Int"                ceiling = ceilingFloatInt-"round/Float->Int"                  round = roundFloatInt-  #-}-instance  RealFrac Float  where--        -- ceiling, floor, and truncate are all small-    {-# INLINE [1] ceiling #-}-    {-# INLINE [1] floor #-}-    {-# INLINE [1] truncate #-}---- We assume that FLT_RADIX is 2 so that we can use more efficient code-#if FLT_RADIX != 2-#error FLT_RADIX must be 2-#endif-    properFraction (F# x#)-      = case decodeFloat_Int# x# of-        (# m#, n# #) ->-            let m = I# m#-                n = I# n#-            in-            if n >= 0-            then (fromIntegral m * (2 ^ n), 0.0)-            else let i = if m >= 0 then                m `shiftR` negate n-                                   else negate (negate m `shiftR` negate n)-                     f = m - (i `shiftL` negate n)-                 in (fromIntegral i, encodeFloat (fromIntegral f) n)--    truncate x  = case properFraction x of-                     (n,_) -> n--    round x     = case properFraction x of-                     (n,r) -> let-                                m         = if r < 0.0 then n - 1 else n + 1-                                half_down = abs r - 0.5-                              in-                              case (compare half_down 0.0) of-                                LT -> n-                                EQ -> if even n then n else m-                                GT -> m--    ceiling x   = case properFraction x of-                    (n,r) -> if r > 0.0 then n + 1 else n--    floor x     = case properFraction x of-                    (n,r) -> if r < 0.0 then n - 1 else n--instance  Floating Float  where-    pi                  =  3.141592653589793238-    exp x               =  expFloat x-    log x               =  logFloat x-    sqrt x              =  sqrtFloat x-    sin x               =  sinFloat x-    cos x               =  cosFloat x-    tan x               =  tanFloat x-    asin x              =  asinFloat x-    acos x              =  acosFloat x-    atan x              =  atanFloat x-    sinh x              =  sinhFloat x-    cosh x              =  coshFloat x-    tanh x              =  tanhFloat x-    (**) x y            =  powerFloat x y-    logBase x y         =  log y / log x--    asinh x = log (x + sqrt (1.0+x*x))-    acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))-    atanh x = 0.5 * log ((1.0+x) / (1.0-x))--instance  RealFloat Float  where-    floatRadix _        =  FLT_RADIX        -- from float.h-    floatDigits _       =  FLT_MANT_DIG     -- ditto-    floatRange _        =  (FLT_MIN_EXP, FLT_MAX_EXP) -- ditto--    decodeFloat (F# f#) = case decodeFloat_Int# f# of-                          (# i, e #) -> (smallInteger i, I# e)--    encodeFloat i (I# e) = F# (encodeFloatInteger i e)--    exponent x          = case decodeFloat x of-                            (m,n) -> if m == 0 then 0 else n + floatDigits x--    significand x       = case decodeFloat x of-                            (m,_) -> encodeFloat m (negate (floatDigits x))--    scaleFloat 0 x      = x-    scaleFloat k x-      | isFix           = x-      | otherwise       = case decodeFloat x of-                            (m,n) -> encodeFloat m (n + clamp bf k)-                        where bf = FLT_MAX_EXP - (FLT_MIN_EXP) + 4*FLT_MANT_DIG-                              isFix = x == 0 || isFloatFinite x == 0--    isNaN x          = 0 /= isFloatNaN x-    isInfinite x     = 0 /= isFloatInfinite x-    isDenormalized x = 0 /= isFloatDenormalized x-    isNegativeZero x = 0 /= isFloatNegativeZero x-    isIEEE _         = True--instance  Show Float  where-    showsPrec   x = showSignedFloat showFloat x-    showList = showList__ (showsPrec 0)----------------------------------------------------------------------------- Double---------------------------------------------------------------------------instance  Num Double  where-    (+)         x y     =  plusDouble x y-    (-)         x y     =  minusDouble x y-    negate      x       =  negateDouble x-    (*)         x y     =  timesDouble x y-    abs x    | x == 0    = 0 -- handles (-0.0)-             | x >  0    = x-             | otherwise = negateDouble x-    signum x | x > 0     = 1-             | x < 0     = negateDouble 1-             | otherwise = x -- handles 0.0, (-0.0), and NaN---    {-# INLINE fromInteger #-}-    fromInteger i = D# (doubleFromInteger i)---instance  Real Double  where-    toRational (D# x#)  =-        case decodeDoubleInteger x# of-          (# m, e# #)-            | isTrue# (e# >=# 0#)                                  ->-                shiftLInteger m e# :% 1-            | isTrue# ((integerToWord m `and#` 1##) `eqWord#` 0##) ->-                case elimZerosInteger m (negateInt# e#) of-                    (# n, d# #) ->  n :% shiftLInteger 1 d#-            | otherwise                                            ->-                m :% shiftLInteger 1 (negateInt# e#)--instance  Fractional Double  where-    (/) x y             =  divideDouble x y-    {-# INLINE fromRational #-}-    fromRational (n:%d) = rationalToDouble n d-    recip x             =  1.0 / x--rationalToDouble :: Integer -> Integer -> Double-{-# NOINLINE [1] rationalToDouble #-}-rationalToDouble n 0-    | n == 0        = 0/0-    | n < 0         = (-1)/0-    | otherwise     = 1/0-rationalToDouble n d-    | n == 0        = encodeFloat 0 0-    | n < 0         = -(fromRat'' minEx mantDigs (-n) d)-    | otherwise     = fromRat'' minEx mantDigs n d-      where-        minEx       = DBL_MIN_EXP-        mantDigs    = DBL_MANT_DIG--instance  Floating Double  where-    pi                  =  3.141592653589793238-    exp x               =  expDouble x-    log x               =  logDouble x-    sqrt x              =  sqrtDouble x-    sin  x              =  sinDouble x-    cos  x              =  cosDouble x-    tan  x              =  tanDouble x-    asin x              =  asinDouble x-    acos x              =  acosDouble x-    atan x              =  atanDouble x-    sinh x              =  sinhDouble x-    cosh x              =  coshDouble x-    tanh x              =  tanhDouble x-    (**) x y            =  powerDouble x y-    logBase x y         =  log y / log x--    asinh x = log (x + sqrt (1.0+x*x))-    acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))-    atanh x = 0.5 * log ((1.0+x) / (1.0-x))---- RULES for Integer and Int-{-# RULES-"properFraction/Double->Integer"    properFraction = properFractionDoubleInteger-"truncate/Double->Integer"          truncate = truncateDoubleInteger-"floor/Double->Integer"             floor = floorDoubleInteger-"ceiling/Double->Integer"           ceiling = ceilingDoubleInteger-"round/Double->Integer"             round = roundDoubleInteger-"properFraction/Double->Int"        properFraction = properFractionDoubleInt-"truncate/Double->Int"              truncate = double2Int-"floor/Double->Int"                 floor = floorDoubleInt-"ceiling/Double->Int"               ceiling = ceilingDoubleInt-"round/Double->Int"                 round = roundDoubleInt-  #-}-instance  RealFrac Double  where--        -- ceiling, floor, and truncate are all small-    {-# INLINE [1] ceiling #-}-    {-# INLINE [1] floor #-}-    {-# INLINE [1] truncate #-}--    properFraction x-      = case (decodeFloat x)      of { (m,n) ->-        if n >= 0 then-            (fromInteger m * 2 ^ n, 0.0)-        else-            case (quotRem m (2^(negate n))) of { (w,r) ->-            (fromInteger w, encodeFloat r n)-            }-        }--    truncate x  = case properFraction x of-                     (n,_) -> n--    round x     = case properFraction x of-                     (n,r) -> let-                                m         = if r < 0.0 then n - 1 else n + 1-                                half_down = abs r - 0.5-                              in-                              case (compare half_down 0.0) of-                                LT -> n-                                EQ -> if even n then n else m-                                GT -> m--    ceiling x   = case properFraction x of-                    (n,r) -> if r > 0.0 then n + 1 else n--    floor x     = case properFraction x of-                    (n,r) -> if r < 0.0 then n - 1 else n--instance  RealFloat Double  where-    floatRadix _        =  FLT_RADIX        -- from float.h-    floatDigits _       =  DBL_MANT_DIG     -- ditto-    floatRange _        =  (DBL_MIN_EXP, DBL_MAX_EXP) -- ditto--    decodeFloat (D# x#)-      = case decodeDoubleInteger x#   of-          (# i, j #) -> (i, I# j)--    encodeFloat i (I# j) = D# (encodeDoubleInteger i j)--    exponent x          = case decodeFloat x of-                            (m,n) -> if m == 0 then 0 else n + floatDigits x--    significand x       = case decodeFloat x of-                            (m,_) -> encodeFloat m (negate (floatDigits x))--    scaleFloat 0 x      = x-    scaleFloat k x-      | isFix           = x-      | otherwise       = case decodeFloat x of-                            (m,n) -> encodeFloat m (n + clamp bd k)-                        where bd = DBL_MAX_EXP - (DBL_MIN_EXP) + 4*DBL_MANT_DIG-                              isFix = x == 0 || isDoubleFinite x == 0--    isNaN x             = 0 /= isDoubleNaN x-    isInfinite x        = 0 /= isDoubleInfinite x-    isDenormalized x    = 0 /= isDoubleDenormalized x-    isNegativeZero x    = 0 /= isDoubleNegativeZero x-    isIEEE _            = True--instance  Show Double  where-    showsPrec   x = showSignedFloat showFloat x-    showList = showList__ (showsPrec 0)------------------------------------------------------------------------------ Enum instances---------------------------------------------------------------------------{--The @Enum@ instances for Floats and Doubles are slightly unusual.-The @toEnum@ function truncates numbers to Int.  The definitions-of @enumFrom@ and @enumFromThen@ allow floats to be used in arithmetic-series: [0,0.1 .. 1.0].  However, roundoff errors make these somewhat-dubious.  This example may have either 10 or 11 elements, depending on-how 0.1 is represented.--NOTE: The instances for Float and Double do not make use of the default-methods for @enumFromTo@ and @enumFromThenTo@, as these rely on there being-a `non-lossy' conversion to and from Ints. Instead we make use of the-1.2 default methods (back in the days when Enum had Ord as a superclass)-for these (@numericEnumFromTo@ and @numericEnumFromThenTo@ below.)--}--instance  Enum Float  where-    succ x         = x + 1-    pred x         = x - 1-    toEnum         = int2Float-    fromEnum       = fromInteger . truncate   -- may overflow-    enumFrom       = numericEnumFrom-    enumFromTo     = numericEnumFromTo-    enumFromThen   = numericEnumFromThen-    enumFromThenTo = numericEnumFromThenTo--instance  Enum Double  where-    succ x         = x + 1-    pred x         = x - 1-    toEnum         =  int2Double-    fromEnum       =  fromInteger . truncate   -- may overflow-    enumFrom       =  numericEnumFrom-    enumFromTo     =  numericEnumFromTo-    enumFromThen   =  numericEnumFromThen-    enumFromThenTo =  numericEnumFromThenTo----------------------------------------------------------------------------- Printing floating point----------------------------------------------------------------------------- | Show a signed 'RealFloat' value to full precision--- using standard decimal notation for arguments whose absolute value lies--- between @0.1@ and @9,999,999@, and scientific notation otherwise.-showFloat :: (RealFloat a) => a -> ShowS-showFloat x  =  showString (formatRealFloat FFGeneric Nothing x)---- These are the format types.  This type is not exported.--data FFFormat = FFExponent | FFFixed | FFGeneric---- This is just a compatibility stub, as the "alt" argument formerly--- didn't exist.-formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String-formatRealFloat fmt decs x = formatRealFloatAlt fmt decs False x--formatRealFloatAlt :: (RealFloat a) => FFFormat -> Maybe Int -> Bool -> a-                 -> String-formatRealFloatAlt fmt decs alt x-   | isNaN x                   = "NaN"-   | isInfinite x              = if x < 0 then "-Infinity" else "Infinity"-   | x < 0 || isNegativeZero x = '-':doFmt fmt (floatToDigits (toInteger base) (-x))-   | otherwise                 = doFmt fmt (floatToDigits (toInteger base) x)- where-  base = 10--  doFmt format (is, e) =-    let ds = map intToDigit is in-    case format of-     FFGeneric ->-      doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)-            (is,e)-     FFExponent ->-      case decs of-       Nothing ->-        let show_e' = show (e-1) in-        case ds of-          "0"     -> "0.0e0"-          [d]     -> d : ".0e" ++ show_e'-          (d:ds') -> d : '.' : ds' ++ "e" ++ show_e'-          []      -> error "formatRealFloat/doFmt/FFExponent: []"-       Just dec ->-        let dec' = max dec 1 in-        case is of-         [0] -> '0' :'.' : take dec' (repeat '0') ++ "e0"-         _ ->-          let-           (ei,is') = roundTo base (dec'+1) is-           (d:ds') = map intToDigit (if ei > 0 then init is' else is')-          in-          d:'.':ds' ++ 'e':show (e-1+ei)-     FFFixed ->-      let-       mk0 ls = case ls of { "" -> "0" ; _ -> ls}-      in-      case decs of-       Nothing-          | e <= 0    -> "0." ++ replicate (-e) '0' ++ ds-          | otherwise ->-             let-                f 0 s    rs  = mk0 (reverse s) ++ '.':mk0 rs-                f n s    ""  = f (n-1) ('0':s) ""-                f n s (r:rs) = f (n-1) (r:s) rs-             in-                f e "" ds-       Just dec ->-        let dec' = max dec 0 in-        if e >= 0 then-         let-          (ei,is') = roundTo base (dec' + e) is-          (ls,rs)  = splitAt (e+ei) (map intToDigit is')-         in-         mk0 ls ++ (if null rs && not alt then "" else '.':rs)-        else-         let-          (ei,is') = roundTo base dec' (replicate (-e) 0 ++ is)-          d:ds' = map intToDigit (if ei > 0 then is' else 0:is')-         in-         d : (if null ds' && not alt then "" else '.':ds')---roundTo :: Int -> Int -> [Int] -> (Int,[Int])-roundTo base d is =-  case f d True is of-    x@(0,_) -> x-    (1,xs)  -> (1, 1:xs)-    _       -> error "roundTo: bad Value"- where-  b2 = base `quot` 2--  f n _ []     = (0, replicate n 0)-  f 0 e (x:xs) | x == b2 && e && all (== 0) xs = (0, [])   -- Round to even when at exactly half the base-               | otherwise = (if x >= b2 then 1 else 0, [])-  f n _ (i:xs)-     | i' == base = (1,0:ds)-     | otherwise  = (0,i':ds)-      where-       (c,ds) = f (n-1) (even i) xs-       i'     = c + i---- Based on "Printing Floating-Point Numbers Quickly and Accurately"--- by R.G. Burger and R.K. Dybvig in PLDI 96.--- This version uses a much slower logarithm estimator. It should be improved.---- | 'floatToDigits' takes a base and a non-negative 'RealFloat' number,--- and returns a list of digits and an exponent.--- In particular, if @x>=0@, and------ > floatToDigits base x = ([d1,d2,...,dn], e)------ then------      (1) @n >= 1@------      (2) @x = 0.d1d2...dn * (base**e)@------      (3) @0 <= di <= base-1@--floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)-floatToDigits _ 0 = ([0], 0)-floatToDigits base x =- let-  (f0, e0) = decodeFloat x-  (minExp0, _) = floatRange x-  p = floatDigits x-  b = floatRadix x-  minExp = minExp0 - p -- the real minimum exponent-  -- Haskell requires that f be adjusted so denormalized numbers-  -- will have an impossibly low exponent.  Adjust for this.-  (f, e) =-   let n = minExp - e0 in-   if n > 0 then (f0 `quot` (expt b n), e0+n) else (f0, e0)-  (r, s, mUp, mDn) =-   if e >= 0 then-    let be = expt b e in-    if f == expt b (p-1) then-      (f*be*b*2, 2*b, be*b, be)     -- according to Burger and Dybvig-    else-      (f*be*2, 2, be, be)-   else-    if e > minExp && f == expt b (p-1) then-      (f*b*2, expt b (-e+1)*2, b, 1)-    else-      (f*2, expt b (-e)*2, 1, 1)-  k :: Int-  k =-   let-    k0 :: Int-    k0 =-     if b == 2 && base == 10 then-        -- logBase 10 2 is very slightly larger than 8651/28738-        -- (about 5.3558e-10), so if log x >= 0, the approximation-        -- k1 is too small, hence we add one and need one fixup step less.-        -- If log x < 0, the approximation errs rather on the high side.-        -- That is usually more than compensated for by ignoring the-        -- fractional part of logBase 2 x, but when x is a power of 1/2-        -- or slightly larger and the exponent is a multiple of the-        -- denominator of the rational approximation to logBase 10 2,-        -- k1 is larger than logBase 10 x. If k1 > 1 + logBase 10 x,-        -- we get a leading zero-digit we don't want.-        -- With the approximation 3/10, this happened for-        -- 0.5^1030, 0.5^1040, ..., 0.5^1070 and values close above.-        -- The approximation 8651/28738 guarantees k1 < 1 + logBase 10 x-        -- for IEEE-ish floating point types with exponent fields-        -- <= 17 bits and mantissae of several thousand bits, earlier-        -- convergents to logBase 10 2 would fail for long double.-        -- Using quot instead of div is a little faster and requires-        -- fewer fixup steps for negative lx.-        let lx = p - 1 + e0-            k1 = (lx * 8651) `quot` 28738-        in if lx >= 0 then k1 + 1 else k1-     else-        -- f :: Integer, log :: Float -> Float,-        --               ceiling :: Float -> Int-        ceiling ((log (fromInteger (f+1) :: Float) +-                 fromIntegral e * log (fromInteger b)) /-                   log (fromInteger base))---WAS:            fromInt e * log (fromInteger b))--    fixup n =-      if n >= 0 then-        if r + mUp <= expt base n * s then n else fixup (n+1)-      else-        if expt base (-n) * (r + mUp) <= s then n else fixup (n+1)-   in-   fixup k0--  gen ds rn sN mUpN mDnN =-   let-    (dn, rn') = (rn * base) `quotRem` sN-    mUpN' = mUpN * base-    mDnN' = mDnN * base-   in-   case (rn' < mDnN', rn' + mUpN' > sN) of-    (True,  False) -> dn : ds-    (False, True)  -> dn+1 : ds-    (True,  True)  -> if rn' * 2 < sN then dn : ds else dn+1 : ds-    (False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'--  rds =-   if k >= 0 then-      gen [] r (s * expt base k) mUp mDn-   else-     let bk = expt base (-k) in-     gen [] (r * bk) s (mUp * bk) (mDn * bk)- in- (map fromIntegral (reverse rds), k)----------------------------------------------------------------------------- Converting from a Rational to a RealFloa---------------------------------------------------------------------------{--[In response to a request for documentation of how fromRational works,-Joe Fasel writes:] A quite reasonable request!  This code was added to-the Prelude just before the 1.2 release, when Lennart, working with an-early version of hbi, noticed that (read . show) was not the identity-for floating-point numbers.  (There was a one-bit error about half the-time.)  The original version of the conversion function was in fact-simply a floating-point divide, as you suggest above. The new version-is, I grant you, somewhat denser.--Unfortunately, Joe's code doesn't work!  Here's an example:--main = putStr (shows (1.82173691287639817263897126389712638972163e-300::Double) "\n")--This program prints-        0.0000000000000000-instead of-        1.8217369128763981e-300--Here's Joe's code:--\begin{pseudocode}-fromRat :: (RealFloat a) => Rational -> a-fromRat x = x'-        where x' = f e----              If the exponent of the nearest floating-point number to x---              is e, then the significand is the integer nearest xb^(-e),---              where b is the floating-point radix.  We start with a good---              guess for e, and if it is correct, the exponent of the---              floating-point number we construct will again be e.  If---              not, one more iteration is needed.--              f e   = if e' == e then y else f e'-                      where y      = encodeFloat (round (x * (1 % b)^^e)) e-                            (_,e') = decodeFloat y-              b     = floatRadix x'----              We obtain a trial exponent by doing a floating-point---              division of x's numerator by its denominator.  The---              result of this division may not itself be the ultimate---              result, because of an accumulation of three rounding---              errors.--              (s,e) = decodeFloat (fromInteger (numerator x) `asTypeOf` x'-                                        / fromInteger (denominator x))-\end{pseudocode}--Now, here's Lennart's code (which works):--}---- | Converts a 'Rational' value into any type in class 'RealFloat'.-{-# RULES-"fromRat/Float"     fromRat = (fromRational :: Rational -> Float)-"fromRat/Double"    fromRat = (fromRational :: Rational -> Double)-  #-}--{-# NOINLINE [1] fromRat #-}-fromRat :: (RealFloat a) => Rational -> a---- Deal with special cases first, delegating the real work to fromRat'-fromRat (n :% 0) | n > 0     =  1/0        -- +Infinity-                 | n < 0     = -1/0        -- -Infinity-                 | otherwise =  0/0        -- NaN--fromRat (n :% d) | n > 0     = fromRat' (n :% d)-                 | n < 0     = - fromRat' ((-n) :% d)-                 | otherwise = encodeFloat 0 0             -- Zero---- Conversion process:--- Scale the rational number by the RealFloat base until--- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).--- Then round the rational to an Integer and encode it with the exponent--- that we got from the scaling.--- To speed up the scaling process we compute the log2 of the number to get--- a first guess of the exponent.--fromRat' :: (RealFloat a) => Rational -> a--- Invariant: argument is strictly positive-fromRat' x = r-  where b = floatRadix r-        p = floatDigits r-        (minExp0, _) = floatRange r-        minExp = minExp0 - p            -- the real minimum exponent-        xMax   = toRational (expt b p)-        p0 = (integerLogBase b (numerator x) - integerLogBase b (denominator x) - p) `max` minExp-        -- if x = n/d and ln = integerLogBase b n, ld = integerLogBase b d,-        -- then b^(ln-ld-1) < x < b^(ln-ld+1)-        f = if p0 < 0 then 1 :% expt b (-p0) else expt b p0 :% 1-        x0 = x / f-        -- if ln - ld >= minExp0, then b^(p-1) < x0 < b^(p+1), so there's at most-        -- one scaling step needed, otherwise, x0 < b^p and no scaling is needed-        (x', p') = if x0 >= xMax then (x0 / toRational b, p0+1) else (x0, p0)-        r = encodeFloat (round x') p'---- Exponentiation with a cache for the most common numbers.-minExpt, maxExpt :: Int-minExpt = 0-maxExpt = 1100--expt :: Integer -> Int -> Integer-expt base n =-    if base == 2 && n >= minExpt && n <= maxExpt then-        expts!n-    else-        if base == 10 && n <= maxExpt10 then-            expts10!n-        else-            base^n--expts :: Array Int Integer-expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]--maxExpt10 :: Int-maxExpt10 = 324--expts10 :: Array Int Integer-expts10 = array (minExpt,maxExpt10) [(n,10^n) | n <- [minExpt .. maxExpt10]]---- Compute the (floor of the) log of i in base b.--- Simplest way would be just divide i by b until it's smaller then b, but that would--- be very slow!  We are just slightly more clever, except for base 2, where--- we take advantage of the representation of Integers.--- The general case could be improved by a lookup table for--- approximating the result by integerLog2 i / integerLog2 b.-integerLogBase :: Integer -> Integer -> Int-integerLogBase b i-   | i < b     = 0-   | b == 2    = I# (integerLog2# i)-   | otherwise = I# (integerLogBase# b i)--{--Unfortunately, the old conversion code was awfully slow due to-a) a slow integer logarithm-b) repeated calculation of gcd's--For the case of Rational's coming from a Float or Double via toRational,-we can exploit the fact that the denominator is a power of two, which for-these brings a huge speedup since we need only shift and add instead-of division.--The below is an adaption of fromRat' for the conversion to-Float or Double exploiting the known floatRadix and avoiding-divisions as much as possible.--}--{-# SPECIALISE fromRat'' :: Int -> Int -> Integer -> Integer -> Float,-                            Int -> Int -> Integer -> Integer -> Double #-}-fromRat'' :: RealFloat a => Int -> Int -> Integer -> Integer -> a--- Invariant: n and d strictly positive-fromRat'' minEx@(I# me#) mantDigs@(I# md#) n d =-    case integerLog2IsPowerOf2# d of-      (# ld#, pw# #)-        | isTrue# (pw# ==# 0#) ->-          case integerLog2# n of-            ln# | isTrue# (ln# >=# (ld# +# me# -# 1#)) ->-                  -- this means n/d >= 2^(minEx-1), i.e. we are guaranteed to get-                  -- a normalised number, round to mantDigs bits-                  if isTrue# (ln# <# md#)-                    then encodeFloat n (I# (negateInt# ld#))-                    else let n'  = n `shiftR` (I# (ln# +# 1# -# md#))-                             n'' = case roundingMode# n (ln# -# md#) of-                                    0# -> n'-                                    2# -> n' + 1-                                    _  -> case fromInteger n' .&. (1 :: Int) of-                                            0 -> n'-                                            _ -> n' + 1-                         in encodeFloat n'' (I# (ln# -# ld# +# 1# -# md#))-                | otherwise ->-                  -- n/d < 2^(minEx-1), a denorm or rounded to 2^(minEx-1)-                  -- the exponent for encoding is always minEx-mantDigs-                  -- so we must shift right by (minEx-mantDigs) - (-ld)-                  case ld# +# (me# -# md#) of-                    ld'# | isTrue# (ld'# <=# 0#) -> -- we would shift left, so we don't shift-                           encodeFloat n (I# ((me# -# md#) -# ld'#))-                         | isTrue# (ld'# <=# ln#) ->-                           let n' = n `shiftR` (I# ld'#)-                           in case roundingMode# n (ld'# -# 1#) of-                                0# -> encodeFloat n' (minEx - mantDigs)-                                1# -> if fromInteger n' .&. (1 :: Int) == 0-                                        then encodeFloat n' (minEx-mantDigs)-                                        else encodeFloat (n' + 1) (minEx-mantDigs)-                                _  -> encodeFloat (n' + 1) (minEx-mantDigs)-                         | isTrue# (ld'# ># (ln# +# 1#)) -> encodeFloat 0 0 -- result of shift < 0.5-                         | otherwise ->  -- first bit of n shifted to 0.5 place-                           case integerLog2IsPowerOf2# n of-                            (# _, 0# #) -> encodeFloat 0 0  -- round to even-                            (# _, _ #)  -> encodeFloat 1 (minEx - mantDigs)-        | otherwise ->-          let ln = I# (integerLog2# n)-              ld = I# ld#-              -- 2^(ln-ld-1) < n/d < 2^(ln-ld+1)-              p0 = max minEx (ln - ld)-              (n', d')-                | p0 < mantDigs = (n `shiftL` (mantDigs - p0), d)-                | p0 == mantDigs = (n, d)-                | otherwise     = (n, d `shiftL` (p0 - mantDigs))-              -- if ln-ld < minEx, then n'/d' < 2^mantDigs, else-              -- 2^(mantDigs-1) < n'/d' < 2^(mantDigs+1) and we-              -- may need one scaling step-              scale p a b-                | (b `shiftL` mantDigs) <= a = (p+1, a, b `shiftL` 1)-                | otherwise = (p, a, b)-              (p', n'', d'') = scale (p0-mantDigs) n' d'-              -- n''/d'' < 2^mantDigs and p' == minEx-mantDigs or n''/d'' >= 2^(mantDigs-1)-              rdq = case n'' `quotRem` d'' of-                     (q,r) -> case compare (r `shiftL` 1) d'' of-                                LT -> q-                                EQ -> if fromInteger q .&. (1 :: Int) == 0-                                        then q else q+1-                                GT -> q+1-          in  encodeFloat rdq p'----------------------------------------------------------------------------- Floating point numeric primops----------------------------------------------------------------------------- Definitions of the boxed PrimOps; these will be--- used in the case of partial applications, etc.--plusFloat, minusFloat, timesFloat, divideFloat :: Float -> Float -> Float-plusFloat   (F# x) (F# y) = F# (plusFloat# x y)-minusFloat  (F# x) (F# y) = F# (minusFloat# x y)-timesFloat  (F# x) (F# y) = F# (timesFloat# x y)-divideFloat (F# x) (F# y) = F# (divideFloat# x y)--negateFloat :: Float -> Float-negateFloat (F# x)        = F# (negateFloat# x)--gtFloat, geFloat, eqFloat, neFloat, ltFloat, leFloat :: Float -> Float -> Bool-gtFloat     (F# x) (F# y) = isTrue# (gtFloat# x y)-geFloat     (F# x) (F# y) = isTrue# (geFloat# x y)-eqFloat     (F# x) (F# y) = isTrue# (eqFloat# x y)-neFloat     (F# x) (F# y) = isTrue# (neFloat# x y)-ltFloat     (F# x) (F# y) = isTrue# (ltFloat# x y)-leFloat     (F# x) (F# y) = isTrue# (leFloat# x y)--expFloat, logFloat, sqrtFloat :: Float -> Float-sinFloat, cosFloat, tanFloat  :: Float -> Float-asinFloat, acosFloat, atanFloat  :: Float -> Float-sinhFloat, coshFloat, tanhFloat  :: Float -> Float-expFloat    (F# x) = F# (expFloat# x)-logFloat    (F# x) = F# (logFloat# x)-sqrtFloat   (F# x) = F# (sqrtFloat# x)-sinFloat    (F# x) = F# (sinFloat# x)-cosFloat    (F# x) = F# (cosFloat# x)-tanFloat    (F# x) = F# (tanFloat# x)-asinFloat   (F# x) = F# (asinFloat# x)-acosFloat   (F# x) = F# (acosFloat# x)-atanFloat   (F# x) = F# (atanFloat# x)-sinhFloat   (F# x) = F# (sinhFloat# x)-coshFloat   (F# x) = F# (coshFloat# x)-tanhFloat   (F# x) = F# (tanhFloat# x)--powerFloat :: Float -> Float -> Float-powerFloat  (F# x) (F# y) = F# (powerFloat# x y)---- definitions of the boxed PrimOps; these will be--- used in the case of partial applications, etc.--plusDouble, minusDouble, timesDouble, divideDouble :: Double -> Double -> Double-plusDouble   (D# x) (D# y) = D# (x +## y)-minusDouble  (D# x) (D# y) = D# (x -## y)-timesDouble  (D# x) (D# y) = D# (x *## y)-divideDouble (D# x) (D# y) = D# (x /## y)--negateDouble :: Double -> Double-negateDouble (D# x)        = D# (negateDouble# x)--gtDouble, geDouble, eqDouble, neDouble, leDouble, ltDouble :: Double -> Double -> Bool-gtDouble    (D# x) (D# y) = isTrue# (x >##  y)-geDouble    (D# x) (D# y) = isTrue# (x >=## y)-eqDouble    (D# x) (D# y) = isTrue# (x ==## y)-neDouble    (D# x) (D# y) = isTrue# (x /=## y)-ltDouble    (D# x) (D# y) = isTrue# (x <##  y)-leDouble    (D# x) (D# y) = isTrue# (x <=## y)--double2Float :: Double -> Float-double2Float (D# x) = F# (double2Float# x)--float2Double :: Float -> Double-float2Double (F# x) = D# (float2Double# x)--expDouble, logDouble, sqrtDouble :: Double -> Double-sinDouble, cosDouble, tanDouble  :: Double -> Double-asinDouble, acosDouble, atanDouble  :: Double -> Double-sinhDouble, coshDouble, tanhDouble  :: Double -> Double-expDouble    (D# x) = D# (expDouble# x)-logDouble    (D# x) = D# (logDouble# x)-sqrtDouble   (D# x) = D# (sqrtDouble# x)-sinDouble    (D# x) = D# (sinDouble# x)-cosDouble    (D# x) = D# (cosDouble# x)-tanDouble    (D# x) = D# (tanDouble# x)-asinDouble   (D# x) = D# (asinDouble# x)-acosDouble   (D# x) = D# (acosDouble# x)-atanDouble   (D# x) = D# (atanDouble# x)-sinhDouble   (D# x) = D# (sinhDouble# x)-coshDouble   (D# x) = D# (coshDouble# x)-tanhDouble   (D# x) = D# (tanhDouble# x)--powerDouble :: Double -> Double -> Double-powerDouble  (D# x) (D# y) = D# (x **## y)--foreign import ccall unsafe "isFloatNaN" isFloatNaN :: Float -> Int-foreign import ccall unsafe "isFloatInfinite" isFloatInfinite :: Float -> Int-foreign import ccall unsafe "isFloatDenormalized" isFloatDenormalized :: Float -> Int-foreign import ccall unsafe "isFloatNegativeZero" isFloatNegativeZero :: Float -> Int-foreign import ccall unsafe "isFloatFinite" isFloatFinite :: Float -> Int--foreign import ccall unsafe "isDoubleNaN" isDoubleNaN :: Double -> Int-foreign import ccall unsafe "isDoubleInfinite" isDoubleInfinite :: Double -> Int-foreign import ccall unsafe "isDoubleDenormalized" isDoubleDenormalized :: Double -> Int-foreign import ccall unsafe "isDoubleNegativeZero" isDoubleNegativeZero :: Double -> Int-foreign import ccall unsafe "isDoubleFinite" isDoubleFinite :: Double -> Int----------------------------------------------------------------------------- Coercion rules---------------------------------------------------------------------------word2Double :: Word -> Double-word2Double (W# w) = D# (word2Double# w)--word2Float :: Word -> Float-word2Float (W# w) = F# (word2Float# w)--{-# RULES-"fromIntegral/Int->Float"   fromIntegral = int2Float-"fromIntegral/Int->Double"  fromIntegral = int2Double-"fromIntegral/Word->Float"  fromIntegral = word2Float-"fromIntegral/Word->Double" fromIntegral = word2Double-"realToFrac/Float->Float"   realToFrac   = id :: Float -> Float-"realToFrac/Float->Double"  realToFrac   = float2Double-"realToFrac/Double->Float"  realToFrac   = double2Float-"realToFrac/Double->Double" realToFrac   = id :: Double -> Double-"realToFrac/Int->Double"    realToFrac   = int2Double   -- See Note [realToFrac int-to-float]-"realToFrac/Int->Float"     realToFrac   = int2Float    --      ..ditto-    #-}--{--Note [realToFrac int-to-float]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-Don found that the RULES for realToFrac/Int->Double and simliarly-Float made a huge difference to some stream-fusion programs.  Here's-an example--      import Data.Array.Vector--      n = 40000000--      main = do-            let c = replicateU n (2::Double)-                a = mapU realToFrac (enumFromToU 0 (n-1) ) :: UArr Double-            print (sumU (zipWithU (*) c a))--Without the RULE we get this loop body:--      case $wtoRational sc_sY4 of ww_aM7 { (# ww1_aM9, ww2_aMa #) ->-      case $wfromRat ww1_aM9 ww2_aMa of tpl_X1P { D# ipv_sW3 ->-      Main.$s$wfold-        (+# sc_sY4 1)-        (+# wild_X1i 1)-        (+## sc2_sY6 (*## 2.0 ipv_sW3))--And with the rule:--     Main.$s$wfold-        (+# sc_sXT 1)-        (+# wild_X1h 1)-        (+## sc2_sXV (*## 2.0 (int2Double# sc_sXT)))--The running time of the program goes from 120 seconds to 0.198 seconds-with the native backend, and 0.143 seconds with the C backend.--A few more details in Trac #2251, and the patch message-"Add RULES for realToFrac from Int".--}---- Utils--showSignedFloat :: (RealFloat a)-  => (a -> ShowS)       -- ^ a function that can show unsigned values-  -> Int                -- ^ the precedence of the enclosing context-  -> a                  -- ^ the value to show-  -> ShowS-showSignedFloat showPos p x-   | x < 0 || isNegativeZero x-       = showParen (p > 6) (showChar '-' . showPos (-x))-   | otherwise = showPos x--{--We need to prevent over/underflow of the exponent in encodeFloat when-called from scaleFloat, hence we clamp the scaling parameter.-We must have a large enough range to cover the maximum difference of-exponents returned by decodeFloat.--}-clamp :: Int -> Int -> Int-clamp bd k = max (-bd) (min bd k)
− GHC/Float/ConversionUtils.hs
@@ -1,100 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, MagicHash, UnboxedTuples, NoImplicitPrelude #-}-{-# OPTIONS_GHC -O2 #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Float.ConversionUtils--- Copyright   :  (c) Daniel Fischer 2010--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Utilities for conversion between Double/Float and Rational-----------------------------------------------------------------------------------#include "MachDeps.h"--module GHC.Float.ConversionUtils ( elimZerosInteger, elimZerosInt# ) where--import GHC.Base-import GHC.Integer-#if WORD_SIZE_IN_BITS < 64-import GHC.IntWord64-#endif--default ()--#if WORD_SIZE_IN_BITS < 64--#define TO64    integerToInt64--toByte64# :: Int64# -> Int#-toByte64# i = word2Int# (and# 255## (int2Word# (int64ToInt# i)))---- Double mantissae have 53 bits, too much for Int#-elim64# :: Int64# -> Int# -> (# Integer, Int# #)-elim64# n e =-    case zeroCount (toByte64# n) of-      t | isTrue# (e <=# t) -> (# int64ToInteger (uncheckedIShiftRA64# n e), 0# #)-        | isTrue# (t <# 8#) -> (# int64ToInteger (uncheckedIShiftRA64# n t), e -# t #)-        | otherwise         -> elim64# (uncheckedIShiftRA64# n 8#) (e -# 8#)--#else--#define TO64    integerToInt---- Double mantissae fit it Int#-elim64# :: Int# -> Int# -> (# Integer, Int# #)-elim64# = elimZerosInt#--#endif--{-# INLINE elimZerosInteger #-}-elimZerosInteger :: Integer -> Int# -> (# Integer, Int# #)-elimZerosInteger m e = elim64# (TO64 m) e--elimZerosInt# :: Int# -> Int# -> (# Integer, Int# #)-elimZerosInt# n e =-    case zeroCount (toByte# n) of-      t | isTrue# (e <=# t) -> (# smallInteger (uncheckedIShiftRA# n e), 0# #)-        | isTrue# (t <# 8#) -> (# smallInteger (uncheckedIShiftRA# n t), e -# t #)-        | otherwise         -> elimZerosInt# (uncheckedIShiftRA# n 8#) (e -# 8#)--{-# INLINE zeroCount #-}-zeroCount :: Int# -> Int#-zeroCount i =-    case zeroCountArr of-      BA ba -> indexInt8Array# ba i--toByte# :: Int# -> Int#-toByte# i = word2Int# (and# 255## (int2Word# i))---data BA = BA ByteArray#---- Number of trailing zero bits in a byte-zeroCountArr :: BA-zeroCountArr =-    let mkArr s =-          case newByteArray# 256# s of-            (# s1, mba #) ->-              case writeInt8Array# mba 0# 8# s1 of-                s2 ->-                  let fillA step val idx st-                        | isTrue# (idx <# 256#) =-                                        case writeInt8Array# mba idx val st of-                                          nx -> fillA step val (idx +# step) nx-                        | isTrue# (step <# 256#) =-                                        fillA (2# *# step) (val +# 1#) step  st-                        | otherwise   = st-                  in case fillA 2# 0# 1# s2 of-                       s3 -> case unsafeFreezeByteArray# mba s3 of-                                (# _, ba #) -> ba-    in case mkArr realWorld# of-        b -> BA b-
− GHC/Float/RealFracMethods.hs
@@ -1,342 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, MagicHash, UnboxedTuples, NoImplicitPrelude #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Float.RealFracMethods--- Copyright   :  (c) Daniel Fischer 2010--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Methods for the RealFrac instances for 'Float' and 'Double',--- with specialised versions for 'Int'.------ Moved to their own module to not bloat GHC.Float further.-----------------------------------------------------------------------------------#include "MachDeps.h"--module GHC.Float.RealFracMethods-    ( -- * Double methods-      -- ** Integer results-      properFractionDoubleInteger-    , truncateDoubleInteger-    , floorDoubleInteger-    , ceilingDoubleInteger-    , roundDoubleInteger-      -- ** Int results-    , properFractionDoubleInt-    , floorDoubleInt-    , ceilingDoubleInt-    , roundDoubleInt-      -- * Double/Int conversions, wrapped primops-    , double2Int-    , int2Double-      -- * Float methods-      -- ** Integer results-    , properFractionFloatInteger-    , truncateFloatInteger-    , floorFloatInteger-    , ceilingFloatInteger-    , roundFloatInteger-      -- ** Int results-    , properFractionFloatInt-    , floorFloatInt-    , ceilingFloatInt-    , roundFloatInt-      -- * Float/Int conversions, wrapped primops-    , float2Int-    , int2Float-    ) where--import GHC.Integer--import GHC.Base-import GHC.Num ()--#if WORD_SIZE_IN_BITS < 64--import GHC.IntWord64--#define TO64 integerToInt64-#define FROM64 int64ToInteger-#define MINUS64 minusInt64#-#define NEGATE64 negateInt64#--#else--#define TO64 integerToInt-#define FROM64 smallInteger-#define MINUS64 ( -# )-#define NEGATE64 negateInt#--uncheckedIShiftRA64# :: Int# -> Int# -> Int#-uncheckedIShiftRA64# = uncheckedIShiftRA#--uncheckedIShiftL64# :: Int# -> Int# -> Int#-uncheckedIShiftL64# = uncheckedIShiftL#--#endif--default ()-----------------------------------------------------------------------------------                              Float Methods                               ------------------------------------------------------------------------------------- Special Functions for Int, nice, easy and fast.--- They should be small enough to be inlined automatically.---- We have to test for ±0.0 to avoid returning -0.0 in the second--- component of the pair. Unfortunately the branching costs a lot--- of performance.-properFractionFloatInt :: Float -> (Int, Float)-properFractionFloatInt (F# x) =-    if isTrue# (x `eqFloat#` 0.0#)-        then (I# 0#, F# 0.0#)-        else case float2Int# x of-                n -> (I# n, F# (x `minusFloat#` int2Float# n))---- truncateFloatInt = float2Int--floorFloatInt :: Float -> Int-floorFloatInt (F# x) =-    case float2Int# x of-      n | isTrue# (x `ltFloat#` int2Float# n) -> I# (n -# 1#)-        | otherwise                           -> I# n--ceilingFloatInt :: Float -> Int-ceilingFloatInt (F# x) =-    case float2Int# x of-      n | isTrue# (int2Float# n `ltFloat#` x) -> I# (n +# 1#)-        | otherwise                           -> I# n--roundFloatInt :: Float -> Int-roundFloatInt x = float2Int (c_rintFloat x)---- Functions with Integer results---- With the new code generator in GHC 7, the explicit bit-fiddling is--- slower than the old code for values of small modulus, but when the--- 'Int' range is left, the bit-fiddling quickly wins big, so we use that.--- If the methods are called on smallish values, hopefully people go--- through Int and not larger types.---- Note: For negative exponents, we must check the validity of the shift--- distance for the right shifts of the mantissa.--{-# INLINE properFractionFloatInteger #-}-properFractionFloatInteger :: Float -> (Integer, Float)-properFractionFloatInteger v@(F# x) =-    case decodeFloat_Int# x of-      (# m, e #)-        | isTrue# (e <# 0#) ->-          case negateInt# e of-            s | isTrue# (s ># 23#) -> (0, v)-              | isTrue# (m <#  0#) ->-                case negateInt# (negateInt# m `uncheckedIShiftRA#` s) of-                  k -> (smallInteger k,-                            case m -# (k `uncheckedIShiftL#` s) of-                              r -> F# (encodeFloatInteger (smallInteger r) e))-              | otherwise           ->-                case m `uncheckedIShiftRL#` s of-                  k -> (smallInteger k,-                            case m -# (k `uncheckedIShiftL#` s) of-                              r -> F# (encodeFloatInteger (smallInteger r) e))-        | otherwise -> (shiftLInteger (smallInteger m) e, F# 0.0#)--{-# INLINE truncateFloatInteger #-}-truncateFloatInteger :: Float -> Integer-truncateFloatInteger x =-    case properFractionFloatInteger x of-      (n, _) -> n---- floor is easier for negative numbers than truncate, so this gets its--- own implementation, it's a little faster.-{-# INLINE floorFloatInteger #-}-floorFloatInteger :: Float -> Integer-floorFloatInteger (F# x) =-    case decodeFloat_Int# x of-      (# m, e #)-        | isTrue# (e <# 0#) ->-          case negateInt# e of-            s | isTrue# (s ># 23#) -> if isTrue# (m <# 0#) then (-1) else 0-              | otherwise          -> smallInteger (m `uncheckedIShiftRA#` s)-        | otherwise -> shiftLInteger (smallInteger m) e---- ceiling x = -floor (-x)--- If giving this its own implementation is faster at all,--- it's only marginally so, hence we keep it short.-{-# INLINE ceilingFloatInteger #-}-ceilingFloatInteger :: Float -> Integer-ceilingFloatInteger (F# x) =-    negateInteger (floorFloatInteger (F# (negateFloat# x)))--{-# INLINE roundFloatInteger #-}-roundFloatInteger :: Float -> Integer-roundFloatInteger x = float2Integer (c_rintFloat x)-----------------------------------------------------------------------------------                              Double Methods                              ------------------------------------------------------------------------------------- Special Functions for Int, nice, easy and fast.--- They should be small enough to be inlined automatically.---- We have to test for ±0.0 to avoid returning -0.0 in the second--- component of the pair. Unfortunately the branching costs a lot--- of performance.-properFractionDoubleInt :: Double -> (Int, Double)-properFractionDoubleInt (D# x) =-    if isTrue# (x ==## 0.0##)-        then (I# 0#, D# 0.0##)-        else case double2Int# x of-                n -> (I# n, D# (x -## int2Double# n))---- truncateDoubleInt = double2Int--floorDoubleInt :: Double -> Int-floorDoubleInt (D# x) =-    case double2Int# x of-      n | isTrue# (x <## int2Double# n) -> I# (n -# 1#)-        | otherwise                     -> I# n--ceilingDoubleInt :: Double -> Int-ceilingDoubleInt (D# x) =-    case double2Int# x of-      n | isTrue# (int2Double# n <## x) -> I# (n +# 1#)-        | otherwise                     -> I# n--roundDoubleInt :: Double -> Int-roundDoubleInt x = double2Int (c_rintDouble x)---- Functions with Integer results---- The new Code generator isn't quite as good for the old 'Double' code--- as for the 'Float' code, so for 'Double' the bit-fiddling also wins--- when the values have small modulus.---- When the exponent is negative, all mantissae have less than 64 bits--- and the right shifting of sized types is much faster than that of--- 'Integer's, especially when we can---- Note: For negative exponents, we must check the validity of the shift--- distance for the right shifts of the mantissa.--{-# INLINE properFractionDoubleInteger #-}-properFractionDoubleInteger :: Double -> (Integer, Double)-properFractionDoubleInteger v@(D# x) =-    case decodeDoubleInteger x of-      (# m, e #)-        | isTrue# (e <# 0#) ->-          case negateInt# e of-            s | isTrue# (s ># 52#) -> (0, v)-              | m < 0                 ->-                case TO64 (negateInteger m) of-                  n ->-                    case n `uncheckedIShiftRA64#` s of-                      k ->-                        (FROM64 (NEGATE64 k),-                          case MINUS64 n (k `uncheckedIShiftL64#` s) of-                            r ->-                              D# (encodeDoubleInteger (FROM64 (NEGATE64 r)) e))-              | otherwise           ->-                case TO64 m of-                  n ->-                    case n `uncheckedIShiftRA64#` s of-                      k -> (FROM64 k,-                            case MINUS64 n (k `uncheckedIShiftL64#` s) of-                              r -> D# (encodeDoubleInteger (FROM64 r) e))-        | otherwise -> (shiftLInteger m e, D# 0.0##)--{-# INLINE truncateDoubleInteger #-}-truncateDoubleInteger :: Double -> Integer-truncateDoubleInteger x =-    case properFractionDoubleInteger x of-      (n, _) -> n---- floor is easier for negative numbers than truncate, so this gets its--- own implementation, it's a little faster.-{-# INLINE floorDoubleInteger #-}-floorDoubleInteger :: Double -> Integer-floorDoubleInteger (D# x) =-    case decodeDoubleInteger x of-      (# m, e #)-        | isTrue# (e <# 0#) ->-          case negateInt# e of-            s | isTrue# (s ># 52#) -> if m < 0 then (-1) else 0-              | otherwise          ->-                case TO64 m of-                  n -> FROM64 (n `uncheckedIShiftRA64#` s)-        | otherwise -> shiftLInteger m e--{-# INLINE ceilingDoubleInteger #-}-ceilingDoubleInteger :: Double -> Integer-ceilingDoubleInteger (D# x) =-    negateInteger (floorDoubleInteger (D# (negateDouble# x)))--{-# INLINE roundDoubleInteger #-}-roundDoubleInteger :: Double -> Integer-roundDoubleInteger x = double2Integer (c_rintDouble x)---- Wrappers around double2Int#, int2Double#, float2Int# and int2Float#,--- we need them here, so we move them from GHC.Float and re-export them--- explicitly from there.--double2Int :: Double -> Int-double2Int (D# x) = I# (double2Int# x)--int2Double :: Int -> Double-int2Double (I# i) = D# (int2Double# i)--float2Int :: Float -> Int-float2Int (F# x) = I# (float2Int# x)--int2Float :: Int -> Float-int2Float (I# i) = F# (int2Float# i)---- Quicker conversions from 'Double' and 'Float' to 'Integer',--- assuming the floating point value is integral.------ Note: Since the value is integral, the exponent can't be less than--- (-TYP_MANT_DIG), so we need not check the validity of the shift--- distance for the right shfts here.--{-# INLINE double2Integer #-}-double2Integer :: Double -> Integer-double2Integer (D# x) =-    case decodeDoubleInteger x of-      (# m, e #)-        | isTrue# (e <# 0#) ->-          case TO64 m of-            n -> FROM64 (n `uncheckedIShiftRA64#` negateInt# e)-        | otherwise -> shiftLInteger m e--{-# INLINE float2Integer #-}-float2Integer :: Float -> Integer-float2Integer (F# x) =-    case decodeFloat_Int# x of-      (# m, e #)-        | isTrue# (e <# 0#) -> smallInteger (m `uncheckedIShiftRA#` negateInt# e)-        | otherwise         -> shiftLInteger (smallInteger m) e---- Foreign imports, the rounding is done faster in C when the value--- isn't integral, so we call out for rounding. For values of large--- modulus, calling out to C is slower than staying in Haskell, but--- presumably 'round' is mostly called for values with smaller modulus,--- when calling out to C is a major win.--- For all other functions, calling out to C gives at most a marginal--- speedup for values of small modulus and is much slower than staying--- in Haskell for values of large modulus, so those are done in Haskell.--foreign import ccall unsafe "rintDouble"-    c_rintDouble :: Double -> Double--foreign import ccall unsafe "rintFloat"-    c_rintFloat :: Float -> Float-
− GHC/Foreign.hs
@@ -1,255 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Foreign--- Copyright   :  (c) The University of Glasgow, 2008-2011--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Foreign marshalling support for CStrings with configurable encodings-----------------------------------------------------------------------------------module GHC.Foreign (-    -- * C strings with a configurable encoding--    -- conversion of C strings into Haskell strings-    ---    peekCString,-    peekCStringLen,--    -- conversion of Haskell strings into C strings-    ---    newCString,-    newCStringLen,--    -- conversion of Haskell strings into C strings using temporary storage-    ---    withCString,-    withCStringLen,--    charIsRepresentable,-  ) where--import Foreign.Marshal.Array-import Foreign.C.Types-import Foreign.Ptr-import Foreign.Storable--import Data.Word---- Imports for the locale-encoding version of marshallers--import Data.Tuple (fst)-import Data.Maybe--import GHC.Show ( show )--import Foreign.Marshal.Alloc-import Foreign.ForeignPtr--import GHC.Debug-import GHC.List-import GHC.Num-import GHC.Base--import GHC.IO-import GHC.IO.Exception-import GHC.IO.Buffer-import GHC.IO.Encoding.Types---c_DEBUG_DUMP :: Bool-c_DEBUG_DUMP = False--putDebugMsg :: String -> IO ()-putDebugMsg | c_DEBUG_DUMP = debugLn-            | otherwise    = const (return ())----- These definitions are identical to those in Foreign.C.String, but copied in here to avoid a cycle:-type CString    = Ptr CChar-type CStringLen = (Ptr CChar, Int)---- exported functions--- ---------------------- | Marshal a NUL terminated C string into a Haskell string.----peekCString    :: TextEncoding -> CString -> IO String-peekCString enc cp = do-    sz <- lengthArray0 nUL cp-    peekEncodedCString enc (cp, sz * cCharSize)---- | Marshal a C string with explicit length into a Haskell string.----peekCStringLen           :: TextEncoding -> CStringLen -> IO String-peekCStringLen = peekEncodedCString---- | Marshal a Haskell string into a NUL terminated C string.------ * the Haskell string may /not/ contain any NUL characters------ * new storage is allocated for the C string and must be---   explicitly freed using 'Foreign.Marshal.Alloc.free' or---   'Foreign.Marshal.Alloc.finalizerFree'.----newCString :: TextEncoding -> String -> IO CString-newCString enc = liftM fst . newEncodedCString enc True---- | Marshal a Haskell string into a C string (ie, character array) with--- explicit length information.------ * new storage is allocated for the C string and must be---   explicitly freed using 'Foreign.Marshal.Alloc.free' or---   'Foreign.Marshal.Alloc.finalizerFree'.----newCStringLen     :: TextEncoding -> String -> IO CStringLen-newCStringLen enc = newEncodedCString enc False---- | Marshal a Haskell string into a NUL terminated C string using temporary--- storage.------ * the Haskell string may /not/ contain any NUL characters------ * the memory is freed when the subcomputation terminates (either---   normally or via an exception), so the pointer to the temporary---   storage must /not/ be used after this.----withCString :: TextEncoding -> String -> (CString -> IO a) -> IO a-withCString enc s act = withEncodedCString enc True s $ \(cp, _sz) -> act cp---- | Marshal a Haskell string into a C string (ie, character array)--- in temporary storage, with explicit length information.------ * the memory is freed when the subcomputation terminates (either---   normally or via an exception), so the pointer to the temporary---   storage must /not/ be used after this.----withCStringLen         :: TextEncoding -> String -> (CStringLen -> IO a) -> IO a-withCStringLen enc = withEncodedCString enc False----- | Determines whether a character can be accurately encoded in a 'CString'.------ Pretty much anyone who uses this function is in a state of sin because--- whether or not a character is encodable will, in general, depend on the--- context in which it occurs.-charIsRepresentable :: TextEncoding -> Char -> IO Bool-charIsRepresentable enc c = withCString enc [c] (fmap (== [c]) . peekCString enc) `catchException` (\e -> let _ = e :: IOException in return False)---- auxiliary definitions--- -------------------------- C's end of string character-nUL :: CChar-nUL  = 0---- Size of a CChar in bytes-cCharSize :: Int-cCharSize = sizeOf (undefined :: CChar)---{-# INLINE peekEncodedCString #-}-peekEncodedCString :: TextEncoding -- ^ Encoding of CString-                   -> CStringLen-                   -> IO String    -- ^ String in Haskell terms-peekEncodedCString (TextEncoding { mkTextDecoder = mk_decoder }) (p, sz_bytes)-  = bracket mk_decoder close $ \decoder -> do-      let chunk_size = sz_bytes `max` 1 -- Decode buffer chunk size in characters: one iteration only for ASCII-      from0 <- fmap (\fp -> bufferAdd sz_bytes (emptyBuffer fp sz_bytes ReadBuffer)) $ newForeignPtr_ (castPtr p)-      to <- newCharBuffer chunk_size WriteBuffer--      let go iteration from = do-            (why, from', to') <- encode decoder from to-            if isEmptyBuffer from'-             then-              -- No input remaining: @why@ will be InputUnderflow, but we don't care-              withBuffer to' $ peekArray (bufferElems to')-             else do-              -- Input remaining: what went wrong?-              putDebugMsg ("peekEncodedCString: " ++ show iteration ++ " " ++ show why)-              (from'', to'') <- case why of InvalidSequence -> recover decoder from' to' -- These conditions are equally bad because-                                            InputUnderflow  -> recover decoder from' to' -- they indicate malformed/truncated input-                                            OutputUnderflow -> return (from', to')       -- We will have more space next time round-              putDebugMsg ("peekEncodedCString: from " ++ summaryBuffer from ++ " " ++ summaryBuffer from' ++ " " ++ summaryBuffer from'')-              putDebugMsg ("peekEncodedCString: to " ++ summaryBuffer to ++ " " ++ summaryBuffer to' ++ " " ++ summaryBuffer to'')-              to_chars <- withBuffer to'' $ peekArray (bufferElems to'')-              fmap (to_chars++) $ go (iteration + 1) from''--      go (0 :: Int) from0--{-# INLINE withEncodedCString #-}-withEncodedCString :: TextEncoding         -- ^ Encoding of CString to create-                   -> Bool                 -- ^ Null-terminate?-                   -> String               -- ^ String to encode-                   -> (CStringLen -> IO a) -- ^ Worker that can safely use the allocated memory-                   -> IO a-withEncodedCString (TextEncoding { mkTextEncoder = mk_encoder }) null_terminate s act-  = bracket mk_encoder close $ \encoder -> withArrayLen s $ \sz p -> do-      from <- fmap (\fp -> bufferAdd sz (emptyBuffer fp sz ReadBuffer)) $ newForeignPtr_ p--      let go iteration to_sz_bytes = do-           putDebugMsg ("withEncodedCString: " ++ show iteration)-           allocaBytes to_sz_bytes $ \to_p -> do-            mb_res <- tryFillBufferAndCall encoder null_terminate from to_p to_sz_bytes act-            case mb_res of-              Nothing  -> go (iteration + 1) (to_sz_bytes * 2)-              Just res -> return res--      -- If the input string is ASCII, this value will ensure we only allocate once-      go (0 :: Int) (cCharSize * (sz + 1))--{-# INLINE newEncodedCString #-}-newEncodedCString :: TextEncoding  -- ^ Encoding of CString to create-                  -> Bool          -- ^ Null-terminate?-                  -> String        -- ^ String to encode-                  -> IO CStringLen-newEncodedCString (TextEncoding { mkTextEncoder = mk_encoder }) null_terminate s-  = bracket mk_encoder close $ \encoder -> withArrayLen s $ \sz p -> do-      from <- fmap (\fp -> bufferAdd sz (emptyBuffer fp sz ReadBuffer)) $ newForeignPtr_ p--      let go iteration to_p to_sz_bytes = do-           putDebugMsg ("newEncodedCString: " ++ show iteration)-           mb_res <- tryFillBufferAndCall encoder null_terminate from to_p to_sz_bytes return-           case mb_res of-             Nothing  -> do-                 let to_sz_bytes' = to_sz_bytes * 2-                 to_p' <- reallocBytes to_p to_sz_bytes'-                 go (iteration + 1) to_p' to_sz_bytes'-             Just res -> return res--      -- If the input string is ASCII, this value will ensure we only allocate once-      let to_sz_bytes = cCharSize * (sz + 1)-      to_p <- mallocBytes to_sz_bytes-      go (0 :: Int) to_p to_sz_bytes---tryFillBufferAndCall :: TextEncoder dstate -> Bool -> Buffer Char -> Ptr Word8 -> Int-                     -> (CStringLen -> IO a) -> IO (Maybe a)-tryFillBufferAndCall encoder null_terminate from0 to_p to_sz_bytes act = do-    to_fp <- newForeignPtr_ to_p-    go (0 :: Int) (from0, emptyBuffer to_fp to_sz_bytes WriteBuffer)-  where-    go iteration (from, to) = do-      (why, from', to') <- encode encoder from to-      putDebugMsg ("tryFillBufferAndCall: " ++ show iteration ++ " " ++ show why ++ " " ++ summaryBuffer from ++ " " ++ summaryBuffer from')-      if isEmptyBuffer from'-       then if null_terminate && bufferAvailable to' == 0-             then return Nothing -- We had enough for the string but not the terminator: ask the caller for more buffer-             else do-               -- Awesome, we had enough buffer-               let bytes = bufferElems to'-               withBuffer to' $ \to_ptr -> do-                   when null_terminate $ pokeElemOff to_ptr (bufR to') 0-                   fmap Just $ act (castPtr to_ptr, bytes) -- NB: the length information is specified as being in *bytes*-       else case why of -- We didn't consume all of the input-              InputUnderflow  -> recover encoder from' to' >>= go (iteration + 1) -- These conditions are equally bad-              InvalidSequence -> recover encoder from' to' >>= go (iteration + 1) -- since the input was truncated/invalid-              OutputUnderflow -> return Nothing -- Oops, out of buffer during decoding: ask the caller for more-
− GHC/ForeignPtr.hs
@@ -1,444 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude-           , BangPatterns-           , MagicHash-           , UnboxedTuples-  #-}-{-# OPTIONS_HADDOCK hide #-}-{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.ForeignPtr--- Copyright   :  (c) The University of Glasgow, 1992-2003--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ GHC's implementation of the 'ForeignPtr' data type.-----------------------------------------------------------------------------------module GHC.ForeignPtr-  (-        ForeignPtr(..),-        ForeignPtrContents(..),-        FinalizerPtr,-        FinalizerEnvPtr,-        newForeignPtr_,-        mallocForeignPtr,-        mallocPlainForeignPtr,-        mallocForeignPtrBytes,-        mallocPlainForeignPtrBytes,-        mallocForeignPtrAlignedBytes,-        mallocPlainForeignPtrAlignedBytes,-        addForeignPtrFinalizer,-        addForeignPtrFinalizerEnv,-        touchForeignPtr,-        unsafeForeignPtrToPtr,-        castForeignPtr,-        newConcForeignPtr,-        addForeignPtrConcFinalizer,-        finalizeForeignPtr-  ) where--import Foreign.Storable-import Data.Foldable    ( sequence_ )-import Data.Typeable--import GHC.Show-import GHC.Base-import GHC.IORef-import GHC.STRef        ( STRef(..) )-import GHC.Ptr          ( Ptr(..), FunPtr(..) )---- |The type 'ForeignPtr' represents references to objects that are--- maintained in a foreign language, i.e., that are not part of the--- data structures usually managed by the Haskell storage manager.--- The essential difference between 'ForeignPtr's and vanilla memory--- references of type @Ptr a@ is that the former may be associated--- with /finalizers/. A finalizer is a routine that is invoked when--- the Haskell storage manager detects that - within the Haskell heap--- and stack - there are no more references left that are pointing to--- the 'ForeignPtr'.  Typically, the finalizer will, then, invoke--- routines in the foreign language that free the resources bound by--- the foreign object.------ The 'ForeignPtr' is parameterised in the same way as 'Ptr'.  The--- type argument of 'ForeignPtr' should normally be an instance of--- class 'Storable'.----data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents-                    deriving Typeable-        -- we cache the Addr# in the ForeignPtr object, but attach-        -- the finalizer to the IORef (or the MutableByteArray# in-        -- the case of a MallocPtr).  The aim of the representation-        -- is to make withForeignPtr efficient; in fact, withForeignPtr-        -- should be just as efficient as unpacking a Ptr, and multiple-        -- withForeignPtrs can share an unpacked ForeignPtr.  Note-        -- that touchForeignPtr only has to touch the ForeignPtrContents-        -- object, because that ensures that whatever the finalizer is-        -- attached to is kept alive.--data Finalizers-  = NoFinalizers-  | CFinalizers (Weak# ())-  | HaskellFinalizers [IO ()]--data ForeignPtrContents-  = PlainForeignPtr !(IORef Finalizers)-  | MallocPtr      (MutableByteArray# RealWorld) !(IORef Finalizers)-  | PlainPtr       (MutableByteArray# RealWorld)--instance Eq (ForeignPtr a) where-    p == q  =  unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q--instance Ord (ForeignPtr a) where-    compare p q  =  compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)--instance Show (ForeignPtr a) where-    showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)----- |A finalizer is represented as a pointer to a foreign function that, at--- finalisation time, gets as an argument a plain pointer variant of the--- foreign pointer that the finalizer is associated with.------ Note that the foreign function /must/ use the @ccall@ calling convention.----type FinalizerPtr a        = FunPtr (Ptr a -> IO ())-type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())--newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)------ ^Turns a plain memory reference into a foreign object by--- associating a finalizer - given by the monadic operation - with the--- reference.  The storage manager will start the finalizer, in a--- separate thread, some time after the last reference to the--- @ForeignPtr@ is dropped.  There is no guarantee of promptness, and--- in fact there is no guarantee that the finalizer will eventually--- run at all.------ Note that references from a finalizer do not necessarily prevent--- another object from being finalized.  If A's finalizer refers to B--- (perhaps using 'touchForeignPtr', then the only guarantee is that--- B's finalizer will never be started before A's.  If both A and B--- are unreachable, then both finalizers will start together.  See--- 'touchForeignPtr' for more on finalizer ordering.----newConcForeignPtr p finalizer-  = do fObj <- newForeignPtr_ p-       addForeignPtrConcFinalizer fObj finalizer-       return fObj--mallocForeignPtr :: Storable a => IO (ForeignPtr a)--- ^ Allocate some memory and return a 'ForeignPtr' to it.  The memory--- will be released automatically when the 'ForeignPtr' is discarded.------ 'mallocForeignPtr' is equivalent to------ >    do { p <- malloc; newForeignPtr finalizerFree p }------ although it may be implemented differently internally: you may not--- assume that the memory returned by 'mallocForeignPtr' has been--- allocated with 'Foreign.Marshal.Alloc.malloc'.------ GHC notes: 'mallocForeignPtr' has a heavily optimised--- implementation in GHC.  It uses pinned memory in the garbage--- collected heap, so the 'ForeignPtr' does not require a finalizer to--- free the memory.  Use of 'mallocForeignPtr' and associated--- functions is strongly recommended in preference to 'newForeignPtr'--- with a finalizer.----mallocForeignPtr = doMalloc undefined-  where doMalloc :: Storable b => b -> IO (ForeignPtr b)-        doMalloc a-          | I# size < 0 = error "mallocForeignPtr: size must be >= 0"-          | otherwise = do-          r <- newIORef NoFinalizers-          IO $ \s ->-            case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->-             (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))-                               (MallocPtr mbarr# r) #)-            }-            where !(I# size)  = sizeOf a-                  !(I# align) = alignment a---- | This function is similar to 'mallocForeignPtr', except that the--- size of the memory required is given explicitly as a number of bytes.-mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)-mallocForeignPtrBytes size | size < 0 =-  error "mallocForeignPtrBytes: size must be >= 0"-mallocForeignPtrBytes (I# size) = do-  r <- newIORef NoFinalizers-  IO $ \s ->-     case newPinnedByteArray# size s      of { (# s', mbarr# #) ->-       (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))-                         (MallocPtr mbarr# r) #)-     }---- | This function is similar to 'mallocForeignPtrBytes', except that the--- size and alignment of the memory required is given explicitly as numbers of--- bytes.-mallocForeignPtrAlignedBytes :: Int -> Int -> IO (ForeignPtr a)-mallocForeignPtrAlignedBytes size _align | size < 0 =-  error "mallocForeignPtrAlignedBytes: size must be >= 0"-mallocForeignPtrAlignedBytes (I# size) (I# align) = do-  r <- newIORef NoFinalizers-  IO $ \s ->-     case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->-       (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))-                         (MallocPtr mbarr# r) #)-     }---- | Allocate some memory and return a 'ForeignPtr' to it.  The memory--- will be released automatically when the 'ForeignPtr' is discarded.------ GHC notes: 'mallocPlainForeignPtr' has a heavily optimised--- implementation in GHC.  It uses pinned memory in the garbage--- collected heap, as for mallocForeignPtr. Unlike mallocForeignPtr, a--- ForeignPtr created with mallocPlainForeignPtr carries no finalizers.--- It is not possible to add a finalizer to a ForeignPtr created with--- mallocPlainForeignPtr. This is useful for ForeignPtrs that will live--- only inside Haskell (such as those created for packed strings).--- Attempts to add a finalizer to a ForeignPtr created this way, or to--- finalize such a pointer, will throw an exception.----mallocPlainForeignPtr :: Storable a => IO (ForeignPtr a)-mallocPlainForeignPtr = doMalloc undefined-  where doMalloc :: Storable b => b -> IO (ForeignPtr b)-        doMalloc a-          | I# size < 0 = error "mallocForeignPtr: size must be >= 0"-          | otherwise = IO $ \s ->-            case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->-             (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))-                               (PlainPtr mbarr#) #)-            }-            where !(I# size)  = sizeOf a-                  !(I# align) = alignment a---- | This function is similar to 'mallocForeignPtrBytes', except that--- the internally an optimised ForeignPtr representation with no--- finalizer is used. Attempts to add a finalizer will cause an--- exception to be thrown.-mallocPlainForeignPtrBytes :: Int -> IO (ForeignPtr a)-mallocPlainForeignPtrBytes size | size < 0 =-  error "mallocPlainForeignPtrBytes: size must be >= 0"-mallocPlainForeignPtrBytes (I# size) = IO $ \s ->-    case newPinnedByteArray# size s      of { (# s', mbarr# #) ->-       (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))-                         (PlainPtr mbarr#) #)-     }---- | This function is similar to 'mallocForeignPtrAlignedBytes', except that--- the internally an optimised ForeignPtr representation with no--- finalizer is used. Attempts to add a finalizer will cause an--- exception to be thrown.-mallocPlainForeignPtrAlignedBytes :: Int -> Int -> IO (ForeignPtr a)-mallocPlainForeignPtrAlignedBytes size _align | size < 0 =-  error "mallocPlainForeignPtrAlignedBytes: size must be >= 0"-mallocPlainForeignPtrAlignedBytes (I# size) (I# align) = IO $ \s ->-    case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->-       (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))-                         (PlainPtr mbarr#) #)-     }--addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()--- ^This function adds a finalizer to the given foreign object.  The--- finalizer will run /before/ all other finalizers for the same--- object which have already been registered.-addForeignPtrFinalizer (FunPtr fp) (ForeignPtr p c) = case c of-  PlainForeignPtr r -> insertCFinalizer r fp 0# nullAddr# p ()-  MallocPtr     _ r -> insertCFinalizer r fp 0# nullAddr# p c-  _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"---- Note [MallocPtr finalizers] (#10904)------ When we have C finalizers for a MallocPtr, the memory is--- heap-resident and would normally be recovered by the GC before the--- finalizers run.  To prevent the memory from being reused too early,--- we attach the MallocPtr constructor to the "value" field of the--- weak pointer when we call mkWeak# in ensureCFinalizerWeak below.--- The GC will keep this field alive until the finalizers have run.--addForeignPtrFinalizerEnv ::-  FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()--- ^ Like 'addForeignPtrFinalizerEnv' but allows the finalizer to be--- passed an additional environment parameter to be passed to the--- finalizer.  The environment passed to the finalizer is fixed by the--- second argument to 'addForeignPtrFinalizerEnv'-addForeignPtrFinalizerEnv (FunPtr fp) (Ptr ep) (ForeignPtr p c) = case c of-  PlainForeignPtr r -> insertCFinalizer r fp 1# ep p ()-  MallocPtr     _ r -> insertCFinalizer r fp 1# ep p c-  _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"--addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()--- ^This function adds a finalizer to the given @ForeignPtr@.  The--- finalizer will run /before/ all other finalizers for the same--- object which have already been registered.------ This is a variant of @addForeignPtrFinalizer@, where the finalizer--- is an arbitrary @IO@ action.  When it is invoked, the finalizer--- will run in a new thread.------ NB. Be very careful with these finalizers.  One common trap is that--- if a finalizer references another finalized value, it does not--- prevent that value from being finalized.  In particular, 'Handle's--- are finalized objects, so a finalizer should not refer to a 'Handle'--- (including @stdout@, @stdin@ or @stderr@).----addForeignPtrConcFinalizer (ForeignPtr _ c) finalizer =-  addForeignPtrConcFinalizer_ c finalizer--addForeignPtrConcFinalizer_ :: ForeignPtrContents -> IO () -> IO ()-addForeignPtrConcFinalizer_ (PlainForeignPtr r) finalizer = do-  noFinalizers <- insertHaskellFinalizer r finalizer-  if noFinalizers-     then IO $ \s ->-              case r of { IORef (STRef r#) ->-              case mkWeak# r# () (foreignPtrFinalizer r) s of {  (# s1, _ #) ->-              (# s1, () #) }}-     else return ()-addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do-  noFinalizers <- insertHaskellFinalizer r finalizer-  if noFinalizers-     then  IO $ \s ->-               case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of-                  (# s1, _ #) -> (# s1, () #)-     else return ()--addForeignPtrConcFinalizer_ _ _ =-  error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"--insertHaskellFinalizer :: IORef Finalizers -> IO () -> IO Bool-insertHaskellFinalizer r f = do-  !wasEmpty <- atomicModifyIORef r $ \finalizers -> case finalizers of-      NoFinalizers -> (HaskellFinalizers [f], True)-      HaskellFinalizers fs -> (HaskellFinalizers (f:fs), False)-      _ -> noMixingError-  return wasEmpty---- | A box around Weak#, private to this module.-data MyWeak = MyWeak (Weak# ())--insertCFinalizer ::-  IORef Finalizers -> Addr# -> Int# -> Addr# -> Addr# -> value -> IO ()-insertCFinalizer r fp flag ep p val = do-  MyWeak w <- ensureCFinalizerWeak r val-  IO $ \s -> case addCFinalizerToWeak# fp p flag ep w s of-      (# s1, 1# #) -> (# s1, () #)--      -- Failed to add the finalizer because some other thread-      -- has finalized w by calling foreignPtrFinalizer. We retry now.-      -- This won't be an infinite loop because that thread must have-      -- replaced the content of r before calling finalizeWeak#.-      (# s1, _ #) -> unIO (insertCFinalizer r fp flag ep p val) s1--ensureCFinalizerWeak :: IORef Finalizers -> value -> IO MyWeak-ensureCFinalizerWeak ref@(IORef (STRef r#)) value = do-  fin <- readIORef ref-  case fin of-      CFinalizers weak -> return (MyWeak weak)-      HaskellFinalizers{} -> noMixingError-      NoFinalizers -> IO $ \s ->-          case mkWeakNoFinalizer# r# (unsafeCoerce# value) s of { (# s1, w #) ->-             -- See Note [MallocPtr finalizers] (#10904)-          case atomicModifyMutVar# r# (update w) s1 of-              { (# s2, (weak, needKill ) #) ->-          if needKill-            then case finalizeWeak# w s2 of { (# s3, _, _ #) ->-              (# s3, weak #) }-            else (# s2, weak #) }}-  where-      update _ fin@(CFinalizers w) = (fin, (MyWeak w, True))-      update w NoFinalizers = (CFinalizers w, (MyWeak w, False))-      update _ _ = noMixingError--noMixingError :: a-noMixingError = error $-   "GHC.ForeignPtr: attempt to mix Haskell and C finalizers " ++-   "in the same ForeignPtr"--foreignPtrFinalizer :: IORef Finalizers -> IO ()-foreignPtrFinalizer r = do-  fs <- atomicModifyIORef r $ \fs -> (NoFinalizers, fs) -- atomic, see #7170-  case fs of-    NoFinalizers -> return ()-    CFinalizers w -> IO $ \s -> case finalizeWeak# w s of-        (# s1, 1#, f #) -> f s1-        (# s1, _, _ #) -> (# s1, () #)-    HaskellFinalizers actions -> sequence_ actions--newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)--- ^Turns a plain memory reference into a foreign pointer that may be--- associated with finalizers by using 'addForeignPtrFinalizer'.-newForeignPtr_ (Ptr obj) =  do-  r <- newIORef NoFinalizers-  return (ForeignPtr obj (PlainForeignPtr r))--touchForeignPtr :: ForeignPtr a -> IO ()--- ^This function ensures that the foreign object in--- question is alive at the given place in the sequence of IO--- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'--- does a 'touchForeignPtr' after it--- executes the user action.------ Note that this function should not be used to express dependencies--- between finalizers on 'ForeignPtr's.  For example, if the finalizer--- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second--- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer--- for @F2@ is never started before the finalizer for @F1@.  They--- might be started together if for example both @F1@ and @F2@ are--- otherwise unreachable, and in that case the scheduler might end up--- running the finalizer for @F2@ first.------ In general, it is not recommended to use finalizers on separate--- objects with ordering constraints between them.  To express the--- ordering robustly requires explicit synchronisation using @MVar@s--- between the finalizers, but even then the runtime sometimes runs--- multiple finalizers sequentially in a single thread (for--- performance reasons), so synchronisation between finalizers could--- result in artificial deadlock.  Another alternative is to use--- explicit reference counting.----touchForeignPtr (ForeignPtr _ r) = touch r--touch :: ForeignPtrContents -> IO ()-touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)--unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a--- ^This function extracts the pointer component of a foreign--- pointer.  This is a potentially dangerous operations, as if the--- argument to 'unsafeForeignPtrToPtr' is the last usage--- occurrence of the given foreign pointer, then its finalizer(s) will--- be run, which potentially invalidates the plain pointer just--- obtained.  Hence, 'touchForeignPtr' must be used--- wherever it has to be guaranteed that the pointer lives on - i.e.,--- has another usage occurrence.------ To avoid subtle coding errors, hand written marshalling code--- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather--- than combinations of 'unsafeForeignPtrToPtr' and--- 'touchForeignPtr'.  However, the latter routines--- are occasionally preferred in tool generated marshalling code.-unsafeForeignPtrToPtr (ForeignPtr fo _) = Ptr fo--castForeignPtr :: ForeignPtr a -> ForeignPtr b--- ^This function casts a 'ForeignPtr'--- parameterised by one type into another type.-castForeignPtr f = unsafeCoerce# f---- | Causes the finalizers associated with a foreign pointer to be run--- immediately.-finalizeForeignPtr :: ForeignPtr a -> IO ()-finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect-finalizeForeignPtr (ForeignPtr _ foreignPtr) = foreignPtrFinalizer refFinalizers-        where-                refFinalizers = case foreignPtr of-                        (PlainForeignPtr ref) -> ref-                        (MallocPtr     _ ref) -> ref-                        PlainPtr _            ->-                            error "finalizeForeignPtr PlainPtr"-
− GHC/GHCi.hs
@@ -1,50 +0,0 @@-{-# LANGUAGE NoImplicitPrelude #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.GHCi--- Copyright   :  (c) The University of Glasgow 2012--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The GHCi Monad lifting interface.------ EXPERIMENTAL! DON'T USE.-----------------------------------------------------------------------------------module GHC.GHCi {-# WARNING "This is an unstable interface." #-} (-        GHCiSandboxIO(..), NoIO()-    ) where--import GHC.Base (IO(), Monad, Functor(fmap), Applicative(..), (>>=), return, id, (.), ap)---- | A monad that can execute GHCi statements by lifting them out of--- m into the IO monad. (e.g state monads)-class (Monad m) => GHCiSandboxIO m where-    ghciStepIO :: m a -> IO a--instance GHCiSandboxIO IO where-    ghciStepIO = id---- | A monad that doesn't allow any IO.-newtype NoIO a = NoIO { noio :: IO a }--instance Functor NoIO where-  fmap f (NoIO a) = NoIO (fmap f a)--instance Applicative NoIO where-  pure  = return-  (<*>) = ap--instance Monad NoIO where-    return a  = NoIO (return a)-    (>>=) k f = NoIO (noio k >>= noio . f)--instance GHCiSandboxIO NoIO where-    ghciStepIO = noio-
− GHC/Generics.hs
@@ -1,819 +0,0 @@-{-# LANGUAGE Trustworthy            #-}-{-# LANGUAGE CPP                    #-}-{-# LANGUAGE NoImplicitPrelude      #-}-{-# LANGUAGE TypeSynonymInstances   #-}-{-# LANGUAGE TypeOperators          #-}-{-# LANGUAGE KindSignatures         #-}-{-# LANGUAGE TypeFamilies           #-}-{-# LANGUAGE StandaloneDeriving     #-}-{-# LANGUAGE DeriveGeneric          #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Generics--- Copyright   :  (c) Universiteit Utrecht 2010-2011, University of Oxford 2012-2013--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ @since 4.6.0.0------ If you're using @GHC.Generics@, you should consider using the--- <http://hackage.haskell.org/package/generic-deriving> package, which--- contains many useful generic functions.--module GHC.Generics  (--- * Introduction------ |------ Datatype-generic functions are are based on the idea of converting values of--- a datatype @T@ into corresponding values of a (nearly) isomorphic type @'Rep' T@.--- The type @'Rep' T@ is--- built from a limited set of type constructors, all provided by this module. A--- datatype-generic function is then an overloaded function with instances--- for most of these type constructors, together with a wrapper that performs--- the mapping between @T@ and @'Rep' T@. By using this technique, we merely need--- a few generic instances in order to implement functionality that works for any--- representable type.------ Representable types are collected in the 'Generic' class, which defines the--- associated type 'Rep' as well as conversion functions 'from' and 'to'.--- Typically, you will not define 'Generic' instances by hand, but have the compiler--- derive them for you.---- ** Representing datatypes------ |------ The key to defining your own datatype-generic functions is to understand how to--- represent datatypes using the given set of type constructors.------ Let us look at an example first:------ @--- data Tree a = Leaf a | Node (Tree a) (Tree a)---   deriving 'Generic'--- @------ The above declaration (which requires the language pragma @DeriveGeneric@)--- causes the following representation to be generated:------ @--- instance 'Generic' (Tree a) where---   type 'Rep' (Tree a) =---     'D1' D1Tree---       ('C1' C1_0Tree---          ('S1' 'NoSelector' ('Par0' a))---        ':+:'---        'C1' C1_1Tree---          ('S1' 'NoSelector' ('Rec0' (Tree a))---           ':*:'---           'S1' 'NoSelector' ('Rec0' (Tree a))))---   ...--- @------ /Hint:/ You can obtain information about the code being generated from GHC by passing--- the @-ddump-deriv@ flag. In GHCi, you can expand a type family such as 'Rep' using--- the @:kind!@ command.----#if 0--- /TODO:/ Newer GHC versions abandon the distinction between 'Par0' and 'Rec0' and will--- use 'Rec0' everywhere.----#endif--- This is a lot of information! However, most of it is actually merely meta-information--- that makes names of datatypes and constructors and more available on the type level.------ Here is a reduced representation for 'Tree' with nearly all meta-information removed,--- for now keeping only the most essential aspects:------ @--- instance 'Generic' (Tree a) where---   type 'Rep' (Tree a) =---     'Par0' a---     ':+:'---     ('Rec0' (Tree a) ':*:' 'Rec0' (Tree a))--- @------ The @Tree@ datatype has two constructors. The representation of individual constructors--- is combined using the binary type constructor ':+:'.------ The first constructor consists of a single field, which is the parameter @a@. This is--- represented as @'Par0' a@.------ The second constructor consists of two fields. Each is a recursive field of type @Tree a@,--- represented as @'Rec0' (Tree a)@. Representations of individual fields are combined using--- the binary type constructor ':*:'.------ Now let us explain the additional tags being used in the complete representation:------    * The @'S1' 'NoSelector'@ indicates that there is no record field selector associated with---      this field of the constructor.------    * The @'C1' C1_0Tree@ and @'C1' C1_1Tree@ invocations indicate that the enclosed part is---      the representation of the first and second constructor of datatype @Tree@, respectively.---      Here, @C1_0Tree@ and @C1_1Tree@ are datatypes generated by the compiler as part of---      @deriving 'Generic'@. These datatypes are proxy types with no values. They are useful---      because they are instances of the type class 'Constructor'. This type class can be used---      to obtain information about the constructor in question, such as its name---      or infix priority.------    * The @'D1' D1Tree@ tag indicates that the enclosed part is the representation of the---      datatype @Tree@. Again, @D1Tree@ is a datatype generated by the compiler. It is a---      proxy type, and is useful by being an instance of class 'Datatype', which---      can be used to obtain the name of a datatype, the module it has been defined in, and---      whether it has been defined using @data@ or @newtype@.---- ** Derived and fundamental representation types------ |------ There are many datatype-generic functions that do not distinguish between positions that--- are parameters or positions that are recursive calls. There are also many datatype-generic--- functions that do not care about the names of datatypes and constructors at all. To keep--- the number of cases to consider in generic functions in such a situation to a minimum,--- it turns out that many of the type constructors introduced above are actually synonyms,--- defining them to be variants of a smaller set of constructors.---- *** Individual fields of constructors: 'K1'------ |------ The type constructors 'Par0' and 'Rec0' are variants of 'K1':------ @--- type 'Par0' = 'K1' 'P'--- type 'Rec0' = 'K1' 'R'--- @------ Here, 'P' and 'R' are type-level proxies again that do not have any associated values.---- *** Meta information: 'M1'------ |------ The type constructors 'S1', 'C1' and 'D1' are all variants of 'M1':------ @--- type 'S1' = 'M1' 'S'--- type 'C1' = 'M1' 'C'--- type 'D1' = 'M1' 'D'--- @------ The types 'S', 'C' and 'D' are once again type-level proxies, just used to create--- several variants of 'M1'.---- *** Additional generic representation type constructors------ |------ Next to 'K1', 'M1', ':+:' and ':*:' there are a few more type constructors that occur--- in the representations of other datatypes.---- **** Empty datatypes: 'V1'------ |------ For empty datatypes, 'V1' is used as a representation. For example,------ @--- data Empty deriving 'Generic'--- @------ yields------ @--- instance 'Generic' Empty where---   type 'Rep' Empty = 'D1' D1Empty 'V1'--- @---- **** Constructors without fields: 'U1'------ |------ If a constructor has no arguments, then 'U1' is used as its representation. For example--- the representation of 'Bool' is------ @--- instance 'Generic' Bool where---   type 'Rep' Bool =---     'D1' D1Bool---       ('C1' C1_0Bool 'U1' ':+:' 'C1' C1_1Bool 'U1')--- @---- *** Representation of types with many constructors or many fields------ |------ As ':+:' and ':*:' are just binary operators, one might ask what happens if the--- datatype has more than two constructors, or a constructor with more than two--- fields. The answer is simple: the operators are used several times, to combine--- all the constructors and fields as needed. However, users /should not rely on--- a specific nesting strategy/ for ':+:' and ':*:' being used. The compiler is--- free to choose any nesting it prefers. (In practice, the current implementation--- tries to produce a more or less balanced nesting, so that the traversal of the--- structure of the datatype from the root to a particular component can be performed--- in logarithmic rather than linear time.)---- ** Defining datatype-generic functions------ |------ A datatype-generic function comprises two parts:------    1. /Generic instances/ for the function, implementing it for most of the representation---       type constructors introduced above.------    2. A /wrapper/ that for any datatype that is in `Generic`, performs the conversion---       between the original value and its `Rep`-based representation and then invokes the---       generic instances.------ As an example, let us look at a function 'encode' that produces a naive, but lossless--- bit encoding of values of various datatypes. So we are aiming to define a function------ @--- encode :: 'Generic' a => a -> [Bool]--- @------ where we use 'Bool' as our datatype for bits.------ For part 1, we define a class @Encode'@. Perhaps surprisingly, this class is parameterized--- over a type constructor @f@ of kind @* -> *@. This is a technicality: all the representation--- type constructors operate with kind @* -> *@ as base kind. But the type argument is never--- being used. This may be changed at some point in the future. The class has a single method,--- and we use the type we want our final function to have, but we replace the occurrences of--- the generic type argument @a@ with @f p@ (where the @p@ is any argument; it will not be used).------ > class Encode' f where--- >   encode' :: f p -> [Bool]------ With the goal in mind to make @encode@ work on @Tree@ and other datatypes, we now define--- instances for the representation type constructors 'V1', 'U1', ':+:', ':*:', 'K1', and 'M1'.---- *** Definition of the generic representation types------ |------ In order to be able to do this, we need to know the actual definitions of these types:------ @--- data    'V1'        p                       -- lifted version of Empty--- data    'U1'        p = 'U1'                  -- lifted version of ()--- data    (':+:') f g p = 'L1' (f p) | 'R1' (g p) -- lifted version of 'Either'--- data    (':*:') f g p = (f p) ':*:' (g p)     -- lifted version of (,)--- newtype 'K1'    i c p = 'K1' { 'unK1' :: c }    -- a container for a c--- newtype 'M1'  i t f p = 'M1' { 'unM1' :: f p }  -- a wrapper--- @------ So, 'U1' is just the unit type, ':+:' is just a binary choice like 'Either',--- ':*:' is a binary pair like the pair constructor @(,)@, and 'K1' is a value--- of a specific type @c@, and 'M1' wraps a value of the generic type argument,--- which in the lifted world is an @f p@ (where we do not care about @p@).---- *** Generic instances------ |------ The instance for 'V1' is slightly awkward (but also rarely used):------ @--- instance Encode' 'V1' where---   encode' x = undefined--- @------ There are no values of type @V1 p@ to pass (except undefined), so this is--- actually impossible. One can ask why it is useful to define an instance for--- 'V1' at all in this case? Well, an empty type can be used as an argument to--- a non-empty type, and you might still want to encode the resulting type.--- As a somewhat contrived example, consider @[Empty]@, which is not an empty--- type, but contains just the empty list. The 'V1' instance ensures that we--- can call the generic function on such types.------ There is exactly one value of type 'U1', so encoding it requires no--- knowledge, and we can use zero bits:------ @--- instance Encode' 'U1' where---   encode' 'U1' = []--- @------ In the case for ':+:', we produce 'False' or 'True' depending on whether--- the constructor of the value provided is located on the left or on the right:------ @--- instance (Encode' f, Encode' g) => Encode' (f ':+:' g) where---   encode' ('L1' x) = False : encode' x---   encode' ('R1' x) = True  : encode' x--- @------ In the case for ':*:', we append the encodings of the two subcomponents:------ @--- instance (Encode' f, Encode' g) => Encode' (f ':*:' g) where---   encode' (x ':*:' y) = encode' x ++ encode' y--- @------ The case for 'K1' is rather interesting. Here, we call the final function--- 'encode' that we yet have to define, recursively. We will use another type--- class 'Encode' for that function:------ @--- instance (Encode c) => Encode' ('K1' i c) where---   encode' ('K1' x) = encode x--- @------ Note how 'Par0' and 'Rec0' both being mapped to 'K1' allows us to define--- a uniform instance here.------ Similarly, we can define a uniform instance for 'M1', because we completely--- disregard all meta-information:------ @--- instance (Encode' f) => Encode' ('M1' i t f) where---   encode' ('M1' x) = encode' x--- @------ Unlike in 'K1', the instance for 'M1' refers to 'encode'', not 'encode'.---- *** The wrapper and generic default------ |------ We now define class 'Encode' for the actual 'encode' function:------ @--- class Encode a where---   encode :: a -> [Bool]---   default encode :: ('Generic' a) => a -> [Bool]---   encode x = encode' ('from' x)--- @------ The incoming 'x' is converted using 'from', then we dispatch to the--- generic instances using 'encode''. We use this as a default definition--- for 'encode'. We need the 'default encode' signature because ordinary--- Haskell default methods must not introduce additional class constraints,--- but our generic default does.------ Defining a particular instance is now as simple as saying------ @--- instance (Encode a) => Encode (Tree a)--- @----#if 0--- /TODO:/ Add usage example?----#endif--- The generic default is being used. In the future, it will hopefully be--- possible to use @deriving Encode@ as well, but GHC does not yet support--- that syntax for this situation.------ Having 'Encode' as a class has the advantage that we can define--- non-generic special cases, which is particularly useful for abstract--- datatypes that have no structural representation. For example, given--- a suitable integer encoding function 'encodeInt', we can define------ @--- instance Encode Int where---   encode = encodeInt--- @---- *** Omitting generic instances------ |------ It is not always required to provide instances for all the generic--- representation types, but omitting instances restricts the set of--- datatypes the functions will work for:------    * If no ':+:' instance is given, the function may still work for---      empty datatypes or datatypes that have a single constructor,---      but will fail on datatypes with more than one constructor.------    * If no ':*:' instance is given, the function may still work for---      datatypes where each constructor has just zero or one field,---      in particular for enumeration types.------    * If no 'K1' instance is given, the function may still work for---      enumeration types, where no constructor has any fields.------    * If no 'V1' instance is given, the function may still work for---      any datatype that is not empty.------    * If no 'U1' instance is given, the function may still work for---      any datatype where each constructor has at least one field.------ An 'M1' instance is always required (but it can just ignore the--- meta-information, as is the case for 'encode' above).-#if 0--- *** Using meta-information------ |------ TODO-#endif--- ** Generic constructor classes------ |------ Datatype-generic functions as defined above work for a large class--- of datatypes, including parameterized datatypes. (We have used 'Tree'--- as our example above, which is of kind @* -> *@.) However, the--- 'Generic' class ranges over types of kind @*@, and therefore, the--- resulting generic functions (such as 'encode') must be parameterized--- by a generic type argument of kind @*@.------ What if we want to define generic classes that range over type--- constructors (such as 'Functor', 'Traversable', or 'Foldable')?---- *** The 'Generic1' class------ |------ Like 'Generic', there is a class 'Generic1' that defines a--- representation 'Rep1' and conversion functions 'from1' and 'to1',--- only that 'Generic1' ranges over types of kind @* -> *@.--- The 'Generic1' class is also derivable.------ The representation 'Rep1' is ever so slightly different from 'Rep'.--- Let us look at 'Tree' as an example again:------ @--- data Tree a = Leaf a | Node (Tree a) (Tree a)---   deriving 'Generic1'--- @------ The above declaration causes the following representation to be generated:------ instance 'Generic1' Tree where---   type 'Rep1' Tree =---     'D1' D1Tree---       ('C1' C1_0Tree---          ('S1' 'NoSelector' 'Par1')---        ':+:'---        'C1' C1_1Tree---          ('S1' 'NoSelector' ('Rec1' Tree)---           ':*:'---           'S1' 'NoSelector' ('Rec1' Tree)))---   ...------ The representation reuses 'D1', 'C1', 'S1' (and thereby 'M1') as well--- as ':+:' and ':*:' from 'Rep'. (This reusability is the reason that we--- carry around the dummy type argument for kind-@*@-types, but there are--- already enough different names involved without duplicating each of--- these.)------ What's different is that we now use 'Par1' to refer to the parameter--- (and that parameter, which used to be @a@), is not mentioned explicitly--- by name anywhere; and we use 'Rec1' to refer to a recursive use of @Tree a@.---- *** Representation of @* -> *@ types------ |------ Unlike 'Par0' and 'Rec0', the 'Par1' and 'Rec1' type constructors do not--- map to 'K1'. They are defined directly, as follows:------ @--- newtype 'Par1'   p = 'Par1' { 'unPar1' ::   p } -- gives access to parameter p--- newtype 'Rec1' f p = 'Rec1' { 'unRec1' :: f p } -- a wrapper--- @------ In 'Par1', the parameter @p@ is used for the first time, whereas 'Rec1' simply--- wraps an application of @f@ to @p@.------ Note that 'K1' (in the guise of 'Rec0') can still occur in a 'Rep1' representation,--- namely when the datatype has a field that does not mention the parameter.------ The declaration------ @--- data WithInt a = WithInt Int a---   deriving 'Generic1'--- @------ yields------ @--- class 'Rep1' WithInt where---   type 'Rep1' WithInt =---     'D1' D1WithInt---       ('C1' C1_0WithInt---         ('S1' 'NoSelector' ('Rec0' Int)---          ':*:'---          'S1' 'NoSelector' 'Par1'))--- @------ If the parameter @a@ appears underneath a composition of other type constructors,--- then the representation involves composition, too:------ @--- data Rose a = Fork a [Rose a]--- @------ yields------ @--- class 'Rep1' Rose where---   type 'Rep1' Rose =---     'D1' D1Rose---       ('C1' C1_0Rose---         ('S1' 'NoSelector' 'Par1'---          ':*:'---          'S1' 'NoSelector' ([] ':.:' 'Rec1' Rose)--- @------ where------ @--- newtype (':.:') f g p = 'Comp1' { 'unComp1' :: f (g p) }--- @-#if 0--- *** Limitations------ |------ /TODO/------ /TODO:/ Also clear up confusion about 'Rec0' and 'Rec1' not really indicating recursion.----#endif--------------------------------------------------------------------------------  -- * Generic representation types-    V1, U1(..), Par1(..), Rec1(..), K1(..), M1(..)-  , (:+:)(..), (:*:)(..), (:.:)(..)--  -- ** Synonyms for convenience-  , Rec0, Par0, R, P-  , D1, C1, S1, D, C, S--  -- * Meta-information-  , Datatype(..), Constructor(..), Selector(..), NoSelector-  , Fixity(..), Associativity(..), Arity(..), prec--  -- * Generic type classes-  , Generic(..), Generic1(..)--  ) where---- We use some base types-import GHC.Types-import Data.Maybe ( Maybe(..) )-import Data.Either ( Either(..) )---- Needed for instances-import GHC.Classes ( Eq, Ord )-import GHC.Read ( Read )-import GHC.Show ( Show )-import Data.Proxy------------------------------------------------------------------------------------- Representation types------------------------------------------------------------------------------------- | Void: used for datatypes without constructors-data V1 p---- | Unit: used for constructors without arguments-data U1 p = U1-  deriving (Eq, Ord, Read, Show, Generic)---- | Used for marking occurrences of the parameter-newtype Par1 p = Par1 { unPar1 :: p }-  deriving (Eq, Ord, Read, Show, Generic)---- | Recursive calls of kind * -> *-newtype Rec1 f p = Rec1 { unRec1 :: f p }-  deriving (Eq, Ord, Read, Show, Generic)---- | Constants, additional parameters and recursion of kind *-newtype K1 i c p = K1 { unK1 :: c }-  deriving (Eq, Ord, Read, Show, Generic)---- | Meta-information (constructor names, etc.)-newtype M1 i c f p = M1 { unM1 :: f p }-  deriving (Eq, Ord, Read, Show, Generic)---- | Sums: encode choice between constructors-infixr 5 :+:-data (:+:) f g p = L1 (f p) | R1 (g p)-  deriving (Eq, Ord, Read, Show, Generic)---- | Products: encode multiple arguments to constructors-infixr 6 :*:-data (:*:) f g p = f p :*: g p-  deriving (Eq, Ord, Read, Show, Generic)---- | Composition of functors-infixr 7 :.:-newtype (:.:) f g p = Comp1 { unComp1 :: f (g p) }-  deriving (Eq, Ord, Read, Show, Generic)---- | Tag for K1: recursion (of kind *)-data R--- | Tag for K1: parameters (other than the last)-data P---- | Type synonym for encoding recursion (of kind *)-type Rec0  = K1 R--- | Type synonym for encoding parameters (other than the last)-type Par0  = K1 P-{-# DEPRECATED Par0 "'Par0' is no longer used; use 'Rec0' instead" #-} -- deprecated in 7.6-{-# DEPRECATED P "'P' is no longer used; use 'R' instead" #-} -- deprecated in 7.6---- | Tag for M1: datatype-data D--- | Tag for M1: constructor-data C--- | Tag for M1: record selector-data S---- | Type synonym for encoding meta-information for datatypes-type D1 = M1 D---- | Type synonym for encoding meta-information for constructors-type C1 = M1 C---- | Type synonym for encoding meta-information for record selectors-type S1 = M1 S----- | Class for datatypes that represent datatypes-class Datatype d where-  -- | The name of the datatype (unqualified)-  datatypeName :: t d (f :: * -> *) a -> [Char]-  -- | The fully-qualified name of the module where the type is declared-  moduleName   :: t d (f :: * -> *) a -> [Char]-  -- | Marks if the datatype is actually a newtype-  isNewtype    :: t d (f :: * -> *) a -> Bool-  isNewtype _ = False----- | Class for datatypes that represent records-class Selector s where-  -- | The name of the selector-  selName :: t s (f :: * -> *) a -> [Char]---- | Used for constructor fields without a name-data NoSelector--instance Selector NoSelector where selName _ = ""---- | Class for datatypes that represent data constructors-class Constructor c where-  -- | The name of the constructor-  conName :: t c (f :: * -> *) a -> [Char]--  -- | The fixity of the constructor-  conFixity :: t c (f :: * -> *) a -> Fixity-  conFixity _ = Prefix--  -- | Marks if this constructor is a record-  conIsRecord :: t c (f :: * -> *) a -> Bool-  conIsRecord _ = False----- | Datatype to represent the arity of a tuple.-data Arity = NoArity | Arity Int-  deriving (Eq, Show, Ord, Read, Generic)---- | Datatype to represent the fixity of a constructor. An infix--- | declaration directly corresponds to an application of 'Infix'.-data Fixity = Prefix | Infix Associativity Int-  deriving (Eq, Show, Ord, Read, Generic)---- | Get the precedence of a fixity value.-prec :: Fixity -> Int-prec Prefix      = 10-prec (Infix _ n) = n---- | Datatype to represent the associativity of a constructor-data Associativity = LeftAssociative-                   | RightAssociative-                   | NotAssociative-  deriving (Eq, Show, Ord, Read, Generic)---- | Representable types of kind *.--- This class is derivable in GHC with the DeriveGeneric flag on.-class Generic a where-  -- | Generic representation type-  type Rep a :: * -> *-  -- | Convert from the datatype to its representation-  from  :: a -> (Rep a) x-  -- | Convert from the representation to the datatype-  to    :: (Rep a) x -> a----- | Representable types of kind * -> *.--- This class is derivable in GHC with the DeriveGeneric flag on.-class Generic1 f where-  -- | Generic representation type-  type Rep1 f :: * -> *-  -- | Convert from the datatype to its representation-  from1  :: f a -> (Rep1 f) a-  -- | Convert from the representation to the datatype-  to1    :: (Rep1 f) a -> f a-------------------------------------------------------------------------------------- Derived instances----------------------------------------------------------------------------------deriving instance Generic [a]-deriving instance Generic (Maybe a)-deriving instance Generic (Either a b)-deriving instance Generic Bool-deriving instance Generic Ordering-deriving instance Generic ()-deriving instance Generic ((,) a b)-deriving instance Generic ((,,) a b c)-deriving instance Generic ((,,,) a b c d)-deriving instance Generic ((,,,,) a b c d e)-deriving instance Generic ((,,,,,) a b c d e f)-deriving instance Generic ((,,,,,,) a b c d e f g)--deriving instance Generic1 []-deriving instance Generic1 Maybe-deriving instance Generic1 (Either a)-deriving instance Generic1 ((,) a)-deriving instance Generic1 ((,,) a b)-deriving instance Generic1 ((,,,) a b c)-deriving instance Generic1 ((,,,,) a b c d)-deriving instance Generic1 ((,,,,,) a b c d e)-deriving instance Generic1 ((,,,,,,) a b c d e f)------------------------------------------------------------------------------------- Primitive representations------------------------------------------------------------------------------------- Int-data D_Int-data C_Int--instance Datatype D_Int where-  datatypeName _ = "Int"-  moduleName   _ = "GHC.Int"--instance Constructor C_Int where-  conName _ = "" -- JPM: I'm not sure this is the right implementation...--instance Generic Int where-  type Rep Int = D1 D_Int (C1 C_Int (S1 NoSelector (Rec0 Int)))-  from x = M1 (M1 (M1 (K1 x)))-  to (M1 (M1 (M1 (K1 x)))) = x----- Float-data D_Float-data C_Float--instance Datatype D_Float where-  datatypeName _ = "Float"-  moduleName   _ = "GHC.Float"--instance Constructor C_Float where-  conName _ = "" -- JPM: I'm not sure this is the right implementation...--instance Generic Float where-  type Rep Float = D1 D_Float (C1 C_Float (S1 NoSelector (Rec0 Float)))-  from x = M1 (M1 (M1 (K1 x)))-  to (M1 (M1 (M1 (K1 x)))) = x----- Double-data D_Double-data C_Double--instance Datatype D_Double where-  datatypeName _ = "Double"-  moduleName   _ = "GHC.Float"--instance Constructor C_Double where-  conName _ = "" -- JPM: I'm not sure this is the right implementation...--instance Generic Double where-  type Rep Double = D1 D_Double (C1 C_Double (S1 NoSelector (Rec0 Double)))-  from x = M1 (M1 (M1 (K1 x)))-  to (M1 (M1 (M1 (K1 x)))) = x----- Char-data D_Char-data C_Char--instance Datatype D_Char where-  datatypeName _ = "Char"-  moduleName   _ = "GHC.Base"--instance Constructor C_Char where-  conName _ = "" -- JPM: I'm not sure this is the right implementation...--instance Generic Char where-  type Rep Char = D1 D_Char (C1 C_Char (S1 NoSelector (Rec0 Char)))-  from x = M1 (M1 (M1 (K1 x)))-  to (M1 (M1 (M1 (K1 x)))) = x--deriving instance Generic (Proxy t)
− GHC/IO.hs
@@ -1,490 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude-           , BangPatterns-           , RankNTypes-           , MagicHash-           , UnboxedTuples-  #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO--- Copyright   :  (c) The University of Glasgow 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Definitions for the 'IO' monad and its friends.-----------------------------------------------------------------------------------module GHC.IO (-        IO(..), unIO, failIO, liftIO,-        unsafePerformIO, unsafeInterleaveIO,-        unsafeDupablePerformIO, unsafeDupableInterleaveIO,-        noDuplicate,--        -- To and from from ST-        stToIO, ioToST, unsafeIOToST, unsafeSTToIO,--        FilePath,--        catchException, catchAny, throwIO,-        mask, mask_, uninterruptibleMask, uninterruptibleMask_,-        MaskingState(..), getMaskingState,-        unsafeUnmask,-        onException, bracket, finally, evaluate-    ) where--import GHC.Base-import GHC.ST-import GHC.Exception-import GHC.Show--import {-# SOURCE #-} GHC.IO.Exception ( userError )---- ------------------------------------------------------------------------------ The IO Monad--{--The IO Monad is just an instance of the ST monad, where the state is-the real world.  We use the exception mechanism (in GHC.Exception) to-implement IO exceptions.--NOTE: The IO representation is deeply wired in to various parts of the-system.  The following list may or may not be exhaustive:--Compiler  - types of various primitives in PrimOp.lhs--RTS       - forceIO (StgMiscClosures.hc)-          - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast-            (Exceptions.hc)-          - raiseAsync (Schedule.c)--Prelude   - GHC.IO.lhs, and several other places including-            GHC.Exception.lhs.--Libraries - parts of hslibs/lang.----SDM--}--liftIO :: IO a -> State# RealWorld -> STret RealWorld a-liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r--failIO :: String -> IO a-failIO s = IO (raiseIO# (toException (userError s)))---- ------------------------------------------------------------------------------ Coercions between IO and ST---- | A monad transformer embedding strict 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        :: ST RealWorld a -> IO a-stToIO (ST m) = IO m--ioToST        :: IO a -> ST RealWorld a-ioToST (IO m) = (ST m)---- This relies on IO and ST having the same representation modulo the--- constraint on the type of the state----unsafeIOToST        :: IO a -> ST s a-unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s--unsafeSTToIO :: ST s a -> IO a-unsafeSTToIO (ST m) = IO (unsafeCoerce# m)---- ------------------------------------------------------------------------------ Unsafe IO operations--{-|-This is the \"back door\" into the 'IO' monad, allowing-'IO' computation to be performed at any time.  For-this to be safe, the 'IO' computation should be-free of side effects and independent of its environment.--If the I\/O computation wrapped in 'unsafePerformIO' performs side-effects, then the relative order in which those side effects take-place (relative to the main I\/O trunk, or other calls to-'unsafePerformIO') is indeterminate.  Furthermore, when using-'unsafePerformIO' to cause side-effects, you should take the following-precautions to ensure the side effects are performed as many times as-you expect them to be.  Note that these precautions are necessary for-GHC, but may not be sufficient, and other compilers may require-different precautions:--  * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@-        that calls 'unsafePerformIO'.  If the call is inlined,-        the I\/O may be performed more than once.--  * Use the compiler flag @-fno-cse@ to prevent common sub-expression-        elimination being performed on the module, which might combine-        two side effects that were meant to be separate.  A good example-        is using multiple global variables (like @test@ in the example below).--  * Make sure that the either you switch off let-floating (@-fno-full-laziness@), or that the-        call to 'unsafePerformIO' cannot float outside a lambda.  For example,-        if you say:-        @-           f x = unsafePerformIO (newIORef [])-        @-        you may get only one reference cell shared between all calls to @f@.-        Better would be-        @-           f x = unsafePerformIO (newIORef [x])-        @-        because now it can't float outside the lambda.--It is less well known that-'unsafePerformIO' is not type safe.  For example:-->     test :: IORef [a]->     test = unsafePerformIO $ newIORef []->->     main = do->             writeIORef test [42]->             bang <- readIORef test->             print (bang :: [Char])--This program will core dump.  This problem with polymorphic references-is well known in the ML community, and does not arise with normal-monadic use of references.  There is no easy way to make it impossible-once you use 'unsafePerformIO'.  Indeed, it is-possible to write @coerce :: a -> b@ with the-help of 'unsafePerformIO'.  So be careful!--}-unsafePerformIO :: IO a -> a-unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)--{-|-This version of 'unsafePerformIO' is more efficient-because it omits the check that the IO is only being performed by a-single thread.  Hence, when you use 'unsafeDupablePerformIO',-there is a possibility that the IO action may be performed multiple-times (on a multiprocessor), and you should therefore ensure that-it gives the same results each time. It may even happen that one-of the duplicated IO actions is only run partially, and then interrupted-in the middle without an exception being raised. Therefore, functions-like 'bracket' cannot be used safely within 'unsafeDupablePerformIO'.--@since 4.4.0.0--}-{-# NOINLINE unsafeDupablePerformIO #-}-    -- See Note [unsafeDupablePerformIO is NOINLINE]-unsafeDupablePerformIO  :: IO a -> a-unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)-     -- See Note [unsafeDupablePerformIO has a lazy RHS]---- Note [unsafeDupablePerformIO is NOINLINE]--- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--- Why do we NOINLINE unsafeDupablePerformIO?  See the comment with--- GHC.ST.runST.  Essentially the issue is that the IO computation--- inside unsafePerformIO must be atomic: it must either all run, or--- not at all.  If we let the compiler see the application of the IO--- to realWorld#, it might float out part of the IO.---- Note [unsafeDupablePerformIO has a lazy RHS]--- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--- Why is there a call to 'lazy' in unsafeDupablePerformIO?--- If we don't have it, the demand analyser discovers the following strictness--- for unsafeDupablePerformIO:  C(U(AV))--- But then consider---      unsafeDupablePerformIO (\s -> let r = f x in---                             case writeIORef v r s of (# s1, _ #) ->---                             (# s1, r #) )--- The strictness analyser will find that the binding for r is strict,--- (because of uPIO's strictness sig), and so it'll evaluate it before--- doing the writeIORef.  This actually makes libraries/base/tests/memo002--- get a deadlock, where we specifically wanted to write a lazy thunk--- into the ref cell.------ Solution: don't expose the strictness of unsafeDupablePerformIO,---           by hiding it with 'lazy'--- But see discussion in Trac #9390 (comment:33)--{-|-'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.-When passed a value of type @IO a@, the 'IO' will only be performed-when the value of the @a@ is demanded.  This is used to implement lazy-file reading, see 'System.IO.hGetContents'.--}-{-# INLINE unsafeInterleaveIO #-}-unsafeInterleaveIO :: IO a -> IO a-unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)---- We used to believe that INLINE on unsafeInterleaveIO was safe,--- because the state from this IO thread is passed explicitly to the--- interleaved IO, so it cannot be floated out and shared.------ HOWEVER, if the compiler figures out that r is used strictly here,--- then it will eliminate the thunk and the side effects in m will no--- longer be shared in the way the programmer was probably expecting,--- but can be performed many times.  In #5943, this broke our--- definition of fixIO, which contains------    ans <- unsafeInterleaveIO (takeMVar m)------ after inlining, we lose the sharing of the takeMVar, so the second--- time 'ans' was demanded we got a deadlock.  We could fix this with--- a readMVar, but it seems wrong for unsafeInterleaveIO to sometimes--- share and sometimes not (plus it probably breaks the noDuplicate).--- So now, we do not inline unsafeDupableInterleaveIO.--{-# NOINLINE unsafeDupableInterleaveIO #-}-unsafeDupableInterleaveIO :: IO a -> IO a-unsafeDupableInterleaveIO (IO m)-  = IO ( \ s -> let-                   r = case m s of (# _, res #) -> res-                in-                (# s, r #))--{-|-Ensures that the suspensions under evaluation by the current thread-are unique; that is, the current thread is not evaluating anything-that is also under evaluation by another thread that has also executed-'noDuplicate'.--This operation is used in the definition of 'unsafePerformIO' to-prevent the IO action from being executed multiple times, which is usually-undesirable.--}-noDuplicate :: IO ()-noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)---- -------------------------------------------------------------------------------- | File and directory names are values of type 'String', whose precise--- meaning is operating system dependent. Files can be opened, yielding a--- handle which can then be used to operate on the contents of that file.--type FilePath = String---- -------------------------------------------------------------------------------- Primitive catch and throwIO--{--catchException used to handle the passing around of the state to the-action and the handler.  This turned out to be a bad idea - it meant-that we had to wrap both arguments in thunks so they could be entered-as normal (remember IO returns an unboxed pair...).--Now catch# has type--    catch# :: IO a -> (b -> IO a) -> IO a--(well almost; the compiler doesn't know about the IO newtype so we-have to work around that in the definition of catchException below).--}--catchException :: Exception e => IO a -> (e -> IO a) -> IO a-catchException (IO io) handler = IO $ catch# io handler'-    where handler' e = case fromException e of-                       Just e' -> unIO (handler e')-                       Nothing -> raiseIO# e--catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a-catchAny (IO io) handler = IO $ catch# io handler'-    where handler' (SomeException e) = unIO (handler e)---- | A variant of 'throw' that can only be used within the 'IO' monad.------ Although 'throwIO' has a type that is an instance of the type of 'throw', the--- two functions are subtly different:------ > throw e   `seq` x  ===> throw e--- > throwIO e `seq` x  ===> x------ The first example will cause the exception @e@ to be raised,--- whereas the second one won\'t.  In fact, 'throwIO' will only cause--- an exception to be raised when it is used within the 'IO' monad.--- The 'throwIO' variant should be used in preference to 'throw' to--- raise an exception within the 'IO' monad because it guarantees--- ordering with respect to other 'IO' operations, whereas 'throw'--- does not.-throwIO :: Exception e => e -> IO a-throwIO e = IO (raiseIO# (toException e))---- -------------------------------------------------------------------------------- Controlling asynchronous exception delivery---- Applying 'block' to a computation will--- execute that computation with asynchronous exceptions--- /blocked/.  That is, any thread which--- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be--- blocked until asynchronous exceptions are unblocked again.  There\'s--- no need to worry about re-enabling asynchronous exceptions; that is--- done automatically on exiting the scope of--- 'block'.------ Threads created by 'Control.Concurrent.forkIO' inherit the blocked--- state from the parent; that is, to start a thread in blocked mode,--- use @block $ forkIO ...@.  This is particularly useful if you need to--- establish an exception handler in the forked thread before any--- asynchronous exceptions are received.-block :: IO a -> IO a-block (IO io) = IO $ maskAsyncExceptions# io---- To re-enable asynchronous exceptions inside the scope of--- 'block', 'unblock' can be--- used.  It scopes in exactly the same way, so on exit from--- 'unblock' asynchronous exception delivery will--- be disabled again.-unblock :: IO a -> IO a-unblock = unsafeUnmask--unsafeUnmask :: IO a -> IO a-unsafeUnmask (IO io) = IO $ unmaskAsyncExceptions# io--blockUninterruptible :: IO a -> IO a-blockUninterruptible (IO io) = IO $ maskUninterruptible# io---- | Describes the behaviour of a thread when an asynchronous--- exception is received.-data MaskingState-  = Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)-  | MaskedInterruptible-      -- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted-  | MaskedUninterruptible-      -- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted- deriving (Eq,Show)---- | Returns the 'MaskingState' for the current thread.-getMaskingState :: IO MaskingState-getMaskingState  = IO $ \s ->-  case getMaskingState# s of-     (# s', i #) -> (# s', case i of-                             0# -> Unmasked-                             1# -> MaskedUninterruptible-                             _  -> MaskedInterruptible #)--onException :: IO a -> IO b -> IO a-onException io what = io `catchException` \e -> do _ <- what-                                                   throwIO (e :: SomeException)---- | Executes an IO computation with asynchronous--- exceptions /masked/.  That is, any thread which attempts to raise--- an exception in the current thread with 'Control.Exception.throwTo'--- will be blocked until asynchronous exceptions are unmasked again.------ The argument passed to 'mask' is a function that takes as its--- argument another function, which can be used to restore the--- prevailing masking state within the context of the masked--- computation.  For example, a common way to use 'mask' is to protect--- the acquisition of a resource:------ > mask $ \restore -> do--- >     x <- acquire--- >     restore (do_something_with x) `onException` release--- >     release------ This code guarantees that @acquire@ is paired with @release@, by masking--- asynchronous exceptions for the critical parts. (Rather than write--- this code yourself, it would be better to use--- 'Control.Exception.bracket' which abstracts the general pattern).------ Note that the @restore@ action passed to the argument to 'mask'--- does not necessarily unmask asynchronous exceptions, it just--- restores the masking state to that of the enclosing context.  Thus--- if asynchronous exceptions are already masked, 'mask' cannot be used--- to unmask exceptions again.  This is so that if you call a library function--- with exceptions masked, you can be sure that the library call will not be--- able to unmask exceptions again.  If you are writing library code and need--- to use asynchronous exceptions, the only way is to create a new thread;--- see 'Control.Concurrent.forkIOWithUnmask'.------ Asynchronous exceptions may still be received while in the masked--- state if the masked thread /blocks/ in certain ways; see--- "Control.Exception#interruptible".------ Threads created by 'Control.Concurrent.forkIO' inherit the--- 'MaskingState' from the parent; that is, to start a thread in the--- 'MaskedInterruptible' state,--- use @mask_ $ forkIO ...@.  This is particularly useful if you need--- to establish an exception handler in the forked thread before any--- asynchronous exceptions are received.  To create a a new thread in--- an unmasked state use 'Control.Concurrent.forkIOUnmasked'.----mask  :: ((forall a. IO a -> IO a) -> IO b) -> IO b---- | Like 'mask', but does not pass a @restore@ action to the argument.-mask_ :: IO a -> IO a---- | Like 'mask', but the masked computation is not interruptible (see--- "Control.Exception#interruptible").  THIS SHOULD BE USED WITH--- GREAT CARE, because if a thread executing in 'uninterruptibleMask'--- blocks for any reason, then the thread (and possibly the program,--- if this is the main thread) will be unresponsive and unkillable.--- This function should only be necessary if you need to mask--- exceptions around an interruptible operation, and you can guarantee--- that the interruptible operation will only block for a short period--- of time.----uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b---- | Like 'uninterruptibleMask', but does not pass a @restore@ action--- to the argument.-uninterruptibleMask_ :: IO a -> IO a--mask_ io = mask $ \_ -> io--mask io = do-  b <- getMaskingState-  case b of-    Unmasked              -> block $ io unblock-    MaskedInterruptible   -> io block-    MaskedUninterruptible -> io blockUninterruptible--uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io--uninterruptibleMask io = do-  b <- getMaskingState-  case b of-    Unmasked              -> blockUninterruptible $ io unblock-    MaskedInterruptible   -> blockUninterruptible $ io block-    MaskedUninterruptible -> io blockUninterruptible--bracket-        :: IO a         -- ^ computation to run first (\"acquire resource\")-        -> (a -> IO b)  -- ^ computation to run last (\"release resource\")-        -> (a -> IO c)  -- ^ computation to run in-between-        -> IO c         -- returns the value from the in-between computation-bracket before after thing =-  mask $ \restore -> do-    a <- before-    r <- restore (thing a) `onException` after a-    _ <- after a-    return r--finally :: IO a         -- ^ computation to run first-        -> IO b         -- ^ computation to run afterward (even if an exception-                        -- was raised)-        -> IO a         -- returns the value from the first computation-a `finally` sequel =-  mask $ \restore -> do-    r <- restore a `onException` sequel-    _ <- sequel-    return r---- | Forces its argument to be evaluated to weak head normal form when--- the resultant 'IO' action is executed. It can be used to order--- evaluation with respect to other 'IO' operations; its semantics are--- given by------ >   evaluate x `seq` y    ==>  y--- >   evaluate x `catch` f  ==>  (return $! x) `catch` f--- >   evaluate x >>= f      ==>  (return $! x) >>= f------ /Note:/ the first equation implies that @(evaluate x)@ is /not/ the--- same as @(return $! x)@.  A correct definition is------ >   evaluate x = (return $! x) >>= return----evaluate :: a -> IO a-evaluate a = IO $ \s -> seq# a s -- NB. see #2273, #5129-
− GHC/IO.hs-boot
@@ -1,9 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude #-}--module GHC.IO where--import GHC.Types--failIO :: [Char] -> IO a-
− GHC/IO/Buffer.hs
@@ -1,291 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Buffer--- Copyright   :  (c) The University of Glasgow 2008--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Buffers used in the IO system-----------------------------------------------------------------------------------module GHC.IO.Buffer (-    -- * Buffers of any element-    Buffer(..), BufferState(..), CharBuffer, CharBufElem,--    -- ** Creation-    newByteBuffer,-    newCharBuffer,-    newBuffer,-    emptyBuffer,--    -- ** Insertion/removal-    bufferRemove,-    bufferAdd,-    slideContents,-    bufferAdjustL,--    -- ** Inspecting-    isEmptyBuffer,-    isFullBuffer,-    isFullCharBuffer,-    isWriteBuffer,-    bufferElems,-    bufferAvailable,-    summaryBuffer,--    -- ** Operating on the raw buffer as a Ptr-    withBuffer,-    withRawBuffer,--    -- ** Assertions-    checkBuffer,--    -- * Raw buffers-    RawBuffer,-    readWord8Buf,-    writeWord8Buf,-    RawCharBuffer,-    peekCharBuf,-    readCharBuf,-    writeCharBuf,-    readCharBufPtr,-    writeCharBufPtr,-    charSize,- ) where--import GHC.Base--- import GHC.IO-import GHC.Num-import GHC.Ptr-import GHC.Word-import GHC.Show-import GHC.Real-import Foreign.C.Types-import Foreign.ForeignPtr-import Foreign.Storable---- Char buffers use either UTF-16 or UTF-32, with the endianness matching--- the endianness of the host.------ Invariants:---   * a Char buffer consists of *valid* UTF-16 or UTF-32---   * only whole characters: no partial surrogate pairs--#define CHARBUF_UTF32---- #define CHARBUF_UTF16------ NB. it won't work to just change this to CHARBUF_UTF16.  Some of--- the code to make this work is there, and it has been tested with--- the Iconv codec, but there are some pieces that are known to be--- broken.  In particular, the built-in codecs--- e.g. GHC.IO.Encoding.UTF{8,16,32} need to use isFullCharBuffer or--- similar in place of the ow >= os comparisons.---- ------------------------------------------------------------------------------ Raw blocks of data--type RawBuffer e = ForeignPtr e--readWord8Buf :: RawBuffer Word8 -> Int -> IO Word8-readWord8Buf arr ix = withForeignPtr arr $ \p -> peekByteOff p ix--writeWord8Buf :: RawBuffer Word8 -> Int -> Word8 -> IO ()-writeWord8Buf arr ix w = withForeignPtr arr $ \p -> pokeByteOff p ix w--#ifdef CHARBUF_UTF16-type CharBufElem = Word16-#else-type CharBufElem = Char-#endif--type RawCharBuffer = RawBuffer CharBufElem--peekCharBuf :: RawCharBuffer -> Int -> IO Char-peekCharBuf arr ix = withForeignPtr arr $ \p -> do-                        (c,_) <- readCharBufPtr p ix-                        return c--{-# INLINE readCharBuf #-}-readCharBuf :: RawCharBuffer -> Int -> IO (Char, Int)-readCharBuf arr ix = withForeignPtr arr $ \p -> readCharBufPtr p ix--{-# INLINE writeCharBuf #-}-writeCharBuf :: RawCharBuffer -> Int -> Char -> IO Int-writeCharBuf arr ix c = withForeignPtr arr $ \p -> writeCharBufPtr p ix c--{-# INLINE readCharBufPtr #-}-readCharBufPtr :: Ptr CharBufElem -> Int -> IO (Char, Int)-#ifdef CHARBUF_UTF16-readCharBufPtr p ix = do-  c1 <- peekElemOff p ix-  if (c1 < 0xd800 || c1 > 0xdbff)-     then return (chr (fromIntegral c1), ix+1)-     else do c2 <- peekElemOff p (ix+1)-             return (unsafeChr ((fromIntegral c1 - 0xd800)*0x400 +-                                (fromIntegral c2 - 0xdc00) + 0x10000), ix+2)-#else-readCharBufPtr p ix = do c <- peekElemOff (castPtr p) ix; return (c, ix+1)-#endif--{-# INLINE writeCharBufPtr #-}-writeCharBufPtr :: Ptr CharBufElem -> Int -> Char -> IO Int-#ifdef CHARBUF_UTF16-writeCharBufPtr p ix ch-  | c < 0x10000 = do pokeElemOff p ix (fromIntegral c)-                     return (ix+1)-  | otherwise   = do let c' = c - 0x10000-                     pokeElemOff p ix (fromIntegral (c' `div` 0x400 + 0xd800))-                     pokeElemOff p (ix+1) (fromIntegral (c' `mod` 0x400 + 0xdc00))-                     return (ix+2)-  where-    c = ord ch-#else-writeCharBufPtr p ix ch = do pokeElemOff (castPtr p) ix ch; return (ix+1)-#endif--charSize :: Int-#ifdef CHARBUF_UTF16-charSize = 2-#else-charSize = 4-#endif---- ------------------------------------------------------------------------------ Buffers---- | A mutable array of bytes that can be passed to foreign functions.------ The buffer is represented by a record, where the record contains--- the raw buffer and the start/end points of the filled portion.  The--- buffer contents itself is mutable, but the rest of the record is--- immutable.  This is a slightly odd mix, but it turns out to be--- quite practical: by making all the buffer metadata immutable, we--- can have operations on buffer metadata outside of the IO monad.------ The "live" elements of the buffer are those between the 'bufL' and--- 'bufR' offsets.  In an empty buffer, 'bufL' is equal to 'bufR', but--- they might not be zero: for exmaple, the buffer might correspond to--- a memory-mapped file and in which case 'bufL' will point to the--- next location to be written, which is not necessarily the beginning--- of the file.-data Buffer e-  = Buffer {-        bufRaw   :: !(RawBuffer e),-        bufState :: BufferState,-        bufSize  :: !Int,          -- in elements, not bytes-        bufL     :: !Int,          -- offset of first item in the buffer-        bufR     :: !Int           -- offset of last item + 1-  }--#ifdef CHARBUF_UTF16-type CharBuffer = Buffer Word16-#else-type CharBuffer = Buffer Char-#endif--data BufferState = ReadBuffer | WriteBuffer deriving (Eq)--withBuffer :: Buffer e -> (Ptr e -> IO a) -> IO a-withBuffer Buffer{ bufRaw=raw } f = withForeignPtr (castForeignPtr raw) f--withRawBuffer :: RawBuffer e -> (Ptr e -> IO a) -> IO a-withRawBuffer raw f = withForeignPtr (castForeignPtr raw) f--isEmptyBuffer :: Buffer e -> Bool-isEmptyBuffer Buffer{ bufL=l, bufR=r } = l == r--isFullBuffer :: Buffer e -> Bool-isFullBuffer Buffer{ bufR=w, bufSize=s } = s == w---- if a Char buffer does not have room for a surrogate pair, it is "full"-isFullCharBuffer :: Buffer e -> Bool-#ifdef CHARBUF_UTF16-isFullCharBuffer buf = bufferAvailable buf < 2-#else-isFullCharBuffer = isFullBuffer-#endif--isWriteBuffer :: Buffer e -> Bool-isWriteBuffer buf = case bufState buf of-                        WriteBuffer -> True-                        ReadBuffer  -> False--bufferElems :: Buffer e -> Int-bufferElems Buffer{ bufR=w, bufL=r } = w - r--bufferAvailable :: Buffer e -> Int-bufferAvailable Buffer{ bufR=w, bufSize=s } = s - w--bufferRemove :: Int -> Buffer e -> Buffer e-bufferRemove i buf@Buffer{ bufL=r } = bufferAdjustL (r+i) buf--bufferAdjustL :: Int -> Buffer e -> Buffer e-bufferAdjustL l buf@Buffer{ bufR=w }-  | l == w    = buf{ bufL=0, bufR=0 }-  | otherwise = buf{ bufL=l, bufR=w }--bufferAdd :: Int -> Buffer e -> Buffer e-bufferAdd i buf@Buffer{ bufR=w } = buf{ bufR=w+i }--emptyBuffer :: RawBuffer e -> Int -> BufferState -> Buffer e-emptyBuffer raw sz state =-  Buffer{ bufRaw=raw, bufState=state, bufR=0, bufL=0, bufSize=sz }--newByteBuffer :: Int -> BufferState -> IO (Buffer Word8)-newByteBuffer c st = newBuffer c c st--newCharBuffer :: Int -> BufferState -> IO CharBuffer-newCharBuffer c st = newBuffer (c * charSize) c st--newBuffer :: Int -> Int -> BufferState -> IO (Buffer e)-newBuffer bytes sz state = do-  fp <- mallocForeignPtrBytes bytes-  return (emptyBuffer fp sz state)---- | slides the contents of the buffer to the beginning-slideContents :: Buffer Word8 -> IO (Buffer Word8)-slideContents buf@Buffer{ bufL=l, bufR=r, bufRaw=raw } = do-  let elems = r - l-  withRawBuffer raw $ \p ->-      do _ <- memmove p (p `plusPtr` l) (fromIntegral elems)-         return ()-  return buf{ bufL=0, bufR=elems }--foreign import ccall unsafe "memmove"-   memmove :: Ptr a -> Ptr a -> CSize -> IO (Ptr a)--summaryBuffer :: Buffer a -> String-summaryBuffer buf = "buf" ++ show (bufSize buf) ++ "(" ++ show (bufL buf) ++ "-" ++ show (bufR buf) ++ ")"---- INVARIANTS on Buffers:---   * r <= w---   * if r == w, and the buffer is for reading, then r == 0 && w == 0---   * a write buffer is never full.  If an operation---     fills up the buffer, it will always flush it before---     returning.---   * a read buffer may be full as a result of hLookAhead.  In normal---     operation, a read buffer always has at least one character of space.--checkBuffer :: Buffer a -> IO ()-checkBuffer buf@Buffer{ bufState = state, bufL=r, bufR=w, bufSize=size } = do-     check buf (-        size > 0-        && r <= w-        && w <= size-        && ( r /= w || state == WriteBuffer || (r == 0 && w == 0) )-        && ( state /= WriteBuffer || w < size ) -- write buffer is never full-      )--check :: Buffer a -> Bool -> IO ()-check _   True  = return ()-check buf False = error ("buffer invariant violation: " ++ summaryBuffer buf)-
− GHC/IO/BufferedIO.hs
@@ -1,126 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.BufferedIO--- Copyright   :  (c) The University of Glasgow 2008--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Class of buffered IO devices-----------------------------------------------------------------------------------module GHC.IO.BufferedIO (-        BufferedIO(..),-        readBuf, readBufNonBlocking, writeBuf, writeBufNonBlocking-    ) where--import GHC.Base-import GHC.Ptr-import Data.Word-import GHC.Num-import GHC.IO.Device as IODevice-import GHC.IO.Device as RawIO-import GHC.IO.Buffer---- | The purpose of 'BufferedIO' is to provide a common interface for I/O--- devices that can read and write data through a buffer.  Devices that--- implement 'BufferedIO' include ordinary files, memory-mapped files,--- and bytestrings.  The underlying device implementing a 'Handle' must--- provide 'BufferedIO'.----class BufferedIO dev where-  -- | allocate a new buffer.  The size of the buffer is at the-  -- discretion of the device; e.g. for a memory-mapped file the-  -- buffer will probably cover the entire file.-  newBuffer         :: dev -> BufferState -> IO (Buffer Word8)--  -- | reads bytes into the buffer, blocking if there are no bytes-  -- available.  Returns the number of bytes read (zero indicates-  -- end-of-file), and the new buffer.-  fillReadBuffer    :: dev -> Buffer Word8 -> IO (Int, Buffer Word8)--  -- | reads bytes into the buffer without blocking.  Returns the-  -- number of bytes read (Nothing indicates end-of-file), and the new-  -- buffer.-  fillReadBuffer0   :: dev -> Buffer Word8 -> IO (Maybe Int, Buffer Word8)--  -- | Prepares an empty write buffer.  This lets the device decide-  -- how to set up a write buffer: the buffer may need to point to a-  -- specific location in memory, for example.  This is typically used-  -- by the client when switching from reading to writing on a-  -- buffered read/write device.-  ---  -- There is no corresponding operation for read buffers, because before-  -- reading the client will always call 'fillReadBuffer'.-  emptyWriteBuffer  :: dev -> Buffer Word8 -> IO (Buffer Word8)-  emptyWriteBuffer _dev buf-    = return buf{ bufL=0, bufR=0, bufState = WriteBuffer }--  -- | Flush all the data from the supplied write buffer out to the device.-  -- The returned buffer should be empty, and ready for writing.-  flushWriteBuffer  :: dev -> Buffer Word8 -> IO (Buffer Word8)--  -- | Flush data from the supplied write buffer out to the device-  -- without blocking.  Returns the number of bytes written and the-  -- remaining buffer.-  flushWriteBuffer0 :: dev -> Buffer Word8 -> IO (Int, Buffer Word8)---- for an I/O device, these operations will perform reading/writing--- to/from the device.---- for a memory-mapped file, the buffer will be the whole file in--- memory.  fillReadBuffer sets the pointers to encompass the whole--- file, and flushWriteBuffer needs to do no I/O.  A memory-mapped--- file has to maintain its own file pointer.---- for a bytestring, again the buffer should match the bytestring in--- memory.---- ------------------------------------------------------------------------------ Low-level read/write to/from buffers---- These operations make it easy to implement an instance of 'BufferedIO'--- for an object that supports 'RawIO'.--readBuf :: RawIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8)-readBuf dev bbuf = do-  let bytes = bufferAvailable bbuf-  res <- withBuffer bbuf $ \ptr ->-             RawIO.read dev (ptr `plusPtr` bufR bbuf) bytes-  return (res, bbuf{ bufR = bufR bbuf + res })-         -- zero indicates end of file--readBufNonBlocking :: RawIO dev => dev -> Buffer Word8-                     -> IO (Maybe Int,   -- Nothing ==> end of file-                                         -- Just n  ==> n bytes were read (n>=0)-                            Buffer Word8)-readBufNonBlocking dev bbuf = do-  let bytes = bufferAvailable bbuf-  res <- withBuffer bbuf $ \ptr ->-           IODevice.readNonBlocking dev (ptr `plusPtr` bufR bbuf) bytes-  case res of-     Nothing -> return (Nothing, bbuf)-     Just n  -> return (Just n, bbuf{ bufR = bufR bbuf + n })--writeBuf :: RawIO dev => dev -> Buffer Word8 -> IO (Buffer Word8)-writeBuf dev bbuf = do-  let bytes = bufferElems bbuf-  withBuffer bbuf $ \ptr ->-      IODevice.write dev (ptr `plusPtr` bufL bbuf) bytes-  return bbuf{ bufL=0, bufR=0 }---- XXX ToDo-writeBufNonBlocking :: RawIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8)-writeBufNonBlocking dev bbuf = do-  let bytes = bufferElems bbuf-  res <- withBuffer bbuf $ \ptr ->-            IODevice.writeNonBlocking dev (ptr `plusPtr` bufL bbuf) bytes-  return (res, bufferAdjustL (bufL bbuf + res) bbuf)-
− GHC/IO/Device.hs
@@ -1,170 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, BangPatterns #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Device--- Copyright   :  (c) The University of Glasgow, 1994-2008--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Type classes for I/O providers.-----------------------------------------------------------------------------------module GHC.IO.Device (-        RawIO(..),-        IODevice(..),-        IODeviceType(..),-        SeekMode(..)-    ) where--import GHC.Base-import GHC.Word-import GHC.Arr-import GHC.Enum-import GHC.Read-import GHC.Show-import GHC.Ptr-import GHC.Num-import GHC.IO-import {-# SOURCE #-} GHC.IO.Exception ( unsupportedOperation )---- | A low-level I/O provider where the data is bytes in memory.-class RawIO a where-  -- | Read up to the specified number of bytes, returning the number-  -- of bytes actually read.  This function should only block if there-  -- is no data available.  If there is not enough data available,-  -- then the function should just return the available data. A return-  -- value of zero indicates that the end of the data stream (e.g. end-  -- of file) has been reached.-  read                :: a -> Ptr Word8 -> Int -> IO Int--  -- | Read up to the specified number of bytes, returning the number-  -- of bytes actually read, or 'Nothing' if the end of the stream has-  -- been reached.-  readNonBlocking     :: a -> Ptr Word8 -> Int -> IO (Maybe Int)--  -- | Write the specified number of bytes.-  write               :: a -> Ptr Word8 -> Int -> IO ()--  -- | Write up to the specified number of bytes without blocking.  Returns-  -- the actual number of bytes written.-  writeNonBlocking    :: a -> Ptr Word8 -> Int -> IO Int----- | I/O operations required for implementing a 'Handle'.-class IODevice a where-  -- | @ready dev write msecs@ returns 'True' if the device has data-  -- to read (if @write@ is 'False') or space to write new data (if-  -- @write@ is 'True').  @msecs@ specifies how long to wait, in-  -- milliseconds.-  ---  ready :: a -> Bool -> Int -> IO Bool--  -- | closes the device.  Further operations on the device should-  -- produce exceptions.-  close :: a -> IO ()--  -- | returns 'True' if the device is a terminal or console.-  isTerminal :: a -> IO Bool-  isTerminal _ = return False--  -- | returns 'True' if the device supports 'seek' operations.-  isSeekable :: a -> IO Bool-  isSeekable _ = return False--  -- | seek to the specified position in the data.-  seek :: a -> SeekMode -> Integer -> IO ()-  seek _ _ _ = ioe_unsupportedOperation--  -- | return the current position in the data.-  tell :: a -> IO Integer-  tell _ = ioe_unsupportedOperation--  -- | return the size of the data.-  getSize :: a -> IO Integer-  getSize _ = ioe_unsupportedOperation--  -- | change the size of the data.-  setSize :: a -> Integer -> IO ()-  setSize _ _ = ioe_unsupportedOperation--  -- | for terminal devices, changes whether characters are echoed on-  -- the device.-  setEcho :: a -> Bool -> IO ()-  setEcho _ _ = ioe_unsupportedOperation--  -- | returns the current echoing status.-  getEcho :: a -> IO Bool-  getEcho _ = ioe_unsupportedOperation--  -- | some devices (e.g. terminals) support a "raw" mode where-  -- characters entered are immediately made available to the program.-  -- If available, this operations enables raw mode.-  setRaw :: a -> Bool -> IO ()-  setRaw _ _ = ioe_unsupportedOperation--  -- | returns the 'IODeviceType' corresponding to this device.-  devType :: a -> IO IODeviceType--  -- | duplicates the device, if possible.  The new device is expected-  -- to share a file pointer with the original device (like Unix @dup@).-  dup :: a -> IO a-  dup _ = ioe_unsupportedOperation--  -- | @dup2 source target@ replaces the target device with the source-  -- device.  The target device is closed first, if necessary, and then-  -- it is made into a duplicate of the first device (like Unix @dup2@).-  dup2 :: a -> a -> IO a-  dup2 _ _ = ioe_unsupportedOperation--ioe_unsupportedOperation :: IO a-ioe_unsupportedOperation = throwIO unsupportedOperation---- | Type of a device that can be used to back a--- 'GHC.IO.Handle.Handle' (see also 'GHC.IO.Handle.mkFileHandle'). The--- standard libraries provide creation of 'GHC.IO.Handle.Handle's via--- Posix file operations with file descriptors (see--- 'GHC.IO.Handle.FD.mkHandleFromFD') with FD being the underlying--- 'GHC.IO.Device.IODevice' instance.------ Users may provide custom instances of 'GHC.IO.Device.IODevice'--- which are expected to conform the following rules:--data IODeviceType-  = Directory -- ^ The standard libraries do not have direct support-              -- for this device type, but a user implementation is-              -- expected to provide a list of file names in-              -- the directory, in any order, separated by @'\0'@-              -- characters, excluding the @"."@ and @".."@ names. See-              -- also 'System.Directory.getDirectoryContents'.  Seek-              -- operations are not supported on directories (other-              -- than to the zero position).-  | Stream    -- ^ A duplex communications channel (results in-              -- creation of a duplex 'GHC.IO.Handle.Handle'). The-              -- standard libraries use this device type when-              -- creating 'GHC.IO.Handle.Handle's for open sockets.-  | RegularFile -- ^ A file that may be read or written, and also-                -- may be seekable.-  | RawDevice -- ^ A "raw" (disk) device which supports block binary-              -- read and write operations and may be seekable only-              -- to positions of certain granularity (block--              -- aligned).-  deriving (Eq)---- -------------------------------------------------------------------------------- SeekMode type---- | A mode that determines the effect of 'hSeek' @hdl mode i@.-data SeekMode-  = AbsoluteSeek        -- ^ the position of @hdl@ is set to @i@.-  | RelativeSeek        -- ^ the position of @hdl@ is set to offset @i@-                        -- from the current position.-  | SeekFromEnd         -- ^ the position of @hdl@ is set to offset @i@-                        -- from the end of the file.-    deriving (Eq, Ord, Ix, Enum, Read, Show)-
− GHC/IO/Encoding.hs
@@ -1,288 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Encoding--- Copyright   :  (c) The University of Glasgow, 2008-2009--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Text codecs for I/O-----------------------------------------------------------------------------------module GHC.IO.Encoding (-        BufferCodec(..), TextEncoding(..), TextEncoder, TextDecoder, CodingProgress(..),-        latin1, latin1_encode, latin1_decode,-        utf8, utf8_bom,-        utf16, utf16le, utf16be,-        utf32, utf32le, utf32be,-        initLocaleEncoding,-        getLocaleEncoding, getFileSystemEncoding, getForeignEncoding,-        setLocaleEncoding, setFileSystemEncoding, setForeignEncoding,-        char8,-        mkTextEncoding,-    ) where--import GHC.Base-import GHC.IO.Exception-import GHC.IO.Buffer-import GHC.IO.Encoding.Failure-import GHC.IO.Encoding.Types-#if !defined(mingw32_HOST_OS)-import qualified GHC.IO.Encoding.Iconv as Iconv-#else-import qualified GHC.IO.Encoding.CodePage as CodePage-import Text.Read (reads)-#endif-import qualified GHC.IO.Encoding.Latin1 as Latin1-import qualified GHC.IO.Encoding.UTF8   as UTF8-import qualified GHC.IO.Encoding.UTF16  as UTF16-import qualified GHC.IO.Encoding.UTF32  as UTF32-import GHC.List-import GHC.Word--import Data.IORef-import Data.Char (toUpper)-import System.IO.Unsafe (unsafePerformIO)---- --------------------------------------------------------------------------------- | The Latin1 (ISO8859-1) encoding.  This encoding maps bytes--- directly to the first 256 Unicode code points, and is thus not a--- complete Unicode encoding.  An attempt to write a character greater than--- '\255' to a 'Handle' using the 'latin1' encoding will result in an error.-latin1  :: TextEncoding-latin1 = Latin1.latin1_checked---- | The UTF-8 Unicode encoding-utf8  :: TextEncoding-utf8 = UTF8.utf8---- | The UTF-8 Unicode encoding, with a byte-order-mark (BOM; the byte--- sequence 0xEF 0xBB 0xBF).  This encoding behaves like 'utf8',--- except that on input, the BOM sequence is ignored at the beginning--- of the stream, and on output, the BOM sequence is prepended.------ The byte-order-mark is strictly unnecessary in UTF-8, but is--- sometimes used to identify the encoding of a file.----utf8_bom  :: TextEncoding-utf8_bom = UTF8.utf8_bom---- | The UTF-16 Unicode encoding (a byte-order-mark should be used to--- indicate endianness).-utf16  :: TextEncoding-utf16 = UTF16.utf16---- | The UTF-16 Unicode encoding (litte-endian)-utf16le  :: TextEncoding-utf16le = UTF16.utf16le---- | The UTF-16 Unicode encoding (big-endian)-utf16be  :: TextEncoding-utf16be = UTF16.utf16be---- | The UTF-32 Unicode encoding (a byte-order-mark should be used to--- indicate endianness).-utf32  :: TextEncoding-utf32 = UTF32.utf32---- | The UTF-32 Unicode encoding (litte-endian)-utf32le  :: TextEncoding-utf32le = UTF32.utf32le---- | The UTF-32 Unicode encoding (big-endian)-utf32be  :: TextEncoding-utf32be = UTF32.utf32be---- | The Unicode encoding of the current locale------ @since 4.5.0.0-getLocaleEncoding :: IO TextEncoding---- | The Unicode encoding of the current locale, but allowing arbitrary--- undecodable bytes to be round-tripped through it.------ This 'TextEncoding' is used to decode and encode command line arguments--- and environment variables on non-Windows platforms.------ On Windows, this encoding *should not* be used if possible because--- the use of code pages is deprecated: Strings should be retrieved--- via the "wide" W-family of UTF-16 APIs instead------ @since 4.5.0.0-getFileSystemEncoding :: IO TextEncoding---- | The Unicode encoding of the current locale, but where undecodable--- bytes are replaced with their closest visual match. Used for--- the 'CString' marshalling functions in "Foreign.C.String"------ @since 4.5.0.0-getForeignEncoding :: IO TextEncoding---- | @since 4.5.0.0-setLocaleEncoding, setFileSystemEncoding, setForeignEncoding :: TextEncoding -> IO ()--(getLocaleEncoding, setLocaleEncoding)         = mkGlobal initLocaleEncoding-(getFileSystemEncoding, setFileSystemEncoding) = mkGlobal initFileSystemEncoding-(getForeignEncoding, setForeignEncoding)       = mkGlobal initForeignEncoding--mkGlobal :: a -> (IO a, a -> IO ())-mkGlobal x = unsafePerformIO $ do-    x_ref <- newIORef x-    return (readIORef x_ref, writeIORef x_ref)---- | @since 4.5.0.0-initLocaleEncoding, initFileSystemEncoding, initForeignEncoding :: TextEncoding--#if !defined(mingw32_HOST_OS)--- It is rather important that we don't just call Iconv.mkIconvEncoding here--- because some iconvs (in particular GNU iconv) will brokenly UTF-8 encode--- lone surrogates without complaint.------ By going through our Haskell implementations of those encodings, we are--- guaranteed to catch such errors.------ FIXME: this is not a complete solution because if the locale encoding is one--- which we don't have a Haskell-side decoder for, iconv might still ignore the--- lone surrogate in the input.-initLocaleEncoding     = unsafePerformIO $ mkTextEncoding' ErrorOnCodingFailure Iconv.localeEncodingName-initFileSystemEncoding = unsafePerformIO $ mkTextEncoding' RoundtripFailure     Iconv.localeEncodingName-initForeignEncoding    = unsafePerformIO $ mkTextEncoding' IgnoreCodingFailure  Iconv.localeEncodingName-#else-initLocaleEncoding     = CodePage.localeEncoding-initFileSystemEncoding = CodePage.mkLocaleEncoding RoundtripFailure-initForeignEncoding    = CodePage.mkLocaleEncoding IgnoreCodingFailure-#endif---- | An encoding in which Unicode code points are translated to bytes--- by taking the code point modulo 256.  When decoding, bytes are--- translated directly into the equivalent code point.------ This encoding never fails in either direction.  However, encoding--- discards information, so encode followed by decode is not the--- identity.------ @since 4.4.0.0-char8 :: TextEncoding-char8 = Latin1.latin1---- | Look up the named Unicode encoding.  May fail with------  * 'isDoesNotExistError' if the encoding is unknown------ The set of known encodings is system-dependent, but includes at least:------  * @UTF-8@------  * @UTF-16@, @UTF-16BE@, @UTF-16LE@------  * @UTF-32@, @UTF-32BE@, @UTF-32LE@------ There is additional notation (borrowed from GNU iconv) for specifying--- how illegal characters are handled:------  * a suffix of @\/\/IGNORE@, e.g. @UTF-8\/\/IGNORE@, will cause---    all illegal sequences on input to be ignored, and on output---    will drop all code points that have no representation in the---    target encoding.------  * a suffix of @\/\/TRANSLIT@ will choose a replacement character---    for illegal sequences or code points.------  * a suffix of @\/\/ROUNDTRIP@ will use a PEP383-style escape mechanism---    to represent any invalid bytes in the input as Unicode codepoints (specifically,---    as lone surrogates, which are normally invalid in UTF-32).---    Upon output, these special codepoints are detected and turned back into the---    corresponding original byte.------    In theory, this mechanism allows arbitrary data to be roundtripped via---    a 'String' with no loss of data. In practice, there are two limitations---    to be aware of:------      1. This only stands a chance of working for an encoding which is an ASCII---         superset, as for security reasons we refuse to escape any bytes smaller---         than 128. Many encodings of interest are ASCII supersets (in particular,---         you can assume that the locale encoding is an ASCII superset) but many---         (such as UTF-16) are not.------      2. If the underlying encoding is not itself roundtrippable, this mechanism---         can fail. Roundtrippable encodings are those which have an injective mapping---         into Unicode. Almost all encodings meet this criteria, but some do not. Notably,---         Shift-JIS (CP932) and Big5 contain several different encodings of the same---         Unicode codepoint.------ On Windows, you can access supported code pages with the prefix--- @CP@; for example, @\"CP1250\"@.----mkTextEncoding :: String -> IO TextEncoding-mkTextEncoding e = case mb_coding_failure_mode of-    Nothing -> unknownEncodingErr e-    Just cfm -> mkTextEncoding' cfm enc-  where-    (enc, suffix) = span (/= '/') e-    mb_coding_failure_mode = case suffix of-        ""            -> Just ErrorOnCodingFailure-        "//IGNORE"    -> Just IgnoreCodingFailure-        "//TRANSLIT"  -> Just TransliterateCodingFailure-        "//ROUNDTRIP" -> Just RoundtripFailure-        _             -> Nothing--mkTextEncoding' :: CodingFailureMode -> String -> IO TextEncoding-mkTextEncoding' cfm enc =-  case [toUpper c | c <- enc, c /= '-'] of-  -- UTF-8 and friends we can handle ourselves-    "UTF8"    -> return $ UTF8.mkUTF8 cfm-    "UTF16"   -> return $ UTF16.mkUTF16 cfm-    "UTF16LE" -> return $ UTF16.mkUTF16le cfm-    "UTF16BE" -> return $ UTF16.mkUTF16be cfm-    "UTF32"   -> return $ UTF32.mkUTF32 cfm-    "UTF32LE" -> return $ UTF32.mkUTF32le cfm-    "UTF32BE" -> return $ UTF32.mkUTF32be cfm-#if defined(mingw32_HOST_OS)-    'C':'P':n | [(cp,"")] <- reads n -> return $ CodePage.mkCodePageEncoding cfm cp-    _ -> unknownEncodingErr (enc ++ codingFailureModeSuffix cfm)-#else-    -- Otherwise, handle other encoding needs via iconv.--    -- Unfortunately there is no good way to determine whether iconv is actually-    -- functional without telling it to do something.-    _ -> do res <- Iconv.mkIconvEncoding cfm enc-            let isAscii = any (== enc) ansiEncNames-            case res of-              Just e -> return e-              -- At this point we know that we can't count on iconv to work-              -- (see, for instance, Trac #10298). However, we still want to do-              --  what we can to work with what we have. For instance, ASCII is-              -- easy. We match on ASCII encodings directly using several-              -- possible aliases (specified by RFC 1345 & Co) and for this use-              -- the 'ascii' encoding-              Nothing-                | isAscii   -> return (Latin1.mkAscii cfm)-                | otherwise ->-                    unknownEncodingErr (enc ++ codingFailureModeSuffix cfm)-  where-    ansiEncNames = -- ASCII aliases-      [ "ANSI_X3.4-1968", "iso-ir-6", "ANSI_X3.4-1986", "ISO_646.irv:1991"-      , "US-ASCII", "us", "IBM367", "cp367", "csASCII", "ASCII", "ISO646-US"-      ]-#endif---latin1_encode :: CharBuffer -> Buffer Word8 -> IO (CharBuffer, Buffer Word8)-latin1_encode input output = fmap (\(_why,input',output') -> (input',output')) $ Latin1.latin1_encode input output -- unchecked, used for char8---latin1_encode = unsafePerformIO $ do mkTextEncoder Iconv.latin1 >>= return.encode--latin1_decode :: Buffer Word8 -> CharBuffer -> IO (Buffer Word8, CharBuffer)-latin1_decode input output = fmap (\(_why,input',output') -> (input',output')) $ Latin1.latin1_decode input output---latin1_decode = unsafePerformIO $ do mkTextDecoder Iconv.latin1 >>= return.encode--unknownEncodingErr :: String -> IO a-unknownEncodingErr e = ioException (IOError Nothing NoSuchThing "mkTextEncoding"-                                            ("unknown encoding:" ++ e)  Nothing Nothing)
− GHC/IO/Encoding.hs-boot
@@ -1,10 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}--module GHC.IO.Encoding where--import GHC.IO (IO)-import GHC.IO.Encoding.Types--getLocaleEncoding, getFileSystemEncoding, getForeignEncoding :: IO TextEncoding-
− GHC/IO/Encoding/CodePage.hs
@@ -1,184 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, BangPatterns, NoImplicitPrelude,-             NondecreasingIndentation, MagicHash #-}--module GHC.IO.Encoding.CodePage(-#if defined(mingw32_HOST_OS)-                        codePageEncoding, mkCodePageEncoding,-                        localeEncoding, mkLocaleEncoding-#endif-                            ) where--#if !defined(mingw32_HOST_OS)-import GHC.Base () -- Build ordering-#else-import GHC.Base-import GHC.Show-import GHC.Num-import GHC.Enum-import GHC.Word-import GHC.IO (unsafePerformIO)-import GHC.IO.Encoding.Failure-import GHC.IO.Encoding.Types-import GHC.IO.Buffer-import Data.Bits-import Data.Maybe-import Data.OldList (lookup)--import qualified GHC.IO.Encoding.CodePage.API as API-import GHC.IO.Encoding.CodePage.Table--import GHC.IO.Encoding.UTF8 (mkUTF8)-import GHC.IO.Encoding.UTF16 (mkUTF16le, mkUTF16be)-import GHC.IO.Encoding.UTF32 (mkUTF32le, mkUTF32be)--#ifdef mingw32_HOST_OS-# if defined(i386_HOST_ARCH)-#  define WINDOWS_CCONV stdcall-# elif defined(x86_64_HOST_ARCH)-#  define WINDOWS_CCONV ccall-# else-#  error Unknown mingw32 arch-# endif-#endif---- note CodePage = UInt which might not work on Win64.  But the Win32 package--- also has this issue.-getCurrentCodePage :: IO Word32-getCurrentCodePage = do-    conCP <- getConsoleCP-    if conCP > 0-        then return conCP-        else getACP---- Since the Win32 package depends on base, we have to import these ourselves:-foreign import WINDOWS_CCONV unsafe "windows.h GetConsoleCP"-    getConsoleCP :: IO Word32--foreign import WINDOWS_CCONV unsafe "windows.h GetACP"-    getACP :: IO Word32--{-# NOINLINE currentCodePage #-}-currentCodePage :: Word32-currentCodePage = unsafePerformIO getCurrentCodePage--localeEncoding :: TextEncoding-localeEncoding = mkLocaleEncoding ErrorOnCodingFailure--mkLocaleEncoding :: CodingFailureMode -> TextEncoding-mkLocaleEncoding cfm = mkCodePageEncoding cfm currentCodePage---codePageEncoding :: Word32 -> TextEncoding-codePageEncoding = mkCodePageEncoding ErrorOnCodingFailure--mkCodePageEncoding :: CodingFailureMode -> Word32 -> TextEncoding-mkCodePageEncoding cfm 65001 = mkUTF8 cfm-mkCodePageEncoding cfm 1200 = mkUTF16le cfm-mkCodePageEncoding cfm 1201 = mkUTF16be cfm-mkCodePageEncoding cfm 12000 = mkUTF32le cfm-mkCodePageEncoding cfm 12001 = mkUTF32be cfm-mkCodePageEncoding cfm cp = maybe (API.mkCodePageEncoding cfm cp) (buildEncoding cfm cp) (lookup cp codePageMap)--buildEncoding :: CodingFailureMode -> Word32 -> CodePageArrays -> TextEncoding-buildEncoding cfm cp SingleByteCP {decoderArray = dec, encoderArray = enc}-  = TextEncoding {-      textEncodingName = "CP" ++ show cp-    , mkTextDecoder = return $ simpleCodec (recoverDecode cfm) $ decodeFromSingleByte dec-    , mkTextEncoder = return $ simpleCodec (recoverEncode cfm) $ encodeToSingleByte enc-    }--simpleCodec :: (Buffer from -> Buffer to -> IO (Buffer from, Buffer to))-            -> (Buffer from -> Buffer to -> IO (CodingProgress, Buffer from, Buffer to))-                -> BufferCodec from to ()-simpleCodec r f = BufferCodec {-    encode = f,-    recover = r,-    close = return (),-    getState = return (),-    setState = return-  }--decodeFromSingleByte :: ConvArray Char -> DecodeBuffer-decodeFromSingleByte convArr-    input@Buffer  { bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-    output@Buffer { bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }-  = let-        done why !ir !ow = return (why,-                                   if ir==iw then input{ bufL=0, bufR=0}-                                             else input{ bufL=ir},-                                   output {bufR=ow})-        loop !ir !ow-            | ow >= os  = done OutputUnderflow ir ow-            | ir >= iw  = done InputUnderflow ir ow-            | otherwise = do-                b <- readWord8Buf iraw ir-                let c = lookupConv convArr b-                if c=='\0' && b /= 0 then invalid else do-                ow' <- writeCharBuf oraw ow c-                loop (ir+1) ow'-          where-            invalid = done InvalidSequence ir ow-    in loop ir0 ow0--encodeToSingleByte :: CompactArray Char Word8 -> EncodeBuffer-encodeToSingleByte CompactArray { encoderMax = maxChar,-                         encoderIndices = indices,-                         encoderValues = values }-    input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ }-    output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }-  = let-        done why !ir !ow = return (why,-                                   if ir==iw then input { bufL=0, bufR=0 }-                                             else input { bufL=ir },-                                   output {bufR=ow})-        loop !ir !ow-            | ow >= os  = done OutputUnderflow ir ow-            | ir >= iw  = done InputUnderflow ir ow-            | otherwise = do-                (c,ir') <- readCharBuf iraw ir-                case lookupCompact maxChar indices values c of-                    Nothing -> invalid-                    Just 0 | c /= '\0' -> invalid-                    Just b -> do-                        writeWord8Buf oraw ow b-                        loop ir' (ow+1)-            where-                invalid = done InvalidSequence ir ow-    in-    loop ir0 ow0-------------------------------------------------- Array access functions---- {-# INLINE lookupConv #-}-lookupConv :: ConvArray Char -> Word8 -> Char-lookupConv a = indexChar a . fromEnum--{-# INLINE lookupCompact #-}-lookupCompact :: Char -> ConvArray Int -> ConvArray Word8 -> Char -> Maybe Word8-lookupCompact maxVal indexes values x-    | x > maxVal = Nothing-    | otherwise = Just $ indexWord8 values $ j + (i .&. mask)-  where-    i = fromEnum x-    mask = (1 `shiftL` n) - 1-    k = i `shiftR` n-    j = indexInt indexes k-    n = blockBitSize--{-# INLINE indexInt #-}-indexInt :: ConvArray Int -> Int -> Int-indexInt (ConvArray p) (I# i) = I# (indexInt16OffAddr# p i)--{-# INLINE indexWord8 #-}-indexWord8 :: ConvArray Word8 -> Int -> Word8-indexWord8 (ConvArray p) (I# i) = W8# (indexWord8OffAddr# p i)--{-# INLINE indexChar #-}-indexChar :: ConvArray Char -> Int -> Char-indexChar (ConvArray p) (I# i) = C# (chr# (indexInt16OffAddr# p i))--#endif-
− GHC/IO/Encoding/CodePage/API.hs
@@ -1,428 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, NondecreasingIndentation,-             RecordWildCards, ScopedTypeVariables #-}-{-# OPTIONS_GHC -fno-warn-name-shadowing #-}--module GHC.IO.Encoding.CodePage.API (-    mkCodePageEncoding-  ) where--import Foreign.C-import Foreign.Ptr-import Foreign.Marshal-import Foreign.Storable-import Data.Bits-import Data.Either-import Data.Word--import GHC.Base-import GHC.List-import GHC.IO.Buffer-import GHC.IO.Encoding.Failure-import GHC.IO.Encoding.Types-import GHC.IO.Encoding.UTF16-import GHC.Num-import GHC.Show-import GHC.Real-import GHC.Windows-import GHC.ForeignPtr (castForeignPtr)--import System.Posix.Internals---c_DEBUG_DUMP :: Bool-c_DEBUG_DUMP = False--debugIO :: String -> IO ()-debugIO s- | c_DEBUG_DUMP = puts s- | otherwise    = return ()---#if defined(i386_HOST_ARCH)-# define WINDOWS_CCONV stdcall-#elif defined(x86_64_HOST_ARCH)-# define WINDOWS_CCONV ccall-#else-# error Unknown mingw32 arch-#endif---type LPCSTR = Ptr Word8---mAX_DEFAULTCHAR :: Int-mAX_DEFAULTCHAR = 2--mAX_LEADBYTES :: Int-mAX_LEADBYTES = 12---- Don't really care about the contents of this, but we have to make sure the size is right-data CPINFO = CPINFO {-    maxCharSize :: UINT,-    defaultChar :: [BYTE], -- ^ Always of length mAX_DEFAULTCHAR-    leadByte    :: [BYTE]  -- ^ Always of length mAX_LEADBYTES-  }--instance Storable CPINFO where-    sizeOf    _ = sizeOf (undefined :: UINT) + (mAX_DEFAULTCHAR + mAX_LEADBYTES) * sizeOf (undefined :: BYTE)-    alignment _ = alignment (undefined :: CInt)-    peek ptr = do-      ptr <- return $ castPtr ptr-      a <- peek ptr-      ptr <- return $ castPtr $ advancePtr ptr 1-      b <- peekArray mAX_DEFAULTCHAR ptr-      c <- peekArray mAX_LEADBYTES   (advancePtr ptr mAX_DEFAULTCHAR)-      return $ CPINFO a b c-    poke ptr val = do-      ptr <- return $ castPtr ptr-      poke ptr (maxCharSize val)-      ptr <- return $ castPtr $ advancePtr ptr 1-      pokeArray' "CPINFO.defaultChar" mAX_DEFAULTCHAR ptr                              (defaultChar val)-      pokeArray' "CPINFO.leadByte"    mAX_LEADBYTES   (advancePtr ptr mAX_DEFAULTCHAR) (leadByte val)--pokeArray' :: Storable a => String -> Int -> Ptr a -> [a] -> IO ()-pokeArray' msg sz ptr xs | length xs == sz = pokeArray ptr xs-                         | otherwise       = error $ msg ++ ": expected " ++ show sz ++ " elements in list but got " ++ show (length xs)---foreign import WINDOWS_CCONV unsafe "windows.h GetCPInfo"-    c_GetCPInfo :: UINT       -- ^ CodePage-                -> Ptr CPINFO -- ^ lpCPInfo-                -> IO BOOL--foreign import WINDOWS_CCONV unsafe "windows.h MultiByteToWideChar"-    c_MultiByteToWideChar :: UINT   -- ^ CodePage-                          -> DWORD  -- ^ dwFlags-                          -> LPCSTR -- ^ lpMultiByteStr-                          -> CInt   -- ^ cbMultiByte-                          -> LPWSTR -- ^ lpWideCharStr-                          -> CInt   -- ^ cchWideChar-                          -> IO CInt--foreign import WINDOWS_CCONV unsafe "windows.h WideCharToMultiByte"-    c_WideCharToMultiByte :: UINT   -- ^ CodePage-                          -> DWORD  -- ^ dwFlags-                          -> LPWSTR -- ^ lpWideCharStr-                          -> CInt   -- ^ cchWideChar-                          -> LPCSTR -- ^ lpMultiByteStr-                          -> CInt   -- ^ cbMultiByte-                          -> LPCSTR -- ^ lpDefaultChar-                          -> LPBOOL -- ^ lpUsedDefaultChar-                          -> IO CInt--foreign import WINDOWS_CCONV unsafe "windows.h IsDBCSLeadByteEx"-    c_IsDBCSLeadByteEx :: UINT    -- ^ CodePage-                       -> BYTE    -- ^ TestChar-                       -> IO BOOL----- | Returns a slow but correct implementation of TextEncoding using the Win32 API.------ This is useful for supporting DBCS text encoding on the console without having to statically link--- in huge code tables into all of our executables, or just as a fallback mechanism if a new code page--- is introduced that we don't know how to deal with ourselves yet.-mkCodePageEncoding :: CodingFailureMode -> Word32 -> TextEncoding-mkCodePageEncoding cfm cp-  = TextEncoding {-        textEncodingName = "CP" ++ show cp,-        mkTextDecoder = newCP (recoverDecode cfm) cpDecode cp,-        mkTextEncoder = newCP (recoverEncode cfm) cpEncode cp-      }--newCP :: (Buffer from -> Buffer to -> IO (Buffer from, Buffer to))-      -> (Word32 -> Int -> CodeBuffer from to)-      -> Word32-      -> IO (BufferCodec from to ())-newCP rec fn cp = do-  -- Fail early if the code page doesn't exist, to match the behaviour of the IConv TextEncoding-  max_char_size <- alloca $ \cpinfo_ptr -> do-    success <- c_GetCPInfo cp cpinfo_ptr-    when (not success) $ throwGetLastError ("GetCPInfo " ++ show cp)-    fmap (fromIntegral . maxCharSize) $ peek cpinfo_ptr--  debugIO $ "GetCPInfo " ++ show cp ++ " = " ++ show max_char_size--  return $ BufferCodec {-    encode = fn cp max_char_size,-    recover = rec,-    close  = return (),-    -- Windows doesn't supply a way to save/restore the state and doesn't need one-    -- since it's a dumb string->string API rather than a clever streaming one.-    getState = return (),-    setState = const $ return ()-  }---utf16_native_encode' :: EncodeBuffer-utf16_native_decode' :: DecodeBuffer-#ifdef WORDS_BIGENDIAN-utf16_native_encode' = utf16be_encode-utf16_native_decode' = utf16be_decode-#else-utf16_native_encode' = utf16le_encode-utf16_native_decode' = utf16le_decode-#endif--saner :: CodeBuffer from to-      -> Buffer from -> Buffer to-      -> IO (CodingProgress, Int, Buffer from, Buffer to)-saner code ibuf obuf = do-  (why, ibuf', obuf') <- code ibuf obuf-  -- Weird but true: the UTF16 codes have a special case (see the "done" functions)-  -- whereby if they entirely consume the input instead of returning an input buffer-  -- that is empty because bufL has reached bufR, they return a buffer that is empty-  -- because bufL = bufR = 0.-  ---  -- This is really very odd and confusing for our code that expects the difference-  -- between the old and new input buffer bufLs to indicate the number of elements-  -- that were consumed!-  ---  -- We fix it by explicitly extracting an integer which is the # of things consumed, like so:-  if isEmptyBuffer ibuf'-   then return (InputUnderflow, bufferElems ibuf,       ibuf', obuf')-   else return (why,            bufL ibuf' - bufL ibuf, ibuf', obuf')--byteView :: Buffer CWchar -> Buffer Word8-byteView (Buffer {..}) = Buffer { bufState = bufState, bufRaw = castForeignPtr bufRaw, bufSize = bufSize * 2, bufL = bufL * 2, bufR = bufR * 2 }--cwcharView :: Buffer Word8 -> Buffer CWchar-cwcharView (Buffer {..}) = Buffer { bufState = bufState, bufRaw = castForeignPtr bufRaw, bufSize = half bufSize, bufL = half bufL, bufR = half bufR }-  where half x = case x `divMod` 2 of (y, 0) -> y-                                      _      -> error "cwcharView: utf16_(encode|decode) (wrote out|consumed) non multiple-of-2 number of bytes"--utf16_native_encode :: CodeBuffer Char CWchar-utf16_native_encode ibuf obuf = do-  (why, ibuf, obuf) <- utf16_native_encode' ibuf (byteView obuf)-  return (why, ibuf, cwcharView obuf)--utf16_native_decode :: CodeBuffer CWchar Char-utf16_native_decode ibuf obuf = do-  (why, ibuf, obuf) <- utf16_native_decode' (byteView ibuf) obuf-  return (why, cwcharView ibuf, obuf)--cpDecode :: Word32 -> Int -> DecodeBuffer-cpDecode cp max_char_size = \ibuf obuf -> do-#ifdef CHARBUF_UTF16-    let mbuf = obuf-#else-    -- FIXME: share the buffer between runs, even if the buffer is not the perfect size-    let sz =       (bufferElems ibuf * 2)     -- I guess in the worst case the input CP text consists of 1-byte sequences that map entirely to things outside the BMP and so require 2 UTF-16 chars-             `min` (bufferAvailable obuf * 2) -- In the best case, each pair of UTF-16 points becomes a single UTF-32 point-    mbuf <- newBuffer (2 * sz) sz WriteBuffer :: IO (Buffer CWchar)-#endif-    debugIO $ "cpDecode " ++ summaryBuffer ibuf ++ " " ++ summaryBuffer mbuf-    (why1, ibuf', mbuf') <- cpRecode try' is_valid_prefix max_char_size 1 0 1 ibuf mbuf-    debugIO $ "cpRecode (cpDecode) = " ++ show why1 ++ " " ++ summaryBuffer ibuf' ++ " " ++ summaryBuffer mbuf'-#ifdef CHARBUF_UTF16-    return (why1, ibuf', mbuf')-#else-    -- Convert as much UTF-16 as possible to UTF-32. Note that it's impossible for this to fail-    -- due to illegal characters since the output from Window's encoding function should be correct UTF-16.-    -- However, it's perfectly possible to run out of either output or input buffer.-    debugIO $ "utf16_native_decode " ++ summaryBuffer mbuf' ++ " " ++ summaryBuffer obuf-    (why2, target_utf16_count, mbuf', obuf) <- saner utf16_native_decode (mbuf' { bufState = ReadBuffer }) obuf-    debugIO $ "utf16_native_decode = " ++ show why2 ++ " " ++ summaryBuffer mbuf' ++ " " ++ summaryBuffer obuf-    case why2 of-      -- If we successfully translate all of the UTF-16 buffer, we need to know why we couldn't get any more-      -- UTF-16 out of the Windows API-      InputUnderflow | isEmptyBuffer mbuf' -> return (why1, ibuf', obuf)-                     | otherwise           -> error "cpDecode: impossible underflown UTF-16 buffer"-      -- InvalidSequence should be impossible since mbuf' is output from Windows.-      InvalidSequence -> error "InvalidSequence on output of Windows API"-      -- If we run out of space in obuf, we need to ask for more output buffer space, while also returning-      -- the characters we have managed to consume so far.-      OutputUnderflow -> do-        -- We have an interesting problem here similar to the cpEncode case where we have to figure out how much-        -- of the byte buffer was consumed to reach as far as the last UTF-16 character we actually decoded to UTF-32 OK.-        ---        -- The minimum number of bytes it could take is half the number of UTF-16 chars we got on the output, since-        -- one byte could theoretically generate two UTF-16 characters.-        -- The common case (ASCII text) is that every byte in the input maps to a single UTF-16 character.-        -- In the worst case max_char_size bytes map to each UTF-16 character.-        byte_count <- bSearch "cpDecode" (cpRecode try' is_valid_prefix max_char_size 1 0 1) ibuf mbuf target_utf16_count (target_utf16_count `div` 2) target_utf16_count (target_utf16_count * max_char_size)-        return (OutputUnderflow, bufferRemove byte_count ibuf, obuf)-#endif-  where-    is_valid_prefix = c_IsDBCSLeadByteEx cp-    try' iptr icnt optr ocnt-     -- MultiByteToWideChar does surprising things if you have ocnt == 0-     | ocnt == 0 = return (Left True)-     | otherwise = do-        err <- c_MultiByteToWideChar (fromIntegral cp) 8 -- MB_ERR_INVALID_CHARS == 8: Fail if an invalid input character is encountered-                                     iptr (fromIntegral icnt) optr (fromIntegral ocnt)-        debugIO $ "MultiByteToWideChar " ++ show cp ++ " 8 " ++ show iptr ++ " " ++ show icnt ++ " " ++ show optr ++ " " ++ show ocnt ++ "\n = " ++ show err-        case err of-          -- 0 indicates that we did not succeed-          0 -> do-            err <- getLastError-            case err of-                122  -> return (Left True)-                1113 -> return (Left False)-                _    -> failWith "MultiByteToWideChar" err-          wrote_chars -> return (Right (fromIntegral wrote_chars))--cpEncode :: Word32 -> Int -> EncodeBuffer-cpEncode cp _max_char_size = \ibuf obuf -> do-#ifdef CHARBUF_UTF16-    let mbuf' = ibuf-#else-    -- FIXME: share the buffer between runs, even though that means we can't size the buffer as we want.-    let sz =       (bufferElems ibuf * 2)     -- UTF-32 always uses 4 bytes. UTF-16 uses at most 4 bytes.-             `min` (bufferAvailable obuf * 2) -- In the best case, each pair of UTF-16 points fits into only 1 byte-    mbuf <- newBuffer (2 * sz) sz WriteBuffer--    -- Convert as much UTF-32 as possible to UTF-16. NB: this can't fail due to output underflow-    -- since we sized the output buffer correctly. However, it could fail due to an illegal character-    -- in the input if it encounters a lone surrogate. In this case, our recovery will be applied as normal.-    (why1, ibuf', mbuf') <- utf16_native_encode ibuf mbuf-#endif-    debugIO $ "\ncpEncode " ++ summaryBuffer mbuf' ++ " " ++ summaryBuffer obuf-    (why2, target_utf16_count, mbuf', obuf) <- saner (cpRecode try' is_valid_prefix 2 1 1 0) (mbuf' { bufState = ReadBuffer }) obuf-    debugIO $ "cpRecode (cpEncode) = " ++ show why2 ++ " " ++ summaryBuffer mbuf' ++ " " ++ summaryBuffer obuf-#ifdef CHARBUF_UTF16-    return (why2, mbuf', obuf)-#else-    case why2 of-      -- If we succesfully translate all of the UTF-16 buffer, we need to know why-      -- we weren't able to get any more UTF-16 out of the UTF-32 buffer-      InputUnderflow | isEmptyBuffer mbuf' -> return (why1, ibuf', obuf)-                     | otherwise           -> error "cpEncode: impossible underflown UTF-16 buffer"-      -- With OutputUnderflow/InvalidSequence we only care about the failings of the UTF-16->CP translation.-      -- Yes, InvalidSequence is possible even though mbuf' is guaranteed to be valid UTF-16, because-      -- the code page may not be able to represent the encoded Unicode codepoint.-      _ -> do-        -- Here is an interesting problem. If we have only managed to translate part of the mbuf'-        -- then we need to return an ibuf which has consumed exactly those bytes required to obtain-        -- that part of the mbuf'. To reconstruct this information, we binary search for the number of-        -- UTF-32 characters required to get the consumed count of UTF-16 characters:-        ---        -- When dealing with data from the BMP (the common case), consuming N UTF-16 characters will be the same as consuming N-        -- UTF-32 characters. We start our search there so that most binary searches will terminate in a single iteration.-        -- Furthermore, the absolute minimum number of UTF-32 characters this can correspond to is 1/2 the UTF-16 byte count-        -- (this will be realised when the input data is entirely not in the BMP).-        utf32_count <- bSearch "cpEncode" utf16_native_encode ibuf mbuf target_utf16_count (target_utf16_count `div` 2) target_utf16_count target_utf16_count-        return (why2, bufferRemove utf32_count ibuf, obuf)-#endif-  where-    -- Single characters should be mappable to bytes. If they aren't supported by the CP then we have an invalid input sequence.-    is_valid_prefix _ = return False--    try' iptr icnt optr ocnt-     -- WideCharToMultiByte does surprising things if you call it with ocnt == 0-     | ocnt == 0 = return (Left True)-     | otherwise = alloca $ \defaulted_ptr -> do-      poke defaulted_ptr False-      err <- c_WideCharToMultiByte (fromIntegral cp) 0 -- NB: the WC_ERR_INVALID_CHARS flag is uselses: only has an effect with the UTF-8 code page-                                   iptr (fromIntegral icnt) optr (fromIntegral ocnt)-                                   nullPtr defaulted_ptr-      defaulted <- peek defaulted_ptr-      debugIO $ "WideCharToMultiByte " ++ show cp ++ " 0 " ++ show iptr ++ " " ++ show icnt ++ " " ++ show optr ++ " " ++ show ocnt ++ " NULL " ++ show defaulted_ptr ++ "\n = " ++ show err ++ ", " ++ show defaulted-      case err of-          -- 0 indicates that we did not succeed-          0 -> do-            err <- getLastError-            case err of-                122  -> return (Left True)-                1113 -> return (Left False)-                _    -> failWith "WideCharToMultiByte" err-          wrote_bytes | defaulted -> return (Left False)-                      | otherwise -> return (Right (fromIntegral wrote_bytes))--bSearch :: String-        -> CodeBuffer from to-        -> Buffer from -> Buffer to -- From buffer (crucial data source) and to buffer (temporary storage only). To buffer must be empty (L=R).-        -> Int               -- Target size of to buffer-        -> Int -> Int -> Int -- Binary search min, mid, max-        -> IO Int            -- Size of from buffer required to reach target size of to buffer-bSearch msg code ibuf mbuf target_to_elems = go-  where-    go mn md mx = do-      -- NB: this loop repeatedly reencodes on top of mbuf using a varying fraction of ibuf. It doesn't-      -- matter if we blast the contents of mbuf since we already consumed all of the contents we are going to use.-      (_why, ibuf, mbuf) <- code (ibuf { bufR = bufL ibuf + md }) mbuf-      debugIO $ "code (bSearch " ++ msg ++ ") " ++ show md ++ " = " ++ show _why ++ ", " ++ summaryBuffer ibuf ++ summaryBuffer mbuf-      -- The normal case is to get InputUnderflow here, which indicates that coding basically-      -- terminated normally.-      ---      -- However, InvalidSequence is also possible if we are being called from cpDecode if we-      -- have just been unlucky enough to set md so that ibuf straddles a byte boundary.-      -- In this case we have to be really careful, because we don't want to report that-      -- "md" elements is the right number when in actual fact we could have had md-1 input-      -- elements and still produced the same number of bufferElems in mbuf.-      ---      -- In fact, we have to worry about this possibility even if we get InputUnderflow-      -- since that will report InputUnderflow rather than InvalidSequence if the buffer-      -- ends in a valid lead byte. So the expedient thing to do is simply to check if-      -- the input buffer was entirely consumed.-      ---      -- When called from cpDecode, OutputUnderflow is also possible.-      ---      -- Luckily if we have InvalidSequence/OutputUnderflow and we do not appear to have reached-      -- the target, what we should do is the same as normal because the fraction of ibuf that our-      -- first "code" coded succesfully must be invalid-sequence-free, and ibuf will always-      -- have been decoded as far as the first invalid sequence in it.-      case bufferElems mbuf `compare` target_to_elems of-        -- Coding n "from" chars from the input yields exactly as many "to" chars-        -- as were consumed by the recode. All is peachy:-        EQ -> debugIO ("bSearch = " ++ show solution) >> return solution-          where solution = md - bufferElems ibuf-        -- If we encoded fewer "to" characters than the target number, try again with more "from" characters (and vice-versa)-        LT -> go' (md+1) mx-        GT -> go' mn (md-1)-    go' mn mx | mn <= mx  = go mn (mn + ((mx - mn) `div` 2)) mx-              | otherwise = error $ "bSearch(" ++ msg ++ "): search crossed! " ++ show (summaryBuffer ibuf, summaryBuffer mbuf, target_to_elems, mn, mx)--cpRecode :: forall from to. (Show from, Storable from)-         => (Ptr from -> Int -> Ptr to -> Int -> IO (Either Bool Int))-         -> (from -> IO Bool)-         -> Int -- ^ Maximum length of a complete translatable sequence in the input (e.g. 2 if the input is UTF-16, 1 if the input is a SBCS, 2 is the input is a DBCS). Must be at least 1.-         -> Int -- ^ Minimum number of output elements per complete translatable sequence in the input (almost certainly 1)-         -> Int -> Int-         -> CodeBuffer from to-cpRecode try' is_valid_prefix max_i_size min_o_size iscale oscale = go-  where-    go :: CodeBuffer from to-    go ibuf obuf | isEmptyBuffer ibuf                = return (InputUnderflow,  ibuf, obuf)-                 | bufferAvailable obuf < min_o_size = return (OutputUnderflow, ibuf, obuf)-                 | otherwise                         = try (bufferElems ibuf `min` ((max_i_size * bufferAvailable obuf) `div` min_o_size)) seek_smaller-      where-        done why = return (why, ibuf, obuf)--        seek_smaller n longer_was_valid-          -- In this case, we can't shrink any further via any method. Calling (try 0) wouldn't be right because that will always claim InputUnderflow...-          | n <= 1 = if longer_was_valid-                      -- try m (where m >= n) was valid but we overflowed the output buffer with even a single input element-                      then done OutputUnderflow-                      -- there was no initial valid sequence in the input, but it might just be a truncated buffer - we need to check-                      else do byte <- withBuffer ibuf $ \ptr -> peekElemOff ptr (bufL ibuf)-                              valid_prefix <- is_valid_prefix byte-                              done (if valid_prefix && bufferElems ibuf < max_i_size then InputUnderflow else InvalidSequence)-          -- If we're already looking at very small buffers, try every n down to 1, to ensure we spot as long a sequence as exists while avoiding trying 0.-          -- Doing it this way ensures that we spot a single initial sequence of length <= max_i_size if any such exists.-          | n < 2 * max_i_size = try (n - 1) (\pred_n pred_n_was_valid -> seek_smaller pred_n (longer_was_valid || pred_n_was_valid))-          -- Otherwise, try a binary chop to try to either get the prefix before the invalid input, or shrink the output down so it fits-          -- in the output buffer. After the chop, try to consume extra input elements to try to recover as much of the sequence as possible if we-          -- end up chopping a multi-element input sequence into two parts.-          ---          -- Note that since max_i_size >= 1:-          --  * (n `div` 2) >= 1, so we don't try 0-          --  * ((n `div` 2) + (max_i_size - 1)) < n, so we don't get into a loop where (seek_smaller n) calls post_divide (n `div` 2) calls (seek_smaller n)-          | let n' = n `div` 2 = try n' (post_divide n' longer_was_valid)--        post_divide _  _                n True  = seek_smaller n True-        post_divide n' longer_was_valid n False | n < n' + max_i_size - 1 = try (n + 1) (post_divide n' longer_was_valid) -- There's still a chance..-                                                | otherwise               = seek_smaller n' longer_was_valid              -- No amount of recovery could save us :(--        try n k_fail = withBuffer ibuf $ \iptr -> withBuffer obuf $ \optr -> do-          ei_err_wrote <- try' (iptr `plusPtr` (bufL ibuf `shiftL` iscale)) n-                               (optr `plusPtr` (bufR obuf `shiftL` oscale)) (bufferAvailable obuf)-          debugIO $ "try " ++ show n ++ " = " ++ show ei_err_wrote-          case ei_err_wrote of-            -- ERROR_INSUFFICIENT_BUFFER: A supplied buffer size was not large enough, or it was incorrectly set to NULL.-            Left True  -> k_fail n True-            -- ERROR_NO_UNICODE_TRANSLATION: Invalid Unicode was found in a string.-            Left False -> k_fail n False-            -- Must have interpreted all given bytes successfully-            -- We need to iterate until we have consumed the complete contents of the buffer-            Right wrote_elts -> go (bufferRemove n ibuf) (obuf { bufR = bufR obuf + wrote_elts })
− GHC/IO/Encoding/CodePage/Table.hs
@@ -1,432 +0,0 @@-{-# LANGUAGE MagicHash, NoImplicitPrelude #-}--- Do not edit this file directly!--- It was generated by the MakeTable.hs script using the files below.--- To regenerate it, run "make" in ../../../../codepages/--- --- Files:--- CP037.TXT--- CP1026.TXT--- CP1250.TXT--- CP1251.TXT--- CP1252.TXT--- CP1253.TXT--- CP1254.TXT--- CP1255.TXT--- CP1256.TXT--- CP1257.TXT--- CP1258.TXT--- CP437.TXT--- CP500.TXT--- CP737.TXT--- CP775.TXT--- CP850.TXT--- CP852.TXT--- CP855.TXT--- CP857.TXT--- CP860.TXT--- CP861.TXT--- CP862.TXT--- CP863.TXT--- CP864.TXT--- CP865.TXT--- CP866.TXT--- CP869.TXT--- CP874.TXT--- CP875.TXT-module GHC.IO.Encoding.CodePage.Table where--import GHC.Prim-import GHC.Base-import GHC.Word-data ConvArray a = ConvArray Addr#-data CompactArray a b = CompactArray {-    encoderMax :: !a,-    encoderIndices :: !(ConvArray Int),-    encoderValues :: !(ConvArray b)-  }--data CodePageArrays = SingleByteCP {-    decoderArray :: !(ConvArray Char),-    encoderArray :: !(CompactArray Char Word8)-  }--blockBitSize :: Int-blockBitSize = 6-codePageMap :: [(Word32, CodePageArrays)]-codePageMap = [-    (37, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x9c\x0\x9\x0\x86\x0\x7f\x0\x97\x0\x8d\x0\x8e\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x9d\x0\x85\x0\x8\x0\x87\x0\x18\x0\x19\x0\x92\x0\x8f\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x80\x0\x81\x0\x82\x0\x83\x0\x84\x0\xa\x0\x17\x0\x1b\x0\x88\x0\x89\x0\x8a\x0\x8b\x0\x8c\x0\x5\x0\x6\x0\x7\x0\x90\x0\x91\x0\x16\x0\x93\x0\x94\x0\x95\x0\x96\x0\x4\x0\x98\x0\x99\x0\x9a\x0\x9b\x0\x14\x0\x15\x0\x9e\x0\x1a\x0\x20\x0\xa0\x0\xe2\x0\xe4\x0\xe0\x0\xe1\x0\xe3\x0\xe5\x0\xe7\x0\xf1\x0\xa2\x0\x2e\x0\x3c\x0\x28\x0\x2b\x0\x7c\x0\x26\x0\xe9\x0\xea\x0\xeb\x0\xe8\x0\xed\x0\xee\x0\xef\x0\xec\x0\xdf\x0\x21\x0\x24\x0\x2a\x0\x29\x0\x3b\x0\xac\x0\x2d\x0\x2f\x0\xc2\x0\xc4\x0\xc0\x0\xc1\x0\xc3\x0\xc5\x0\xc7\x0\xd1\x0\xa6\x0\x2c\x0\x25\x0\x5f\x0\x3e\x0\x3f\x0\xf8\x0\xc9\x0\xca\x0\xcb\x0\xc8\x0\xcd\x0\xce\x0\xcf\x0\xcc\x0\x60\x0\x3a\x0\x23\x0\x40\x0\x27\x0\x3d\x0\x22\x0\xd8\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\xab\x0\xbb\x0\xf0\x0\xfd\x0\xfe\x0\xb1\x0\xb0\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\xaa\x0\xba\x0\xe6\x0\xb8\x0\xc6\x0\xa4\x0\xb5\x0\x7e\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\xa1\x0\xbf\x0\xd0\x0\xdd\x0\xde\x0\xae\x0\x5e\x0\xa3\x0\xa5\x0\xb7\x0\xa9\x0\xa7\x0\xb6\x0\xbc\x0\xbd\x0\xbe\x0\x5b\x0\x5d\x0\xaf\x0\xa8\x0\xb4\x0\xd7\x0\x7b\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\xad\x0\xf4\x0\xf6\x0\xf2\x0\xf3\x0\xf5\x0\x7d\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\xb9\x0\xfb\x0\xfc\x0\xf9\x0\xfa\x0\xff\x0\x5c\x0\xf7\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\xb2\x0\xd4\x0\xd6\x0\xd2\x0\xd3\x0\xd5\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\xb3\x0\xdb\x0\xdc\x0\xd9\x0\xda\x0\x9f\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x37\x2d\x2e\x2f\x16\x5\x25\xb\xc\xd\xe\xf\x10\x11\x12\x13\x3c\x3d\x32\x26\x18\x19\x3f\x27\x1c\x1d\x1e\x1f\x40\x5a\x7f\x7b\x5b\x6c\x50\x7d\x4d\x5d\x5c\x4e\x6b\x60\x4b\x61\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\x7a\x5e\x4c\x7e\x6e\x6f\x7c\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xba\xe0\xbb\xb0\x6d\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96\x97\x98\x99\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xc0\x4f\xd0\xa1\x7\x20\x21\x22\x23\x24\x15\x6\x17\x28\x29\x2a\x2b\x2c\x9\xa\x1b\x30\x31\x1a\x33\x34\x35\x36\x8\x38\x39\x3a\x3b\x4\x14\x3e\xff\x41\xaa\x4a\xb1\x9f\xb2\x6a\xb5\xbd\xb4\x9a\x8a\x5f\xca\xaf\xbc\x90\x8f\xea\xfa\xbe\xa0\xb6\xb3\x9d\xda\x9b\x8b\xb7\xb8\xb9\xab\x64\x65\x62\x66\x63\x67\x9e\x68\x74\x71\x72\x73\x78\x75\x76\x77\xac\x69\xed\xee\xeb\xef\xec\xbf\x80\xfd\xfe\xfb\xfc\xad\xae\x59\x44\x45\x42\x46\x43\x47\x9c\x48\x54\x51\x52\x53\x58\x55\x56\x57\x8c\x49\xcd\xce\xcb\xcf\xcc\xe1\x70\xdd\xde\xdb\xdc\x8d\x8e\xdf"#-        , encoderMax = '\255'-        }--   }-    )--    ,-    (1026, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x9c\x0\x9\x0\x86\x0\x7f\x0\x97\x0\x8d\x0\x8e\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x9d\x0\x85\x0\x8\x0\x87\x0\x18\x0\x19\x0\x92\x0\x8f\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x80\x0\x81\x0\x82\x0\x83\x0\x84\x0\xa\x0\x17\x0\x1b\x0\x88\x0\x89\x0\x8a\x0\x8b\x0\x8c\x0\x5\x0\x6\x0\x7\x0\x90\x0\x91\x0\x16\x0\x93\x0\x94\x0\x95\x0\x96\x0\x4\x0\x98\x0\x99\x0\x9a\x0\x9b\x0\x14\x0\x15\x0\x9e\x0\x1a\x0\x20\x0\xa0\x0\xe2\x0\xe4\x0\xe0\x0\xe1\x0\xe3\x0\xe5\x0\x7b\x0\xf1\x0\xc7\x0\x2e\x0\x3c\x0\x28\x0\x2b\x0\x21\x0\x26\x0\xe9\x0\xea\x0\xeb\x0\xe8\x0\xed\x0\xee\x0\xef\x0\xec\x0\xdf\x0\x1e\x1\x30\x1\x2a\x0\x29\x0\x3b\x0\x5e\x0\x2d\x0\x2f\x0\xc2\x0\xc4\x0\xc0\x0\xc1\x0\xc3\x0\xc5\x0\x5b\x0\xd1\x0\x5f\x1\x2c\x0\x25\x0\x5f\x0\x3e\x0\x3f\x0\xf8\x0\xc9\x0\xca\x0\xcb\x0\xc8\x0\xcd\x0\xce\x0\xcf\x0\xcc\x0\x31\x1\x3a\x0\xd6\x0\x5e\x1\x27\x0\x3d\x0\xdc\x0\xd8\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\xab\x0\xbb\x0\x7d\x0\x60\x0\xa6\x0\xb1\x0\xb0\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\xaa\x0\xba\x0\xe6\x0\xb8\x0\xc6\x0\xa4\x0\xb5\x0\xf6\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\xa1\x0\xbf\x0\x5d\x0\x24\x0\x40\x0\xae\x0\xa2\x0\xa3\x0\xa5\x0\xb7\x0\xa9\x0\xa7\x0\xb6\x0\xbc\x0\xbd\x0\xbe\x0\xac\x0\x7c\x0\xaf\x0\xa8\x0\xb4\x0\xd7\x0\xe7\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\xad\x0\xf4\x0\x7e\x0\xf2\x0\xf3\x0\xf5\x0\x1f\x1\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\xb9\x0\xfb\x0\x5c\x0\xf9\x0\xfa\x0\xff\x0\xfc\x0\xf7\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\xb2\x0\xd4\x0\x23\x0\xd2\x0\xd3\x0\xd5\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\xb3\x0\xdb\x0\x22\x0\xd9\x0\xda\x0\x9f\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x37\x2d\x2e\x2f\x16\x5\x25\xb\xc\xd\xe\xf\x10\x11\x12\x13\x3c\x3d\x32\x26\x18\x19\x3f\x27\x1c\x1d\x1e\x1f\x40\x4f\xfc\xec\xad\x6c\x50\x7d\x4d\x5d\x5c\x4e\x6b\x60\x4b\x61\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\x7a\x5e\x4c\x7e\x6e\x6f\xae\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\x68\xdc\xac\x5f\x6d\x8d\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96\x97\x98\x99\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\x48\xbb\x8c\xcc\x7\x20\x21\x22\x23\x24\x15\x6\x17\x28\x29\x2a\x2b\x2c\x9\xa\x1b\x30\x31\x1a\x33\x34\x35\x36\x8\x38\x39\x3a\x3b\x4\x14\x3e\xff\x41\xaa\xb0\xb1\x9f\xb2\x8e\xb5\xbd\xb4\x9a\x8a\xba\xca\xaf\xbc\x90\x8f\xea\xfa\xbe\xa0\xb6\xb3\x9d\xda\x9b\x8b\xb7\xb8\xb9\xab\x64\x65\x62\x66\x63\x67\x9e\x4a\x74\x71\x72\x73\x78\x75\x76\x77\x0\x69\xed\xee\xeb\xef\x7b\xbf\x80\xfd\xfe\xfb\x7f\x0\x0\x59\x44\x45\x42\x46\x43\x47\x9c\xc0\x54\x51\x52\x53\x58\x55\x56\x57\x0\x49\xcd\xce\xcb\xcf\xa1\xe1\x70\xdd\xde\xdb\xe0\x0\x0\xdf\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x5a\xd0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x5b\x79\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x7c\x6a"#-        , encoderMax = '\351'-        }--   }-    )--    ,-    (1250, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xac\x20\x0\x0\x1a\x20\x0\x0\x1e\x20\x26\x20\x20\x20\x21\x20\x0\x0\x30\x20\x60\x1\x39\x20\x5a\x1\x64\x1\x7d\x1\x79\x1\x0\x0\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\x0\x0\x22\x21\x61\x1\x3a\x20\x5b\x1\x65\x1\x7e\x1\x7a\x1\xa0\x0\xc7\x2\xd8\x2\x41\x1\xa4\x0\x4\x1\xa6\x0\xa7\x0\xa8\x0\xa9\x0\x5e\x1\xab\x0\xac\x0\xad\x0\xae\x0\x7b\x1\xb0\x0\xb1\x0\xdb\x2\x42\x1\xb4\x0\xb5\x0\xb6\x0\xb7\x0\xb8\x0\x5\x1\x5f\x1\xbb\x0\x3d\x1\xdd\x2\x3e\x1\x7c\x1\x54\x1\xc1\x0\xc2\x0\x2\x1\xc4\x0\x39\x1\x6\x1\xc7\x0\xc\x1\xc9\x0\x18\x1\xcb\x0\x1a\x1\xcd\x0\xce\x0\xe\x1\x10\x1\x43\x1\x47\x1\xd3\x0\xd4\x0\x50\x1\xd6\x0\xd7\x0\x58\x1\x6e\x1\xda\x0\x70\x1\xdc\x0\xdd\x0\x62\x1\xdf\x0\x55\x1\xe1\x0\xe2\x0\x3\x1\xe4\x0\x3a\x1\x7\x1\xe7\x0\xd\x1\xe9\x0\x19\x1\xeb\x0\x1b\x1\xed\x0\xee\x0\xf\x1\x11\x1\x44\x1\x48\x1\xf3\x0\xf4\x0\x51\x1\xf6\x0\xf7\x0\x59\x1\x6f\x1\xfa\x0\x71\x1\xfc\x0\xfd\x0\x63\x1\xd9\x2"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\xc0\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x0\x2\x80\x1\x40\x2\x80\x1\x80\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\x0\x0\xa4\x0\xa6\xa7\xa8\xa9\x0\xab\xac\xad\xae\x0\xb0\xb1\x0\x0\xb4\xb5\xb6\xb7\xb8\x0\x0\xbb\x0\x0\x0\x0\x0\xc1\xc2\x0\xc4\x0\x0\xc7\x0\xc9\x0\xcb\x0\xcd\xce\x0\x0\x0\x0\xd3\xd4\x0\xd6\xd7\x0\x0\xda\x0\xdc\xdd\x0\xdf\x0\xe1\xe2\x0\xe4\x0\x0\xe7\x0\xe9\x0\xeb\x0\xed\xee\x0\x0\x0\x0\xf3\xf4\x0\xf6\xf7\x0\x0\xfa\x0\xfc\xfd\x0\x0\x0\x0\xc3\xe3\xa5\xb9\xc6\xe6\x0\x0\x0\x0\xc8\xe8\xcf\xef\xd0\xf0\x0\x0\x0\x0\x0\x0\xca\xea\xcc\xec\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc5\xe5\x0\x0\xbc\xbe\x0\x0\xa3\xb3\xd1\xf1\x0\x0\xd2\xf2\x0\x0\x0\x0\x0\x0\x0\xd5\xf5\x0\x0\xc0\xe0\x0\x0\xd8\xf8\x8c\x9c\x0\x0\xaa\xba\x8a\x9a\xde\xfe\x8d\x9d\x0\x0\x0\x0\x0\x0\x0\x0\xd9\xf9\xdb\xfb\x0\x0\x0\x0\x0\x0\x0\x8f\x9f\xaf\xbf\x8e\x9e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa1\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa2\xff\x0\xb2\x0\xbd\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x96\x97\x0\x0\x0\x91\x92\x82\x0\x93\x94\x84\x0\x86\x87\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x0\x8b\x9b\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x80\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x99"#-        , encoderMax = '\8482'-        }--   }-    )--    ,-    (1251, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\x2\x4\x3\x4\x1a\x20\x53\x4\x1e\x20\x26\x20\x20\x20\x21\x20\xac\x20\x30\x20\x9\x4\x39\x20\xa\x4\xc\x4\xb\x4\xf\x4\x52\x4\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\x0\x0\x22\x21\x59\x4\x3a\x20\x5a\x4\x5c\x4\x5b\x4\x5f\x4\xa0\x0\xe\x4\x5e\x4\x8\x4\xa4\x0\x90\x4\xa6\x0\xa7\x0\x1\x4\xa9\x0\x4\x4\xab\x0\xac\x0\xad\x0\xae\x0\x7\x4\xb0\x0\xb1\x0\x6\x4\x56\x4\x91\x4\xb5\x0\xb6\x0\xb7\x0\x51\x4\x16\x21\x54\x4\xbb\x0\x58\x4\x5\x4\x55\x4\x57\x4\x10\x4\x11\x4\x12\x4\x13\x4\x14\x4\x15\x4\x16\x4\x17\x4\x18\x4\x19\x4\x1a\x4\x1b\x4\x1c\x4\x1d\x4\x1e\x4\x1f\x4\x20\x4\x21\x4\x22\x4\x23\x4\x24\x4\x25\x4\x26\x4\x27\x4\x28\x4\x29\x4\x2a\x4\x2b\x4\x2c\x4\x2d\x4\x2e\x4\x2f\x4\x30\x4\x31\x4\x32\x4\x33\x4\x34\x4\x35\x4\x36\x4\x37\x4\x38\x4\x39\x4\x3a\x4\x3b\x4\x3c\x4\x3d\x4\x3e\x4\x3f\x4\x40\x4\x41\x4\x42\x4\x43\x4\x44\x4\x45\x4\x46\x4\x47\x4\x48\x4\x49\x4\x4a\x4\x4b\x4\x4c\x4\x4d\x4\x4e\x4\x4f\x4"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x0\x1\x40\x1\x80\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x1\xc0\x0\x0\x2\xc0\x0\x40\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\x0\x0\xa4\x0\xa6\xa7\x0\xa9\x0\xab\xac\xad\xae\x0\xb0\xb1\x0\x0\x0\xb5\xb6\xb7\x0\x0\x0\xbb\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa8\x80\x81\xaa\xbd\xb2\xaf\xa3\x8a\x8c\x8e\x8d\x0\xa1\x8f\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x0\xb8\x90\x83\xba\xbe\xb3\xbf\xbc\x9a\x9c\x9e\x9d\x0\xa2\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa5\xb4\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x96\x97\x0\x0\x0\x91\x92\x82\x0\x93\x94\x84\x0\x86\x87\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x0\x8b\x9b\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x88\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xb9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x99"#-        , encoderMax = '\8482'-        }--   }-    )--    ,-    (1252, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xac\x20\x0\x0\x1a\x20\x92\x1\x1e\x20\x26\x20\x20\x20\x21\x20\xc6\x2\x30\x20\x60\x1\x39\x20\x52\x1\x0\x0\x7d\x1\x0\x0\x0\x0\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\xdc\x2\x22\x21\x61\x1\x3a\x20\x53\x1\x0\x0\x7e\x1\x78\x1\xa0\x0\xa1\x0\xa2\x0\xa3\x0\xa4\x0\xa5\x0\xa6\x0\xa7\x0\xa8\x0\xa9\x0\xaa\x0\xab\x0\xac\x0\xad\x0\xae\x0\xaf\x0\xb0\x0\xb1\x0\xb2\x0\xb3\x0\xb4\x0\xb5\x0\xb6\x0\xb7\x0\xb8\x0\xb9\x0\xba\x0\xbb\x0\xbc\x0\xbd\x0\xbe\x0\xbf\x0\xc0\x0\xc1\x0\xc2\x0\xc3\x0\xc4\x0\xc5\x0\xc6\x0\xc7\x0\xc8\x0\xc9\x0\xca\x0\xcb\x0\xcc\x0\xcd\x0\xce\x0\xcf\x0\xd0\x0\xd1\x0\xd2\x0\xd3\x0\xd4\x0\xd5\x0\xd6\x0\xd7\x0\xd8\x0\xd9\x0\xda\x0\xdb\x0\xdc\x0\xdd\x0\xde\x0\xdf\x0\xe0\x0\xe1\x0\xe2\x0\xe3\x0\xe4\x0\xe5\x0\xe6\x0\xe7\x0\xe8\x0\xe9\x0\xea\x0\xeb\x0\xec\x0\xed\x0\xee\x0\xef\x0\xf0\x0\xf1\x0\xf2\x0\xf3\x0\xf4\x0\xf5\x0\xf6\x0\xf7\x0\xf8\x0\xf9\x0\xfa\x0\xfb\x0\xfc\x0\xfd\x0\xfe\x0\xff\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\x0\x1\x0\x1\x0\x1\x0\x1\xc0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x2\x0\x1\x40\x2\x0\x1\x80\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8c\x9c\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8a\x9a\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\x0\x8e\x9e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x83\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x88\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x98\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x96\x97\x0\x0\x0\x91\x92\x82\x0\x93\x94\x84\x0\x86\x87\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x0\x8b\x9b\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x80\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x99"#-        , encoderMax = '\8482'-        }--   }-    )--    ,-    (1253, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xac\x20\x0\x0\x1a\x20\x92\x1\x1e\x20\x26\x20\x20\x20\x21\x20\x0\x0\x30\x20\x0\x0\x39\x20\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\x0\x0\x22\x21\x0\x0\x3a\x20\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\x85\x3\x86\x3\xa3\x0\xa4\x0\xa5\x0\xa6\x0\xa7\x0\xa8\x0\xa9\x0\x0\x0\xab\x0\xac\x0\xad\x0\xae\x0\x15\x20\xb0\x0\xb1\x0\xb2\x0\xb3\x0\x84\x3\xb5\x0\xb6\x0\xb7\x0\x88\x3\x89\x3\x8a\x3\xbb\x0\x8c\x3\xbd\x0\x8e\x3\x8f\x3\x90\x3\x91\x3\x92\x3\x93\x3\x94\x3\x95\x3\x96\x3\x97\x3\x98\x3\x99\x3\x9a\x3\x9b\x3\x9c\x3\x9d\x3\x9e\x3\x9f\x3\xa0\x3\xa1\x3\x0\x0\xa3\x3\xa4\x3\xa5\x3\xa6\x3\xa7\x3\xa8\x3\xa9\x3\xaa\x3\xab\x3\xac\x3\xad\x3\xae\x3\xaf\x3\xb0\x3\xb1\x3\xb2\x3\xb3\x3\xb4\x3\xb5\x3\xb6\x3\xb7\x3\xb8\x3\xb9\x3\xba\x3\xbb\x3\xbc\x3\xbd\x3\xbe\x3\xbf\x3\xc0\x3\xc1\x3\xc2\x3\xc3\x3\xc4\x3\xc5\x3\xc6\x3\xc7\x3\xc8\x3\xc9\x3\xca\x3\xcb\x3\xcc\x3\xcd\x3\xce\x3\x0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\xc0\x0\xc0\x0\x0\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x40\x1\x80\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x1\xc0\x0\x0\x2\xc0\x0\x40\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\x0\xa3\xa4\xa5\xa6\xa7\xa8\xa9\x0\xab\xac\xad\xae\x0\xb0\xb1\xb2\xb3\x0\xb5\xb6\xb7\x0\x0\x0\xbb\x0\xbd\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x83\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xb4\xa1\xa2\x0\xb8\xb9\xba\x0\xbc\x0\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\x0\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x96\x97\xaf\x0\x0\x91\x92\x82\x0\x93\x94\x84\x0\x86\x87\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x0\x8b\x9b\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x80\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x99"#-        , encoderMax = '\8482'-        }--   }-    )--    ,-    (1254, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xac\x20\x0\x0\x1a\x20\x92\x1\x1e\x20\x26\x20\x20\x20\x21\x20\xc6\x2\x30\x20\x60\x1\x39\x20\x52\x1\x0\x0\x0\x0\x0\x0\x0\x0\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\xdc\x2\x22\x21\x61\x1\x3a\x20\x53\x1\x0\x0\x0\x0\x78\x1\xa0\x0\xa1\x0\xa2\x0\xa3\x0\xa4\x0\xa5\x0\xa6\x0\xa7\x0\xa8\x0\xa9\x0\xaa\x0\xab\x0\xac\x0\xad\x0\xae\x0\xaf\x0\xb0\x0\xb1\x0\xb2\x0\xb3\x0\xb4\x0\xb5\x0\xb6\x0\xb7\x0\xb8\x0\xb9\x0\xba\x0\xbb\x0\xbc\x0\xbd\x0\xbe\x0\xbf\x0\xc0\x0\xc1\x0\xc2\x0\xc3\x0\xc4\x0\xc5\x0\xc6\x0\xc7\x0\xc8\x0\xc9\x0\xca\x0\xcb\x0\xcc\x0\xcd\x0\xce\x0\xcf\x0\x1e\x1\xd1\x0\xd2\x0\xd3\x0\xd4\x0\xd5\x0\xd6\x0\xd7\x0\xd8\x0\xd9\x0\xda\x0\xdb\x0\xdc\x0\x30\x1\x5e\x1\xdf\x0\xe0\x0\xe1\x0\xe2\x0\xe3\x0\xe4\x0\xe5\x0\xe6\x0\xe7\x0\xe8\x0\xe9\x0\xea\x0\xeb\x0\xec\x0\xed\x0\xee\x0\xef\x0\x1f\x1\xf1\x0\xf2\x0\xf3\x0\xf4\x0\xf5\x0\xf6\x0\xf7\x0\xf8\x0\xf9\x0\xfa\x0\xfb\x0\xfc\x0\x31\x1\x5f\x1\xff\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\x0\x2\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\x40\x2\xc0\x1\x80\x2\xc0\x1\xc0\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\x0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\x0\x0\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\x0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\x0\x0\xff\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xd0\xf0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdd\xfd\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8c\x9c\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xde\xfe\x8a\x9a\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x83\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x88\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x98\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x96\x97\x0\x0\x0\x91\x92\x82\x0\x93\x94\x84\x0\x86\x87\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x0\x8b\x9b\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x80\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x99"#-        , encoderMax = '\8482'-        }--   }-    )--    ,-    (1255, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xac\x20\x0\x0\x1a\x20\x92\x1\x1e\x20\x26\x20\x20\x20\x21\x20\xc6\x2\x30\x20\x0\x0\x39\x20\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\xdc\x2\x22\x21\x0\x0\x3a\x20\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\xa1\x0\xa2\x0\xa3\x0\xaa\x20\xa5\x0\xa6\x0\xa7\x0\xa8\x0\xa9\x0\xd7\x0\xab\x0\xac\x0\xad\x0\xae\x0\xaf\x0\xb0\x0\xb1\x0\xb2\x0\xb3\x0\xb4\x0\xb5\x0\xb6\x0\xb7\x0\xb8\x0\xb9\x0\xf7\x0\xbb\x0\xbc\x0\xbd\x0\xbe\x0\xbf\x0\xb0\x5\xb1\x5\xb2\x5\xb3\x5\xb4\x5\xb5\x5\xb6\x5\xb7\x5\xb8\x5\xb9\x5\x0\x0\xbb\x5\xbc\x5\xbd\x5\xbe\x5\xbf\x5\xc0\x5\xc1\x5\xc2\x5\xc3\x5\xf0\x5\xf1\x5\xf2\x5\xf3\x5\xf4\x5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xd0\x5\xd1\x5\xd2\x5\xd3\x5\xd4\x5\xd5\x5\xd6\x5\xd7\x5\xd8\x5\xd9\x5\xda\x5\xdb\x5\xdc\x5\xdd\x5\xde\x5\xdf\x5\xe0\x5\xe1\x5\xe2\x5\xe3\x5\xe4\x5\xe5\x5\xe6\x5\xe7\x5\xe8\x5\xe9\x5\xea\x5\x0\x0\x0\x0\xe\x20\xf\x20\x0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x0\x1\x40\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\xc0\x1\x0\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x2\x0\x1\x80\x2\x0\x1\xc0\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\xa1\xa2\xa3\x0\xa5\xa6\xa7\xa8\xa9\x0\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\x0\xbb\xbc\xbd\xbe\xbf\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xaa\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xba\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x83\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x88\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x98\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\x0\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\x0\x0\x0\x0\x0\xd4\xd5\xd6\xd7\xd8\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfd\xfe\x0\x0\x0\x96\x97\x0\x0\x0\x91\x92\x82\x0\x93\x94\x84\x0\x86\x87\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x0\x8b\x9b\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa4\x0\x80\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x99"#-        , encoderMax = '\8482'-        }--   }-    )--    ,-    (1256, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xac\x20\x7e\x6\x1a\x20\x92\x1\x1e\x20\x26\x20\x20\x20\x21\x20\xc6\x2\x30\x20\x79\x6\x39\x20\x52\x1\x86\x6\x98\x6\x88\x6\xaf\x6\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\xa9\x6\x22\x21\x91\x6\x3a\x20\x53\x1\xc\x20\xd\x20\xba\x6\xa0\x0\xc\x6\xa2\x0\xa3\x0\xa4\x0\xa5\x0\xa6\x0\xa7\x0\xa8\x0\xa9\x0\xbe\x6\xab\x0\xac\x0\xad\x0\xae\x0\xaf\x0\xb0\x0\xb1\x0\xb2\x0\xb3\x0\xb4\x0\xb5\x0\xb6\x0\xb7\x0\xb8\x0\xb9\x0\x1b\x6\xbb\x0\xbc\x0\xbd\x0\xbe\x0\x1f\x6\xc1\x6\x21\x6\x22\x6\x23\x6\x24\x6\x25\x6\x26\x6\x27\x6\x28\x6\x29\x6\x2a\x6\x2b\x6\x2c\x6\x2d\x6\x2e\x6\x2f\x6\x30\x6\x31\x6\x32\x6\x33\x6\x34\x6\x35\x6\x36\x6\xd7\x0\x37\x6\x38\x6\x39\x6\x3a\x6\x40\x6\x41\x6\x42\x6\x43\x6\xe0\x0\x44\x6\xe2\x0\x45\x6\x46\x6\x47\x6\x48\x6\xe7\x0\xe8\x0\xe9\x0\xea\x0\xeb\x0\x49\x6\x4a\x6\xee\x0\xef\x0\x4b\x6\x4c\x6\x4d\x6\x4e\x6\xf4\x0\x4f\x6\x50\x6\xf7\x0\x51\x6\xf9\x0\x52\x6\xfb\x0\xfc\x0\xe\x20\xf\x20\xd2\x6"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\x0\x1\x0\x1\x0\x1\x0\x1\xc0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x2\x40\x2\x80\x2\xc0\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x3\x0\x1\x40\x3\x0\x1\x80\x3"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\x0\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\x0\xbb\xbc\xbd\xbe\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xd7\x0\x0\x0\x0\x0\x0\x0\x0\xe0\x0\xe2\x0\x0\x0\x0\xe7\xe8\xe9\xea\xeb\x0\x0\xee\xef\x0\x0\x0\x0\xf4\x0\x0\xf7\x0\xf9\x0\xfb\xfc\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8c\x9c\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x83\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x88\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa1\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xba\x0\x0\x0\xbf\x0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\x0\x0\x0\x0\x0\xdc\xdd\xde\xdf\xe1\xe3\xe4\xe5\xe6\xec\xed\xf0\xf1\xf2\xf3\xf5\xf6\xf8\xfa\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8a\x0\x0\x0\x0\x81\x0\x0\x0\x0\x0\x0\x0\x8d\x0\x8f\x0\x0\x0\x0\x0\x0\x0\x0\x9a\x0\x0\x0\x0\x0\x0\x8e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x98\x0\x0\x0\x0\x0\x90\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\xaa\x0\x0\xc0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9d\x9e\xfd\xfe\x0\x0\x0\x96\x97\x0\x0\x0\x91\x92\x82\x0\x93\x94\x84\x0\x86\x87\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x0\x8b\x9b\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x80\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x99"#-        , encoderMax = '\8482'-        }--   }-    )--    ,-    (1257, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xac\x20\x0\x0\x1a\x20\x0\x0\x1e\x20\x26\x20\x20\x20\x21\x20\x0\x0\x30\x20\x0\x0\x39\x20\x0\x0\xa8\x0\xc7\x2\xb8\x0\x0\x0\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\x0\x0\x22\x21\x0\x0\x3a\x20\x0\x0\xaf\x0\xdb\x2\x0\x0\xa0\x0\x0\x0\xa2\x0\xa3\x0\xa4\x0\x0\x0\xa6\x0\xa7\x0\xd8\x0\xa9\x0\x56\x1\xab\x0\xac\x0\xad\x0\xae\x0\xc6\x0\xb0\x0\xb1\x0\xb2\x0\xb3\x0\xb4\x0\xb5\x0\xb6\x0\xb7\x0\xf8\x0\xb9\x0\x57\x1\xbb\x0\xbc\x0\xbd\x0\xbe\x0\xe6\x0\x4\x1\x2e\x1\x0\x1\x6\x1\xc4\x0\xc5\x0\x18\x1\x12\x1\xc\x1\xc9\x0\x79\x1\x16\x1\x22\x1\x36\x1\x2a\x1\x3b\x1\x60\x1\x43\x1\x45\x1\xd3\x0\x4c\x1\xd5\x0\xd6\x0\xd7\x0\x72\x1\x41\x1\x5a\x1\x6a\x1\xdc\x0\x7b\x1\x7d\x1\xdf\x0\x5\x1\x2f\x1\x1\x1\x7\x1\xe4\x0\xe5\x0\x19\x1\x13\x1\xd\x1\xe9\x0\x7a\x1\x17\x1\x23\x1\x37\x1\x2b\x1\x3c\x1\x61\x1\x44\x1\x46\x1\xf3\x0\x4d\x1\xf5\x0\xf6\x0\xf7\x0\x73\x1\x42\x1\x5b\x1\x6b\x1\xfc\x0\x7c\x1\x7e\x1\xd9\x2"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\xc0\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x0\x2\x80\x1\x40\x2\x80\x1\x80\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\xa2\xa3\xa4\x0\xa6\xa7\x8d\xa9\x0\xab\xac\xad\xae\x9d\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\x8f\xb9\x0\xbb\xbc\xbd\xbe\x0\x0\x0\x0\x0\xc4\xc5\xaf\x0\x0\xc9\x0\x0\x0\x0\x0\x0\x0\x0\x0\xd3\x0\xd5\xd6\xd7\xa8\x0\x0\x0\xdc\x0\x0\xdf\x0\x0\x0\x0\xe4\xe5\xbf\x0\x0\xe9\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf3\x0\xf5\xf6\xf7\xb8\x0\x0\x0\xfc\x0\x0\x0\xc2\xe2\x0\x0\xc0\xe0\xc3\xe3\x0\x0\x0\x0\xc8\xe8\x0\x0\x0\x0\xc7\xe7\x0\x0\xcb\xeb\xc6\xe6\x0\x0\x0\x0\x0\x0\x0\x0\xcc\xec\x0\x0\x0\x0\x0\x0\xce\xee\x0\x0\xc1\xe1\x0\x0\x0\x0\x0\x0\xcd\xed\x0\x0\x0\xcf\xef\x0\x0\x0\x0\xd9\xf9\xd1\xf1\xd2\xf2\x0\x0\x0\x0\x0\xd4\xf4\x0\x0\x0\x0\x0\x0\x0\x0\xaa\xba\x0\x0\xda\xfa\x0\x0\x0\x0\xd0\xf0\x0\x0\x0\x0\x0\x0\x0\x0\xdb\xfb\x0\x0\x0\x0\x0\x0\xd8\xf8\x0\x0\x0\x0\x0\xca\xea\xdd\xfd\xde\xfe\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\x0\x9e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x96\x97\x0\x0\x0\x91\x92\x82\x0\x93\x94\x84\x0\x86\x87\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x0\x8b\x9b\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x80\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x99"#-        , encoderMax = '\8482'-        }--   }-    )--    ,-    (1258, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xac\x20\x0\x0\x1a\x20\x92\x1\x1e\x20\x26\x20\x20\x20\x21\x20\xc6\x2\x30\x20\x0\x0\x39\x20\x52\x1\x0\x0\x0\x0\x0\x0\x0\x0\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\xdc\x2\x22\x21\x0\x0\x3a\x20\x53\x1\x0\x0\x0\x0\x78\x1\xa0\x0\xa1\x0\xa2\x0\xa3\x0\xa4\x0\xa5\x0\xa6\x0\xa7\x0\xa8\x0\xa9\x0\xaa\x0\xab\x0\xac\x0\xad\x0\xae\x0\xaf\x0\xb0\x0\xb1\x0\xb2\x0\xb3\x0\xb4\x0\xb5\x0\xb6\x0\xb7\x0\xb8\x0\xb9\x0\xba\x0\xbb\x0\xbc\x0\xbd\x0\xbe\x0\xbf\x0\xc0\x0\xc1\x0\xc2\x0\x2\x1\xc4\x0\xc5\x0\xc6\x0\xc7\x0\xc8\x0\xc9\x0\xca\x0\xcb\x0\x0\x3\xcd\x0\xce\x0\xcf\x0\x10\x1\xd1\x0\x9\x3\xd3\x0\xd4\x0\xa0\x1\xd6\x0\xd7\x0\xd8\x0\xd9\x0\xda\x0\xdb\x0\xdc\x0\xaf\x1\x3\x3\xdf\x0\xe0\x0\xe1\x0\xe2\x0\x3\x1\xe4\x0\xe5\x0\xe6\x0\xe7\x0\xe8\x0\xe9\x0\xea\x0\xeb\x0\x1\x3\xed\x0\xee\x0\xef\x0\x11\x1\xf1\x0\x23\x3\xf3\x0\xf4\x0\xa1\x1\xf6\x0\xf7\x0\xf8\x0\xf9\x0\xfa\x0\xfb\x0\xfc\x0\xb0\x1\xab\x20\xff\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\x0\x2\x40\x2\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\xc0\x1\x80\x2\xc0\x1\xc0\x2\xc0\x1\x0\x3"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\x0\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\x0\xcd\xce\xcf\x0\xd1\x0\xd3\xd4\x0\xd6\xd7\xd8\xd9\xda\xdb\xdc\x0\x0\xdf\xe0\xe1\xe2\x0\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\x0\xed\xee\xef\x0\xf1\x0\xf3\xf4\x0\xf6\xf7\xf8\xf9\xfa\xfb\xfc\x0\x0\xff\x0\x0\xc3\xe3\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xd0\xf0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8c\x9c\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x83\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xd5\xf5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdd\xfd\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x88\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x98\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcc\xec\x0\xde\x0\x0\x0\x0\x0\xd2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x96\x97\x0\x0\x0\x91\x92\x82\x0\x93\x94\x84\x0\x86\x87\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x0\x8b\x9b\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe\x80\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x99"#-        , encoderMax = '\8482'-        }--   }-    )--    ,-    (437, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xc7\x0\xfc\x0\xe9\x0\xe2\x0\xe4\x0\xe0\x0\xe5\x0\xe7\x0\xea\x0\xeb\x0\xe8\x0\xef\x0\xee\x0\xec\x0\xc4\x0\xc5\x0\xc9\x0\xe6\x0\xc6\x0\xf4\x0\xf6\x0\xf2\x0\xfb\x0\xf9\x0\xff\x0\xd6\x0\xdc\x0\xa2\x0\xa3\x0\xa5\x0\xa7\x20\x92\x1\xe1\x0\xed\x0\xf3\x0\xfa\x0\xf1\x0\xd1\x0\xaa\x0\xba\x0\xbf\x0\x10\x23\xac\x0\xbd\x0\xbc\x0\xa1\x0\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x61\x25\x62\x25\x56\x25\x55\x25\x63\x25\x51\x25\x57\x25\x5d\x25\x5c\x25\x5b\x25\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x5e\x25\x5f\x25\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\x67\x25\x68\x25\x64\x25\x65\x25\x59\x25\x58\x25\x52\x25\x53\x25\x6b\x25\x6a\x25\x18\x25\xc\x25\x88\x25\x84\x25\x8c\x25\x90\x25\x80\x25\xb1\x3\xdf\x0\x93\x3\xc0\x3\xa3\x3\xc3\x3\xb5\x0\xc4\x3\xa6\x3\x98\x3\xa9\x3\xb4\x3\x1e\x22\xc6\x3\xb5\x3\x29\x22\x61\x22\xb1\x0\x65\x22\x64\x22\x20\x23\x21\x23\xf7\x0\x48\x22\xb0\x0\x19\x22\xb7\x0\x1a\x22\x7f\x20\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x0\x1\x40\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x1\xc0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x2\x40\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x2\xc0\x2\x0\x1\x0\x1\x0\x3\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x3\x80\x3\xc0\x3"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\xad\x9b\x9c\x0\x9d\x0\x0\x0\x0\xa6\xae\xaa\x0\x0\x0\xf8\xf1\xfd\x0\x0\xe6\x0\xfa\x0\x0\xa7\xaf\xac\xab\x0\xa8\x0\x0\x0\x0\x8e\x8f\x92\x80\x0\x90\x0\x0\x0\x0\x0\x0\x0\xa5\x0\x0\x0\x0\x99\x0\x0\x0\x0\x0\x9a\x0\x0\xe1\x85\xa0\x83\x0\x84\x86\x91\x87\x8a\x82\x88\x89\x8d\xa1\x8c\x8b\x0\xa4\x95\xa2\x93\x0\x94\xf6\x0\x97\xa3\x96\x81\x0\x0\x98\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe2\x0\x0\x0\x0\xe9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe4\x0\x0\xe8\x0\x0\xea\x0\x0\x0\x0\x0\x0\x0\xe0\x0\x0\xeb\xee\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe3\x0\x0\xe5\xe7\x0\xed\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfc\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf9\xfb\x0\x0\x0\xec\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xef\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf0\x0\x0\xf3\xf2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf4\xf5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\xd5\xd6\xc9\xb8\xb7\xbb\xd4\xd3\xc8\xbe\xbd\xbc\xc6\xc7\xcc\xb5\xb6\xb9\xd1\xd2\xcb\xcf\xd0\xca\xd8\xd7\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\xdd\x0\x0\x0\xde\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (500, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x9c\x0\x9\x0\x86\x0\x7f\x0\x97\x0\x8d\x0\x8e\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x9d\x0\x85\x0\x8\x0\x87\x0\x18\x0\x19\x0\x92\x0\x8f\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x80\x0\x81\x0\x82\x0\x83\x0\x84\x0\xa\x0\x17\x0\x1b\x0\x88\x0\x89\x0\x8a\x0\x8b\x0\x8c\x0\x5\x0\x6\x0\x7\x0\x90\x0\x91\x0\x16\x0\x93\x0\x94\x0\x95\x0\x96\x0\x4\x0\x98\x0\x99\x0\x9a\x0\x9b\x0\x14\x0\x15\x0\x9e\x0\x1a\x0\x20\x0\xa0\x0\xe2\x0\xe4\x0\xe0\x0\xe1\x0\xe3\x0\xe5\x0\xe7\x0\xf1\x0\x5b\x0\x2e\x0\x3c\x0\x28\x0\x2b\x0\x21\x0\x26\x0\xe9\x0\xea\x0\xeb\x0\xe8\x0\xed\x0\xee\x0\xef\x0\xec\x0\xdf\x0\x5d\x0\x24\x0\x2a\x0\x29\x0\x3b\x0\x5e\x0\x2d\x0\x2f\x0\xc2\x0\xc4\x0\xc0\x0\xc1\x0\xc3\x0\xc5\x0\xc7\x0\xd1\x0\xa6\x0\x2c\x0\x25\x0\x5f\x0\x3e\x0\x3f\x0\xf8\x0\xc9\x0\xca\x0\xcb\x0\xc8\x0\xcd\x0\xce\x0\xcf\x0\xcc\x0\x60\x0\x3a\x0\x23\x0\x40\x0\x27\x0\x3d\x0\x22\x0\xd8\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\xab\x0\xbb\x0\xf0\x0\xfd\x0\xfe\x0\xb1\x0\xb0\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\xaa\x0\xba\x0\xe6\x0\xb8\x0\xc6\x0\xa4\x0\xb5\x0\x7e\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\xa1\x0\xbf\x0\xd0\x0\xdd\x0\xde\x0\xae\x0\xa2\x0\xa3\x0\xa5\x0\xb7\x0\xa9\x0\xa7\x0\xb6\x0\xbc\x0\xbd\x0\xbe\x0\xac\x0\x7c\x0\xaf\x0\xa8\x0\xb4\x0\xd7\x0\x7b\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\xad\x0\xf4\x0\xf6\x0\xf2\x0\xf3\x0\xf5\x0\x7d\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\xb9\x0\xfb\x0\xfc\x0\xf9\x0\xfa\x0\xff\x0\x5c\x0\xf7\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\xb2\x0\xd4\x0\xd6\x0\xd2\x0\xd3\x0\xd5\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\xb3\x0\xdb\x0\xdc\x0\xd9\x0\xda\x0\x9f\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x37\x2d\x2e\x2f\x16\x5\x25\xb\xc\xd\xe\xf\x10\x11\x12\x13\x3c\x3d\x32\x26\x18\x19\x3f\x27\x1c\x1d\x1e\x1f\x40\x4f\x7f\x7b\x5b\x6c\x50\x7d\x4d\x5d\x5c\x4e\x6b\x60\x4b\x61\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\x7a\x5e\x4c\x7e\x6e\x6f\x7c\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\x4a\xe0\x5a\x5f\x6d\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96\x97\x98\x99\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xc0\xbb\xd0\xa1\x7\x20\x21\x22\x23\x24\x15\x6\x17\x28\x29\x2a\x2b\x2c\x9\xa\x1b\x30\x31\x1a\x33\x34\x35\x36\x8\x38\x39\x3a\x3b\x4\x14\x3e\xff\x41\xaa\xb0\xb1\x9f\xb2\x6a\xb5\xbd\xb4\x9a\x8a\xba\xca\xaf\xbc\x90\x8f\xea\xfa\xbe\xa0\xb6\xb3\x9d\xda\x9b\x8b\xb7\xb8\xb9\xab\x64\x65\x62\x66\x63\x67\x9e\x68\x74\x71\x72\x73\x78\x75\x76\x77\xac\x69\xed\xee\xeb\xef\xec\xbf\x80\xfd\xfe\xfb\xfc\xad\xae\x59\x44\x45\x42\x46\x43\x47\x9c\x48\x54\x51\x52\x53\x58\x55\x56\x57\x8c\x49\xcd\xce\xcb\xcf\xcc\xe1\x70\xdd\xde\xdb\xdc\x8d\x8e\xdf"#-        , encoderMax = '\255'-        }--   }-    )--    ,-    (737, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\x91\x3\x92\x3\x93\x3\x94\x3\x95\x3\x96\x3\x97\x3\x98\x3\x99\x3\x9a\x3\x9b\x3\x9c\x3\x9d\x3\x9e\x3\x9f\x3\xa0\x3\xa1\x3\xa3\x3\xa4\x3\xa5\x3\xa6\x3\xa7\x3\xa8\x3\xa9\x3\xb1\x3\xb2\x3\xb3\x3\xb4\x3\xb5\x3\xb6\x3\xb7\x3\xb8\x3\xb9\x3\xba\x3\xbb\x3\xbc\x3\xbd\x3\xbe\x3\xbf\x3\xc0\x3\xc1\x3\xc3\x3\xc2\x3\xc4\x3\xc5\x3\xc6\x3\xc7\x3\xc8\x3\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x61\x25\x62\x25\x56\x25\x55\x25\x63\x25\x51\x25\x57\x25\x5d\x25\x5c\x25\x5b\x25\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x5e\x25\x5f\x25\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\x67\x25\x68\x25\x64\x25\x65\x25\x59\x25\x58\x25\x52\x25\x53\x25\x6b\x25\x6a\x25\x18\x25\xc\x25\x88\x25\x84\x25\x8c\x25\x90\x25\x80\x25\xc9\x3\xac\x3\xad\x3\xae\x3\xca\x3\xaf\x3\xcc\x3\xcd\x3\xcb\x3\xce\x3\x86\x3\x88\x3\x89\x3\x8a\x3\x8c\x3\x8e\x3\x8f\x3\xb1\x0\x65\x22\x64\x22\xaa\x3\xab\x3\xf7\x0\x48\x22\xb0\x0\x19\x22\xb7\x0\x1a\x22\x7f\x20\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x1\x80\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\xc0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x2\x40\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x2\xc0\x2\x0\x3"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf8\xf1\xfd\x0\x0\x0\x0\xfa\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf6\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xea\x0\xeb\xec\xed\x0\xee\x0\xef\xf0\x0\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x0\x91\x92\x93\x94\x95\x96\x97\xf4\xf5\xe1\xe2\xe3\xe5\x0\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xaa\xa9\xab\xac\xad\xae\xaf\xe0\xe4\xe8\xe6\xe7\xe9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfc\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf9\xfb\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf3\xf2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\xd5\xd6\xc9\xb8\xb7\xbb\xd4\xd3\xc8\xbe\xbd\xbc\xc6\xc7\xcc\xb5\xb6\xb9\xd1\xd2\xcb\xcf\xd0\xca\xd8\xd7\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\xdd\x0\x0\x0\xde\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (775, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\x6\x1\xfc\x0\xe9\x0\x1\x1\xe4\x0\x23\x1\xe5\x0\x7\x1\x42\x1\x13\x1\x56\x1\x57\x1\x2b\x1\x79\x1\xc4\x0\xc5\x0\xc9\x0\xe6\x0\xc6\x0\x4d\x1\xf6\x0\x22\x1\xa2\x0\x5a\x1\x5b\x1\xd6\x0\xdc\x0\xf8\x0\xa3\x0\xd8\x0\xd7\x0\xa4\x0\x0\x1\x2a\x1\xf3\x0\x7b\x1\x7c\x1\x7a\x1\x1d\x20\xa6\x0\xa9\x0\xae\x0\xac\x0\xbd\x0\xbc\x0\x41\x1\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x4\x1\xc\x1\x18\x1\x16\x1\x63\x25\x51\x25\x57\x25\x5d\x25\x2e\x1\x60\x1\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x72\x1\x6a\x1\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\x7d\x1\x5\x1\xd\x1\x19\x1\x17\x1\x2f\x1\x61\x1\x73\x1\x6b\x1\x7e\x1\x18\x25\xc\x25\x88\x25\x84\x25\x8c\x25\x90\x25\x80\x25\xd3\x0\xdf\x0\x4c\x1\x43\x1\xf5\x0\xd5\x0\xb5\x0\x44\x1\x36\x1\x37\x1\x3b\x1\x3c\x1\x46\x1\x12\x1\x45\x1\x19\x20\xad\x0\xb1\x0\x1c\x20\xbe\x0\xb6\x0\xa7\x0\xf7\x0\x1e\x20\xb0\x0\x19\x22\xb7\x0\xb9\x0\xb3\x0\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\xc0\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x0\x2\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x40\x2\x80\x2\xc0\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\x0\x96\x9c\x9f\x0\xa7\xf5\x0\xa8\x0\xae\xaa\xf0\xa9\x0\xf8\xf1\xfd\xfc\x0\xe6\xf4\xfa\x0\xfb\x0\xaf\xac\xab\xf3\x0\x0\x0\x0\x0\x8e\x8f\x92\x0\x0\x90\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe0\x0\xe5\x99\x9e\x9d\x0\x0\x0\x9a\x0\x0\xe1\x0\x0\x0\x0\x84\x86\x91\x0\x0\x82\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa2\x0\xe4\x94\xf6\x9b\x0\x0\x0\x81\x0\x0\x0\xa0\x83\x0\x0\xb5\xd0\x80\x87\x0\x0\x0\x0\xb6\xd1\x0\x0\x0\x0\xed\x89\x0\x0\xb8\xd3\xb7\xd2\x0\x0\x0\x0\x0\x0\x0\x0\x95\x85\x0\x0\x0\x0\x0\x0\xa1\x8c\x0\x0\xbd\xd4\x0\x0\x0\x0\x0\x0\xe8\xe9\x0\x0\x0\xea\xeb\x0\x0\x0\x0\xad\x88\xe3\xe7\xee\xec\x0\x0\x0\x0\x0\xe2\x93\x0\x0\x0\x0\x0\x0\x0\x0\x8a\x8b\x0\x0\x97\x98\x0\x0\x0\x0\xbe\xd5\x0\x0\x0\x0\x0\x0\x0\x0\xc7\xd7\x0\x0\x0\x0\x0\x0\xc6\xd6\x0\x0\x0\x0\x0\x8d\xa5\xa3\xa4\xcf\xd8\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xef\x0\x0\xf2\xa6\xf7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\x0\x0\xc9\x0\x0\xbb\x0\x0\xc8\x0\x0\xbc\x0\x0\xcc\x0\x0\xb9\x0\x0\xcb\x0\x0\xca\x0\x0\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\xdd\x0\x0\x0\xde\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (850, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xc7\x0\xfc\x0\xe9\x0\xe2\x0\xe4\x0\xe0\x0\xe5\x0\xe7\x0\xea\x0\xeb\x0\xe8\x0\xef\x0\xee\x0\xec\x0\xc4\x0\xc5\x0\xc9\x0\xe6\x0\xc6\x0\xf4\x0\xf6\x0\xf2\x0\xfb\x0\xf9\x0\xff\x0\xd6\x0\xdc\x0\xf8\x0\xa3\x0\xd8\x0\xd7\x0\x92\x1\xe1\x0\xed\x0\xf3\x0\xfa\x0\xf1\x0\xd1\x0\xaa\x0\xba\x0\xbf\x0\xae\x0\xac\x0\xbd\x0\xbc\x0\xa1\x0\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\xc1\x0\xc2\x0\xc0\x0\xa9\x0\x63\x25\x51\x25\x57\x25\x5d\x25\xa2\x0\xa5\x0\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\xe3\x0\xc3\x0\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\xa4\x0\xf0\x0\xd0\x0\xca\x0\xcb\x0\xc8\x0\x31\x1\xcd\x0\xce\x0\xcf\x0\x18\x25\xc\x25\x88\x25\x84\x25\xa6\x0\xcc\x0\x80\x25\xd3\x0\xdf\x0\xd4\x0\xd2\x0\xf5\x0\xd5\x0\xb5\x0\xfe\x0\xde\x0\xda\x0\xdb\x0\xd9\x0\xfd\x0\xdd\x0\xaf\x0\xb4\x0\xad\x0\xb1\x0\x17\x20\xbe\x0\xb6\x0\xa7\x0\xf7\x0\xb8\x0\xb0\x0\xa8\x0\xb7\x0\xb9\x0\xb3\x0\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\xc0\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x40\x1\x0\x2\x40\x2\x80\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\xad\xbd\x9c\xcf\xbe\xdd\xf5\xf9\xb8\xa6\xae\xaa\xf0\xa9\xee\xf8\xf1\xfd\xfc\xef\xe6\xf4\xfa\xf7\xfb\xa7\xaf\xac\xab\xf3\xa8\xb7\xb5\xb6\xc7\x8e\x8f\x92\x80\xd4\x90\xd2\xd3\xde\xd6\xd7\xd8\xd1\xa5\xe3\xe0\xe2\xe5\x99\x9e\x9d\xeb\xe9\xea\x9a\xed\xe8\xe1\x85\xa0\x83\xc6\x84\x86\x91\x87\x8a\x82\x88\x89\x8d\xa1\x8c\x8b\xd0\xa4\x95\xa2\x93\xe4\x94\xf6\x9b\x97\xa3\x96\x81\xec\xe7\x98\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xd5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\x0\x0\xc9\x0\x0\xbb\x0\x0\xc8\x0\x0\xbc\x0\x0\xcc\x0\x0\xb9\x0\x0\xcb\x0\x0\xca\x0\x0\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\x0\x0\x0\x0\x0\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (852, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xc7\x0\xfc\x0\xe9\x0\xe2\x0\xe4\x0\x6f\x1\x7\x1\xe7\x0\x42\x1\xeb\x0\x50\x1\x51\x1\xee\x0\x79\x1\xc4\x0\x6\x1\xc9\x0\x39\x1\x3a\x1\xf4\x0\xf6\x0\x3d\x1\x3e\x1\x5a\x1\x5b\x1\xd6\x0\xdc\x0\x64\x1\x65\x1\x41\x1\xd7\x0\xd\x1\xe1\x0\xed\x0\xf3\x0\xfa\x0\x4\x1\x5\x1\x7d\x1\x7e\x1\x18\x1\x19\x1\xac\x0\x7a\x1\xc\x1\x5f\x1\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\xc1\x0\xc2\x0\x1a\x1\x5e\x1\x63\x25\x51\x25\x57\x25\x5d\x25\x7b\x1\x7c\x1\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x2\x1\x3\x1\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\xa4\x0\x11\x1\x10\x1\xe\x1\xcb\x0\xf\x1\x47\x1\xcd\x0\xce\x0\x1b\x1\x18\x25\xc\x25\x88\x25\x84\x25\x62\x1\x6e\x1\x80\x25\xd3\x0\xdf\x0\xd4\x0\x43\x1\x44\x1\x48\x1\x60\x1\x61\x1\x54\x1\xda\x0\x55\x1\x70\x1\xfd\x0\xdd\x0\x63\x1\xb4\x0\xad\x0\xdd\x2\xdb\x2\xc7\x2\xd8\x2\xa7\x0\xf7\x0\xb8\x0\xb0\x0\xa8\x0\xd9\x2\x71\x1\x58\x1\x59\x1\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\xc0\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x0\x2\x40\x2\x80\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\x0\x0\x0\xcf\x0\x0\xf5\xf9\x0\x0\xae\xaa\xf0\x0\x0\xf8\x0\x0\x0\xef\x0\x0\x0\xf7\x0\x0\xaf\x0\x0\x0\x0\x0\xb5\xb6\x0\x8e\x0\x0\x80\x0\x90\x0\xd3\x0\xd6\xd7\x0\x0\x0\x0\xe0\xe2\x0\x99\x9e\x0\x0\xe9\x0\x9a\xed\x0\xe1\x0\xa0\x83\x0\x84\x0\x0\x87\x0\x82\x0\x89\x0\xa1\x8c\x0\x0\x0\x0\xa2\x93\x0\x94\xf6\x0\x0\xa3\x0\x81\xec\x0\x0\x0\x0\xc6\xc7\xa4\xa5\x8f\x86\x0\x0\x0\x0\xac\x9f\xd2\xd4\xd1\xd0\x0\x0\x0\x0\x0\x0\xa8\xa9\xb7\xd8\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x91\x92\x0\x0\x95\x96\x0\x0\x9d\x88\xe3\xe4\x0\x0\xd5\xe5\x0\x0\x0\x0\x0\x0\x0\x8a\x8b\x0\x0\xe8\xea\x0\x0\xfc\xfd\x97\x98\x0\x0\xb8\xad\xe6\xe7\xdd\xee\x9b\x9c\x0\x0\x0\x0\x0\x0\x0\x0\xde\x85\xeb\xfb\x0\x0\x0\x0\x0\x0\x0\x8d\xab\xbd\xbe\xa6\xa7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf3\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf4\xfa\x0\xf2\x0\xf1\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\x0\x0\xc9\x0\x0\xbb\x0\x0\xc8\x0\x0\xbc\x0\x0\xcc\x0\x0\xb9\x0\x0\xcb\x0\x0\xca\x0\x0\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\x0\x0\x0\x0\x0\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (855, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\x52\x4\x2\x4\x53\x4\x3\x4\x51\x4\x1\x4\x54\x4\x4\x4\x55\x4\x5\x4\x56\x4\x6\x4\x57\x4\x7\x4\x58\x4\x8\x4\x59\x4\x9\x4\x5a\x4\xa\x4\x5b\x4\xb\x4\x5c\x4\xc\x4\x5e\x4\xe\x4\x5f\x4\xf\x4\x4e\x4\x2e\x4\x4a\x4\x2a\x4\x30\x4\x10\x4\x31\x4\x11\x4\x46\x4\x26\x4\x34\x4\x14\x4\x35\x4\x15\x4\x44\x4\x24\x4\x33\x4\x13\x4\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x45\x4\x25\x4\x38\x4\x18\x4\x63\x25\x51\x25\x57\x25\x5d\x25\x39\x4\x19\x4\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x3a\x4\x1a\x4\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\xa4\x0\x3b\x4\x1b\x4\x3c\x4\x1c\x4\x3d\x4\x1d\x4\x3e\x4\x1e\x4\x3f\x4\x18\x25\xc\x25\x88\x25\x84\x25\x1f\x4\x4f\x4\x80\x25\x2f\x4\x40\x4\x20\x4\x41\x4\x21\x4\x42\x4\x22\x4\x43\x4\x23\x4\x36\x4\x16\x4\x32\x4\x12\x4\x4c\x4\x2c\x4\x16\x21\xad\x0\x4b\x4\x2b\x4\x37\x4\x17\x4\x48\x4\x28\x4\x4d\x4\x2d\x4\x49\x4\x29\x4\x47\x4\x27\x4\xa7\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x0\x1\x40\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x80\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x1\x0\x2\x40\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\x0\x0\x0\xcf\x0\x0\xfd\x0\x0\x0\xae\x0\xf0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xaf\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x85\x81\x83\x87\x89\x8b\x8d\x8f\x91\x93\x95\x97\x0\x99\x9b\xa1\xa3\xec\xad\xa7\xa9\xea\xf4\xb8\xbe\xc7\xd1\xd3\xd5\xd7\xdd\xe2\xe4\xe6\xe8\xab\xb6\xa5\xfc\xf6\xfa\x9f\xf2\xee\xf8\x9d\xe0\xa0\xa2\xeb\xac\xa6\xa8\xe9\xf3\xb7\xbd\xc6\xd0\xd2\xd4\xd6\xd8\xe1\xe3\xe5\xe7\xaa\xb5\xa4\xfb\xf5\xf9\x9e\xf1\xed\xf7\x9c\xde\x0\x84\x80\x82\x86\x88\x8a\x8c\x8e\x90\x92\x94\x96\x0\x98\x9a\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xef\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\x0\x0\xc9\x0\x0\xbb\x0\x0\xc8\x0\x0\xbc\x0\x0\xcc\x0\x0\xb9\x0\x0\xcb\x0\x0\xca\x0\x0\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\x0\x0\x0\x0\x0\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (857, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xc7\x0\xfc\x0\xe9\x0\xe2\x0\xe4\x0\xe0\x0\xe5\x0\xe7\x0\xea\x0\xeb\x0\xe8\x0\xef\x0\xee\x0\x31\x1\xc4\x0\xc5\x0\xc9\x0\xe6\x0\xc6\x0\xf4\x0\xf6\x0\xf2\x0\xfb\x0\xf9\x0\x30\x1\xd6\x0\xdc\x0\xf8\x0\xa3\x0\xd8\x0\x5e\x1\x5f\x1\xe1\x0\xed\x0\xf3\x0\xfa\x0\xf1\x0\xd1\x0\x1e\x1\x1f\x1\xbf\x0\xae\x0\xac\x0\xbd\x0\xbc\x0\xa1\x0\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\xc1\x0\xc2\x0\xc0\x0\xa9\x0\x63\x25\x51\x25\x57\x25\x5d\x25\xa2\x0\xa5\x0\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\xe3\x0\xc3\x0\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\xa4\x0\xba\x0\xaa\x0\xca\x0\xcb\x0\xc8\x0\x0\x0\xcd\x0\xce\x0\xcf\x0\x18\x25\xc\x25\x88\x25\x84\x25\xa6\x0\xcc\x0\x80\x25\xd3\x0\xdf\x0\xd4\x0\xd2\x0\xf5\x0\xd5\x0\xb5\x0\x0\x0\xd7\x0\xda\x0\xdb\x0\xd9\x0\xec\x0\xff\x0\xaf\x0\xb4\x0\xad\x0\xb1\x0\x0\x0\xbe\x0\xb6\x0\xa7\x0\xf7\x0\xb8\x0\xb0\x0\xa8\x0\xb7\x0\xb9\x0\xb3\x0\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x40\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\x80\x1\xc0\x1\x0\x2\x40\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\xad\xbd\x9c\xcf\xbe\xdd\xf5\xf9\xb8\xd1\xae\xaa\xf0\xa9\xee\xf8\xf1\xfd\xfc\xef\xe6\xf4\xfa\xf7\xfb\xd0\xaf\xac\xab\xf3\xa8\xb7\xb5\xb6\xc7\x8e\x8f\x92\x80\xd4\x90\xd2\xd3\xde\xd6\xd7\xd8\x0\xa5\xe3\xe0\xe2\xe5\x99\xe8\x9d\xeb\xe9\xea\x9a\x0\x0\xe1\x85\xa0\x83\xc6\x84\x86\x91\x87\x8a\x82\x88\x89\xec\xa1\x8c\x8b\x0\xa4\x95\xa2\x93\xe4\x94\xf6\x9b\x97\xa3\x96\x81\x0\x0\xed\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa6\xa7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x98\x8d\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9e\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\x0\x0\xc9\x0\x0\xbb\x0\x0\xc8\x0\x0\xbc\x0\x0\xcc\x0\x0\xb9\x0\x0\xcb\x0\x0\xca\x0\x0\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\x0\x0\x0\x0\x0\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (860, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xc7\x0\xfc\x0\xe9\x0\xe2\x0\xe3\x0\xe0\x0\xc1\x0\xe7\x0\xea\x0\xca\x0\xe8\x0\xcd\x0\xd4\x0\xec\x0\xc3\x0\xc2\x0\xc9\x0\xc0\x0\xc8\x0\xf4\x0\xf5\x0\xf2\x0\xda\x0\xf9\x0\xcc\x0\xd5\x0\xdc\x0\xa2\x0\xa3\x0\xd9\x0\xa7\x20\xd3\x0\xe1\x0\xed\x0\xf3\x0\xfa\x0\xf1\x0\xd1\x0\xaa\x0\xba\x0\xbf\x0\xd2\x0\xac\x0\xbd\x0\xbc\x0\xa1\x0\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x61\x25\x62\x25\x56\x25\x55\x25\x63\x25\x51\x25\x57\x25\x5d\x25\x5c\x25\x5b\x25\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x5e\x25\x5f\x25\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\x67\x25\x68\x25\x64\x25\x65\x25\x59\x25\x58\x25\x52\x25\x53\x25\x6b\x25\x6a\x25\x18\x25\xc\x25\x88\x25\x84\x25\x8c\x25\x90\x25\x80\x25\xb1\x3\xdf\x0\x93\x3\xc0\x3\xa3\x3\xc3\x3\xb5\x0\xc4\x3\xa6\x3\x98\x3\xa9\x3\xb4\x3\x1e\x22\xc6\x3\xb5\x3\x29\x22\x61\x22\xb1\x0\x65\x22\x64\x22\x20\x23\x21\x23\xf7\x0\x48\x22\xb0\x0\x19\x22\xb7\x0\x1a\x22\x7f\x20\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x1\x80\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\xc0\x1\x0\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x2\x80\x2\x0\x1\x0\x1\xc0\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x3\x40\x3\x80\x3"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\xad\x9b\x9c\x0\x0\x0\x0\x0\x0\xa6\xae\xaa\x0\x0\x0\xf8\xf1\xfd\x0\x0\xe6\x0\xfa\x0\x0\xa7\xaf\xac\xab\x0\xa8\x91\x86\x8f\x8e\x0\x0\x0\x80\x92\x90\x89\x0\x98\x8b\x0\x0\x0\xa5\xa9\x9f\x8c\x99\x0\x0\x0\x9d\x96\x0\x9a\x0\x0\xe1\x85\xa0\x83\x84\x0\x0\x0\x87\x8a\x82\x88\x0\x8d\xa1\x0\x0\x0\xa4\x95\xa2\x93\x94\x0\xf6\x0\x97\xa3\x0\x81\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe2\x0\x0\x0\x0\xe9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe4\x0\x0\xe8\x0\x0\xea\x0\x0\x0\x0\x0\x0\x0\xe0\x0\x0\xeb\xee\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe3\x0\x0\xe5\xe7\x0\xed\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfc\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf9\xfb\x0\x0\x0\xec\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xef\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf0\x0\x0\xf3\xf2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf4\xf5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\xd5\xd6\xc9\xb8\xb7\xbb\xd4\xd3\xc8\xbe\xbd\xbc\xc6\xc7\xcc\xb5\xb6\xb9\xd1\xd2\xcb\xcf\xd0\xca\xd8\xd7\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\xdd\x0\x0\x0\xde\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (861, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xc7\x0\xfc\x0\xe9\x0\xe2\x0\xe4\x0\xe0\x0\xe5\x0\xe7\x0\xea\x0\xeb\x0\xe8\x0\xd0\x0\xf0\x0\xde\x0\xc4\x0\xc5\x0\xc9\x0\xe6\x0\xc6\x0\xf4\x0\xf6\x0\xfe\x0\xfb\x0\xdd\x0\xfd\x0\xd6\x0\xdc\x0\xf8\x0\xa3\x0\xd8\x0\xa7\x20\x92\x1\xe1\x0\xed\x0\xf3\x0\xfa\x0\xc1\x0\xcd\x0\xd3\x0\xda\x0\xbf\x0\x10\x23\xac\x0\xbd\x0\xbc\x0\xa1\x0\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x61\x25\x62\x25\x56\x25\x55\x25\x63\x25\x51\x25\x57\x25\x5d\x25\x5c\x25\x5b\x25\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x5e\x25\x5f\x25\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\x67\x25\x68\x25\x64\x25\x65\x25\x59\x25\x58\x25\x52\x25\x53\x25\x6b\x25\x6a\x25\x18\x25\xc\x25\x88\x25\x84\x25\x8c\x25\x90\x25\x80\x25\xb1\x3\xdf\x0\x93\x3\xc0\x3\xa3\x3\xc3\x3\xb5\x0\xc4\x3\xa6\x3\x98\x3\xa9\x3\xb4\x3\x1e\x22\xc6\x3\xb5\x3\x29\x22\x61\x22\xb1\x0\x65\x22\x64\x22\x20\x23\x21\x23\xf7\x0\x48\x22\xb0\x0\x19\x22\xb7\x0\x1a\x22\x7f\x20\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x0\x1\x40\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x1\xc0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x2\x40\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x2\xc0\x2\x0\x1\x0\x1\x0\x3\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x3\x80\x3\xc0\x3"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\xad\x0\x9c\x0\x0\x0\x0\x0\x0\x0\xae\xaa\x0\x0\x0\xf8\xf1\xfd\x0\x0\xe6\x0\xfa\x0\x0\x0\xaf\xac\xab\x0\xa8\x0\xa4\x0\x0\x8e\x8f\x92\x80\x0\x90\x0\x0\x0\xa5\x0\x0\x8b\x0\x0\xa6\x0\x0\x99\x0\x9d\x0\xa7\x0\x9a\x97\x8d\xe1\x85\xa0\x83\x0\x84\x86\x91\x87\x8a\x82\x88\x89\x0\xa1\x0\x0\x8c\x0\x0\xa2\x93\x0\x94\xf6\x9b\x0\xa3\x96\x81\x98\x95\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe2\x0\x0\x0\x0\xe9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe4\x0\x0\xe8\x0\x0\xea\x0\x0\x0\x0\x0\x0\x0\xe0\x0\x0\xeb\xee\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe3\x0\x0\xe5\xe7\x0\xed\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfc\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf9\xfb\x0\x0\x0\xec\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xef\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf0\x0\x0\xf3\xf2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf4\xf5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\xd5\xd6\xc9\xb8\xb7\xbb\xd4\xd3\xc8\xbe\xbd\xbc\xc6\xc7\xcc\xb5\xb6\xb9\xd1\xd2\xcb\xcf\xd0\xca\xd8\xd7\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\xdd\x0\x0\x0\xde\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (862, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xd0\x5\xd1\x5\xd2\x5\xd3\x5\xd4\x5\xd5\x5\xd6\x5\xd7\x5\xd8\x5\xd9\x5\xda\x5\xdb\x5\xdc\x5\xdd\x5\xde\x5\xdf\x5\xe0\x5\xe1\x5\xe2\x5\xe3\x5\xe4\x5\xe5\x5\xe6\x5\xe7\x5\xe8\x5\xe9\x5\xea\x5\xa2\x0\xa3\x0\xa5\x0\xa7\x20\x92\x1\xe1\x0\xed\x0\xf3\x0\xfa\x0\xf1\x0\xd1\x0\xaa\x0\xba\x0\xbf\x0\x10\x23\xac\x0\xbd\x0\xbc\x0\xa1\x0\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x61\x25\x62\x25\x56\x25\x55\x25\x63\x25\x51\x25\x57\x25\x5d\x25\x5c\x25\x5b\x25\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x5e\x25\x5f\x25\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\x67\x25\x68\x25\x64\x25\x65\x25\x59\x25\x58\x25\x52\x25\x53\x25\x6b\x25\x6a\x25\x18\x25\xc\x25\x88\x25\x84\x25\x8c\x25\x90\x25\x80\x25\xb1\x3\xdf\x0\x93\x3\xc0\x3\xa3\x3\xc3\x3\xb5\x0\xc4\x3\xa6\x3\x98\x3\xa9\x3\xb4\x3\x1e\x22\xc6\x3\xb5\x3\x29\x22\x61\x22\xb1\x0\x65\x22\x64\x22\x20\x23\x21\x23\xf7\x0\x48\x22\xb0\x0\x19\x22\xb7\x0\x1a\x22\x7f\x20\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x0\x1\x40\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x1\xc0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x2\x80\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\xc0\x2\x0\x3\x0\x1\x0\x1\x40\x3\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x3\xc0\x3\x0\x4"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\xad\x9b\x9c\x0\x9d\x0\x0\x0\x0\xa6\xae\xaa\x0\x0\x0\xf8\xf1\xfd\x0\x0\xe6\x0\xfa\x0\x0\xa7\xaf\xac\xab\x0\xa8\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe1\x0\xa0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa1\x0\x0\x0\xa4\x0\xa2\x0\x0\x0\xf6\x0\x0\xa3\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe2\x0\x0\x0\x0\xe9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe4\x0\x0\xe8\x0\x0\xea\x0\x0\x0\x0\x0\x0\x0\xe0\x0\x0\xeb\xee\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe3\x0\x0\xe5\xe7\x0\xed\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfc\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf9\xfb\x0\x0\x0\xec\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xef\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf0\x0\x0\xf3\xf2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf4\xf5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\xd5\xd6\xc9\xb8\xb7\xbb\xd4\xd3\xc8\xbe\xbd\xbc\xc6\xc7\xcc\xb5\xb6\xb9\xd1\xd2\xcb\xcf\xd0\xca\xd8\xd7\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\xdd\x0\x0\x0\xde\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (863, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xc7\x0\xfc\x0\xe9\x0\xe2\x0\xc2\x0\xe0\x0\xb6\x0\xe7\x0\xea\x0\xeb\x0\xe8\x0\xef\x0\xee\x0\x17\x20\xc0\x0\xa7\x0\xc9\x0\xc8\x0\xca\x0\xf4\x0\xcb\x0\xcf\x0\xfb\x0\xf9\x0\xa4\x0\xd4\x0\xdc\x0\xa2\x0\xa3\x0\xd9\x0\xdb\x0\x92\x1\xa6\x0\xb4\x0\xf3\x0\xfa\x0\xa8\x0\xb8\x0\xb3\x0\xaf\x0\xce\x0\x10\x23\xac\x0\xbd\x0\xbc\x0\xbe\x0\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x61\x25\x62\x25\x56\x25\x55\x25\x63\x25\x51\x25\x57\x25\x5d\x25\x5c\x25\x5b\x25\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x5e\x25\x5f\x25\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\x67\x25\x68\x25\x64\x25\x65\x25\x59\x25\x58\x25\x52\x25\x53\x25\x6b\x25\x6a\x25\x18\x25\xc\x25\x88\x25\x84\x25\x8c\x25\x90\x25\x80\x25\xb1\x3\xdf\x0\x93\x3\xc0\x3\xa3\x3\xc3\x3\xb5\x0\xc4\x3\xa6\x3\x98\x3\xa9\x3\xb4\x3\x1e\x22\xc6\x3\xb5\x3\x29\x22\x61\x22\xb1\x0\x65\x22\x64\x22\x20\x23\x21\x23\xf7\x0\x48\x22\xb0\x0\x19\x22\xb7\x0\x1a\x22\x7f\x20\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x0\x1\x40\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x1\xc0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x2\x40\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x2\xc0\x2\x0\x1\x0\x1\x0\x3\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x3\x80\x3\xc0\x3"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\x0\x9b\x9c\x98\x0\xa0\x8f\xa4\x0\x0\xae\xaa\x0\x0\xa7\xf8\xf1\xfd\xa6\xa1\xe6\x86\xfa\xa5\x0\x0\xaf\xac\xab\xad\x0\x8e\x0\x84\x0\x0\x0\x0\x80\x91\x90\x92\x94\x0\x0\xa8\x95\x0\x0\x0\x0\x99\x0\x0\x0\x0\x9d\x0\x9e\x9a\x0\x0\xe1\x85\x0\x83\x0\x0\x0\x0\x87\x8a\x82\x88\x89\x0\x0\x8c\x8b\x0\x0\x0\xa2\x93\x0\x0\xf6\x0\x97\xa3\x96\x81\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe2\x0\x0\x0\x0\xe9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe4\x0\x0\xe8\x0\x0\xea\x0\x0\x0\x0\x0\x0\x0\xe0\x0\x0\xeb\xee\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe3\x0\x0\xe5\xe7\x0\xed\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8d\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfc\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf9\xfb\x0\x0\x0\xec\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xef\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf0\x0\x0\xf3\xf2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf4\xf5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\xd5\xd6\xc9\xb8\xb7\xbb\xd4\xd3\xc8\xbe\xbd\xbc\xc6\xc7\xcc\xb5\xb6\xb9\xd1\xd2\xcb\xcf\xd0\xca\xd8\xd7\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\xdd\x0\x0\x0\xde\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (864, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x6a\x6\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xb0\x0\xb7\x0\x19\x22\x1a\x22\x92\x25\x0\x25\x2\x25\x3c\x25\x24\x25\x2c\x25\x1c\x25\x34\x25\x10\x25\xc\x25\x14\x25\x18\x25\xb2\x3\x1e\x22\xc6\x3\xb1\x0\xbd\x0\xbc\x0\x48\x22\xab\x0\xbb\x0\xf7\xfe\xf8\xfe\x0\x0\x0\x0\xfb\xfe\xfc\xfe\x0\x0\xa0\x0\xad\x0\x82\xfe\xa3\x0\xa4\x0\x84\xfe\x0\x0\x0\x0\x8e\xfe\x8f\xfe\x95\xfe\x99\xfe\xc\x6\x9d\xfe\xa1\xfe\xa5\xfe\x60\x6\x61\x6\x62\x6\x63\x6\x64\x6\x65\x6\x66\x6\x67\x6\x68\x6\x69\x6\xd1\xfe\x1b\x6\xb1\xfe\xb5\xfe\xb9\xfe\x1f\x6\xa2\x0\x80\xfe\x81\xfe\x83\xfe\x85\xfe\xca\xfe\x8b\xfe\x8d\xfe\x91\xfe\x93\xfe\x97\xfe\x9b\xfe\x9f\xfe\xa3\xfe\xa7\xfe\xa9\xfe\xab\xfe\xad\xfe\xaf\xfe\xb3\xfe\xb7\xfe\xbb\xfe\xbf\xfe\xc1\xfe\xc5\xfe\xcb\xfe\xcf\xfe\xa6\x0\xac\x0\xf7\x0\xd7\x0\xc9\xfe\x40\x6\xd3\xfe\xd7\xfe\xdb\xfe\xdf\xfe\xe3\xfe\xe7\xfe\xeb\xfe\xed\xfe\xef\xfe\xf3\xfe\xbd\xfe\xcc\xfe\xce\xfe\xcd\xfe\xe1\xfe\x7d\xfe\x51\x6\xe5\xfe\xe9\xfe\xec\xfe\xf0\xfe\xf2\xfe\xd0\xfe\xd5\xfe\xf5\xfe\xf6\xfe\xdd\xfe\xd9\xfe\xf1\xfe\xa0\x25\x0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x1\x80\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\xc0\x1\x0\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x2\x80\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\xc0\x2\x0\x1\x0\x3\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x3\x80\x3\xc0\x3"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x0\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\xc0\xa3\xa4\x0\xdb\x0\x0\x0\x0\x97\xdc\xa1\x0\x0\x80\x93\x0\x0\x0\x0\x0\x81\x0\x0\x0\x98\x95\x94\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xde\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdd\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x90\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x92\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xac\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xbb\x0\x0\x0\xbf\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf1\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\x25\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x82\x83\x0\x0\x0\x91\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x96\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x85\x0\x86\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8d\x0\x0\x0\x8c\x0\x0\x0\x8e\x0\x0\x0\x8f\x0\x0\x0\x8a\x0\x0\x0\x0\x0\x0\x0\x88\x0\x0\x0\x0\x0\x0\x0\x89\x0\x0\x0\x0\x0\x0\x0\x8b\x0\x0\x0\x0\x0\x0\x0\x87\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x84\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf0\x0\x0\xc1\xc2\xa2\xc3\xa5\xc4\x0\x0\x0\x0\x0\xc6\x0\xc7\xa8\xa9\x0\xc8\x0\xc9\x0\xaa\x0\xca\x0\xab\x0\xcb\x0\xad\x0\xcc\x0\xae\x0\xcd\x0\xaf\x0\xce\x0\xcf\x0\xd0\x0\xd1\x0\xd2\x0\xbc\x0\xd3\x0\xbd\x0\xd4\x0\xbe\x0\xd5\x0\xeb\x0\xd6\x0\xd7\x0\x0\x0\xd8\x0\x0\x0\xdf\xc5\xd9\xec\xee\xed\xda\xf7\xba\x0\xe1\x0\xf8\x0\xe2\x0\xfc\x0\xe3\x0\xfb\x0\xe4\x0\xef\x0\xe5\x0\xf2\x0\xe6\x0\xf3\x0\xe7\xf4\xe8\x0\xe9\xf5\xfd\xf6\xea\x0\xf9\xfa\x99\x9a\x0\x0\x9d\x9e"#-        , encoderMax = '\65276'-        }--   }-    )--    ,-    (865, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xc7\x0\xfc\x0\xe9\x0\xe2\x0\xe4\x0\xe0\x0\xe5\x0\xe7\x0\xea\x0\xeb\x0\xe8\x0\xef\x0\xee\x0\xec\x0\xc4\x0\xc5\x0\xc9\x0\xe6\x0\xc6\x0\xf4\x0\xf6\x0\xf2\x0\xfb\x0\xf9\x0\xff\x0\xd6\x0\xdc\x0\xf8\x0\xa3\x0\xd8\x0\xa7\x20\x92\x1\xe1\x0\xed\x0\xf3\x0\xfa\x0\xf1\x0\xd1\x0\xaa\x0\xba\x0\xbf\x0\x10\x23\xac\x0\xbd\x0\xbc\x0\xa1\x0\xab\x0\xa4\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x61\x25\x62\x25\x56\x25\x55\x25\x63\x25\x51\x25\x57\x25\x5d\x25\x5c\x25\x5b\x25\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x5e\x25\x5f\x25\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\x67\x25\x68\x25\x64\x25\x65\x25\x59\x25\x58\x25\x52\x25\x53\x25\x6b\x25\x6a\x25\x18\x25\xc\x25\x88\x25\x84\x25\x8c\x25\x90\x25\x80\x25\xb1\x3\xdf\x0\x93\x3\xc0\x3\xa3\x3\xc3\x3\xb5\x0\xc4\x3\xa6\x3\x98\x3\xa9\x3\xb4\x3\x1e\x22\xc6\x3\xb5\x3\x29\x22\x61\x22\xb1\x0\x65\x22\x64\x22\x20\x23\x21\x23\xf7\x0\x48\x22\xb0\x0\x19\x22\xb7\x0\x1a\x22\x7f\x20\xb2\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\x0\x1\x0\x1\x40\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x1\xc0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x2\x40\x2\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x80\x2\xc0\x2\x0\x1\x0\x1\x0\x3\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x0\x1\x40\x3\x80\x3\xc0\x3"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\xad\x0\x9c\xaf\x0\x0\x0\x0\x0\xa6\xae\xaa\x0\x0\x0\xf8\xf1\xfd\x0\x0\xe6\x0\xfa\x0\x0\xa7\x0\xac\xab\x0\xa8\x0\x0\x0\x0\x8e\x8f\x92\x80\x0\x90\x0\x0\x0\x0\x0\x0\x0\xa5\x0\x0\x0\x0\x99\x0\x9d\x0\x0\x0\x9a\x0\x0\xe1\x85\xa0\x83\x0\x84\x86\x91\x87\x8a\x82\x88\x89\x8d\xa1\x8c\x8b\x0\xa4\x95\xa2\x93\x0\x94\xf6\x9b\x97\xa3\x96\x81\x0\x0\x98\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe2\x0\x0\x0\x0\xe9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe4\x0\x0\xe8\x0\x0\xea\x0\x0\x0\x0\x0\x0\x0\xe0\x0\x0\xeb\xee\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xe3\x0\x0\xe5\xe7\x0\xed\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfc\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x9e\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf9\xfb\x0\x0\x0\xec\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xef\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf0\x0\x0\xf3\xf2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf4\xf5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\xd5\xd6\xc9\xb8\xb7\xbb\xd4\xd3\xc8\xbe\xbd\xbc\xc6\xc7\xcc\xb5\xb6\xb9\xd1\xd2\xcb\xcf\xd0\xca\xd8\xd7\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\xdd\x0\x0\x0\xde\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (866, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\x10\x4\x11\x4\x12\x4\x13\x4\x14\x4\x15\x4\x16\x4\x17\x4\x18\x4\x19\x4\x1a\x4\x1b\x4\x1c\x4\x1d\x4\x1e\x4\x1f\x4\x20\x4\x21\x4\x22\x4\x23\x4\x24\x4\x25\x4\x26\x4\x27\x4\x28\x4\x29\x4\x2a\x4\x2b\x4\x2c\x4\x2d\x4\x2e\x4\x2f\x4\x30\x4\x31\x4\x32\x4\x33\x4\x34\x4\x35\x4\x36\x4\x37\x4\x38\x4\x39\x4\x3a\x4\x3b\x4\x3c\x4\x3d\x4\x3e\x4\x3f\x4\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x61\x25\x62\x25\x56\x25\x55\x25\x63\x25\x51\x25\x57\x25\x5d\x25\x5c\x25\x5b\x25\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\x5e\x25\x5f\x25\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\x67\x25\x68\x25\x64\x25\x65\x25\x59\x25\x58\x25\x52\x25\x53\x25\x6b\x25\x6a\x25\x18\x25\xc\x25\x88\x25\x84\x25\x8c\x25\x90\x25\x80\x25\x40\x4\x41\x4\x42\x4\x43\x4\x44\x4\x45\x4\x46\x4\x47\x4\x48\x4\x49\x4\x4a\x4\x4b\x4\x4c\x4\x4d\x4\x4e\x4\x4f\x4\x1\x4\x51\x4\x4\x4\x54\x4\x7\x4\x57\x4\xe\x4\x5e\x4\xb0\x0\x19\x22\xb7\x0\x1a\x22\x16\x21\xa4\x0\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x0\x1\x40\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x80\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x0\x2\x40\x2\x80\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\x0\x0\x0\xfd\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf8\x0\x0\x0\x0\x0\x0\xfa\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf0\x0\x0\xf2\x0\x0\xf4\x0\x0\x0\x0\x0\x0\xf6\x0\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\x0\xf1\x0\x0\xf3\x0\x0\xf5\x0\x0\x0\x0\x0\x0\xf7\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfc\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xf9\xfb\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\xd5\xd6\xc9\xb8\xb7\xbb\xd4\xd3\xc8\xbe\xbd\xbc\xc6\xc7\xcc\xb5\xb6\xb9\xd1\xd2\xcb\xcf\xd0\xca\xd8\xd7\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\xdd\x0\x0\x0\xde\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (869, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x86\x3\x0\x0\xb7\x0\xac\x0\xa6\x0\x18\x20\x19\x20\x88\x3\x15\x20\x89\x3\x8a\x3\xaa\x3\x8c\x3\x0\x0\x0\x0\x8e\x3\xab\x3\xa9\x0\x8f\x3\xb2\x0\xb3\x0\xac\x3\xa3\x0\xad\x3\xae\x3\xaf\x3\xca\x3\x90\x3\xcc\x3\xcd\x3\x91\x3\x92\x3\x93\x3\x94\x3\x95\x3\x96\x3\x97\x3\xbd\x0\x98\x3\x99\x3\xab\x0\xbb\x0\x91\x25\x92\x25\x93\x25\x2\x25\x24\x25\x9a\x3\x9b\x3\x9c\x3\x9d\x3\x63\x25\x51\x25\x57\x25\x5d\x25\x9e\x3\x9f\x3\x10\x25\x14\x25\x34\x25\x2c\x25\x1c\x25\x0\x25\x3c\x25\xa0\x3\xa1\x3\x5a\x25\x54\x25\x69\x25\x66\x25\x60\x25\x50\x25\x6c\x25\xa3\x3\xa4\x3\xa5\x3\xa6\x3\xa7\x3\xa8\x3\xa9\x3\xb1\x3\xb2\x3\xb3\x3\x18\x25\xc\x25\x88\x25\x84\x25\xb4\x3\xb5\x3\x80\x25\xb6\x3\xb7\x3\xb8\x3\xb9\x3\xba\x3\xbb\x3\xbc\x3\xbd\x3\xbe\x3\xbf\x3\xc0\x3\xc1\x3\xc3\x3\xc2\x3\xc4\x3\x84\x3\xad\x0\xb1\x0\xc5\x3\xc6\x3\xc7\x3\xa7\x0\xc8\x3\x85\x3\xb0\x0\xa8\x0\xc9\x3\xcb\x3\xb0\x3\xce\x3\xa0\x25\xa0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x0\x1\x40\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x80\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x1\x0\x2\x40\x2"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xff\x0\x0\x9c\x0\x0\x8a\xf5\xf9\x97\x0\xae\x89\xf0\x0\x0\xf8\xf1\x99\x9a\x0\x0\x0\x88\x0\x0\x0\xaf\x0\xab\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xef\xf7\x86\x0\x8d\x8f\x90\x0\x92\x0\x95\x98\xa1\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xac\xad\xb5\xb6\xb7\xb8\xbd\xbe\xc6\xc7\x0\xcf\xd0\xd1\xd2\xd3\xd4\xd5\x91\x96\x9b\x9d\x9e\x9f\xfc\xd6\xd7\xd8\xdd\xde\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xed\xec\xee\xf2\xf3\xf4\xf6\xfa\xa0\xfb\xa2\xa3\xfd\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x8e\x0\x0\x8b\x8c\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xc4\x0\xb3\x0\x0\x0\x0\x0\x0\x0\x0\x0\xda\x0\x0\x0\xbf\x0\x0\x0\xc0\x0\x0\x0\xd9\x0\x0\x0\xc3\x0\x0\x0\x0\x0\x0\x0\xb4\x0\x0\x0\x0\x0\x0\x0\xc2\x0\x0\x0\x0\x0\x0\x0\xc1\x0\x0\x0\x0\x0\x0\x0\xc5\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcd\xba\x0\x0\xc9\x0\x0\xbb\x0\x0\xc8\x0\x0\xbc\x0\x0\xcc\x0\x0\xb9\x0\x0\xcb\x0\x0\xca\x0\x0\xce\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xdf\x0\x0\x0\xdc\x0\x0\x0\xdb\x0\x0\x0\x0\x0\x0\x0\x0\xb0\xb1\xb2\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xfe"#-        , encoderMax = '\9632'-        }--   }-    )--    ,-    (874, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x4\x0\x5\x0\x6\x0\x7\x0\x8\x0\x9\x0\xa\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x14\x0\x15\x0\x16\x0\x17\x0\x18\x0\x19\x0\x1a\x0\x1b\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x20\x0\x21\x0\x22\x0\x23\x0\x24\x0\x25\x0\x26\x0\x27\x0\x28\x0\x29\x0\x2a\x0\x2b\x0\x2c\x0\x2d\x0\x2e\x0\x2f\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\x3a\x0\x3b\x0\x3c\x0\x3d\x0\x3e\x0\x3f\x0\x40\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\x5b\x0\x5c\x0\x5d\x0\x5e\x0\x5f\x0\x60\x0\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\x7b\x0\x7c\x0\x7d\x0\x7e\x0\x7f\x0\xac\x20\x0\x0\x0\x0\x0\x0\x0\x0\x26\x20\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x18\x20\x19\x20\x1c\x20\x1d\x20\x22\x20\x13\x20\x14\x20\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\x1\xe\x2\xe\x3\xe\x4\xe\x5\xe\x6\xe\x7\xe\x8\xe\x9\xe\xa\xe\xb\xe\xc\xe\xd\xe\xe\xe\xf\xe\x10\xe\x11\xe\x12\xe\x13\xe\x14\xe\x15\xe\x16\xe\x17\xe\x18\xe\x19\xe\x1a\xe\x1b\xe\x1c\xe\x1d\xe\x1e\xe\x1f\xe\x20\xe\x21\xe\x22\xe\x23\xe\x24\xe\x25\xe\x26\xe\x27\xe\x28\xe\x29\xe\x2a\xe\x2b\xe\x2c\xe\x2d\xe\x2e\xe\x2f\xe\x30\xe\x31\xe\x32\xe\x33\xe\x34\xe\x35\xe\x36\xe\x37\xe\x38\xe\x39\xe\x3a\xe\x0\x0\x0\x0\x0\x0\x0\x0\x3f\xe\x40\xe\x41\xe\x42\xe\x43\xe\x44\xe\x45\xe\x46\xe\x47\xe\x48\xe\x49\xe\x4a\xe\x4b\xe\x4c\xe\x4d\xe\x4e\xe\x4f\xe\x50\xe\x51\xe\x52\xe\x53\xe\x54\xe\x55\xe\x56\xe\x57\xe\x58\xe\x59\xe\x5a\xe\x5b\xe\x0\x0\x0\x0\x0\x0\x0\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x0\x1\x40\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x80\x1\xc0\x0\xc0\x1"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\x0\x0\x0\x0\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x96\x97\x0\x0\x0\x91\x92\x0\x0\x93\x94\x0\x0\x0\x0\x95\x0\x0\x0\x85\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x80"#-        , encoderMax = '\8364'-        }--   }-    )--    ,-    (875, SingleByteCP {-     decoderArray = ConvArray "\x0\x0\x1\x0\x2\x0\x3\x0\x9c\x0\x9\x0\x86\x0\x7f\x0\x97\x0\x8d\x0\x8e\x0\xb\x0\xc\x0\xd\x0\xe\x0\xf\x0\x10\x0\x11\x0\x12\x0\x13\x0\x9d\x0\x85\x0\x8\x0\x87\x0\x18\x0\x19\x0\x92\x0\x8f\x0\x1c\x0\x1d\x0\x1e\x0\x1f\x0\x80\x0\x81\x0\x82\x0\x83\x0\x84\x0\xa\x0\x17\x0\x1b\x0\x88\x0\x89\x0\x8a\x0\x8b\x0\x8c\x0\x5\x0\x6\x0\x7\x0\x90\x0\x91\x0\x16\x0\x93\x0\x94\x0\x95\x0\x96\x0\x4\x0\x98\x0\x99\x0\x9a\x0\x9b\x0\x14\x0\x15\x0\x9e\x0\x1a\x0\x20\x0\x91\x3\x92\x3\x93\x3\x94\x3\x95\x3\x96\x3\x97\x3\x98\x3\x99\x3\x5b\x0\x2e\x0\x3c\x0\x28\x0\x2b\x0\x21\x0\x26\x0\x9a\x3\x9b\x3\x9c\x3\x9d\x3\x9e\x3\x9f\x3\xa0\x3\xa1\x3\xa3\x3\x5d\x0\x24\x0\x2a\x0\x29\x0\x3b\x0\x5e\x0\x2d\x0\x2f\x0\xa4\x3\xa5\x3\xa6\x3\xa7\x3\xa8\x3\xa9\x3\xaa\x3\xab\x3\x7c\x0\x2c\x0\x25\x0\x5f\x0\x3e\x0\x3f\x0\xa8\x0\x86\x3\x88\x3\x89\x3\xa0\x0\x8a\x3\x8c\x3\x8e\x3\x8f\x3\x60\x0\x3a\x0\x23\x0\x40\x0\x27\x0\x3d\x0\x22\x0\x85\x3\x61\x0\x62\x0\x63\x0\x64\x0\x65\x0\x66\x0\x67\x0\x68\x0\x69\x0\xb1\x3\xb2\x3\xb3\x3\xb4\x3\xb5\x3\xb6\x3\xb0\x0\x6a\x0\x6b\x0\x6c\x0\x6d\x0\x6e\x0\x6f\x0\x70\x0\x71\x0\x72\x0\xb7\x3\xb8\x3\xb9\x3\xba\x3\xbb\x3\xbc\x3\xb4\x0\x7e\x0\x73\x0\x74\x0\x75\x0\x76\x0\x77\x0\x78\x0\x79\x0\x7a\x0\xbd\x3\xbe\x3\xbf\x3\xc0\x3\xc1\x3\xc3\x3\xa3\x0\xac\x3\xad\x3\xae\x3\xca\x3\xaf\x3\xcc\x3\xcd\x3\xcb\x3\xce\x3\xc2\x3\xc4\x3\xc5\x3\xc6\x3\xc7\x3\xc8\x3\x7b\x0\x41\x0\x42\x0\x43\x0\x44\x0\x45\x0\x46\x0\x47\x0\x48\x0\x49\x0\xad\x0\xc9\x3\x90\x3\xb0\x3\x18\x20\x15\x20\x7d\x0\x4a\x0\x4b\x0\x4c\x0\x4d\x0\x4e\x0\x4f\x0\x50\x0\x51\x0\x52\x0\xb1\x0\xbd\x0\x1a\x0\x87\x3\x19\x20\xa6\x0\x5c\x0\x1a\x0\x53\x0\x54\x0\x55\x0\x56\x0\x57\x0\x58\x0\x59\x0\x5a\x0\xb2\x0\xa7\x0\x1a\x0\x1a\x0\xab\x0\xac\x0\x30\x0\x31\x0\x32\x0\x33\x0\x34\x0\x35\x0\x36\x0\x37\x0\x38\x0\x39\x0\xb3\x0\xa9\x0\x1a\x0\x1a\x0\xbb\x0\x9f\x0"#-     , encoderArray = - CompactArray {-        encoderIndices = ConvArray "\x0\x0\x40\x0\x80\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x0\x1\x40\x1\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\xc0\x0\x80\x1"#-        , encoderValues = ConvArray "\x0\x1\x2\x3\x37\x2d\x2e\x2f\x16\x5\x25\xb\xc\xd\xe\xf\x10\x11\x12\x13\x3c\x3d\x32\x26\x18\x19\xfd\x27\x1c\x1d\x1e\x1f\x40\x4f\x7f\x7b\x5b\x6c\x50\x7d\x4d\x5d\x5c\x4e\x6b\x60\x4b\x61\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\x7a\x5e\x4c\x7e\x6e\x6f\x7c\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\x4a\xe0\x5a\x5f\x6d\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96\x97\x98\x99\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xc0\x6a\xd0\xa1\x7\x20\x21\x22\x23\x24\x15\x6\x17\x28\x29\x2a\x2b\x2c\x9\xa\x1b\x30\x31\x1a\x33\x34\x35\x36\x8\x38\x39\x3a\x3b\x4\x14\x3e\xff\x74\x0\x0\xb0\x0\x0\xdf\xeb\x70\xfb\x0\xee\xef\xca\x0\x0\x90\xda\xea\xfa\xa0\x0\x0\x0\x0\x0\x0\xfe\x0\xdb\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x80\x71\xdd\x72\x73\x75\x0\x76\x0\x77\x78\xcc\x41\x42\x43\x44\x45\x46\x47\x48\x49\x51\x52\x53\x54\x55\x56\x57\x58\x0\x59\x62\x63\x64\x65\x66\x67\x68\x69\xb1\xb2\xb3\xb5\xcd\x8a\x8b\x8c\x8d\x8e\x8f\x9a\x9b\x9c\x9d\x9e\x9f\xaa\xab\xac\xad\xae\xba\xaf\xbb\xbc\xbd\xbe\xbf\xcb\xb4\xb8\xb6\xb7\xb9\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\xcf\x0\x0\xce\xde"#-        , encoderMax = '\8217'-        }--   }-    )-    ]
− GHC/IO/Encoding/Failure.hs
@@ -1,202 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Encoding.Failure--- Copyright   :  (c) The University of Glasgow, 2008-2011--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Types for specifying how text encoding/decoding fails-----------------------------------------------------------------------------------module GHC.IO.Encoding.Failure (-    CodingFailureMode(..), codingFailureModeSuffix,-    isSurrogate,-    recoverDecode, recoverEncode-  ) where--import GHC.IO-import GHC.IO.Buffer-import GHC.IO.Exception--import GHC.Base-import GHC.Char-import GHC.Word-import GHC.Show-import GHC.Num-import GHC.Real ( fromIntegral )----import System.Posix.Internals---- | The 'CodingFailureMode' is used to construct 'TextEncoding's, and--- specifies how they handle illegal sequences.-data CodingFailureMode-  = ErrorOnCodingFailure-       -- ^ Throw an error when an illegal sequence is encountered-  | IgnoreCodingFailure-       -- ^ Attempt to ignore and recover if an illegal sequence is-       -- encountered-  | TransliterateCodingFailure-       -- ^ Replace with the closest visual match upon an illegal-       -- sequence-  | RoundtripFailure-       -- ^ Use the private-use escape mechanism to attempt to allow-       -- illegal sequences to be roundtripped.-  deriving (Show)-       -- This will only work properly for those encodings which are-       -- strict supersets of ASCII in the sense that valid ASCII data-       -- is also valid in that encoding. This is not true for-       -- e.g. UTF-16, because ASCII characters must be padded to two-       -- bytes to retain their meaning.---- Note [Roundtripping]--- ~~~~~~~~~~~~~~~~~~~~------ Roundtripping is based on the ideas of PEP383.------ We used to use the range of private-use characters from 0xEF80 to--- 0xEFFF designated for "encoding hacks" by the ConScript Unicode Registery--- to encode these characters.------ However, people didn't like this because it means we don't get--- guaranteed roundtripping for byte sequences that look like a UTF-8--- encoded codepoint 0xEFxx.------ So now like PEP383 we use lone surrogate codepoints 0xDCxx to escape--- undecodable bytes, even though that may confuse Unicode processing--- software written in Haskell. This guarantees roundtripping because--- unicode input that includes lone surrogate codepoints is invalid by--- definition.------ When we used private-use characters there was a technical problem when it--- came to encoding back to bytes using iconv. The iconv code will not fail when--- it tries to encode a private-use character (as it would if trying to encode--- a surrogate), which means that we won't get a chance to replace it--- with the byte we originally escaped.------ To work around this, when filling the buffer to be encoded (in--- writeBlocks/withEncodedCString/newEncodedCString), we replaced the--- private-use characters with lone surrogates again! Likewise, when--- reading from a buffer (unpack/unpack_nl/peekEncodedCString) we have--- to do the inverse process.------ The user of String would never see these lone surrogates, but it--- ensures that iconv will throw an error when encountering them.  We--- use lone surrogates in the range 0xDC00 to 0xDCFF for this purpose.--codingFailureModeSuffix :: CodingFailureMode -> String-codingFailureModeSuffix ErrorOnCodingFailure       = ""-codingFailureModeSuffix IgnoreCodingFailure        = "//IGNORE"-codingFailureModeSuffix TransliterateCodingFailure = "//TRANSLIT"-codingFailureModeSuffix RoundtripFailure           = "//ROUNDTRIP"---- | In transliterate mode, we use this character when decoding--- unknown bytes.------ This is the defined Unicode replacement character:--- <http://www.fileformat.info/info/unicode/char/0fffd/index.htm>-unrepresentableChar :: Char-unrepresentableChar = '\xFFFD'---- It is extraordinarily important that this series of--- predicates/transformers gets inlined, because they tend to be used--- in inner loops related to text encoding. In particular,--- surrogatifyRoundtripCharacter must be inlined (see #5536)---- | Some characters are actually "surrogate" codepoints defined for--- use in UTF-16. We need to signal an invalid character if we detect--- them when encoding a sequence of 'Char's into 'Word8's because they--- won't give valid Unicode.------ We may also need to signal an invalid character if we detect them--- when encoding a sequence of 'Char's into 'Word8's because the--- 'RoundtripFailure' mode creates these to round-trip bytes through--- our internal UTF-16 encoding.-{-# INLINE isSurrogate #-}-isSurrogate :: Char -> Bool-isSurrogate c = (0xD800 <= x && x <= 0xDBFF)-             || (0xDC00 <= x && x <= 0xDFFF)-  where x = ord c---- Bytes (in Buffer Word8) --> lone surrogates (in Buffer CharBufElem)-{-# INLINE escapeToRoundtripCharacterSurrogate #-}-escapeToRoundtripCharacterSurrogate :: Word8 -> Char-escapeToRoundtripCharacterSurrogate b-  | b < 128   = chr (fromIntegral b)-      -- Disallow 'smuggling' of ASCII bytes. For roundtripping to-      -- work, this assumes encoding is ASCII-superset.-  | otherwise = chr (0xDC00 + fromIntegral b)---- Lone surrogates (in Buffer CharBufElem) --> bytes (in Buffer Word8)-{-# INLINE unescapeRoundtripCharacterSurrogate #-}-unescapeRoundtripCharacterSurrogate :: Char -> Maybe Word8-unescapeRoundtripCharacterSurrogate c-    | 0xDC80 <= x && x < 0xDD00 = Just (fromIntegral x) -- Discard high byte-    | otherwise                 = Nothing-  where x = ord c--recoverDecode :: CodingFailureMode -> Buffer Word8 -> Buffer Char-              -> IO (Buffer Word8, Buffer Char)-recoverDecode cfm input@Buffer{  bufRaw=iraw, bufL=ir, bufR=_  }-                  output@Buffer{ bufRaw=oraw, bufL=_,  bufR=ow } = do- --puts $ "recoverDecode " ++ show ir- case cfm of-  ErrorOnCodingFailure       -> ioe_decodingError-  IgnoreCodingFailure        -> return (input { bufL=ir+1 }, output)-  TransliterateCodingFailure -> do-      ow' <- writeCharBuf oraw ow unrepresentableChar-      return (input { bufL=ir+1 }, output { bufR=ow' })-  RoundtripFailure           -> do-      b <- readWord8Buf iraw ir-      ow' <- writeCharBuf oraw ow (escapeToRoundtripCharacterSurrogate b)-      return (input { bufL=ir+1 }, output { bufR=ow' })--recoverEncode :: CodingFailureMode -> Buffer Char -> Buffer Word8-              -> IO (Buffer Char, Buffer Word8)-recoverEncode cfm input@Buffer{  bufRaw=iraw, bufL=ir, bufR=_  }-                  output@Buffer{ bufRaw=oraw, bufL=_,  bufR=ow } = do-  (c,ir') <- readCharBuf iraw ir-  --puts $ "recoverEncode " ++ show ir ++ " " ++ show ir'-  case cfm of-    IgnoreCodingFailure        -> return (input { bufL=ir' }, output)-    TransliterateCodingFailure -> do-        if c == '?'-         then return (input { bufL=ir' }, output)-         else do-          -- XXX: evil hack! To implement transliteration, we just-          -- poke an ASCII ? into the input buffer and tell the caller-          -- to try and decode again. This is *probably* safe given-          -- current uses of TextEncoding.-          ---          -- The "if" test above ensures we skip if the encoding fails-          -- to deal with the ?, though this should never happen in-          -- practice as all encodings are in fact capable of-          -- reperesenting all ASCII characters.-          _ir' <- writeCharBuf iraw ir '?'-          return (input, output)--        -- This implementation does not work because e.g. UTF-16-        -- requires 2 bytes to encode a simple ASCII value-        --writeWord8Buf oraw ow unrepresentableByte-        --return (input { bufL=ir' }, output { bufR=ow+1 })-    RoundtripFailure | Just x <- unescapeRoundtripCharacterSurrogate c -> do-        writeWord8Buf oraw ow x-        return (input { bufL=ir' }, output { bufR=ow+1 })-    _                          -> ioe_encodingError--ioe_decodingError :: IO a-ioe_decodingError = ioException-    (IOError Nothing InvalidArgument "recoverDecode"-        "invalid byte sequence" Nothing Nothing)--ioe_encodingError :: IO a-ioe_encodingError = ioException-    (IOError Nothing InvalidArgument "recoverEncode"-        "invalid character" Nothing Nothing)-
− GHC/IO/Encoding/Iconv.hs
@@ -1,201 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , NondecreasingIndentation-  #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Encoding.Iconv--- Copyright   :  (c) The University of Glasgow, 2008-2009--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ This module provides text encoding/decoding using iconv-----------------------------------------------------------------------------------module GHC.IO.Encoding.Iconv (-#if !defined(mingw32_HOST_OS)-   iconvEncoding, mkIconvEncoding,-   localeEncodingName-#endif- ) where--#include "MachDeps.h"-#include "HsBaseConfig.h"--#if defined(mingw32_HOST_OS)-import GHC.Base () -- For build ordering-#else--import Foreign-import Foreign.C hiding (charIsRepresentable)-import Data.Maybe-import GHC.Base-import GHC.Foreign (charIsRepresentable)-import GHC.IO.Buffer-import GHC.IO.Encoding.Failure-import GHC.IO.Encoding.Types-import GHC.List (span)-import GHC.Num-import GHC.Show-import GHC.Real-import System.IO.Unsafe (unsafePerformIO)-import System.Posix.Internals--c_DEBUG_DUMP :: Bool-c_DEBUG_DUMP = False--iconv_trace :: String -> IO ()-iconv_trace s- | c_DEBUG_DUMP = puts s- | otherwise    = return ()---- -------------------------------------------------------------------------------- iconv encoders/decoders--{-# NOINLINE localeEncodingName #-}-localeEncodingName :: String-localeEncodingName = unsafePerformIO $ do-   -- Use locale_charset() or nl_langinfo(CODESET) to get the encoding-   -- if we have either of them.-   cstr <- c_localeEncoding-   peekCAString cstr -- Assume charset names are ASCII---- We hope iconv_t is a storable type.  It should be, since it has at least the--- value -1, which is a possible return value from iconv_open.-type IConv = CLong -- ToDo: (#type iconv_t)--foreign import ccall unsafe "hs_iconv_open"-    hs_iconv_open :: CString -> CString -> IO IConv--foreign import ccall unsafe "hs_iconv_close"-    hs_iconv_close :: IConv -> IO CInt--foreign import ccall unsafe "hs_iconv"-    hs_iconv :: IConv -> Ptr CString -> Ptr CSize -> Ptr CString -> Ptr CSize-          -> IO CSize--foreign import ccall unsafe "localeEncoding"-    c_localeEncoding :: IO CString--haskellChar :: String-#ifdef WORDS_BIGENDIAN-haskellChar | charSize == 2 = "UTF-16BE"-            | otherwise     = "UTF-32BE"-#else-haskellChar | charSize == 2 = "UTF-16LE"-            | otherwise     = "UTF-32LE"-#endif--char_shift :: Int-char_shift | charSize == 2 = 1-           | otherwise     = 2--iconvEncoding :: String -> IO (Maybe TextEncoding)-iconvEncoding = mkIconvEncoding ErrorOnCodingFailure---- | Construct an iconv-based 'TextEncoding' for the given character set and--- 'CodingFailureMode'.------ As iconv is missing in some minimal environments (e.g. #10298), this--- checks to ensure that iconv is working properly before returning the--- encoding, returning 'Nothing' if not.-mkIconvEncoding :: CodingFailureMode -> String -> IO (Maybe TextEncoding)-mkIconvEncoding cfm charset = do-    let enc = TextEncoding {-                  textEncodingName = charset,-                  mkTextDecoder = newIConv raw_charset (haskellChar ++ suffix)-                                           (recoverDecode cfm) iconvDecode,-                  mkTextEncoder = newIConv haskellChar charset-                                           (recoverEncode cfm) iconvEncode}-    good <- charIsRepresentable enc 'a'-    return $ if good-               then Just enc-               else Nothing-  where-    -- An annoying feature of GNU iconv is that the //PREFIXES only take-    -- effect when they appear on the tocode parameter to iconv_open:-    (raw_charset, suffix) = span (/= '/') charset--newIConv :: String -> String-   -> (Buffer a -> Buffer b -> IO (Buffer a, Buffer b))-   -> (IConv -> Buffer a -> Buffer b -> IO (CodingProgress, Buffer a, Buffer b))-   -> IO (BufferCodec a b ())-newIConv from to rec fn =-  -- Assume charset names are ASCII-  withCAString from $ \ from_str ->-  withCAString to   $ \ to_str -> do-    iconvt <- throwErrnoIfMinus1 "mkTextEncoding" $ hs_iconv_open to_str from_str-    let iclose = throwErrnoIfMinus1_ "Iconv.close" $ hs_iconv_close iconvt-    return BufferCodec{-                encode = fn iconvt,-                recover = rec,-                close  = iclose,-                -- iconv doesn't supply a way to save/restore the state-                getState = return (),-                setState = const $ return ()-                }--iconvDecode :: IConv -> DecodeBuffer-iconvDecode iconv_t ibuf obuf = iconvRecode iconv_t ibuf 0 obuf char_shift--iconvEncode :: IConv -> EncodeBuffer-iconvEncode iconv_t ibuf obuf = iconvRecode iconv_t ibuf char_shift obuf 0--iconvRecode :: IConv -> Buffer a -> Int -> Buffer b -> Int-            -> IO (CodingProgress, Buffer a, Buffer b)-iconvRecode iconv_t-  input@Buffer{  bufRaw=iraw, bufL=ir, bufR=iw, bufSize=_  }  iscale-  output@Buffer{ bufRaw=oraw, bufL=_,  bufR=ow, bufSize=os }  oscale-  = do-    iconv_trace ("haskellChar=" ++ show haskellChar)-    iconv_trace ("iconvRecode before, input=" ++ show (summaryBuffer input))-    iconv_trace ("iconvRecode before, output=" ++ show (summaryBuffer output))-    withRawBuffer iraw $ \ piraw -> do-    withRawBuffer oraw $ \ poraw -> do-    with (piraw `plusPtr` (ir `shiftL` iscale)) $ \ p_inbuf -> do-    with (poraw `plusPtr` (ow `shiftL` oscale)) $ \ p_outbuf -> do-    with (fromIntegral ((iw-ir) `shiftL` iscale)) $ \ p_inleft -> do-    with (fromIntegral ((os-ow) `shiftL` oscale)) $ \ p_outleft -> do-      res <- hs_iconv iconv_t p_inbuf p_inleft p_outbuf p_outleft-      new_inleft  <- peek p_inleft-      new_outleft <- peek p_outleft-      let-          new_inleft'  = fromIntegral new_inleft `shiftR` iscale-          new_outleft' = fromIntegral new_outleft `shiftR` oscale-          new_input-            | new_inleft == 0  = input { bufL = 0, bufR = 0 }-            | otherwise        = input { bufL = iw - new_inleft' }-          new_output = output{ bufR = os - new_outleft' }-      iconv_trace ("iconv res=" ++ show res)-      iconv_trace ("iconvRecode after,  input=" ++ show (summaryBuffer new_input))-      iconv_trace ("iconvRecode after,  output=" ++ show (summaryBuffer new_output))-      if (res /= -1)-        then do -- all input translated-           return (InputUnderflow, new_input, new_output)-        else do-      errno <- getErrno-      case errno of-        e | e == e2BIG  -> return (OutputUnderflow, new_input, new_output)-          | e == eINVAL -> return (InputUnderflow, new_input, new_output)-           -- Sometimes iconv reports EILSEQ for a-           -- character in the input even when there is no room-           -- in the output; in this case we might be about to-           -- change the encoding anyway, so the following bytes-           -- could very well be in a different encoding.-           ---           -- Because we can only say InvalidSequence if there is at least-           -- one element left in the output, we have to special case this.-          | e == eILSEQ -> return (if new_outleft' == 0 then OutputUnderflow else InvalidSequence, new_input, new_output)-          | otherwise -> do-              iconv_trace ("iconv returned error: " ++ show (errnoToIOError "iconv" e Nothing Nothing))-              throwErrno "iconvRecoder"--#endif /* !mingw32_HOST_OS */-
− GHC/IO/Encoding/Latin1.hs
@@ -1,230 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude-           , BangPatterns-           , NondecreasingIndentation-  #-}-{-# OPTIONS_GHC  -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Encoding.Latin1--- Copyright   :  (c) The University of Glasgow, 2009--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Single-byte encodings that map directly to Unicode code points.------ Portions Copyright   : (c) Tom Harper 2008-2009,---                        (c) Bryan O'Sullivan 2009,---                        (c) Duncan Coutts 2009-----------------------------------------------------------------------------------module GHC.IO.Encoding.Latin1 (-  latin1, mkLatin1,-  latin1_checked, mkLatin1_checked,-  ascii, mkAscii,-  latin1_decode,-  ascii_decode,-  latin1_encode,-  latin1_checked_encode,-  ascii_encode,-  ) where--import GHC.Base-import GHC.Real-import GHC.Num--- import GHC.IO-import GHC.IO.Buffer-import GHC.IO.Encoding.Failure-import GHC.IO.Encoding.Types---- -------------------------------------------------------------------------------- Latin1--latin1 :: TextEncoding-latin1 = mkLatin1 ErrorOnCodingFailure---- | @since 4.4.0.0-mkLatin1 :: CodingFailureMode -> TextEncoding-mkLatin1 cfm = TextEncoding { textEncodingName = "ISO8859-1",-                              mkTextDecoder = latin1_DF cfm,-                              mkTextEncoder = latin1_EF cfm }--latin1_DF :: CodingFailureMode -> IO (TextDecoder ())-latin1_DF cfm =-  return (BufferCodec {-             encode   = latin1_decode,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--latin1_EF :: CodingFailureMode -> IO (TextEncoder ())-latin1_EF cfm =-  return (BufferCodec {-             encode   = latin1_encode,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--latin1_checked :: TextEncoding-latin1_checked = mkLatin1_checked ErrorOnCodingFailure---- | @since 4.4.0.0-mkLatin1_checked :: CodingFailureMode -> TextEncoding-mkLatin1_checked cfm = TextEncoding { textEncodingName = "ISO8859-1(checked)",-                                      mkTextDecoder = latin1_DF cfm,-                                      mkTextEncoder = latin1_checked_EF cfm }--latin1_checked_EF :: CodingFailureMode -> IO (TextEncoder ())-latin1_checked_EF cfm =-  return (BufferCodec {-             encode   = latin1_checked_encode,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })---- -------------------------------------------------------------------------------- ASCII---- | @since 4.8.2.0-ascii :: TextEncoding-ascii = mkAscii ErrorOnCodingFailure---- | @since 4.8.2.0-mkAscii :: CodingFailureMode -> TextEncoding-mkAscii cfm = TextEncoding { textEncodingName = "ASCII",-                             mkTextDecoder = ascii_DF cfm,-                             mkTextEncoder = ascii_EF cfm }--ascii_DF :: CodingFailureMode -> IO (TextDecoder ())-ascii_DF cfm =-  return (BufferCodec {-             encode   = ascii_decode,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--ascii_EF :: CodingFailureMode -> IO (TextEncoder ())-ascii_EF cfm =-  return (BufferCodec {-             encode   = ascii_encode,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })------ -------------------------------------------------------------------------------- The actual decoders and encoders---- TODO: Eliminate code duplication between the checked and unchecked--- versions of the decoder or encoder (but don't change the Core!)--latin1_decode :: DecodeBuffer-latin1_decode -  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let -       loop !ir !ow-         | ow >= os = done OutputUnderflow ir ow-         | ir >= iw = done InputUnderflow ir ow-         | otherwise = do-              c0 <- readWord8Buf iraw ir-              ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral c0))-              loop (ir+1) ow'--       -- lambda-lifted, to avoid thunks being built in the inner-loop:-       done why !ir !ow = return (why,-                                  if ir == iw then input{ bufL=0, bufR=0 }-                                              else input{ bufL=ir },-                                  output{ bufR=ow })-    in-    loop ir0 ow0--ascii_decode :: DecodeBuffer-ascii_decode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-       loop !ir !ow-         | ow >= os = done OutputUnderflow ir ow-         | ir >= iw = done InputUnderflow ir ow-         | otherwise = do-              c0 <- readWord8Buf iraw ir-              if c0 > 0x7f then invalid else do-              ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral c0))-              loop (ir+1) ow'-         where-           invalid = done InvalidSequence ir ow--       -- lambda-lifted, to avoid thunks being built in the inner-loop:-       done why !ir !ow = return (why,-                                  if ir == iw then input{ bufL=0, bufR=0 }-                                              else input{ bufL=ir },-                                  output{ bufR=ow })-    in-    loop ir0 ow0--latin1_encode :: EncodeBuffer-latin1_encode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-      done why !ir !ow = return (why,-                                 if ir == iw then input{ bufL=0, bufR=0 }-                                             else input{ bufL=ir },-                                 output{ bufR=ow })-      loop !ir !ow-        | ow >= os = done OutputUnderflow ir ow-        | ir >= iw = done InputUnderflow ir ow-        | otherwise = do-           (c,ir') <- readCharBuf iraw ir-           writeWord8Buf oraw ow (fromIntegral (ord c))-           loop ir' (ow+1)-    in-    loop ir0 ow0--latin1_checked_encode :: EncodeBuffer-latin1_checked_encode input output- = single_byte_checked_encode 0xff input output--ascii_encode :: EncodeBuffer-ascii_encode input output- = single_byte_checked_encode 0x7f input output--single_byte_checked_encode :: Int -> EncodeBuffer-single_byte_checked_encode max_legal_char-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-      done why !ir !ow = return (why,-                                 if ir == iw then input{ bufL=0, bufR=0 }-                                             else input{ bufL=ir },-                                 output{ bufR=ow })-      loop !ir !ow-        | ow >= os = done OutputUnderflow ir ow-        | ir >= iw = done InputUnderflow ir ow-        | otherwise = do-           (c,ir') <- readCharBuf iraw ir-           if ord c > max_legal_char then invalid else do-           writeWord8Buf oraw ow (fromIntegral (ord c))-           loop ir' (ow+1)-        where-           invalid = done InvalidSequence ir ow-    in-    loop ir0 ow0-{-# INLINE single_byte_checked_encode #-}
− GHC/IO/Encoding/Types.hs
@@ -1,132 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, ExistentialQuantification #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Encoding.Types--- Copyright   :  (c) The University of Glasgow, 2008-2009--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Types for text encoding/decoding-----------------------------------------------------------------------------------module GHC.IO.Encoding.Types (-    BufferCodec(..),-    TextEncoding(..),-    TextEncoder, TextDecoder,-    CodeBuffer, EncodeBuffer, DecodeBuffer,-    CodingProgress(..)-  ) where--import GHC.Base-import GHC.Word-import GHC.Show--- import GHC.IO-import GHC.IO.Buffer---- -------------------------------------------------------------------------------- Text encoders/decoders--data BufferCodec from to state = BufferCodec {-  encode :: CodeBuffer from to,-   -- ^ The @encode@ function translates elements of the buffer @from@-   -- to the buffer @to@.  It should translate as many elements as possible-   -- given the sizes of the buffers, including translating zero elements-   -- if there is either not enough room in @to@, or @from@ does not-   -- contain a complete multibyte sequence.-   ---   -- If multiple CodingProgress returns are possible, OutputUnderflow must be-   -- preferred to InvalidSequence. This allows GHC's IO library to assume that-   -- if we observe InvalidSequence there is at least a single element available-   -- in the output buffer.-   ---   -- The fact that as many elements as possible are translated is used by the IO-   -- library in order to report translation errors at the point they-   -- actually occur, rather than when the buffer is translated.-  -  recover :: Buffer from -> Buffer to -> IO (Buffer from, Buffer to),-   -- ^ The @recover@ function is used to continue decoding-   -- in the presence of invalid or unrepresentable sequences. This includes-   -- both those detected by @encode@ returning @InvalidSequence@ and those-   -- that occur because the input byte sequence appears to be truncated.-   ---   -- Progress will usually be made by skipping the first element of the @from@-   -- buffer. This function should only be called if you are certain that you-   -- wish to do this skipping and if the @to@ buffer has at least one element-   -- of free space. Because this function deals with decoding failure, it assumes-   -- that the from buffer has at least one element.-   ---   -- @recover@ may raise an exception rather than skipping anything.-   ---   -- Currently, some implementations of @recover@ may mutate the input buffer.-   -- In particular, this feature is used to implement transliteration.-   ---   -- @since 4.4.0.0-  -  close  :: IO (),-   -- ^ Resources associated with the encoding may now be released.-   -- The @encode@ function may not be called again after calling-   -- @close@.--  getState :: IO state,-   -- ^ Return the current state of the codec.-   ---   -- Many codecs are not stateful, and in these case the state can be-   -- represented as '()'.  Other codecs maintain a state.  For-   -- example, UTF-16 recognises a BOM (byte-order-mark) character at-   -- the beginning of the input, and remembers thereafter whether to-   -- use big-endian or little-endian mode.  In this case, the state-   -- of the codec would include two pieces of information: whether we-   -- are at the beginning of the stream (the BOM only occurs at the-   -- beginning), and if not, whether to use the big or little-endian-   -- encoding.--  setState :: state -> IO ()-   -- restore the state of the codec using the state from a previous-   -- call to 'getState'.- }--type CodeBuffer from to = Buffer from -> Buffer to -> IO (CodingProgress, Buffer from, Buffer to)-type DecodeBuffer = CodeBuffer Word8 Char-type EncodeBuffer = CodeBuffer Char Word8--type TextDecoder state = BufferCodec Word8 CharBufElem state-type TextEncoder state = BufferCodec CharBufElem Word8 state---- | A 'TextEncoding' is a specification of a conversion scheme--- between sequences of bytes and sequences of Unicode characters.------ For example, UTF-8 is an encoding of Unicode characters into a sequence--- of bytes.  The 'TextEncoding' for UTF-8 is 'utf8'.-data TextEncoding-  = forall dstate estate . TextEncoding  {-        textEncodingName :: String,-                   -- ^ a string that can be passed to 'mkTextEncoding' to-                   -- create an equivalent 'TextEncoding'.-        mkTextDecoder :: IO (TextDecoder dstate),-                   -- ^ Creates a means of decoding bytes into characters: the result must not-                   -- be shared between several byte sequences or simultaneously across threads-        mkTextEncoder :: IO (TextEncoder estate)-                   -- ^ Creates a means of encode characters into bytes: the result must not-                   -- be shared between several character sequences or simultaneously across threads-  }--instance Show TextEncoding where-  -- | Returns the value of 'textEncodingName'-  show te = textEncodingName te---- | @since 4.4.0.0-data CodingProgress = InputUnderflow  -- ^ Stopped because the input contains insufficient available elements,-                                      -- or all of the input sequence has been sucessfully translated.-                    | OutputUnderflow -- ^ Stopped because the output contains insufficient free elements-                    | InvalidSequence -- ^ Stopped because there are sufficient free elements in the output-                                      -- to output at least one encoded ASCII character, but the input contains-                                      -- an invalid or unrepresentable sequence-                    deriving (Eq, Show)-
− GHC/IO/Encoding/UTF16.hs
@@ -1,359 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude-           , BangPatterns-           , NondecreasingIndentation-           , MagicHash-  #-}-{-# OPTIONS_GHC  -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Encoding.UTF16--- Copyright   :  (c) The University of Glasgow, 2009--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ UTF-16 Codecs for the IO library------ Portions Copyright   : (c) Tom Harper 2008-2009,---                        (c) Bryan O'Sullivan 2009,---                        (c) Duncan Coutts 2009-----------------------------------------------------------------------------------module GHC.IO.Encoding.UTF16 (-  utf16, mkUTF16,-  utf16_decode,-  utf16_encode,--  utf16be, mkUTF16be,-  utf16be_decode,-  utf16be_encode,--  utf16le, mkUTF16le,-  utf16le_decode,-  utf16le_encode,-  ) where--import GHC.Base-import GHC.Real-import GHC.Num--- import GHC.IO-import GHC.IO.Buffer-import GHC.IO.Encoding.Failure-import GHC.IO.Encoding.Types-import GHC.Word-import Data.Bits-import GHC.IORef---- -------------------------------------------------------------------------------- The UTF-16 codec: either UTF16BE or UTF16LE with a BOM--utf16  :: TextEncoding-utf16 = mkUTF16 ErrorOnCodingFailure---- | @since 4.4.0.0-mkUTF16 :: CodingFailureMode -> TextEncoding-mkUTF16 cfm =  TextEncoding { textEncodingName = "UTF-16",-                              mkTextDecoder = utf16_DF cfm,-                              mkTextEncoder = utf16_EF cfm }--utf16_DF :: CodingFailureMode -> IO (TextDecoder (Maybe DecodeBuffer))-utf16_DF cfm = do-  seen_bom <- newIORef Nothing-  return (BufferCodec {-             encode   = utf16_decode seen_bom,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = readIORef seen_bom,-             setState = writeIORef seen_bom-          })--utf16_EF :: CodingFailureMode -> IO (TextEncoder Bool)-utf16_EF cfm = do-  done_bom <- newIORef False-  return (BufferCodec {-             encode   = utf16_encode done_bom,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = readIORef done_bom,-             setState = writeIORef done_bom-          })--utf16_encode :: IORef Bool -> EncodeBuffer-utf16_encode done_bom input-  output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow, bufSize=os }- = do-  b <- readIORef done_bom-  if b then utf16_native_encode input output-       else if os - ow < 2-               then return (OutputUnderflow,input,output)-               else do-                    writeIORef done_bom True-                    writeWord8Buf oraw ow     bom1-                    writeWord8Buf oraw (ow+1) bom2-                    utf16_native_encode input output{ bufR = ow+2 }--utf16_decode :: IORef (Maybe DecodeBuffer) -> DecodeBuffer-utf16_decode seen_bom-  input@Buffer{  bufRaw=iraw, bufL=ir, bufR=iw,  bufSize=_  }-  output- = do-   mb <- readIORef seen_bom-   case mb of-     Just decode -> decode input output-     Nothing ->-       if iw - ir < 2 then return (InputUnderflow,input,output) else do-       c0 <- readWord8Buf iraw ir-       c1 <- readWord8Buf iraw (ir+1)-       case () of-        _ | c0 == bomB && c1 == bomL -> do-               writeIORef seen_bom (Just utf16be_decode)-               utf16be_decode input{ bufL= ir+2 } output-          | c0 == bomL && c1 == bomB -> do-               writeIORef seen_bom (Just utf16le_decode)-               utf16le_decode input{ bufL= ir+2 } output-          | otherwise -> do-               writeIORef seen_bom (Just utf16_native_decode)-               utf16_native_decode input output---bomB, bomL, bom1, bom2 :: Word8-bomB = 0xfe-bomL = 0xff---- choose UTF-16BE by default for UTF-16 output-utf16_native_decode :: DecodeBuffer-utf16_native_decode = utf16be_decode--utf16_native_encode :: EncodeBuffer-utf16_native_encode = utf16be_encode--bom1 = bomB-bom2 = bomL---- -------------------------------------------------------------------------------- UTF16LE and UTF16BE--utf16be :: TextEncoding-utf16be = mkUTF16be ErrorOnCodingFailure---- | @since 4.4.0.0-mkUTF16be :: CodingFailureMode -> TextEncoding-mkUTF16be cfm = TextEncoding { textEncodingName = "UTF-16BE",-                               mkTextDecoder = utf16be_DF cfm,-                               mkTextEncoder = utf16be_EF cfm }--utf16be_DF :: CodingFailureMode -> IO (TextDecoder ())-utf16be_DF cfm =-  return (BufferCodec {-             encode   = utf16be_decode,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--utf16be_EF :: CodingFailureMode -> IO (TextEncoder ())-utf16be_EF cfm =-  return (BufferCodec {-             encode   = utf16be_encode,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--utf16le :: TextEncoding-utf16le = mkUTF16le ErrorOnCodingFailure---- | @since 4.4.0.0-mkUTF16le :: CodingFailureMode -> TextEncoding-mkUTF16le cfm = TextEncoding { textEncodingName = "UTF16-LE",-                               mkTextDecoder = utf16le_DF cfm,-                               mkTextEncoder = utf16le_EF cfm }--utf16le_DF :: CodingFailureMode -> IO (TextDecoder ())-utf16le_DF cfm =-  return (BufferCodec {-             encode   = utf16le_decode,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--utf16le_EF :: CodingFailureMode -> IO (TextEncoder ())-utf16le_EF cfm =-  return (BufferCodec {-             encode   = utf16le_encode,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })---utf16be_decode :: DecodeBuffer-utf16be_decode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-       loop !ir !ow-         | ow >= os     = done OutputUnderflow ir ow-         | ir >= iw     = done InputUnderflow ir ow-         | ir + 1 == iw = done InputUnderflow ir ow-         | otherwise = do-              c0 <- readWord8Buf iraw ir-              c1 <- readWord8Buf iraw (ir+1)-              let x1 = fromIntegral c0 `shiftL` 8 + fromIntegral c1-              if validate1 x1-                 then do ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral x1))-                         loop (ir+2) ow'-                 else if iw - ir < 4 then done InputUnderflow ir ow else do-                      c2 <- readWord8Buf iraw (ir+2)-                      c3 <- readWord8Buf iraw (ir+3)-                      let x2 = fromIntegral c2 `shiftL` 8 + fromIntegral c3-                      if not (validate2 x1 x2) then invalid else do-                      ow' <- writeCharBuf oraw ow (chr2 x1 x2)-                      loop (ir+4) ow'-         where-           invalid = done InvalidSequence ir ow--       -- lambda-lifted, to avoid thunks being built in the inner-loop:-       done why !ir !ow = return (why,-                                  if ir == iw then input{ bufL=0, bufR=0 }-                                              else input{ bufL=ir },-                                  output{ bufR=ow })-    in-    loop ir0 ow0--utf16le_decode :: DecodeBuffer-utf16le_decode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-       loop !ir !ow-         | ow >= os     = done OutputUnderflow ir ow-         | ir >= iw     = done InputUnderflow ir ow-         | ir + 1 == iw = done InputUnderflow ir ow-         | otherwise = do-              c0 <- readWord8Buf iraw ir-              c1 <- readWord8Buf iraw (ir+1)-              let x1 = fromIntegral c1 `shiftL` 8 + fromIntegral c0-              if validate1 x1-                 then do ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral x1))-                         loop (ir+2) ow'-                 else if iw - ir < 4 then done InputUnderflow ir ow else do-                      c2 <- readWord8Buf iraw (ir+2)-                      c3 <- readWord8Buf iraw (ir+3)-                      let x2 = fromIntegral c3 `shiftL` 8 + fromIntegral c2-                      if not (validate2 x1 x2) then invalid else do-                      ow' <- writeCharBuf oraw ow (chr2 x1 x2)-                      loop (ir+4) ow'-         where-           invalid = done InvalidSequence ir ow--       -- lambda-lifted, to avoid thunks being built in the inner-loop:-       done why !ir !ow = return (why,-                                  if ir == iw then input{ bufL=0, bufR=0 }-                                              else input{ bufL=ir },-                                  output{ bufR=ow })-    in-    loop ir0 ow0--utf16be_encode :: EncodeBuffer-utf16be_encode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-      done why !ir !ow = return (why,-                                 if ir == iw then input{ bufL=0, bufR=0 }-                                             else input{ bufL=ir },-                                 output{ bufR=ow })-      loop !ir !ow-        | ir >= iw     =  done InputUnderflow ir ow-        | os - ow < 2  =  done OutputUnderflow ir ow-        | otherwise = do-           (c,ir') <- readCharBuf iraw ir-           case ord c of-             x | x < 0x10000 -> if isSurrogate c then done InvalidSequence ir ow else do-                    writeWord8Buf oraw ow     (fromIntegral (x `shiftR` 8))-                    writeWord8Buf oraw (ow+1) (fromIntegral x)-                    loop ir' (ow+2)-               | otherwise -> do-                    if os - ow < 4 then done OutputUnderflow ir ow else do-                    let-                         n1 = x - 0x10000-                         c1 = fromIntegral (n1 `shiftR` 18 + 0xD8)-                         c2 = fromIntegral (n1 `shiftR` 10)-                         n2 = n1 .&. 0x3FF-                         c3 = fromIntegral (n2 `shiftR` 8 + 0xDC)-                         c4 = fromIntegral n2-                    ---                    writeWord8Buf oraw ow     c1-                    writeWord8Buf oraw (ow+1) c2-                    writeWord8Buf oraw (ow+2) c3-                    writeWord8Buf oraw (ow+3) c4-                    loop ir' (ow+4)-    in-    loop ir0 ow0--utf16le_encode :: EncodeBuffer-utf16le_encode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-      done why !ir !ow = return (why,-                                 if ir == iw then input{ bufL=0, bufR=0 }-                                             else input{ bufL=ir },-                                 output{ bufR=ow })-      loop !ir !ow-        | ir >= iw     =  done InputUnderflow ir ow-        | os - ow < 2  =  done OutputUnderflow ir ow-        | otherwise = do-           (c,ir') <- readCharBuf iraw ir-           case ord c of-             x | x < 0x10000 -> if isSurrogate c then done InvalidSequence ir ow else do-                    writeWord8Buf oraw ow     (fromIntegral x)-                    writeWord8Buf oraw (ow+1) (fromIntegral (x `shiftR` 8))-                    loop ir' (ow+2)-               | otherwise ->-                    if os - ow < 4 then done OutputUnderflow ir ow else do-                    let-                         n1 = x - 0x10000-                         c1 = fromIntegral (n1 `shiftR` 18 + 0xD8)-                         c2 = fromIntegral (n1 `shiftR` 10)-                         n2 = n1 .&. 0x3FF-                         c3 = fromIntegral (n2 `shiftR` 8 + 0xDC)-                         c4 = fromIntegral n2-                    ---                    writeWord8Buf oraw ow     c2-                    writeWord8Buf oraw (ow+1) c1-                    writeWord8Buf oraw (ow+2) c4-                    writeWord8Buf oraw (ow+3) c3-                    loop ir' (ow+4)-    in-    loop ir0 ow0--chr2 :: Word16 -> Word16 -> Char-chr2 (W16# a#) (W16# b#) = C# (chr# (upper# +# lower# +# 0x10000#))-    where-      !x# = word2Int# a#-      !y# = word2Int# b#-      !upper# = uncheckedIShiftL# (x# -# 0xD800#) 10#-      !lower# = y# -# 0xDC00#-{-# INLINE chr2 #-}--validate1    :: Word16 -> Bool-validate1 x1 = (x1 >= 0 && x1 < 0xD800) || x1 > 0xDFFF-{-# INLINE validate1 #-}--validate2       ::  Word16 -> Word16 -> Bool-validate2 x1 x2 = x1 >= 0xD800 && x1 <= 0xDBFF &&-                  x2 >= 0xDC00 && x2 <= 0xDFFF-{-# INLINE validate2 #-}-
− GHC/IO/Encoding/UTF32.hs
@@ -1,336 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude-           , BangPatterns-           , NondecreasingIndentation-           , MagicHash-  #-}-{-# OPTIONS_GHC  -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Encoding.UTF32--- Copyright   :  (c) The University of Glasgow, 2009--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ UTF-32 Codecs for the IO library------ Portions Copyright   : (c) Tom Harper 2008-2009,---                        (c) Bryan O'Sullivan 2009,---                        (c) Duncan Coutts 2009-----------------------------------------------------------------------------------module GHC.IO.Encoding.UTF32 (-  utf32, mkUTF32,-  utf32_decode,-  utf32_encode,--  utf32be, mkUTF32be,-  utf32be_decode,-  utf32be_encode,--  utf32le, mkUTF32le,-  utf32le_decode,-  utf32le_encode,-  ) where--import GHC.Base-import GHC.Real-import GHC.Num--- import GHC.IO-import GHC.IO.Buffer-import GHC.IO.Encoding.Failure-import GHC.IO.Encoding.Types-import GHC.Word-import Data.Bits-import GHC.IORef---- -------------------------------------------------------------------------------- The UTF-32 codec: either UTF-32BE or UTF-32LE with a BOM--utf32  :: TextEncoding-utf32 = mkUTF32 ErrorOnCodingFailure---- | @since 4.4.0.0-mkUTF32 :: CodingFailureMode -> TextEncoding-mkUTF32 cfm = TextEncoding { textEncodingName = "UTF-32",-                             mkTextDecoder = utf32_DF cfm,-                             mkTextEncoder = utf32_EF cfm }--utf32_DF :: CodingFailureMode -> IO (TextDecoder (Maybe DecodeBuffer))-utf32_DF cfm = do-  seen_bom <- newIORef Nothing-  return (BufferCodec {-             encode   = utf32_decode seen_bom,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = readIORef seen_bom,-             setState = writeIORef seen_bom-          })--utf32_EF :: CodingFailureMode -> IO (TextEncoder Bool)-utf32_EF cfm = do-  done_bom <- newIORef False-  return (BufferCodec {-             encode   = utf32_encode done_bom,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = readIORef done_bom,-             setState = writeIORef done_bom-          })--utf32_encode :: IORef Bool -> EncodeBuffer-utf32_encode done_bom input-  output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow, bufSize=os }- = do-  b <- readIORef done_bom-  if b then utf32_native_encode input output-       else if os - ow < 4-               then return (OutputUnderflow, input,output)-               else do-                    writeIORef done_bom True-                    writeWord8Buf oraw ow     bom0-                    writeWord8Buf oraw (ow+1) bom1-                    writeWord8Buf oraw (ow+2) bom2-                    writeWord8Buf oraw (ow+3) bom3-                    utf32_native_encode input output{ bufR = ow+4 }--utf32_decode :: IORef (Maybe DecodeBuffer) -> DecodeBuffer-utf32_decode seen_bom-  input@Buffer{  bufRaw=iraw, bufL=ir, bufR=iw,  bufSize=_  }-  output- = do-   mb <- readIORef seen_bom-   case mb of-     Just decode -> decode input output-     Nothing ->-       if iw - ir < 4 then return (InputUnderflow, input,output) else do-       c0 <- readWord8Buf iraw ir-       c1 <- readWord8Buf iraw (ir+1)-       c2 <- readWord8Buf iraw (ir+2)-       c3 <- readWord8Buf iraw (ir+3)-       case () of-        _ | c0 == bom0 && c1 == bom1 && c2 == bom2 && c3 == bom3 -> do-               writeIORef seen_bom (Just utf32be_decode)-               utf32be_decode input{ bufL= ir+4 } output-        _ | c0 == bom3 && c1 == bom2 && c2 == bom1 && c3 == bom0 -> do-               writeIORef seen_bom (Just utf32le_decode)-               utf32le_decode input{ bufL= ir+4 } output-          | otherwise -> do-               writeIORef seen_bom (Just utf32_native_decode)-               utf32_native_decode input output---bom0, bom1, bom2, bom3 :: Word8-bom0 = 0-bom1 = 0-bom2 = 0xfe-bom3 = 0xff---- choose UTF-32BE by default for UTF-32 output-utf32_native_decode :: DecodeBuffer-utf32_native_decode = utf32be_decode--utf32_native_encode :: EncodeBuffer-utf32_native_encode = utf32be_encode---- -------------------------------------------------------------------------------- UTF32LE and UTF32BE--utf32be :: TextEncoding-utf32be = mkUTF32be ErrorOnCodingFailure---- | @since 4.4.0.0-mkUTF32be :: CodingFailureMode -> TextEncoding-mkUTF32be cfm = TextEncoding { textEncodingName = "UTF-32BE",-                               mkTextDecoder = utf32be_DF cfm,-                               mkTextEncoder = utf32be_EF cfm }--utf32be_DF :: CodingFailureMode -> IO (TextDecoder ())-utf32be_DF cfm =-  return (BufferCodec {-             encode   = utf32be_decode,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--utf32be_EF :: CodingFailureMode -> IO (TextEncoder ())-utf32be_EF cfm =-  return (BufferCodec {-             encode   = utf32be_encode,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })---utf32le :: TextEncoding-utf32le = mkUTF32le ErrorOnCodingFailure---- | @since 4.4.0.0-mkUTF32le :: CodingFailureMode -> TextEncoding-mkUTF32le cfm = TextEncoding { textEncodingName = "UTF-32LE",-                               mkTextDecoder = utf32le_DF cfm,-                               mkTextEncoder = utf32le_EF cfm }--utf32le_DF :: CodingFailureMode -> IO (TextDecoder ())-utf32le_DF cfm =-  return (BufferCodec {-             encode   = utf32le_decode,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--utf32le_EF :: CodingFailureMode -> IO (TextEncoder ())-utf32le_EF cfm =-  return (BufferCodec {-             encode   = utf32le_encode,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })---utf32be_decode :: DecodeBuffer-utf32be_decode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-       loop !ir !ow-         | ow >= os    = done OutputUnderflow ir ow-         | iw - ir < 4 = done InputUnderflow  ir ow-         | otherwise = do-              c0 <- readWord8Buf iraw ir-              c1 <- readWord8Buf iraw (ir+1)-              c2 <- readWord8Buf iraw (ir+2)-              c3 <- readWord8Buf iraw (ir+3)-              let x1 = chr4 c0 c1 c2 c3-              if not (validate x1) then invalid else do-              ow' <- writeCharBuf oraw ow x1-              loop (ir+4) ow'-         where-           invalid = done InvalidSequence ir ow--       -- lambda-lifted, to avoid thunks being built in the inner-loop:-       done why !ir !ow = return (why,-                                  if ir == iw then input{ bufL=0, bufR=0 }-                                              else input{ bufL=ir },-                                  output{ bufR=ow })-    in-    loop ir0 ow0--utf32le_decode :: DecodeBuffer-utf32le_decode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-       loop !ir !ow-         | ow >= os    = done OutputUnderflow ir ow-         | iw - ir < 4 = done InputUnderflow  ir ow-         | otherwise = do-              c0 <- readWord8Buf iraw ir-              c1 <- readWord8Buf iraw (ir+1)-              c2 <- readWord8Buf iraw (ir+2)-              c3 <- readWord8Buf iraw (ir+3)-              let x1 = chr4 c3 c2 c1 c0-              if not (validate x1) then invalid else do-              ow' <- writeCharBuf oraw ow x1-              loop (ir+4) ow'-         where-           invalid = done InvalidSequence ir ow--       -- lambda-lifted, to avoid thunks being built in the inner-loop:-       done why !ir !ow = return (why,-                                  if ir == iw then input{ bufL=0, bufR=0 }-                                              else input{ bufL=ir },-                                  output{ bufR=ow })-    in-    loop ir0 ow0--utf32be_encode :: EncodeBuffer-utf32be_encode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-      done why !ir !ow = return (why,-                                 if ir == iw then input{ bufL=0, bufR=0 }-                                             else input{ bufL=ir },-                                 output{ bufR=ow })-      loop !ir !ow-        | ir >= iw    = done InputUnderflow  ir ow-        | os - ow < 4 = done OutputUnderflow ir ow-        | otherwise = do-           (c,ir') <- readCharBuf iraw ir-           if isSurrogate c then done InvalidSequence ir ow else do-             let (c0,c1,c2,c3) = ord4 c-             writeWord8Buf oraw ow     c0-             writeWord8Buf oraw (ow+1) c1-             writeWord8Buf oraw (ow+2) c2-             writeWord8Buf oraw (ow+3) c3-             loop ir' (ow+4)-    in-    loop ir0 ow0--utf32le_encode :: EncodeBuffer-utf32le_encode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let-      done why !ir !ow = return (why,-                                 if ir == iw then input{ bufL=0, bufR=0 }-                                             else input{ bufL=ir },-                                 output{ bufR=ow })-      loop !ir !ow-        | ir >= iw    = done InputUnderflow  ir ow-        | os - ow < 4 = done OutputUnderflow ir ow-        | otherwise = do-           (c,ir') <- readCharBuf iraw ir-           if isSurrogate c then done InvalidSequence ir ow else do-             let (c0,c1,c2,c3) = ord4 c-             writeWord8Buf oraw ow     c3-             writeWord8Buf oraw (ow+1) c2-             writeWord8Buf oraw (ow+2) c1-             writeWord8Buf oraw (ow+3) c0-             loop ir' (ow+4)-    in-    loop ir0 ow0--chr4 :: Word8 -> Word8 -> Word8 -> Word8 -> Char-chr4 (W8# x1#) (W8# x2#) (W8# x3#) (W8# x4#) =-    C# (chr# (z1# +# z2# +# z3# +# z4#))-    where-      !y1# = word2Int# x1#-      !y2# = word2Int# x2#-      !y3# = word2Int# x3#-      !y4# = word2Int# x4#-      !z1# = uncheckedIShiftL# y1# 24#-      !z2# = uncheckedIShiftL# y2# 16#-      !z3# = uncheckedIShiftL# y3# 8#-      !z4# = y4#-{-# INLINE chr4 #-}--ord4 :: Char -> (Word8,Word8,Word8,Word8)-ord4 c = (fromIntegral (x `shiftR` 24),-          fromIntegral (x `shiftR` 16),-          fromIntegral (x `shiftR` 8),-          fromIntegral x)-  where-    x = ord c-{-# INLINE ord4 #-}---validate    :: Char -> Bool-validate c = (x1 >= 0x0 && x1 < 0xD800) || (x1 > 0xDFFF && x1 <= 0x10FFFF)-   where x1 = ord c-{-# INLINE validate #-}-
− GHC/IO/Encoding/UTF8.hs
@@ -1,362 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude-           , BangPatterns-           , NondecreasingIndentation-           , MagicHash-  #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Encoding.UTF8--- Copyright   :  (c) The University of Glasgow, 2009--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ UTF-8 Codec for the IO library------ Portions Copyright   : (c) Tom Harper 2008-2009,---                        (c) Bryan O'Sullivan 2009,---                        (c) Duncan Coutts 2009-----------------------------------------------------------------------------------module GHC.IO.Encoding.UTF8 (-  utf8, mkUTF8,-  utf8_bom, mkUTF8_bom-  ) where--import GHC.Base-import GHC.Real-import GHC.Num-import GHC.IORef--- import GHC.IO-import GHC.IO.Buffer-import GHC.IO.Encoding.Failure-import GHC.IO.Encoding.Types-import GHC.Word-import Data.Bits--utf8 :: TextEncoding-utf8 = mkUTF8 ErrorOnCodingFailure---- | @since 4.4.0.0-mkUTF8 :: CodingFailureMode -> TextEncoding-mkUTF8 cfm = TextEncoding { textEncodingName = "UTF-8",-                            mkTextDecoder = utf8_DF cfm,-                            mkTextEncoder = utf8_EF cfm }---utf8_DF :: CodingFailureMode -> IO (TextDecoder ())-utf8_DF cfm =-  return (BufferCodec {-             encode   = utf8_decode,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--utf8_EF :: CodingFailureMode -> IO (TextEncoder ())-utf8_EF cfm =-  return (BufferCodec {-             encode   = utf8_encode,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = return (),-             setState = const $ return ()-          })--utf8_bom :: TextEncoding-utf8_bom = mkUTF8_bom ErrorOnCodingFailure--mkUTF8_bom :: CodingFailureMode -> TextEncoding-mkUTF8_bom cfm = TextEncoding { textEncodingName = "UTF-8BOM",-                                mkTextDecoder = utf8_bom_DF cfm,-                                mkTextEncoder = utf8_bom_EF cfm }--utf8_bom_DF :: CodingFailureMode -> IO (TextDecoder Bool)-utf8_bom_DF cfm = do-   ref <- newIORef True-   return (BufferCodec {-             encode   = utf8_bom_decode ref,-             recover  = recoverDecode cfm,-             close    = return (),-             getState = readIORef ref,-             setState = writeIORef ref-          })--utf8_bom_EF :: CodingFailureMode -> IO (TextEncoder Bool)-utf8_bom_EF cfm = do-   ref <- newIORef True-   return (BufferCodec {-             encode   = utf8_bom_encode ref,-             recover  = recoverEncode cfm,-             close    = return (),-             getState = readIORef ref,-             setState = writeIORef ref-          })--utf8_bom_decode :: IORef Bool -> DecodeBuffer-utf8_bom_decode ref-  input@Buffer{  bufRaw=iraw, bufL=ir, bufR=iw,  bufSize=_  }-  output- = do-   first <- readIORef ref-   if not first-      then utf8_decode input output-      else do-       let no_bom = do writeIORef ref False; utf8_decode input output-       if iw - ir < 1 then return (InputUnderflow,input,output) else do-       c0 <- readWord8Buf iraw ir-       if (c0 /= bom0) then no_bom else do-       if iw - ir < 2 then return (InputUnderflow,input,output) else do-       c1 <- readWord8Buf iraw (ir+1)-       if (c1 /= bom1) then no_bom else do-       if iw - ir < 3 then return (InputUnderflow,input,output) else do-       c2 <- readWord8Buf iraw (ir+2)-       if (c2 /= bom2) then no_bom else do-       -- found a BOM, ignore it and carry on-       writeIORef ref False-       utf8_decode input{ bufL = ir + 3 } output--utf8_bom_encode :: IORef Bool -> EncodeBuffer-utf8_bom_encode ref input-  output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow, bufSize=os }- = do-  b <- readIORef ref-  if not b then utf8_encode input output-           else if os - ow < 3-                  then return (OutputUnderflow,input,output)-                  else do-                    writeIORef ref False-                    writeWord8Buf oraw ow     bom0-                    writeWord8Buf oraw (ow+1) bom1-                    writeWord8Buf oraw (ow+2) bom2-                    utf8_encode input output{ bufR = ow+3 }--bom0, bom1, bom2 :: Word8-bom0 = 0xef-bom1 = 0xbb-bom2 = 0xbf--utf8_decode :: DecodeBuffer-utf8_decode -  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let -       loop !ir !ow-         | ow >= os = done OutputUnderflow ir ow-         | ir >= iw = done InputUnderflow ir ow-         | otherwise = do-              c0 <- readWord8Buf iraw ir-              case c0 of-                _ | c0 <= 0x7f -> do -                           ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral c0))-                           loop (ir+1) ow'-                  | c0 >= 0xc0 && c0 <= 0xc1 -> invalid -- Overlong forms-                  | c0 >= 0xc2 && c0 <= 0xdf ->-                           if iw - ir < 2 then done InputUnderflow ir ow else do-                           c1 <- readWord8Buf iraw (ir+1)-                           if (c1 < 0x80 || c1 >= 0xc0) then invalid else do-                           ow' <- writeCharBuf oraw ow (chr2 c0 c1)-                           loop (ir+2) ow'-                  | c0 >= 0xe0 && c0 <= 0xef ->-                      case iw - ir of-                        1 -> done InputUnderflow ir ow-                        2 -> do -- check for an error even when we don't have-                                -- the full sequence yet (#3341)-                           c1 <- readWord8Buf iraw (ir+1)-                           if not (validate3 c0 c1 0x80) -                              then invalid else done InputUnderflow ir ow-                        _ -> do-                           c1 <- readWord8Buf iraw (ir+1)-                           c2 <- readWord8Buf iraw (ir+2)-                           if not (validate3 c0 c1 c2) then invalid else do-                           ow' <- writeCharBuf oraw ow (chr3 c0 c1 c2)-                           loop (ir+3) ow'-                  | c0 >= 0xf0 ->-                      case iw - ir of-                        1 -> done InputUnderflow ir ow-                        2 -> do -- check for an error even when we don't have-                                -- the full sequence yet (#3341)-                           c1 <- readWord8Buf iraw (ir+1)-                           if not (validate4 c0 c1 0x80 0x80)-                              then invalid else done InputUnderflow ir ow-                        3 -> do-                           c1 <- readWord8Buf iraw (ir+1)-                           c2 <- readWord8Buf iraw (ir+2)-                           if not (validate4 c0 c1 c2 0x80)-                              then invalid else done InputUnderflow ir ow-                        _ -> do-                           c1 <- readWord8Buf iraw (ir+1)-                           c2 <- readWord8Buf iraw (ir+2)-                           c3 <- readWord8Buf iraw (ir+3)-                           if not (validate4 c0 c1 c2 c3) then invalid else do-                           ow' <- writeCharBuf oraw ow (chr4 c0 c1 c2 c3)-                           loop (ir+4) ow'-                  | otherwise ->-                           invalid-         where-           invalid = done InvalidSequence ir ow--       -- lambda-lifted, to avoid thunks being built in the inner-loop:-       done why !ir !ow = return (why,-                                  if ir == iw then input{ bufL=0, bufR=0 }-                                              else input{ bufL=ir },-                                  output{ bufR=ow })-   in-   loop ir0 ow0--utf8_encode :: EncodeBuffer-utf8_encode-  input@Buffer{  bufRaw=iraw, bufL=ir0, bufR=iw,  bufSize=_  }-  output@Buffer{ bufRaw=oraw, bufL=_,   bufR=ow0, bufSize=os }- = let -      done why !ir !ow = return (why,-                                 if ir == iw then input{ bufL=0, bufR=0 }-                                             else input{ bufL=ir },-                                 output{ bufR=ow })-      loop !ir !ow-        | ow >= os = done OutputUnderflow ir ow-        | ir >= iw = done InputUnderflow ir ow-        | otherwise = do-           (c,ir') <- readCharBuf iraw ir-           case ord c of-             x | x <= 0x7F   -> do-                    writeWord8Buf oraw ow (fromIntegral x)-                    loop ir' (ow+1)-               | x <= 0x07FF ->-                    if os - ow < 2 then done OutputUnderflow ir ow else do-                    let (c1,c2) = ord2 c-                    writeWord8Buf oraw ow     c1-                    writeWord8Buf oraw (ow+1) c2-                    loop ir' (ow+2)-               | x <= 0xFFFF -> if isSurrogate c then done InvalidSequence ir ow else do-                    if os - ow < 3 then done OutputUnderflow ir ow else do-                    let (c1,c2,c3) = ord3 c-                    writeWord8Buf oraw ow     c1-                    writeWord8Buf oraw (ow+1) c2-                    writeWord8Buf oraw (ow+2) c3-                    loop ir' (ow+3)-               | otherwise -> do-                    if os - ow < 4 then done OutputUnderflow ir ow else do-                    let (c1,c2,c3,c4) = ord4 c-                    writeWord8Buf oraw ow     c1-                    writeWord8Buf oraw (ow+1) c2-                    writeWord8Buf oraw (ow+2) c3-                    writeWord8Buf oraw (ow+3) c4-                    loop ir' (ow+4)-   in-   loop ir0 ow0---- -------------------------------------------------------------------------------- UTF-8 primitives, lifted from Data.Text.Fusion.Utf8-  -ord2   :: Char -> (Word8,Word8)-ord2 c = assert (n >= 0x80 && n <= 0x07ff) (x1,x2)-    where-      n  = ord c-      x1 = fromIntegral $ (n `shiftR` 6) + 0xC0-      x2 = fromIntegral $ (n .&. 0x3F)   + 0x80--ord3   :: Char -> (Word8,Word8,Word8)-ord3 c = assert (n >= 0x0800 && n <= 0xffff) (x1,x2,x3)-    where-      n  = ord c-      x1 = fromIntegral $ (n `shiftR` 12) + 0xE0-      x2 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80-      x3 = fromIntegral $ (n .&. 0x3F) + 0x80--ord4   :: Char -> (Word8,Word8,Word8,Word8)-ord4 c = assert (n >= 0x10000) (x1,x2,x3,x4)-    where-      n  = ord c-      x1 = fromIntegral $ (n `shiftR` 18) + 0xF0-      x2 = fromIntegral $ ((n `shiftR` 12) .&. 0x3F) + 0x80-      x3 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80-      x4 = fromIntegral $ (n .&. 0x3F) + 0x80--chr2       :: Word8 -> Word8 -> Char-chr2 (W8# x1#) (W8# x2#) = C# (chr# (z1# +# z2#))-    where-      !y1# = word2Int# x1#-      !y2# = word2Int# x2#-      !z1# = uncheckedIShiftL# (y1# -# 0xC0#) 6#-      !z2# = y2# -# 0x80#-{-# INLINE chr2 #-}--chr3          :: Word8 -> Word8 -> Word8 -> Char-chr3 (W8# x1#) (W8# x2#) (W8# x3#) = C# (chr# (z1# +# z2# +# z3#))-    where-      !y1# = word2Int# x1#-      !y2# = word2Int# x2#-      !y3# = word2Int# x3#-      !z1# = uncheckedIShiftL# (y1# -# 0xE0#) 12#-      !z2# = uncheckedIShiftL# (y2# -# 0x80#) 6#-      !z3# = y3# -# 0x80#-{-# INLINE chr3 #-}--chr4             :: Word8 -> Word8 -> Word8 -> Word8 -> Char-chr4 (W8# x1#) (W8# x2#) (W8# x3#) (W8# x4#) =-    C# (chr# (z1# +# z2# +# z3# +# z4#))-    where-      !y1# = word2Int# x1#-      !y2# = word2Int# x2#-      !y3# = word2Int# x3#-      !y4# = word2Int# x4#-      !z1# = uncheckedIShiftL# (y1# -# 0xF0#) 18#-      !z2# = uncheckedIShiftL# (y2# -# 0x80#) 12#-      !z3# = uncheckedIShiftL# (y3# -# 0x80#) 6#-      !z4# = y4# -# 0x80#-{-# INLINE chr4 #-}--between :: Word8                -- ^ byte to check-        -> Word8                -- ^ lower bound-        -> Word8                -- ^ upper bound-        -> Bool-between x y z = x >= y && x <= z-{-# INLINE between #-}--validate3          :: Word8 -> Word8 -> Word8 -> Bool-{-# INLINE validate3 #-}-validate3 x1 x2 x3 = validate3_1 ||-                     validate3_2 ||-                     validate3_3 ||-                     validate3_4-  where-    validate3_1 = (x1 == 0xE0) &&-                  between x2 0xA0 0xBF &&-                  between x3 0x80 0xBF-    validate3_2 = between x1 0xE1 0xEC &&-                  between x2 0x80 0xBF &&-                  between x3 0x80 0xBF-    validate3_3 = x1 == 0xED &&-                  between x2 0x80 0x9F &&-                  between x3 0x80 0xBF-    validate3_4 = between x1 0xEE 0xEF &&-                  between x2 0x80 0xBF &&-                  between x3 0x80 0xBF--validate4             :: Word8 -> Word8 -> Word8 -> Word8 -> Bool-{-# INLINE validate4 #-}-validate4 x1 x2 x3 x4 = validate4_1 ||-                        validate4_2 ||-                        validate4_3-  where -    validate4_1 = x1 == 0xF0 &&-                  between x2 0x90 0xBF &&-                  between x3 0x80 0xBF &&-                  between x4 0x80 0xBF-    validate4_2 = between x1 0xF1 0xF3 &&-                  between x2 0x80 0xBF &&-                  between x3 0x80 0xBF &&-                  between x4 0x80 0xBF-    validate4_3 = x1 == 0xF4 &&-                  between x2 0x80 0x8F &&-                  between x3 0x80 0xBF &&-                  between x4 0x80 0xBF-
− GHC/IO/Exception.hs
@@ -1,394 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, AutoDeriveTypeable, MagicHash,-             ExistentialQuantification #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Exception--- Copyright   :  (c) The University of Glasgow, 2009--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ IO-related Exception types and functions-----------------------------------------------------------------------------------module GHC.IO.Exception (-  BlockedIndefinitelyOnMVar(..), blockedIndefinitelyOnMVar,-  BlockedIndefinitelyOnSTM(..), blockedIndefinitelyOnSTM,-  Deadlock(..),-  AllocationLimitExceeded(..), allocationLimitExceeded,-  AssertionFailed(..),--  SomeAsyncException(..),-  asyncExceptionToException, asyncExceptionFromException,-  AsyncException(..), stackOverflow, heapOverflow,--  ArrayException(..),-  ExitCode(..),--  ioException,-  ioError,-  IOError,-  IOException(..),-  IOErrorType(..),-  userError,-  assertError,-  unsupportedOperation,-  untangle,- ) where--import GHC.Base-import GHC.List-import GHC.IO-import GHC.Show-import GHC.Read-import GHC.Exception-import GHC.IO.Handle.Types-import Foreign.C.Types--import Data.Typeable     ( Typeable, cast )---- --------------------------------------------------------------------------- Exception datatypes and operations---- |The thread is blocked on an @MVar@, but there are no other references--- to the @MVar@ so it can't ever continue.-data BlockedIndefinitelyOnMVar = BlockedIndefinitelyOnMVar-    deriving Typeable--instance Exception BlockedIndefinitelyOnMVar--instance Show BlockedIndefinitelyOnMVar where-    showsPrec _ BlockedIndefinitelyOnMVar = showString "thread blocked indefinitely in an MVar operation"--blockedIndefinitelyOnMVar :: SomeException -- for the RTS-blockedIndefinitelyOnMVar = toException BlockedIndefinitelyOnMVar----------- |The thread is waiting to retry an STM transaction, but there are no--- other references to any @TVar@s involved, so it can't ever continue.-data BlockedIndefinitelyOnSTM = BlockedIndefinitelyOnSTM-    deriving Typeable--instance Exception BlockedIndefinitelyOnSTM--instance Show BlockedIndefinitelyOnSTM where-    showsPrec _ BlockedIndefinitelyOnSTM = showString "thread blocked indefinitely in an STM transaction"--blockedIndefinitelyOnSTM :: SomeException -- for the RTS-blockedIndefinitelyOnSTM = toException BlockedIndefinitelyOnSTM----------- |There are no runnable threads, so the program is deadlocked.--- The @Deadlock@ exception is raised in the main thread only.-data Deadlock = Deadlock-    deriving Typeable--instance Exception Deadlock--instance Show Deadlock where-    showsPrec _ Deadlock = showString "<<deadlock>>"----------- |This thread has exceeded its allocation limit.  See--- 'GHC.Conc.setAllocationCounter' and--- 'GHC.Conc.enableAllocationLimit'.------ @since 4.8.0.0-data AllocationLimitExceeded = AllocationLimitExceeded-    deriving Typeable--instance Exception AllocationLimitExceeded where-  toException = asyncExceptionToException-  fromException = asyncExceptionFromException--instance Show AllocationLimitExceeded where-    showsPrec _ AllocationLimitExceeded =-      showString "allocation limit exceeded"--allocationLimitExceeded :: SomeException -- for the RTS-allocationLimitExceeded = toException AllocationLimitExceeded----------- |'assert' was applied to 'False'.-data AssertionFailed = AssertionFailed String-    deriving Typeable--instance Exception AssertionFailed--instance Show AssertionFailed where-    showsPrec _ (AssertionFailed err) = showString err----------- |Superclass for asynchronous exceptions.------ @since 4.7.0.0-data SomeAsyncException = forall e . Exception e => SomeAsyncException e-  deriving Typeable--instance Show SomeAsyncException where-    show (SomeAsyncException e) = show e--instance Exception SomeAsyncException---- |@since 4.7.0.0-asyncExceptionToException :: Exception e => e -> SomeException-asyncExceptionToException = toException . SomeAsyncException---- |@since 4.7.0.0-asyncExceptionFromException :: Exception e => SomeException -> Maybe e-asyncExceptionFromException x = do-    SomeAsyncException a <- fromException x-    cast a----- |Asynchronous exceptions.-data AsyncException-  = StackOverflow-        -- ^The current thread\'s stack exceeded its limit.-        -- Since an exception has been raised, the thread\'s stack-        -- will certainly be below its limit again, but the-        -- programmer should take remedial action-        -- immediately.-  | HeapOverflow-        -- ^The program\'s heap is reaching its limit, and-        -- the program should take action to reduce the amount of-        -- live data it has. Notes:-        ---        --   * It is undefined which thread receives this exception.-        ---        --   * GHC currently does not throw 'HeapOverflow' exceptions.-  | ThreadKilled-        -- ^This exception is raised by another thread-        -- calling 'Control.Concurrent.killThread', or by the system-        -- if it needs to terminate the thread for some-        -- reason.-  | UserInterrupt-        -- ^This exception is raised by default in the main thread of-        -- the program when the user requests to terminate the program-        -- via the usual mechanism(s) (e.g. Control-C in the console).-  deriving (Eq, Ord, Typeable)--instance Exception AsyncException where-  toException = asyncExceptionToException-  fromException = asyncExceptionFromException---- | Exceptions generated by array operations-data ArrayException-  = IndexOutOfBounds    String-        -- ^An attempt was made to index an array outside-        -- its declared bounds.-  | UndefinedElement    String-        -- ^An attempt was made to evaluate an element of an-        -- array that had not been initialized.-  deriving (Eq, Ord, Typeable)--instance Exception ArrayException---- for the RTS-stackOverflow, heapOverflow :: SomeException-stackOverflow = toException StackOverflow-heapOverflow  = toException HeapOverflow--instance Show AsyncException where-  showsPrec _ StackOverflow   = showString "stack overflow"-  showsPrec _ HeapOverflow    = showString "heap overflow"-  showsPrec _ ThreadKilled    = showString "thread killed"-  showsPrec _ UserInterrupt   = showString "user interrupt"--instance Show ArrayException where-  showsPrec _ (IndexOutOfBounds s)-        = showString "array index out of range"-        . (if not (null s) then showString ": " . showString s-                           else id)-  showsPrec _ (UndefinedElement s)-        = showString "undefined array element"-        . (if not (null s) then showString ": " . showString s-                           else id)---- -------------------------------------------------------------------------------- The ExitCode type---- We need it here because it is used in ExitException in the--- Exception datatype (above).---- | Defines the exit codes that a program can return.-data ExitCode-  = ExitSuccess -- ^ indicates successful termination;-  | ExitFailure Int-                -- ^ indicates program failure with an exit code.-                -- The exact interpretation of the code is-                -- operating-system dependent.  In particular, some values-                -- may be prohibited (e.g. 0 on a POSIX-compliant system).-  deriving (Eq, Ord, Read, Show, Typeable)--instance Exception ExitCode--ioException     :: IOException -> IO a-ioException err = throwIO err---- | Raise an 'IOError' in the 'IO' monad.-ioError         :: IOError -> IO a-ioError         =  ioException---- ------------------------------------------------------------------------------ IOError type---- | The Haskell 2010 type for exceptions in the 'IO' monad.--- Any I\/O operation may raise an 'IOError' instead of returning a result.--- For a more general type of exception, including also those that arise--- in pure code, see "Control.Exception.Exception".------ In Haskell 2010, this is an opaque type.-type IOError = IOException---- |Exceptions that occur in the @IO@ monad.--- An @IOException@ records a more specific error type, a descriptive--- string and maybe the handle that was used when the error was--- flagged.-data IOException- = IOError {-     ioe_handle   :: Maybe Handle,   -- the handle used by the action flagging-                                     -- the error.-     ioe_type     :: IOErrorType,    -- what it was.-     ioe_location :: String,         -- location.-     ioe_description :: String,      -- error type specific information.-     ioe_errno    :: Maybe CInt,     -- errno leading to this error, if any.-     ioe_filename :: Maybe FilePath  -- filename the error is related to.-   }-    deriving Typeable--instance Exception IOException--instance Eq IOException where-  (IOError h1 e1 loc1 str1 en1 fn1) == (IOError h2 e2 loc2 str2 en2 fn2) =-    e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && en1==en2 && fn1==fn2---- | An abstract type that contains a value for each variant of 'IOError'.-data IOErrorType-  -- Haskell 2010:-  = AlreadyExists-  | NoSuchThing-  | ResourceBusy-  | ResourceExhausted-  | EOF-  | IllegalOperation-  | PermissionDenied-  | UserError-  -- GHC only:-  | UnsatisfiedConstraints-  | SystemError-  | ProtocolError-  | OtherError-  | InvalidArgument-  | InappropriateType-  | HardwareFault-  | UnsupportedOperation-  | TimeExpired-  | ResourceVanished-  | Interrupted--instance Eq IOErrorType where-   x == y = isTrue# (getTag x ==# getTag y)--instance Show IOErrorType where-  showsPrec _ e =-    showString $-    case e of-      AlreadyExists     -> "already exists"-      NoSuchThing       -> "does not exist"-      ResourceBusy      -> "resource busy"-      ResourceExhausted -> "resource exhausted"-      EOF               -> "end of file"-      IllegalOperation  -> "illegal operation"-      PermissionDenied  -> "permission denied"-      UserError         -> "user error"-      HardwareFault     -> "hardware fault"-      InappropriateType -> "inappropriate type"-      Interrupted       -> "interrupted"-      InvalidArgument   -> "invalid argument"-      OtherError        -> "failed"-      ProtocolError     -> "protocol error"-      ResourceVanished  -> "resource vanished"-      SystemError       -> "system error"-      TimeExpired       -> "timeout"-      UnsatisfiedConstraints -> "unsatisfied constraints" -- ultra-precise!-      UnsupportedOperation -> "unsupported operation"---- | Construct an 'IOError' value with a string describing the error.--- The 'fail' method of the 'IO' instance of the 'Monad' class raises a--- 'userError', thus:------ > instance Monad IO where--- >   ...--- >   fail s = ioError (userError s)----userError       :: String  -> IOError-userError str   =  IOError Nothing UserError "" str Nothing Nothing---- ------------------------------------------------------------------------------ Showing IOErrors--instance Show IOException where-    showsPrec p (IOError hdl iot loc s _ fn) =-      (case fn of-         Nothing -> case hdl of-                        Nothing -> id-                        Just h  -> showsPrec p h . showString ": "-         Just name -> showString name . showString ": ") .-      (case loc of-         "" -> id-         _  -> showString loc . showString ": ") .-      showsPrec p iot .-      (case s of-         "" -> id-         _  -> showString " (" . showString s . showString ")")---- Note the use of "lazy". This means that---     assert False (throw e)--- will throw the assertion failure rather than e. See trac #5561.-assertError :: Addr# -> Bool -> a -> a-assertError str predicate v-  | predicate = lazy v-  | otherwise = throw (AssertionFailed (untangle str "Assertion failed"))--unsupportedOperation :: IOError-unsupportedOperation =-   (IOError Nothing UnsupportedOperation ""-        "Operation is not supported" Nothing Nothing)--{--(untangle coded message) expects "coded" to be of the form-        "location|details"-It prints-        location message details--}-untangle :: Addr# -> String -> String-untangle coded message-  =  location-  ++ ": "-  ++ message-  ++ details-  ++ "\n"-  where-    coded_str = unpackCStringUtf8# coded--    (location, details)-      = case (span not_bar coded_str) of { (loc, rest) ->-        case rest of-          ('|':det) -> (loc, ' ' : det)-          _         -> (loc, "")-        }-    not_bar c = c /= '|'-
− GHC/IO/Exception.hs-boot
@@ -1,15 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}--module GHC.IO.Exception where--import GHC.Base-import GHC.Exception--data IOException-instance Exception IOException--type IOError = IOException-userError :: String  -> IOError-unsupportedOperation :: IOError-
− GHC/IO/FD.hs
@@ -1,677 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , BangPatterns-           , AutoDeriveTypeable-  #-}-{-# OPTIONS_GHC -fno-warn-identities #-}--- Whether there are identities depends on the platform-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.FD--- Copyright   :  (c) The University of Glasgow, 1994-2008--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Raw read/write operations on file descriptors-----------------------------------------------------------------------------------module GHC.IO.FD (-        FD(..),-        openFile, mkFD, release,-        setNonBlockingMode,-        readRawBufferPtr, readRawBufferPtrNoBlock, writeRawBufferPtr,-        stdin, stdout, stderr-    ) where--import GHC.Base-import GHC.Num-import GHC.Real-import GHC.Show-import GHC.Enum-import Data.Typeable--import GHC.IO-import GHC.IO.IOMode-import GHC.IO.Buffer-import GHC.IO.BufferedIO-import qualified GHC.IO.Device-import GHC.IO.Device (SeekMode(..), IODeviceType(..))-import GHC.Conc.IO-import GHC.IO.Exception-#ifdef mingw32_HOST_OS-import GHC.Windows-#endif--import Foreign-import Foreign.C-import qualified System.Posix.Internals-import System.Posix.Internals hiding (FD, setEcho, getEcho)-import System.Posix.Types--#ifdef mingw32_HOST_OS-# if defined(i386_HOST_ARCH)-#  define WINDOWS_CCONV stdcall-# elif defined(x86_64_HOST_ARCH)-#  define WINDOWS_CCONV ccall-# else-#  error Unknown mingw32 arch-# endif-#endif--c_DEBUG_DUMP :: Bool-c_DEBUG_DUMP = False---- -------------------------------------------------------------------------------- The file-descriptor IO device--data FD = FD {-  fdFD :: {-# UNPACK #-} !CInt,-#ifdef mingw32_HOST_OS-  -- On Windows, a socket file descriptor needs to be read and written-  -- using different functions (send/recv).-  fdIsSocket_ :: {-# UNPACK #-} !Int-#else-  -- On Unix we need to know whether this FD has O_NONBLOCK set.-  -- If it has, then we can use more efficient routines to read/write to it.-  -- It is always safe for this to be off.-  fdIsNonBlocking :: {-# UNPACK #-} !Int-#endif- }- deriving Typeable--#ifdef mingw32_HOST_OS-fdIsSocket :: FD -> Bool-fdIsSocket fd = fdIsSocket_ fd /= 0-#endif--instance Show FD where-  show fd = show (fdFD fd)--instance GHC.IO.Device.RawIO FD where-  read             = fdRead-  readNonBlocking  = fdReadNonBlocking-  write            = fdWrite-  writeNonBlocking = fdWriteNonBlocking--instance GHC.IO.Device.IODevice FD where-  ready         = ready-  close         = close-  isTerminal    = isTerminal-  isSeekable    = isSeekable-  seek          = seek-  tell          = tell-  getSize       = getSize-  setSize       = setSize-  setEcho       = setEcho-  getEcho       = getEcho-  setRaw        = setRaw-  devType       = devType-  dup           = dup-  dup2          = dup2---- We used to use System.Posix.Internals.dEFAULT_BUFFER_SIZE, which is--- taken from the value of BUFSIZ on the current platform.  This value--- varies too much though: it is 512 on Windows, 1024 on OS X and 8192--- on Linux.  So let's just use a decent size on every platform:-dEFAULT_FD_BUFFER_SIZE :: Int-dEFAULT_FD_BUFFER_SIZE = 8096--instance BufferedIO FD where-  newBuffer _dev state = newByteBuffer dEFAULT_FD_BUFFER_SIZE state-  fillReadBuffer    fd buf = readBuf' fd buf-  fillReadBuffer0   fd buf = readBufNonBlocking fd buf-  flushWriteBuffer  fd buf = writeBuf' fd buf-  flushWriteBuffer0 fd buf = writeBufNonBlocking fd buf--readBuf' :: FD -> Buffer Word8 -> IO (Int, Buffer Word8)-readBuf' fd buf = do-  when c_DEBUG_DUMP $-      puts ("readBuf fd=" ++ show fd ++ " " ++ summaryBuffer buf ++ "\n")-  (r,buf') <- readBuf fd buf-  when c_DEBUG_DUMP $-      puts ("after: " ++ summaryBuffer buf' ++ "\n")-  return (r,buf')--writeBuf' :: FD -> Buffer Word8 -> IO (Buffer Word8)-writeBuf' fd buf = do-  when c_DEBUG_DUMP $-      puts ("writeBuf fd=" ++ show fd ++ " " ++ summaryBuffer buf ++ "\n")-  writeBuf fd buf---- -------------------------------------------------------------------------------- opening files---- | Open a file and make an 'FD' for it.  Truncates the file to zero--- size when the `IOMode` is `WriteMode`.-openFile-  :: FilePath -- ^ file to open-  -> IOMode   -- ^ mode in which to open the file-  -> Bool     -- ^ open the file in non-blocking mode?-  -> IO (FD,IODeviceType)--openFile filepath iomode non_blocking =-  withFilePath filepath $ \ f ->--    let-      oflags1 = case iomode of-                  ReadMode      -> read_flags-                  WriteMode     -> write_flags-                  ReadWriteMode -> rw_flags-                  AppendMode    -> append_flags--#ifdef mingw32_HOST_OS-      binary_flags = o_BINARY-#else-      binary_flags = 0-#endif--      oflags2 = oflags1 .|. binary_flags--      oflags | non_blocking = oflags2 .|. nonblock_flags-             | otherwise    = oflags2-    in do--    -- the old implementation had a complicated series of three opens,-    -- which is perhaps because we have to be careful not to open-    -- directories.  However, the man pages I've read say that open()-    -- always returns EISDIR if the file is a directory and was opened-    -- for writing, so I think we're ok with a single open() here...-    fd <- throwErrnoIfMinus1Retry "openFile"-                (if non_blocking then c_open      f oflags 0o666-                                 else c_safe_open f oflags 0o666)--    (fD,fd_type) <- mkFD fd iomode Nothing{-no stat-}-                            False{-not a socket-}-                            non_blocking-            `catchAny` \e -> do _ <- c_close fd-                                throwIO e--    -- we want to truncate() if this is an open in WriteMode, but only-    -- if the target is a RegularFile.  ftruncate() fails on special files-    -- like /dev/null.-    when (iomode == WriteMode && fd_type == RegularFile) $-      setSize fD 0--    return (fD,fd_type)--std_flags, output_flags, read_flags, write_flags, rw_flags,-    append_flags, nonblock_flags :: CInt-std_flags    = o_NOCTTY-output_flags = std_flags    .|. o_CREAT-read_flags   = std_flags    .|. o_RDONLY-write_flags  = output_flags .|. o_WRONLY-rw_flags     = output_flags .|. o_RDWR-append_flags = write_flags  .|. o_APPEND-nonblock_flags = o_NONBLOCK----- | Make a 'FD' from an existing file descriptor.  Fails if the FD--- refers to a directory.  If the FD refers to a file, `mkFD` locks--- the file according to the Haskell 2010 single writer/multiple reader--- locking semantics (this is why we need the `IOMode` argument too).-mkFD :: CInt-     -> IOMode-     -> Maybe (IODeviceType, CDev, CIno)-     -- the results of fdStat if we already know them, or we want-     -- to prevent fdToHandle_stat from doing its own stat.-     -- These are used for:-     --   - we fail if the FD refers to a directory-     --   - if the FD refers to a file, we lock it using (cdev,cino)-     -> Bool   -- ^ is a socket (on Windows)-     -> Bool   -- ^ is in non-blocking mode on Unix-     -> IO (FD,IODeviceType)--mkFD fd iomode mb_stat is_socket is_nonblock = do--    let _ = (is_socket, is_nonblock) -- warning suppression--    (fd_type,dev,ino) <--        case mb_stat of-          Nothing   -> fdStat fd-          Just stat -> return stat--    let write = case iomode of-                   ReadMode -> False-                   _ -> True--    case fd_type of-        Directory ->-           ioException (IOError Nothing InappropriateType "openFile"-                           "is a directory" Nothing Nothing)--        -- regular files need to be locked-        RegularFile -> do-           -- On Windows we need an additional call to get a unique device id-           -- and inode, since fstat just returns 0 for both.-           (unique_dev, unique_ino) <- getUniqueFileInfo fd dev ino-           r <- lockFile fd unique_dev unique_ino (fromBool write)-           when (r == -1)  $-                ioException (IOError Nothing ResourceBusy "openFile"-                                   "file is locked" Nothing Nothing)--        _other_type -> return ()--#ifdef mingw32_HOST_OS-    when (not is_socket) $ setmode fd True >> return ()-#endif--    return (FD{ fdFD = fd,-#ifndef mingw32_HOST_OS-                fdIsNonBlocking = fromEnum is_nonblock-#else-                fdIsSocket_ = fromEnum is_socket-#endif-              },-            fd_type)--getUniqueFileInfo :: CInt -> CDev -> CIno -> IO (Word64, Word64)-#ifndef mingw32_HOST_OS-getUniqueFileInfo _ dev ino = return (fromIntegral dev, fromIntegral ino)-#else-getUniqueFileInfo fd _ _ = do-  with 0 $ \devptr -> do-    with 0 $ \inoptr -> do-      c_getUniqueFileInfo fd devptr inoptr-      liftM2 (,) (peek devptr) (peek inoptr)-#endif--#ifdef mingw32_HOST_OS-foreign import ccall unsafe "__hscore_setmode"-  setmode :: CInt -> Bool -> IO CInt-#endif---- -------------------------------------------------------------------------------- Standard file descriptors--stdFD :: CInt -> FD-stdFD fd = FD { fdFD = fd,-#ifdef mingw32_HOST_OS-                fdIsSocket_ = 0-#else-                fdIsNonBlocking = 0-   -- We don't set non-blocking mode on standard handles, because it may-   -- confuse other applications attached to the same TTY/pipe-   -- see Note [nonblock]-#endif-                }--stdin, stdout, stderr :: FD-stdin  = stdFD 0-stdout = stdFD 1-stderr = stdFD 2---- -------------------------------------------------------------------------------- Operations on file descriptors--close :: FD -> IO ()-close fd =-  do let closer realFd =-           throwErrnoIfMinus1Retry_ "GHC.IO.FD.close" $-#ifdef mingw32_HOST_OS-           if fdIsSocket fd then-             c_closesocket (fromIntegral realFd)-           else-#endif-             c_close (fromIntegral realFd)--     -- release the lock *first*, because otherwise if we're preempted-     -- after closing but before releasing, the FD may have been reused.-     -- (#7646)-     release fd--     closeFdWith closer (fromIntegral (fdFD fd))--release :: FD -> IO ()-release fd = do _ <- unlockFile (fdFD fd)-                return ()--#ifdef mingw32_HOST_OS-foreign import WINDOWS_CCONV unsafe "HsBase.h closesocket"-   c_closesocket :: CInt -> IO CInt-#endif--isSeekable :: FD -> IO Bool-isSeekable fd = do-  t <- devType fd-  return (t == RegularFile || t == RawDevice)--seek :: FD -> SeekMode -> Integer -> IO ()-seek fd mode off = do-  throwErrnoIfMinus1Retry_ "seek" $-     c_lseek (fdFD fd) (fromIntegral off) seektype- where-    seektype :: CInt-    seektype = case mode of-                   AbsoluteSeek -> sEEK_SET-                   RelativeSeek -> sEEK_CUR-                   SeekFromEnd  -> sEEK_END--tell :: FD -> IO Integer-tell fd =- fromIntegral `fmap`-   (throwErrnoIfMinus1Retry "hGetPosn" $-      c_lseek (fdFD fd) 0 sEEK_CUR)--getSize :: FD -> IO Integer-getSize fd = fdFileSize (fdFD fd)--setSize :: FD -> Integer -> IO ()-setSize fd size = do-  throwErrnoIf_ (/=0) "GHC.IO.FD.setSize"  $-     c_ftruncate (fdFD fd) (fromIntegral size)--devType :: FD -> IO IODeviceType-devType fd = do (ty,_,_) <- fdStat (fdFD fd); return ty--dup :: FD -> IO FD-dup fd = do-  newfd <- throwErrnoIfMinus1 "GHC.IO.FD.dup" $ c_dup (fdFD fd)-  return fd{ fdFD = newfd }--dup2 :: FD -> FD -> IO FD-dup2 fd fdto = do-  -- Windows' dup2 does not return the new descriptor, unlike Unix-  throwErrnoIfMinus1_ "GHC.IO.FD.dup2" $-    c_dup2 (fdFD fd) (fdFD fdto)-  return fd{ fdFD = fdFD fdto } -- original FD, with the new fdFD--setNonBlockingMode :: FD -> Bool -> IO FD-setNonBlockingMode fd set = do-  setNonBlockingFD (fdFD fd) set-#if defined(mingw32_HOST_OS)-  return fd-#else-  return fd{ fdIsNonBlocking = fromEnum set }-#endif--ready :: FD -> Bool -> Int -> IO Bool-ready fd write msecs = do-  r <- throwErrnoIfMinus1Retry "GHC.IO.FD.ready" $-          fdReady (fdFD fd) (fromIntegral $ fromEnum $ write)-                            (fromIntegral msecs)-#if defined(mingw32_HOST_OS)-                          (fromIntegral $ fromEnum $ fdIsSocket fd)-#else-                          0-#endif-  return (toEnum (fromIntegral r))--foreign import ccall safe "fdReady"-  fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt---- ------------------------------------------------------------------------------ Terminal-related stuff--isTerminal :: FD -> IO Bool-isTerminal fd =-#if defined(mingw32_HOST_OS)-    if fdIsSocket fd then return False-                     else is_console (fdFD fd) >>= return.toBool-#else-    c_isatty (fdFD fd) >>= return.toBool-#endif--setEcho :: FD -> Bool -> IO ()-setEcho fd on = System.Posix.Internals.setEcho (fdFD fd) on--getEcho :: FD -> IO Bool-getEcho fd = System.Posix.Internals.getEcho (fdFD fd)--setRaw :: FD -> Bool -> IO ()-setRaw fd raw = System.Posix.Internals.setCooked (fdFD fd) (not raw)---- -------------------------------------------------------------------------------- Reading and Writing--fdRead :: FD -> Ptr Word8 -> Int -> IO Int-fdRead fd ptr bytes-  = do { r <- readRawBufferPtr "GHC.IO.FD.fdRead" fd ptr 0 (fromIntegral bytes)-       ; return (fromIntegral r) }--fdReadNonBlocking :: FD -> Ptr Word8 -> Int -> IO (Maybe Int)-fdReadNonBlocking fd ptr bytes = do-  r <- readRawBufferPtrNoBlock "GHC.IO.FD.fdReadNonBlocking" fd ptr-           0 (fromIntegral bytes)-  case fromIntegral r of-    (-1) -> return (Nothing)-    n    -> return (Just n)---fdWrite :: FD -> Ptr Word8 -> Int -> IO ()-fdWrite fd ptr bytes = do-  res <- writeRawBufferPtr "GHC.IO.FD.fdWrite" fd ptr 0 (fromIntegral bytes)-  let res' = fromIntegral res-  if res' < bytes-     then fdWrite fd (ptr `plusPtr` res') (bytes - res')-     else return ()---- XXX ToDo: this isn't non-blocking-fdWriteNonBlocking :: FD -> Ptr Word8 -> Int -> IO Int-fdWriteNonBlocking fd ptr bytes = do-  res <- writeRawBufferPtrNoBlock "GHC.IO.FD.fdWriteNonBlocking" fd ptr 0-            (fromIntegral bytes)-  return (fromIntegral res)---- -------------------------------------------------------------------------------- FD operations---- Low level routines for reading/writing to (raw)buffers:--#ifndef mingw32_HOST_OS--{--NOTE [nonblock]:--Unix has broken semantics when it comes to non-blocking I/O: you can-set the O_NONBLOCK flag on an FD, but it applies to the all other FDs-attached to the same underlying file, pipe or TTY; there's no way to-have private non-blocking behaviour for an FD.  See bug #724.--We fix this by only setting O_NONBLOCK on FDs that we create; FDs that-come from external sources or are exposed externally are left in-blocking mode.  This solution has some problems though.  We can't-completely simulate a non-blocking read without O_NONBLOCK: several-cases are wrong here.  The cases that are wrong:--  * reading/writing to a blocking FD in non-threaded mode.-    In threaded mode, we just make a safe call to read().-    In non-threaded mode we call select() before attempting to read,-    but that leaves a small race window where the data can be read-    from the file descriptor before we issue our blocking read().-  * readRawBufferNoBlock for a blocking FD--NOTE [2363]:--In the threaded RTS we could just make safe calls to read()/write()-for file descriptors in blocking mode without worrying about blocking-other threads, but the problem with this is that the thread will be-uninterruptible while it is blocked in the foreign call.  See #2363.-So now we always call fdReady() before reading, and if fdReady-indicates that there's no data, we call threadWaitRead.---}--readRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO Int-readRawBufferPtr loc !fd buf off len-  | isNonBlocking fd = unsafe_read -- unsafe is ok, it can't block-  | otherwise    = do r <- throwErrnoIfMinus1 loc-                                (unsafe_fdReady (fdFD fd) 0 0 0)-                      if r /= 0-                        then read-                        else do threadWaitRead (fromIntegral (fdFD fd)); read-  where-    do_read call = fromIntegral `fmap`-                      throwErrnoIfMinus1RetryMayBlock loc call-                            (threadWaitRead (fromIntegral (fdFD fd)))-    read        = if threaded then safe_read else unsafe_read-    unsafe_read = do_read (c_read (fdFD fd) (buf `plusPtr` off) len)-    safe_read   = do_read (c_safe_read (fdFD fd) (buf `plusPtr` off) len)---- return: -1 indicates EOF, >=0 is bytes read-readRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO Int-readRawBufferPtrNoBlock loc !fd buf off len-  | isNonBlocking fd  = unsafe_read -- unsafe is ok, it can't block-  | otherwise    = do r <- unsafe_fdReady (fdFD fd) 0 0 0-                      if r /= 0 then safe_read-                                else return 0-       -- XXX see note [nonblock]- where-   do_read call = do r <- throwErrnoIfMinus1RetryOnBlock loc call (return (-1))-                     case r of-                       (-1) -> return 0-                       0    -> return (-1)-                       n    -> return (fromIntegral n)-   unsafe_read  = do_read (c_read (fdFD fd) (buf `plusPtr` off) len)-   safe_read    = do_read (c_safe_read (fdFD fd) (buf `plusPtr` off) len)--writeRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt-writeRawBufferPtr loc !fd buf off len-  | isNonBlocking fd = unsafe_write -- unsafe is ok, it can't block-  | otherwise   = do r <- unsafe_fdReady (fdFD fd) 1 0 0-                     if r /= 0-                        then write-                        else do threadWaitWrite (fromIntegral (fdFD fd)); write-  where-    do_write call = fromIntegral `fmap`-                      throwErrnoIfMinus1RetryMayBlock loc call-                        (threadWaitWrite (fromIntegral (fdFD fd)))-    write         = if threaded then safe_write else unsafe_write-    unsafe_write  = do_write (c_write (fdFD fd) (buf `plusPtr` off) len)-    safe_write    = do_write (c_safe_write (fdFD fd) (buf `plusPtr` off) len)--writeRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt-writeRawBufferPtrNoBlock loc !fd buf off len-  | isNonBlocking fd = unsafe_write -- unsafe is ok, it can't block-  | otherwise   = do r <- unsafe_fdReady (fdFD fd) 1 0 0-                     if r /= 0 then write-                               else return 0-  where-    do_write call = do r <- throwErrnoIfMinus1RetryOnBlock loc call (return (-1))-                       case r of-                         (-1) -> return 0-                         n    -> return (fromIntegral n)-    write         = if threaded then safe_write else unsafe_write-    unsafe_write  = do_write (c_write (fdFD fd) (buf `plusPtr` off) len)-    safe_write    = do_write (c_safe_write (fdFD fd) (buf `plusPtr` off) len)--isNonBlocking :: FD -> Bool-isNonBlocking fd = fdIsNonBlocking fd /= 0--foreign import ccall unsafe "fdReady"-  unsafe_fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt--#else /* mingw32_HOST_OS.... */--readRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt-readRawBufferPtr loc !fd buf off len-  | threaded  = blockingReadRawBufferPtr loc fd buf off len-  | otherwise = asyncReadRawBufferPtr    loc fd buf off len--writeRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt-writeRawBufferPtr loc !fd buf off len-  | threaded  = blockingWriteRawBufferPtr loc fd buf off len-  | otherwise = asyncWriteRawBufferPtr    loc fd buf off len--readRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt-readRawBufferPtrNoBlock = readRawBufferPtr--writeRawBufferPtrNoBlock :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt-writeRawBufferPtrNoBlock = writeRawBufferPtr---- Async versions of the read/write primitives, for the non-threaded RTS--asyncReadRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt-asyncReadRawBufferPtr loc !fd buf off len = do-    (l, rc) <- asyncRead (fromIntegral (fdFD fd)) (fdIsSocket_ fd)-                        (fromIntegral len) (buf `plusPtr` off)-    if l == (-1)-      then-        ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)-      else return (fromIntegral l)--asyncWriteRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt-asyncWriteRawBufferPtr loc !fd buf off len = do-    (l, rc) <- asyncWrite (fromIntegral (fdFD fd)) (fdIsSocket_ fd)-                  (fromIntegral len) (buf `plusPtr` off)-    if l == (-1)-      then-        ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)-      else return (fromIntegral l)---- Blocking versions of the read/write primitives, for the threaded RTS--blockingReadRawBufferPtr :: String -> FD -> Ptr Word8 -> Int -> CSize -> IO CInt-blockingReadRawBufferPtr loc fd buf off len-  = fmap fromIntegral $ throwErrnoIfMinus1Retry loc $-        if fdIsSocket fd-           then c_safe_recv (fdFD fd) (buf `plusPtr` off) len 0-           else c_safe_read (fdFD fd) (buf `plusPtr` off) len--blockingWriteRawBufferPtr :: String -> FD -> Ptr Word8-> Int -> CSize -> IO CInt-blockingWriteRawBufferPtr loc fd buf off len-  = fmap fromIntegral $ throwErrnoIfMinus1Retry loc $-        if fdIsSocket fd-           then c_safe_send  (fdFD fd) (buf `plusPtr` off) len 0-           else do-             r <- c_safe_write (fdFD fd) (buf `plusPtr` off) len-             when (r == -1) c_maperrno-             return r-      -- we don't trust write() to give us the correct errno, and-      -- instead do the errno conversion from GetLastError()-      -- ourselves.  The main reason is that we treat ERROR_NO_DATA-      -- (pipe is closing) as EPIPE, whereas write() returns EINVAL-      -- for this case.  We need to detect EPIPE correctly, because it-      -- shouldn't be reported as an error when it happens on stdout.---- NOTE: "safe" versions of the read/write calls for use by the threaded RTS.--- These calls may block, but that's ok.--foreign import WINDOWS_CCONV safe "recv"-   c_safe_recv :: CInt -> Ptr Word8 -> CSize -> CInt{-flags-} -> IO CSsize--foreign import WINDOWS_CCONV safe "send"-   c_safe_send :: CInt -> Ptr Word8 -> CSize -> CInt{-flags-} -> IO CSsize--#endif--foreign import ccall "rtsSupportsBoundThreads" threaded :: Bool---- -------------------------------------------------------------------------------- utils--#ifndef mingw32_HOST_OS-throwErrnoIfMinus1RetryOnBlock  :: String -> IO CSsize -> IO CSsize -> IO CSsize-throwErrnoIfMinus1RetryOnBlock loc f on_block  =-  do-    res <- f-    if (res :: CSsize) == -1-      then do-        err <- getErrno-        if err == eINTR-          then throwErrnoIfMinus1RetryOnBlock loc f on_block-          else if err == eWOULDBLOCK || err == eAGAIN-                 then do on_block-                 else throwErrno loc-      else return res-#endif---- -------------------------------------------------------------------------------- Locking/unlocking--foreign import ccall unsafe "lockFile"-  lockFile :: CInt -> Word64 -> Word64 -> CInt -> IO CInt--foreign import ccall unsafe "unlockFile"-  unlockFile :: CInt -> IO CInt--#ifdef mingw32_HOST_OS-foreign import ccall unsafe "get_unique_file_info"-  c_getUniqueFileInfo :: CInt -> Ptr Word64 -> Ptr Word64 -> IO ()-#endif
− GHC/IO/Handle.hs
@@ -1,743 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , RecordWildCards-           , NondecreasingIndentation-  #-}-{-# OPTIONS_GHC -fno-warn-unused-matches #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Handle--- Copyright   :  (c) The University of Glasgow, 1994-2009--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  non-portable------ External API for GHC's Handle implementation-----------------------------------------------------------------------------------module GHC.IO.Handle (-   Handle,-   BufferMode(..),--   mkFileHandle, mkDuplexHandle,--   hFileSize, hSetFileSize, hIsEOF, hLookAhead,-   hSetBuffering, hSetBinaryMode, hSetEncoding, hGetEncoding,-   hFlush, hFlushAll, hDuplicate, hDuplicateTo,--   hClose, hClose_help,--   HandlePosition, HandlePosn(..), hGetPosn, hSetPosn,-   SeekMode(..), hSeek, hTell,--   hIsOpen, hIsClosed, hIsReadable, hIsWritable, hGetBuffering, hIsSeekable,-   hSetEcho, hGetEcho, hIsTerminalDevice,--   hSetNewlineMode, Newline(..), NewlineMode(..), nativeNewline,-   noNewlineTranslation, universalNewlineMode, nativeNewlineMode,--   hShow,--   hWaitForInput, hGetChar, hGetLine, hGetContents, hPutChar, hPutStr,--   hGetBuf, hGetBufNonBlocking, hPutBuf, hPutBufNonBlocking- ) where--import GHC.IO-import GHC.IO.Exception-import GHC.IO.Encoding-import GHC.IO.Buffer-import GHC.IO.BufferedIO ( BufferedIO )-import GHC.IO.Device as IODevice-import GHC.IO.Handle.Types-import GHC.IO.Handle.Internals-import GHC.IO.Handle.Text-import qualified GHC.IO.BufferedIO as Buffered--import GHC.Base-import GHC.Exception-import GHC.MVar-import GHC.IORef-import GHC.Show-import GHC.Num-import GHC.Real-import Data.Maybe-import Data.Typeable---- ------------------------------------------------------------------------------ Closing a handle---- | Computation 'hClose' @hdl@ makes handle @hdl@ closed.  Before the--- computation finishes, if @hdl@ is writable its buffer is flushed as--- for 'hFlush'.--- Performing 'hClose' on a handle that has already been closed has no effect;--- doing so is not an error.  All other operations on a closed handle will fail.--- If 'hClose' fails for any reason, any further operations (apart from--- 'hClose') on the handle will still fail as if @hdl@ had been successfully--- closed.--hClose :: Handle -> IO ()-hClose h@(FileHandle _ m)     = do-  mb_exc <- hClose' h m-  hClose_maybethrow mb_exc h-hClose h@(DuplexHandle _ r w) = do-  excs <- mapM (hClose' h) [r,w]-  hClose_maybethrow (listToMaybe (catMaybes excs)) h--hClose_maybethrow :: Maybe SomeException -> Handle -> IO ()-hClose_maybethrow Nothing  h = return ()-hClose_maybethrow (Just e) h = hClose_rethrow e h--hClose_rethrow :: SomeException -> Handle -> IO ()-hClose_rethrow e h =-  case fromException e of-    Just ioe -> ioError (augmentIOError ioe "hClose" h)-    Nothing  -> throwIO e--hClose' :: Handle -> MVar Handle__ -> IO (Maybe SomeException)-hClose' h m = withHandle' "hClose" h m $ hClose_help---------------------------------------------------------------------------------- Detecting and changing the size of a file---- | For a handle @hdl@ which attached to a physical file,--- 'hFileSize' @hdl@ returns the size of that file in 8-bit bytes.--hFileSize :: Handle -> IO Integer-hFileSize handle =-    withHandle_ "hFileSize" handle $ \ handle_@Handle__{haDevice=dev} -> do-    case haType handle_ of-      ClosedHandle              -> ioe_closedHandle-      SemiClosedHandle          -> ioe_closedHandle-      _ -> do flushWriteBuffer handle_-              r <- IODevice.getSize dev-              if r /= -1-                 then return r-                 else ioException (IOError Nothing InappropriateType "hFileSize"-                                   "not a regular file" Nothing Nothing)----- | 'hSetFileSize' @hdl@ @size@ truncates the physical file with handle @hdl@ to @size@ bytes.--hSetFileSize :: Handle -> Integer -> IO ()-hSetFileSize handle size =-    withHandle_ "hSetFileSize" handle $ \ handle_@Handle__{haDevice=dev} -> do-    case haType handle_ of-      ClosedHandle              -> ioe_closedHandle-      SemiClosedHandle          -> ioe_closedHandle-      _ -> do flushWriteBuffer handle_-              IODevice.setSize dev size-              return ()---- ------------------------------------------------------------------------------ Detecting the End of Input---- | For a readable handle @hdl@, 'hIsEOF' @hdl@ returns--- 'True' if no further input can be taken from @hdl@ or for a--- physical file, if the current I\/O position is equal to the length of--- the file.  Otherwise, it returns 'False'.------ NOTE: 'hIsEOF' may block, because it has to attempt to read from--- the stream to determine whether there is any more data to be read.--hIsEOF :: Handle -> IO Bool-hIsEOF handle = wantReadableHandle_ "hIsEOF" handle $ \Handle__{..} -> do--  cbuf <- readIORef haCharBuffer-  if not (isEmptyBuffer cbuf) then return False else do--  bbuf <- readIORef haByteBuffer-  if not (isEmptyBuffer bbuf) then return False else do--  -- NB. do no decoding, just fill the byte buffer; see #3808-  (r,bbuf') <- Buffered.fillReadBuffer haDevice bbuf-  if r == 0-     then return True-     else do writeIORef haByteBuffer bbuf'-             return False---- ------------------------------------------------------------------------------ Looking ahead---- | Computation 'hLookAhead' returns the next character from the handle--- without removing it from the input buffer, blocking until a character--- is available.------ This operation may fail with:------  * 'isEOFError' if the end of file has been reached.--hLookAhead :: Handle -> IO Char-hLookAhead handle =-  wantReadableHandle_ "hLookAhead"  handle hLookAhead_---- ------------------------------------------------------------------------------ Buffering Operations---- Three kinds of buffering are supported: line-buffering,--- block-buffering or no-buffering.  See GHC.IO.Handle for definition and--- further explanation of what the type represent.---- | Computation 'hSetBuffering' @hdl mode@ sets the mode of buffering for--- handle @hdl@ on subsequent reads and writes.------ If the buffer mode is changed from 'BlockBuffering' or--- 'LineBuffering' to 'NoBuffering', then------  * if @hdl@ is writable, the buffer is flushed as for 'hFlush';------  * if @hdl@ is not writable, the contents of the buffer is discarded.------ This operation may fail with:------  * 'isPermissionError' if the handle has already been used for reading---    or writing and the implementation does not allow the buffering mode---    to be changed.--hSetBuffering :: Handle -> BufferMode -> IO ()-hSetBuffering handle mode =-  withAllHandles__ "hSetBuffering" handle $ \ handle_@Handle__{..} -> do-  case haType of-    ClosedHandle -> ioe_closedHandle-    _ -> do-         if mode == haBufferMode then return handle_ else do--         -- See [note Buffer Sizing] in GHC.IO.Handle.Types--          -- check for errors:-          case mode of-              BlockBuffering (Just n) | n <= 0    -> ioe_bufsiz n-              _ -> return ()--          -- for input terminals we need to put the terminal into-          -- cooked or raw mode depending on the type of buffering.-          is_tty <- IODevice.isTerminal haDevice-          when (is_tty && isReadableHandleType haType) $-                case mode of-#ifndef mingw32_HOST_OS-        -- 'raw' mode under win32 is a bit too specialised (and troublesome-        -- for most common uses), so simply disable its use here.-                  NoBuffering -> IODevice.setRaw haDevice True-#else-                  NoBuffering -> return ()-#endif-                  _           -> IODevice.setRaw haDevice False--          -- throw away spare buffers, they might be the wrong size-          writeIORef haBuffers BufferListNil--          return Handle__{ haBufferMode = mode,.. }---- -------------------------------------------------------------------------------- hSetEncoding---- | The action 'hSetEncoding' @hdl@ @encoding@ changes the text encoding--- for the handle @hdl@ to @encoding@.  The default encoding when a 'Handle' is--- created is 'localeEncoding', namely the default encoding for the current--- locale.------ To create a 'Handle' with no encoding at all, use 'openBinaryFile'.  To--- stop further encoding or decoding on an existing 'Handle', use--- 'hSetBinaryMode'.------ 'hSetEncoding' may need to flush buffered data in order to change--- the encoding.----hSetEncoding :: Handle -> TextEncoding -> IO ()-hSetEncoding hdl encoding = do-  withAllHandles__ "hSetEncoding" hdl $ \h_@Handle__{..} -> do-    flushCharBuffer h_-    closeTextCodecs h_-    openTextEncoding (Just encoding) haType $ \ mb_encoder mb_decoder -> do-    bbuf <- readIORef haByteBuffer-    ref <- newIORef (error "last_decode")-    return (Handle__{ haLastDecode = ref,-                      haDecoder = mb_decoder,-                      haEncoder = mb_encoder,-                      haCodec   = Just encoding, .. })---- | Return the current 'TextEncoding' for the specified 'Handle', or--- 'Nothing' if the 'Handle' is in binary mode.------ Note that the 'TextEncoding' remembers nothing about the state of--- the encoder/decoder in use on this 'Handle'.  For example, if the--- encoding in use is UTF-16, then using 'hGetEncoding' and--- 'hSetEncoding' to save and restore the encoding may result in an--- extra byte-order-mark being written to the file.----hGetEncoding :: Handle -> IO (Maybe TextEncoding)-hGetEncoding hdl =-  withHandle_ "hGetEncoding" hdl $ \h_@Handle__{..} -> return haCodec---- -------------------------------------------------------------------------------- hFlush---- | The action 'hFlush' @hdl@ causes any items buffered for output--- in handle @hdl@ to be sent immediately to the operating system.------ This operation may fail with:------  * 'isFullError' if the device is full;------  * 'isPermissionError' if a system resource limit would be exceeded.---    It is unspecified whether the characters in the buffer are discarded---    or retained under these circumstances.--hFlush :: Handle -> IO ()-hFlush handle = wantWritableHandle "hFlush" handle flushWriteBuffer---- | The action 'hFlushAll' @hdl@ flushes all buffered data in @hdl@,--- including any buffered read data.  Buffered read data is flushed--- by seeking the file position back to the point before the bufferred--- data was read, and hence only works if @hdl@ is seekable (see--- 'hIsSeekable').------ This operation may fail with:------  * 'isFullError' if the device is full;------  * 'isPermissionError' if a system resource limit would be exceeded.---    It is unspecified whether the characters in the buffer are discarded---    or retained under these circumstances;------  * 'isIllegalOperation' if @hdl@ has buffered read data, and is not---    seekable.--hFlushAll :: Handle -> IO ()-hFlushAll handle = withHandle_ "hFlushAll" handle flushBuffer---- -------------------------------------------------------------------------------- Repositioning Handles--data HandlePosn = HandlePosn Handle HandlePosition--instance Eq HandlePosn where-    (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2--instance Show HandlePosn where-   showsPrec p (HandlePosn h pos) =-        showsPrec p h . showString " at position " . shows pos--  -- HandlePosition is the Haskell equivalent of POSIX' off_t.-  -- We represent it as an Integer on the Haskell side, but-  -- cheat slightly in that hGetPosn calls upon a C helper-  -- that reports the position back via (merely) an Int.-type HandlePosition = Integer---- | Computation 'hGetPosn' @hdl@ returns the current I\/O position of--- @hdl@ as a value of the abstract type 'HandlePosn'.--hGetPosn :: Handle -> IO HandlePosn-hGetPosn handle = do-    posn <- hTell handle-    return (HandlePosn handle posn)---- | If a call to 'hGetPosn' @hdl@ returns a position @p@,--- then computation 'hSetPosn' @p@ sets the position of @hdl@--- to the position it held at the time of the call to 'hGetPosn'.------ This operation may fail with:------  * 'isPermissionError' if a system resource limit would be exceeded.--hSetPosn :: HandlePosn -> IO ()-hSetPosn (HandlePosn h i) = hSeek h AbsoluteSeek i---- ------------------------------------------------------------------------------ hSeek--{- Note:- - when seeking using `SeekFromEnd', positive offsets (>=0) means-   seeking at or past EOF.-- - we possibly deviate from the report on the issue of seeking within-   the buffer and whether to flush it or not.  The report isn't exactly-   clear here.--}---- | Computation 'hSeek' @hdl mode i@ sets the position of handle--- @hdl@ depending on @mode@.--- The offset @i@ is given in terms of 8-bit bytes.------ If @hdl@ is block- or line-buffered, then seeking to a position which is not--- in the current buffer will first cause any items in the output buffer to be--- written to the device, and then cause the input buffer to be discarded.--- Some handles may not be seekable (see 'hIsSeekable'), or only support a--- subset of the possible positioning operations (for instance, it may only--- be possible to seek to the end of a tape, or to a positive offset from--- the beginning or current position).--- It is not possible to set a negative I\/O position, or for--- a physical file, an I\/O position beyond the current end-of-file.------ This operation may fail with:------  * 'isIllegalOperationError' if the Handle is not seekable, or does---     not support the requested seek mode.------  * 'isPermissionError' if a system resource limit would be exceeded.--hSeek :: Handle -> SeekMode -> Integer -> IO ()-hSeek handle mode offset =-    wantSeekableHandle "hSeek" handle $ \ handle_@Handle__{..} -> do-    debugIO ("hSeek " ++ show (mode,offset))-    buf <- readIORef haCharBuffer--    if isWriteBuffer buf-        then do flushWriteBuffer handle_-                IODevice.seek haDevice mode offset-        else do--    let r = bufL buf; w = bufR buf-    if mode == RelativeSeek && isNothing haDecoder &&-       offset >= 0 && offset < fromIntegral (w - r)-        then writeIORef haCharBuffer buf{ bufL = r + fromIntegral offset }-        else do--    flushCharReadBuffer handle_-    flushByteReadBuffer handle_-    IODevice.seek haDevice mode offset----- | Computation 'hTell' @hdl@ returns the current position of the--- handle @hdl@, as the number of bytes from the beginning of--- the file.  The value returned may be subsequently passed to--- 'hSeek' to reposition the handle to the current position.------ This operation may fail with:------  * 'isIllegalOperationError' if the Handle is not seekable.----hTell :: Handle -> IO Integer-hTell handle =-    wantSeekableHandle "hGetPosn" handle $ \ handle_@Handle__{..} -> do--      posn <- IODevice.tell haDevice--      -- we can't tell the real byte offset if there are buffered-      -- Chars, so must flush first:-      flushCharBuffer handle_--      bbuf <- readIORef haByteBuffer--      let real_posn-           | isWriteBuffer bbuf = posn + fromIntegral (bufferElems bbuf)-           | otherwise          = posn - fromIntegral (bufferElems bbuf)--      cbuf <- readIORef haCharBuffer-      debugIO ("\nhGetPosn: (posn, real_posn) = " ++ show (posn, real_posn))-      debugIO ("   cbuf: " ++ summaryBuffer cbuf ++-            "   bbuf: " ++ summaryBuffer bbuf)--      return real_posn---- -------------------------------------------------------------------------------- Handle Properties---- A number of operations return information about the properties of a--- handle.  Each of these operations returns `True' if the handle has--- the specified property, and `False' otherwise.--hIsOpen :: Handle -> IO Bool-hIsOpen handle =-    withHandle_ "hIsOpen" handle $ \ handle_ -> do-    case haType handle_ of-      ClosedHandle         -> return False-      SemiClosedHandle     -> return False-      _                    -> return True--hIsClosed :: Handle -> IO Bool-hIsClosed handle =-    withHandle_ "hIsClosed" handle $ \ handle_ -> do-    case haType handle_ of-      ClosedHandle         -> return True-      _                    -> return False--{- not defined, nor exported, but mentioned-   here for documentation purposes:--    hSemiClosed :: Handle -> IO Bool-    hSemiClosed h = do-       ho <- hIsOpen h-       hc <- hIsClosed h-       return (not (ho || hc))--}--hIsReadable :: Handle -> IO Bool-hIsReadable (DuplexHandle _ _ _) = return True-hIsReadable handle =-    withHandle_ "hIsReadable" handle $ \ handle_ -> do-    case haType handle_ of-      ClosedHandle         -> ioe_closedHandle-      SemiClosedHandle     -> ioe_closedHandle-      htype                -> return (isReadableHandleType htype)--hIsWritable :: Handle -> IO Bool-hIsWritable (DuplexHandle _ _ _) = return True-hIsWritable handle =-    withHandle_ "hIsWritable" handle $ \ handle_ -> do-    case haType handle_ of-      ClosedHandle         -> ioe_closedHandle-      SemiClosedHandle     -> ioe_closedHandle-      htype                -> return (isWritableHandleType htype)---- | Computation 'hGetBuffering' @hdl@ returns the current buffering mode--- for @hdl@.--hGetBuffering :: Handle -> IO BufferMode-hGetBuffering handle =-    withHandle_ "hGetBuffering" handle $ \ handle_ -> do-    case haType handle_ of-      ClosedHandle         -> ioe_closedHandle-      _ ->-           -- We're being non-standard here, and allow the buffering-           -- of a semi-closed handle to be queried.   -- sof 6/98-          return (haBufferMode handle_)  -- could be stricter..--hIsSeekable :: Handle -> IO Bool-hIsSeekable handle =-    withHandle_ "hIsSeekable" handle $ \ handle_@Handle__{..} -> do-    case haType of-      ClosedHandle         -> ioe_closedHandle-      SemiClosedHandle     -> ioe_closedHandle-      AppendHandle         -> return False-      _                    -> IODevice.isSeekable haDevice---- -------------------------------------------------------------------------------- Changing echo status (Non-standard GHC extensions)---- | Set the echoing status of a handle connected to a terminal.--hSetEcho :: Handle -> Bool -> IO ()-hSetEcho handle on = do-    isT   <- hIsTerminalDevice handle-    if not isT-     then return ()-     else-      withHandle_ "hSetEcho" handle $ \ Handle__{..} -> do-      case haType of-         ClosedHandle -> ioe_closedHandle-         _            -> IODevice.setEcho haDevice on---- | Get the echoing status of a handle connected to a terminal.--hGetEcho :: Handle -> IO Bool-hGetEcho handle = do-    isT   <- hIsTerminalDevice handle-    if not isT-     then return False-     else-       withHandle_ "hGetEcho" handle $ \ Handle__{..} -> do-       case haType of-         ClosedHandle -> ioe_closedHandle-         _            -> IODevice.getEcho haDevice---- | Is the handle connected to a terminal?--hIsTerminalDevice :: Handle -> IO Bool-hIsTerminalDevice handle = do-    withHandle_ "hIsTerminalDevice" handle $ \ Handle__{..} -> do-     case haType of-       ClosedHandle -> ioe_closedHandle-       _            -> IODevice.isTerminal haDevice---- -------------------------------------------------------------------------------- hSetBinaryMode---- | Select binary mode ('True') or text mode ('False') on a open handle.--- (See also 'openBinaryFile'.)------ This has the same effect as calling 'hSetEncoding' with 'char8', together--- with 'hSetNewlineMode' with 'noNewlineTranslation'.----hSetBinaryMode :: Handle -> Bool -> IO ()-hSetBinaryMode handle bin =-  withAllHandles__ "hSetBinaryMode" handle $ \ h_@Handle__{..} ->-    do-         flushCharBuffer h_-         closeTextCodecs h_--         mb_te <- if bin then return Nothing-                         else fmap Just getLocaleEncoding--         openTextEncoding mb_te haType $ \ mb_encoder mb_decoder -> do--         -- should match the default newline mode, whatever that is-         let nl    | bin       = noNewlineTranslation-                   | otherwise = nativeNewlineMode--         bbuf <- readIORef haByteBuffer-         ref <- newIORef (error "codec_state", bbuf)--         return Handle__{ haLastDecode = ref,-                          haEncoder  = mb_encoder,-                          haDecoder  = mb_decoder,-                          haCodec    = mb_te,-                          haInputNL  = inputNL nl,-                          haOutputNL = outputNL nl, .. }---- -------------------------------------------------------------------------------- hSetNewlineMode---- | Set the 'NewlineMode' on the specified 'Handle'.  All buffered--- data is flushed first.-hSetNewlineMode :: Handle -> NewlineMode -> IO ()-hSetNewlineMode handle NewlineMode{ inputNL=i, outputNL=o } =-  withAllHandles__ "hSetNewlineMode" handle $ \h_@Handle__{..} ->-    do-         flushBuffer h_-         return h_{ haInputNL=i, haOutputNL=o }---- -------------------------------------------------------------------------------- Duplicating a Handle---- | Returns a duplicate of the original handle, with its own buffer.--- The two Handles will share a file pointer, however.  The original--- handle's buffer is flushed, including discarding any input data,--- before the handle is duplicated.--hDuplicate :: Handle -> IO Handle-hDuplicate h@(FileHandle path m) = do-  withHandle_' "hDuplicate" h m $ \h_ ->-      dupHandle path h Nothing h_ (Just handleFinalizer)-hDuplicate h@(DuplexHandle path r w) = do-  write_side@(FileHandle _ write_m) <--     withHandle_' "hDuplicate" h w $ \h_ ->-        dupHandle path h Nothing h_ (Just handleFinalizer)-  read_side@(FileHandle _ read_m) <--    withHandle_' "hDuplicate" h r $ \h_ ->-        dupHandle path h (Just write_m) h_  Nothing-  return (DuplexHandle path read_m write_m)--dupHandle :: FilePath-          -> Handle-          -> Maybe (MVar Handle__)-          -> Handle__-          -> Maybe HandleFinalizer-          -> IO Handle-dupHandle filepath h other_side h_@Handle__{..} mb_finalizer = do-  -- flush the buffer first, so we don't have to copy its contents-  flushBuffer h_-  case other_side of-    Nothing -> do-       new_dev <- IODevice.dup haDevice-       dupHandle_ new_dev filepath other_side h_ mb_finalizer-    Just r  ->-       withHandle_' "dupHandle" h r $ \Handle__{haDevice=dev} -> do-         dupHandle_ dev filepath other_side h_ mb_finalizer--dupHandle_ :: (IODevice dev, BufferedIO dev, Typeable dev) => dev-           -> FilePath-           -> Maybe (MVar Handle__)-           -> Handle__-           -> Maybe HandleFinalizer-           -> IO Handle-dupHandle_ new_dev filepath other_side h_@Handle__{..} mb_finalizer = do-   -- XXX wrong!-  mb_codec <- if isJust haEncoder then fmap Just getLocaleEncoding else return Nothing-  mkHandle new_dev filepath haType True{-buffered-} mb_codec-      NewlineMode { inputNL = haInputNL, outputNL = haOutputNL }-      mb_finalizer other_side---- -------------------------------------------------------------------------------- Replacing a Handle--{- |-Makes the second handle a duplicate of the first handle.  The second-handle will be closed first, if it is not already.--This can be used to retarget the standard Handles, for example:--> do h <- openFile "mystdout" WriteMode->    hDuplicateTo h stdout--}--hDuplicateTo :: Handle -> Handle -> IO ()-hDuplicateTo h1@(FileHandle path m1) h2@(FileHandle _ m2)  = do- withHandle__' "hDuplicateTo" h2 m2 $ \h2_ -> do-   _ <- hClose_help h2_-   withHandle_' "hDuplicateTo" h1 m1 $ \h1_ -> do-     dupHandleTo path h1 Nothing h2_ h1_ (Just handleFinalizer)-hDuplicateTo h1@(DuplexHandle path r1 w1) h2@(DuplexHandle _ r2 w2)  = do- withHandle__' "hDuplicateTo" h2 w2  $ \w2_ -> do-   _ <- hClose_help w2_-   withHandle_' "hDuplicateTo" h1 w1 $ \w1_ -> do-     dupHandleTo path h1 Nothing w2_ w1_ (Just handleFinalizer)- withHandle__' "hDuplicateTo" h2 r2  $ \r2_ -> do-   _ <- hClose_help r2_-   withHandle_' "hDuplicateTo" h1 r1 $ \r1_ -> do-     dupHandleTo path h1 (Just w1) r2_ r1_ Nothing-hDuplicateTo h1 _ =-  ioe_dupHandlesNotCompatible h1---ioe_dupHandlesNotCompatible :: Handle -> IO a-ioe_dupHandlesNotCompatible h =-   ioException (IOError (Just h) IllegalOperation "hDuplicateTo"-                "handles are incompatible" Nothing Nothing)--dupHandleTo :: FilePath-            -> Handle-            -> Maybe (MVar Handle__)-            -> Handle__-            -> Handle__-            -> Maybe HandleFinalizer-            -> IO Handle__-dupHandleTo filepath h other_side-            hto_@Handle__{haDevice=devTo,..}-            h_@Handle__{haDevice=dev} mb_finalizer = do-  flushBuffer h_-  case cast devTo of-    Nothing   -> ioe_dupHandlesNotCompatible h-    Just dev' -> do-      _ <- IODevice.dup2 dev dev'-      FileHandle _ m <- dupHandle_ dev' filepath other_side h_ mb_finalizer-      takeMVar m---- ------------------------------------------------------------------------------ showing Handles.------ | 'hShow' is in the 'IO' monad, and gives more comprehensive output--- than the (pure) instance of 'Show' for 'Handle'.--hShow :: Handle -> IO String-hShow h@(FileHandle path _) = showHandle' path False h-hShow h@(DuplexHandle path _ _) = showHandle' path True h--showHandle' :: String -> Bool -> Handle -> IO String-showHandle' filepath is_duplex h =-  withHandle_ "showHandle" h $ \hdl_ ->-    let-     showType | is_duplex = showString "duplex (read-write)"-              | otherwise = shows (haType hdl_)-    in-    return-      (( showChar '{' .-        showHdl (haType hdl_)-            (showString "loc=" . showString filepath . showChar ',' .-             showString "type=" . showType . showChar ',' .-             showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haCharBuffer hdl_))) (haBufferMode hdl_) . showString "}" )-      ) "")-   where--    showHdl :: HandleType -> ShowS -> ShowS-    showHdl ht cont =-       case ht of-        ClosedHandle  -> shows ht . showString "}"-        _ -> cont--    showBufMode :: Buffer e -> BufferMode -> ShowS-    showBufMode buf bmo =-      case bmo of-        NoBuffering   -> showString "none"-        LineBuffering -> showString "line"-        BlockBuffering (Just n) -> showString "block " . showParen True (shows n)-        BlockBuffering Nothing  -> showString "block " . showParen True (shows def)-      where-       def :: Int-       def = bufSize buf-
− GHC/IO/Handle.hs-boot
@@ -1,10 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}--module GHC.IO.Handle where--import GHC.IO-import GHC.IO.Handle.Types--hFlush :: Handle -> IO ()-
− GHC/IO/Handle/FD.hs
@@ -1,291 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Handle.FD--- Copyright   :  (c) The University of Glasgow, 1994-2008--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Handle operations implemented by file descriptors (FDs)-----------------------------------------------------------------------------------module GHC.IO.Handle.FD ( -  stdin, stdout, stderr,-  openFile, openBinaryFile, openFileBlocking,-  mkHandleFromFD, fdToHandle, fdToHandle',-  isEOF- ) where--import GHC.Base-import GHC.Show-import Data.Maybe-import Foreign.C.Types-import GHC.MVar-import GHC.IO-import GHC.IO.Encoding-import GHC.IO.Device as IODevice-import GHC.IO.Exception-import GHC.IO.IOMode-import GHC.IO.Handle-import GHC.IO.Handle.Types-import GHC.IO.Handle.Internals-import qualified GHC.IO.FD as FD-import qualified System.Posix.Internals as Posix---- ------------------------------------------------------------------------------ Standard Handles---- Three handles are allocated during program initialisation.  The first--- two manage input or output from the Haskell program's standard input--- or output channel respectively.  The third manages output to the--- standard error channel. These handles are initially open.---- | A handle managing input from the Haskell program's standard input channel.-stdin :: Handle-{-# NOINLINE stdin #-}-stdin = unsafePerformIO $ do-   -- ToDo: acquire lock-   setBinaryMode FD.stdin-   enc <- getLocaleEncoding-   mkHandle FD.stdin "<stdin>" ReadHandle True (Just enc)-                nativeNewlineMode{-translate newlines-}-                (Just stdHandleFinalizer) Nothing---- | A handle managing output to the Haskell program's standard output channel.-stdout :: Handle-{-# NOINLINE stdout #-}-stdout = unsafePerformIO $ do-   -- ToDo: acquire lock-   setBinaryMode FD.stdout-   enc <- getLocaleEncoding-   mkHandle FD.stdout "<stdout>" WriteHandle True (Just enc)-                nativeNewlineMode{-translate newlines-}-                (Just stdHandleFinalizer) Nothing---- | A handle managing output to the Haskell program's standard error channel.-stderr :: Handle-{-# NOINLINE stderr #-}-stderr = unsafePerformIO $ do-    -- ToDo: acquire lock-   setBinaryMode FD.stderr-   enc <- getLocaleEncoding-   mkHandle FD.stderr "<stderr>" WriteHandle False{-stderr is unbuffered-} -                (Just enc)-                nativeNewlineMode{-translate newlines-}-                (Just stdHandleFinalizer) Nothing--stdHandleFinalizer :: FilePath -> MVar Handle__ -> IO ()-stdHandleFinalizer fp m = do-  h_ <- takeMVar m-  flushWriteBuffer h_-  case haType h_ of -      ClosedHandle -> return ()-      _other       -> closeTextCodecs h_-  putMVar m (ioe_finalizedHandle fp)---- We have to put the FDs into binary mode on Windows to avoid the newline--- translation that the CRT IO library does.-setBinaryMode :: FD.FD -> IO ()-#ifdef mingw32_HOST_OS-setBinaryMode fd = do _ <- setmode (FD.fdFD fd) True-                      return ()-#else-setBinaryMode _ = return ()-#endif--#ifdef mingw32_HOST_OS-foreign import ccall unsafe "__hscore_setmode"-  setmode :: CInt -> Bool -> IO CInt-#endif---- ------------------------------------------------------------------------------ isEOF---- | The computation 'isEOF' is identical to 'hIsEOF',--- except that it works only on 'stdin'.--isEOF :: IO Bool-isEOF = hIsEOF stdin---- ------------------------------------------------------------------------------ Opening and Closing Files--addFilePathToIOError :: String -> FilePath -> IOException -> IOException-addFilePathToIOError fun fp ioe-  = ioe{ ioe_location = fun, ioe_filename = Just fp }---- | Computation 'openFile' @file mode@ allocates and returns a new, open--- handle to manage the file @file@.  It manages input if @mode@--- is 'ReadMode', output if @mode@ is 'WriteMode' or 'AppendMode',--- and both input and output if mode is 'ReadWriteMode'.------ If the file does not exist and it is opened for output, it should be--- created as a new file.  If @mode@ is 'WriteMode' and the file--- already exists, then it should be truncated to zero length.--- Some operating systems delete empty files, so there is no guarantee--- that the file will exist following an 'openFile' with @mode@--- 'WriteMode' unless it is subsequently written to successfully.--- The handle is positioned at the end of the file if @mode@ is--- 'AppendMode', and otherwise at the beginning (in which case its--- internal position is 0).--- The initial buffer mode is implementation-dependent.------ This operation may fail with:------  * 'isAlreadyInUseError' if the file is already open and cannot be reopened;------  * 'isDoesNotExistError' if the file does not exist; or------  * 'isPermissionError' if the user does not have permission to open the file.------ Note: if you will be working with files containing binary data, you'll want to--- be using 'openBinaryFile'.-openFile :: FilePath -> IOMode -> IO Handle-openFile fp im = -  catchException-    (openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE True)-    (\e -> ioError (addFilePathToIOError "openFile" fp e))---- | Like 'openFile', but opens the file in ordinary blocking mode.--- This can be useful for opening a FIFO for reading: if we open in--- non-blocking mode then the open will fail if there are no writers,--- whereas a blocking open will block until a writer appears.------ @since 4.4.0.0-openFileBlocking :: FilePath -> IOMode -> IO Handle-openFileBlocking fp im =-  catchException-    (openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE False)-    (\e -> ioError (addFilePathToIOError "openFile" fp e))---- | Like 'openFile', but open the file in binary mode.--- On Windows, reading a file in text mode (which is the default)--- will translate CRLF to LF, and writing will translate LF to CRLF.--- This is usually what you want with text files.  With binary files--- this is undesirable; also, as usual under Microsoft operating systems,--- text mode treats control-Z as EOF.  Binary mode turns off all special--- treatment of end-of-line and end-of-file characters.--- (See also 'hSetBinaryMode'.)--openBinaryFile :: FilePath -> IOMode -> IO Handle-openBinaryFile fp m =-  catchException-    (openFile' fp m True True)-    (\e -> ioError (addFilePathToIOError "openBinaryFile" fp e))--openFile' :: String -> IOMode -> Bool -> Bool -> IO Handle-openFile' filepath iomode binary non_blocking = do-  -- first open the file to get an FD-  (fd, fd_type) <- FD.openFile filepath iomode non_blocking--  mb_codec <- if binary then return Nothing else fmap Just getLocaleEncoding--  -- then use it to make a Handle-  mkHandleFromFD fd fd_type filepath iomode-                   False {- do not *set* non-blocking mode -}-                   mb_codec-            `onException` IODevice.close fd-        -- NB. don't forget to close the FD if mkHandleFromFD fails, otherwise-        -- this FD leaks.-        -- ASSERT: if we just created the file, then fdToHandle' won't fail-        -- (so we don't need to worry about removing the newly created file-        --  in the event of an error).----- ------------------------------------------------------------------------------ Converting file descriptors to Handles--mkHandleFromFD-   :: FD.FD-   -> IODeviceType-   -> FilePath  -- a string describing this file descriptor (e.g. the filename)-   -> IOMode-   -> Bool      --  *set* non-blocking mode on the FD-   -> Maybe TextEncoding-   -> IO Handle--mkHandleFromFD fd0 fd_type filepath iomode set_non_blocking mb_codec-  = do-#ifndef mingw32_HOST_OS-    -- turn on non-blocking mode-    fd <- if set_non_blocking -             then FD.setNonBlockingMode fd0 True-             else return fd0-#else-    let _ = set_non_blocking -- warning suppression-    fd <- return fd0-#endif--    let nl | isJust mb_codec = nativeNewlineMode-           | otherwise       = noNewlineTranslation--    case fd_type of-        Directory -> -           ioException (IOError Nothing InappropriateType "openFile"-                           "is a directory" Nothing Nothing)--        Stream-           -- only *Streams* can be DuplexHandles.  Other read/write-           -- Handles must share a buffer.-           | ReadWriteMode <- iomode -> -                mkDuplexHandle fd filepath mb_codec nl-                   --        _other -> -           mkFileHandle fd filepath iomode mb_codec nl---- | Old API kept to avoid breaking clients-fdToHandle' :: CInt-            -> Maybe IODeviceType-            -> Bool -- is_socket on Win, non-blocking on Unix-            -> FilePath-            -> IOMode-            -> Bool -- binary-            -> IO Handle-fdToHandle' fdint mb_type is_socket filepath iomode binary = do-  let mb_stat = case mb_type of-                        Nothing          -> Nothing-                          -- mkFD will do the stat:-                        Just RegularFile -> Nothing-                          -- no stat required for streams etc.:-                        Just other       -> Just (other,0,0)-  (fd,fd_type) <- FD.mkFD fdint iomode mb_stat-                       is_socket-                       is_socket-  enc <- if binary then return Nothing else fmap Just getLocaleEncoding-  mkHandleFromFD fd fd_type filepath iomode is_socket enc----- | Turn an existing file descriptor into a Handle.  This is used by--- various external libraries to make Handles.------ Makes a binary Handle.  This is for historical reasons; it should--- probably be a text Handle with the default encoding and newline--- translation instead.-fdToHandle :: Posix.FD -> IO Handle-fdToHandle fdint = do-   iomode <- Posix.fdGetMode fdint-   (fd,fd_type) <- FD.mkFD fdint iomode Nothing-            False{-is_socket-} -              -- NB. the is_socket flag is False, meaning that:-              --  on Windows we're guessing this is not a socket (XXX)-            False{-is_nonblock-}-              -- file descriptors that we get from external sources are-              -- not put into non-blocking mode, because that would affect-              -- other users of the file descriptor-   let fd_str = "<file descriptor: " ++ show fd ++ ">"-   mkHandleFromFD fd fd_type fd_str iomode False{-non-block-} -                  Nothing -- bin mode---- ------------------------------------------------------------------------------ Are files opened by default in text or binary mode, if the user doesn't--- specify?--dEFAULT_OPEN_IN_BINARY_MODE :: Bool-dEFAULT_OPEN_IN_BINARY_MODE = False
− GHC/IO/Handle/FD.hs-boot
@@ -1,10 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}--module GHC.IO.Handle.FD where--import GHC.IO.Handle.Types---- used in GHC.Conc, which is below GHC.IO.Handle.FD-stdout :: Handle-
− GHC/IO/Handle/Internals.hs
@@ -1,941 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude-           , RecordWildCards-           , BangPatterns-           , NondecreasingIndentation-           , RankNTypes-  #-}-{-# OPTIONS_GHC -fno-warn-unused-matches #-}-{-# OPTIONS_GHC -fno-warn-name-shadowing #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Handle.Internals--- Copyright   :  (c) The University of Glasgow, 1994-2001--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ This module defines the basic operations on I\/O \"handles\".  All--- of the operations defined here are independent of the underlying--- device.-----------------------------------------------------------------------------------module GHC.IO.Handle.Internals (-  withHandle, withHandle', withHandle_,-  withHandle__', withHandle_', withAllHandles__,-  wantWritableHandle, wantReadableHandle, wantReadableHandle_,-  wantSeekableHandle,--  mkHandle, mkFileHandle, mkDuplexHandle,-  openTextEncoding, closeTextCodecs, initBufferState,-  dEFAULT_CHAR_BUFFER_SIZE,--  flushBuffer, flushWriteBuffer, flushCharReadBuffer,-  flushCharBuffer, flushByteReadBuffer, flushByteWriteBuffer,--  readTextDevice, writeCharBuffer, readTextDeviceNonBlocking,-  decodeByteBuf,--  augmentIOError,-  ioe_closedHandle, ioe_EOF, ioe_notReadable, ioe_notWritable,-  ioe_finalizedHandle, ioe_bufsiz,--  hClose_help, hLookAhead_,--  HandleFinalizer, handleFinalizer,--  debugIO,- ) where--import GHC.IO-import GHC.IO.IOMode-import GHC.IO.Encoding as Encoding-import GHC.IO.Encoding.Types (CodeBuffer)-import GHC.IO.Handle.Types-import GHC.IO.Buffer-import GHC.IO.BufferedIO (BufferedIO)-import GHC.IO.Exception-import GHC.IO.Device (IODevice, SeekMode(..))-import qualified GHC.IO.Device as IODevice-import qualified GHC.IO.BufferedIO as Buffered--import GHC.Conc.Sync-import GHC.Real-import GHC.Base-import GHC.Exception-import GHC.Num          ( Num(..) )-import GHC.Show-import GHC.IORef-import GHC.MVar-import Data.Typeable-import Data.Maybe-import Foreign-import System.Posix.Internals hiding (FD)--import Foreign.C--c_DEBUG_DUMP :: Bool-c_DEBUG_DUMP = False---- ------------------------------------------------------------------------------ Creating a new handle--type HandleFinalizer = FilePath -> MVar Handle__ -> IO ()--newFileHandle :: FilePath -> Maybe HandleFinalizer -> Handle__ -> IO Handle-newFileHandle filepath mb_finalizer hc = do-  m <- newMVar hc-  case mb_finalizer of-    Just finalizer -> addMVarFinalizer m (finalizer filepath m)-    Nothing        -> return ()-  return (FileHandle filepath m)---- ------------------------------------------------------------------------------ Working with Handles--{--In the concurrent world, handles are locked during use.  This is done-by wrapping an MVar around the handle which acts as a mutex over-operations on the handle.--To avoid races, we use the following bracketing operations.  The idea-is to obtain the lock, do some operation and replace the lock again,-whether the operation succeeded or failed.  We also want to handle the-case where the thread receives an exception while processing the IO-operation: in these cases we also want to relinquish the lock.--There are three versions of @withHandle@: corresponding to the three-possible combinations of:--        - the operation may side-effect the handle-        - the operation may return a result--If the operation generates an error or an exception is raised, the-original handle is always replaced.--}--{-# INLINE withHandle #-}-withHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a-withHandle fun h@(FileHandle _ m)     act = withHandle' fun h m act-withHandle fun h@(DuplexHandle _ m _) act = withHandle' fun h m act--withHandle' :: String -> Handle -> MVar Handle__-   -> (Handle__ -> IO (Handle__,a)) -> IO a-withHandle' fun h m act =- mask_ $ do-   (h',v)  <- do_operation fun h act m-   checkHandleInvariants h'-   putMVar m h'-   return v--{-# INLINE withHandle_ #-}-withHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a-withHandle_ fun h@(FileHandle _ m)     act = withHandle_' fun h m act-withHandle_ fun h@(DuplexHandle _ m _) act = withHandle_' fun h m act--withHandle_' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a-withHandle_' fun h m act = withHandle' fun h m $ \h_ -> do-                              a <- act h_-                              return (h_,a)--withAllHandles__ :: String -> Handle -> (Handle__ -> IO Handle__) -> IO ()-withAllHandles__ fun h@(FileHandle _ m)     act = withHandle__' fun h m act-withAllHandles__ fun h@(DuplexHandle _ r w) act = do-  withHandle__' fun h r act-  withHandle__' fun h w act--withHandle__' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO Handle__)-              -> IO ()-withHandle__' fun h m act =- mask_ $ do-   h'  <- do_operation fun h act m-   checkHandleInvariants h'-   putMVar m h'-   return ()--do_operation :: String -> Handle -> (Handle__ -> IO a) -> MVar Handle__ -> IO a-do_operation fun h act m = do-  h_ <- takeMVar m-  checkHandleInvariants h_-  act h_ `catchException` handler h_-  where-    handler h_ e = do-      putMVar m h_-      case () of-        _ | Just ioe <- fromException e ->-            ioError (augmentIOError ioe fun h)-        _ | Just async_ex <- fromException e -> do -- see Note [async]-            let _ = async_ex :: SomeAsyncException-            t <- myThreadId-            throwTo t e-            do_operation fun h act m-        _otherwise ->-            throwIO e---- Note [async]------ If an asynchronous exception is raised during an I/O operation,--- normally it is fine to just re-throw the exception synchronously.--- However, if we are inside an unsafePerformIO or an--- unsafeInterleaveIO, this would replace the enclosing thunk with the--- exception raised, which is wrong (#3997).  We have to release the--- lock on the Handle, but what do we replace the thunk with?  What--- should happen when the thunk is subsequently demanded again?------ The only sensible choice we have is to re-do the IO operation on--- resumption, but then we have to be careful in the IO library that--- this is always safe to do.  In particular we should------    never perform any side-effects before an interruptible operation------ because the interruptible operation may raise an asynchronous--- exception, which may cause the operation and its side effects to be--- subsequently performed again.------ Re-doing the IO operation is achieved by:---   - using throwTo to re-throw the asynchronous exception asynchronously---     in the current thread---   - on resumption, it will be as if throwTo returns.  In that case, we---     recursively invoke the original operation (see do_operation above).------ Interruptible operations in the I/O library are:---    - threadWaitRead/threadWaitWrite---    - fillReadBuffer/flushWriteBuffer---    - readTextDevice/writeTextDevice--augmentIOError :: IOException -> String -> Handle -> IOException-augmentIOError ioe@IOError{ ioe_filename = fp } fun h-  = ioe { ioe_handle = Just h, ioe_location = fun, ioe_filename = filepath }-  where filepath-          | Just _ <- fp = fp-          | otherwise = case h of-                          FileHandle path _     -> Just path-                          DuplexHandle path _ _ -> Just path---- ------------------------------------------------------------------------------ Wrapper for write operations.--wantWritableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a-wantWritableHandle fun h@(FileHandle _ m) act-  = wantWritableHandle' fun h m act-wantWritableHandle fun h@(DuplexHandle _ _ m) act-  = wantWritableHandle' fun h m act-    -- we know it's not a ReadHandle or ReadWriteHandle, but we have to-    -- check for ClosedHandle/SemiClosedHandle. (#4808)--wantWritableHandle'-        :: String -> Handle -> MVar Handle__-        -> (Handle__ -> IO a) -> IO a-wantWritableHandle' fun h m act-   = withHandle_' fun h m (checkWritableHandle act)--checkWritableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a-checkWritableHandle act h_@Handle__{..}-  = case haType of-      ClosedHandle         -> ioe_closedHandle-      SemiClosedHandle     -> ioe_closedHandle-      ReadHandle           -> ioe_notWritable-      ReadWriteHandle      -> do-        buf <- readIORef haCharBuffer-        when (not (isWriteBuffer buf)) $ do-           flushCharReadBuffer h_-           flushByteReadBuffer h_-           buf <- readIORef haCharBuffer-           writeIORef haCharBuffer buf{ bufState = WriteBuffer }-           buf <- readIORef haByteBuffer-           buf' <- Buffered.emptyWriteBuffer haDevice buf-           writeIORef haByteBuffer buf'-        act h_-      _other               -> act h_---- ------------------------------------------------------------------------------ Wrapper for read operations.--wantReadableHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a-wantReadableHandle fun h act = withHandle fun h (checkReadableHandle act)--wantReadableHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a-wantReadableHandle_ fun h@(FileHandle  _ m)   act-  = wantReadableHandle' fun h m act-wantReadableHandle_ fun h@(DuplexHandle _ m _) act-  = wantReadableHandle' fun h m act-    -- we know it's not a WriteHandle or ReadWriteHandle, but we have to-    -- check for ClosedHandle/SemiClosedHandle. (#4808)--wantReadableHandle'-        :: String -> Handle -> MVar Handle__-        -> (Handle__ -> IO a) -> IO a-wantReadableHandle' fun h m act-  = withHandle_' fun h m (checkReadableHandle act)--checkReadableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a-checkReadableHandle act h_@Handle__{..} =-    case haType of-      ClosedHandle         -> ioe_closedHandle-      SemiClosedHandle     -> ioe_closedHandle-      AppendHandle         -> ioe_notReadable-      WriteHandle          -> ioe_notReadable-      ReadWriteHandle      -> do-          -- a read/write handle and we want to read from it.  We must-          -- flush all buffered write data first.-          bbuf <- readIORef haByteBuffer-          when (isWriteBuffer bbuf) $ do-             when (not (isEmptyBuffer bbuf)) $ flushByteWriteBuffer h_-             cbuf' <- readIORef haCharBuffer-             writeIORef haCharBuffer cbuf'{ bufState = ReadBuffer }-             bbuf <- readIORef haByteBuffer-             writeIORef haByteBuffer bbuf{ bufState = ReadBuffer }-          act h_-      _other               -> act h_---- ------------------------------------------------------------------------------ Wrapper for seek operations.--wantSeekableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a-wantSeekableHandle fun h@(DuplexHandle _ _ _) _act =-  ioException (IOError (Just h) IllegalOperation fun-                   "handle is not seekable" Nothing Nothing)-wantSeekableHandle fun h@(FileHandle _ m) act =-  withHandle_' fun h m (checkSeekableHandle act)--checkSeekableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a-checkSeekableHandle act handle_@Handle__{haDevice=dev} =-    case haType handle_ of-      ClosedHandle      -> ioe_closedHandle-      SemiClosedHandle  -> ioe_closedHandle-      AppendHandle      -> ioe_notSeekable-      _ -> do b <- IODevice.isSeekable dev-              if b then act handle_-                   else ioe_notSeekable---- -------------------------------------------------------------------------------- Handy IOErrors--ioe_closedHandle, ioe_EOF,-  ioe_notReadable, ioe_notWritable, ioe_cannotFlushNotSeekable,-  ioe_notSeekable :: IO a--ioe_closedHandle = ioException-   (IOError Nothing IllegalOperation ""-        "handle is closed" Nothing Nothing)-ioe_EOF = ioException-   (IOError Nothing EOF "" "" Nothing Nothing)-ioe_notReadable = ioException-   (IOError Nothing IllegalOperation ""-        "handle is not open for reading" Nothing Nothing)-ioe_notWritable = ioException-   (IOError Nothing IllegalOperation ""-        "handle is not open for writing" Nothing Nothing)-ioe_notSeekable = ioException-   (IOError Nothing IllegalOperation ""-        "handle is not seekable" Nothing Nothing)-ioe_cannotFlushNotSeekable = ioException-   (IOError Nothing IllegalOperation ""-      "cannot flush the read buffer: underlying device is not seekable"-        Nothing Nothing)--ioe_finalizedHandle :: FilePath -> Handle__-ioe_finalizedHandle fp = throw-   (IOError Nothing IllegalOperation ""-        "handle is finalized" Nothing (Just fp))--ioe_bufsiz :: Int -> IO a-ioe_bufsiz n = ioException-   (IOError Nothing InvalidArgument "hSetBuffering"-        ("illegal buffer size " ++ showsPrec 9 n []) Nothing Nothing)-                                -- 9 => should be parens'ified.---- ------------------------------------------------------------------------------ Wrapper for Handle encoding/decoding.---- The interface for TextEncoding changed so that a TextEncoding doesn't raise--- an exception if it encounters an invalid sequnce. Furthermore, encoding--- returns a reason as to why encoding stopped, letting us know if it was due--- to input/output underflow or an invalid sequence.------ This code adapts this elaborated interface back to the original TextEncoding--- interface.------ FIXME: it is possible that Handle code using the haDecoder/haEncoder fields--- could be made clearer by using the 'encode' interface directly. I have not--- looked into this.--streamEncode :: BufferCodec from to state-             -> Buffer from -> Buffer to-             -> IO (Buffer from, Buffer to)-streamEncode codec from to = fmap (\(_, from', to') -> (from', to')) $ recoveringEncode codec from to---- | Just like 'encode', but interleaves calls to 'encode' with calls to 'recover' in order to make as much progress as possible-recoveringEncode :: BufferCodec from to state -> CodeBuffer from to-recoveringEncode codec from to = go from to-  where-    go from to = do-      (why, from', to') <- encode codec from to-      -- When we are dealing with Handles, we don't care about input/output-      -- underflow particularly, and we want to delay errors about invalid-      -- sequences as far as possible.-      case why of-        InvalidSequence | bufL from == bufL from' -> do-          -- NB: it is OK to call recover here. Because we saw InvalidSequence, by the invariants-          -- on "encode" it must be the case that there is at least one elements available in the output-          -- buffer. Furthermore, clearly there is at least one element in the input buffer since we found-          -- something invalid there!-          (from', to') <- recover codec from' to'-          go from' to'-        _ -> return (why, from', to')---- -------------------------------------------------------------------------------- Handle Finalizers---- For a duplex handle, we arrange that the read side points to the write side--- (and hence keeps it alive if the read side is alive).  This is done by--- having the haOtherSide field of the read side point to the read side.--- The finalizer is then placed on the write side, and the handle only gets--- finalized once, when both sides are no longer required.---- NOTE about finalized handles: It's possible that a handle can be--- finalized and then we try to use it later, for example if the--- handle is referenced from another finalizer, or from a thread that--- has become unreferenced and then resurrected (arguably in the--- latter case we shouldn't finalize the Handle...).  Anyway,--- we try to emit a helpful message which is better than nothing.------ [later; 8/2010] However, a program like this can yield a strange--- error message:------   main = writeFile "out" loop---   loop = let x = x in x------ because the main thread and the Handle are both unreachable at the--- same time, the Handle may get finalized before the main thread--- receives the NonTermination exception, and the exception handler--- will then report an error.  We'd rather this was not an error and--- the program just prints "<<loop>>".--handleFinalizer :: FilePath -> MVar Handle__ -> IO ()-handleFinalizer fp m = do-  handle_ <- takeMVar m-  (handle_', _) <- hClose_help handle_-  putMVar m handle_'-  return ()---- ------------------------------------------------------------------------------ Allocating buffers---- using an 8k char buffer instead of 32k improved performance for a--- basic "cat" program by ~30% for me.  --SDM-dEFAULT_CHAR_BUFFER_SIZE :: Int-dEFAULT_CHAR_BUFFER_SIZE = 2048 -- 8k/sizeof(HsChar)--getCharBuffer :: IODevice dev => dev -> BufferState-              -> IO (IORef CharBuffer, BufferMode)-getCharBuffer dev state = do-  buffer <- newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state-  ioref  <- newIORef buffer-  is_tty <- IODevice.isTerminal dev--  let buffer_mode-         | is_tty    = LineBuffering-         | otherwise = BlockBuffering Nothing--  return (ioref, buffer_mode)--mkUnBuffer :: BufferState -> IO (IORef CharBuffer, BufferMode)-mkUnBuffer state = do-  buffer <- newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state-              --  See [note Buffer Sizing], GHC.IO.Handle.Types-  ref <- newIORef buffer-  return (ref, NoBuffering)---- -------------------------------------------------------------------------------- Flushing buffers---- | syncs the file with the buffer, including moving the--- file pointer backwards in the case of a read buffer.  This can fail--- on a non-seekable read Handle.-flushBuffer :: Handle__ -> IO ()-flushBuffer h_@Handle__{..} = do-  buf <- readIORef haCharBuffer-  case bufState buf of-    ReadBuffer  -> do-        flushCharReadBuffer h_-        flushByteReadBuffer h_-    WriteBuffer -> do-        flushByteWriteBuffer h_---- | flushes the Char buffer only.  Works on all Handles.-flushCharBuffer :: Handle__ -> IO ()-flushCharBuffer h_@Handle__{..} = do-  cbuf <- readIORef haCharBuffer-  case bufState cbuf of-    ReadBuffer  -> do-        flushCharReadBuffer h_-    WriteBuffer ->-        when (not (isEmptyBuffer cbuf)) $-           error "internal IO library error: Char buffer non-empty"---- -------------------------------------------------------------------------------- Writing data (flushing write buffers)---- flushWriteBuffer flushes the buffer iff it contains pending write--- data.  Flushes both the Char and the byte buffer, leaving both--- empty.-flushWriteBuffer :: Handle__ -> IO ()-flushWriteBuffer h_@Handle__{..} = do-  buf <- readIORef haByteBuffer-  when (isWriteBuffer buf) $ flushByteWriteBuffer h_--flushByteWriteBuffer :: Handle__ -> IO ()-flushByteWriteBuffer h_@Handle__{..} = do-  bbuf <- readIORef haByteBuffer-  when (not (isEmptyBuffer bbuf)) $ do-    bbuf' <- Buffered.flushWriteBuffer haDevice bbuf-    writeIORef haByteBuffer bbuf'---- write the contents of the CharBuffer to the Handle__.--- The data will be encoded and pushed to the byte buffer,--- flushing if the buffer becomes full.-writeCharBuffer :: Handle__ -> CharBuffer -> IO ()-writeCharBuffer h_@Handle__{..} !cbuf = do-  ---  bbuf <- readIORef haByteBuffer--  debugIO ("writeCharBuffer: cbuf=" ++ summaryBuffer cbuf ++-        " bbuf=" ++ summaryBuffer bbuf)--  (cbuf',bbuf') <- case haEncoder of-    Nothing      -> latin1_encode cbuf bbuf-    Just encoder -> (streamEncode encoder) cbuf bbuf--  debugIO ("writeCharBuffer after encoding: cbuf=" ++ summaryBuffer cbuf' ++-        " bbuf=" ++ summaryBuffer bbuf')--          -- flush if the write buffer is full-  if isFullBuffer bbuf'-          --  or we made no progress-     || not (isEmptyBuffer cbuf') && bufL cbuf' == bufL cbuf-          -- or the byte buffer has more elements than the user wanted buffered-     || (case haBufferMode of-          BlockBuffering (Just s) -> bufferElems bbuf' >= s-          NoBuffering -> True-          _other -> False)-    then do-      bbuf'' <- Buffered.flushWriteBuffer haDevice bbuf'-      writeIORef haByteBuffer bbuf''-    else-      writeIORef haByteBuffer bbuf'--  if not (isEmptyBuffer cbuf')-     then writeCharBuffer h_ cbuf'-     else return ()---- -------------------------------------------------------------------------------- Flushing read buffers---- It is always possible to flush the Char buffer back to the byte buffer.-flushCharReadBuffer :: Handle__ -> IO ()-flushCharReadBuffer Handle__{..} = do-  cbuf <- readIORef haCharBuffer-  if isWriteBuffer cbuf || isEmptyBuffer cbuf then return () else do--  -- haLastDecode is the byte buffer just before we did our last batch of-  -- decoding.  We're going to re-decode the bytes up to the current char,-  -- to find out where we should revert the byte buffer to.-  (codec_state, bbuf0) <- readIORef haLastDecode--  cbuf0 <- readIORef haCharBuffer-  writeIORef haCharBuffer cbuf0{ bufL=0, bufR=0 }--  -- if we haven't used any characters from the char buffer, then just-  -- re-install the old byte buffer.-  if bufL cbuf0 == 0-     then do writeIORef haByteBuffer bbuf0-             return ()-     else do--  case haDecoder of-    Nothing -> do-      writeIORef haByteBuffer bbuf0 { bufL = bufL bbuf0 + bufL cbuf0 }-      -- no decoder: the number of bytes to decode is the same as the-      -- number of chars we have used up.--    Just decoder -> do-      debugIO ("flushCharReadBuffer re-decode, bbuf=" ++ summaryBuffer bbuf0 ++-               " cbuf=" ++ summaryBuffer cbuf0)--      -- restore the codec state-      setState decoder codec_state--      (bbuf1,cbuf1) <- (streamEncode decoder) bbuf0-                               cbuf0{ bufL=0, bufR=0, bufSize = bufL cbuf0 }--      debugIO ("finished, bbuf=" ++ summaryBuffer bbuf1 ++-               " cbuf=" ++ summaryBuffer cbuf1)--      writeIORef haByteBuffer bbuf1----- When flushing the byte read buffer, we seek backwards by the number--- of characters in the buffer.  The file descriptor must therefore be--- seekable: attempting to flush the read buffer on an unseekable--- handle is not allowed.--flushByteReadBuffer :: Handle__ -> IO ()-flushByteReadBuffer h_@Handle__{..} = do-  bbuf <- readIORef haByteBuffer--  if isEmptyBuffer bbuf then return () else do--  seekable <- IODevice.isSeekable haDevice-  when (not seekable) $ ioe_cannotFlushNotSeekable--  let seek = negate (bufR bbuf - bufL bbuf)--  debugIO ("flushByteReadBuffer: new file offset = " ++ show seek)-  IODevice.seek haDevice RelativeSeek (fromIntegral seek)--  writeIORef haByteBuffer bbuf{ bufL=0, bufR=0 }---- ------------------------------------------------------------------------------- Making Handles--mkHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev-            -> FilePath-            -> HandleType-            -> Bool                     -- buffered?-            -> Maybe TextEncoding-            -> NewlineMode-            -> Maybe HandleFinalizer-            -> Maybe (MVar Handle__)-            -> IO Handle--mkHandle dev filepath ha_type buffered mb_codec nl finalizer other_side = do-   openTextEncoding mb_codec ha_type $ \ mb_encoder mb_decoder -> do--   let buf_state = initBufferState ha_type-   bbuf <- Buffered.newBuffer dev buf_state-   bbufref <- newIORef bbuf-   last_decode <- newIORef (error "codec_state", bbuf)--   (cbufref,bmode) <--         if buffered then getCharBuffer dev buf_state-                     else mkUnBuffer buf_state--   spares <- newIORef BufferListNil-   newFileHandle filepath finalizer-            (Handle__ { haDevice = dev,-                        haType = ha_type,-                        haBufferMode = bmode,-                        haByteBuffer = bbufref,-                        haLastDecode = last_decode,-                        haCharBuffer = cbufref,-                        haBuffers = spares,-                        haEncoder = mb_encoder,-                        haDecoder = mb_decoder,-                        haCodec = mb_codec,-                        haInputNL = inputNL nl,-                        haOutputNL = outputNL nl,-                        haOtherSide = other_side-                      })---- | makes a new 'Handle'-mkFileHandle :: (IODevice dev, BufferedIO dev, Typeable dev)-             => dev -- ^ the underlying IO device, which must support-                    -- 'IODevice', 'BufferedIO' and 'Typeable'-             -> FilePath-                    -- ^ a string describing the 'Handle', e.g. the file-                    -- path for a file.  Used in error messages.-             -> IOMode-                    -- The mode in which the 'Handle' is to be used-             -> Maybe TextEncoding-                    -- Create the 'Handle' with no text encoding?-             -> NewlineMode-                    -- Translate newlines?-             -> IO Handle-mkFileHandle dev filepath iomode mb_codec tr_newlines = do-   mkHandle dev filepath (ioModeToHandleType iomode) True{-buffered-} mb_codec-            tr_newlines-            (Just handleFinalizer) Nothing{-other_side-}---- | like 'mkFileHandle', except that a 'Handle' is created with two--- independent buffers, one for reading and one for writing.  Used for--- full-duplex streams, such as network sockets.-mkDuplexHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev-               -> FilePath -> Maybe TextEncoding -> NewlineMode -> IO Handle-mkDuplexHandle dev filepath mb_codec tr_newlines = do--  write_side@(FileHandle _ write_m) <--       mkHandle dev filepath WriteHandle True mb_codec-                        tr_newlines-                        (Just handleFinalizer)-                        Nothing -- no othersie--  read_side@(FileHandle _ read_m) <--      mkHandle dev filepath ReadHandle True mb_codec-                        tr_newlines-                        Nothing -- no finalizer-                        (Just write_m)--  return (DuplexHandle filepath read_m write_m)--ioModeToHandleType :: IOMode -> HandleType-ioModeToHandleType ReadMode      = ReadHandle-ioModeToHandleType WriteMode     = WriteHandle-ioModeToHandleType ReadWriteMode = ReadWriteHandle-ioModeToHandleType AppendMode    = AppendHandle--initBufferState :: HandleType -> BufferState-initBufferState ReadHandle = ReadBuffer-initBufferState _          = WriteBuffer--openTextEncoding-   :: Maybe TextEncoding-   -> HandleType-   -> (forall es ds . Maybe (TextEncoder es) -> Maybe (TextDecoder ds) -> IO a)-   -> IO a--openTextEncoding Nothing   ha_type cont = cont Nothing Nothing-openTextEncoding (Just TextEncoding{..}) ha_type cont = do-    mb_decoder <- if isReadableHandleType ha_type then do-                     decoder <- mkTextDecoder-                     return (Just decoder)-                  else-                     return Nothing-    mb_encoder <- if isWritableHandleType ha_type then do-                     encoder <- mkTextEncoder-                     return (Just encoder)-                  else-                     return Nothing-    cont mb_encoder mb_decoder--closeTextCodecs :: Handle__ -> IO ()-closeTextCodecs Handle__{..} = do-  case haDecoder of Nothing -> return (); Just d -> Encoding.close d-  case haEncoder of Nothing -> return (); Just d -> Encoding.close d---- ------------------------------------------------------------------------------ closing Handles---- hClose_help is also called by lazyRead (in GHC.IO.Handle.Text) when--- EOF is read or an IO error occurs on a lazy stream.  The--- semi-closed Handle is then closed immediately.  We have to be--- careful with DuplexHandles though: we have to leave the closing to--- the finalizer in that case, because the write side may still be in--- use.-hClose_help :: Handle__ -> IO (Handle__, Maybe SomeException)-hClose_help handle_ =-  case haType handle_ of-      ClosedHandle -> return (handle_,Nothing)-      _ -> do mb_exc1 <- trymaybe $ flushWriteBuffer handle_ -- interruptible-                    -- it is important that hClose doesn't fail and-                    -- leave the Handle open (#3128), so we catch-                    -- exceptions when flushing the buffer.-              (h_, mb_exc2) <- hClose_handle_ handle_-              return (h_, if isJust mb_exc1 then mb_exc1 else mb_exc2)---trymaybe :: IO () -> IO (Maybe SomeException)-trymaybe io = (do io; return Nothing) `catchException` \e -> return (Just e)--hClose_handle_ :: Handle__ -> IO (Handle__, Maybe SomeException)-hClose_handle_ h_@Handle__{..} = do--    -- close the file descriptor, but not when this is the read-    -- side of a duplex handle.-    -- If an exception is raised by the close(), we want to continue-    -- to close the handle and release the lock if it has one, then-    -- we return the exception to the caller of hClose_help which can-    -- raise it if necessary.-    maybe_exception <--      case haOtherSide of-        Nothing -> trymaybe $ IODevice.close haDevice-        Just _  -> return Nothing--    -- free the spare buffers-    writeIORef haBuffers BufferListNil-    writeIORef haCharBuffer noCharBuffer-    writeIORef haByteBuffer noByteBuffer--    -- release our encoder/decoder-    closeTextCodecs h_--    -- we must set the fd to -1, because the finalizer is going-    -- to run eventually and try to close/unlock it.-    -- ToDo: necessary?  the handle will be marked ClosedHandle-    -- XXX GHC won't let us use record update here, hence wildcards-    return (Handle__{ haType = ClosedHandle, .. }, maybe_exception)--{-# NOINLINE noCharBuffer #-}-noCharBuffer :: CharBuffer-noCharBuffer = unsafePerformIO $ newCharBuffer 1 ReadBuffer--{-# NOINLINE noByteBuffer #-}-noByteBuffer :: Buffer Word8-noByteBuffer = unsafePerformIO $ newByteBuffer 1 ReadBuffer---- ------------------------------------------------------------------------------ Looking ahead--hLookAhead_ :: Handle__ -> IO Char-hLookAhead_ handle_@Handle__{..} = do-    buf <- readIORef haCharBuffer--    -- fill up the read buffer if necessary-    new_buf <- if isEmptyBuffer buf-                  then readTextDevice handle_ buf-                  else return buf-    writeIORef haCharBuffer new_buf--    peekCharBuf (bufRaw buf) (bufL buf)---- ------------------------------------------------------------------------------ debugging--debugIO :: String -> IO ()-debugIO s- | c_DEBUG_DUMP-    = do _ <- withCStringLen (s ++ "\n") $-                  \(p, len) -> c_write 1 (castPtr p) (fromIntegral len)-         return ()- | otherwise = return ()---- ------------------------------------------------------------------------------- Text input/output---- Read characters into the provided buffer.  Return when any--- characters are available; raise an exception if the end of--- file is reached.------ In uses of readTextDevice within base, the input buffer is either:---   * empty---   * or contains a single \r (when doing newline translation)------ The input character buffer must have a capacity at least 1 greater--- than the number of elements it currently contains.------ Users of this function expect that the buffer returned contains--- at least 1 more character than the input buffer.-readTextDevice :: Handle__ -> CharBuffer -> IO CharBuffer-readTextDevice h_@Handle__{..} cbuf = do-  ---  bbuf0 <- readIORef haByteBuffer--  debugIO ("readTextDevice: cbuf=" ++ summaryBuffer cbuf ++-        " bbuf=" ++ summaryBuffer bbuf0)--  bbuf1 <- if not (isEmptyBuffer bbuf0)-              then return bbuf0-              else do-                   (r,bbuf1) <- Buffered.fillReadBuffer haDevice bbuf0-                   if r == 0 then ioe_EOF else do  -- raise EOF-                   return bbuf1--  debugIO ("readTextDevice after reading: bbuf=" ++ summaryBuffer bbuf1)--  (bbuf2,cbuf') <--      case haDecoder of-          Nothing      -> do-               writeIORef haLastDecode (error "codec_state", bbuf1)-               latin1_decode bbuf1 cbuf-          Just decoder -> do-               state <- getState decoder-               writeIORef haLastDecode (state, bbuf1)-               (streamEncode decoder) bbuf1 cbuf--  debugIO ("readTextDevice after decoding: cbuf=" ++ summaryBuffer cbuf' ++-        " bbuf=" ++ summaryBuffer bbuf2)--  -- We can't return from readTextDevice without reading at least a single extra character,-  -- so check that we have managed to achieve that-  writeIORef haByteBuffer bbuf2-  if bufR cbuf' == bufR cbuf-     -- we need more bytes to make a Char. NB: bbuf2 may be empty (even though bbuf1 wasn't) when we-     -- are using an encoding that can skip bytes without outputting characters, such as UTF8//IGNORE-     then readTextDevice' h_ bbuf2 cbuf-     else return cbuf'---- we have an incomplete byte sequence at the end of the buffer: try to--- read more bytes.-readTextDevice' :: Handle__ -> Buffer Word8 -> CharBuffer -> IO CharBuffer-readTextDevice' h_@Handle__{..} bbuf0 cbuf0 = do-  ---  -- copy the partial sequence to the beginning of the buffer, so we have-  -- room to read more bytes.-  bbuf1 <- slideContents bbuf0--  -- readTextDevice only calls us if we got some bytes but not some characters.-  -- This can't occur if haDecoder is Nothing because latin1_decode accepts all bytes.-  let Just decoder = haDecoder--  (r,bbuf2) <- Buffered.fillReadBuffer haDevice bbuf1-  if r == 0-   then do-     -- bbuf2 can be empty here when we encounter an invalid byte sequence at the end of the input-     -- with a //IGNORE codec which consumes bytes without outputting characters-     if isEmptyBuffer bbuf2 then ioe_EOF else do-     (bbuf3, cbuf1) <- recover decoder bbuf2 cbuf0-     debugIO ("readTextDevice' after recovery: bbuf=" ++ summaryBuffer bbuf3 ++ ", cbuf=" ++ summaryBuffer cbuf1)-     writeIORef haByteBuffer bbuf3-     -- We should recursively invoke readTextDevice after recovery,-     -- if recovery did not add at least one new character to the buffer:-     --  1. If we were using IgnoreCodingFailure it might be the case that-     --     cbuf1 is the same length as cbuf0 and we need to raise ioe_EOF-     --  2. If we were using TransliterateCodingFailure we might have *mutated*-     --     the byte buffer without changing the pointers into either buffer.-     --     We need to try and decode it again - it might just go through this time.-     if bufR cbuf1 == bufR cbuf0-      then readTextDevice h_ cbuf1-      else return cbuf1-   else do-    debugIO ("readTextDevice' after reading: bbuf=" ++ summaryBuffer bbuf2)--    (bbuf3,cbuf1) <- do-       state <- getState decoder-       writeIORef haLastDecode (state, bbuf2)-       (streamEncode decoder) bbuf2 cbuf0--    debugIO ("readTextDevice' after decoding: cbuf=" ++ summaryBuffer cbuf1 ++-          " bbuf=" ++ summaryBuffer bbuf3)--    writeIORef haByteBuffer bbuf3-    if bufR cbuf0 == bufR cbuf1-       then readTextDevice' h_ bbuf3 cbuf1-       else return cbuf1---- Read characters into the provided buffer.  Do not block;--- return zero characters instead.  Raises an exception on end-of-file.-readTextDeviceNonBlocking :: Handle__ -> CharBuffer -> IO CharBuffer-readTextDeviceNonBlocking h_@Handle__{..} cbuf = do-  ---  bbuf0 <- readIORef haByteBuffer-  when (isEmptyBuffer bbuf0) $ do-     (r,bbuf1) <- Buffered.fillReadBuffer0 haDevice bbuf0-     if isNothing r then ioe_EOF else do  -- raise EOF-     writeIORef haByteBuffer bbuf1--  decodeByteBuf h_ cbuf---- Decode bytes from the byte buffer into the supplied CharBuffer.-decodeByteBuf :: Handle__ -> CharBuffer -> IO CharBuffer-decodeByteBuf h_@Handle__{..} cbuf = do-  ---  bbuf0 <- readIORef haByteBuffer--  (bbuf2,cbuf') <--      case haDecoder of-          Nothing      -> do-               writeIORef haLastDecode (error "codec_state", bbuf0)-               latin1_decode bbuf0 cbuf-          Just decoder -> do-               state <- getState decoder-               writeIORef haLastDecode (state, bbuf0)-               (streamEncode decoder) bbuf0 cbuf--  writeIORef haByteBuffer bbuf2-  return cbuf'-
− GHC/IO/Handle/Text.hs
@@ -1,1006 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , RecordWildCards-           , BangPatterns-           , NondecreasingIndentation-           , MagicHash-  #-}-{-# OPTIONS_GHC -fno-warn-name-shadowing #-}-{-# OPTIONS_GHC -fno-warn-unused-matches #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Text--- Copyright   :  (c) The University of Glasgow, 1992-2008--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ String I\/O functions-----------------------------------------------------------------------------------module GHC.IO.Handle.Text (-        hWaitForInput, hGetChar, hGetLine, hGetContents, hPutChar, hPutStr,-        commitBuffer',       -- hack, see below-        hGetBuf, hGetBufSome, hGetBufNonBlocking, hPutBuf, hPutBufNonBlocking,-        memcpy, hPutStrLn,-    ) where--import GHC.IO-import GHC.IO.FD-import GHC.IO.Buffer-import qualified GHC.IO.BufferedIO as Buffered-import GHC.IO.Exception-import GHC.Exception-import GHC.IO.Handle.Types-import GHC.IO.Handle.Internals-import qualified GHC.IO.Device as IODevice-import qualified GHC.IO.Device as RawIO--import Foreign-import Foreign.C--import qualified Control.Exception as Exception-import Data.Typeable-import System.IO.Error-import Data.Maybe--import GHC.IORef-import GHC.Base-import GHC.Real-import GHC.Num-import GHC.Show-import GHC.List---- ------------------------------------------------------------------------------ Simple input operations---- If hWaitForInput finds anything in the Handle's buffer, it--- immediately returns.  If not, it tries to read from the underlying--- OS handle. Notice that for buffered Handles connected to terminals--- this means waiting until a complete line is available.---- | Computation 'hWaitForInput' @hdl t@--- waits until input is available on handle @hdl@.--- It returns 'True' as soon as input is available on @hdl@,--- or 'False' if no input is available within @t@ milliseconds.  Note that--- 'hWaitForInput' waits until one or more full /characters/ are available,--- which means that it needs to do decoding, and hence may fail--- with a decoding error.------ If @t@ is less than zero, then @hWaitForInput@ waits indefinitely.------ This operation may fail with:------  * 'isEOFError' if the end of file has been reached.------  * a decoding error, if the input begins with an invalid byte sequence---    in this Handle's encoding.------ NOTE for GHC users: unless you use the @-threaded@ flag,--- @hWaitForInput hdl t@ where @t >= 0@ will block all other Haskell--- threads for the duration of the call.  It behaves like a--- @safe@ foreign call in this respect.-----hWaitForInput :: Handle -> Int -> IO Bool-hWaitForInput h msecs = do-  wantReadableHandle_ "hWaitForInput" h $ \ handle_@Handle__{..} -> do-  cbuf <- readIORef haCharBuffer--  if not (isEmptyBuffer cbuf) then return True else do--  if msecs < 0-        then do cbuf' <- readTextDevice handle_ cbuf-                writeIORef haCharBuffer cbuf'-                return True-        else do-               -- there might be bytes in the byte buffer waiting to be decoded-               cbuf' <- decodeByteBuf handle_ cbuf-               writeIORef haCharBuffer cbuf'--               if not (isEmptyBuffer cbuf') then return True else do--                r <- IODevice.ready haDevice False{-read-} msecs-                if r then do -- Call hLookAhead' to throw an EOF-                             -- exception if appropriate-                             _ <- hLookAhead_ handle_-                             return True-                     else return False-                -- XXX we should only return when there are full characters-                -- not when there are only bytes.  That would mean looping-                -- and re-running IODevice.ready if we don't have any full-                -- characters; but we don't know how long we've waited-                -- so far.---- ------------------------------------------------------------------------------ hGetChar---- | Computation 'hGetChar' @hdl@ reads a character from the file or--- channel managed by @hdl@, blocking until a character is available.------ This operation may fail with:------  * 'isEOFError' if the end of file has been reached.--hGetChar :: Handle -> IO Char-hGetChar handle =-  wantReadableHandle_ "hGetChar" handle $ \handle_@Handle__{..} -> do--  -- buffering mode makes no difference: we just read whatever is available-  -- from the device (blocking only if there is nothing available), and then-  -- return the first character.-  -- See [note Buffered Reading] in GHC.IO.Handle.Types-  buf0 <- readIORef haCharBuffer--  buf1 <- if isEmptyBuffer buf0-             then readTextDevice handle_ buf0-             else return buf0--  (c1,i) <- readCharBuf (bufRaw buf1) (bufL buf1)-  let buf2 = bufferAdjustL i buf1--  if haInputNL == CRLF && c1 == '\r'-     then do-            mbuf3 <- if isEmptyBuffer buf2-                      then maybeFillReadBuffer handle_ buf2-                      else return (Just buf2)--            case mbuf3 of-               -- EOF, so just return the '\r' we have-               Nothing -> do-                  writeIORef haCharBuffer buf2-                  return '\r'-               Just buf3 -> do-                  (c2,i2) <- readCharBuf (bufRaw buf2) (bufL buf2)-                  if c2 == '\n'-                     then do-                       writeIORef haCharBuffer (bufferAdjustL i2 buf3)-                       return '\n'-                     else do-                       -- not a \r\n sequence, so just return the \r-                       writeIORef haCharBuffer buf3-                       return '\r'-     else do-            writeIORef haCharBuffer buf2-            return c1---- ------------------------------------------------------------------------------ hGetLine---- | Computation 'hGetLine' @hdl@ reads a line from the file or--- channel managed by @hdl@.------ This operation may fail with:------  * 'isEOFError' if the end of file is encountered when reading---    the /first/ character of the line.------ If 'hGetLine' encounters end-of-file at any other point while reading--- in a line, it is treated as a line terminator and the (partial)--- line is returned.--hGetLine :: Handle -> IO String-hGetLine h =-  wantReadableHandle_ "hGetLine" h $ \ handle_ -> do-     hGetLineBuffered handle_--hGetLineBuffered :: Handle__ -> IO String-hGetLineBuffered handle_@Handle__{..} = do-  buf <- readIORef haCharBuffer-  hGetLineBufferedLoop handle_ buf []--hGetLineBufferedLoop :: Handle__-                     -> CharBuffer -> [String]-                     -> IO String-hGetLineBufferedLoop handle_@Handle__{..}-        buf@Buffer{ bufL=r0, bufR=w, bufRaw=raw0 } xss =-  let-        -- find the end-of-line character, if there is one-        loop raw r-           | r == w = return (False, w)-           | otherwise =  do-                (c,r') <- readCharBuf raw r-                if c == '\n'-                   then return (True, r) -- NB. not r': don't include the '\n'-                   else loop raw r'-  in do-  (eol, off) <- loop raw0 r0--  debugIO ("hGetLineBufferedLoop: r=" ++ show r0 ++ ", w=" ++ show w ++ ", off=" ++ show off)--  (xs,r') <- if haInputNL == CRLF-                then unpack_nl raw0 r0 off ""-                else do xs <- unpack raw0 r0 off ""-                        return (xs,off)--  -- if eol == True, then off is the offset of the '\n'-  -- otherwise off == w and the buffer is now empty.-  if eol -- r' == off-        then do writeIORef haCharBuffer (bufferAdjustL (off+1) buf)-                return (concat (reverse (xs:xss)))-        else do-             let buf1 = bufferAdjustL r' buf-             maybe_buf <- maybeFillReadBuffer handle_ buf1-             case maybe_buf of-                -- Nothing indicates we caught an EOF, and we may have a-                -- partial line to return.-                Nothing -> do-                     -- we reached EOF.  There might be a lone \r left-                     -- in the buffer, so check for that and-                     -- append it to the line if necessary.-                     ---                     let pre = if not (isEmptyBuffer buf1) then "\r" else ""-                     writeIORef haCharBuffer buf1{ bufL=0, bufR=0 }-                     let str = concat (reverse (pre:xs:xss))-                     if not (null str)-                        then return str-                        else ioe_EOF-                Just new_buf ->-                     hGetLineBufferedLoop handle_ new_buf (xs:xss)--maybeFillReadBuffer :: Handle__ -> CharBuffer -> IO (Maybe CharBuffer)-maybeFillReadBuffer handle_ buf-  = Exception.catch-     (do buf' <- getSomeCharacters handle_ buf-         return (Just buf')-     )-     (\e -> do if isEOFError e-                  then return Nothing-                  else ioError e)---- See GHC.IO.Buffer-#define CHARBUF_UTF32--- #define CHARBUF_UTF16---- NB. performance-critical code: eyeball the Core.-unpack :: RawCharBuffer -> Int -> Int -> [Char] -> IO [Char]-unpack !buf !r !w acc0- | r == w    = return acc0- | otherwise =-  withRawBuffer buf $ \pbuf ->-    let-        unpackRB acc !i-         | i < r  = return acc-         | otherwise = do-              -- Here, we are rather careful to only put an *evaluated* character-              -- in the output string. Due to pointer tagging, this allows the consumer-              -- to avoid ping-ponging between the actual consumer code and the thunk code-#ifdef CHARBUF_UTF16-              -- reverse-order decoding of UTF-16-              c2 <- peekElemOff pbuf i-              if (c2 < 0xdc00 || c2 > 0xdffff)-                 then unpackRB (unsafeChr (fromIntegral c2) : acc) (i-1)-                 else do c1 <- peekElemOff pbuf (i-1)-                         let c = (fromIntegral c1 - 0xd800) * 0x400 +-                                 (fromIntegral c2 - 0xdc00) + 0x10000-                         case desurrogatifyRoundtripCharacter (unsafeChr c) of-                           { C# c# -> unpackRB (C# c# : acc) (i-2) }-#else-              c <- peekElemOff pbuf i-              unpackRB (c : acc) (i-1)-#endif-     in-     unpackRB acc0 (w-1)---- NB. performance-critical code: eyeball the Core.-unpack_nl :: RawCharBuffer -> Int -> Int -> [Char] -> IO ([Char],Int)-unpack_nl !buf !r !w acc0- | r == w    =  return (acc0, 0)- | otherwise =-  withRawBuffer buf $ \pbuf ->-    let-        unpackRB acc !i-         | i < r  = return acc-         | otherwise = do-              c <- peekElemOff pbuf i-              if (c == '\n' && i > r)-                 then do-                         c1 <- peekElemOff pbuf (i-1)-                         if (c1 == '\r')-                            then unpackRB ('\n':acc) (i-2)-                            else unpackRB ('\n':acc) (i-1)-                 else do-                         unpackRB (c : acc) (i-1)-     in do-     c <- peekElemOff pbuf (w-1)-     if (c == '\r')-        then do-                -- If the last char is a '\r', we need to know whether or-                -- not it is followed by a '\n', so leave it in the buffer-                -- for now and just unpack the rest.-                str <- unpackRB acc0 (w-2)-                return (str, w-1)-        else do-                str <- unpackRB acc0 (w-1)-                return (str, w)---- Note [#5536]------ We originally had------    let c' = desurrogatifyRoundtripCharacter c in---    c' `seq` unpackRB (c':acc) (i-1)------ but this resulted in Core like------    case (case x <# y of True -> C# e1; False -> C# e2) of c---      C# _ -> unpackRB (c:acc) (i-1)------ which compiles into a continuation for the outer case, with each--- branch of the inner case building a C# and then jumping to the--- continuation.  We'd rather not have this extra jump, which makes--- quite a difference to performance (see #5536) It turns out that--- matching on the C# directly causes GHC to do the case-of-case,--- giving much straighter code.---- -------------------------------------------------------------------------------- hGetContents---- hGetContents on a DuplexHandle only affects the read side: you can--- carry on writing to it afterwards.---- | Computation 'hGetContents' @hdl@ returns the list of characters--- corresponding to the unread portion of the channel or file managed--- by @hdl@, which is put into an intermediate state, /semi-closed/.--- In this state, @hdl@ is effectively closed,--- but items are read from @hdl@ on demand and accumulated in a special--- list returned by 'hGetContents' @hdl@.------ Any operation that fails because a handle is closed,--- also fails if a handle is semi-closed.  The only exception is 'hClose'.--- A semi-closed handle becomes closed:------  * if 'hClose' is applied to it;------  * if an I\/O error occurs when reading an item from the handle;------  * or once the entire contents of the handle has been read.------ Once a semi-closed handle becomes closed, the contents of the--- associated list becomes fixed.  The contents of this final list is--- only partially specified: it will contain at least all the items of--- the stream that were evaluated prior to the handle becoming closed.------ Any I\/O errors encountered while a handle is semi-closed are simply--- discarded.------ This operation may fail with:------  * 'isEOFError' if the end of file has been reached.--hGetContents :: Handle -> IO String-hGetContents handle =-   wantReadableHandle "hGetContents" handle $ \handle_ -> do-      xs <- lazyRead handle-      return (handle_{ haType=SemiClosedHandle}, xs )---- Note that someone may close the semi-closed handle (or change its--- buffering), so each time these lazy read functions are pulled on,--- they have to check whether the handle has indeed been closed.--lazyRead :: Handle -> IO String-lazyRead handle =-   unsafeInterleaveIO $-        withHandle "hGetContents" handle $ \ handle_ -> do-        case haType handle_ of-          SemiClosedHandle -> lazyReadBuffered handle handle_-          ClosedHandle-            -> ioException-                  (IOError (Just handle) IllegalOperation "hGetContents"-                        "delayed read on closed handle" Nothing Nothing)-          _ -> ioException-                  (IOError (Just handle) IllegalOperation "hGetContents"-                        "illegal handle type" Nothing Nothing)--lazyReadBuffered :: Handle -> Handle__ -> IO (Handle__, [Char])-lazyReadBuffered h handle_@Handle__{..} = do-   buf <- readIORef haCharBuffer-   Exception.catch-        (do-            buf'@Buffer{..} <- getSomeCharacters handle_ buf-            lazy_rest <- lazyRead h-            (s,r) <- if haInputNL == CRLF-                         then unpack_nl bufRaw bufL bufR lazy_rest-                         else do s <- unpack bufRaw bufL bufR lazy_rest-                                 return (s,bufR)-            writeIORef haCharBuffer (bufferAdjustL r buf')-            return (handle_, s)-        )-        (\e -> do (handle_', _) <- hClose_help handle_-                  debugIO ("hGetContents caught: " ++ show e)-                  -- We might have a \r cached in CRLF mode.  So we-                  -- need to check for that and return it:-                  let r = if isEOFError e-                             then if not (isEmptyBuffer buf)-                                     then "\r"-                                     else ""-                             else-                                  throw (augmentIOError e "hGetContents" h)--                  return (handle_', r)-        )---- ensure we have some characters in the buffer-getSomeCharacters :: Handle__ -> CharBuffer -> IO CharBuffer-getSomeCharacters handle_@Handle__{..} buf@Buffer{..} =-  case bufferElems buf of--    -- buffer empty: read some more-    0 -> readTextDevice handle_ buf--    -- if the buffer has a single '\r' in it and we're doing newline-    -- translation: read some more-    1 | haInputNL == CRLF -> do-      (c,_) <- readCharBuf bufRaw bufL-      if c == '\r'-         then do -- shuffle the '\r' to the beginning.  This is only safe-                 -- if we're about to call readTextDevice, otherwise it-                 -- would mess up flushCharBuffer.-                 -- See [note Buffer Flushing], GHC.IO.Handle.Types-                 _ <- writeCharBuf bufRaw 0 '\r'-                 let buf' = buf{ bufL=0, bufR=1 }-                 readTextDevice handle_ buf'-         else do-                 return buf--    -- buffer has some chars in it already: just return it-    _otherwise ->-      return buf---- ------------------------------------------------------------------------------ hPutChar---- | Computation 'hPutChar' @hdl ch@ writes the character @ch@ to the--- file or channel managed by @hdl@.  Characters may be buffered if--- buffering is enabled for @hdl@.------ This operation may fail with:------  * 'isFullError' if the device is full; or------  * 'isPermissionError' if another system resource limit would be exceeded.--hPutChar :: Handle -> Char -> IO ()-hPutChar handle c = do-    c `seq` return ()-    wantWritableHandle "hPutChar" handle $ \ handle_  -> do-     hPutcBuffered handle_ c--hPutcBuffered :: Handle__ -> Char -> IO ()-hPutcBuffered handle_@Handle__{..} c = do-  buf <- readIORef haCharBuffer-  if c == '\n'-     then do buf1 <- if haOutputNL == CRLF-                        then do-                          buf1 <- putc buf '\r'-                          putc buf1 '\n'-                        else do-                          putc buf '\n'-             writeCharBuffer handle_ buf1-             when is_line $ flushByteWriteBuffer handle_-      else do-          buf1 <- putc buf c-          writeCharBuffer handle_ buf1-          return ()-  where-    is_line = case haBufferMode of-                LineBuffering -> True-                _             -> False--    putc buf@Buffer{ bufRaw=raw, bufR=w } c = do-       debugIO ("putc: " ++ summaryBuffer buf)-       w'  <- writeCharBuf raw w c-       return buf{ bufR = w' }---- ------------------------------------------------------------------------------ hPutStr---- We go to some trouble to avoid keeping the handle locked while we're--- evaluating the string argument to hPutStr, in case doing so triggers another--- I/O operation on the same handle which would lead to deadlock.  The classic--- case is------              putStr (trace "hello" "world")------ so the basic scheme is this:------      * copy the string into a fresh buffer,---      * "commit" the buffer to the handle.------ Committing may involve simply copying the contents of the new--- buffer into the handle's buffer, flushing one or both buffers, or--- maybe just swapping the buffers over (if the handle's buffer was--- empty).  See commitBuffer below.---- | Computation 'hPutStr' @hdl s@ writes the string--- @s@ to the file or channel managed by @hdl@.------ This operation may fail with:------  * 'isFullError' if the device is full; or------  * 'isPermissionError' if another system resource limit would be exceeded.--hPutStr :: Handle -> String -> IO ()-hPutStr handle str = hPutStr' handle str False---- | The same as 'hPutStr', but adds a newline character.-hPutStrLn :: Handle -> String -> IO ()-hPutStrLn handle str = hPutStr' handle str True-  -- An optimisation: we treat hPutStrLn specially, to avoid the-  -- overhead of a single putChar '\n', which is quite high now that we-  -- have to encode eagerly.--hPutStr' :: Handle -> String -> Bool -> IO ()-hPutStr' handle str add_nl =-  do-    (buffer_mode, nl) <--         wantWritableHandle "hPutStr" handle $ \h_ -> do-                       bmode <- getSpareBuffer h_-                       return (bmode, haOutputNL h_)--    case buffer_mode of-       (NoBuffering, _) -> do-            hPutChars handle str        -- v. slow, but we don't care-            when add_nl $ hPutChar handle '\n'-       (LineBuffering, buf) -> do-            writeBlocks handle True  add_nl nl buf str-       (BlockBuffering _, buf) -> do-            writeBlocks handle False add_nl nl buf str--hPutChars :: Handle -> [Char] -> IO ()-hPutChars _      [] = return ()-hPutChars handle (c:cs) = hPutChar handle c >> hPutChars handle cs--getSpareBuffer :: Handle__ -> IO (BufferMode, CharBuffer)-getSpareBuffer Handle__{haCharBuffer=ref,-                        haBuffers=spare_ref,-                        haBufferMode=mode}- = do-   case mode of-     NoBuffering -> return (mode, error "no buffer!")-     _ -> do-          bufs <- readIORef spare_ref-          buf  <- readIORef ref-          case bufs of-            BufferListCons b rest -> do-                writeIORef spare_ref rest-                return ( mode, emptyBuffer b (bufSize buf) WriteBuffer)-            BufferListNil -> do-                new_buf <- newCharBuffer (bufSize buf) WriteBuffer-                return (mode, new_buf)----- NB. performance-critical code: eyeball the Core.-writeBlocks :: Handle -> Bool -> Bool -> Newline -> Buffer CharBufElem -> String -> IO ()-writeBlocks hdl line_buffered add_nl nl-            buf@Buffer{ bufRaw=raw, bufSize=len } s =-  let-   shoveString :: Int -> [Char] -> [Char] -> IO ()-   shoveString !n [] [] = do-        commitBuffer hdl raw len n False{-no flush-} True{-release-}-   shoveString !n [] rest = do-        shoveString n rest []-   shoveString !n (c:cs) rest-     -- n+1 so we have enough room to write '\r\n' if necessary-     | n + 1 >= len = do-        commitBuffer hdl raw len n False{-flush-} False-        shoveString 0 (c:cs) rest-     | c == '\n'  =  do-        n' <- if nl == CRLF-                 then do-                    n1 <- writeCharBuf raw n  '\r'-                    writeCharBuf raw n1 '\n'-                 else do-                    writeCharBuf raw n c-        if line_buffered-           then do-                -- end of line, so write and flush-               commitBuffer hdl raw len n' True{-flush-} False-               shoveString 0 cs rest-           else do-               shoveString n' cs rest-     | otherwise = do-        n' <- writeCharBuf raw n c-        shoveString n' cs rest-  in-  shoveString 0 s (if add_nl then "\n" else "")---- -------------------------------------------------------------------------------- commitBuffer handle buf sz count flush release------ Write the contents of the buffer 'buf' ('sz' bytes long, containing--- 'count' bytes of data) to handle (handle must be block or line buffered).--commitBuffer-        :: Handle                       -- handle to commit to-        -> RawCharBuffer -> Int         -- address and size (in bytes) of buffer-        -> Int                          -- number of bytes of data in buffer-        -> Bool                         -- True <=> flush the handle afterward-        -> Bool                         -- release the buffer?-        -> IO ()--commitBuffer hdl !raw !sz !count flush release =-  wantWritableHandle "commitBuffer" hdl $ \h_@Handle__{..} -> do-      debugIO ("commitBuffer: sz=" ++ show sz ++ ", count=" ++ show count-            ++ ", flush=" ++ show flush ++ ", release=" ++ show release)--      writeCharBuffer h_ Buffer{ bufRaw=raw, bufState=WriteBuffer,-                                 bufL=0, bufR=count, bufSize=sz }--      when flush $ flushByteWriteBuffer h_--      -- release the buffer if necessary-      when release $ do-          -- find size of current buffer-          old_buf@Buffer{ bufSize=size } <- readIORef haCharBuffer-          when (sz == size) $ do-               spare_bufs <- readIORef haBuffers-               writeIORef haBuffers (BufferListCons raw spare_bufs)--      return ()---- backwards compatibility; the text package uses this-commitBuffer' :: RawCharBuffer -> Int -> Int -> Bool -> Bool -> Handle__-              -> IO CharBuffer-commitBuffer' raw sz@(I# _) count@(I# _) flush release h_@Handle__{..}-   = do-      debugIO ("commitBuffer: sz=" ++ show sz ++ ", count=" ++ show count-            ++ ", flush=" ++ show flush ++ ", release=" ++ show release)--      let this_buf = Buffer{ bufRaw=raw, bufState=WriteBuffer,-                             bufL=0, bufR=count, bufSize=sz }--      writeCharBuffer h_ this_buf--      when flush $ flushByteWriteBuffer h_--      -- release the buffer if necessary-      when release $ do-          -- find size of current buffer-          old_buf@Buffer{ bufSize=size } <- readIORef haCharBuffer-          when (sz == size) $ do-               spare_bufs <- readIORef haBuffers-               writeIORef haBuffers (BufferListCons raw spare_bufs)--      return this_buf---- ------------------------------------------------------------------------------ Reading/writing sequences of bytes.---- ------------------------------------------------------------------------------ hPutBuf---- | 'hPutBuf' @hdl buf count@ writes @count@ 8-bit bytes from the--- buffer @buf@ to the handle @hdl@.  It returns ().------ 'hPutBuf' ignores any text encoding that applies to the 'Handle',--- writing the bytes directly to the underlying file or device.------ 'hPutBuf' ignores the prevailing 'TextEncoding' and--- 'NewlineMode' on the 'Handle', and writes bytes directly.------ This operation may fail with:------  * 'ResourceVanished' if the handle is a pipe or socket, and the---    reading end is closed.  (If this is a POSIX system, and the program---    has not asked to ignore SIGPIPE, then a SIGPIPE may be delivered---    instead, whose default action is to terminate the program).--hPutBuf :: Handle                       -- handle to write to-        -> Ptr a                        -- address of buffer-        -> Int                          -- number of bytes of data in buffer-        -> IO ()-hPutBuf h ptr count = do _ <- hPutBuf' h ptr count True-                         return ()--hPutBufNonBlocking-        :: Handle                       -- handle to write to-        -> Ptr a                        -- address of buffer-        -> Int                          -- number of bytes of data in buffer-        -> IO Int                       -- returns: number of bytes written-hPutBufNonBlocking h ptr count = hPutBuf' h ptr count False--hPutBuf':: Handle                       -- handle to write to-        -> Ptr a                        -- address of buffer-        -> Int                          -- number of bytes of data in buffer-        -> Bool                         -- allow blocking?-        -> IO Int-hPutBuf' handle ptr count can_block-  | count == 0 = return 0-  | count <  0 = illegalBufferSize handle "hPutBuf" count-  | otherwise =-    wantWritableHandle "hPutBuf" handle $-      \ h_@Handle__{..} -> do-          debugIO ("hPutBuf count=" ++ show count)--          r <- bufWrite h_ (castPtr ptr) count can_block--          -- we must flush if this Handle is set to NoBuffering.  If-          -- it is set to LineBuffering, be conservative and flush-          -- anyway (we didn't check for newlines in the data).-          case haBufferMode of-             BlockBuffering _      -> do return ()-             _line_or_no_buffering -> do flushWriteBuffer h_-          return r--bufWrite :: Handle__-> Ptr Word8 -> Int -> Bool -> IO Int-bufWrite h_@Handle__{..} ptr count can_block =-  seq count $ do  -- strictness hack-  old_buf@Buffer{ bufRaw=old_raw, bufR=w, bufSize=size }-     <- readIORef haByteBuffer--  -- enough room in handle buffer?-  if (size - w > count)-        -- There's enough room in the buffer:-        -- just copy the data in and update bufR.-        then do debugIO ("hPutBuf: copying to buffer, w=" ++ show w)-                copyToRawBuffer old_raw w ptr count-                writeIORef haByteBuffer old_buf{ bufR = w + count }-                return count--        -- else, we have to flush-        else do debugIO "hPutBuf: flushing first"-                old_buf' <- Buffered.flushWriteBuffer haDevice old_buf-                        -- TODO: we should do a non-blocking flush here-                writeIORef haByteBuffer old_buf'-                -- if we can fit in the buffer, then just loop-                if count < size-                   then bufWrite h_ ptr count can_block-                   else if can_block-                           then do writeChunk h_ (castPtr ptr) count-                                   return count-                           else writeChunkNonBlocking h_ (castPtr ptr) count--writeChunk :: Handle__ -> Ptr Word8 -> Int -> IO ()-writeChunk h_@Handle__{..} ptr bytes-  | Just fd <- cast haDevice  =  RawIO.write (fd::FD) ptr bytes-  | otherwise = error "Todo: hPutBuf"--writeChunkNonBlocking :: Handle__ -> Ptr Word8 -> Int -> IO Int-writeChunkNonBlocking h_@Handle__{..} ptr bytes-  | Just fd <- cast haDevice  =  RawIO.writeNonBlocking (fd::FD) ptr bytes-  | otherwise = error "Todo: hPutBuf"---- ------------------------------------------------------------------------------ hGetBuf---- | 'hGetBuf' @hdl buf count@ reads data from the handle @hdl@--- into the buffer @buf@ until either EOF is reached or--- @count@ 8-bit bytes have been read.--- It returns the number of bytes actually read.  This may be zero if--- EOF was reached before any data was read (or if @count@ is zero).------ 'hGetBuf' never raises an EOF exception, instead it returns a value--- smaller than @count@.------ If the handle is a pipe or socket, and the writing end--- is closed, 'hGetBuf' will behave as if EOF was reached.------ 'hGetBuf' ignores the prevailing 'TextEncoding' and 'NewlineMode'--- on the 'Handle', and reads bytes directly.--hGetBuf :: Handle -> Ptr a -> Int -> IO Int-hGetBuf h ptr count-  | count == 0 = return 0-  | count <  0 = illegalBufferSize h "hGetBuf" count-  | otherwise =-      wantReadableHandle_ "hGetBuf" h $ \ h_@Handle__{..} -> do-         flushCharReadBuffer h_-         buf@Buffer{ bufRaw=raw, bufR=w, bufL=r, bufSize=sz }-            <- readIORef haByteBuffer-         if isEmptyBuffer buf-            then bufReadEmpty    h_ buf (castPtr ptr) 0 count-            else bufReadNonEmpty h_ buf (castPtr ptr) 0 count---- small reads go through the buffer, large reads are satisfied by--- taking data first from the buffer and then direct from the file--- descriptor.--bufReadNonEmpty :: Handle__ -> Buffer Word8 -> Ptr Word8 -> Int -> Int -> IO Int-bufReadNonEmpty h_@Handle__{..}-                buf@Buffer{ bufRaw=raw, bufR=w, bufL=r, bufSize=sz }-                ptr !so_far !count- = do-        let avail = w - r-        if (count < avail)-           then do-                copyFromRawBuffer ptr raw r count-                writeIORef haByteBuffer buf{ bufL = r + count }-                return (so_far + count)-           else do--        copyFromRawBuffer ptr raw r avail-        let buf' = buf{ bufR=0, bufL=0 }-        writeIORef haByteBuffer buf'-        let remaining = count - avail-            so_far' = so_far + avail-            ptr' = ptr `plusPtr` avail--        if remaining == 0-           then return so_far'-           else bufReadEmpty h_ buf' ptr' so_far' remaining---bufReadEmpty :: Handle__ -> Buffer Word8 -> Ptr Word8 -> Int -> Int -> IO Int-bufReadEmpty h_@Handle__{..}-             buf@Buffer{ bufRaw=raw, bufR=w, bufL=r, bufSize=sz }-             ptr so_far count- | count > sz, Just fd <- cast haDevice = loop fd 0 count- | otherwise = do-     (r,buf') <- Buffered.fillReadBuffer haDevice buf-     if r == 0-        then return so_far-        else do writeIORef haByteBuffer buf'-                bufReadNonEmpty h_ buf' ptr so_far count- where-  loop :: FD -> Int -> Int -> IO Int-  loop fd off bytes | bytes <= 0 = return (so_far + off)-  loop fd off bytes = do-    r <- RawIO.read (fd::FD) (ptr `plusPtr` off) bytes-    if r == 0-        then return (so_far + off)-        else loop fd (off + r) (bytes - r)---- ------------------------------------------------------------------------------ hGetBufSome---- | 'hGetBufSome' @hdl buf count@ reads data from the handle @hdl@--- into the buffer @buf@.  If there is any data available to read,--- then 'hGetBufSome' returns it immediately; it only blocks if there--- is no data to be read.------ It returns the number of bytes actually read.  This may be zero if--- EOF was reached before any data was read (or if @count@ is zero).------ 'hGetBufSome' never raises an EOF exception, instead it returns a value--- smaller than @count@.------ If the handle is a pipe or socket, and the writing end--- is closed, 'hGetBufSome' will behave as if EOF was reached.------ 'hGetBufSome' ignores the prevailing 'TextEncoding' and 'NewlineMode'--- on the 'Handle', and reads bytes directly.--hGetBufSome :: Handle -> Ptr a -> Int -> IO Int-hGetBufSome h ptr count-  | count == 0 = return 0-  | count <  0 = illegalBufferSize h "hGetBufSome" count-  | otherwise =-      wantReadableHandle_ "hGetBufSome" h $ \ h_@Handle__{..} -> do-         flushCharReadBuffer h_-         buf@Buffer{ bufSize=sz } <- readIORef haByteBuffer-         if isEmptyBuffer buf-            then case count > sz of  -- large read? optimize it with a little special case:-                    True | Just fd <- haFD h_ -> do RawIO.read fd (castPtr ptr) count-                    _ -> do (r,buf') <- Buffered.fillReadBuffer haDevice buf-                            if r == 0-                               then return 0-                               else do writeIORef haByteBuffer buf'-                                       bufReadNBNonEmpty h_ buf' (castPtr ptr) 0 (min r count)-                                        -- new count is  (min r count), so-                                        -- that bufReadNBNonEmpty will not-                                        -- issue another read.-            else-              let count' = min count (bufferElems buf)-              in bufReadNBNonEmpty h_ buf (castPtr ptr) 0 count'--haFD :: Handle__ -> Maybe FD-haFD h_@Handle__{..} = cast haDevice---- | 'hGetBufNonBlocking' @hdl buf count@ reads data from the handle @hdl@--- into the buffer @buf@ until either EOF is reached, or--- @count@ 8-bit bytes have been read, or there is no more data available--- to read immediately.------ 'hGetBufNonBlocking' is identical to 'hGetBuf', except that it will--- never block waiting for data to become available, instead it returns--- only whatever data is available.  To wait for data to arrive before--- calling 'hGetBufNonBlocking', use 'hWaitForInput'.------ If the handle is a pipe or socket, and the writing end--- is closed, 'hGetBufNonBlocking' will behave as if EOF was reached.------ 'hGetBufNonBlocking' ignores the prevailing 'TextEncoding' and--- 'NewlineMode' on the 'Handle', and reads bytes directly.------ NOTE: on Windows, this function does not work correctly; it--- behaves identically to 'hGetBuf'.--hGetBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int-hGetBufNonBlocking h ptr count-  | count == 0 = return 0-  | count <  0 = illegalBufferSize h "hGetBufNonBlocking" count-  | otherwise =-      wantReadableHandle_ "hGetBufNonBlocking" h $ \ h_@Handle__{..} -> do-         flushCharReadBuffer h_-         buf@Buffer{ bufRaw=raw, bufR=w, bufL=r, bufSize=sz }-            <- readIORef haByteBuffer-         if isEmptyBuffer buf-            then bufReadNBEmpty    h_ buf (castPtr ptr) 0 count-            else bufReadNBNonEmpty h_ buf (castPtr ptr) 0 count--bufReadNBEmpty :: Handle__ -> Buffer Word8 -> Ptr Word8 -> Int -> Int -> IO Int-bufReadNBEmpty   h_@Handle__{..}-                 buf@Buffer{ bufRaw=raw, bufR=w, bufL=r, bufSize=sz }-                 ptr so_far count-  | count > sz,-    Just fd <- cast haDevice = do-       m <- RawIO.readNonBlocking (fd::FD) ptr count-       case m of-         Nothing -> return so_far-         Just n  -> return (so_far + n)-- | otherwise = do-     buf <- readIORef haByteBuffer-     (r,buf') <- Buffered.fillReadBuffer0 haDevice buf-     case r of-       Nothing -> return so_far-       Just 0  -> return so_far-       Just r  -> do-         writeIORef haByteBuffer buf'-         bufReadNBNonEmpty h_ buf' ptr so_far (min count r)-                          -- NOTE: new count is    min count r-                          -- so we will just copy the contents of the-                          -- buffer in the recursive call, and not-                          -- loop again.---bufReadNBNonEmpty :: Handle__ -> Buffer Word8 -> Ptr Word8 -> Int -> Int -> IO Int-bufReadNBNonEmpty h_@Handle__{..}-                  buf@Buffer{ bufRaw=raw, bufR=w, bufL=r, bufSize=sz }-                  ptr so_far count-  = do-        let avail = w - r-        if (count < avail)-           then do-                copyFromRawBuffer ptr raw r count-                writeIORef haByteBuffer buf{ bufL = r + count }-                return (so_far + count)-           else do--        copyFromRawBuffer ptr raw r avail-        let buf' = buf{ bufR=0, bufL=0 }-        writeIORef haByteBuffer buf'-        let remaining = count - avail-            so_far' = so_far + avail-            ptr' = ptr `plusPtr` avail--        if remaining == 0-           then return so_far'-           else bufReadNBEmpty h_ buf' ptr' so_far' remaining---- ------------------------------------------------------------------------------ memcpy wrappers--copyToRawBuffer :: RawBuffer e -> Int -> Ptr e -> Int -> IO ()-copyToRawBuffer raw off ptr bytes =- withRawBuffer raw $ \praw ->-   do _ <- memcpy (praw `plusPtr` off) ptr (fromIntegral bytes)-      return ()--copyFromRawBuffer :: Ptr e -> RawBuffer e -> Int -> Int -> IO ()-copyFromRawBuffer ptr raw off bytes =- withRawBuffer raw $ \praw ->-   do _ <- memcpy ptr (praw `plusPtr` off) (fromIntegral bytes)-      return ()--foreign import ccall unsafe "memcpy"-   memcpy :: Ptr a -> Ptr a -> CSize -> IO (Ptr ())---------------------------------------------------------------------------------- Internal Utils--illegalBufferSize :: Handle -> String -> Int -> IO a-illegalBufferSize handle fn sz =-        ioException (IOError (Just handle)-                            InvalidArgument  fn-                            ("illegal buffer size " ++ showsPrec 9 sz [])-                            Nothing Nothing)-
− GHC/IO/Handle/Types.hs
@@ -1,430 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , ExistentialQuantification-           , AutoDeriveTypeable-  #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.Handle.Types--- Copyright   :  (c) The University of Glasgow, 1994-2009--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Basic types for the implementation of IO Handles.-----------------------------------------------------------------------------------module GHC.IO.Handle.Types (-      Handle(..), Handle__(..), showHandle,-      checkHandleInvariants,-      BufferList(..),-      HandleType(..),-      isReadableHandleType, isWritableHandleType, isReadWriteHandleType,-      BufferMode(..),-      BufferCodec(..),-      NewlineMode(..), Newline(..), nativeNewline,-      universalNewlineMode, noNewlineTranslation, nativeNewlineMode-  ) where--#undef DEBUG--import GHC.Base-import GHC.MVar-import GHC.IO-import GHC.IO.Buffer-import GHC.IO.BufferedIO-import GHC.IO.Encoding.Types-import GHC.IORef-import GHC.Show-import GHC.Read-import GHC.Word-import GHC.IO.Device-import Data.Typeable-#ifdef DEBUG-import Control.Monad-#endif---- ------------------------------------------------------------------------------ Handle type----  A Handle is represented by (a reference to) a record---  containing the state of the I/O port/device. We record---  the following pieces of info:----    * type (read,write,closed etc.)---    * the underlying file descriptor---    * buffering mode---    * buffer, and spare buffers---    * user-friendly name (usually the---      FilePath used when IO.openFile was called)---- Note: when a Handle is garbage collected, we want to flush its buffer--- and close the OS file handle, so as to free up a (precious) resource.---- | Haskell defines operations to read and write characters from and to files,--- represented by values of type @Handle@.  Each value of this type is a--- /handle/: a record used by the Haskell run-time system to /manage/ I\/O--- with file system objects.  A handle has at least the following properties:------  * whether it manages input or output or both;------  * whether it is /open/, /closed/ or /semi-closed/;------  * whether the object is seekable;------  * whether buffering is disabled, or enabled on a line or block basis;------  * a buffer (whose length may be zero).------ Most handles will also have a current I\/O position indicating where the next--- input or output operation will occur.  A handle is /readable/ if it--- manages only input or both input and output; likewise, it is /writable/ if--- it manages only output or both input and output.  A handle is /open/ when--- first allocated.--- Once it is closed it can no longer be used for either input or output,--- though an implementation cannot re-use its storage while references--- remain to it.  Handles are in the 'Show' and 'Eq' classes.  The string--- produced by showing a handle is system dependent; it should include--- enough information to identify the handle for debugging.  A handle is--- equal according to '==' only to itself; no attempt--- is made to compare the internal state of different handles for equality.--data Handle-  = FileHandle                          -- A normal handle to a file-        FilePath                        -- the file (used for error messages-                                        -- only)-        !(MVar Handle__)--  | DuplexHandle                        -- A handle to a read/write stream-        FilePath                        -- file for a FIFO, otherwise some-                                        --   descriptive string (used for error-                                        --   messages only)-        !(MVar Handle__)                -- The read side-        !(MVar Handle__)                -- The write side--  deriving Typeable---- NOTES:---    * A 'FileHandle' is seekable.  A 'DuplexHandle' may or may not be---      seekable.--instance Eq Handle where- (FileHandle _ h1)     == (FileHandle _ h2)     = h1 == h2- (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2- _ == _ = False--data Handle__-  = forall dev enc_state dec_state . (IODevice dev, BufferedIO dev, Typeable dev) =>-    Handle__ {-      haDevice      :: !dev,-      haType        :: HandleType,           -- type (read/write/append etc.)-      haByteBuffer  :: !(IORef (Buffer Word8)),-      haBufferMode  :: BufferMode,-      haLastDecode  :: !(IORef (dec_state, Buffer Word8)),-      haCharBuffer  :: !(IORef (Buffer CharBufElem)), -- the current buffer-      haBuffers     :: !(IORef (BufferList CharBufElem)),  -- spare buffers-      haEncoder     :: Maybe (TextEncoder enc_state),-      haDecoder     :: Maybe (TextDecoder dec_state),-      haCodec       :: Maybe TextEncoding,-      haInputNL     :: Newline,-      haOutputNL    :: Newline,-      haOtherSide   :: Maybe (MVar Handle__) -- ptr to the write side of a-                                             -- duplex handle.-    }-    deriving Typeable---- we keep a few spare buffers around in a handle to avoid allocating--- a new one for each hPutStr.  These buffers are *guaranteed* to be the--- same size as the main buffer.-data BufferList e-  = BufferListNil-  | BufferListCons (RawBuffer e) (BufferList e)----  Internally, we classify handles as being one---  of the following:--data HandleType- = ClosedHandle- | SemiClosedHandle- | ReadHandle- | WriteHandle- | AppendHandle- | ReadWriteHandle--isReadableHandleType :: HandleType -> Bool-isReadableHandleType ReadHandle         = True-isReadableHandleType ReadWriteHandle    = True-isReadableHandleType _                  = False--isWritableHandleType :: HandleType -> Bool-isWritableHandleType AppendHandle    = True-isWritableHandleType WriteHandle     = True-isWritableHandleType ReadWriteHandle = True-isWritableHandleType _               = False--isReadWriteHandleType :: HandleType -> Bool-isReadWriteHandleType ReadWriteHandle{} = True-isReadWriteHandleType _                 = False---- INVARIANTS on Handles:------   * A handle *always* has a buffer, even if it is only 1 character long---     (an unbuffered handle needs a 1 character buffer in order to support---      hLookAhead and hIsEOF).---   * In a read Handle, the byte buffer is always empty (we decode when reading)---   * In a wriite Handle, the Char buffer is always empty (we encode when writing)----checkHandleInvariants :: Handle__ -> IO ()-#ifdef DEBUG-checkHandleInvariants h_ = do- bbuf <- readIORef (haByteBuffer h_)- checkBuffer bbuf- cbuf <- readIORef (haCharBuffer h_)- checkBuffer cbuf- when (isWriteBuffer cbuf && not (isEmptyBuffer cbuf)) $-   error ("checkHandleInvariants: char write buffer non-empty: " ++-          summaryBuffer bbuf ++ ", " ++ summaryBuffer cbuf)- when (isWriteBuffer bbuf /= isWriteBuffer cbuf) $-   error ("checkHandleInvariants: buffer modes differ: " ++-          summaryBuffer bbuf ++ ", " ++ summaryBuffer cbuf)--#else-checkHandleInvariants _ = return ()-#endif---- ------------------------------------------------------------------------------ Buffering modes---- | Three kinds of buffering are supported: line-buffering,--- block-buffering or no-buffering.  These modes have the following--- effects. For output, items are written out, or /flushed/,--- from the internal buffer according to the buffer mode:------  * /line-buffering/: the entire output buffer is flushed---    whenever a newline is output, the buffer overflows,---    a 'System.IO.hFlush' is issued, or the handle is closed.------  * /block-buffering/: the entire buffer is written out whenever it---    overflows, a 'System.IO.hFlush' is issued, or the handle is closed.------  * /no-buffering/: output is written immediately, and never stored---    in the buffer.------ An implementation is free to flush the buffer more frequently,--- but not less frequently, than specified above.--- The output buffer is emptied as soon as it has been written out.------ Similarly, input occurs according to the buffer mode for the handle:------  * /line-buffering/: when the buffer for the handle is not empty,---    the next item is obtained from the buffer; otherwise, when the---    buffer is empty, characters up to and including the next newline---    character are read into the buffer.  No characters are available---    until the newline character is available or the buffer is full.------  * /block-buffering/: when the buffer for the handle becomes empty,---    the next block of data is read into the buffer.------  * /no-buffering/: the next input item is read and returned.---    The 'System.IO.hLookAhead' operation implies that even a no-buffered---    handle may require a one-character buffer.------ The default buffering mode when a handle is opened is--- implementation-dependent and may depend on the file system object--- which is attached to that handle.--- For most implementations, physical files will normally be block-buffered--- and terminals will normally be line-buffered.--data BufferMode- = NoBuffering  -- ^ buffering is disabled if possible.- | LineBuffering-                -- ^ line-buffering should be enabled if possible.- | BlockBuffering (Maybe Int)-                -- ^ block-buffering should be enabled if possible.-                -- The size of the buffer is @n@ items if the argument-                -- is 'Just' @n@ and is otherwise implementation-dependent.-   deriving (Eq, Ord, Read, Show)--{--[note Buffering Implementation]--Each Handle has two buffers: a byte buffer (haByteBuffer) and a Char-buffer (haCharBuffer).--[note Buffered Reading]--For read Handles, bytes are read into the byte buffer, and immediately-decoded into the Char buffer (see-GHC.IO.Handle.Internals.readTextDevice).  The only way there might be-some data left in the byte buffer is if there is a partial multi-byte-character sequence that cannot be decoded into a full character.--Note that the buffering mode (haBufferMode) makes no difference when-reading data into a Handle.  When reading, we can always just read all-the data there is available without blocking, decode it into the Char-buffer, and then provide it immediately to the caller.--[note Buffered Writing]--Characters are written into the Char buffer by e.g. hPutStr.  At the-end of the operation, or when the char buffer is full, the buffer is-decoded to the byte buffer (see writeCharBuffer).  This is so that we-can detect encoding errors at the right point.--Hence, the Char buffer is always empty between Handle operations.--[note Buffer Sizing]--The char buffer is always a default size (dEFAULT_CHAR_BUFFER_SIZE).-The byte buffer size is chosen by the underlying device (via its-IODevice.newBuffer).  Hence the size of these buffers is not under-user control.--There are certain minimum sizes for these buffers imposed by the-library (but not checked):-- - we must be able to buffer at least one character, so that-   hLookAhead can work-- - the byte buffer must be able to store at least one encoded-   character in the current encoding (6 bytes?)-- - when reading, the char buffer must have room for two characters, so-   that we can spot the \r\n sequence.--How do we implement hSetBuffering?--For reading, we have never used the user-supplied buffer size, because-there's no point: we always pass all available data to the reader-immediately.  Buffering would imply waiting until a certain amount of-data is available, which has no advantages.  So hSetBuffering is-essentially a no-op for read handles, except that it turns on/off raw-mode for the underlying device if necessary.--For writing, the buffering mode is handled by the write operations-themselves (hPutChar and hPutStr).  Every write ends with-writeCharBuffer, which checks whether the buffer should be flushed-according to the current buffering mode.  Additionally, we look for-newlines and flush if the mode is LineBuffering.--[note Buffer Flushing]--** Flushing the Char buffer--We must be able to flush the Char buffer, in order to implement-hSetEncoding, and things like hGetBuf which want to read raw bytes.--Flushing the Char buffer on a write Handle is easy: it is always empty.--Flushing the Char buffer on a read Handle involves rewinding the byte-buffer to the point representing the next Char in the Char buffer.-This is done by-- - remembering the state of the byte buffer *before* the last decode-- - re-decoding the bytes that represent the chars already read from the-   Char buffer.  This gives us the point in the byte buffer that-   represents the *next* Char to be read.--In order for this to work, after readTextHandle we must NOT MODIFY THE-CONTENTS OF THE BYTE OR CHAR BUFFERS, except to remove characters from-the Char buffer.--** Flushing the byte buffer--The byte buffer can be flushed if the Char buffer has already been-flushed (see above).  For a read Handle, flushing the byte buffer-means seeking the device back by the number of bytes in the buffer,-and hence it is only possible on a seekable Handle.---}---- ------------------------------------------------------------------------------ Newline translation---- | The representation of a newline in the external file or stream.-data Newline = LF    -- ^ '\n'-             | CRLF  -- ^ '\r\n'-             deriving (Eq, Ord, Read, Show)---- | Specifies the translation, if any, of newline characters between--- internal Strings and the external file or stream.  Haskell Strings--- are assumed to represent newlines with the '\n' character; the--- newline mode specifies how to translate '\n' on output, and what to--- translate into '\n' on input.-data NewlineMode-  = NewlineMode { inputNL :: Newline,-                    -- ^ the representation of newlines on input-                  outputNL :: Newline-                    -- ^ the representation of newlines on output-                 }-             deriving (Eq, Ord, Read, Show)---- | The native newline representation for the current platform: 'LF'--- on Unix systems, 'CRLF' on Windows.-nativeNewline :: Newline-#ifdef mingw32_HOST_OS-nativeNewline = CRLF-#else-nativeNewline = LF-#endif---- | Map '\r\n' into '\n' on input, and '\n' to the native newline--- represetnation on output.  This mode can be used on any platform, and--- works with text files using any newline convention.  The downside is--- that @readFile >>= writeFile@ might yield a different file.------ > universalNewlineMode  = NewlineMode { inputNL  = CRLF,--- >                                       outputNL = nativeNewline }----universalNewlineMode :: NewlineMode-universalNewlineMode  = NewlineMode { inputNL  = CRLF,-                                      outputNL = nativeNewline }---- | Use the native newline representation on both input and output------ > nativeNewlineMode  = NewlineMode { inputNL  = nativeNewline--- >                                    outputNL = nativeNewline }----nativeNewlineMode    :: NewlineMode-nativeNewlineMode     = NewlineMode { inputNL  = nativeNewline,-                                      outputNL = nativeNewline }---- | Do no newline translation at all.------ > noNewlineTranslation  = NewlineMode { inputNL  = LF, outputNL = LF }----noNewlineTranslation :: NewlineMode-noNewlineTranslation  = NewlineMode { inputNL  = LF, outputNL = LF }---- ------------------------------------------------------------------------------ Show instance for Handles---- handle types are 'show'n when printing error msgs, so--- we provide a more user-friendly Show instance for it--- than the derived one.--instance Show HandleType where-  showsPrec _ t =-    case t of-      ClosedHandle      -> showString "closed"-      SemiClosedHandle  -> showString "semi-closed"-      ReadHandle        -> showString "readable"-      WriteHandle       -> showString "writable"-      AppendHandle      -> showString "writable (append)"-      ReadWriteHandle   -> showString "read-writable"--instance Show Handle where-  showsPrec _ (FileHandle   file _)   = showHandle file-  showsPrec _ (DuplexHandle file _ _) = showHandle file--showHandle :: FilePath -> String -> String-showHandle file = showString "{handle: " . showString file . showString "}"-
− GHC/IO/IOMode.hs
@@ -1,30 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IO.IOMode--- Copyright   :  (c) The University of Glasgow, 1994-2008--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ The IOMode type-----------------------------------------------------------------------------------module GHC.IO.IOMode (IOMode(..)) where--import GHC.Base-import GHC.Show-import GHC.Read-import GHC.Arr-import GHC.Enum---- | See 'System.IO.openFile'-data IOMode      =  ReadMode | WriteMode | AppendMode | ReadWriteMode-                    deriving (Eq, Ord, Ix, Enum, Read, Show)-
− GHC/IOArray.hs
@@ -1,77 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude, AutoDeriveTypeable, RoleAnnotations #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IOArray--- Copyright   :  (c) The University of Glasgow 2008--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The IOArray type-----------------------------------------------------------------------------------module GHC.IOArray (-        IOArray(..),-        newIOArray, unsafeReadIOArray, unsafeWriteIOArray,-        readIOArray, writeIOArray,-        boundsIOArray-    ) where--import GHC.Base-import GHC.IO-import GHC.Arr-import Data.Typeable.Internal---- ------------------------------------------------------------------------------ | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.--- The type arguments are as follows:------  * @i@: the index type of the array (should be an instance of 'Ix')------  * @e@: the element type of the array.--------newtype IOArray i e = IOArray (STArray RealWorld i e) deriving( Typeable )---- index type should have a nominal role due to Ix class. See also #9220.-type role IOArray nominal representational---- explicit instance because Haddock can't figure out a derived one-instance Eq (IOArray i e) where-  IOArray x == IOArray y = x == y---- |Build a new 'IOArray'-newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)-{-# INLINE newIOArray #-}-newIOArray lu initial  = stToIO $ do {marr <- newSTArray lu initial; return (IOArray marr)}---- | Read a value from an 'IOArray'-unsafeReadIOArray  :: Ix i => IOArray i e -> Int -> IO e-{-# INLINE unsafeReadIOArray #-}-unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)---- | Write a new value into an 'IOArray'-unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()-{-# INLINE unsafeWriteIOArray #-}-unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)---- | Read a value from an 'IOArray'-readIOArray  :: Ix i => IOArray i e -> i -> IO e-readIOArray (IOArray marr) i = stToIO (readSTArray marr i)---- | Write a new value into an 'IOArray'-writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()-writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)--{-# INLINE boundsIOArray #-}-boundsIOArray :: IOArray i e -> (i,i)-boundsIOArray (IOArray marr) = boundsSTArray marr-
− GHC/IORef.hs
@@ -1,54 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash, AutoDeriveTypeable #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.IORef--- Copyright   :  (c) The University of Glasgow 2008--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The IORef type-----------------------------------------------------------------------------------module GHC.IORef (-        IORef(..),-        newIORef, readIORef, writeIORef, atomicModifyIORef-    ) where--import GHC.Base-import GHC.STRef-import GHC.IO-import Data.Typeable.Internal( Typeable )---- ------------------------------------------------------------------------------ IORefs---- |A mutable variable in the 'IO' monad-newtype IORef a = IORef (STRef RealWorld a) deriving( Typeable )---- explicit instance because Haddock can't figure out a derived one-instance Eq (IORef a) where-  IORef x == IORef y = x == y---- |Build a new 'IORef'-newIORef    :: a -> IO (IORef a)-newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)---- |Read the value of an 'IORef'-readIORef   :: IORef a -> IO a-readIORef  (IORef var) = stToIO (readSTRef var)---- |Write a new value into an 'IORef'-writeIORef  :: IORef a -> a -> IO ()-writeIORef (IORef var) v = stToIO (writeSTRef var v)--atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b-atomicModifyIORef (IORef (STRef r#)) f = IO $ \s -> atomicModifyMutVar# r# f s-
− GHC/IP.hs
@@ -1,17 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FunctionalDependencies #-}-{-# LANGUAGE KindSignatures #-}-{-# LANGUAGE DataKinds #-}-{-# LANGUAGE NoImplicitPrelude #-}---- | @since 4.6.0.0-module GHC.IP (IP(..)) where--import GHC.TypeLits---- | The syntax @?x :: a@ is desugared into @IP "x" a@-class IP (x :: Symbol) a | x -> a where-  ip :: a--
− GHC/Int.hs
@@ -1,1021 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash, UnboxedTuples,-             StandaloneDeriving, AutoDeriveTypeable, NegativeLiterals #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Int--- Copyright   :  (c) The University of Glasgow 1997-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The sized integral datatypes, 'Int8', 'Int16', 'Int32', and 'Int64'.-----------------------------------------------------------------------------------#include "MachDeps.h"--module GHC.Int (-        Int8(..), Int16(..), Int32(..), Int64(..),-        uncheckedIShiftL64#, uncheckedIShiftRA64#-    ) where--import Data.Bits-import Data.Maybe--#if WORD_SIZE_IN_BITS < 64-import GHC.IntWord64-#endif--import GHC.Base-import GHC.Enum-import GHC.Num-import GHC.Real-import GHC.Read-import GHC.Arr-import GHC.Word hiding (uncheckedShiftL64#, uncheckedShiftRL64#)-import GHC.Show-import Data.Typeable------------------------------------------------------------------------------ type Int8----------------------------------------------------------------------------- Int8 is represented in the same way as Int. Operations may assume--- and must ensure that it holds only values from its logical range.--data {-# CTYPE "HsInt8" #-} Int8 = I8# Int# deriving (Eq, Ord, Typeable)--- ^ 8-bit signed integer type--instance Show Int8 where-    showsPrec p x = showsPrec p (fromIntegral x :: Int)--instance Num Int8 where-    (I8# x#) + (I8# y#)    = I8# (narrow8Int# (x# +# y#))-    (I8# x#) - (I8# y#)    = I8# (narrow8Int# (x# -# y#))-    (I8# x#) * (I8# y#)    = I8# (narrow8Int# (x# *# y#))-    negate (I8# x#)        = I8# (narrow8Int# (negateInt# x#))-    abs x | x >= 0         = x-          | otherwise      = negate x-    signum x | x > 0       = 1-    signum 0               = 0-    signum _               = -1-    fromInteger i          = I8# (narrow8Int# (integerToInt i))--instance Real Int8 where-    toRational x = toInteger x % 1--instance Enum Int8 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Int8"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Int8"-    toEnum i@(I# i#)-        | i >= fromIntegral (minBound::Int8) && i <= fromIntegral (maxBound::Int8)-                        = I8# i#-        | otherwise     = toEnumError "Int8" i (minBound::Int8, maxBound::Int8)-    fromEnum (I8# x#)   = I# x#-    enumFrom            = boundedEnumFrom-    enumFromThen        = boundedEnumFromThen--instance Integral Int8 where-    quot    x@(I8# x#) y@(I8# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I8# (narrow8Int# (x# `quotInt#` y#))-    rem     (I8# x#) y@(I8# y#)-        | y == 0                     = divZeroError-        | otherwise                  = I8# (narrow8Int# (x# `remInt#` y#))-    div     x@(I8# x#) y@(I8# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I8# (narrow8Int# (x# `divInt#` y#))-    mod       (I8# x#) y@(I8# y#)-        | y == 0                     = divZeroError-        | otherwise                  = I8# (narrow8Int# (x# `modInt#` y#))-    quotRem x@(I8# x#) y@(I8# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = case x# `quotRemInt#` y# of-                                       (# q, r #) ->-                                           (I8# (narrow8Int# q),-                                            I8# (narrow8Int# r))-    divMod  x@(I8# x#) y@(I8# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = case x# `divModInt#` y# of-                                       (# d, m #) ->-                                           (I8# (narrow8Int# d),-                                            I8# (narrow8Int# m))-    toInteger (I8# x#)               = smallInteger x#--instance Bounded Int8 where-    minBound = -0x80-    maxBound =  0x7F--instance Ix Int8 where-    range (m,n)         = [m..n]-    unsafeIndex (m,_) i = fromIntegral i - fromIntegral m-    inRange (m,n) i     = m <= i && i <= n--instance Read Int8 where-    readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]--instance Bits Int8 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (I8# x#) .&.   (I8# y#)   = I8# (word2Int# (int2Word# x# `and#` int2Word# y#))-    (I8# x#) .|.   (I8# y#)   = I8# (word2Int# (int2Word# x# `or#`  int2Word# y#))-    (I8# x#) `xor` (I8# y#)   = I8# (word2Int# (int2Word# x# `xor#` int2Word# y#))-    complement (I8# x#)       = I8# (word2Int# (not# (int2Word# x#)))-    (I8# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#) = I8# (narrow8Int# (x# `iShiftL#` i#))-        | otherwise           = I8# (x# `iShiftRA#` negateInt# i#)-    (I8# x#) `shiftL`       (I# i#) = I8# (narrow8Int# (x# `iShiftL#` i#))-    (I8# x#) `unsafeShiftL` (I# i#) = I8# (narrow8Int# (x# `uncheckedIShiftL#` i#))-    (I8# x#) `shiftR`       (I# i#) = I8# (x# `iShiftRA#` i#)-    (I8# x#) `unsafeShiftR` (I# i#) = I8# (x# `uncheckedIShiftRA#` i#)-    (I8# x#) `rotate` (I# i#)-        | isTrue# (i'# ==# 0#)-        = I8# x#-        | otherwise-        = I8# (narrow8Int# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#`-                                       (x'# `uncheckedShiftRL#` (8# -# i'#)))))-        where-        !x'# = narrow8Word# (int2Word# x#)-        !i'# = word2Int# (int2Word# i# `and#` 7##)-    bitSizeMaybe i            = Just (finiteBitSize i)-    bitSize i                 = finiteBitSize i-    isSigned _                = True-    popCount (I8# x#)         = I# (word2Int# (popCnt8# (int2Word# x#)))-    bit                       = bitDefault-    testBit                   = testBitDefault--instance FiniteBits Int8 where-    finiteBitSize _ = 8-    countLeadingZeros  (I8# x#) = I# (word2Int# (clz8# (int2Word# x#)))-    countTrailingZeros (I8# x#) = I# (word2Int# (ctz8# (int2Word# x#)))--{-# RULES-"fromIntegral/Int8->Int8" fromIntegral = id :: Int8 -> Int8-"fromIntegral/a->Int8"    fromIntegral = \x -> case fromIntegral x of I# x# -> I8# (narrow8Int# x#)-"fromIntegral/Int8->a"    fromIntegral = \(I8# x#) -> fromIntegral (I# x#)-  #-}--{-# RULES-"properFraction/Float->(Int8,Float)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Int8) n, y :: Float) }-"truncate/Float->Int8"-    truncate = (fromIntegral :: Int -> Int8) . (truncate :: Float -> Int)-"floor/Float->Int8"-    floor    = (fromIntegral :: Int -> Int8) . (floor :: Float -> Int)-"ceiling/Float->Int8"-    ceiling  = (fromIntegral :: Int -> Int8) . (ceiling :: Float -> Int)-"round/Float->Int8"-    round    = (fromIntegral :: Int -> Int8) . (round  :: Float -> Int)-  #-}--{-# RULES-"properFraction/Double->(Int8,Double)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Int8) n, y :: Double) }-"truncate/Double->Int8"-    truncate = (fromIntegral :: Int -> Int8) . (truncate :: Double -> Int)-"floor/Double->Int8"-    floor    = (fromIntegral :: Int -> Int8) . (floor :: Double -> Int)-"ceiling/Double->Int8"-    ceiling  = (fromIntegral :: Int -> Int8) . (ceiling :: Double -> Int)-"round/Double->Int8"-    round    = (fromIntegral :: Int -> Int8) . (round  :: Double -> Int)-  #-}----------------------------------------------------------------------------- type Int16----------------------------------------------------------------------------- Int16 is represented in the same way as Int. Operations may assume--- and must ensure that it holds only values from its logical range.--data {-# CTYPE "HsInt16" #-} Int16 = I16# Int# deriving (Eq, Ord, Typeable)--- ^ 16-bit signed integer type--instance Show Int16 where-    showsPrec p x = showsPrec p (fromIntegral x :: Int)--instance Num Int16 where-    (I16# x#) + (I16# y#)  = I16# (narrow16Int# (x# +# y#))-    (I16# x#) - (I16# y#)  = I16# (narrow16Int# (x# -# y#))-    (I16# x#) * (I16# y#)  = I16# (narrow16Int# (x# *# y#))-    negate (I16# x#)       = I16# (narrow16Int# (negateInt# x#))-    abs x | x >= 0         = x-          | otherwise      = negate x-    signum x | x > 0       = 1-    signum 0               = 0-    signum _               = -1-    fromInteger i          = I16# (narrow16Int# (integerToInt i))--instance Real Int16 where-    toRational x = toInteger x % 1--instance Enum Int16 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Int16"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Int16"-    toEnum i@(I# i#)-        | i >= fromIntegral (minBound::Int16) && i <= fromIntegral (maxBound::Int16)-                        = I16# i#-        | otherwise     = toEnumError "Int16" i (minBound::Int16, maxBound::Int16)-    fromEnum (I16# x#)  = I# x#-    enumFrom            = boundedEnumFrom-    enumFromThen        = boundedEnumFromThen--instance Integral Int16 where-    quot    x@(I16# x#) y@(I16# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I16# (narrow16Int# (x# `quotInt#` y#))-    rem       (I16# x#) y@(I16# y#)-        | y == 0                     = divZeroError-        | otherwise                  = I16# (narrow16Int# (x# `remInt#` y#))-    div     x@(I16# x#) y@(I16# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I16# (narrow16Int# (x# `divInt#` y#))-    mod       (I16# x#) y@(I16# y#)-        | y == 0                     = divZeroError-        | otherwise                  = I16# (narrow16Int# (x# `modInt#` y#))-    quotRem x@(I16# x#) y@(I16# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = case x# `quotRemInt#` y# of-                                       (# q, r #) ->-                                           (I16# (narrow16Int# q),-                                            I16# (narrow16Int# r))-    divMod  x@(I16# x#) y@(I16# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = case x# `divModInt#` y# of-                                       (# d, m #) ->-                                           (I16# (narrow16Int# d),-                                            I16# (narrow16Int# m))-    toInteger (I16# x#)              = smallInteger x#--instance Bounded Int16 where-    minBound = -0x8000-    maxBound =  0x7FFF--instance Ix Int16 where-    range (m,n)         = [m..n]-    unsafeIndex (m,_) i = fromIntegral i - fromIntegral m-    inRange (m,n) i     = m <= i && i <= n--instance Read Int16 where-    readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]--instance Bits Int16 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (I16# x#) .&.   (I16# y#)  = I16# (word2Int# (int2Word# x# `and#` int2Word# y#))-    (I16# x#) .|.   (I16# y#)  = I16# (word2Int# (int2Word# x# `or#`  int2Word# y#))-    (I16# x#) `xor` (I16# y#)  = I16# (word2Int# (int2Word# x# `xor#` int2Word# y#))-    complement (I16# x#)       = I16# (word2Int# (not# (int2Word# x#)))-    (I16# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)  = I16# (narrow16Int# (x# `iShiftL#` i#))-        | otherwise            = I16# (x# `iShiftRA#` negateInt# i#)-    (I16# x#) `shiftL`       (I# i#) = I16# (narrow16Int# (x# `iShiftL#` i#))-    (I16# x#) `unsafeShiftL` (I# i#) = I16# (narrow16Int# (x# `uncheckedIShiftL#` i#))-    (I16# x#) `shiftR`       (I# i#) = I16# (x# `iShiftRA#` i#)-    (I16# x#) `unsafeShiftR` (I# i#) = I16# (x# `uncheckedIShiftRA#` i#)-    (I16# x#) `rotate` (I# i#)-        | isTrue# (i'# ==# 0#)-        = I16# x#-        | otherwise-        = I16# (narrow16Int# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#`-                                         (x'# `uncheckedShiftRL#` (16# -# i'#)))))-        where-        !x'# = narrow16Word# (int2Word# x#)-        !i'# = word2Int# (int2Word# i# `and#` 15##)-    bitSizeMaybe i             = Just (finiteBitSize i)-    bitSize i                  = finiteBitSize i-    isSigned _                 = True-    popCount (I16# x#)         = I# (word2Int# (popCnt16# (int2Word# x#)))-    bit                        = bitDefault-    testBit                    = testBitDefault--instance FiniteBits Int16 where-    finiteBitSize _ = 16-    countLeadingZeros  (I16# x#) = I# (word2Int# (clz16# (int2Word# x#)))-    countTrailingZeros (I16# x#) = I# (word2Int# (ctz16# (int2Word# x#)))--{-# RULES-"fromIntegral/Word8->Int16"  fromIntegral = \(W8# x#) -> I16# (word2Int# x#)-"fromIntegral/Int8->Int16"   fromIntegral = \(I8# x#) -> I16# x#-"fromIntegral/Int16->Int16"  fromIntegral = id :: Int16 -> Int16-"fromIntegral/a->Int16"      fromIntegral = \x -> case fromIntegral x of I# x# -> I16# (narrow16Int# x#)-"fromIntegral/Int16->a"      fromIntegral = \(I16# x#) -> fromIntegral (I# x#)-  #-}--{-# RULES-"properFraction/Float->(Int16,Float)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Int16) n, y :: Float) }-"truncate/Float->Int16"-    truncate = (fromIntegral :: Int -> Int16) . (truncate :: Float -> Int)-"floor/Float->Int16"-    floor    = (fromIntegral :: Int -> Int16) . (floor :: Float -> Int)-"ceiling/Float->Int16"-    ceiling  = (fromIntegral :: Int -> Int16) . (ceiling :: Float -> Int)-"round/Float->Int16"-    round    = (fromIntegral :: Int -> Int16) . (round  :: Float -> Int)-  #-}--{-# RULES-"properFraction/Double->(Int16,Double)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Int16) n, y :: Double) }-"truncate/Double->Int16"-    truncate = (fromIntegral :: Int -> Int16) . (truncate :: Double -> Int)-"floor/Double->Int16"-    floor    = (fromIntegral :: Int -> Int16) . (floor :: Double -> Int)-"ceiling/Double->Int16"-    ceiling  = (fromIntegral :: Int -> Int16) . (ceiling :: Double -> Int)-"round/Double->Int16"-    round    = (fromIntegral :: Int -> Int16) . (round  :: Double -> Int)-  #-}----------------------------------------------------------------------------- type Int32----------------------------------------------------------------------------- Int32 is represented in the same way as Int.-#if WORD_SIZE_IN_BITS > 32--- Operations may assume and must ensure that it holds only values--- from its logical range.-#endif--data {-# CTYPE "HsInt32" #-} Int32 = I32# Int# deriving (Eq, Ord, Typeable)--- ^ 32-bit signed integer type--instance Show Int32 where-    showsPrec p x = showsPrec p (fromIntegral x :: Int)--instance Num Int32 where-    (I32# x#) + (I32# y#)  = I32# (narrow32Int# (x# +# y#))-    (I32# x#) - (I32# y#)  = I32# (narrow32Int# (x# -# y#))-    (I32# x#) * (I32# y#)  = I32# (narrow32Int# (x# *# y#))-    negate (I32# x#)       = I32# (narrow32Int# (negateInt# x#))-    abs x | x >= 0         = x-          | otherwise      = negate x-    signum x | x > 0       = 1-    signum 0               = 0-    signum _               = -1-    fromInteger i          = I32# (narrow32Int# (integerToInt i))--instance Enum Int32 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Int32"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Int32"-#if WORD_SIZE_IN_BITS == 32-    toEnum (I# i#)      = I32# i#-#else-    toEnum i@(I# i#)-        | i >= fromIntegral (minBound::Int32) && i <= fromIntegral (maxBound::Int32)-                        = I32# i#-        | otherwise     = toEnumError "Int32" i (minBound::Int32, maxBound::Int32)-#endif-    fromEnum (I32# x#)  = I# x#-    enumFrom            = boundedEnumFrom-    enumFromThen        = boundedEnumFromThen--instance Integral Int32 where-    quot    x@(I32# x#) y@(I32# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I32# (narrow32Int# (x# `quotInt#` y#))-    rem       (I32# x#) y@(I32# y#)-        | y == 0                     = divZeroError-          -- The quotRem CPU instruction fails for minBound `quotRem` -1,-          -- but minBound `rem` -1 is well-defined (0). We therefore-          -- special-case it.-        | y == (-1)                  = 0-        | otherwise                  = I32# (narrow32Int# (x# `remInt#` y#))-    div     x@(I32# x#) y@(I32# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I32# (narrow32Int# (x# `divInt#` y#))-    mod       (I32# x#) y@(I32# y#)-        | y == 0                     = divZeroError-          -- The divMod CPU instruction fails for minBound `divMod` -1,-          -- but minBound `mod` -1 is well-defined (0). We therefore-          -- special-case it.-        | y == (-1)                  = 0-        | otherwise                  = I32# (narrow32Int# (x# `modInt#` y#))-    quotRem x@(I32# x#) y@(I32# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = case x# `quotRemInt#` y# of-                                       (# q, r #) ->-                                           (I32# (narrow32Int# q),-                                            I32# (narrow32Int# r))-    divMod  x@(I32# x#) y@(I32# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = case x# `divModInt#` y# of-                                       (# d, m #) ->-                                           (I32# (narrow32Int# d),-                                            I32# (narrow32Int# m))-    toInteger (I32# x#)              = smallInteger x#--instance Read Int32 where-    readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]--instance Bits Int32 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (I32# x#) .&.   (I32# y#)  = I32# (word2Int# (int2Word# x# `and#` int2Word# y#))-    (I32# x#) .|.   (I32# y#)  = I32# (word2Int# (int2Word# x# `or#`  int2Word# y#))-    (I32# x#) `xor` (I32# y#)  = I32# (word2Int# (int2Word# x# `xor#` int2Word# y#))-    complement (I32# x#)       = I32# (word2Int# (not# (int2Word# x#)))-    (I32# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)  = I32# (narrow32Int# (x# `iShiftL#` i#))-        | otherwise            = I32# (x# `iShiftRA#` negateInt# i#)-    (I32# x#) `shiftL`       (I# i#) = I32# (narrow32Int# (x# `iShiftL#` i#))-    (I32# x#) `unsafeShiftL` (I# i#) =-        I32# (narrow32Int# (x# `uncheckedIShiftL#` i#))-    (I32# x#) `shiftR`       (I# i#) = I32# (x# `iShiftRA#` i#)-    (I32# x#) `unsafeShiftR` (I# i#) = I32# (x# `uncheckedIShiftRA#` i#)-    (I32# x#) `rotate` (I# i#)-        | isTrue# (i'# ==# 0#)-        = I32# x#-        | otherwise-        = I32# (narrow32Int# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#`-                                         (x'# `uncheckedShiftRL#` (32# -# i'#)))))-        where-        !x'# = narrow32Word# (int2Word# x#)-        !i'# = word2Int# (int2Word# i# `and#` 31##)-    bitSizeMaybe i             = Just (finiteBitSize i)-    bitSize i                  = finiteBitSize i-    isSigned _                 = True-    popCount (I32# x#)         = I# (word2Int# (popCnt32# (int2Word# x#)))-    bit                        = bitDefault-    testBit                    = testBitDefault--instance FiniteBits Int32 where-    finiteBitSize _ = 32-    countLeadingZeros  (I32# x#) = I# (word2Int# (clz32# (int2Word# x#)))-    countTrailingZeros (I32# x#) = I# (word2Int# (ctz32# (int2Word# x#)))--{-# RULES-"fromIntegral/Word8->Int32"  fromIntegral = \(W8# x#) -> I32# (word2Int# x#)-"fromIntegral/Word16->Int32" fromIntegral = \(W16# x#) -> I32# (word2Int# x#)-"fromIntegral/Int8->Int32"   fromIntegral = \(I8# x#) -> I32# x#-"fromIntegral/Int16->Int32"  fromIntegral = \(I16# x#) -> I32# x#-"fromIntegral/Int32->Int32"  fromIntegral = id :: Int32 -> Int32-"fromIntegral/a->Int32"      fromIntegral = \x -> case fromIntegral x of I# x# -> I32# (narrow32Int# x#)-"fromIntegral/Int32->a"      fromIntegral = \(I32# x#) -> fromIntegral (I# x#)-  #-}--{-# RULES-"properFraction/Float->(Int32,Float)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Int32) n, y :: Float) }-"truncate/Float->Int32"-    truncate = (fromIntegral :: Int -> Int32) . (truncate :: Float -> Int)-"floor/Float->Int32"-    floor    = (fromIntegral :: Int -> Int32) . (floor :: Float -> Int)-"ceiling/Float->Int32"-    ceiling  = (fromIntegral :: Int -> Int32) . (ceiling :: Float -> Int)-"round/Float->Int32"-    round    = (fromIntegral :: Int -> Int32) . (round  :: Float -> Int)-  #-}--{-# RULES-"properFraction/Double->(Int32,Double)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Int32) n, y :: Double) }-"truncate/Double->Int32"-    truncate = (fromIntegral :: Int -> Int32) . (truncate :: Double -> Int)-"floor/Double->Int32"-    floor    = (fromIntegral :: Int -> Int32) . (floor :: Double -> Int)-"ceiling/Double->Int32"-    ceiling  = (fromIntegral :: Int -> Int32) . (ceiling :: Double -> Int)-"round/Double->Int32"-    round    = (fromIntegral :: Int -> Int32) . (round  :: Double -> Int)-  #-}--instance Real Int32 where-    toRational x = toInteger x % 1--instance Bounded Int32 where-    minBound = -0x80000000-    maxBound =  0x7FFFFFFF--instance Ix Int32 where-    range (m,n)         = [m..n]-    unsafeIndex (m,_) i = fromIntegral i - fromIntegral m-    inRange (m,n) i     = m <= i && i <= n----------------------------------------------------------------------------- type Int64---------------------------------------------------------------------------#if WORD_SIZE_IN_BITS < 64--data {-# CTYPE "HsInt64" #-} Int64 = I64# Int64# deriving( Typeable )--- ^ 64-bit signed integer type--instance Eq Int64 where-    (I64# x#) == (I64# y#) = isTrue# (x# `eqInt64#` y#)-    (I64# x#) /= (I64# y#) = isTrue# (x# `neInt64#` y#)--instance Ord Int64 where-    (I64# x#) <  (I64# y#) = isTrue# (x# `ltInt64#` y#)-    (I64# x#) <= (I64# y#) = isTrue# (x# `leInt64#` y#)-    (I64# x#) >  (I64# y#) = isTrue# (x# `gtInt64#` y#)-    (I64# x#) >= (I64# y#) = isTrue# (x# `geInt64#` y#)--instance Show Int64 where-    showsPrec p x = showsPrec p (toInteger x)--instance Num Int64 where-    (I64# x#) + (I64# y#)  = I64# (x# `plusInt64#`  y#)-    (I64# x#) - (I64# y#)  = I64# (x# `minusInt64#` y#)-    (I64# x#) * (I64# y#)  = I64# (x# `timesInt64#` y#)-    negate (I64# x#)       = I64# (negateInt64# x#)-    abs x | x >= 0         = x-          | otherwise      = negate x-    signum x | x > 0       = 1-    signum 0               = 0-    signum _               = -1-    fromInteger i          = I64# (integerToInt64 i)--instance Enum Int64 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Int64"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Int64"-    toEnum (I# i#)      = I64# (intToInt64# i#)-    fromEnum x@(I64# x#)-        | x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)-                        = I# (int64ToInt# x#)-        | otherwise     = fromEnumError "Int64" x-    enumFrom            = integralEnumFrom-    enumFromThen        = integralEnumFromThen-    enumFromTo          = integralEnumFromTo-    enumFromThenTo      = integralEnumFromThenTo--instance Integral Int64 where-    quot    x@(I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I64# (x# `quotInt64#` y#)-    rem       (I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-          -- The quotRem CPU instruction fails for minBound `quotRem` -1,-          -- but minBound `rem` -1 is well-defined (0). We therefore-          -- special-case it.-        | y == (-1)                  = 0-        | otherwise                  = I64# (x# `remInt64#` y#)-    div     x@(I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I64# (x# `divInt64#` y#)-    mod       (I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-          -- The divMod CPU instruction fails for minBound `divMod` -1,-          -- but minBound `mod` -1 is well-defined (0). We therefore-          -- special-case it.-        | y == (-1)                  = 0-        | otherwise                  = I64# (x# `modInt64#` y#)-    quotRem x@(I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = (I64# (x# `quotInt64#` y#),-                                        I64# (x# `remInt64#` y#))-    divMod  x@(I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = (I64# (x# `divInt64#` y#),-                                        I64# (x# `modInt64#` y#))-    toInteger (I64# x)               = int64ToInteger x---divInt64#, modInt64# :: Int64# -> Int64# -> Int64#---- Define div in terms of quot, being careful to avoid overflow (#7233)-x# `divInt64#` y#-    | isTrue# (x# `gtInt64#` zero) && isTrue# (y# `ltInt64#` zero)-        = ((x# `minusInt64#` one) `quotInt64#` y#) `minusInt64#` one-    | isTrue# (x# `ltInt64#` zero) && isTrue# (y# `gtInt64#` zero)-        = ((x# `plusInt64#` one)  `quotInt64#` y#) `minusInt64#` one-    | otherwise-        = x# `quotInt64#` y#-    where-    !zero = intToInt64# 0#-    !one  = intToInt64# 1#--x# `modInt64#` y#-    | isTrue# (x# `gtInt64#` zero) && isTrue# (y# `ltInt64#` zero) ||-      isTrue# (x# `ltInt64#` zero) && isTrue# (y# `gtInt64#` zero)-        = if isTrue# (r# `neInt64#` zero) then r# `plusInt64#` y# else zero-    | otherwise = r#-    where-    !zero = intToInt64# 0#-    !r# = x# `remInt64#` y#--instance Read Int64 where-    readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]--instance Bits Int64 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (I64# x#) .&.   (I64# y#)  = I64# (word64ToInt64# (int64ToWord64# x# `and64#` int64ToWord64# y#))-    (I64# x#) .|.   (I64# y#)  = I64# (word64ToInt64# (int64ToWord64# x# `or64#`  int64ToWord64# y#))-    (I64# x#) `xor` (I64# y#)  = I64# (word64ToInt64# (int64ToWord64# x# `xor64#` int64ToWord64# y#))-    complement (I64# x#)       = I64# (word64ToInt64# (not64# (int64ToWord64# x#)))-    (I64# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)  = I64# (x# `iShiftL64#` i#)-        | otherwise            = I64# (x# `iShiftRA64#` negateInt# i#)-    (I64# x#) `shiftL` (I# i#) = I64# (x# `iShiftL64#` i#)-    (I64# x#) `unsafeShiftL` (I# i#) = I64# (x# `uncheckedIShiftL64#` i#)-    (I64# x#) `shiftR` (I# i#) = I64# (x# `iShiftRA64#` i#)-    (I64# x#) `unsafeShiftR` (I# i#) = I64# (x# `uncheckedIShiftRA64#` i#)-    (I64# x#) `rotate` (I# i#)-        | isTrue# (i'# ==# 0#)-        = I64# x#-        | otherwise-        = I64# (word64ToInt64# ((x'# `uncheckedShiftL64#` i'#) `or64#`-                                (x'# `uncheckedShiftRL64#` (64# -# i'#))))-        where-        !x'# = int64ToWord64# x#-        !i'# = word2Int# (int2Word# i# `and#` 63##)-    bitSizeMaybe i             = Just (finiteBitSize i)-    bitSize i                  = finiteBitSize i-    isSigned _                 = True-    popCount (I64# x#)         =-        I# (word2Int# (popCnt64# (int64ToWord64# x#)))-    bit                        = bitDefault-    testBit                    = testBitDefault---- give the 64-bit shift operations the same treatment as the 32-bit--- ones (see GHC.Base), namely we wrap them in tests to catch the--- cases when we're shifting more than 64 bits to avoid unspecified--- behaviour in the C shift operations.--iShiftL64#, iShiftRA64# :: Int64# -> Int# -> Int64#--a `iShiftL64#` b  | isTrue# (b >=# 64#) = intToInt64# 0#-                  | otherwise           = a `uncheckedIShiftL64#` b--a `iShiftRA64#` b | isTrue# (b >=# 64#) = if isTrue# (a `ltInt64#` (intToInt64# 0#))-                                          then intToInt64# (-1#)-                                          else intToInt64# 0#-                  | otherwise = a `uncheckedIShiftRA64#` b--{-# RULES-"fromIntegral/Int->Int64"    fromIntegral = \(I#   x#) -> I64# (intToInt64# x#)-"fromIntegral/Word->Int64"   fromIntegral = \(W#   x#) -> I64# (word64ToInt64# (wordToWord64# x#))-"fromIntegral/Word64->Int64" fromIntegral = \(W64# x#) -> I64# (word64ToInt64# x#)-"fromIntegral/Int64->Int"    fromIntegral = \(I64# x#) -> I#   (int64ToInt# x#)-"fromIntegral/Int64->Word"   fromIntegral = \(I64# x#) -> W#   (int2Word# (int64ToInt# x#))-"fromIntegral/Int64->Word64" fromIntegral = \(I64# x#) -> W64# (int64ToWord64# x#)-"fromIntegral/Int64->Int64"  fromIntegral = id :: Int64 -> Int64-  #-}---- No RULES for RealFrac methods if Int is smaller than Int64, we can't--- go through Int and whether going through Integer is faster is uncertain.-#else---- Int64 is represented in the same way as Int.--- Operations may assume and must ensure that it holds only values--- from its logical range.--data {-# CTYPE "HsInt64" #-} Int64 = I64# Int# deriving (Eq, Ord, Typeable)--- ^ 64-bit signed integer type--instance Show Int64 where-    showsPrec p x = showsPrec p (fromIntegral x :: Int)--instance Num Int64 where-    (I64# x#) + (I64# y#)  = I64# (x# +# y#)-    (I64# x#) - (I64# y#)  = I64# (x# -# y#)-    (I64# x#) * (I64# y#)  = I64# (x# *# y#)-    negate (I64# x#)       = I64# (negateInt# x#)-    abs x | x >= 0         = x-          | otherwise      = negate x-    signum x | x > 0       = 1-    signum 0               = 0-    signum _               = -1-    fromInteger i          = I64# (integerToInt i)--instance Enum Int64 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Int64"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Int64"-    toEnum (I# i#)      = I64# i#-    fromEnum (I64# x#)  = I# x#-    enumFrom            = boundedEnumFrom-    enumFromThen        = boundedEnumFromThen--instance Integral Int64 where-    quot    x@(I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I64# (x# `quotInt#` y#)-    rem       (I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-          -- The quotRem CPU instruction fails for minBound `quotRem` -1,-          -- but minBound `rem` -1 is well-defined (0). We therefore-          -- special-case it.-        | y == (-1)                  = 0-        | otherwise                  = I64# (x# `remInt#` y#)-    div     x@(I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-        | y == (-1) && x == minBound = overflowError -- Note [Order of tests]-        | otherwise                  = I64# (x# `divInt#` y#)-    mod       (I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-          -- The divMod CPU instruction fails for minBound `divMod` -1,-          -- but minBound `mod` -1 is well-defined (0). We therefore-          -- special-case it.-        | y == (-1)                  = 0-        | otherwise                  = I64# (x# `modInt#` y#)-    quotRem x@(I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = case x# `quotRemInt#` y# of-                                       (# q, r #) ->-                                           (I64# q, I64# r)-    divMod  x@(I64# x#) y@(I64# y#)-        | y == 0                     = divZeroError-          -- Note [Order of tests]-        | y == (-1) && x == minBound = (overflowError, 0)-        | otherwise                  = case x# `divModInt#` y# of-                                       (# d, m #) ->-                                           (I64# d, I64# m)-    toInteger (I64# x#)              = smallInteger x#--instance Read Int64 where-    readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]--instance Bits Int64 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (I64# x#) .&.   (I64# y#)  = I64# (word2Int# (int2Word# x# `and#` int2Word# y#))-    (I64# x#) .|.   (I64# y#)  = I64# (word2Int# (int2Word# x# `or#`  int2Word# y#))-    (I64# x#) `xor` (I64# y#)  = I64# (word2Int# (int2Word# x# `xor#` int2Word# y#))-    complement (I64# x#)       = I64# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))-    (I64# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)  = I64# (x# `iShiftL#` i#)-        | otherwise            = I64# (x# `iShiftRA#` negateInt# i#)-    (I64# x#) `shiftL`       (I# i#) = I64# (x# `iShiftL#` i#)-    (I64# x#) `unsafeShiftL` (I# i#) = I64# (x# `uncheckedIShiftL#` i#)-    (I64# x#) `shiftR`       (I# i#) = I64# (x# `iShiftRA#` i#)-    (I64# x#) `unsafeShiftR` (I# i#) = I64# (x# `uncheckedIShiftRA#` i#)-    (I64# x#) `rotate` (I# i#)-        | isTrue# (i'# ==# 0#)-        = I64# x#-        | otherwise-        = I64# (word2Int# ((x'# `uncheckedShiftL#` i'#) `or#`-                           (x'# `uncheckedShiftRL#` (64# -# i'#))))-        where-        !x'# = int2Word# x#-        !i'# = word2Int# (int2Word# i# `and#` 63##)-    bitSizeMaybe i             = Just (finiteBitSize i)-    bitSize i                  = finiteBitSize i-    isSigned _                 = True-    popCount (I64# x#)         = I# (word2Int# (popCnt64# (int2Word# x#)))-    bit                        = bitDefault-    testBit                    = testBitDefault--{-# RULES-"fromIntegral/a->Int64" fromIntegral = \x -> case fromIntegral x of I# x# -> I64# x#-"fromIntegral/Int64->a" fromIntegral = \(I64# x#) -> fromIntegral (I# x#)-  #-}--{-# RULES-"properFraction/Float->(Int64,Float)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Int64) n, y :: Float) }-"truncate/Float->Int64"-    truncate = (fromIntegral :: Int -> Int64) . (truncate :: Float -> Int)-"floor/Float->Int64"-    floor    = (fromIntegral :: Int -> Int64) . (floor :: Float -> Int)-"ceiling/Float->Int64"-    ceiling  = (fromIntegral :: Int -> Int64) . (ceiling :: Float -> Int)-"round/Float->Int64"-    round    = (fromIntegral :: Int -> Int64) . (round  :: Float -> Int)-  #-}--{-# RULES-"properFraction/Double->(Int64,Double)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Int64) n, y :: Double) }-"truncate/Double->Int64"-    truncate = (fromIntegral :: Int -> Int64) . (truncate :: Double -> Int)-"floor/Double->Int64"-    floor    = (fromIntegral :: Int -> Int64) . (floor :: Double -> Int)-"ceiling/Double->Int64"-    ceiling  = (fromIntegral :: Int -> Int64) . (ceiling :: Double -> Int)-"round/Double->Int64"-    round    = (fromIntegral :: Int -> Int64) . (round  :: Double -> Int)-  #-}--uncheckedIShiftL64# :: Int# -> Int# -> Int#-uncheckedIShiftL64#  = uncheckedIShiftL#--uncheckedIShiftRA64# :: Int# -> Int# -> Int#-uncheckedIShiftRA64# = uncheckedIShiftRA#-#endif--instance FiniteBits Int64 where-    finiteBitSize _ = 64-#if WORD_SIZE_IN_BITS < 64-    countLeadingZeros  (I64# x#) = I# (word2Int# (clz64# (int64ToWord64# x#)))-    countTrailingZeros (I64# x#) = I# (word2Int# (ctz64# (int64ToWord64# x#)))-#else-    countLeadingZeros  (I64# x#) = I# (word2Int# (clz64# (int2Word# x#)))-    countTrailingZeros (I64# x#) = I# (word2Int# (ctz64# (int2Word# x#)))-#endif--instance Real Int64 where-    toRational x = toInteger x % 1--instance Bounded Int64 where-    minBound = -0x8000000000000000-    maxBound =  0x7FFFFFFFFFFFFFFF--instance Ix Int64 where-    range (m,n)         = [m..n]-    unsafeIndex (m,_) i = fromIntegral i - fromIntegral m-    inRange (m,n) i     = m <= i && i <= n---{- Note [Order of tests]-~~~~~~~~~~~~~~~~~~~~~~~~~-(See Trac #3065, #5161.) Suppose we had a definition like:--    quot x y-     | y == 0                     = divZeroError-     | x == minBound && y == (-1) = overflowError-     | otherwise                  = x `primQuot` y--Note in particular that the-    x == minBound-test comes before the-    y == (-1)-test.--this expands to something like:--    case y of-    0 -> divZeroError-    _ -> case x of-         -9223372036854775808 ->-             case y of-             -1 -> overflowError-             _ -> x `primQuot` y-         _ -> x `primQuot` y--Now if we have the call (x `quot` 2), and quot gets inlined, then we get:--    case 2 of-    0 -> divZeroError-    _ -> case x of-         -9223372036854775808 ->-             case 2 of-             -1 -> overflowError-             _ -> x `primQuot` 2-         _ -> x `primQuot` 2--which simplifies to:--    case x of-    -9223372036854775808 -> x `primQuot` 2-    _                    -> x `primQuot` 2--Now we have a case with two identical branches, which would be-eliminated (assuming it doesn't affect strictness, which it doesn't in-this case), leaving the desired:--    x `primQuot` 2--except in the minBound branch we know what x is, and GHC cleverly does-the division at compile time, giving:--    case x of-    -9223372036854775808 -> -4611686018427387904-    _                    -> x `primQuot` 2--So instead we use a definition like:--    quot x y-     | y == 0                     = divZeroError-     | y == (-1) && x == minBound = overflowError-     | otherwise                  = x `primQuot` y--which gives us:--    case y of-    0 -> divZeroError-    -1 ->-        case x of-        -9223372036854775808 -> overflowError-        _ -> x `primQuot` y-    _ -> x `primQuot` y--for which our call (x `quot` 2) expands to:--    case 2 of-    0 -> divZeroError-    -1 ->-        case x of-        -9223372036854775808 -> overflowError-        _ -> x `primQuot` 2-    _ -> x `primQuot` 2--which simplifies to:--    x `primQuot` 2--as required.----But we now have the same problem with a constant numerator: the call-(2 `quot` y) expands to--    case y of-    0 -> divZeroError-    -1 ->-        case 2 of-        -9223372036854775808 -> overflowError-        _ -> 2 `primQuot` y-    _ -> 2 `primQuot` y--which simplifies to:--    case y of-    0 -> divZeroError-    -1 -> 2 `primQuot` y-    _ -> 2 `primQuot` y--which simplifies to:--    case y of-    0 -> divZeroError-    -1 -> -2-    _ -> 2 `primQuot` y---However, constant denominators are more common than constant numerators,-so the-    y == (-1) && x == minBound-order gives us better code in the common case.--}
− GHC/List.hs
@@ -1,1014 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, ScopedTypeVariables, MagicHash #-}-{-# LANGUAGE BangPatterns #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.List--- Copyright   :  (c) The University of Glasgow 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The List data type and its operations-----------------------------------------------------------------------------------module GHC.List (-   -- [] (..),          -- built-in syntax; can't be used in export list--   map, (++), filter, concat,-   head, last, tail, init, uncons, null, length, (!!),-   foldl, foldl', foldl1, foldl1', scanl, scanl1, scanl', foldr, foldr1,-   scanr, scanr1, iterate, repeat, replicate, cycle,-   take, drop, sum, product, maximum, minimum, splitAt, takeWhile, dropWhile,-   span, break, reverse, and, or,-   any, all, elem, notElem, lookup,-   concatMap,-   zip, zip3, zipWith, zipWith3, unzip, unzip3,-   errorEmptyList,-- ) where--import Data.Maybe-import GHC.Base-import GHC.Num (Num(..))-import GHC.Integer (Integer)--infixl 9  !!-infix  4 `elem`, `notElem`------------------------------------------------------------------- List-manipulation functions------------------------------------------------------------------- | Extract the first element of a list, which must be non-empty.-head                    :: [a] -> a-head (x:_)              =  x-head []                 =  badHead-{-# NOINLINE [1] head #-}--badHead :: a-badHead = errorEmptyList "head"---- This rule is useful in cases like---      head [y | (x,y) <- ps, x==t]-{-# RULES-"head/build"    forall (g::forall b.(a->b->b)->b->b) .-                head (build g) = g (\x _ -> x) badHead-"head/augment"  forall xs (g::forall b. (a->b->b) -> b -> b) .-                head (augment g xs) = g (\x _ -> x) (head xs)- #-}---- | Decompose a list into its head and tail. If the list is empty,--- returns 'Nothing'. If the list is non-empty, returns @'Just' (x, xs)@,--- where @x@ is the head of the list and @xs@ its tail.------ @since 4.8.0.0-uncons                  :: [a] -> Maybe (a, [a])-uncons []               = Nothing-uncons (x:xs)           = Just (x, xs)---- | Extract the elements after the head of a list, which must be non-empty.-tail                    :: [a] -> [a]-tail (_:xs)             =  xs-tail []                 =  errorEmptyList "tail"---- | Extract the last element of a list, which must be finite and non-empty.-last                    :: [a] -> a-#ifdef USE_REPORT_PRELUDE-last [x]                =  x-last (_:xs)             =  last xs-last []                 =  errorEmptyList "last"-#else--- Use foldl to make last a good consumer.--- This will compile to good code for the actual GHC.List.last.--- (At least as long it is eta-expaned, otherwise it does not, #10260.)-last xs = foldl (\_ x -> x) lastError xs-{-# INLINE last #-}--- The inline pragma is required to make GHC remember the implementation via--- foldl.-lastError :: a-lastError = errorEmptyList "last"-#endif---- | Return all the elements of a list except the last one.--- The list must be non-empty.-init                    :: [a] -> [a]-#ifdef USE_REPORT_PRELUDE-init [x]                =  []-init (x:xs)             =  x : init xs-init []                 =  errorEmptyList "init"-#else--- eliminate repeated cases-init []                 =  errorEmptyList "init"-init (x:xs)             =  init' x xs-  where init' _ []     = []-        init' y (z:zs) = y : init' z zs-#endif---- | Test whether a list is empty.-null                    :: [a] -> Bool-null []                 =  True-null (_:_)              =  False---- | /O(n)/. 'length' returns the length of a finite list as an 'Int'.--- It is an instance of the more general 'Data.List.genericLength',--- the result type of which may be any kind of number.-{-# NOINLINE [1] length #-}-length                  :: [a] -> Int-length xs               = lenAcc xs 0--lenAcc          :: [a] -> Int -> Int-lenAcc []     n = n-lenAcc (_:ys) n = lenAcc ys (n+1)--{-# RULES-"length" [~1] forall xs . length xs = foldr lengthFB idLength xs 0-"lengthList" [1] foldr lengthFB idLength = lenAcc- #-}---- The lambda form turns out to be necessary to make this inline--- when we need it to and give good performance.-{-# INLINE [0] lengthFB #-}-lengthFB :: x -> (Int -> Int) -> Int -> Int-lengthFB _ r = \ !a -> r (a + 1)--{-# INLINE [0] idLength #-}-idLength :: Int -> Int-idLength = id---- | 'filter', applied to a predicate and a list, returns the list of--- those elements that satisfy the predicate; i.e.,------ > filter p xs = [ x | x <- xs, p x]--{-# NOINLINE [1] filter #-}-filter :: (a -> Bool) -> [a] -> [a]-filter _pred []    = []-filter pred (x:xs)-  | pred x         = x : filter pred xs-  | otherwise      = filter pred xs--{-# NOINLINE [0] filterFB #-}-filterFB :: (a -> b -> b) -> (a -> Bool) -> a -> b -> b-filterFB c p x r | p x       = x `c` r-                 | otherwise = r--{-# RULES-"filter"     [~1] forall p xs.  filter p xs = build (\c n -> foldr (filterFB c p) n xs)-"filterList" [1]  forall p.     foldr (filterFB (:) p) [] = filter p-"filterFB"        forall c p q. filterFB (filterFB c p) q = filterFB c (\x -> q x && p x)- #-}---- Note the filterFB rule, which has p and q the "wrong way round" in the RHS.---     filterFB (filterFB c p) q a b---   = if q a then filterFB c p a b else b---   = if q a then (if p a then c a b else b) else b---   = if q a && p a then c a b else b---   = filterFB c (\x -> q x && p x) a b--- I originally wrote (\x -> p x && q x), which is wrong, and actually--- gave rise to a live bug report.  SLPJ.----- | 'foldl', applied to a binary operator, a starting value (typically--- the left-identity of the operator), and a list, reduces the list--- using the binary operator, from left to right:------ > foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn------ The list must be finite.---- We write foldl as a non-recursive thing, so that it--- can be inlined, and then (often) strictness-analysed,--- and hence the classic space leak on foldl (+) 0 xs--foldl :: forall a b. (b -> a -> b) -> b -> [a] -> b-{-# INLINE foldl #-}-foldl k z0 xs =-  foldr (\(v::a) (fn::b->b) -> oneShot (\(z::b) -> fn (k z v))) (id :: b -> b) xs z0-  -- See Note [Left folds via right fold]--{--Note [Left folds via right fold]--Implementing foldl et. al. via foldr is only a good idea if the compiler can-optimize the resulting code (eta-expand the recursive "go"). See #7994.-We hope that one of the two measure kick in:--   * Call Arity (-fcall-arity, enabled by default) eta-expands it if it can see-     all calls and determine that the arity is large.-   * The oneShot annotation gives a hint to the regular arity analysis that-     it may assume that the lambda is called at most once.-     See [One-shot lambdas] in CoreArity and especially [Eta expanding thunks]-     in CoreArity.--The oneShot annotations used in this module are correct, as we only use them in-argumets to foldr, where we know how the arguments are called.--}---- -------------------------------------------------------------------------------- | A strict version of 'foldl'.-foldl'           :: forall a b . (b -> a -> b) -> b -> [a] -> b-{-# INLINE foldl' #-}-foldl' k z0 xs =-  foldr (\(v::a) (fn::b->b) -> oneShot (\(z::b) -> z `seq` fn (k z v))) (id :: b -> b) xs z0-  -- See Note [Left folds via right fold]---- | 'foldl1' is a variant of 'foldl' that has no starting value argument,--- and thus must be applied to non-empty lists.-foldl1                  :: (a -> a -> a) -> [a] -> a-foldl1 f (x:xs)         =  foldl f x xs-foldl1 _ []             =  errorEmptyList "foldl1"---- | A strict version of 'foldl1'-foldl1'                  :: (a -> a -> a) -> [a] -> a-foldl1' f (x:xs)         =  foldl' f x xs-foldl1' _ []             =  errorEmptyList "foldl1'"---- -------------------------------------------------------------------------------- List sum and product---- | The 'sum' function computes the sum of a finite list of numbers.-sum                     :: (Num a) => [a] -> a-{-# INLINE sum #-}-sum                     =  foldl (+) 0---- | The 'product' function computes the product of a finite list of numbers.-product                 :: (Num a) => [a] -> a-{-# INLINE product #-}-product                 =  foldl (*) 1---- | 'scanl' is similar to 'foldl', but returns a list of successive--- reduced values from the left:------ > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]------ Note that------ > last (scanl f z xs) == foldl f z xs.---- This peculiar arrangement is necessary to prevent scanl being rewritten in--- its own right-hand side.-{-# NOINLINE [1] scanl #-}-scanl                   :: (b -> a -> b) -> b -> [a] -> [b]-scanl                   = scanlGo-  where-    scanlGo           :: (b -> a -> b) -> b -> [a] -> [b]-    scanlGo f q ls    = q : (case ls of-                               []   -> []-                               x:xs -> scanlGo f (f q x) xs)---- Note [scanl rewrite rules]-{-# RULES-"scanl"  [~1] forall f a bs . scanl f a bs =-  build (\c n -> a `c` foldr (scanlFB f c) (constScanl n) bs a)-"scanlList" [1] forall f (a::a) bs .-    foldr (scanlFB f (:)) (constScanl []) bs a = tail (scanl f a bs)- #-}--{-# INLINE [0] scanlFB #-}-scanlFB :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c-scanlFB f c = \b g -> oneShot (\x -> let b' = f x b in b' `c` g b')-  -- See Note [Left folds via right fold]--{-# INLINE [0] constScanl #-}-constScanl :: a -> b -> a-constScanl = const----- | 'scanl1' is a variant of 'scanl' that has no starting value argument:------ > scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]--scanl1                  :: (a -> a -> a) -> [a] -> [a]-scanl1 f (x:xs)         =  scanl f x xs-scanl1 _ []             =  []---- | A strictly accumulating version of 'scanl'-{-# NOINLINE [1] scanl' #-}-scanl'           :: (b -> a -> b) -> b -> [a] -> [b]--- This peculiar form is needed to prevent scanl' from being rewritten--- in its own right hand side.-scanl' = scanlGo'-  where-    scanlGo'           :: (b -> a -> b) -> b -> [a] -> [b]-    scanlGo' f !q ls    = q : (case ls of-                            []   -> []-                            x:xs -> scanlGo' f (f q x) xs)---- Note [scanl rewrite rules]-{-# RULES-"scanl'"  [~1] forall f a bs . scanl' f a bs =-  build (\c n -> a `c` foldr (scanlFB' f c) (flipSeqScanl' n) bs a)-"scanlList'" [1] forall f a bs .-    foldr (scanlFB' f (:)) (flipSeqScanl' []) bs a = tail (scanl' f a bs)- #-}--{-# INLINE [0] scanlFB' #-}-scanlFB' :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c-scanlFB' f c = \b g -> oneShot (\x -> let !b' = f x b in b' `c` g b')-  -- See Note [Left folds via right fold]--{-# INLINE [0] flipSeqScanl' #-}-flipSeqScanl' :: a -> b -> a-flipSeqScanl' a !_b = a--{--Note [scanl rewrite rules]-~~~~~~~~~~~~~~~~~~~~~~~~~~--In most cases, when we rewrite a form to one that can fuse, we try to rewrite it-back to the original form if it does not fuse. For scanl, we do something a-little different. In particular, we rewrite--scanl f a bs--to--build (\c n -> a `c` foldr (scanlFB f c) (constScanl n) bs a)--When build is inlined, this becomes--a : foldr (scanlFB f (:)) (constScanl []) bs a--To rewrite this form back to scanl, we would need a rule that looked like--forall f a bs. a : foldr (scanlFB f (:)) (constScanl []) bs a = scanl f a bs--The problem with this rule is that it has (:) at its head. This would have the-effect of changing the way the inliner looks at (:), not only here but-everywhere.  In most cases, this makes no difference, but in some cases it-causes it to come to a different decision about whether to inline something.-Based on nofib benchmarks, this is bad for performance. Therefore, we instead-match on everything past the :, which is just the tail of scanl.--}---- foldr, foldr1, scanr, and scanr1 are the right-to-left duals of the--- above functions.---- | 'foldr1' is a variant of 'foldr' that has no starting value argument,--- and thus must be applied to non-empty lists.--foldr1                  :: (a -> a -> a) -> [a] -> a-foldr1 f = go-  where go [x]            =  x-        go (x:xs)         =  f x (go xs)-        go []             =  errorEmptyList "foldr1"-{-# INLINE [0] foldr1 #-}---- | 'scanr' is the right-to-left dual of 'scanl'.--- Note that------ > head (scanr f z xs) == foldr f z xs.-{-# NOINLINE [1] scanr #-}-scanr                   :: (a -> b -> b) -> b -> [a] -> [b]-scanr _ q0 []           =  [q0]-scanr f q0 (x:xs)       =  f x q : qs-                           where qs@(q:_) = scanr f q0 xs--{-# INLINE [0] strictUncurryScanr #-}-strictUncurryScanr :: (a -> b -> c) -> (a, b) -> c-strictUncurryScanr f pair = case pair of-                              (x, y) -> f x y--{-# INLINE [0] scanrFB #-}-scanrFB :: (a -> b -> b) -> (b -> c -> c) -> a -> (b, c) -> (b, c)-scanrFB f c = \x (r, est) -> (f x r, r `c` est)--{-# RULES-"scanr" [~1] forall f q0 ls . scanr f q0 ls =-  build (\c n -> strictUncurryScanr c (foldr (scanrFB f c) (q0,n) ls))-"scanrList" [1] forall f q0 ls .-               strictUncurryScanr (:) (foldr (scanrFB f (:)) (q0,[]) ls) =-                 scanr f q0 ls- #-}---- | 'scanr1' is a variant of 'scanr' that has no starting value argument.-scanr1                  :: (a -> a -> a) -> [a] -> [a]-scanr1 _ []             =  []-scanr1 _ [x]            =  [x]-scanr1 f (x:xs)         =  f x q : qs-                           where qs@(q:_) = scanr1 f xs---- | 'maximum' returns the maximum value from a list,--- which must be non-empty, finite, and of an ordered type.--- It is a special case of 'Data.List.maximumBy', which allows the--- programmer to supply their own comparison function.-maximum                 :: (Ord a) => [a] -> a-{-# INLINE [1] maximum #-}-maximum []              =  errorEmptyList "maximum"-maximum xs              =  foldl1 max xs--{-# RULES-  "maximumInt"     maximum = (strictMaximum :: [Int]     -> Int);-  "maximumInteger" maximum = (strictMaximum :: [Integer] -> Integer)- #-}---- We can't make the overloaded version of maximum strict without--- changing its semantics (max might not be strict), but we can for--- the version specialised to 'Int'.-strictMaximum           :: (Ord a) => [a] -> a-strictMaximum []        =  errorEmptyList "maximum"-strictMaximum xs        =  foldl1' max xs---- | 'minimum' returns the minimum value from a list,--- which must be non-empty, finite, and of an ordered type.--- It is a special case of 'Data.List.minimumBy', which allows the--- programmer to supply their own comparison function.-minimum                 :: (Ord a) => [a] -> a-{-# INLINE [1] minimum #-}-minimum []              =  errorEmptyList "minimum"-minimum xs              =  foldl1 min xs--{-# RULES-  "minimumInt"     minimum = (strictMinimum :: [Int]     -> Int);-  "minimumInteger" minimum = (strictMinimum :: [Integer] -> Integer)- #-}--strictMinimum           :: (Ord a) => [a] -> a-strictMinimum []        =  errorEmptyList "minimum"-strictMinimum xs        =  foldl1' min xs----- | 'iterate' @f x@ returns an infinite list of repeated applications--- of @f@ to @x@:------ > iterate f x == [x, f x, f (f x), ...]--{-# NOINLINE [1] iterate #-}-iterate :: (a -> a) -> a -> [a]-iterate f x =  x : iterate f (f x)--{-# NOINLINE [0] iterateFB #-}-iterateFB :: (a -> b -> b) -> (a -> a) -> a -> b-iterateFB c f x0 = go x0-  where go x = x `c` go (f x)--{-# RULES-"iterate"    [~1] forall f x.   iterate f x = build (\c _n -> iterateFB c f x)-"iterateFB"  [1]                iterateFB (:) = iterate- #-}----- | 'repeat' @x@ is an infinite list, with @x@ the value of every element.-repeat :: a -> [a]-{-# INLINE [0] repeat #-}--- The pragma just gives the rules more chance to fire-repeat x = xs where xs = x : xs--{-# INLINE [0] repeatFB #-}     -- ditto-repeatFB :: (a -> b -> b) -> a -> b-repeatFB c x = xs where xs = x `c` xs---{-# RULES-"repeat"    [~1] forall x. repeat x = build (\c _n -> repeatFB c x)-"repeatFB"  [1]  repeatFB (:)       = repeat- #-}---- | 'replicate' @n x@ is a list of length @n@ with @x@ the value of--- every element.--- It is an instance of the more general 'Data.List.genericReplicate',--- in which @n@ may be of any integral type.-{-# INLINE replicate #-}-replicate               :: Int -> a -> [a]-replicate n x           =  take n (repeat x)---- | 'cycle' ties a finite list into a circular one, or equivalently,--- the infinite repetition of the original list.  It is the identity--- on infinite lists.--cycle                   :: [a] -> [a]-cycle []                = errorEmptyList "cycle"-cycle xs                = xs' where xs' = xs ++ xs'---- | 'takeWhile', applied to a predicate @p@ and a list @xs@, returns the--- longest prefix (possibly empty) of @xs@ of elements that satisfy @p@:------ > takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]--- > takeWhile (< 9) [1,2,3] == [1,2,3]--- > takeWhile (< 0) [1,2,3] == []-----{-# NOINLINE [1] takeWhile #-}-takeWhile               :: (a -> Bool) -> [a] -> [a]-takeWhile _ []          =  []-takeWhile p (x:xs)-            | p x       =  x : takeWhile p xs-            | otherwise =  []--{-# INLINE [0] takeWhileFB #-}-takeWhileFB :: (a -> Bool) -> (a -> b -> b) -> b -> a -> b -> b-takeWhileFB p c n = \x r -> if p x then x `c` r else n---- The takeWhileFB rule is similar to the filterFB rule. It works like this:--- takeWhileFB q (takeWhileFB p c n) n =--- \x r -> if q x then (takeWhileFB p c n) x r else n =--- \x r -> if q x then (\x' r' -> if p x' then x' `c` r' else n) x r else n =--- \x r -> if q x then (if p x then x `c` r else n) else n =--- \x r -> if q x && p x then x `c` r else n =--- takeWhileFB (\x -> q x && p x) c n-{-# RULES-"takeWhile"     [~1] forall p xs. takeWhile p xs =-                                build (\c n -> foldr (takeWhileFB p c n) n xs)-"takeWhileList" [1]  forall p.    foldr (takeWhileFB p (:) []) [] = takeWhile p-"takeWhileFB"        forall c n p q. takeWhileFB q (takeWhileFB p c n) n =-                        takeWhileFB (\x -> q x && p x) c n- #-}---- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@:------ > dropWhile (< 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]--- > dropWhile (< 9) [1,2,3] == []--- > dropWhile (< 0) [1,2,3] == [1,2,3]-----dropWhile               :: (a -> Bool) -> [a] -> [a]-dropWhile _ []          =  []-dropWhile p xs@(x:xs')-            | p x       =  dropWhile p xs'-            | otherwise =  xs---- | 'take' @n@, applied to a list @xs@, returns the prefix of @xs@--- of length @n@, or @xs@ itself if @n > 'length' xs@:------ > take 5 "Hello World!" == "Hello"--- > take 3 [1,2,3,4,5] == [1,2,3]--- > take 3 [1,2] == [1,2]--- > take 3 [] == []--- > take (-1) [1,2] == []--- > take 0 [1,2] == []------ It is an instance of the more general 'Data.List.genericTake',--- in which @n@ may be of any integral type.-take                   :: Int -> [a] -> [a]-#ifdef USE_REPORT_PRELUDE-take n _      | n <= 0 =  []-take _ []              =  []-take n (x:xs)          =  x : take (n-1) xs-#else--{- We always want to inline this to take advantage of a known length argument-sign. Note, however, that it's important for the RULES to grab take, rather-than trying to INLINE take immediately and then letting the RULES grab-unsafeTake. Presumably the latter approach doesn't grab it early enough; it led-to an allocation regression in nofib/fft2. -}-{-# INLINE [1] take #-}-take n xs | 0 < n     = unsafeTake n xs-          | otherwise = []---- A version of take that takes the whole list if it's given an argument less--- than 1.-{-# NOINLINE [1] unsafeTake #-}-unsafeTake :: Int -> [a] -> [a]-unsafeTake !_  []     = []-unsafeTake 1   (x: _) = [x]-unsafeTake m   (x:xs) = x : unsafeTake (m - 1) xs--{-# RULES-"take"     [~1] forall n xs . take n xs =-  build (\c nil -> if 0 < n-                   then foldr (takeFB c nil) (flipSeqTake nil) xs n-                   else nil)-"unsafeTakeList"  [1] forall n xs . foldr (takeFB (:) []) (flipSeqTake []) xs n-                                        = unsafeTake n xs- #-}--{-# INLINE [0] flipSeqTake #-}--- Just flip seq, specialized to Int, but not inlined too early.--- It's important to force the numeric argument here, even though--- it's not used. Otherwise, take n [] doesn't force n. This is--- bad for strictness analysis and unboxing, and leads to increased--- allocation in T7257.-flipSeqTake :: a -> Int -> a-flipSeqTake x !_n = x--{-# INLINE [0] takeFB #-}-takeFB :: (a -> b -> b) -> b -> a -> (Int -> b) -> Int -> b--- The \m accounts for the fact that takeFB is used in a higher-order--- way by takeFoldr, so it's better to inline.  A good example is---     take n (repeat x)--- for which we get excellent code... but only if we inline takeFB--- when given four arguments-takeFB c n x xs-  = \ m -> case m of-            1 -> x `c` n-            _ -> x `c` xs (m - 1)-#endif---- | 'drop' @n xs@ returns the suffix of @xs@--- after the first @n@ elements, or @[]@ if @n > 'length' xs@:------ > drop 6 "Hello World!" == "World!"--- > drop 3 [1,2,3,4,5] == [4,5]--- > drop 3 [1,2] == []--- > drop 3 [] == []--- > drop (-1) [1,2] == [1,2]--- > drop 0 [1,2] == [1,2]------ It is an instance of the more general 'Data.List.genericDrop',--- in which @n@ may be of any integral type.-drop                   :: Int -> [a] -> [a]-#ifdef USE_REPORT_PRELUDE-drop n xs     | n <= 0 =  xs-drop _ []              =  []-drop n (_:xs)          =  drop (n-1) xs-#else /* hack away */-{-# INLINE drop #-}-drop n ls-  | n <= 0     = ls-  | otherwise  = unsafeDrop n ls-  where-    -- A version of drop that drops the whole list if given an argument-    -- less than 1-    unsafeDrop :: Int -> [a] -> [a]-    unsafeDrop !_ []     = []-    unsafeDrop 1  (_:xs) = xs-    unsafeDrop m  (_:xs) = unsafeDrop (m - 1) xs-#endif---- | 'splitAt' @n xs@ returns a tuple where first element is @xs@ prefix of--- length @n@ and second element is the remainder of the list:------ > splitAt 6 "Hello World!" == ("Hello ","World!")--- > splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])--- > splitAt 1 [1,2,3] == ([1],[2,3])--- > splitAt 3 [1,2,3] == ([1,2,3],[])--- > splitAt 4 [1,2,3] == ([1,2,3],[])--- > splitAt 0 [1,2,3] == ([],[1,2,3])--- > splitAt (-1) [1,2,3] == ([],[1,2,3])------ It is equivalent to @('take' n xs, 'drop' n xs)@ when @n@ is not @_|_@--- (@splitAt _|_ xs = _|_@).--- 'splitAt' is an instance of the more general 'Data.List.genericSplitAt',--- in which @n@ may be of any integral type.-splitAt                :: Int -> [a] -> ([a],[a])--#ifdef USE_REPORT_PRELUDE-splitAt n xs           =  (take n xs, drop n xs)-#else-splitAt n ls-  | n <= 0 = ([], ls)-  | otherwise          = splitAt' n ls-    where-        splitAt' :: Int -> [a] -> ([a], [a])-        splitAt' _  []     = ([], [])-        splitAt' 1  (x:xs) = ([x], xs)-        splitAt' m  (x:xs) = (x:xs', xs'')-          where-            (xs', xs'') = splitAt' (m - 1) xs-#endif /* USE_REPORT_PRELUDE */---- | 'span', applied to a predicate @p@ and a list @xs@, returns a tuple where--- first element is longest prefix (possibly empty) of @xs@ of elements that--- satisfy @p@ and second element is the remainder of the list:------ > span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])--- > span (< 9) [1,2,3] == ([1,2,3],[])--- > span (< 0) [1,2,3] == ([],[1,2,3])------ 'span' @p xs@ is equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@--span                    :: (a -> Bool) -> [a] -> ([a],[a])-span _ xs@[]            =  (xs, xs)-span p xs@(x:xs')-         | p x          =  let (ys,zs) = span p xs' in (x:ys,zs)-         | otherwise    =  ([],xs)---- | 'break', applied to a predicate @p@ and a list @xs@, returns a tuple where--- first element is longest prefix (possibly empty) of @xs@ of elements that--- /do not satisfy/ @p@ and second element is the remainder of the list:------ > break (> 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])--- > break (< 9) [1,2,3] == ([],[1,2,3])--- > break (> 9) [1,2,3] == ([1,2,3],[])------ 'break' @p@ is equivalent to @'span' ('not' . p)@.--break                   :: (a -> Bool) -> [a] -> ([a],[a])-#ifdef USE_REPORT_PRELUDE-break p                 =  span (not . p)-#else--- HBC version (stolen)-break _ xs@[]           =  (xs, xs)-break p xs@(x:xs')-           | p x        =  ([],xs)-           | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)-#endif---- | 'reverse' @xs@ returns the elements of @xs@ in reverse order.--- @xs@ must be finite.-reverse                 :: [a] -> [a]-#ifdef USE_REPORT_PRELUDE-reverse                 =  foldl (flip (:)) []-#else-reverse l =  rev l []-  where-    rev []     a = a-    rev (x:xs) a = rev xs (x:a)-#endif---- | 'and' returns the conjunction of a Boolean list.  For the result to be--- 'True', the list must be finite; 'False', however, results from a 'False'--- value at a finite index of a finite or infinite list.-and                     :: [Bool] -> Bool-#ifdef USE_REPORT_PRELUDE-and                     =  foldr (&&) True-#else-and []          =  True-and (x:xs)      =  x && and xs-{-# NOINLINE [1] and #-}--{-# RULES-"and/build"     forall (g::forall b.(Bool->b->b)->b->b) .-                and (build g) = g (&&) True- #-}-#endif---- | 'or' returns the disjunction of a Boolean list.  For the result to be--- 'False', the list must be finite; 'True', however, results from a 'True'--- value at a finite index of a finite or infinite list.-or                      :: [Bool] -> Bool-#ifdef USE_REPORT_PRELUDE-or                      =  foldr (||) False-#else-or []           =  False-or (x:xs)       =  x || or xs-{-# NOINLINE [1] or #-}--{-# RULES-"or/build"      forall (g::forall b.(Bool->b->b)->b->b) .-                or (build g) = g (||) False- #-}-#endif---- | Applied to a predicate and a list, 'any' determines if any element--- of the list satisfies the predicate.  For the result to be--- 'False', the list must be finite; 'True', however, results from a 'True'--- value for the predicate applied to an element at a finite index of a finite or infinite list.-any                     :: (a -> Bool) -> [a] -> Bool--#ifdef USE_REPORT_PRELUDE-any p                   =  or . map p-#else-any _ []        = False-any p (x:xs)    = p x || any p xs--{-# NOINLINE [1] any #-}--{-# RULES-"any/build"     forall p (g::forall b.(a->b->b)->b->b) .-                any p (build g) = g ((||) . p) False- #-}-#endif---- | Applied to a predicate and a list, 'all' determines if all elements--- of the list satisfy the predicate. For the result to be--- 'True', the list must be finite; 'False', however, results from a 'False'--- value for the predicate applied to an element at a finite index of a finite or infinite list.-all                     :: (a -> Bool) -> [a] -> Bool-#ifdef USE_REPORT_PRELUDE-all p                   =  and . map p-#else-all _ []        =  True-all p (x:xs)    =  p x && all p xs--{-# NOINLINE [1] all #-}--{-# RULES-"all/build"     forall p (g::forall b.(a->b->b)->b->b) .-                all p (build g) = g ((&&) . p) True- #-}-#endif---- | 'elem' is the list membership predicate, usually written in infix form,--- e.g., @x \`elem\` xs@.  For the result to be--- 'False', the list must be finite; 'True', however, results from an element--- equal to @x@ found at a finite index of a finite or infinite list.-elem                    :: (Eq a) => a -> [a] -> Bool-#ifdef USE_REPORT_PRELUDE-elem x                  =  any (== x)-#else-elem _ []       = False-elem x (y:ys)   = x==y || elem x ys-{-# NOINLINE [1] elem #-}-{-# RULES-"elem/build"    forall x (g :: forall b . Eq a => (a -> b -> b) -> b -> b)-   . elem x (build g) = g (\ y r -> (x == y) || r) False- #-}-#endif---- | 'notElem' is the negation of 'elem'.-notElem                 :: (Eq a) => a -> [a] -> Bool-#ifdef USE_REPORT_PRELUDE-notElem x               =  all (/= x)-#else-notElem _ []    =  True-notElem x (y:ys)=  x /= y && notElem x ys-{-# NOINLINE [1] notElem #-}-{-# RULES-"notElem/build" forall x (g :: forall b . Eq a => (a -> b -> b) -> b -> b)-   . notElem x (build g) = g (\ y r -> (x /= y) && r) True- #-}-#endif---- | 'lookup' @key assocs@ looks up a key in an association list.-lookup                  :: (Eq a) => a -> [(a,b)] -> Maybe b-lookup _key []          =  Nothing-lookup  key ((x,y):xys)-    | key == x          =  Just y-    | otherwise         =  lookup key xys---- | Map a function over a list and concatenate the results.-concatMap               :: (a -> [b]) -> [a] -> [b]-concatMap f             =  foldr ((++) . f) []--{-# NOINLINE [1] concatMap #-}--{-# RULES-"concatMap" forall f xs . concatMap f xs =-    build (\c n -> foldr (\x b -> foldr c b (f x)) n xs)- #-}----- | Concatenate a list of lists.-concat :: [[a]] -> [a]-concat = foldr (++) []--{-# NOINLINE [1] concat #-}--{-# RULES-  "concat" forall xs. concat xs =-     build (\c n -> foldr (\x y -> foldr c y x) n xs)--- We don't bother to turn non-fusible applications of concat back into concat- #-}---- | List index (subscript) operator, starting from 0.--- It is an instance of the more general 'Data.List.genericIndex',--- which takes an index of any integral type.-(!!)                    :: [a] -> Int -> a-#ifdef USE_REPORT_PRELUDE-xs     !! n | n < 0 =  error "Prelude.!!: negative index"-[]     !! _         =  error "Prelude.!!: index too large"-(x:_)  !! 0         =  x-(_:xs) !! n         =  xs !! (n-1)-#else---- We don't really want the errors to inline with (!!).--- We may want to fuss around a bit with NOINLINE, and--- if so we should be careful not to trip up known-bottom--- optimizations.-tooLarge :: Int -> a-tooLarge _ = error (prel_list_str ++ "!!: index too large")--negIndex :: a-negIndex = error $ prel_list_str ++ "!!: negative index"--{-# INLINABLE (!!) #-}-xs !! n-  | n < 0     = negIndex-  | otherwise = foldr (\x r k -> case k of-                                   0 -> x-                                   _ -> r (k-1)) tooLarge xs n-#endif------------------------------------------------------------------- The zip family-----------------------------------------------------------------foldr2 :: (a -> b -> c -> c) -> c -> [a] -> [b] -> c-foldr2 k z = go-  where-        go []    _ys     = z-        go _xs   []      = z-        go (x:xs) (y:ys) = k x y (go xs ys)-{-# INLINE [0] foldr2 #-}--foldr2_left :: (a -> b -> c -> d) -> d -> a -> ([b] -> c) -> [b] -> d-foldr2_left _k  z _x _r []     = z-foldr2_left  k _z  x  r (y:ys) = k x y (r ys)---- foldr2 k z xs ys = foldr (foldr2_left k z)  (\_ -> z) xs ys-{-# RULES-"foldr2/left"   forall k z ys (g::forall b.(a->b->b)->b->b) .-                  foldr2 k z (build g) ys = g (foldr2_left  k z) (\_ -> z) ys- #-}--- There used to be a foldr2/right rule, allowing foldr2 to fuse with a build--- form on the right. However, this causes trouble if the right list ends in--- a bottom that is only avoided by the left list ending at that spot. That is,--- foldr2 f z [a,b,c] (d:e:f:_|_), where the right list is produced by a build--- form, would cause the foldr2/right rule to introduce bottom. Example:------ zip [1,2,3,4] (unfoldr (\s -> if s > 4 then undefined else Just (s,s+1)) 1)------ should produce------ [(1,1),(2,2),(3,3),(4,4)]------ but with the foldr2/right rule it would instead produce------ (1,1):(2,2):(3,3):(4,4):_|_---- Zips for larger tuples are in the List module.--------------------------------------------------- | 'zip' takes two lists and returns a list of corresponding pairs.--- If one input list is short, excess elements of the longer list are--- discarded.------ 'zip' is right-lazy:------ > zip [] _|_ = []-{-# NOINLINE [1] zip #-}-zip :: [a] -> [b] -> [(a,b)]-zip []     _bs    = []-zip _as    []     = []-zip (a:as) (b:bs) = (a,b) : zip as bs--{-# INLINE [0] zipFB #-}-zipFB :: ((a, b) -> c -> d) -> a -> b -> c -> d-zipFB c = \x y r -> (x,y) `c` r--{-# RULES-"zip"      [~1] forall xs ys. zip xs ys = build (\c n -> foldr2 (zipFB c) n xs ys)-"zipList"  [1]  foldr2 (zipFB (:)) []   = zip- #-}--------------------------------------------------- | 'zip3' takes three lists and returns a list of triples, analogous to--- 'zip'.-zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]--- Specification--- zip3 =  zipWith3 (,,)-zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs-zip3 _      _      _      = []----- The zipWith family generalises the zip family by zipping with the--- function given as the first argument, instead of a tupling function.--------------------------------------------------- | 'zipWith' generalises 'zip' by zipping with the function given--- as the first argument, instead of a tupling function.--- For example, @'zipWith' (+)@ is applied to two lists to produce the--- list of corresponding sums.------ 'zipWith' is right-lazy:------ > zipWith f [] _|_ = []-{-# NOINLINE [1] zipWith #-}-zipWith :: (a->b->c) -> [a]->[b]->[c]-zipWith _f []     _bs    = []-zipWith _f _as    []     = []-zipWith f  (a:as) (b:bs) = f a b : zipWith f as bs---- zipWithFB must have arity 2 since it gets two arguments in the "zipWith"--- rule; it might not get inlined otherwise-{-# INLINE [0] zipWithFB #-}-zipWithFB :: (a -> b -> c) -> (d -> e -> a) -> d -> e -> b -> c-zipWithFB c f = \x y r -> (x `f` y) `c` r--{-# RULES-"zipWith"       [~1] forall f xs ys.    zipWith f xs ys = build (\c n -> foldr2 (zipWithFB c f) n xs ys)-"zipWithList"   [1]  forall f.  foldr2 (zipWithFB (:) f) [] = zipWith f-  #-}---- | The 'zipWith3' function takes a function which combines three--- elements, as well as three lists and returns a list of their point-wise--- combination, analogous to 'zipWith'.-zipWith3                :: (a->b->c->d) -> [a]->[b]->[c]->[d]-zipWith3 z (a:as) (b:bs) (c:cs)-                        =  z a b c : zipWith3 z as bs cs-zipWith3 _ _ _ _        =  []---- | 'unzip' transforms a list of pairs into a list of first components--- and a list of second components.-unzip    :: [(a,b)] -> ([a],[b])-{-# INLINE unzip #-}-unzip    =  foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])---- | The 'unzip3' function takes a list of triples and returns three--- lists, analogous to 'unzip'.-unzip3   :: [(a,b,c)] -> ([a],[b],[c])-{-# INLINE unzip3 #-}-unzip3   =  foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))-                  ([],[],[])------------------------------------------------------------------- Error code------------------------------------------------------------------- Common up near identical calls to `error' to reduce the number--- constant strings created when compiled:--errorEmptyList :: String -> a-errorEmptyList fun =-  error (prel_list_str ++ fun ++ ": empty list")--prel_list_str :: String-prel_list_str = "Prelude."
− GHC/MVar.hs
@@ -1,182 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples, AutoDeriveTypeable #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.MVar--- Copyright   :  (c) The University of Glasgow 2008--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The MVar type-----------------------------------------------------------------------------------module GHC.MVar (-        -- * MVars-          MVar(..)-        , newMVar-        , newEmptyMVar-        , takeMVar-        , readMVar-        , putMVar-        , tryTakeMVar-        , tryPutMVar-        , tryReadMVar-        , isEmptyMVar-        , addMVarFinalizer-    ) where--import GHC.Base-import Data.Typeable--data MVar a = MVar (MVar# RealWorld a) deriving( Typeable )-{- ^-An 'MVar' (pronounced \"em-var\") is a synchronising variable, used-for communication between concurrent threads.  It can be thought of-as a a box, which may be empty or full.--}---- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module-instance Eq (MVar a) where-        (MVar mvar1#) == (MVar mvar2#) = isTrue# (sameMVar# mvar1# mvar2#)--{--M-Vars are rendezvous points for concurrent threads.  They begin-empty, and any attempt to read an empty M-Var blocks.  When an M-Var-is written, a single blocked thread may be freed.  Reading an M-Var-toggles its state from full back to empty.  Therefore, any value-written to an M-Var may only be read once.  Multiple reads and writes-are allowed, but there must be at least one read between any two-writes.--}----Defined in IOBase to avoid cycle: data MVar a = MVar (SynchVar# RealWorld a)---- |Create an 'MVar' which is initially empty.-newEmptyMVar  :: IO (MVar a)-newEmptyMVar = IO $ \ s# ->-    case newMVar# s# of-         (# s2#, svar# #) -> (# s2#, MVar svar# #)---- |Create an 'MVar' which contains the supplied value.-newMVar :: a -> IO (MVar a)-newMVar value =-    newEmptyMVar        >>= \ mvar ->-    putMVar mvar value  >>-    return mvar---- |Return the contents of the 'MVar'.  If the 'MVar' is currently--- empty, 'takeMVar' will wait until it is full.  After a 'takeMVar',--- the 'MVar' is left empty.------ There are two further important properties of 'takeMVar':------   * 'takeMVar' is single-wakeup.  That is, if there are multiple---     threads blocked in 'takeMVar', and the 'MVar' becomes full,---     only one thread will be woken up.  The runtime guarantees that---     the woken thread completes its 'takeMVar' operation.------   * When multiple threads are blocked on an 'MVar', they are---     woken up in FIFO order.  This is useful for providing---     fairness properties of abstractions built using 'MVar's.----takeMVar :: MVar a -> IO a-takeMVar (MVar mvar#) = IO $ \ s# -> takeMVar# mvar# s#---- |Atomically read the contents of an 'MVar'.  If the 'MVar' is--- currently empty, 'readMVar' will wait until its full.--- 'readMVar' is guaranteed to receive the next 'putMVar'.------ 'readMVar' is multiple-wakeup, so when multiple readers are--- blocked on an 'MVar', all of them are woken up at the same time.------ /Compatibility note:/ Prior to base 4.7, 'readMVar' was a combination--- of 'takeMVar' and 'putMVar'.  This mean that in the presence of--- other threads attempting to 'putMVar', 'readMVar' could block.--- Furthermore, 'readMVar' would not receive the next 'putMVar' if there--- was already a pending thread blocked on 'takeMVar'.  The old behavior--- can be recovered by implementing 'readMVar as follows:------ @---  readMVar :: MVar a -> IO a---  readMVar m =---    mask_ $ do---      a <- takeMVar m---      putMVar m a---      return a--- @-readMVar :: MVar a -> IO a-readMVar (MVar mvar#) = IO $ \ s# -> readMVar# mvar# s#---- |Put a value into an 'MVar'.  If the 'MVar' is currently full,--- 'putMVar' will wait until it becomes empty.------ There are two further important properties of 'putMVar':------   * 'putMVar' is single-wakeup.  That is, if there are multiple---     threads blocked in 'putMVar', and the 'MVar' becomes empty,---     only one thread will be woken up.  The runtime guarantees that---     the woken thread completes its 'putMVar' operation.------   * When multiple threads are blocked on an 'MVar', they are---     woken up in FIFO order.  This is useful for providing---     fairness properties of abstractions built using 'MVar's.----putMVar  :: MVar a -> a -> IO ()-putMVar (MVar mvar#) x = IO $ \ s# ->-    case putMVar# mvar# x s# of-        s2# -> (# s2#, () #)---- |A non-blocking version of 'takeMVar'.  The 'tryTakeMVar' function--- returns immediately, with 'Nothing' if the 'MVar' was empty, or--- @'Just' a@ if the 'MVar' was full with contents @a@.  After 'tryTakeMVar',--- the 'MVar' is left empty.-tryTakeMVar :: MVar a -> IO (Maybe a)-tryTakeMVar (MVar m) = IO $ \ s ->-    case tryTakeMVar# m s of-        (# s', 0#, _ #) -> (# s', Nothing #)      -- MVar is empty-        (# s', _,  a #) -> (# s', Just a  #)      -- MVar is full---- |A non-blocking version of 'putMVar'.  The 'tryPutMVar' function--- attempts to put the value @a@ into the 'MVar', returning 'True' if--- it was successful, or 'False' otherwise.-tryPutMVar  :: MVar a -> a -> IO Bool-tryPutMVar (MVar mvar#) x = IO $ \ s# ->-    case tryPutMVar# mvar# x s# of-        (# s, 0# #) -> (# s, False #)-        (# s, _  #) -> (# s, True #)---- |A non-blocking version of 'readMVar'.  The 'tryReadMVar' function--- returns immediately, with 'Nothing' if the 'MVar' was empty, or--- @'Just' a@ if the 'MVar' was full with contents @a@.------ @since 4.7.0.0-tryReadMVar :: MVar a -> IO (Maybe a)-tryReadMVar (MVar m) = IO $ \ s ->-    case tryReadMVar# m s of-        (# s', 0#, _ #) -> (# s', Nothing #)      -- MVar is empty-        (# s', _,  a #) -> (# s', Just a  #)      -- MVar is full---- |Check whether a given 'MVar' is empty.------ Notice that the boolean value returned  is just a snapshot of--- the state of the MVar. By the time you get to react on its result,--- the MVar may have been filled (or emptied) - so be extremely--- careful when using this operation.   Use 'tryTakeMVar' instead if possible.-isEmptyMVar :: MVar a -> IO Bool-isEmptyMVar (MVar mv#) = IO $ \ s# ->-    case isEmptyMVar# mv# s# of-        (# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #)---- |Add a finalizer to an 'MVar' (GHC only).  See "Foreign.ForeignPtr" and--- "System.Mem.Weak" for more about finalizers.-addMVarFinalizer :: MVar a -> IO () -> IO ()-addMVarFinalizer (MVar m) finalizer =-  IO $ \s -> case mkWeak# m () finalizer s of { (# s1, _ #) -> (# s1, () #) }-
− GHC/Natural.hs
@@ -1,644 +0,0 @@-{-# LANGUAGE AutoDeriveTypeable #-}-{-# LANGUAGE BangPatterns #-}-{-# LANGUAGE CPP #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE MagicHash #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE UnboxedTuples #-}-{-# LANGUAGE Unsafe #-}--{-# OPTIONS_HADDOCK not-home #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Natural--- Copyright   :  (C) 2014 Herbert Valerio Riedel,---                (C) 2011 Edward Kmett--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The arbitrary-precision 'Natural' number type.------ __Note__: This is an internal GHC module with an API subject to--- change.  It's recommended use the "Numeric.Natural" module to import--- the 'Natural' type.------ @since 4.8.0.0-------------------------------------------------------------------------------module GHC.Natural-    ( -- * The 'Natural' number type-      ---      -- | __Warning__: The internal implementation of 'Natural'-      -- (i.e. which constructors are available) depends on the-      -- 'Integer' backend used!-      Natural(..)-    , isValidNatural-      -- * Conversions-    , wordToNatural-    , naturalToWordMaybe-      -- * Checked subtraction-    , minusNaturalMaybe-      -- * Modular arithmetic-    , powModNatural-    ) where--#include "MachDeps.h"--#if defined(MIN_VERSION_integer_gmp)-# define HAVE_GMP_BIGNAT MIN_VERSION_integer_gmp(1,0,0)-#else-# define HAVE_GMP_BIGNAT 0-#endif--import GHC.Arr-import GHC.Base-import GHC.Exception-#if HAVE_GMP_BIGNAT-import GHC.Integer.GMP.Internals-import Data.Word-import Data.Int-#endif-import GHC.Num-import GHC.Real-import GHC.Read-import GHC.Show-import GHC.Enum-import GHC.List--import Data.Bits-import Data.Data--default ()--#if HAVE_GMP_BIGNAT--- TODO: if saturated arithmetic is to used, replace 'throw Underflow' by '0'---- | Type representing arbitrary-precision non-negative integers.------ Operations whose result would be negative--- @'throw' ('Underflow' :: 'ArithException')@.------ @since 4.8.0.0-data Natural = NatS#                 GmpLimb# -- ^ in @[0, maxBound::Word]@-             | NatJ# {-# UNPACK #-} !BigNat   -- ^ in @]maxBound::Word, +inf[@-                                              ---                                              -- __Invariant__: 'NatJ#' is used-                                              -- /iff/ value doesn't fit in-                                              -- 'NatS#' constructor.-             deriving (Eq,Ord) -- NB: Order of constructors *must*-                               -- coincide with 'Ord' relation---- | Test whether all internal invariants are satisfied by 'Natural' value------ This operation is mostly useful for test-suites and/or code which--- constructs 'Integer' values directly.------ @since 4.8.0.0-isValidNatural :: Natural -> Bool-isValidNatural (NatS# _)  = True-isValidNatural (NatJ# bn) = isTrue# (isValidBigNat# bn)-                            && I# (sizeofBigNat# bn) > 0--{-# RULES-"fromIntegral/Natural->Natural"  fromIntegral = id :: Natural -> Natural-"fromIntegral/Natural->Integer"  fromIntegral = toInteger :: Natural->Integer-"fromIntegral/Natural->Word"     fromIntegral = naturalToWord-"fromIntegral/Natural->Word8"-    fromIntegral = (fromIntegral :: Word -> Word8)  . naturalToWord-"fromIntegral/Natural->Word16"-    fromIntegral = (fromIntegral :: Word -> Word16) . naturalToWord-"fromIntegral/Natural->Word32"-    fromIntegral = (fromIntegral :: Word -> Word32) . naturalToWord-"fromIntegral/Natural->Int8"-    fromIntegral = (fromIntegral :: Int -> Int8)    . naturalToInt-"fromIntegral/Natural->Int16"-    fromIntegral = (fromIntegral :: Int -> Int16)   . naturalToInt-"fromIntegral/Natural->Int32"-    fromIntegral = (fromIntegral :: Int -> Int32)   . naturalToInt-  #-}--{-# RULES-"fromIntegral/Word->Natural"     fromIntegral = wordToNatural-"fromIntegral/Word8->Natural"-    fromIntegral = wordToNatural . (fromIntegral :: Word8  -> Word)-"fromIntegral/Word16->Natural"-    fromIntegral = wordToNatural . (fromIntegral :: Word16 -> Word)-"fromIntegral/Word32->Natural"-    fromIntegral = wordToNatural . (fromIntegral :: Word32 -> Word)-"fromIntegral/Int->Natural"     fromIntegral = intToNatural-"fromIntegral/Int8->Natural"-    fromIntegral = intToNatural  . (fromIntegral :: Int8  -> Int)-"fromIntegral/Int16->Natural"-    fromIntegral = intToNatural  . (fromIntegral :: Int16 -> Int)-"fromIntegral/Int32->Natural"-    fromIntegral = intToNatural  . (fromIntegral :: Int32 -> Int)-  #-}--#if WORD_SIZE_IN_BITS == 64--- these RULES are valid for Word==Word64 & Int==Int64-{-# RULES-"fromIntegral/Natural->Word64"-    fromIntegral = (fromIntegral :: Word -> Word64) . naturalToWord-"fromIntegral/Natural->Int64"-    fromIntegral = (fromIntegral :: Int -> Int64) . naturalToInt-"fromIntegral/Word64->Natural"-    fromIntegral = wordToNatural . (fromIntegral :: Word64 -> Word)-"fromIntegral/Int64->Natural"-    fromIntegral = intToNatural . (fromIntegral :: Int64 -> Int)-  #-}-#endif--instance Show Natural where-    showsPrec p (NatS# w#)  = showsPrec p (W# w#)-    showsPrec p (NatJ# bn)  = showsPrec p (Jp# bn)--instance Read Natural where-    readsPrec d = map (\(n, s) -> (fromInteger n, s))-                  . filter ((>= 0) . (\(x,_)->x)) . readsPrec d--instance Num Natural where-    fromInteger (S# i#) | I# i# >= 0  = NatS# (int2Word# i#)-    fromInteger (Jp# bn)              = bigNatToNatural bn-    fromInteger _                     = throw Underflow--    (+) = plusNatural-    (*) = timesNatural-    (-) = minusNatural--    abs                  = id--    signum (NatS# 0##)   = NatS# 0##-    signum _             = NatS# 1##--    negate (NatS# 0##)   = NatS# 0##-    negate _             = throw Underflow--instance Real Natural where-    toRational (NatS# w)  = toRational (W# w)-    toRational (NatJ# bn) = toRational (Jp# bn)--#if OPTIMISE_INTEGER_GCD_LCM-{-# RULES-"gcd/Natural->Natural->Natural" gcd = gcdNatural-"lcm/Natural->Natural->Natural" lcm = lcmNatural-  #-}---- | Compute greatest common divisor.-gcdNatural :: Natural -> Natural -> Natural-gcdNatural (NatS# 0##) y       = y-gcdNatural x       (NatS# 0##) = x-gcdNatural (NatS# 1##) _       = (NatS# 1##)-gcdNatural _       (NatS# 1##) = (NatS# 1##)-gcdNatural (NatJ# x) (NatJ# y) = bigNatToNatural (gcdBigNat x y)-gcdNatural (NatJ# x) (NatS# y) = NatS# (gcdBigNatWord x y)-gcdNatural (NatS# x) (NatJ# y) = NatS# (gcdBigNatWord y x)-gcdNatural (NatS# x) (NatS# y) = NatS# (gcdWord x y)---- | compute least common multiplier.-lcmNatural :: Natural -> Natural -> Natural-lcmNatural (NatS# 0##) _ = (NatS# 0##)-lcmNatural _ (NatS# 0##) = (NatS# 0##)-lcmNatural (NatS# 1##) y = y-lcmNatural x (NatS# 1##) = x-lcmNatural x y           = (x `quot` (gcdNatural x y)) * y--#endif--instance Enum Natural where-    succ n = n `plusNatural`  NatS# 1##-    pred n = n `minusNatural` NatS# 1##--    toEnum = intToNatural--    fromEnum (NatS# w) | i >= 0 = i-      where-        i = fromIntegral (W# w)-    fromEnum _ = error "fromEnum: out of Int range"--    enumFrom x        = enumDeltaNatural      x (NatS# 1##)-    enumFromThen x y-      | x <= y        = enumDeltaNatural      x (y-x)-      | otherwise     = enumNegDeltaToNatural x (x-y) (NatS# 0##)--    enumFromTo x lim  = enumDeltaToNatural    x (NatS# 1##) lim-    enumFromThenTo x y lim-      | x <= y        = enumDeltaToNatural    x (y-x) lim-      | otherwise     = enumNegDeltaToNatural x (x-y) lim--------------------------------------------------------------------------------- Helpers for 'Enum Natural'; TODO: optimise & make fusion work--enumDeltaNatural :: Natural -> Natural -> [Natural]-enumDeltaNatural !x d = x : enumDeltaNatural (x+d) d--enumDeltaToNatural :: Natural -> Natural -> Natural -> [Natural]-enumDeltaToNatural x0 delta lim = go x0-  where-    go x | x > lim   = []-         | otherwise = x : go (x+delta)--enumNegDeltaToNatural :: Natural -> Natural -> Natural -> [Natural]-enumNegDeltaToNatural x0 ndelta lim = go x0-  where-    go x | x < lim     = []-         | x >= ndelta = x : go (x-ndelta)-         | otherwise   = [x]--------------------------------------------------------------------------------instance Integral Natural where-    toInteger (NatS# w)  = wordToInteger w-    toInteger (NatJ# bn) = Jp# bn--    divMod = quotRem-    div    = quot-    mod    = rem--    quotRem _ (NatS# 0##) = throw DivideByZero-    quotRem n (NatS# 1##) = (n,NatS# 0##)-    quotRem n@(NatS# _) (NatJ# _) = (NatS# 0##, n)-    quotRem (NatS# n) (NatS# d) = case quotRem (W# n) (W# d) of-        (q,r) -> (wordToNatural q, wordToNatural r)-    quotRem (NatJ# n) (NatS# d) = case quotRemBigNatWord n d of-        (# q,r #) -> (bigNatToNatural q, NatS# r)-    quotRem (NatJ# n) (NatJ# d) = case quotRemBigNat n d of-        (# q,r #) -> (bigNatToNatural q, bigNatToNatural r)--    quot _       (NatS# 0##) = throw DivideByZero-    quot n       (NatS# 1##) = n-    quot (NatS# _) (NatJ# _) = NatS# 0##-    quot (NatS# n) (NatS# d) = wordToNatural (quot (W# n) (W# d))-    quot (NatJ# n) (NatS# d) = bigNatToNatural (quotBigNatWord n d)-    quot (NatJ# n) (NatJ# d) = bigNatToNatural (quotBigNat n d)--    rem _         (NatS# 0##) = throw DivideByZero-    rem _         (NatS# 1##) = NatS# 0##-    rem n@(NatS# _) (NatJ# _) = n-    rem   (NatS# n) (NatS# d) = wordToNatural (rem (W# n) (W# d))-    rem   (NatJ# n) (NatS# d) = NatS# (remBigNatWord n d)-    rem   (NatJ# n) (NatJ# d) = bigNatToNatural (remBigNat n d)--instance Ix Natural where-    range (m,n) = [m..n]-    inRange (m,n) i = m <= i && i <= n-    unsafeIndex (m,_) i = fromIntegral (i-m)-    index b i | inRange b i = unsafeIndex b i-              | otherwise   = indexError b i "Natural"---instance Bits Natural where-    NatS# n .&. NatS# m = wordToNatural (W# n .&. W# m)-    NatS# n .&. NatJ# m = wordToNatural (W# n .&. W# (bigNatToWord m))-    NatJ# n .&. NatS# m = wordToNatural (W# (bigNatToWord n) .&. W# m)-    NatJ# n .&. NatJ# m = bigNatToNatural (andBigNat n m)--    NatS# n .|. NatS# m = wordToNatural (W# n .|. W# m)-    NatS# n .|. NatJ# m = NatJ# (orBigNat (wordToBigNat n) m)-    NatJ# n .|. NatS# m = NatJ# (orBigNat n (wordToBigNat m))-    NatJ# n .|. NatJ# m = NatJ# (orBigNat n m)--    NatS# n `xor` NatS# m = wordToNatural (W# n `xor` W# m)-    NatS# n `xor` NatJ# m = NatJ# (xorBigNat (wordToBigNat n) m)-    NatJ# n `xor` NatS# m = NatJ# (xorBigNat n (wordToBigNat m))-    NatJ# n `xor` NatJ# m = bigNatToNatural (xorBigNat n m)--    complement _ = error "Bits.complement: Natural complement undefined"--    bitSizeMaybe _ = Nothing-    bitSize = error "Natural: bitSize"-    isSigned _ = False--    bit i@(I# i#) | i < finiteBitSize (0::Word) = wordToNatural (bit i)-                  | otherwise                   = NatJ# (bitBigNat i#)--    testBit (NatS# w) i = testBit (W# w) i-    testBit (NatJ# bn) (I# i#) = testBitBigNat bn i#--    -- TODO: setBit, clearBit, complementBit (needs more primitives)--    shiftL n           0 = n-    shiftL (NatS# 0##) _ = NatS# 0##-    shiftL (NatS# 1##) i = bit i-    shiftL (NatS# w) (I# i#)-        = bigNatToNatural $ shiftLBigNat (wordToBigNat w) i#-    shiftL (NatJ# bn) (I# i#)-        = bigNatToNatural $ shiftLBigNat bn i#--    shiftR n          0       = n-    shiftR (NatS# w)  i       = wordToNatural $ shiftR (W# w) i-    shiftR (NatJ# bn) (I# i#) = bigNatToNatural (shiftRBigNat bn i#)--    rotateL = shiftL-    rotateR = shiftR--    popCount (NatS# w)  = popCount (W# w)-    popCount (NatJ# bn) = I# (popCountBigNat bn)--    zeroBits = NatS# 0##---------------------------------------------------------------------------------- | 'Natural' Addition-plusNatural :: Natural -> Natural -> Natural-plusNatural (NatS# 0##) y         = y-plusNatural x         (NatS# 0##) = x-plusNatural (NatS# x) (NatS# y)-    = case plusWord2# x y of-       (# 0##, l #) -> NatS# l-       (# h,   l #) -> NatJ# (wordToBigNat2 h l)-plusNatural (NatS# x) (NatJ# y) = NatJ# (plusBigNatWord y x)-plusNatural (NatJ# x) (NatS# y) = NatJ# (plusBigNatWord x y)-plusNatural (NatJ# x) (NatJ# y) = NatJ# (plusBigNat     x y)---- | 'Natural' multiplication-timesNatural :: Natural -> Natural -> Natural-timesNatural _         (NatS# 0##) = NatS# 0##-timesNatural (NatS# 0##) _         = NatS# 0##-timesNatural x         (NatS# 1##) = x-timesNatural (NatS# 1##) y         = y-timesNatural (NatS# x) (NatS# y) = case timesWord2# x y of-    (# 0##, 0## #) -> NatS# 0##-    (# 0##, xy  #) -> NatS# xy-    (# h  , l   #) -> NatJ# $ wordToBigNat2 h l-timesNatural (NatS# x) (NatJ# y) = NatJ# $ timesBigNatWord y x-timesNatural (NatJ# x) (NatS# y) = NatJ# $ timesBigNatWord x y-timesNatural (NatJ# x) (NatJ# y) = NatJ# $ timesBigNat     x y---- | 'Natural' subtraction. May @'throw' 'Underflow'@.-minusNatural :: Natural -> Natural -> Natural-minusNatural x         (NatS# 0##) = x-minusNatural (NatS# x) (NatS# y) = case subWordC# x y of-    (# l, 0# #) -> NatS# l-    _           -> throw Underflow-minusNatural (NatS# _) (NatJ# _) = throw Underflow-minusNatural (NatJ# x) (NatS# y)-    = bigNatToNatural $ minusBigNatWord x y-minusNatural (NatJ# x) (NatJ# y)-    = bigNatToNatural $ minusBigNat     x y---- | 'Natural' subtraction. Returns 'Nothing's for non-positive results.------ @since 4.8.0.0-minusNaturalMaybe :: Natural -> Natural -> Maybe Natural-minusNaturalMaybe x         (NatS# 0##) = Just x-minusNaturalMaybe (NatS# x) (NatS# y) = case subWordC# x y of-    (# l, 0# #) -> Just (NatS# l)-    _           -> Nothing-  where-minusNaturalMaybe (NatS# _) (NatJ# _) = Nothing-minusNaturalMaybe (NatJ# x) (NatS# y)-    = Just $ bigNatToNatural $ minusBigNatWord x y-minusNaturalMaybe (NatJ# x) (NatJ# y)-  | isTrue# (isNullBigNat# res) = Nothing-  | otherwise = Just (bigNatToNatural res)-  where-    res = minusBigNat x y---- | Helper for 'minusNatural' and 'minusNaturalMaybe'-subWordC# :: Word# -> Word# -> (# Word#, Int# #)-subWordC# x# y# = (# d#, c# #)-  where-    d# = x# `minusWord#` y#-    c# = d# `gtWord#` x#---- | Convert 'BigNat' to 'Natural'.--- Throws 'Underflow' if passed a 'nullBigNat'.-bigNatToNatural :: BigNat -> Natural-bigNatToNatural bn-  | isTrue# (sizeofBigNat# bn ==# 1#) = NatS# (bigNatToWord bn)-  | isTrue# (isNullBigNat# bn)        = throw Underflow-  | otherwise                         = NatJ# bn--naturalToBigNat :: Natural -> BigNat-naturalToBigNat (NatS# w#) = wordToBigNat w#-naturalToBigNat (NatJ# bn) = bn---- | Convert 'Int' to 'Natural'.--- Throws 'Underflow' when passed a negative 'Int'.-intToNatural :: Int -> Natural-intToNatural i | i<0 = throw Underflow-intToNatural (I# i#) = NatS# (int2Word# i#)--naturalToWord :: Natural -> Word-naturalToWord (NatS# w#) = W# w#-naturalToWord (NatJ# bn) = W# (bigNatToWord bn)--naturalToInt :: Natural -> Int-naturalToInt (NatS# w#) = I# (word2Int# w#)-naturalToInt (NatJ# bn) = I# (bigNatToInt bn)--#else /* !HAVE_GMP_BIGNAT */-------------------------------------------------------------------------------- Use wrapped 'Integer' as fallback; taken from Edward Kmett's nats package---- | Type representing arbitrary-precision non-negative integers.------ Operations whose result would be negative--- @'throw' ('Underflow' :: 'ArithException')@.------ @since 4.8.0.0-newtype Natural = Natural Integer -- ^ __Invariant__: non-negative 'Integer'-                deriving (Eq,Ord,Ix)---- | Test whether all internal invariants are satisfied by 'Natural' value------ This operation is mostly useful for test-suites and/or code which--- constructs 'Integer' values directly.------ @since 4.8.0.0-isValidNatural :: Natural -> Bool-isValidNatural (Natural i) = i >= 0--instance Read Natural where-    readsPrec d = map (\(n, s) -> (Natural n, s))-                  . filter ((>= 0) . (\(x,_)->x)) . readsPrec d--instance Show Natural where-    showsPrec d (Natural i) = showsPrec d i--instance Num Natural where-  Natural n + Natural m = Natural (n + m)-  {-# INLINE (+) #-}-  Natural n * Natural m = Natural (n * m)-  {-# INLINE (*) #-}-  Natural n - Natural m | result < 0 = throw Underflow-                        | otherwise  = Natural result-    where result = n - m-  {-# INLINE (-) #-}-  abs (Natural n) = Natural n-  {-# INLINE abs #-}-  signum (Natural n) = Natural (signum n)-  {-# INLINE signum #-}-  fromInteger n-    | n >= 0 = Natural n-    | otherwise = throw Underflow-  {-# INLINE fromInteger #-}---- | 'Natural' subtraction. Returns 'Nothing's for non-positive results.------ @since 4.8.0.0-minusNaturalMaybe :: Natural -> Natural -> Maybe Natural-minusNaturalMaybe x y-  | x >= y    = Just (x - y)-  | otherwise = Nothing--instance Bits Natural where-  Natural n .&. Natural m = Natural (n .&. m)-  {-# INLINE (.&.) #-}-  Natural n .|. Natural m = Natural (n .|. m)-  {-# INLINE (.|.) #-}-  xor (Natural n) (Natural m) = Natural (xor n m)-  {-# INLINE xor #-}-  complement _ = error "Bits.complement: Natural complement undefined"-  {-# INLINE complement #-}-  shift (Natural n) = Natural . shift n-  {-# INLINE shift #-}-  rotate (Natural n) = Natural . rotate n-  {-# INLINE rotate #-}-  bit = Natural . bit-  {-# INLINE bit #-}-  setBit (Natural n) = Natural . setBit n-  {-# INLINE setBit #-}-  clearBit (Natural n) = Natural . clearBit n-  {-# INLINE clearBit #-}-  complementBit (Natural n) = Natural . complementBit n-  {-# INLINE complementBit #-}-  testBit (Natural n) = testBit n-  {-# INLINE testBit #-}-  bitSizeMaybe _ = Nothing-  {-# INLINE bitSizeMaybe #-}-  bitSize = error "Natural: bitSize"-  {-# INLINE bitSize #-}-  isSigned _ = False-  {-# INLINE isSigned #-}-  shiftL (Natural n) = Natural . shiftL n-  {-# INLINE shiftL #-}-  shiftR (Natural n) = Natural . shiftR n-  {-# INLINE shiftR #-}-  rotateL (Natural n) = Natural . rotateL n-  {-# INLINE rotateL #-}-  rotateR (Natural n) = Natural . rotateR n-  {-# INLINE rotateR #-}-  popCount (Natural n) = popCount n-  {-# INLINE popCount #-}-  zeroBits = Natural 0--instance Real Natural where-  toRational (Natural a) = toRational a-  {-# INLINE toRational #-}--instance Enum Natural where-  pred (Natural 0) = error "Natural.pred: 0"-  pred (Natural n) = Natural (pred n)-  {-# INLINE pred #-}-  succ (Natural n) = Natural (succ n)-  {-# INLINE succ #-}-  fromEnum (Natural n) = fromEnum n-  {-# INLINE fromEnum #-}-  toEnum n | n < 0     = error "Natural.toEnum: negative"-           | otherwise = Natural (toEnum n)-  {-# INLINE toEnum #-}--  enumFrom     = coerce (enumFrom     :: Integer -> [Integer])-  enumFromThen x y-    | x <= y    = coerce (enumFromThen :: Integer -> Integer -> [Integer]) x y-    | otherwise = enumFromThenTo x y 0--  enumFromTo   = coerce (enumFromTo   :: Integer -> Integer -> [Integer])-  enumFromThenTo-    = coerce (enumFromThenTo :: Integer -> Integer -> Integer -> [Integer])--instance Integral Natural where-  quot (Natural a) (Natural b) = Natural (quot a b)-  {-# INLINE quot #-}-  rem (Natural a) (Natural b) = Natural (rem a b)-  {-# INLINE rem #-}-  div (Natural a) (Natural b) = Natural (div a b)-  {-# INLINE div #-}-  mod (Natural a) (Natural b) = Natural (mod a b)-  {-# INLINE mod #-}-  divMod (Natural a) (Natural b) = (Natural q, Natural r)-    where (q,r) = divMod a b-  {-# INLINE divMod #-}-  quotRem (Natural a) (Natural b) = (Natural q, Natural r)-    where (q,r) = quotRem a b-  {-# INLINE quotRem #-}-  toInteger (Natural a) = a-  {-# INLINE toInteger #-}-#endif---- | Construct 'Natural' from 'Word' value.------ @since 4.8.0.0-wordToNatural :: Word -> Natural-#if HAVE_GMP_BIGNAT-wordToNatural (W# w#) = NatS# w#-#else-wordToNatural w = Natural (fromIntegral w)-#endif---- | Try downcasting 'Natural' to 'Word' value.--- Returns 'Nothing' if value doesn't fit in 'Word'.------ @since 4.8.0.0-naturalToWordMaybe :: Natural -> Maybe Word-#if HAVE_GMP_BIGNAT-naturalToWordMaybe (NatS# w#) = Just (W# w#)-naturalToWordMaybe (NatJ# _)  = Nothing-#else-naturalToWordMaybe (Natural i)-  | i <= maxw  = Just (fromIntegral i)-  | otherwise  = Nothing-  where-    maxw = toInteger (maxBound :: Word)-#endif---- This follows the same style as the other integral 'Data' instances--- defined in "Data.Data"-naturalType :: DataType-naturalType = mkIntType "Numeric.Natural.Natural"--instance Data Natural where-  toConstr x = mkIntegralConstr naturalType x-  gunfold _ z c = case constrRep c of-                    (IntConstr x) -> z (fromIntegral x)-                    _ -> error $ "Data.Data.gunfold: Constructor " ++ show c-                                 ++ " is not of type Natural"-  dataTypeOf _ = naturalType---- | \"@'powModNatural' /b/ /e/ /m/@\" computes base @/b/@ raised to--- exponent @/e/@ modulo @/m/@.------ @since 4.8.0.0-powModNatural :: Natural -> Natural -> Natural -> Natural-#if HAVE_GMP_BIGNAT-powModNatural _           _           (NatS# 0##) = throw DivideByZero-powModNatural _           _           (NatS# 1##) = NatS# 0##-powModNatural _           (NatS# 0##) _           = NatS# 1##-powModNatural (NatS# 0##) _           _           = NatS# 0##-powModNatural (NatS# 1##) _           _           = NatS# 1##-powModNatural (NatS# b)   (NatS# e)   (NatS# m)   = NatS# (powModWord b e m)-powModNatural b           e           (NatS# m)-  = NatS# (powModBigNatWord (naturalToBigNat b) (naturalToBigNat e) m)-powModNatural b           e           (NatJ# m)-  = bigNatToNatural (powModBigNat (naturalToBigNat b) (naturalToBigNat e) m)-#else--- Portable reference fallback implementation-powModNatural _ _ 0 = throw DivideByZero-powModNatural _ _ 1 = 0-powModNatural _ 0 _ = 1-powModNatural 0 _ _ = 0-powModNatural 1 _ _ = 1-powModNatural b0 e0 m = go b0 e0 1-  where-    go !b e !r-      | odd e     = go b' e' (r*b `mod` m)-      | e == 0    = r-      | otherwise = go b' e' r-      where-        b' = b*b `mod` m-        e' = e   `unsafeShiftR` 1 -- slightly faster than "e `div` 2"-#endif
− GHC/Num.hs
@@ -1,99 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Num--- Copyright   :  (c) The University of Glasgow 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The 'Num' class and the 'Integer' type.-----------------------------------------------------------------------------------module GHC.Num (module GHC.Num, module GHC.Integer) where--import GHC.Base-import GHC.Integer--infixl 7  *-infixl 6  +, ---default ()              -- Double isn't available yet,-                        -- and we shouldn't be using defaults anyway---- | Basic numeric class.-class  Num a  where-    {-# MINIMAL (+), (*), abs, signum, fromInteger, (negate | (-)) #-}--    (+), (-), (*)       :: a -> a -> a-    -- | Unary negation.-    negate              :: a -> a-    -- | Absolute value.-    abs                 :: a -> a-    -- | Sign of a number.-    -- The functions 'abs' and 'signum' should satisfy the law:-    ---    -- > abs x * signum x == x-    ---    -- For real numbers, the 'signum' is either @-1@ (negative), @0@ (zero)-    -- or @1@ (positive).-    signum              :: a -> a-    -- | Conversion from an 'Integer'.-    -- An integer literal represents the application of the function-    -- 'fromInteger' to the appropriate value of type 'Integer',-    -- so such literals have type @('Num' a) => a@.-    fromInteger         :: Integer -> a--    {-# INLINE (-) #-}-    {-# INLINE negate #-}-    x - y               = x + negate y-    negate x            = 0 - x---- | the same as @'flip' ('-')@.------ Because @-@ is treated specially in the Haskell grammar,--- @(-@ /e/@)@ is not a section, but an application of prefix negation.--- However, @('subtract'@ /exp/@)@ is equivalent to the disallowed section.-{-# INLINE subtract #-}-subtract :: (Num a) => a -> a -> a-subtract x y = y - x--instance  Num Int  where-    I# x + I# y = I# (x +# y)-    I# x - I# y = I# (x -# y)-    negate (I# x) = I# (negateInt# x)-    I# x * I# y = I# (x *# y)-    abs n  = if n `geInt` 0 then n else negate n--    signum n | n `ltInt` 0 = negate 1-             | n `eqInt` 0 = 0-             | otherwise   = 1--    {-# INLINE fromInteger #-}   -- Just to be sure!-    fromInteger i = I# (integerToInt i)--instance Num Word where-    (W# x#) + (W# y#)      = W# (x# `plusWord#` y#)-    (W# x#) - (W# y#)      = W# (x# `minusWord#` y#)-    (W# x#) * (W# y#)      = W# (x# `timesWord#` y#)-    negate (W# x#)         = W# (int2Word# (negateInt# (word2Int# x#)))-    abs x                  = x-    signum 0               = 0-    signum _               = 1-    fromInteger i          = W# (integerToWord i)--instance  Num Integer  where-    (+) = plusInteger-    (-) = minusInteger-    (*) = timesInteger-    negate         = negateInteger-    fromInteger x  =  x--    abs = absInteger-    signum = signumInteger
− GHC/OldList.hs
@@ -1,29 +0,0 @@-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE Safe #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.OldList--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ This legacy module provides access to the list-specialised operations--- of "Data.List". This module may go away again in future GHC versions and--- is provided as transitional tool to access some of the list-specialised--- operations that had to be generalised due to the implementation of the--- <https://wiki.haskell.org/Foldable_Traversable_In_Prelude Foldable/Traversable-in-Prelude Proposal (FTP)>.------ If the operations needed are available in "GHC.List", it's--- recommended to avoid importing this module and use "GHC.List"--- instead for now.------ @since 4.8.0.0--------------------------------------------------------------------------------module GHC.OldList (module Data.OldList) where--import Data.OldList
− GHC/PArr.hs
@@ -1,37 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE ParallelArrays, MagicHash #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.PArr--- Copyright   :  (c) 2001-2011 The Data Parallel Haskell team--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ BIG UGLY HACK: The desugarer special cases this module.  Despite the uses of '-XParallelArrays',---                the desugarer does not load 'Data.Array.Parallel' into its global state. (Hence,---                the present module may not use any other piece of '-XParallelArray' syntax.)------                This will be cleaned up when we change the internal represention of '[::]' to not---                rely on a wired-in type constructor.--module GHC.PArr where--import GHC.Base---- Representation of parallel arrays------ Vanilla representation of parallel Haskell based on standard GHC arrays that is used if the--- vectorised is /not/ used.------ NB: This definition *must* be kept in sync with `TysWiredIn.parrTyCon'!----data [::] e = PArr !Int (Array# e)--type PArr = [::]   -- this synonym is to get access to '[::]' without using the special syntax
− GHC/Pack.hs
@@ -1,101 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Pack--- Copyright   :  (c) The University of Glasgow 1997-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ This module provides a small set of low-level functions for packing--- and unpacking a chunk of bytes. Used by code emitted by the compiler--- plus the prelude libraries.------ The programmer level view of packed strings is provided by a GHC--- system library PackedString.-----------------------------------------------------------------------------------module GHC.Pack-       (-        -- (**) - emitted by compiler.--        packCString#,-        unpackCString,-        unpackCString#,-        unpackNBytes#,-        unpackFoldrCString#,  -- (**)-        unpackAppendCString#,  -- (**)-       )-        where--import GHC.Base-import GHC.List ( length )-import GHC.ST-import GHC.Ptr--data ByteArray ix              = ByteArray        ix ix ByteArray#-data MutableByteArray s ix     = MutableByteArray ix ix (MutableByteArray# s)--unpackCString :: Ptr a -> [Char]-unpackCString a@(Ptr addr)-  | a == nullPtr  = []-  | otherwise      = unpackCString# addr--packCString#         :: [Char]          -> ByteArray#-packCString# str = case (packString str) of { ByteArray _ _ bytes -> bytes }--packString :: [Char] -> ByteArray Int-packString str = runST (packStringST str)--packStringST :: [Char] -> ST s (ByteArray Int)-packStringST str =-  let len = length str  in-  packNBytesST len str--packNBytesST :: Int -> [Char] -> ST s (ByteArray Int)-packNBytesST (I# length#) str =-  {--   allocate an array that will hold the string-   (not forgetting the NUL byte at the end)-  -}- new_ps_array (length# +# 1#) >>= \ ch_array ->-   -- fill in packed string from "str"- fill_in ch_array 0# str   >>-   -- freeze the puppy:- freeze_ps_array ch_array length#- where-  fill_in :: MutableByteArray s Int -> Int# -> [Char] -> ST s ()-  fill_in arr_in# idx [] =-   write_ps_array arr_in# idx (chr# 0#) >>-   return ()--  fill_in arr_in# idx (C# c : cs) =-   write_ps_array arr_in# idx c  >>-   fill_in arr_in# (idx +# 1#) cs---- (Very :-) ``Specialised'' versions of some CharArray things...--new_ps_array    :: Int# -> ST s (MutableByteArray s Int)-write_ps_array  :: MutableByteArray s Int -> Int# -> Char# -> ST s ()-freeze_ps_array :: MutableByteArray s Int -> Int# -> ST s (ByteArray Int)--new_ps_array size = ST $ \ s ->-    case (newByteArray# size s)   of { (# s2#, barr# #) ->-    (# s2#, MutableByteArray bot bot barr# #) }-  where-    bot = error "new_ps_array"--write_ps_array (MutableByteArray _ _ barr#) n ch = ST $ \ s# ->-    case writeCharArray# barr# n ch s#  of { s2#   ->-    (# s2#, () #) }---- same as unsafeFreezeByteArray-freeze_ps_array (MutableByteArray _ _ arr#) len# = ST $ \ s# ->-    case unsafeFreezeByteArray# arr# s# of { (# s2#, frozen# #) ->-    (# s2#, ByteArray 0 (I# len#) frozen# #) }
− GHC/Profiling.hs
@@ -1,10 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---- | @since 4.7.0.0-module GHC.Profiling where--import GHC.Base--foreign import ccall startProfTimer :: IO ()-foreign import ccall stopProfTimer :: IO ()
− GHC/Ptr.hs
@@ -1,174 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, RoleAnnotations #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Ptr--- Copyright   :  (c) The FFI Task Force, 2000-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  ffi@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The 'Ptr' and 'FunPtr' types and operations.-----------------------------------------------------------------------------------module GHC.Ptr (-        Ptr(..), FunPtr(..),-        nullPtr, castPtr, plusPtr, alignPtr, minusPtr,-        nullFunPtr, castFunPtr,--        -- * Unsafe functions-        castFunPtrToPtr, castPtrToFunPtr-    ) where--import GHC.Base-import GHC.Show-import GHC.Num-import GHC.List ( length, replicate )-import Numeric          ( showHex )--#include "MachDeps.h"----------------------------------------------------------------------------- Data pointers.---- The role of Ptr's parameter is phantom, as there is no relation between--- the Haskell representation and whathever the user puts at the end of the--- pointer. And phantom is useful to implement castPtr (see #9163)---- redundant role annotation checks that this doesn't change-type role Ptr phantom-data Ptr a = Ptr Addr# deriving (Eq, Ord)--- ^ A value of type @'Ptr' a@ represents a pointer to an object, or an--- array of objects, which may be marshalled to or from Haskell values--- of type @a@.------ The type @a@ will often be an instance of class--- 'Foreign.Storable.Storable' which provides the marshalling operations.--- However this is not essential, and you can provide your own operations--- to access the pointer.  For example you might write small foreign--- functions to get or set the fields of a C @struct@.---- |The constant 'nullPtr' contains a distinguished value of 'Ptr'--- that is not associated with a valid memory location.-nullPtr :: Ptr a-nullPtr = Ptr nullAddr#---- |The 'castPtr' function casts a pointer from one type to another.-castPtr :: Ptr a -> Ptr b-castPtr = coerce---- |Advances the given address by the given offset in bytes.-plusPtr :: Ptr a -> Int -> Ptr b-plusPtr (Ptr addr) (I# d) = Ptr (plusAddr# addr d)---- |Given an arbitrary address and an alignment constraint,--- 'alignPtr' yields the next higher address that fulfills the--- alignment constraint.  An alignment constraint @x@ is fulfilled by--- any address divisible by @x@.  This operation is idempotent.-alignPtr :: Ptr a -> Int -> Ptr a-alignPtr addr@(Ptr a) (I# i)-  = case remAddr# a i of {-      0# -> addr;-      n -> Ptr (plusAddr# a (i -# n)) }---- |Computes the offset required to get from the second to the first--- argument.  We have------ > p2 == p1 `plusPtr` (p2 `minusPtr` p1)-minusPtr :: Ptr a -> Ptr b -> Int-minusPtr (Ptr a1) (Ptr a2) = I# (minusAddr# a1 a2)----------------------------------------------------------------------------- Function pointers for the default calling convention.---- 'FunPtr' has a phantom role for similar reasons to 'Ptr'. Note--- that 'FunPtr's role cannot become nominal without changes elsewhere--- in GHC. See Note [FFI type roles] in TcForeign.-type role FunPtr phantom-data FunPtr a = FunPtr Addr# deriving (Eq, Ord)--- ^ A value of type @'FunPtr' a@ is a pointer to a function callable--- from foreign code.  The type @a@ will normally be a /foreign type/,--- a function type with zero or more arguments where------ * the argument types are /marshallable foreign types/,---   i.e. 'Char', 'Int', 'Double', 'Float',---   'Bool', 'Data.Int.Int8', 'Data.Int.Int16', 'Data.Int.Int32',---   'Data.Int.Int64', 'Data.Word.Word8', 'Data.Word.Word16',---   'Data.Word.Word32', 'Data.Word.Word64', @'Ptr' a@, @'FunPtr' a@,---   @'Foreign.StablePtr.StablePtr' a@ or a renaming of any of these---   using @newtype@.------ * the return type is either a marshallable foreign type or has the form---   @'IO' t@ where @t@ is a marshallable foreign type or @()@.------ A value of type @'FunPtr' a@ may be a pointer to a foreign function,--- either returned by another foreign function or imported with a--- a static address import like------ > foreign import ccall "stdlib.h &free"--- >   p_free :: FunPtr (Ptr a -> IO ())------ or a pointer to a Haskell function created using a /wrapper/ stub--- declared to produce a 'FunPtr' of the correct type.  For example:------ > type Compare = Int -> Int -> Bool--- > foreign import ccall "wrapper"--- >   mkCompare :: Compare -> IO (FunPtr Compare)------ Calls to wrapper stubs like @mkCompare@ allocate storage, which--- should be released with 'Foreign.Ptr.freeHaskellFunPtr' when no--- longer required.------ To convert 'FunPtr' values to corresponding Haskell functions, one--- can define a /dynamic/ stub for the specific foreign type, e.g.------ > type IntFunction = CInt -> IO ()--- > foreign import ccall "dynamic"--- >   mkFun :: FunPtr IntFunction -> IntFunction---- |The constant 'nullFunPtr' contains a--- distinguished value of 'FunPtr' that is not--- associated with a valid memory location.-nullFunPtr :: FunPtr a-nullFunPtr = FunPtr nullAddr#---- |Casts a 'FunPtr' to a 'FunPtr' of a different type.-castFunPtr :: FunPtr a -> FunPtr b-castFunPtr = coerce---- |Casts a 'FunPtr' to a 'Ptr'.------ /Note:/ this is valid only on architectures where data and function--- pointers range over the same set of addresses, and should only be used--- for bindings to external libraries whose interface already relies on--- this assumption.-castFunPtrToPtr :: FunPtr a -> Ptr b-castFunPtrToPtr (FunPtr addr) = Ptr addr---- |Casts a 'Ptr' to a 'FunPtr'.------ /Note:/ this is valid only on architectures where data and function--- pointers range over the same set of addresses, and should only be used--- for bindings to external libraries whose interface already relies on--- this assumption.-castPtrToFunPtr :: Ptr a -> FunPtr b-castPtrToFunPtr (Ptr addr) = FunPtr addr------------------------------------------------------------------------------ Show instances for Ptr and FunPtr--instance Show (Ptr a) where-   showsPrec _ (Ptr a) rs = pad_out (showHex (wordToInteger(int2Word#(addr2Int# a))) "")-     where-        -- want 0s prefixed to pad it out to a fixed length.-       pad_out ls =-          '0':'x':(replicate (2*SIZEOF_HSPTR - length ls) '0') ++ ls ++ rs--instance Show (FunPtr a) where-   showsPrec p = showsPrec p . castFunPtrToPtr
− GHC/RTS/Flags.hsc
@@ -1,457 +0,0 @@-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE RecordWildCards   #-}---- | Accessors to GHC RTS flags.--- Descriptions of flags can be seen in--- <https://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html GHC User's Guide>,--- or by running RTS help message using @+RTS --help@.------ @since 4.8.0.0----module GHC.RTS.Flags-  ( RtsTime-  , RtsNat-  , RTSFlags (..)-  , GiveGCStats (..)-  , GCFlags (..)-  , ConcFlags (..)-  , MiscFlags (..)-  , DebugFlags (..)-  , DoCostCentres (..)-  , CCFlags (..)-  , DoHeapProfile (..)-  , ProfFlags (..)-  , DoTrace (..)-  , TraceFlags (..)-  , TickyFlags (..)-  , getRTSFlags-  , getGCFlags-  , getConcFlags-  , getMiscFlags-  , getDebugFlags-  , getCCFlags-  , getProfFlags-  , getTraceFlags-  , getTickyFlags-  ) where--#include "Rts.h"-#include "rts/Flags.h"--import Control.Applicative-import Control.Monad--import Foreign.C.String    (peekCString)-import Foreign.C.Types     (CChar, CInt)-import Foreign.Ptr         (Ptr, nullPtr)-import Foreign.Storable    (peekByteOff)--import GHC.Base-import GHC.Enum-import GHC.IO-import GHC.Real-import GHC.Show-import GHC.Word---- | @'Time'@ is defined as a @'StgWord64'@ in @stg/Types.h@------ @since 4.8.2.0-type RtsTime = Word64---- | @'nat'@ defined in @rts/Types.h@------ @since 4.8.2.0-type RtsNat = #{type unsigned int}---- | Should we produce a summary of the garbage collector statistics after the--- program has exited?------ @since 4.8.2.0-data GiveGCStats-    = NoGCStats-    | CollectGCStats-    | OneLineGCStats-    | SummaryGCStats-    | VerboseGCStats-    deriving (Show)--instance Enum GiveGCStats where-    fromEnum NoGCStats      = #{const NO_GC_STATS}-    fromEnum CollectGCStats = #{const COLLECT_GC_STATS}-    fromEnum OneLineGCStats = #{const ONELINE_GC_STATS}-    fromEnum SummaryGCStats = #{const SUMMARY_GC_STATS}-    fromEnum VerboseGCStats = #{const VERBOSE_GC_STATS}--    toEnum #{const NO_GC_STATS}      = NoGCStats-    toEnum #{const COLLECT_GC_STATS} = CollectGCStats-    toEnum #{const ONELINE_GC_STATS} = OneLineGCStats-    toEnum #{const SUMMARY_GC_STATS} = SummaryGCStats-    toEnum #{const VERBOSE_GC_STATS} = VerboseGCStats-    toEnum e = error ("invalid enum for GiveGCStats: " ++ show e)---- | Parameters of the garbage collector.------ @since 4.8.0.0-data GCFlags = GCFlags-    { statsFile             :: Maybe FilePath-    , giveStats             :: GiveGCStats-    , maxStkSize            :: RtsNat-    , initialStkSize        :: RtsNat-    , stkChunkSize          :: RtsNat-    , stkChunkBufferSize    :: RtsNat-    , maxHeapSize           :: RtsNat-    , minAllocAreaSize      :: RtsNat-    , minOldGenSize         :: RtsNat-    , heapSizeSuggestion    :: RtsNat-    , heapSizeSuggestionAuto :: Bool-    , oldGenFactor          :: Double-    , pcFreeHeap            :: Double-    , generations           :: RtsNat-    , steps                 :: RtsNat-    , squeezeUpdFrames      :: Bool-    , compact               :: Bool -- ^ True <=> "compact all the time"-    , compactThreshold      :: Double-    , sweep                 :: Bool-      -- ^ use "mostly mark-sweep" instead of copying for the oldest generation-    , ringBell              :: Bool-    , frontpanel            :: Bool-    , idleGCDelayTime       :: RtsTime-    , doIdleGC              :: Bool-    , heapBase              :: Word -- ^ address to ask the OS for memory-    , allocLimitGrace       :: Word-    } deriving (Show)---- | Parameters concerning context switching------ @since 4.8.0.0-data ConcFlags = ConcFlags-    { ctxtSwitchTime  :: RtsTime-    , ctxtSwitchTicks :: Int-    } deriving (Show)---- | Miscellaneous parameters------ @since 4.8.0.0-data MiscFlags = MiscFlags-    { tickInterval          :: RtsTime-    , installSignalHandlers :: Bool-    , machineReadable       :: Bool-    , linkerMemBase         :: Word-      -- ^ address to ask the OS for memory for the linker, 0 ==> off-    } deriving (Show)---- | Flags to control debugging output & extra checking in various--- subsystems.------ @since 4.8.0.0-data DebugFlags = DebugFlags-    { scheduler   :: Bool -- ^ 's'-    , interpreter :: Bool -- ^ 'i'-    , weak        :: Bool -- ^ 'w'-    , gccafs      :: Bool -- ^ 'G'-    , gc          :: Bool -- ^ 'g'-    , block_alloc :: Bool -- ^ 'b'-    , sanity      :: Bool -- ^ 'S'-    , stable      :: Bool -- ^ 't'-    , prof        :: Bool -- ^ 'p'-    , linker      :: Bool -- ^ 'l' the object linker-    , apply       :: Bool -- ^ 'a'-    , stm         :: Bool -- ^ 'm'-    , squeeze     :: Bool -- ^ 'z' stack squeezing & lazy blackholing-    , hpc         :: Bool -- ^ 'c' coverage-    , sparks      :: Bool -- ^ 'r'-    } deriving (Show)---- | Should the RTS produce a cost-center summary?------ @since 4.8.2.0-data DoCostCentres-    = CostCentresNone-    | CostCentresSummary-    | CostCentresVerbose-    | CostCentresAll-    | CostCentresXML-    deriving (Show)--instance Enum DoCostCentres where-    fromEnum CostCentresNone    = #{const COST_CENTRES_NONE}-    fromEnum CostCentresSummary = #{const COST_CENTRES_SUMMARY}-    fromEnum CostCentresVerbose = #{const COST_CENTRES_VERBOSE}-    fromEnum CostCentresAll     = #{const COST_CENTRES_ALL}-    fromEnum CostCentresXML     = #{const COST_CENTRES_XML}--    toEnum #{const COST_CENTRES_NONE}    = CostCentresNone-    toEnum #{const COST_CENTRES_SUMMARY} = CostCentresSummary-    toEnum #{const COST_CENTRES_VERBOSE} = CostCentresVerbose-    toEnum #{const COST_CENTRES_ALL}     = CostCentresAll-    toEnum #{const COST_CENTRES_XML}     = CostCentresXML-    toEnum e = error ("invalid enum for DoCostCentres: " ++ show e)---- | Parameters pertaining to the cost-center profiler.------ @since 4.8.0.0-data CCFlags = CCFlags-    { doCostCentres :: DoCostCentres-    , profilerTicks :: Int-    , msecsPerTick  :: Int-    } deriving (Show)---- | What sort of heap profile are we collecting?------ @since 4.8.2.0-data DoHeapProfile-    = NoHeapProfiling-    | HeapByCCS-    | HeapByMod-    | HeapByDescr-    | HeapByType-    | HeapByRetainer-    | HeapByLDV-    | HeapByClosureType-    deriving (Show)--instance Enum DoHeapProfile where-    fromEnum NoHeapProfiling   = #{const NO_HEAP_PROFILING}-    fromEnum HeapByCCS         = #{const HEAP_BY_CCS}-    fromEnum HeapByMod         = #{const HEAP_BY_MOD}-    fromEnum HeapByDescr       = #{const HEAP_BY_DESCR}-    fromEnum HeapByType        = #{const HEAP_BY_TYPE}-    fromEnum HeapByRetainer    = #{const HEAP_BY_RETAINER}-    fromEnum HeapByLDV         = #{const HEAP_BY_LDV}-    fromEnum HeapByClosureType = #{const HEAP_BY_CLOSURE_TYPE}--    toEnum #{const NO_HEAP_PROFILING}    = NoHeapProfiling-    toEnum #{const HEAP_BY_CCS}          = HeapByCCS-    toEnum #{const HEAP_BY_MOD}          = HeapByMod-    toEnum #{const HEAP_BY_DESCR}        = HeapByDescr-    toEnum #{const HEAP_BY_TYPE}         = HeapByType-    toEnum #{const HEAP_BY_RETAINER}     = HeapByRetainer-    toEnum #{const HEAP_BY_LDV}          = HeapByLDV-    toEnum #{const HEAP_BY_CLOSURE_TYPE} = HeapByClosureType-    toEnum e = error ("invalid enum for DoHeapProfile: " ++ show e)---- | Parameters of the cost-center profiler------ @since 4.8.0.0-data ProfFlags = ProfFlags-    { doHeapProfile            :: DoHeapProfile-    , heapProfileInterval      :: RtsTime -- ^ time between samples-    , heapProfileIntervalTicks :: Word    -- ^ ticks between samples (derived)-    , includeTSOs              :: Bool-    , showCCSOnException       :: Bool-    , maxRetainerSetSize       :: Word-    , ccsLength                :: Word-    , modSelector              :: Maybe String-    , descrSelector            :: Maybe String-    , typeSelector             :: Maybe String-    , ccSelector               :: Maybe String-    , ccsSelector              :: Maybe String-    , retainerSelector         :: Maybe String-    , bioSelector              :: Maybe String-    } deriving (Show)---- | Is event tracing enabled?------ @since 4.8.2.0-data DoTrace-    = TraceNone      -- ^ no tracing-    | TraceEventLog  -- ^ send tracing events to the event log-    | TraceStderr    -- ^ send tracing events to @stderr@-    deriving (Show)--instance Enum DoTrace where-    fromEnum TraceNone     = #{const TRACE_NONE}-    fromEnum TraceEventLog = #{const TRACE_EVENTLOG}-    fromEnum TraceStderr   = #{const TRACE_STDERR}--    toEnum #{const TRACE_NONE}     = TraceNone-    toEnum #{const TRACE_EVENTLOG} = TraceEventLog-    toEnum #{const TRACE_STDERR}   = TraceStderr-    toEnum e = error ("invalid enum for DoTrace: " ++ show e)---- | Parameters pertaining to event tracing------ @since 4.8.0.0-data TraceFlags = TraceFlags-    { tracing        :: DoTrace-    , timestamp      :: Bool -- ^ show timestamp in stderr output-    , traceScheduler :: Bool -- ^ trace scheduler events-    , traceGc        :: Bool -- ^ trace GC events-    , sparksSampled  :: Bool -- ^ trace spark events by a sampled method-    , sparksFull     :: Bool -- ^ trace spark events 100% accurately-    , user           :: Bool -- ^ trace user events (emitted from Haskell code)-    } deriving (Show)---- | Parameters pertaining to ticky-ticky profiler------ @since 4.8.0.0-data TickyFlags = TickyFlags-    { showTickyStats :: Bool-    , tickyFile      :: Maybe FilePath-    } deriving (Show)---- | Parameters of the runtime system------ @since 4.8.0.0-data RTSFlags = RTSFlags-    { gcFlags         :: GCFlags-    , concurrentFlags :: ConcFlags-    , miscFlags       :: MiscFlags-    , debugFlags      :: DebugFlags-    , costCentreFlags :: CCFlags-    , profilingFlags  :: ProfFlags-    , traceFlags      :: TraceFlags-    , tickyFlags      :: TickyFlags-    } deriving (Show)--foreign import ccall safe "getGcFlags"-  getGcFlagsPtr :: IO (Ptr ())--foreign import ccall safe "getConcFlags"-  getConcFlagsPtr :: IO (Ptr ())--foreign import ccall safe "getMiscFlags"-  getMiscFlagsPtr :: IO (Ptr ())--foreign import ccall safe "getDebugFlags"-  getDebugFlagsPtr :: IO (Ptr ())--foreign import ccall safe "getCcFlags"-  getCcFlagsPtr :: IO (Ptr ())--foreign import ccall safe "getProfFlags" getProfFlagsPtr :: IO (Ptr ())--foreign import ccall safe "getTraceFlags"-  getTraceFlagsPtr :: IO (Ptr ())--foreign import ccall safe "getTickyFlags"-  getTickyFlagsPtr :: IO (Ptr ())--getRTSFlags :: IO RTSFlags-getRTSFlags = do-  RTSFlags <$> getGCFlags-           <*> getConcFlags-           <*> getMiscFlags-           <*> getDebugFlags-           <*> getCCFlags-           <*> getProfFlags-           <*> getTraceFlags-           <*> getTickyFlags--peekFilePath :: Ptr () -> IO (Maybe FilePath)-peekFilePath ptr-  | ptr == nullPtr = return Nothing-  | otherwise      = return (Just "<filepath>")---- | Read a NUL terminated string. Return Nothing in case of a NULL pointer.-peekCStringOpt :: Ptr CChar -> IO (Maybe String)-peekCStringOpt ptr-  | ptr == nullPtr = return Nothing-  | otherwise      = Just <$> peekCString ptr--getGCFlags :: IO GCFlags-getGCFlags = do-  ptr <- getGcFlagsPtr-  GCFlags <$> (peekFilePath =<< #{peek GC_FLAGS, statsFile} ptr)-          <*> (toEnum . fromIntegral <$>-                (#{peek GC_FLAGS, giveStats} ptr :: IO RtsNat))-          <*> #{peek GC_FLAGS, maxStkSize} ptr-          <*> #{peek GC_FLAGS, initialStkSize} ptr-          <*> #{peek GC_FLAGS, stkChunkSize} ptr-          <*> #{peek GC_FLAGS, stkChunkBufferSize} ptr-          <*> #{peek GC_FLAGS, maxHeapSize} ptr-          <*> #{peek GC_FLAGS, minAllocAreaSize} ptr-          <*> #{peek GC_FLAGS, minOldGenSize} ptr-          <*> #{peek GC_FLAGS, heapSizeSuggestion} ptr-          <*> #{peek GC_FLAGS, heapSizeSuggestionAuto} ptr-          <*> #{peek GC_FLAGS, oldGenFactor} ptr-          <*> #{peek GC_FLAGS, pcFreeHeap} ptr-          <*> #{peek GC_FLAGS, generations} ptr-          <*> #{peek GC_FLAGS, steps} ptr-          <*> #{peek GC_FLAGS, squeezeUpdFrames} ptr-          <*> #{peek GC_FLAGS, compact} ptr-          <*> #{peek GC_FLAGS, compactThreshold} ptr-          <*> #{peek GC_FLAGS, sweep} ptr-          <*> #{peek GC_FLAGS, ringBell} ptr-          <*> #{peek GC_FLAGS, frontpanel} ptr-          <*> #{peek GC_FLAGS, idleGCDelayTime} ptr-          <*> #{peek GC_FLAGS, doIdleGC} ptr-          <*> #{peek GC_FLAGS, heapBase} ptr-          <*> #{peek GC_FLAGS, allocLimitGrace} ptr--getConcFlags :: IO ConcFlags-getConcFlags = do-  ptr <- getConcFlagsPtr-  ConcFlags <$> #{peek CONCURRENT_FLAGS, ctxtSwitchTime} ptr-            <*> #{peek CONCURRENT_FLAGS, ctxtSwitchTicks} ptr--getMiscFlags :: IO MiscFlags-getMiscFlags = do-  ptr <- getMiscFlagsPtr-  MiscFlags <$> #{peek MISC_FLAGS, tickInterval} ptr-            <*> #{peek MISC_FLAGS, install_signal_handlers} ptr-            <*> #{peek MISC_FLAGS, machineReadable} ptr-            <*> #{peek MISC_FLAGS, linkerMemBase} ptr--getDebugFlags :: IO DebugFlags-getDebugFlags = do-  ptr <- getDebugFlagsPtr-  DebugFlags <$> #{peek DEBUG_FLAGS, scheduler} ptr-             <*> #{peek DEBUG_FLAGS, interpreter} ptr-             <*> #{peek DEBUG_FLAGS, weak} ptr-             <*> #{peek DEBUG_FLAGS, gccafs} ptr-             <*> #{peek DEBUG_FLAGS, gc} ptr-             <*> #{peek DEBUG_FLAGS, block_alloc} ptr-             <*> #{peek DEBUG_FLAGS, sanity} ptr-             <*> #{peek DEBUG_FLAGS, stable} ptr-             <*> #{peek DEBUG_FLAGS, prof} ptr-             <*> #{peek DEBUG_FLAGS, linker} ptr-             <*> #{peek DEBUG_FLAGS, apply} ptr-             <*> #{peek DEBUG_FLAGS, stm} ptr-             <*> #{peek DEBUG_FLAGS, squeeze} ptr-             <*> #{peek DEBUG_FLAGS, hpc} ptr-             <*> #{peek DEBUG_FLAGS, sparks} ptr--getCCFlags :: IO CCFlags-getCCFlags = do-  ptr <- getCcFlagsPtr-  CCFlags <$> (toEnum . fromIntegral-                <$> (#{peek COST_CENTRE_FLAGS, doCostCentres} ptr :: IO RtsNat))-          <*> #{peek COST_CENTRE_FLAGS, profilerTicks} ptr-          <*> #{peek COST_CENTRE_FLAGS, msecsPerTick} ptr--getProfFlags :: IO ProfFlags-getProfFlags = do-  ptr <- getProfFlagsPtr-  ProfFlags <$> (toEnum <$> #{peek PROFILING_FLAGS, doHeapProfile} ptr)-            <*> #{peek PROFILING_FLAGS, heapProfileInterval} ptr-            <*> #{peek PROFILING_FLAGS, heapProfileIntervalTicks} ptr-            <*> #{peek PROFILING_FLAGS, includeTSOs} ptr-            <*> #{peek PROFILING_FLAGS, showCCSOnException} ptr-            <*> #{peek PROFILING_FLAGS, maxRetainerSetSize} ptr-            <*> #{peek PROFILING_FLAGS, ccsLength} ptr-            <*> (peekCStringOpt =<< #{peek PROFILING_FLAGS, modSelector} ptr)-            <*> (peekCStringOpt =<< #{peek PROFILING_FLAGS, descrSelector} ptr)-            <*> (peekCStringOpt =<< #{peek PROFILING_FLAGS, typeSelector} ptr)-            <*> (peekCStringOpt =<< #{peek PROFILING_FLAGS, ccSelector} ptr)-            <*> (peekCStringOpt =<< #{peek PROFILING_FLAGS, ccsSelector} ptr)-            <*> (peekCStringOpt =<< #{peek PROFILING_FLAGS, retainerSelector} ptr)-            <*> (peekCStringOpt =<< #{peek PROFILING_FLAGS, bioSelector} ptr)--getTraceFlags :: IO TraceFlags-getTraceFlags = do-  ptr <- getTraceFlagsPtr-  TraceFlags <$> (toEnum . fromIntegral-                   <$> (#{peek TRACE_FLAGS, tracing} ptr :: IO CInt))-             <*> #{peek TRACE_FLAGS, timestamp} ptr-             <*> #{peek TRACE_FLAGS, scheduler} ptr-             <*> #{peek TRACE_FLAGS, gc} ptr-             <*> #{peek TRACE_FLAGS, sparks_sampled} ptr-             <*> #{peek TRACE_FLAGS, sparks_full} ptr-             <*> #{peek TRACE_FLAGS, user} ptr--getTickyFlags :: IO TickyFlags-getTickyFlags = do-  ptr <- getTickyFlagsPtr-  TickyFlags <$> #{peek TICKY_FLAGS, showTickyStats} ptr-             <*> (peekFilePath =<< #{peek TICKY_FLAGS, tickyFile} ptr)
− GHC/Read.hs
@@ -1,650 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, StandaloneDeriving, ScopedTypeVariables #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Read--- Copyright   :  (c) The University of Glasgow, 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The 'Read' class and instances for basic data types.-----------------------------------------------------------------------------------module GHC.Read-  ( Read(..)   -- class--  -- ReadS type-  , ReadS--  -- H2010 compatibility-  , lex-  , lexLitChar-  , readLitChar-  , lexDigits--  -- defining readers-  , lexP, expectP-  , paren-  , parens-  , list-  , choose-  , readListDefault, readListPrecDefault-  , readNumber--  -- Temporary-  , readParen-  )- where--import qualified Text.ParserCombinators.ReadP as P--import Text.ParserCombinators.ReadP-  ( ReadS-  , readP_to_S-  )--import qualified Text.Read.Lex as L--- Lex exports 'lex', which is also defined here,--- hence the qualified import.--- We can't import *anything* unqualified, because that--- confuses Haddock.--import Text.ParserCombinators.ReadPrec--import Data.Maybe--import GHC.Unicode       ( isDigit )-import GHC.Num-import GHC.Real-import GHC.Float-import GHC.Show-import GHC.Base-import GHC.Arr----- | @'readParen' 'True' p@ parses what @p@ parses, but surrounded with--- parentheses.------ @'readParen' 'False' p@ parses what @p@ parses, but optionally--- surrounded with parentheses.-readParen       :: Bool -> ReadS a -> ReadS a--- A Haskell 2010 function-readParen b g   =  if b then mandatory else optional-                   where optional r  = g r ++ mandatory r-                         mandatory r = do-                                ("(",s) <- lex r-                                (x,t)   <- optional s-                                (")",u) <- lex t-                                return (x,u)---- | Parsing of 'String's, producing values.------ Derived instances of 'Read' make the following assumptions, which--- derived instances of 'Text.Show.Show' obey:------ * If the constructor is defined to be an infix operator, then the---   derived 'Read' instance will parse only infix applications of---   the constructor (not the prefix form).------ * Associativity is not used to reduce the occurrence of parentheses,---   although precedence may be.------ * If the constructor is defined using record syntax, the derived 'Read'---   will parse only the record-syntax form, and furthermore, the fields---   must be given in the same order as the original declaration.------ * The derived 'Read' instance allows arbitrary Haskell whitespace---   between tokens of the input string.  Extra parentheses are also---   allowed.------ For example, given the declarations------ > infixr 5 :^:--- > data Tree a =  Leaf a  |  Tree a :^: Tree a------ the derived instance of 'Read' in Haskell 2010 is equivalent to------ > instance (Read a) => Read (Tree a) where--- >--- >         readsPrec d r =  readParen (d > app_prec)--- >                          (\r -> [(Leaf m,t) |--- >                                  ("Leaf",s) <- lex r,--- >                                  (m,t) <- readsPrec (app_prec+1) s]) r--- >--- >                       ++ readParen (d > up_prec)--- >                          (\r -> [(u:^:v,w) |--- >                                  (u,s) <- readsPrec (up_prec+1) r,--- >                                  (":^:",t) <- lex s,--- >                                  (v,w) <- readsPrec (up_prec+1) t]) r--- >--- >           where app_prec = 10--- >                 up_prec = 5------ Note that right-associativity of @:^:@ is unused.------ The derived instance in GHC is equivalent to------ > instance (Read a) => Read (Tree a) where--- >--- >         readPrec = parens $ (prec app_prec $ do--- >                                  Ident "Leaf" <- lexP--- >                                  m <- step readPrec--- >                                  return (Leaf m))--- >--- >                      +++ (prec up_prec $ do--- >                                  u <- step readPrec--- >                                  Symbol ":^:" <- lexP--- >                                  v <- step readPrec--- >                                  return (u :^: v))--- >--- >           where app_prec = 10--- >                 up_prec = 5--- >--- >         readListPrec = readListPrecDefault--class Read a where-  {-# MINIMAL readsPrec | readPrec #-}--  -- | attempts to parse a value from the front of the string, returning-  -- a list of (parsed value, remaining string) pairs.  If there is no-  -- successful parse, the returned list is empty.-  ---  -- Derived instances of 'Read' and 'Text.Show.Show' satisfy the following:-  ---  -- * @(x,\"\")@ is an element of-  --   @('readsPrec' d ('Text.Show.showsPrec' d x \"\"))@.-  ---  -- That is, 'readsPrec' parses the string produced by-  -- 'Text.Show.showsPrec', and delivers the value that-  -- 'Text.Show.showsPrec' started with.--  readsPrec    :: Int   -- ^ the operator precedence of the enclosing-                        -- context (a number from @0@ to @11@).-                        -- Function application has precedence @10@.-                -> ReadS a--  -- | The method 'readList' is provided to allow the programmer to-  -- give a specialised way of parsing lists of values.-  -- For example, this is used by the predefined 'Read' instance of-  -- the 'Char' type, where values of type 'String' should be are-  -- expected to use double quotes, rather than square brackets.-  readList     :: ReadS [a]--  -- | Proposed replacement for 'readsPrec' using new-style parsers (GHC only).-  readPrec     :: ReadPrec a--  -- | Proposed replacement for 'readList' using new-style parsers (GHC only).-  -- The default definition uses 'readList'.  Instances that define 'readPrec'-  -- should also define 'readListPrec' as 'readListPrecDefault'.-  readListPrec :: ReadPrec [a]--  -- default definitions-  readsPrec    = readPrec_to_S readPrec-  readList     = readPrec_to_S (list readPrec) 0-  readPrec     = readS_to_Prec readsPrec-  readListPrec = readS_to_Prec (\_ -> readList)--readListDefault :: Read a => ReadS [a]--- ^ A possible replacement definition for the 'readList' method (GHC only).---   This is only needed for GHC, and even then only for 'Read' instances---   where 'readListPrec' isn't defined as 'readListPrecDefault'.-readListDefault = readPrec_to_S readListPrec 0--readListPrecDefault :: Read a => ReadPrec [a]--- ^ A possible replacement definition for the 'readListPrec' method,---   defined using 'readPrec' (GHC only).-readListPrecDefault = list readPrec----------------------------------------------------------------------------- H2010 compatibility---- | The 'lex' function reads a single lexeme from the input, discarding--- initial white space, and returning the characters that constitute the--- lexeme.  If the input string contains only white space, 'lex' returns a--- single successful \`lexeme\' consisting of the empty string.  (Thus--- @'lex' \"\" = [(\"\",\"\")]@.)  If there is no legal lexeme at the--- beginning of the input string, 'lex' fails (i.e. returns @[]@).------ This lexer is not completely faithful to the Haskell lexical syntax--- in the following respects:------ * Qualified names are not handled properly------ * Octal and hexadecimal numerics are not recognized as a single token------ * Comments are not treated properly-lex :: ReadS String             -- As defined by H2010-lex s  = readP_to_S L.hsLex s---- | Read a string representation of a character, using Haskell--- source-language escape conventions.  For example:------ > lexLitChar  "\\nHello"  =  [("\\n", "Hello")]----lexLitChar :: ReadS String      -- As defined by H2010-lexLitChar = readP_to_S (do { (s, _) <- P.gather L.lexChar ;-                              return s })-        -- There was a skipSpaces before the P.gather L.lexChar,-        -- but that seems inconsistent with readLitChar---- | Read a string representation of a character, using Haskell--- source-language escape conventions, and convert it to the character--- that it encodes.  For example:------ > readLitChar "\\nHello"  =  [('\n', "Hello")]----readLitChar :: ReadS Char       -- As defined by H2010-readLitChar = readP_to_S L.lexChar---- | Reads a non-empty string of decimal digits.-lexDigits :: ReadS String-lexDigits = readP_to_S (P.munch1 isDigit)----------------------------------------------------------------------------- utility parsers--lexP :: ReadPrec L.Lexeme--- ^ Parse a single lexeme-lexP = lift L.lex--expectP :: L.Lexeme -> ReadPrec ()-expectP lexeme = lift (L.expect lexeme)--paren :: ReadPrec a -> ReadPrec a--- ^ @(paren p)@ parses \"(P0)\"---      where @p@ parses \"P0\" in precedence context zero-paren p = do expectP (L.Punc "(")-             x <- reset p-             expectP (L.Punc ")")-             return x--parens :: ReadPrec a -> ReadPrec a--- ^ @(parens p)@ parses \"P\", \"(P0)\", \"((P0))\", etc,---      where @p@ parses \"P\"  in the current precedence context---          and parses \"P0\" in precedence context zero-parens p = optional- where-  optional  = p +++ mandatory-  mandatory = paren optional--list :: ReadPrec a -> ReadPrec [a]--- ^ @(list p)@ parses a list of things parsed by @p@,--- using the usual square-bracket syntax.-list readx =-  parens-  ( do expectP (L.Punc "[")-       (listRest False +++ listNext)-  )- where-  listRest started =-    do L.Punc c <- lexP-       case c of-         "]"           -> return []-         "," | started -> listNext-         _             -> pfail--  listNext =-    do x  <- reset readx-       xs <- listRest True-       return (x:xs)--choose :: [(String, ReadPrec a)] -> ReadPrec a--- ^ Parse the specified lexeme and continue as specified.--- Esp useful for nullary constructors; e.g.---    @choose [(\"A\", return A), (\"B\", return B)]@--- We match both Ident and Symbol because the constructor--- might be an operator eg @(:~:)@-choose sps = foldr ((+++) . try_one) pfail sps-           where-             try_one (s,p) = do { token <- lexP ;-                                  case token of-                                    L.Ident s'  | s==s' -> p-                                    L.Symbol s' | s==s' -> p-                                    _other              -> pfail }------------------------------------------------------------------- Simple instances of Read-----------------------------------------------------------------instance Read Char where-  readPrec =-    parens-    ( do L.Char c <- lexP-         return c-    )--  readListPrec =-    parens-    ( do L.String s <- lexP     -- Looks for "foo"-         return s-     +++-      readListPrecDefault       -- Looks for ['f','o','o']-    )                           -- (more generous than H2010 spec)--  readList = readListDefault--instance Read Bool where-  readPrec =-    parens-    ( do L.Ident s <- lexP-         case s of-           "True"  -> return True-           "False" -> return False-           _       -> pfail-    )--  readListPrec = readListPrecDefault-  readList     = readListDefault--instance Read Ordering where-  readPrec =-    parens-    ( do L.Ident s <- lexP-         case s of-           "LT" -> return LT-           "EQ" -> return EQ-           "GT" -> return GT-           _    -> pfail-    )--  readListPrec = readListPrecDefault-  readList     = readListDefault------------------------------------------------------------------- Structure instances of Read: Maybe, List etc-----------------------------------------------------------------{--For structured instances of Read we start using the precedences.  The-idea is then that 'parens (prec k p)' will fail immediately when trying-to parse it in a context with a higher precedence level than k. But if-there is one parenthesis parsed, then the required precedence level-drops to 0 again, and parsing inside p may succeed.--'appPrec' is just the precedence level of function application.  So,-if we are parsing function application, we'd better require the-precedence level to be at least 'appPrec'. Otherwise, we have to put-parentheses around it.--'step' is used to increase the precedence levels inside a-parser, and can be used to express left- or right- associativity. For-example, % is defined to be left associative, so we only increase-precedence on the right hand side.--Note how step is used in for example the Maybe parser to increase the-precedence beyond appPrec, so that basically only literals and-parenthesis-like objects such as (...) and [...] can be an argument to-'Just'.--}--instance Read a => Read (Maybe a) where-  readPrec =-    parens-    (do expectP (L.Ident "Nothing")-        return Nothing-     +++-     prec appPrec (-        do expectP (L.Ident "Just")-           x <- step readPrec-           return (Just x))-    )--  readListPrec = readListPrecDefault-  readList     = readListDefault--instance Read a => Read [a] where-  {-# SPECIALISE instance Read [String] #-}-  {-# SPECIALISE instance Read [Char] #-}-  {-# SPECIALISE instance Read [Int] #-}-  readPrec     = readListPrec-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance  (Ix a, Read a, Read b) => Read (Array a b)  where-    readPrec = parens $ prec appPrec $-               do expectP (L.Ident "array")-                  theBounds <- step readPrec-                  vals   <- step readPrec-                  return (array theBounds vals)--    readListPrec = readListPrecDefault-    readList     = readListDefault--instance Read L.Lexeme where-  readPrec     = lexP-  readListPrec = readListPrecDefault-  readList     = readListDefault------------------------------------------------------------------- Numeric instances of Read-----------------------------------------------------------------readNumber :: Num a => (L.Lexeme -> ReadPrec a) -> ReadPrec a--- Read a signed number-readNumber convert =-  parens-  ( do x <- lexP-       case x of-         L.Symbol "-" -> do y <- lexP-                            n <- convert y-                            return (negate n)--         _   -> convert x-  )---convertInt :: Num a => L.Lexeme -> ReadPrec a-convertInt (L.Number n)- | Just i <- L.numberToInteger n = return (fromInteger i)-convertInt _ = pfail--convertFrac :: forall a . RealFloat a => L.Lexeme -> ReadPrec a-convertFrac (L.Ident "NaN")      = return (0 / 0)-convertFrac (L.Ident "Infinity") = return (1 / 0)-convertFrac (L.Number n) = let resRange = floatRange (undefined :: a)-                           in case L.numberToRangedRational resRange n of-                              Nothing -> return (1 / 0)-                              Just rat -> return $ fromRational rat-convertFrac _            = pfail--instance Read Int where-  readPrec     = readNumber convertInt-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance Read Word where-    readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]--instance Read Integer where-  readPrec     = readNumber convertInt-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance Read Float where-  readPrec     = readNumber convertFrac-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance Read Double where-  readPrec     = readNumber convertFrac-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Integral a, Read a) => Read (Ratio a) where-  readPrec =-    parens-    ( prec ratioPrec-      ( do x <- step readPrec-           expectP (L.Symbol "%")-           y <- step readPrec-           return (x % y)-      )-    )--  readListPrec = readListPrecDefault-  readList     = readListDefault------------------------------------------------------------------------------ Tuple instances of Read, up to size 15---------------------------------------------------------------------------instance Read () where-  readPrec =-    parens-    ( paren-      ( return ()-      )-    )--  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b) => Read (a,b) where-  readPrec = wrap_tup read_tup2-  readListPrec = readListPrecDefault-  readList     = readListDefault--wrap_tup :: ReadPrec a -> ReadPrec a-wrap_tup p = parens (paren p)--read_comma :: ReadPrec ()-read_comma = expectP (L.Punc ",")--read_tup2 :: (Read a, Read b) => ReadPrec (a,b)--- Reads "a , b"  no parens!-read_tup2 = do x <- readPrec-               read_comma-               y <- readPrec-               return (x,y)--read_tup4 :: (Read a, Read b, Read c, Read d) => ReadPrec (a,b,c,d)-read_tup4 = do  (a,b) <- read_tup2-                read_comma-                (c,d) <- read_tup2-                return (a,b,c,d)---read_tup8 :: (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h)-          => ReadPrec (a,b,c,d,e,f,g,h)-read_tup8 = do  (a,b,c,d) <- read_tup4-                read_comma-                (e,f,g,h) <- read_tup4-                return (a,b,c,d,e,f,g,h)---instance (Read a, Read b, Read c) => Read (a, b, c) where-  readPrec = wrap_tup (do { (a,b) <- read_tup2; read_comma-                          ; c <- readPrec-                          ; return (a,b,c) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d) => Read (a, b, c, d) where-  readPrec = wrap_tup read_tup4-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e) => Read (a, b, c, d, e) where-  readPrec = wrap_tup (do { (a,b,c,d) <- read_tup4; read_comma-                          ; e <- readPrec-                          ; return (a,b,c,d,e) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f)-        => Read (a, b, c, d, e, f) where-  readPrec = wrap_tup (do { (a,b,c,d) <- read_tup4; read_comma-                          ; (e,f) <- read_tup2-                          ; return (a,b,c,d,e,f) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g)-        => Read (a, b, c, d, e, f, g) where-  readPrec = wrap_tup (do { (a,b,c,d) <- read_tup4; read_comma-                          ; (e,f) <- read_tup2; read_comma-                          ; g <- readPrec-                          ; return (a,b,c,d,e,f,g) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h)-        => Read (a, b, c, d, e, f, g, h) where-  readPrec     = wrap_tup read_tup8-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h,-          Read i)-        => Read (a, b, c, d, e, f, g, h, i) where-  readPrec = wrap_tup (do { (a,b,c,d,e,f,g,h) <- read_tup8; read_comma-                          ; i <- readPrec-                          ; return (a,b,c,d,e,f,g,h,i) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h,-          Read i, Read j)-        => Read (a, b, c, d, e, f, g, h, i, j) where-  readPrec = wrap_tup (do { (a,b,c,d,e,f,g,h) <- read_tup8; read_comma-                          ; (i,j) <- read_tup2-                          ; return (a,b,c,d,e,f,g,h,i,j) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h,-          Read i, Read j, Read k)-        => Read (a, b, c, d, e, f, g, h, i, j, k) where-  readPrec = wrap_tup (do { (a,b,c,d,e,f,g,h) <- read_tup8; read_comma-                          ; (i,j) <- read_tup2; read_comma-                          ; k <- readPrec-                          ; return (a,b,c,d,e,f,g,h,i,j,k) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h,-          Read i, Read j, Read k, Read l)-        => Read (a, b, c, d, e, f, g, h, i, j, k, l) where-  readPrec = wrap_tup (do { (a,b,c,d,e,f,g,h) <- read_tup8; read_comma-                          ; (i,j,k,l) <- read_tup4-                          ; return (a,b,c,d,e,f,g,h,i,j,k,l) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h,-          Read i, Read j, Read k, Read l, Read m)-        => Read (a, b, c, d, e, f, g, h, i, j, k, l, m) where-  readPrec = wrap_tup (do { (a,b,c,d,e,f,g,h) <- read_tup8; read_comma-                          ; (i,j,k,l) <- read_tup4; read_comma-                          ; m <- readPrec-                          ; return (a,b,c,d,e,f,g,h,i,j,k,l,m) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h,-          Read i, Read j, Read k, Read l, Read m, Read n)-        => Read (a, b, c, d, e, f, g, h, i, j, k, l, m, n) where-  readPrec = wrap_tup (do { (a,b,c,d,e,f,g,h) <- read_tup8; read_comma-                          ; (i,j,k,l) <- read_tup4; read_comma-                          ; (m,n) <- read_tup2-                          ; return (a,b,c,d,e,f,g,h,i,j,k,l,m,n) })-  readListPrec = readListPrecDefault-  readList     = readListDefault--instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h,-          Read i, Read j, Read k, Read l, Read m, Read n, Read o)-        => Read (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) where-  readPrec = wrap_tup (do { (a,b,c,d,e,f,g,h) <- read_tup8; read_comma-                          ; (i,j,k,l) <- read_tup4; read_comma-                          ; (m,n) <- read_tup2; read_comma-                          ; o <- readPrec-                          ; return (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) })-  readListPrec = readListPrecDefault-  readList     = readListDefault
− GHC/Real.hs
@@ -1,664 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples, BangPatterns #-}-{-# OPTIONS_GHC -fno-warn-orphans #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Real--- Copyright   :  (c) The University of Glasgow, 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The types 'Ratio' and 'Rational', and the classes 'Real', 'Fractional',--- 'Integral', and 'RealFrac'.-----------------------------------------------------------------------------------module GHC.Real where--import GHC.Base-import GHC.Num-import GHC.List-import GHC.Enum-import GHC.Show-import {-# SOURCE #-} GHC.Exception( divZeroException, overflowException, ratioZeroDenomException )--#ifdef OPTIMISE_INTEGER_GCD_LCM-# if defined(MIN_VERSION_integer_gmp)-import GHC.Integer.GMP.Internals-# else-#  error unsupported OPTIMISE_INTEGER_GCD_LCM configuration-# endif-#endif--infixr 8  ^, ^^-infixl 7  /, `quot`, `rem`, `div`, `mod`-infixl 7  %--default ()              -- Double isn't available yet,-                        -- and we shouldn't be using defaults anyway----------------------------------------------------------------------------- Divide by zero and arithmetic overflow----------------------------------------------------------------------------- We put them here because they are needed relatively early--- in the libraries before the Exception type has been defined yet.--{-# NOINLINE divZeroError #-}-divZeroError :: a-divZeroError = raise# divZeroException--{-# NOINLINE ratioZeroDenominatorError #-}-ratioZeroDenominatorError :: a-ratioZeroDenominatorError = raise# ratioZeroDenomException--{-# NOINLINE overflowError #-}-overflowError :: a-overflowError = raise# overflowException------------------------------------------------------------------- The Ratio and Rational types------------------------------------------------------------------- | Rational numbers, with numerator and denominator of some 'Integral' type.-data  Ratio a = !a :% !a  deriving (Eq)---- | Arbitrary-precision rational numbers, represented as a ratio of--- two 'Integer' values.  A rational number may be constructed using--- the '%' operator.-type  Rational          =  Ratio Integer--ratioPrec, ratioPrec1 :: Int-ratioPrec  = 7  -- Precedence of ':%' constructor-ratioPrec1 = ratioPrec + 1--infinity, notANumber :: Rational-infinity   = 1 :% 0-notANumber = 0 :% 0---- Use :%, not % for Inf/NaN; the latter would--- immediately lead to a runtime error, because it normalises.---- | Forms the ratio of two integral numbers.-{-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}-(%)                     :: (Integral a) => a -> a -> Ratio a---- | Extract the numerator of the ratio in reduced form:--- the numerator and denominator have no common factor and the denominator--- is positive.-numerator       :: (Integral a) => Ratio a -> a---- | Extract the denominator of the ratio in reduced form:--- the numerator and denominator have no common factor and the denominator--- is positive.-denominator     :: (Integral a) => Ratio a -> a----- | 'reduce' is a subsidiary function used only in this module.--- It normalises a ratio by dividing both numerator and denominator by--- their greatest common divisor.-reduce ::  (Integral a) => a -> a -> Ratio a-{-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}-reduce _ 0              =  ratioZeroDenominatorError-reduce x y              =  (x `quot` d) :% (y `quot` d)-                           where d = gcd x y--x % y                   =  reduce (x * signum y) (abs y)--numerator   (x :% _)    =  x-denominator (_ :% y)    =  y------------------------------------------------------------------- Standard numeric classes-----------------------------------------------------------------class  (Num a, Ord a) => Real a  where-    -- | the rational equivalent of its real argument with full precision-    toRational          ::  a -> Rational---- | Integral numbers, supporting integer division.-class  (Real a, Enum a) => Integral a  where-    -- | integer division truncated toward zero-    quot                :: a -> a -> a-    -- | integer remainder, satisfying-    ---    -- > (x `quot` y)*y + (x `rem` y) == x-    rem                 :: a -> a -> a-    -- | integer division truncated toward negative infinity-    div                 :: a -> a -> a-    -- | integer modulus, satisfying-    ---    -- > (x `div` y)*y + (x `mod` y) == x-    mod                 :: a -> a -> a-    -- | simultaneous 'quot' and 'rem'-    quotRem             :: a -> a -> (a,a)-    -- | simultaneous 'div' and 'mod'-    divMod              :: a -> a -> (a,a)-    -- | conversion to 'Integer'-    toInteger           :: a -> Integer--    {-# INLINE quot #-}-    {-# INLINE rem #-}-    {-# INLINE div #-}-    {-# INLINE mod #-}-    n `quot` d          =  q  where (q,_) = quotRem n d-    n `rem` d           =  r  where (_,r) = quotRem n d-    n `div` d           =  q  where (q,_) = divMod n d-    n `mod` d           =  r  where (_,r) = divMod n d--    divMod n d          =  if signum r == negate (signum d) then (q-1, r+d) else qr-                           where qr@(q,r) = quotRem n d---- | Fractional numbers, supporting real division.-class  (Num a) => Fractional a  where-    {-# MINIMAL fromRational, (recip | (/)) #-}--    -- | fractional division-    (/)                 :: a -> a -> a-    -- | reciprocal fraction-    recip               :: a -> a-    -- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@).-    -- A floating literal stands for an application of 'fromRational'-    -- to a value of type 'Rational', so such literals have type-    -- @('Fractional' a) => a@.-    fromRational        :: Rational -> a--    {-# INLINE recip #-}-    {-# INLINE (/) #-}-    recip x             =  1 / x-    x / y               = x * recip y---- | Extracting components of fractions.-class  (Real a, Fractional a) => RealFrac a  where-    -- | The function 'properFraction' takes a real fractional number @x@-    -- and returns a pair @(n,f)@ such that @x = n+f@, and:-    ---    -- * @n@ is an integral number with the same sign as @x@; and-    ---    -- * @f@ is a fraction with the same type and sign as @x@,-    --   and with absolute value less than @1@.-    ---    -- The default definitions of the 'ceiling', 'floor', 'truncate'-    -- and 'round' functions are in terms of 'properFraction'.-    properFraction      :: (Integral b) => a -> (b,a)-    -- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@-    truncate            :: (Integral b) => a -> b-    -- | @'round' x@ returns the nearest integer to @x@;-    --   the even integer if @x@ is equidistant between two integers-    round               :: (Integral b) => a -> b-    -- | @'ceiling' x@ returns the least integer not less than @x@-    ceiling             :: (Integral b) => a -> b-    -- | @'floor' x@ returns the greatest integer not greater than @x@-    floor               :: (Integral b) => a -> b--    {-# INLINE truncate #-}-    truncate x          =  m  where (m,_) = properFraction x--    round x             =  let (n,r) = properFraction x-                               m     = if r < 0 then n - 1 else n + 1-                           in case signum (abs r - 0.5) of-                                -1 -> n-                                0  -> if even n then n else m-                                1  -> m-                                _  -> error "round default defn: Bad value"--    ceiling x           =  if r > 0 then n + 1 else n-                           where (n,r) = properFraction x--    floor x             =  if r < 0 then n - 1 else n-                           where (n,r) = properFraction x---- These 'numeric' enumerations come straight from the Report--numericEnumFrom         :: (Fractional a) => a -> [a]-numericEnumFrom n       =  n `seq` (n : numericEnumFrom (n + 1))--numericEnumFromThen     :: (Fractional a) => a -> a -> [a]-numericEnumFromThen n m = n `seq` m `seq` (n : numericEnumFromThen m (m+m-n))--numericEnumFromTo       :: (Ord a, Fractional a) => a -> a -> [a]-numericEnumFromTo n m   = takeWhile (<= m + 1/2) (numericEnumFrom n)--numericEnumFromThenTo   :: (Ord a, Fractional a) => a -> a -> a -> [a]-numericEnumFromThenTo e1 e2 e3-    = takeWhile predicate (numericEnumFromThen e1 e2)-                                where-                                 mid = (e2 - e1) / 2-                                 predicate | e2 >= e1  = (<= e3 + mid)-                                           | otherwise = (>= e3 + mid)------------------------------------------------------------------- Instances for Int-----------------------------------------------------------------instance  Real Int  where-    toRational x        =  toInteger x :% 1--instance  Integral Int  where-    toInteger (I# i) = smallInteger i--    a `quot` b-     | b == 0                     = divZeroError-     | b == (-1) && a == minBound = overflowError -- Note [Order of tests]-                                                  -- in GHC.Int-     | otherwise                  =  a `quotInt` b--    a `rem` b-     | b == 0                     = divZeroError-       -- The quotRem CPU instruction fails for minBound `quotRem` -1,-       -- but minBound `rem` -1 is well-defined (0). We therefore-       -- special-case it.-     | b == (-1)                  = 0-     | otherwise                  =  a `remInt` b--    a `div` b-     | b == 0                     = divZeroError-     | b == (-1) && a == minBound = overflowError -- Note [Order of tests]-                                                  -- in GHC.Int-     | otherwise                  =  a `divInt` b--    a `mod` b-     | b == 0                     = divZeroError-       -- The divMod CPU instruction fails for minBound `divMod` -1,-       -- but minBound `mod` -1 is well-defined (0). We therefore-       -- special-case it.-     | b == (-1)                  = 0-     | otherwise                  =  a `modInt` b--    a `quotRem` b-     | b == 0                     = divZeroError-       -- Note [Order of tests] in GHC.Int-     | b == (-1) && a == minBound = (overflowError, 0)-     | otherwise                  =  a `quotRemInt` b--    a `divMod` b-     | b == 0                     = divZeroError-       -- Note [Order of tests] in GHC.Int-     | b == (-1) && a == minBound = (overflowError, 0)-     | otherwise                  =  a `divModInt` b------------------------------------------------------------------- Instances for @Word@-----------------------------------------------------------------instance Real Word where-    toRational x = toInteger x % 1--instance Integral Word where-    quot    (W# x#) y@(W# y#)-        | y /= 0                = W# (x# `quotWord#` y#)-        | otherwise             = divZeroError-    rem     (W# x#) y@(W# y#)-        | y /= 0                = W# (x# `remWord#` y#)-        | otherwise             = divZeroError-    div     (W# x#) y@(W# y#)-        | y /= 0                = W# (x# `quotWord#` y#)-        | otherwise             = divZeroError-    mod     (W# x#) y@(W# y#)-        | y /= 0                = W# (x# `remWord#` y#)-        | otherwise             = divZeroError-    quotRem (W# x#) y@(W# y#)-        | y /= 0                = case x# `quotRemWord#` y# of-                                  (# q, r #) ->-                                      (W# q, W# r)-        | otherwise             = divZeroError-    divMod  (W# x#) y@(W# y#)-        | y /= 0                = (W# (x# `quotWord#` y#), W# (x# `remWord#` y#))-        | otherwise             = divZeroError-    toInteger (W# x#)           = wordToInteger x#------------------------------------------------------------------- Instances for Integer-----------------------------------------------------------------instance  Real Integer  where-    toRational x        =  x :% 1---- Note [Integer division constant folding]--- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~------ Constant folding of quot, rem, div, mod, divMod and quotRem for--- Integer arguments depends crucially on inlining. Constant folding--- rules defined in compiler/prelude/PrelRules.lhs trigger for--- quotInteger, remInteger and so on. So if calls to quot, rem and so on--- were not inlined the rules would not fire. The rules would also not--- fire if calls to quotInteger and so on were inlined, but this does not--- happen because they are all marked with NOINLINE pragma - see documentation--- of integer-gmp or integer-simple.--instance  Integral Integer where-    toInteger n      = n--    {-# INLINE quot #-}-    _ `quot` 0 = divZeroError-    n `quot` d = n `quotInteger` d--    {-# INLINE rem #-}-    _ `rem` 0 = divZeroError-    n `rem` d = n `remInteger` d--    {-# INLINE div #-}-    _ `div` 0 = divZeroError-    n `div` d = n `divInteger` d--    {-# INLINE mod #-}-    _ `mod` 0 = divZeroError-    n `mod` d = n `modInteger` d--    {-# INLINE divMod #-}-    _ `divMod` 0 = divZeroError-    n `divMod` d = case n `divModInteger` d of-                     (# x, y #) -> (x, y)--    {-# INLINE quotRem #-}-    _ `quotRem` 0 = divZeroError-    n `quotRem` d = case n `quotRemInteger` d of-                      (# q, r #) -> (q, r)------------------------------------------------------------------- Instances for @Ratio@-----------------------------------------------------------------instance  (Integral a)  => Ord (Ratio a)  where-    {-# SPECIALIZE instance Ord Rational #-}-    (x:%y) <= (x':%y')  =  x * y' <= x' * y-    (x:%y) <  (x':%y')  =  x * y' <  x' * y--instance  (Integral a)  => Num (Ratio a)  where-    {-# SPECIALIZE instance Num Rational #-}-    (x:%y) + (x':%y')   =  reduce (x*y' + x'*y) (y*y')-    (x:%y) - (x':%y')   =  reduce (x*y' - x'*y) (y*y')-    (x:%y) * (x':%y')   =  reduce (x * x') (y * y')-    negate (x:%y)       =  (-x) :% y-    abs (x:%y)          =  abs x :% y-    signum (x:%_)       =  signum x :% 1-    fromInteger x       =  fromInteger x :% 1--{-# RULES "fromRational/id" fromRational = id :: Rational -> Rational #-}-instance  (Integral a)  => Fractional (Ratio a)  where-    {-# SPECIALIZE instance Fractional Rational #-}-    (x:%y) / (x':%y')   =  (x*y') % (y*x')-    recip (0:%_)        = ratioZeroDenominatorError-    recip (x:%y)-        | x < 0         = negate y :% negate x-        | otherwise     = y :% x-    fromRational (x:%y) =  fromInteger x % fromInteger y--instance  (Integral a)  => Real (Ratio a)  where-    {-# SPECIALIZE instance Real Rational #-}-    toRational (x:%y)   =  toInteger x :% toInteger y--instance  (Integral a)  => RealFrac (Ratio a)  where-    {-# SPECIALIZE instance RealFrac Rational #-}-    properFraction (x:%y) = (fromInteger (toInteger q), r:%y)-                          where (q,r) = quotRem x y--instance  (Integral a, Show a)  => Show (Ratio a)  where-    {-# SPECIALIZE instance Show Rational #-}-    showsPrec p (x:%y)  =  showParen (p > ratioPrec) $-                           showsPrec ratioPrec1 x .-                           showString " % " .-                           -- H98 report has spaces round the %-                           -- but we removed them [May 04]-                           -- and added them again for consistency with-                           -- Haskell 98 [Sep 08, #1920]-                           showsPrec ratioPrec1 y--instance  (Integral a)  => Enum (Ratio a)  where-    {-# SPECIALIZE instance Enum Rational #-}-    succ x              =  x + 1-    pred x              =  x - 1--    toEnum n            =  fromIntegral n :% 1-    fromEnum            =  fromInteger . truncate--    enumFrom            =  numericEnumFrom-    enumFromThen        =  numericEnumFromThen-    enumFromTo          =  numericEnumFromTo-    enumFromThenTo      =  numericEnumFromThenTo------------------------------------------------------------------- Coercions------------------------------------------------------------------- | general coercion from integral types-{-# NOINLINE [1] fromIntegral #-}-fromIntegral :: (Integral a, Num b) => a -> b-fromIntegral = fromInteger . toInteger--{-# RULES-"fromIntegral/Int->Int" fromIntegral = id :: Int -> Int-    #-}--{-# RULES-"fromIntegral/Int->Word"  fromIntegral = \(I# x#) -> W# (int2Word# x#)-"fromIntegral/Word->Int"  fromIntegral = \(W# x#) -> I# (word2Int# x#)-"fromIntegral/Word->Word" fromIntegral = id :: Word -> Word-    #-}---- | general coercion to fractional types-realToFrac :: (Real a, Fractional b) => a -> b-{-# NOINLINE [1] realToFrac #-}-realToFrac = fromRational . toRational------------------------------------------------------------------- Overloaded numeric functions------------------------------------------------------------------- | Converts a possibly-negative 'Real' value to a string.-showSigned :: (Real a)-  => (a -> ShowS)       -- ^ a function that can show unsigned values-  -> Int                -- ^ the precedence of the enclosing context-  -> a                  -- ^ the value to show-  -> ShowS-showSigned showPos p x-   | x < 0     = showParen (p > 6) (showChar '-' . showPos (-x))-   | otherwise = showPos x--even, odd       :: (Integral a) => a -> Bool-even n          =  n `rem` 2 == 0-odd             =  not . even-{-# SPECIALISE even :: Int -> Bool #-}-{-# SPECIALISE odd  :: Int -> Bool #-}-{-# SPECIALISE even :: Integer -> Bool #-}-{-# SPECIALISE odd  :: Integer -> Bool #-}------------------------------------------------------------ | raise a number to a non-negative integral power-{-# SPECIALISE [1] (^) ::-        Integer -> Integer -> Integer,-        Integer -> Int -> Integer,-        Int -> Int -> Int #-}-{-# INLINABLE [1] (^) #-}    -- See Note [Inlining (^)]-(^) :: (Num a, Integral b) => a -> b -> a-x0 ^ y0 | y0 < 0    = error "Negative exponent"-        | y0 == 0   = 1-        | otherwise = f x0 y0-    where -- f : x0 ^ y0 = x ^ y-          f x y | even y    = f (x * x) (y `quot` 2)-                | y == 1    = x-                | otherwise = g (x * x) ((y - 1) `quot` 2) x-          -- g : x0 ^ y0 = (x ^ y) * z-          g x y z | even y = g (x * x) (y `quot` 2) z-                  | y == 1 = x * z-                  | otherwise = g (x * x) ((y - 1) `quot` 2) (x * z)---- | raise a number to an integral power-(^^)            :: (Fractional a, Integral b) => a -> b -> a-{-# INLINABLE [1] (^^) #-}         -- See Note [Inlining (^)-x ^^ n          =  if n >= 0 then x^n else recip (x^(negate n))--{- Note [Inlining (^)-   ~~~~~~~~~~~~~~~~~~~~~-   The INLINABLE pragma allows (^) to be specialised at its call sites.-   If it is called repeatedly at the same type, that can make a huge-   difference, because of those constants which can be repeatedly-   calculated.--   Currently the fromInteger calls are not floated because we get-             \d1 d2 x y -> blah-   after the gentle round of simplification. -}--{- Rules for powers with known small exponent-    see #5237-    For small exponents, (^) is inefficient compared to manually-    expanding the multiplication tree.-    Here, rules for the most common exponent types are given.-    The range of exponents for which rules are given is quite-    arbitrary and kept small to not unduly increase the number of rules.-    0 and 1 are excluded based on the assumption that nobody would-    write x^0 or x^1 in code and the cases where an exponent could-    be statically resolved to 0 or 1 are rare.--    It might be desirable to have corresponding rules also for-    exponents of other types, in particular Word, but we can't-    have those rules here (importing GHC.Word or GHC.Int would-    create a cyclic module dependency), and it's doubtful they-    would fire, since the exponents of other types tend to get-    floated out before the rule has a chance to fire.--    Also desirable would be rules for (^^), but I haven't managed-    to get those to fire.--    Note: Trying to save multiplications by sharing the square for-    exponents 4 and 5 does not save time, indeed, for Double, it is-    up to twice slower, so the rules contain flat sequences of-    multiplications.--}--{-# RULES-"^2/Int"        forall x. x ^ (2 :: Int) = let u = x in u*u-"^3/Int"        forall x. x ^ (3 :: Int) = let u = x in u*u*u-"^4/Int"        forall x. x ^ (4 :: Int) = let u = x in u*u*u*u-"^5/Int"        forall x. x ^ (5 :: Int) = let u = x in u*u*u*u*u-"^2/Integer"    forall x. x ^ (2 :: Integer) = let u = x in u*u-"^3/Integer"    forall x. x ^ (3 :: Integer) = let u = x in u*u*u-"^4/Integer"    forall x. x ^ (4 :: Integer) = let u = x in u*u*u*u-"^5/Integer"    forall x. x ^ (5 :: Integer) = let u = x in u*u*u*u*u-  #-}------------------------------------------------------------ Special power functions for Rational------ see #4337------ Rationale:--- For a legitimate Rational (n :% d), the numerator and denominator are--- coprime, i.e. they have no common prime factor.--- Therefore all powers (n ^ a) and (d ^ b) are also coprime, so it is--- not necessary to compute the greatest common divisor, which would be--- done in the default implementation at each multiplication step.--- Since exponentiation quickly leads to very large numbers and--- calculation of gcds is generally very slow for large numbers,--- avoiding the gcd leads to an order of magnitude speedup relatively--- soon (and an asymptotic improvement overall).------ Note:--- We cannot use these functions for general Ratio a because that would--- change results in a multitude of cases.--- The cause is that if a and b are coprime, their remainders by any--- positive modulus generally aren't, so in the default implementation--- reduction occurs.------ Example:--- (17 % 3) ^ 3 :: Ratio Word8--- Default:--- (17 % 3) ^ 3 = ((17 % 3) ^ 2) * (17 % 3)---              = ((289 `mod` 256) % 9) * (17 % 3)---              = (33 % 9) * (17 % 3)---              = (11 % 3) * (17 % 3)---              = (187 % 9)--- But:--- ((17^3) `mod` 256) % (3^3)   = (4913 `mod` 256) % 27---                              = 49 % 27------ TODO:--- Find out whether special-casing for numerator, denominator or--- exponent = 1 (or -1, where that may apply) gains something.---- Special version of (^) for Rational base-{-# RULES "(^)/Rational"    (^) = (^%^) #-}-(^%^)           :: Integral a => Rational -> a -> Rational-(n :% d) ^%^ e-    | e < 0     = error "Negative exponent"-    | e == 0    = 1 :% 1-    | otherwise = (n ^ e) :% (d ^ e)---- Special version of (^^) for Rational base-{-# RULES "(^^)/Rational"   (^^) = (^^%^^) #-}-(^^%^^)         :: Integral a => Rational -> a -> Rational-(n :% d) ^^%^^ e-    | e > 0     = (n ^ e) :% (d ^ e)-    | e == 0    = 1 :% 1-    | n > 0     = (d ^ (negate e)) :% (n ^ (negate e))-    | n == 0    = ratioZeroDenominatorError-    | otherwise = let nn = d ^ (negate e)-                      dd = (negate n) ^ (negate e)-                  in if even e then (nn :% dd) else (negate nn :% dd)------------------------------------------------------------ | @'gcd' x y@ is the non-negative factor of both @x@ and @y@ of which--- every common factor of @x@ and @y@ is also a factor; for example--- @'gcd' 4 2 = 2@, @'gcd' (-4) 6 = 2@, @'gcd' 0 4@ = @4@. @'gcd' 0 0@ = @0@.--- (That is, the common divisor that is \"greatest\" in the divisibility--- preordering.)------ Note: Since for signed fixed-width integer types, @'abs' 'minBound' < 0@,--- the result may be negative if one of the arguments is @'minBound'@ (and--- necessarily is if the other is @0@ or @'minBound'@) for such types.-gcd             :: (Integral a) => a -> a -> a-{-# NOINLINE [1] gcd #-}-gcd x y         =  gcd' (abs x) (abs y)-                   where gcd' a 0  =  a-                         gcd' a b  =  gcd' b (a `rem` b)---- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.-lcm             :: (Integral a) => a -> a -> a-{-# SPECIALISE lcm :: Int -> Int -> Int #-}-{-# NOINLINE [1] lcm #-}-lcm _ 0         =  0-lcm 0 _         =  0-lcm x y         =  abs ((x `quot` (gcd x y)) * y)--#ifdef OPTIMISE_INTEGER_GCD_LCM-{-# RULES-"gcd/Int->Int->Int"             gcd = gcdInt'-"gcd/Integer->Integer->Integer" gcd = gcdInteger-"lcm/Integer->Integer->Integer" lcm = lcmInteger- #-}--gcdInt' :: Int -> Int -> Int-gcdInt' (I# x) (I# y) = I# (gcdInt x y)--#if MIN_VERSION_integer_gmp(1,0,0)-{-# RULES-"gcd/Word->Word->Word"          gcd = gcdWord'- #-}--gcdWord' :: Word -> Word -> Word-gcdWord' (W# x) (W# y) = W# (gcdWord x y)-#endif-#endif--integralEnumFrom :: (Integral a, Bounded a) => a -> [a]-integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]--integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]-integralEnumFromThen n1 n2-  | i_n2 >= i_n1  = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]-  | otherwise     = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]-  where-    i_n1 = toInteger n1-    i_n2 = toInteger n2--integralEnumFromTo :: Integral a => a -> a -> [a]-integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]--integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]-integralEnumFromThenTo n1 n2 m-  = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]
− GHC/ST.hs
@@ -1,165 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples, RankNTypes #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.ST--- Copyright   :  (c) The University of Glasgow, 1992-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The 'ST' Monad.-----------------------------------------------------------------------------------module GHC.ST (-        ST(..), STret(..), STRep,-        fixST, runST, runSTRep,--        -- * Unsafe functions-        liftST, unsafeInterleaveST-    ) where--import GHC.Base-import GHC.Show--default ()---- The state-transformer monad proper.  By default the monad is strict;--- too many people got bitten by space leaks when it was lazy.---- | The strict 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 'Control.Monad.ST.stToIO').------ It serves to keep the internal states of different invocations--- of 'runST' separate from each other and from invocations of--- 'Control.Monad.ST.stToIO'.------ The '>>=' and '>>' operations are strict in the state (though not in--- values stored in the state).  For example,------ @'runST' (writeSTRef _|_ v >>= f) = _|_@-newtype ST s a = ST (STRep s a)-type STRep s a = State# s -> (# State# s, a #)--instance Functor (ST s) where-    fmap f (ST m) = ST $ \ s ->-      case (m s) of { (# new_s, r #) ->-      (# new_s, f r #) }--instance Applicative (ST s) where-    pure = return-    (<*>) = ap--instance Monad (ST s) where-    {-# INLINE return #-}-    {-# INLINE (>>)   #-}-    {-# INLINE (>>=)  #-}-    return x = ST (\ s -> (# s, x #))-    m >> k   = m >>= \ _ -> k--    (ST m) >>= k-      = ST (\ s ->-        case (m s) of { (# new_s, r #) ->-        case (k r) of { ST k2 ->-        (k2 new_s) }})--data STret s a = STret (State# s) a---- liftST is useful when we want a lifted result from an ST computation.  See--- fixST below.-liftST :: ST s a -> State# s -> STret s a-liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r--{-# NOINLINE unsafeInterleaveST #-}-unsafeInterleaveST :: ST s a -> ST s a-unsafeInterleaveST (ST m) = ST ( \ s ->-    let-        r = case m s of (# _, res #) -> res-    in-    (# s, 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 -> ST s a) -> ST s a-fixST k = ST $ \ s ->-    let ans       = liftST (k r) s-        STret _ r = ans-    in-    case ans of STret s' x -> (# s', x #)--instance  Show (ST s a)  where-    showsPrec _ _  = showString "<<ST action>>"-    showList       = showList__ (showsPrec 0)--{--Definition of runST-~~~~~~~~~~~~~~~~~~~--SLPJ 95/04: Why @runST@ must not have an unfolding; consider:-\begin{verbatim}-f x =-  runST ( \ s -> let-                    (a, s')  = newArray# 100 [] s-                    (_, s'') = fill_in_array_or_something a x s'-                  in-                  freezeArray# a s'' )-\end{verbatim}-If we inline @runST@, we'll get:-\begin{verbatim}-f x = let-        (a, s')  = newArray# 100 [] realWorld#{-NB-}-        (_, s'') = fill_in_array_or_something a x s'-      in-      freezeArray# a s''-\end{verbatim}-And now the @newArray#@ binding can be floated to become a CAF, which-is totally and utterly wrong:-\begin{verbatim}-f = let-    (a, s')  = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!-    in-    \ x ->-        let (_, s'') = fill_in_array_or_something a x s' in-        freezeArray# a s''-\end{verbatim}-All calls to @f@ will share a {\em single} array!  End SLPJ 95/04.--}--{-# INLINE runST #-}--- The INLINE prevents runSTRep getting inlined in *this* module--- so that it is still visible when runST is inlined in an importing--- module.  Regrettably delicate.  runST is behaving like a wrapper.---- | 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 :: (forall s. ST s a) -> a-runST st = runSTRep (case st of { ST st_rep -> st_rep })---- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness--- That's what the "INLINE [0]" says.---              SLPJ Apr 99--- {-# INLINE [0] runSTRep #-}---- SDM: further to the above, inline phase 0 is run *before*--- full-laziness at the moment, which means that the above comment is--- invalid.  Inlining runSTRep doesn't make a huge amount of--- difference, anyway.  Hence:--{-# NOINLINE runSTRep #-}-runSTRep :: (forall s. STRep s a) -> a-runSTRep st_rep = case st_rep realWorld# of-                        (# _, r #) -> r
− GHC/STRef.hs
@@ -1,49 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.STRef--- Copyright   :  (c) The University of Glasgow, 1994-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ References in the 'ST' monad.-----------------------------------------------------------------------------------module GHC.STRef (-        STRef(..),-        newSTRef, readSTRef, writeSTRef-    ) where--import GHC.ST-import GHC.Base--data STRef s a = STRef (MutVar# s a)--- ^ a value of type @STRef s a@ is a mutable variable in state thread @s@,--- containing a value of type @a@---- |Build a new 'STRef' in the current state thread-newSTRef :: a -> ST s (STRef s a)-newSTRef init = ST $ \s1# ->-    case newMutVar# init s1#            of { (# s2#, var# #) ->-    (# s2#, STRef var# #) }---- |Read the value of an 'STRef'-readSTRef :: STRef s a -> ST s a-readSTRef (STRef var#) = ST $ \s1# -> readMutVar# var# s1#---- |Write a new value into an 'STRef'-writeSTRef :: STRef s a -> a -> ST s ()-writeSTRef (STRef var#) val = ST $ \s1# ->-    case writeMutVar# var# val s1#      of { s2# ->-    (# s2#, () #) }---- Just pointer equality on mutable references:-instance Eq (STRef s a) where-    STRef v1# == STRef v2# = isTrue# (sameMutVar# v1# v2#)
− GHC/Show.hs
@@ -1,507 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, StandaloneDeriving,-             MagicHash, UnboxedTuples #-}-{-# OPTIONS_HADDOCK hide #-}--#include "MachDeps.h"-#if SIZEOF_HSWORD == 4-#define DIGITS       9-#define BASE         1000000000-#elif SIZEOF_HSWORD == 8-#define DIGITS       18-#define BASE         1000000000000000000-#else-#error Please define DIGITS and BASE--- DIGITS should be the largest integer such that---     10^DIGITS < 2^(SIZEOF_HSWORD * 8 - 1)--- BASE should be 10^DIGITS. Note that ^ is not available yet.-#endif---------------------------------------------------------------------------------- |--- Module      :  GHC.Show--- Copyright   :  (c) The University of Glasgow, 1992-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ The 'Show' class, and related operations.-----------------------------------------------------------------------------------module GHC.Show-        (-        Show(..), ShowS,--        -- Instances for Show: (), [], Bool, Ordering, Int, Char--        -- Show support code-        shows, showChar, showString, showMultiLineString,-        showParen, showList__, showSpace,-        showLitChar, showLitString, protectEsc,-        intToDigit, showSignedInt,-        appPrec, appPrec1,--        -- Character operations-        asciiTab,-  )-        where--import GHC.Base-import GHC.Num-import GHC.List ((!!), foldr1, break)---- | The @shows@ functions return a function that prepends the--- output 'String' to an existing 'String'.  This allows constant-time--- concatenation of results using function composition.-type ShowS = String -> String---- | Conversion of values to readable 'String's.------ Derived instances of 'Show' have the following properties, which--- are compatible with derived instances of 'Text.Read.Read':------ * The result of 'show' is a syntactically correct Haskell---   expression containing only constants, given the fixity---   declarations in force at the point where the type is declared.---   It contains only the constructor names defined in the data type,---   parentheses, and spaces.  When labelled constructor fields are---   used, braces, commas, field names, and equal signs are also used.------ * If the constructor is defined to be an infix operator, then---   'showsPrec' will produce infix applications of the constructor.------ * the representation will be enclosed in parentheses if the---   precedence of the top-level constructor in @x@ is less than @d@---   (associativity is ignored).  Thus, if @d@ is @0@ then the result---   is never surrounded in parentheses; if @d@ is @11@ it is always---   surrounded in parentheses, unless it is an atomic expression.------ * If the constructor is defined using record syntax, then 'show'---   will produce the record-syntax form, with the fields given in the---   same order as the original declaration.------ For example, given the declarations------ > infixr 5 :^:--- > data Tree a =  Leaf a  |  Tree a :^: Tree a------ the derived instance of 'Show' is equivalent to------ > instance (Show a) => Show (Tree a) where--- >--- >        showsPrec d (Leaf m) = showParen (d > app_prec) $--- >             showString "Leaf " . showsPrec (app_prec+1) m--- >          where app_prec = 10--- >--- >        showsPrec d (u :^: v) = showParen (d > up_prec) $--- >             showsPrec (up_prec+1) u .--- >             showString " :^: "      .--- >             showsPrec (up_prec+1) v--- >          where up_prec = 5------ Note that right-associativity of @:^:@ is ignored.  For example,------ * @'show' (Leaf 1 :^: Leaf 2 :^: Leaf 3)@ produces the string---   @\"Leaf 1 :^: (Leaf 2 :^: Leaf 3)\"@.--class  Show a  where-    {-# MINIMAL showsPrec | show #-}--    -- | Convert a value to a readable 'String'.-    ---    -- 'showsPrec' should satisfy the law-    ---    -- > showsPrec d x r ++ s  ==  showsPrec d x (r ++ s)-    ---    -- Derived instances of 'Text.Read.Read' and 'Show' satisfy the following:-    ---    -- * @(x,\"\")@ is an element of-    --   @('Text.Read.readsPrec' d ('showsPrec' d x \"\"))@.-    ---    -- That is, 'Text.Read.readsPrec' parses the string produced by-    -- 'showsPrec', and delivers the value that 'showsPrec' started with.--    showsPrec :: Int    -- ^ the operator precedence of the enclosing-                        -- context (a number from @0@ to @11@).-                        -- Function application has precedence @10@.-              -> a      -- ^ the value to be converted to a 'String'-              -> ShowS--    -- | A specialised variant of 'showsPrec', using precedence context-    -- zero, and returning an ordinary 'String'.-    show      :: a   -> String--    -- | The method 'showList' is provided to allow the programmer to-    -- give a specialised way of showing lists of values.-    -- For example, this is used by the predefined 'Show' instance of-    -- the 'Char' type, where values of type 'String' should be shown-    -- in double quotes, rather than between square brackets.-    showList  :: [a] -> ShowS--    showsPrec _ x s = show x ++ s-    show x          = shows x ""-    showList ls   s = showList__ shows ls s--showList__ :: (a -> ShowS) ->  [a] -> ShowS-showList__ _     []     s = "[]" ++ s-showList__ showx (x:xs) s = '[' : showx x (showl xs)-  where-    showl []     = ']' : s-    showl (y:ys) = ',' : showx y (showl ys)--appPrec, appPrec1 :: Int-        -- Use unboxed stuff because we don't have overloaded numerics yet-appPrec = I# 10#        -- Precedence of application:-                        --   one more than the maximum operator precedence of 9-appPrec1 = I# 11#       -- appPrec + 1------------------------------------------------------------------- Simple Instances-----------------------------------------------------------------deriving instance Show ()--instance Show a => Show [a]  where-  {-# SPECIALISE instance Show [String] #-}-  {-# SPECIALISE instance Show [Char] #-}-  {-# SPECIALISE instance Show [Int] #-}-  showsPrec _         = showList--deriving instance Show Bool-deriving instance Show Ordering--instance  Show Char  where-    showsPrec _ '\'' = showString "'\\''"-    showsPrec _ c    = showChar '\'' . showLitChar c . showChar '\''--    showList cs = showChar '"' . showLitString cs . showChar '"'--instance Show Int where-    showsPrec = showSignedInt--instance Show Word where-    showsPrec _ (W# w) = showWord w--showWord :: Word# -> ShowS-showWord w# cs- | isTrue# (w# `ltWord#` 10##) = C# (chr# (ord# '0'# +# word2Int# w#)) : cs- | otherwise = case chr# (ord# '0'# +# word2Int# (w# `remWord#` 10##)) of-               c# ->-                   showWord (w# `quotWord#` 10##) (C# c# : cs)--deriving instance Show a => Show (Maybe a)------------------------------------------------------------------- Show instances for the first few tuple------------------------------------------------------------------- The explicit 's' parameters are important--- Otherwise GHC thinks that "shows x" might take a lot of work to compute--- and generates defns like---      showsPrec _ (x,y) = let sx = shows x; sy = shows y in---                          \s -> showChar '(' (sx (showChar ',' (sy (showChar ')' s))))--instance  (Show a, Show b) => Show (a,b)  where-  showsPrec _ (a,b) s = show_tuple [shows a, shows b] s--instance (Show a, Show b, Show c) => Show (a, b, c) where-  showsPrec _ (a,b,c) s = show_tuple [shows a, shows b, shows c] s--instance (Show a, Show b, Show c, Show d) => Show (a, b, c, d) where-  showsPrec _ (a,b,c,d) s = show_tuple [shows a, shows b, shows c, shows d] s--instance (Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e) where-  showsPrec _ (a,b,c,d,e) s = show_tuple [shows a, shows b, shows c, shows d, shows e] s--instance (Show a, Show b, Show c, Show d, Show e, Show f) => Show (a,b,c,d,e,f) where-  showsPrec _ (a,b,c,d,e,f) s = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f] s--instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g)-        => Show (a,b,c,d,e,f,g) where-  showsPrec _ (a,b,c,d,e,f,g) s-        = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g] s--instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h)-         => Show (a,b,c,d,e,f,g,h) where-  showsPrec _ (a,b,c,d,e,f,g,h) s-        = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h] s--instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i)-         => Show (a,b,c,d,e,f,g,h,i) where-  showsPrec _ (a,b,c,d,e,f,g,h,i) s-        = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,-                      shows i] s--instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j)-         => Show (a,b,c,d,e,f,g,h,i,j) where-  showsPrec _ (a,b,c,d,e,f,g,h,i,j) s-        = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,-                      shows i, shows j] s--instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k)-         => Show (a,b,c,d,e,f,g,h,i,j,k) where-  showsPrec _ (a,b,c,d,e,f,g,h,i,j,k) s-        = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,-                      shows i, shows j, shows k] s--instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k,-          Show l)-         => Show (a,b,c,d,e,f,g,h,i,j,k,l) where-  showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l) s-        = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,-                      shows i, shows j, shows k, shows l] s--instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k,-          Show l, Show m)-         => Show (a,b,c,d,e,f,g,h,i,j,k,l,m) where-  showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m) s-        = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,-                      shows i, shows j, shows k, shows l, shows m] s--instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k,-          Show l, Show m, Show n)-         => Show (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where-  showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m,n) s-        = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,-                      shows i, shows j, shows k, shows l, shows m, shows n] s--instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k,-          Show l, Show m, Show n, Show o)-         => Show (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where-  showsPrec _ (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) s-        = show_tuple [shows a, shows b, shows c, shows d, shows e, shows f, shows g, shows h,-                      shows i, shows j, shows k, shows l, shows m, shows n, shows o] s--show_tuple :: [ShowS] -> ShowS-show_tuple ss = showChar '('-              . foldr1 (\s r -> s . showChar ',' . r) ss-              . showChar ')'------------------------------------------------------------------- Support code for Show------------------------------------------------------------------- | equivalent to 'showsPrec' with a precedence of 0.-shows           :: (Show a) => a -> ShowS-shows           =  showsPrec 0---- | utility function converting a 'Char' to a show function that--- simply prepends the character unchanged.-showChar        :: Char -> ShowS-showChar        =  (:)---- | utility function converting a 'String' to a show function that--- simply prepends the string unchanged.-showString      :: String -> ShowS-showString      =  (++)---- | utility function that surrounds the inner show function with--- parentheses when the 'Bool' parameter is 'True'.-showParen       :: Bool -> ShowS -> ShowS-showParen b p   =  if b then showChar '(' . p . showChar ')' else p--showSpace :: ShowS-showSpace = {-showChar ' '-} \ xs -> ' ' : xs---- Code specific for characters---- | Convert a character to a string using only printable characters,--- using Haskell source-language escape conventions.  For example:------ > showLitChar '\n' s  =  "\\n" ++ s----showLitChar                :: Char -> ShowS-showLitChar c s | c > '\DEL' =  showChar '\\' (protectEsc isDec (shows (ord c)) s)-showLitChar '\DEL'         s =  showString "\\DEL" s-showLitChar '\\'           s =  showString "\\\\" s-showLitChar c s | c >= ' '   =  showChar c s-showLitChar '\a'           s =  showString "\\a" s-showLitChar '\b'           s =  showString "\\b" s-showLitChar '\f'           s =  showString "\\f" s-showLitChar '\n'           s =  showString "\\n" s-showLitChar '\r'           s =  showString "\\r" s-showLitChar '\t'           s =  showString "\\t" s-showLitChar '\v'           s =  showString "\\v" s-showLitChar '\SO'          s =  protectEsc (== 'H') (showString "\\SO") s-showLitChar c              s =  showString ('\\' : asciiTab!!ord c) s-        -- I've done manual eta-expansion here, because otherwise it's-        -- impossible to stop (asciiTab!!ord) getting floated out as an MFE--showLitString :: String -> ShowS--- | Same as 'showLitChar', but for strings--- It converts the string to a string using Haskell escape conventions--- for non-printable characters. Does not add double-quotes around the--- whole thing; the caller should do that.--- The main difference from showLitChar (apart from the fact that the--- argument is a string not a list) is that we must escape double-quotes-showLitString []         s = s-showLitString ('"' : cs) s = showString "\\\"" (showLitString cs s)-showLitString (c   : cs) s = showLitChar c (showLitString cs s)-   -- Making 's' an explicit parameter makes it clear to GHC that-   -- showLitString has arity 2, which avoids it allocating an extra lambda-   -- The sticking point is the recursive call to (showLitString cs), which-   -- it can't figure out would be ok with arity 2.--showMultiLineString :: String -> [String]--- | Like 'showLitString' (expand escape characters using Haskell--- escape conventions), but---   * break the string into multiple lines---   * wrap the entire thing in double quotes--- Example:  @showMultiLineString "hello\ngoodbye\nblah"@--- returns   @["\"hello\\n\\", "\\goodbye\n\\", "\\blah\""]@-showMultiLineString str-  = go '\"' str-  where-    go ch s = case break (== '\n') s of-                (l, _:s'@(_:_)) -> (ch : showLitString l "\\n\\") : go '\\' s'-                (l, "\n")       -> [ch : showLitString l "\\n\""]-                (l, _)          -> [ch : showLitString l "\""]--isDec :: Char -> Bool-isDec c = c >= '0' && c <= '9'--protectEsc :: (Char -> Bool) -> ShowS -> ShowS-protectEsc p f             = f . cont-                             where cont s@(c:_) | p c = "\\&" ++ s-                                   cont s             = s---asciiTab :: [String]-asciiTab = -- Using an array drags in the array module.  listArray ('\NUL', ' ')-           ["NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",-            "BS",  "HT",  "LF",  "VT",  "FF",  "CR",  "SO",  "SI",-            "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",-            "CAN", "EM",  "SUB", "ESC", "FS",  "GS",  "RS",  "US",-            "SP"]---- Code specific for Ints.---- | Convert an 'Int' in the range @0@..@15@ to the corresponding single--- digit 'Char'.  This function fails on other inputs, and generates--- lower-case hexadecimal digits.-intToDigit :: Int -> Char-intToDigit (I# i)-    | isTrue# (i >=# 0#)  && isTrue# (i <=#  9#) = unsafeChr (ord '0' + I# i)-    | isTrue# (i >=# 10#) && isTrue# (i <=# 15#) = unsafeChr (ord 'a' + I# i - 10)-    | otherwise =  error ("Char.intToDigit: not a digit " ++ show (I# i))--showSignedInt :: Int -> Int -> ShowS-showSignedInt (I# p) (I# n) r-    | isTrue# (n <# 0#) && isTrue# (p ># 6#) = '(' : itos n (')' : r)-    | otherwise                              = itos n r--itos :: Int# -> String -> String-itos n# cs-    | isTrue# (n# <# 0#) =-        let !(I# minInt#) = minInt in-        if isTrue# (n# ==# minInt#)-                -- negateInt# minInt overflows, so we can't do that:-           then '-' : (case n# `quotRemInt#` 10# of-                       (# q, r #) ->-                           itos' (negateInt# q) (itos' (negateInt# r) cs))-           else '-' : itos' (negateInt# n#) cs-    | otherwise = itos' n# cs-    where-    itos' :: Int# -> String -> String-    itos' x# cs'-        | isTrue# (x# <# 10#) = C# (chr# (ord# '0'# +# x#)) : cs'-        | otherwise = case x# `quotRemInt#` 10# of-                      (# q, r #) ->-                          case chr# (ord# '0'# +# r) of-                          c# ->-                              itos' q (C# c# : cs')------------------------------------------------------------------- The Integer instances for Show-----------------------------------------------------------------instance Show Integer where-    showsPrec p n r-        | p > 6 && n < 0 = '(' : integerToString n (')' : r)-        -- Minor point: testing p first gives better code-        -- in the not-uncommon case where the p argument-        -- is a constant-        | otherwise = integerToString n r-    showList = showList__ (showsPrec 0)---- Divide an conquer implementation of string conversion-integerToString :: Integer -> String -> String-integerToString n0 cs0-    | n0 < 0    = '-' : integerToString' (- n0) cs0-    | otherwise = integerToString' n0 cs0-    where-    integerToString' :: Integer -> String -> String-    integerToString' n cs-        | n < BASE  = jhead (fromInteger n) cs-        | otherwise = jprinth (jsplitf (BASE*BASE) n) cs--    -- Split n into digits in base p. We first split n into digits-    -- in base p*p and then split each of these digits into two.-    -- Note that the first 'digit' modulo p*p may have a leading zero-    -- in base p that we need to drop - this is what jsplith takes care of.-    -- jsplitb the handles the remaining digits.-    jsplitf :: Integer -> Integer -> [Integer]-    jsplitf p n-        | p > n     = [n]-        | otherwise = jsplith p (jsplitf (p*p) n)--    jsplith :: Integer -> [Integer] -> [Integer]-    jsplith p (n:ns) =-        case n `quotRemInteger` p of-        (# q, r #) ->-            if q > 0 then q : r : jsplitb p ns-                     else     r : jsplitb p ns-    jsplith _ [] = error "jsplith: []"--    jsplitb :: Integer -> [Integer] -> [Integer]-    jsplitb _ []     = []-    jsplitb p (n:ns) = case n `quotRemInteger` p of-                       (# q, r #) ->-                           q : r : jsplitb p ns--    -- Convert a number that has been split into digits in base BASE^2-    -- this includes a last splitting step and then conversion of digits-    -- that all fit into a machine word.-    jprinth :: [Integer] -> String -> String-    jprinth (n:ns) cs =-        case n `quotRemInteger` BASE of-        (# q', r' #) ->-            let q = fromInteger q'-                r = fromInteger r'-            in if q > 0 then jhead q $ jblock r $ jprintb ns cs-                        else jhead r $ jprintb ns cs-    jprinth [] _ = error "jprinth []"--    jprintb :: [Integer] -> String -> String-    jprintb []     cs = cs-    jprintb (n:ns) cs = case n `quotRemInteger` BASE of-                        (# q', r' #) ->-                            let q = fromInteger q'-                                r = fromInteger r'-                            in jblock q $ jblock r $ jprintb ns cs--    -- Convert an integer that fits into a machine word. Again, we have two-    -- functions, one that drops leading zeros (jhead) and one that doesn't-    -- (jblock)-    jhead :: Int -> String -> String-    jhead n cs-        | n < 10    = case unsafeChr (ord '0' + n) of-            c@(C# _) -> c : cs-        | otherwise = case unsafeChr (ord '0' + r) of-            c@(C# _) -> jhead q (c : cs)-        where-        (q, r) = n `quotRemInt` 10--    jblock = jblock' {- ' -} DIGITS--    jblock' :: Int -> Int -> String -> String-    jblock' d n cs-        | d == 1    = case unsafeChr (ord '0' + n) of-             c@(C# _) -> c : cs-        | otherwise = case unsafeChr (ord '0' + r) of-             c@(C# _) -> jblock' (d - 1) q (c : cs)-        where-        (q, r) = n `quotRemInt` 10
− GHC/SrcLoc.hs
@@ -1,33 +0,0 @@-{-# LANGUAGE RecordWildCards #-}-module GHC.SrcLoc-  ( SrcLoc-  , srcLocPackage-  , srcLocModule-  , srcLocFile-  , srcLocStartLine-  , srcLocStartCol-  , srcLocEndLine-  , srcLocEndCol--  -- * Pretty printing-  , showSrcLoc-  ) where---- | A single location in the source code.-data SrcLoc = SrcLoc-  { srcLocPackage   :: String-  , srcLocModule    :: String-  , srcLocFile      :: String-  , srcLocStartLine :: Int-  , srcLocStartCol  :: Int-  , srcLocEndLine   :: Int-  , srcLocEndCol    :: Int-  } deriving (Show, Eq)--showSrcLoc :: SrcLoc -> String-showSrcLoc SrcLoc {..}-  = concat [ srcLocFile, ":"-           , show srcLocStartLine, ":"-           , show srcLocStartCol, " in "-           , srcLocPackage, ":", srcLocModule-           ]
− GHC/Stable.hs
@@ -1,111 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude-           , DeriveDataTypeable-           , MagicHash-           , UnboxedTuples-  #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Stable--- Copyright   :  (c) The University of Glasgow, 1992-2004--- License     :  see libraries/base/LICENSE------ Maintainer  :  ffi@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Stable pointers.-----------------------------------------------------------------------------------module GHC.Stable (-        StablePtr(..),-        newStablePtr,-        deRefStablePtr,-        freeStablePtr,-        castStablePtrToPtr,-        castPtrToStablePtr-    ) where--import GHC.Ptr-import GHC.Base-import Data.Typeable.Internal---------------------------------------------------------------------------------- Stable Pointers--{- |-A /stable pointer/ is a reference to a Haskell expression that is-guaranteed not to be affected by garbage collection, i.e., it will neither be-deallocated nor will the value of the stable pointer itself change during-garbage collection (ordinary references may be relocated during garbage-collection).  Consequently, stable pointers can be passed to foreign code,-which can treat it as an opaque reference to a Haskell value.--A value of type @StablePtr a@ is a stable pointer to a Haskell-expression of type @a@.--}-data {-# CTYPE "HsStablePtr" #-} StablePtr a = StablePtr (StablePtr# a)-  deriving( Typeable )---- |--- Create a stable pointer referring to the given Haskell value.----newStablePtr   :: a -> IO (StablePtr a)-newStablePtr a = IO $ \ s ->-    case makeStablePtr# a s of (# s', sp #) -> (# s', StablePtr sp #)---- |--- Obtain the Haskell value referenced by a stable pointer, i.e., the--- same value that was passed to the corresponding call to--- 'makeStablePtr'.  If the argument to 'deRefStablePtr' has--- already been freed using 'freeStablePtr', the behaviour of--- 'deRefStablePtr' is undefined.----deRefStablePtr :: StablePtr a -> IO a-deRefStablePtr (StablePtr sp) = IO $ \s -> deRefStablePtr# sp s---- |--- Dissolve the association between the stable pointer and the Haskell--- value. Afterwards, if the stable pointer is passed to--- 'deRefStablePtr' or 'freeStablePtr', the behaviour is--- undefined.  However, the stable pointer may still be passed to--- 'castStablePtrToPtr', but the @'Foreign.Ptr.Ptr' ()@ value returned--- by 'castStablePtrToPtr', in this case, is undefined (in particular,--- it may be 'Foreign.Ptr.nullPtr').  Nevertheless, the call--- to 'castStablePtrToPtr' is guaranteed not to diverge.----foreign import ccall unsafe "hs_free_stable_ptr" freeStablePtr :: StablePtr a -> IO ()---- |--- Coerce a stable pointer to an address. No guarantees are made about--- the resulting value, except that the original stable pointer can be--- recovered by 'castPtrToStablePtr'.  In particular, the address may not--- refer to an accessible memory location and any attempt to pass it to--- the member functions of the class 'Foreign.Storable.Storable' leads to--- undefined behaviour.----castStablePtrToPtr :: StablePtr a -> Ptr ()-castStablePtrToPtr (StablePtr s) = Ptr (unsafeCoerce# s)----- |--- The inverse of 'castStablePtrToPtr', i.e., we have the identity------ > sp == castPtrToStablePtr (castStablePtrToPtr sp)------ for any stable pointer @sp@ on which 'freeStablePtr' has--- not been executed yet.  Moreover, 'castPtrToStablePtr' may--- only be applied to pointers that have been produced by--- 'castStablePtrToPtr'.----castPtrToStablePtr :: Ptr () -> StablePtr a-castPtrToStablePtr (Ptr a) = StablePtr (unsafeCoerce# a)--instance Eq (StablePtr a) where-    (StablePtr sp1) == (StablePtr sp2) =-        case eqStablePtr# sp1 sp2 of-           0# -> False-           _  -> True
− GHC/Stack.hsc
@@ -1,185 +0,0 @@-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Stack--- Copyright   :  (c) The University of Glasgow 2011--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Access to GHC's call-stack simulation------ @since 4.5.0.0--------------------------------------------------------------------------------{-# LANGUAGE UnboxedTuples, MagicHash, NoImplicitPrelude #-}-module GHC.Stack (-    -- * Call stacks-    -- ** Simulated by the RTS-    currentCallStack,-    whoCreated,-    errorWithStackTrace,--    -- ** Explicitly created via implicit-parameters-    CallStack,-    getCallStack,-    showCallStack,--    -- * Internals-    CostCentreStack,-    CostCentre,-    getCurrentCCS,-    getCCSOf,-    ccsCC,-    ccsParent,-    ccLabel,-    ccModule,-    ccSrcSpan,-    ccsToStrings,-    renderStack-  ) where--import Data.List ( unlines )--import Foreign-import Foreign.C--import GHC.IO-import GHC.Base-import GHC.Ptr-import GHC.Foreign as GHC-import GHC.IO.Encoding-import GHC.Exception-import GHC.List ( concatMap, null, reverse )-import GHC.Show-import GHC.SrcLoc--#define PROFILING-#include "Rts.h"--data CostCentreStack-data CostCentre--getCurrentCCS :: dummy -> IO (Ptr CostCentreStack)-getCurrentCCS dummy = IO $ \s ->-   case getCurrentCCS## dummy s of-     (## s', addr ##) -> (## s', Ptr addr ##)--getCCSOf :: a -> IO (Ptr CostCentreStack)-getCCSOf obj = IO $ \s ->-   case getCCSOf## obj s of-     (## s', addr ##) -> (## s', Ptr addr ##)--ccsCC :: Ptr CostCentreStack -> IO (Ptr CostCentre)-ccsCC p = (# peek CostCentreStack, cc) p--ccsParent :: Ptr CostCentreStack -> IO (Ptr CostCentreStack)-ccsParent p = (# peek CostCentreStack, prevStack) p--ccLabel :: Ptr CostCentre -> IO CString-ccLabel p = (# peek CostCentre, label) p--ccModule :: Ptr CostCentre -> IO CString-ccModule p = (# peek CostCentre, module) p--ccSrcSpan :: Ptr CostCentre -> IO CString-ccSrcSpan p = (# peek CostCentre, srcloc) p---- | returns a '[String]' representing the current call stack.  This--- can be useful for debugging.------ The implementation uses the call-stack simulation maintined by the--- profiler, so it only works if the program was compiled with @-prof@--- and contains suitable SCC annotations (e.g. by using @-fprof-auto@).--- Otherwise, the list returned is likely to be empty or--- uninformative.------ @since 4.5.0.0--currentCallStack :: IO [String]-currentCallStack = ccsToStrings =<< getCurrentCCS ()--ccsToStrings :: Ptr CostCentreStack -> IO [String]-ccsToStrings ccs0 = go ccs0 []-  where-    go ccs acc-     | ccs == nullPtr = return acc-     | otherwise = do-        cc  <- ccsCC ccs-        lbl <- GHC.peekCString utf8 =<< ccLabel cc-        mdl <- GHC.peekCString utf8 =<< ccModule cc-        loc <- GHC.peekCString utf8 =<< ccSrcSpan cc-        parent <- ccsParent ccs-        if (mdl == "MAIN" && lbl == "MAIN")-           then return acc-           else go parent ((mdl ++ '.':lbl ++ ' ':'(':loc ++ ")") : acc)---- | Get the stack trace attached to an object.------ @since 4.5.0.0-whoCreated :: a -> IO [String]-whoCreated obj = do-  ccs <- getCCSOf obj-  ccsToStrings ccs--renderStack :: [String] -> String-renderStack strs = "Stack trace:" ++ concatMap ("\n  "++) (reverse strs)---- | Like the function 'error', but appends a stack trace to the error--- message if one is available.------ @since 4.7.0.0-errorWithStackTrace :: String -> a-errorWithStackTrace x = unsafeDupablePerformIO $ do-   stack <- ccsToStrings =<< getCurrentCCS x-   if null stack-      then throwIO (ErrorCall x)-      else throwIO (ErrorCall (x ++ '\n' : renderStack stack))---------------------------------------------------------------------------- Explicit call-stacks built via ImplicitParams--------------------------------------------------------------------------- | @CallStack@s are an alternate method of obtaining the call stack at a given--- point in the program.------ When an implicit-parameter of type @CallStack@ occurs in a program, GHC will--- solve it with the current location. If another @CallStack@ implicit-parameter--- is in-scope (e.g. as a function argument), the new location will be appended--- to the one in-scope, creating an explicit call-stack. For example,------ @--- myerror :: (?loc :: CallStack) => String -> a--- myerror msg = error (msg ++ "\n" ++ showCallStack ?loc)--- @--- ghci> myerror "die"--- *** Exception: die--- ?loc, called at MyError.hs:7:51 in main:MyError---   myerror, called at <interactive>:2:1 in interactive:Ghci1------ @CallStack@s do not interact with the RTS and do not require compilation with--- @-prof@. On the other hand, as they are built up explicitly using--- implicit-parameters, they will generally not contain as much information as--- the simulated call-stacks maintained by the RTS.------ The @CallStack@ type is abstract, but it can be converted into a--- @[(String, SrcLoc)]@ via 'getCallStack'. The @String@ is the name of function--- that was called, the 'SrcLoc' is the call-site. The list is ordered with the--- most recently called function at the head.------ @since 4.9.0.0-data CallStack = CallStack { getCallStack :: [(String, SrcLoc)] }-  -- See Note [Overview of implicit CallStacks]-  deriving (Show, Eq)--showCallStack :: CallStack -> String-showCallStack (CallStack (root:rest))-  = unlines (showCallSite root : map (indent . showCallSite) rest)-  where-  indent l = "  " ++ l-  showCallSite (f, loc) = f ++ ", called at " ++ showSrcLoc loc-showCallStack _ = error "CallStack cannot be empty!"
− GHC/StaticPtr.hs
@@ -1,117 +0,0 @@-{-# LANGUAGE DeriveDataTypeable        #-}-{-# LANGUAGE MagicHash                 #-}-{-# LANGUAGE UnboxedTuples             #-}-{-# LANGUAGE ExistentialQuantification #-}--------------------------------------------------------------------------------- |--- Module      :  GHC.StaticPtr--- Copyright   :  (C) 2014 I/O Tweag--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Symbolic references to values.------ References to values are usually implemented with memory addresses, and this--- is practical when communicating values between the different pieces of a--- single process.------ When values are communicated across different processes running in possibly--- different machines, though, addresses are no longer useful since each--- process may use different addresses to store a given value.------ To solve such concern, the references provided by this module offer a key--- that can be used to locate the values on each process. Each process maintains--- a global table of references which can be looked up with a given key. This--- table is known as the Static Pointer Table. The reference can then be--- dereferenced to obtain the value.-----------------------------------------------------------------------------------module GHC.StaticPtr-  ( StaticPtr-  , deRefStaticPtr-  , StaticKey-  , staticKey-  , unsafeLookupStaticPtr-  , StaticPtrInfo(..)-  , staticPtrInfo-  , staticPtrKeys-  ) where--import Data.Typeable       (Typeable)-import Foreign.C.Types     (CInt(..))-import Foreign.Marshal     (allocaArray, peekArray, withArray)-import Foreign.Ptr         (castPtr)-import GHC.Exts            (addrToAny#)-import GHC.Ptr             (Ptr(..), nullPtr)-import GHC.Fingerprint     (Fingerprint(..))----- | A reference to a value of type 'a'.-data StaticPtr a = StaticPtr StaticKey StaticPtrInfo a-  deriving Typeable---- | Dereferences a static pointer.-deRefStaticPtr :: StaticPtr a -> a-deRefStaticPtr (StaticPtr _ _ v) = v---- | A key for `StaticPtrs` that can be serialized and used with--- 'unsafeLookupStaticPtr'.-type StaticKey = Fingerprint---- | The 'StaticKey' that can be used to look up the given 'StaticPtr'.-staticKey :: StaticPtr a -> StaticKey-staticKey (StaticPtr k _ _) = k---- | Looks up a 'StaticPtr' by its 'StaticKey'.------ If the 'StaticPtr' is not found returns @Nothing@.------ This function is unsafe because the program behavior is undefined if the type--- of the returned 'StaticPtr' does not match the expected one.----unsafeLookupStaticPtr :: StaticKey -> IO (Maybe (StaticPtr a))-unsafeLookupStaticPtr (Fingerprint w1 w2) = do-    ptr@(Ptr addr) <- withArray [w1,w2] (hs_spt_lookup . castPtr)-    if (ptr == nullPtr)-    then return Nothing-    else case addrToAny# addr of-           (# spe #) -> return (Just spe)--foreign import ccall unsafe hs_spt_lookup :: Ptr () -> IO (Ptr a)---- | Miscelaneous information available for debugging purposes.-data StaticPtrInfo = StaticPtrInfo-    { -- | Package key of the package where the static pointer is defined-      spInfoPackageKey  :: String-      -- | Name of the module where the static pointer is defined-    , spInfoModuleName :: String-      -- | An internal name that is distinct for every static pointer defined in-      -- a given module.-    , spInfoName       :: String-      -- | Source location of the definition of the static pointer as a-      -- @(Line, Column)@ pair.-    , spInfoSrcLoc     :: (Int, Int)-    }-  deriving (Show, Typeable)---- | 'StaticPtrInfo' of the given 'StaticPtr'.-staticPtrInfo :: StaticPtr a -> StaticPtrInfo-staticPtrInfo (StaticPtr _ n _) = n---- | A list of all known keys.-staticPtrKeys :: IO [StaticKey]-staticPtrKeys = do-    keyCount <- hs_spt_key_count-    allocaArray (fromIntegral keyCount) $ \p -> do-      count <- hs_spt_keys p keyCount-      peekArray (fromIntegral count) p >>=-        mapM (\pa -> peekArray 2 pa >>= \[w1, w2] -> return $ Fingerprint w1 w2)-{-# NOINLINE staticPtrKeys #-}--foreign import ccall unsafe hs_spt_key_count :: IO CInt--foreign import ccall unsafe hs_spt_keys :: Ptr a -> CInt -> IO CInt
− GHC/Stats.hsc
@@ -1,154 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE RecordWildCards #-}-{-# OPTIONS_GHC -funbox-strict-fields #-}---------------------------------------------------------------------------------- | This module provides access to internal garbage collection and--- memory usage statistics.  These statistics are not available unless--- a program is run with the @-T@ RTS flag.------ This module is GHC-only and should not be considered portable.------ @since 4.5.0.0-------------------------------------------------------------------------------module GHC.Stats-    ( GCStats(..)-    , getGCStats-    , getGCStatsEnabled-) where--import Control.Monad-import Data.Int-import GHC.Base-import GHC.Read ( Read )-import GHC.Show ( Show )-import GHC.IO.Exception-import Foreign.Marshal.Alloc-import Foreign.Storable-import Foreign.Ptr--#include "Rts.h"--foreign import ccall "getGCStats"        getGCStats_       :: Ptr () -> IO ()---- | Returns whether GC stats have been enabled (with @+RTS -T@, for example).------ @since 4.6.0.0-foreign import ccall "getGCStatsEnabled" getGCStatsEnabled :: IO Bool---- I'm probably violating a bucket of constraints here... oops.---- | Global garbage collection and memory statistics.------ @since 4.5.0.0-data GCStats = GCStats-    { bytesAllocated :: !Int64 -- ^ Total number of bytes allocated-    , numGcs :: !Int64 -- ^ Number of garbage collections performed-    , maxBytesUsed :: !Int64 -- ^ Maximum number of live bytes seen so far-    , numByteUsageSamples :: !Int64 -- ^ Number of byte usage samples taken-    -- | Sum of all byte usage samples, can be used with-    -- 'numByteUsageSamples' to calculate averages with-    -- arbitrary weighting (if you are sampling this record multiple-    -- times).-    , cumulativeBytesUsed :: !Int64-    , bytesCopied :: !Int64 -- ^ Number of bytes copied during GC-    , currentBytesUsed :: !Int64 -- ^ Current number of live bytes-    , currentBytesSlop :: !Int64 -- ^ Current number of bytes lost to slop-    , maxBytesSlop :: !Int64 -- ^ Maximum number of bytes lost to slop at any one time so far-    , peakMegabytesAllocated :: !Int64 -- ^ Maximum number of megabytes allocated-    -- | CPU time spent running mutator threads.  This does not include-    -- any profiling overhead or initialization.-    , mutatorCpuSeconds :: !Double-    -- | Wall clock time spent running mutator threads.  This does not-    -- include initialization.-    , mutatorWallSeconds :: !Double-    , gcCpuSeconds :: !Double -- ^ CPU time spent running GC-    , gcWallSeconds :: !Double -- ^ Wall clock time spent running GC-    , cpuSeconds :: !Double -- ^ Total CPU time elapsed since program start-    , wallSeconds :: !Double -- ^ Total wall clock time elapsed since start-    -- | Number of bytes copied during GC, minus space held by mutable-    -- lists held by the capabilities.  Can be used with-    -- 'parMaxBytesCopied' to determine how well parallel GC utilized-    -- all cores.-    , parTotBytesCopied :: !Int64-    -- | Sum of number of bytes copied each GC by the most active GC-    -- thread each GC.  The ratio of 'parTotBytesCopied' divided by-    -- 'parMaxBytesCopied' approaches 1 for a maximally sequential-    -- run and approaches the number of threads (set by the RTS flag-    -- @-N@) for a maximally parallel run.-    , parMaxBytesCopied :: !Int64-    } deriving (Show, Read)--    {--    , initCpuSeconds :: !Double-    , initWallSeconds :: !Double-    -}---- | Retrieves garbage collection and memory statistics as of the last--- garbage collection.  If you would like your statistics as recent as--- possible, first run a 'System.Mem.performGC'.------ @since 4.5.0.0-getGCStats :: IO GCStats-getGCStats = do-  statsEnabled <- getGCStatsEnabled-  unless statsEnabled .  ioError $ IOError-    Nothing-    UnsupportedOperation-    ""-    "getGCStats: GC stats not enabled. Use `+RTS -T -RTS' to enable them."-    Nothing-    Nothing-  allocaBytes (#size GCStats) $ \p -> do-    getGCStats_ p-    bytesAllocated <- (# peek GCStats, bytes_allocated) p-    numGcs <- (# peek GCStats, num_gcs ) p-    numByteUsageSamples <- (# peek GCStats, num_byte_usage_samples ) p-    maxBytesUsed <- (# peek GCStats, max_bytes_used ) p-    cumulativeBytesUsed <- (# peek GCStats, cumulative_bytes_used ) p-    bytesCopied <- (# peek GCStats, bytes_copied ) p-    currentBytesUsed <- (# peek GCStats, current_bytes_used ) p-    currentBytesSlop <- (# peek GCStats, current_bytes_slop) p-    maxBytesSlop <- (# peek GCStats, max_bytes_slop) p-    peakMegabytesAllocated <- (# peek GCStats, peak_megabytes_allocated ) p-    {--    initCpuSeconds <- (# peek GCStats, init_cpu_seconds) p-    initWallSeconds <- (# peek GCStats, init_wall_seconds) p-    -}-    mutatorCpuSeconds <- (# peek GCStats, mutator_cpu_seconds) p-    mutatorWallSeconds <- (# peek GCStats, mutator_wall_seconds) p-    gcCpuSeconds <- (# peek GCStats, gc_cpu_seconds) p-    gcWallSeconds <- (# peek GCStats, gc_wall_seconds) p-    cpuSeconds <- (# peek GCStats, cpu_seconds) p-    wallSeconds <- (# peek GCStats, wall_seconds) p-    parTotBytesCopied <- (# peek GCStats, par_tot_bytes_copied) p-    parMaxBytesCopied <- (# peek GCStats, par_max_bytes_copied) p-    return GCStats { .. }--{----- Nontrivial to implement: TaskStats needs arbitrarily large--- amounts of memory, spark stats wants to use SparkCounters--- but that needs a new rts/ header.--data TaskStats = TaskStats-    { taskMutCpuSeconds :: Int64-    , taskMutWallSeconds :: Int64-    , taskGcCpuSeconds :: Int64-    , taskGcWallSeconds :: Int64-    } deriving (Show, Read)--data SparkStats = SparkStats-    { sparksCreated :: Int64-    , sparksDud :: Int64-    , sparksOverflowed :: Int64-    , sparksConverted :: Int64-    , sparksGcd :: Int64-    , sparksFizzled :: Int64-    } deriving (Show, Read)---- We also could get per-generation stats, which requires a--- non-constant but at runtime known about of memory.---}
− GHC/Storable.hs
@@ -1,158 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Storable--- Copyright   :  (c) The FFI task force, 2000-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  ffi@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Helper functions for "Foreign.Storable"-----------------------------------------------------------------------------------module GHC.Storable-        ( readWideCharOffPtr-        , readIntOffPtr-        , readWordOffPtr-        , readPtrOffPtr-        , readFunPtrOffPtr-        , readFloatOffPtr-        , readDoubleOffPtr-        , readStablePtrOffPtr-        , readInt8OffPtr-        , readInt16OffPtr-        , readInt32OffPtr-        , readInt64OffPtr-        , readWord8OffPtr-        , readWord16OffPtr-        , readWord32OffPtr-        , readWord64OffPtr-        , writeWideCharOffPtr-        , writeIntOffPtr-        , writeWordOffPtr-        , writePtrOffPtr-        , writeFunPtrOffPtr-        , writeFloatOffPtr-        , writeDoubleOffPtr-        , writeStablePtrOffPtr-        , writeInt8OffPtr-        , writeInt16OffPtr-        , writeInt32OffPtr-        , writeInt64OffPtr-        , writeWord8OffPtr-        , writeWord16OffPtr-        , writeWord32OffPtr-        , writeWord64OffPtr-        ) where--import GHC.Stable ( StablePtr(..) )-import GHC.Int-import GHC.Word-import GHC.Ptr-import GHC.Base--readWideCharOffPtr  :: Ptr Char          -> Int -> IO Char-readIntOffPtr       :: Ptr Int           -> Int -> IO Int-readWordOffPtr      :: Ptr Word          -> Int -> IO Word-readPtrOffPtr       :: Ptr (Ptr a)       -> Int -> IO (Ptr a)-readFunPtrOffPtr    :: Ptr (FunPtr a)    -> Int -> IO (FunPtr a)-readFloatOffPtr     :: Ptr Float         -> Int -> IO Float-readDoubleOffPtr    :: Ptr Double        -> Int -> IO Double-readStablePtrOffPtr :: Ptr (StablePtr a) -> Int -> IO (StablePtr a)-readInt8OffPtr      :: Ptr Int8          -> Int -> IO Int8-readInt16OffPtr     :: Ptr Int16         -> Int -> IO Int16-readInt32OffPtr     :: Ptr Int32         -> Int -> IO Int32-readInt64OffPtr     :: Ptr Int64         -> Int -> IO Int64-readWord8OffPtr     :: Ptr Word8         -> Int -> IO Word8-readWord16OffPtr    :: Ptr Word16        -> Int -> IO Word16-readWord32OffPtr    :: Ptr Word32        -> Int -> IO Word32-readWord64OffPtr    :: Ptr Word64        -> Int -> IO Word64--readWideCharOffPtr (Ptr a) (I# i)-  = IO $ \s -> case readWideCharOffAddr# a i s  of (# s2, x #) -> (# s2, C# x #)-readIntOffPtr (Ptr a) (I# i)-  = IO $ \s -> case readIntOffAddr# a i s       of (# s2, x #) -> (# s2, I# x #)-readWordOffPtr (Ptr a) (I# i)-  = IO $ \s -> case readWordOffAddr# a i s      of (# s2, x #) -> (# s2, W# x #)-readPtrOffPtr (Ptr a) (I# i)-  = IO $ \s -> case readAddrOffAddr# a i s      of (# s2, x #) -> (# s2, Ptr x #)-readFunPtrOffPtr (Ptr a) (I# i)-  = IO $ \s -> case readAddrOffAddr# a i s      of (# s2, x #) -> (# s2, FunPtr x #)-readFloatOffPtr (Ptr a) (I# i)-  = IO $ \s -> case readFloatOffAddr# a i s     of (# s2, x #) -> (# s2, F# x #)-readDoubleOffPtr (Ptr a) (I# i)-  = IO $ \s -> case readDoubleOffAddr# a i s    of (# s2, x #) -> (# s2, D# x #)-readStablePtrOffPtr (Ptr a) (I# i)-  = IO $ \s -> case readStablePtrOffAddr# a i s of (# s2, x #) -> (# s2, StablePtr x #)-readInt8OffPtr (Ptr a) (I# i)-  = IO $ \s -> case readInt8OffAddr# a i s      of (# s2, x #) -> (# s2, I8# x #)-readWord8OffPtr (Ptr a) (I# i)-  = IO $ \s -> case readWord8OffAddr# a i s     of (# s2, x #) -> (# s2, W8# x #)-readInt16OffPtr (Ptr a) (I# i)-  = IO $ \s -> case readInt16OffAddr# a i s     of (# s2, x #) -> (# s2, I16# x #)-readWord16OffPtr (Ptr a) (I# i)-  = IO $ \s -> case readWord16OffAddr# a i s    of (# s2, x #) -> (# s2, W16# x #)-readInt32OffPtr (Ptr a) (I# i)-  = IO $ \s -> case readInt32OffAddr# a i s     of (# s2, x #) -> (# s2, I32# x #)-readWord32OffPtr (Ptr a) (I# i)-  = IO $ \s -> case readWord32OffAddr# a i s    of (# s2, x #) -> (# s2, W32# x #)-readInt64OffPtr (Ptr a) (I# i)-  = IO $ \s -> case readInt64OffAddr# a i s     of (# s2, x #) -> (# s2, I64# x #)-readWord64OffPtr (Ptr a) (I# i)-  = IO $ \s -> case readWord64OffAddr# a i s    of (# s2, x #) -> (# s2, W64# x #)--writeWideCharOffPtr  :: Ptr Char          -> Int -> Char        -> IO ()-writeIntOffPtr       :: Ptr Int           -> Int -> Int         -> IO ()-writeWordOffPtr      :: Ptr Word          -> Int -> Word        -> IO ()-writePtrOffPtr       :: Ptr (Ptr a)       -> Int -> Ptr a       -> IO ()-writeFunPtrOffPtr    :: Ptr (FunPtr a)    -> Int -> FunPtr a    -> IO ()-writeFloatOffPtr     :: Ptr Float         -> Int -> Float       -> IO ()-writeDoubleOffPtr    :: Ptr Double        -> Int -> Double      -> IO ()-writeStablePtrOffPtr :: Ptr (StablePtr a) -> Int -> StablePtr a -> IO ()-writeInt8OffPtr      :: Ptr Int8          -> Int -> Int8        -> IO ()-writeInt16OffPtr     :: Ptr Int16         -> Int -> Int16       -> IO ()-writeInt32OffPtr     :: Ptr Int32         -> Int -> Int32       -> IO ()-writeInt64OffPtr     :: Ptr Int64         -> Int -> Int64       -> IO ()-writeWord8OffPtr     :: Ptr Word8         -> Int -> Word8       -> IO ()-writeWord16OffPtr    :: Ptr Word16        -> Int -> Word16      -> IO ()-writeWord32OffPtr    :: Ptr Word32        -> Int -> Word32      -> IO ()-writeWord64OffPtr    :: Ptr Word64        -> Int -> Word64      -> IO ()--writeWideCharOffPtr (Ptr a) (I# i) (C# x)-  = IO $ \s -> case writeWideCharOffAddr# a i x s  of s2 -> (# s2, () #)-writeIntOffPtr (Ptr a) (I# i) (I# x)-  = IO $ \s -> case writeIntOffAddr# a i x s       of s2 -> (# s2, () #)-writeWordOffPtr (Ptr a) (I# i) (W# x)-  = IO $ \s -> case writeWordOffAddr# a i x s      of s2 -> (# s2, () #)-writePtrOffPtr (Ptr a) (I# i) (Ptr x)-  = IO $ \s -> case writeAddrOffAddr# a i x s      of s2 -> (# s2, () #)-writeFunPtrOffPtr (Ptr a) (I# i) (FunPtr x)-  = IO $ \s -> case writeAddrOffAddr# a i x s      of s2 -> (# s2, () #)-writeFloatOffPtr (Ptr a) (I# i) (F# x)-  = IO $ \s -> case writeFloatOffAddr# a i x s     of s2 -> (# s2, () #)-writeDoubleOffPtr (Ptr a) (I# i) (D# x)-  = IO $ \s -> case writeDoubleOffAddr# a i x s    of s2 -> (# s2, () #)-writeStablePtrOffPtr (Ptr a) (I# i) (StablePtr x)-  = IO $ \s -> case writeStablePtrOffAddr# a i x s of s2 -> (# s2 , () #)-writeInt8OffPtr (Ptr a) (I# i) (I8# x)-  = IO $ \s -> case writeInt8OffAddr# a i x s      of s2 -> (# s2, () #)-writeWord8OffPtr (Ptr a) (I# i) (W8# x)-  = IO $ \s -> case writeWord8OffAddr# a i x s     of s2 -> (# s2, () #)-writeInt16OffPtr (Ptr a) (I# i) (I16# x)-  = IO $ \s -> case writeInt16OffAddr# a i x s     of s2 -> (# s2, () #)-writeWord16OffPtr (Ptr a) (I# i) (W16# x)-  = IO $ \s -> case writeWord16OffAddr# a i x s    of s2 -> (# s2, () #)-writeInt32OffPtr (Ptr a) (I# i) (I32# x)-  = IO $ \s -> case writeInt32OffAddr# a i x s     of s2 -> (# s2, () #)-writeWord32OffPtr (Ptr a) (I# i) (W32# x)-  = IO $ \s -> case writeWord32OffAddr# a i x s    of s2 -> (# s2, () #)-writeInt64OffPtr (Ptr a) (I# i) (I64# x)-  = IO $ \s -> case writeInt64OffAddr# a i x s     of s2 -> (# s2, () #)-writeWord64OffPtr (Ptr a) (I# i) (W64# x)-  = IO $ \s -> case writeWord64OffAddr# a i x s    of s2 -> (# s2, () #)
− GHC/TopHandler.hs
@@ -1,254 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , MagicHash-           , UnboxedTuples-  #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.TopHandler--- Copyright   :  (c) The University of Glasgow, 2001-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Support for catching exceptions raised during top-level computations--- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports)-----------------------------------------------------------------------------------module GHC.TopHandler (-        runMainIO, runIO, runIOFastExit, runNonIO,-        topHandler, topHandlerFastExit,-        reportStackOverflow, reportError,-        flushStdHandles-    ) where--#include "HsBaseConfig.h"--import Control.Exception-import Data.Maybe--import Foreign-import Foreign.C-import GHC.Base-import GHC.Conc hiding (throwTo)-import GHC.Real-import GHC.IO-import GHC.IO.Handle.FD-import GHC.IO.Handle-import GHC.IO.Exception-import GHC.Weak--#if defined(mingw32_HOST_OS)-import GHC.ConsoleHandler-#else-import Data.Dynamic (toDyn)-#endif---- | 'runMainIO' is wrapped around 'Main.main' (or whatever main is--- called in the program).  It catches otherwise uncaught exceptions,--- and also flushes stdout\/stderr before exiting.-runMainIO :: IO a -> IO a-runMainIO main =-    do-      main_thread_id <- myThreadId-      weak_tid <- mkWeakThreadId main_thread_id-      install_interrupt_handler $ do-           m <- deRefWeak weak_tid-           case m of-               Nothing  -> return ()-               Just tid -> throwTo tid (toException UserInterrupt)-      main -- hs_exit() will flush-    `catch`-      topHandler--install_interrupt_handler :: IO () -> IO ()-#ifdef mingw32_HOST_OS-install_interrupt_handler handler = do-  _ <- GHC.ConsoleHandler.installHandler $-     Catch $ \event ->-        case event of-           ControlC -> handler-           Break    -> handler-           Close    -> handler-           _ -> return ()-  return ()-#else-#include "rts/Signals.h"--- specialised version of System.Posix.Signals.installHandler, which--- isn't available here.-install_interrupt_handler handler = do-   let sig = CONST_SIGINT :: CInt-   _ <- setHandler sig (Just (const handler, toDyn handler))-   _ <- stg_sig_install sig STG_SIG_RST nullPtr-     -- STG_SIG_RST: the second ^C kills us for real, just in case the-     -- RTS or program is unresponsive.-   return ()--foreign import ccall unsafe-  stg_sig_install-        :: CInt                         -- sig no.-        -> CInt                         -- action code (STG_SIG_HAN etc.)-        -> Ptr ()                       -- (in, out) blocked-        -> IO CInt                      -- (ret) old action code-#endif---- | 'runIO' is wrapped around every @foreign export@ and @foreign--- import \"wrapper\"@ to mop up any uncaught exceptions.  Thus, the--- result of running 'System.Exit.exitWith' in a foreign-exported--- function is the same as in the main thread: it terminates the--- program.----runIO :: IO a -> IO a-runIO main = catch main topHandler---- | Like 'runIO', but in the event of an exception that causes an exit,--- we don't shut down the system cleanly, we just exit.  This is--- useful in some cases, because the safe exit version will give other--- threads a chance to clean up first, which might shut down the--- system in a different way.  For example, try------   main = forkIO (runIO (exitWith (ExitFailure 1))) >> threadDelay 10000------ This will sometimes exit with "interrupted" and code 0, because the--- main thread is given a chance to shut down when the child thread calls--- safeExit.  There is a race to shut down between the main and child threads.----runIOFastExit :: IO a -> IO a-runIOFastExit main = catch main topHandlerFastExit-        -- NB. this is used by the testsuite driver---- | The same as 'runIO', but for non-IO computations.  Used for--- wrapping @foreign export@ and @foreign import \"wrapper\"@ when these--- are used to export Haskell functions with non-IO types.----runNonIO :: a -> IO a-runNonIO a = catch (a `seq` return a) topHandler--topHandler :: SomeException -> IO a-topHandler err = catch (real_handler safeExit err) topHandler--topHandlerFastExit :: SomeException -> IO a-topHandlerFastExit err =-  catchException (real_handler fastExit err) topHandlerFastExit---- Make sure we handle errors while reporting the error!--- (e.g. evaluating the string passed to 'error' might generate---  another error, etc.)----real_handler :: (Int -> IO a) -> SomeException -> IO a-real_handler exit se = do-  flushStdHandles -- before any error output-  case fromException se of-      Just StackOverflow -> do-           reportStackOverflow-           exit 2--      Just UserInterrupt  -> exitInterrupted--      _ -> case fromException se of-           -- only the main thread gets ExitException exceptions-           Just ExitSuccess     -> exit 0-           Just (ExitFailure n) -> exit n--           -- EPIPE errors received for stdout are ignored (#2699)-           _ -> catch (case fromException se of-                Just IOError{ ioe_type = ResourceVanished,-                              ioe_errno = Just ioe,-                              ioe_handle = Just hdl }-                   | Errno ioe == ePIPE, hdl == stdout -> exit 0-                _ -> do reportError se-                        exit 1-                ) (disasterHandler exit) -- See Note [Disaster with iconv]---- don't use errorBelch() directly, because we cannot call varargs functions--- using the FFI.-foreign import ccall unsafe "HsBase.h errorBelch2"-   errorBelch :: CString -> CString -> IO ()--disasterHandler :: (Int -> IO a) -> IOError -> IO a-disasterHandler exit _ =-  withCAString "%s" $ \fmt ->-    withCAString msgStr $ \msg ->-      errorBelch fmt msg >> exit 1-  where-    msgStr =-        "encountered an exception while trying to report an exception." ++-        "One possible reason for this is that we failed while trying to " ++-        "encode an error message. Check that your locale is configured " ++-        "properly."--{- Note [Disaster with iconv]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--When using iconv, it's possible for things like iconv_open to fail in-restricted environments (like an initram or restricted container), but-when this happens the error raised inevitably calls `peekCString`,-which depends on the users locale, which depends on using-`iconv_open`... which causes an infinite loop.--This occurrence is also known as tickets #10298 and #7695. So to work-around it we just set _another_ error handler and bail directly by-calling the RTS, without iconv at all.--}----- try to flush stdout/stderr, but don't worry if we fail--- (these handles might have errors, and we don't want to go into--- an infinite loop).-flushStdHandles :: IO ()-flushStdHandles = do-  hFlush stdout `catchAny` \_ -> return ()-  hFlush stderr `catchAny` \_ -> return ()--safeExit, fastExit :: Int -> IO a-safeExit = exitHelper useSafeExit-fastExit = exitHelper useFastExit--unreachable :: IO a-unreachable = fail "If you can read this, shutdownHaskellAndExit did not exit."--exitHelper :: CInt -> Int -> IO a-#ifdef mingw32_HOST_OS-exitHelper exitKind r =-  shutdownHaskellAndExit (fromIntegral r) exitKind >> unreachable-#else--- On Unix we use an encoding for the ExitCode:---      0 -- 255  normal exit code---   -127 -- -1   exit by signal--- For any invalid encoding we just use a replacement (0xff).-exitHelper exitKind r-  | r >= 0 && r <= 255-  = shutdownHaskellAndExit   (fromIntegral   r)  exitKind >> unreachable-  | r >= -127 && r <= -1-  = shutdownHaskellAndSignal (fromIntegral (-r)) exitKind >> unreachable-  | otherwise-  = shutdownHaskellAndExit   0xff                exitKind >> unreachable--foreign import ccall "shutdownHaskellAndSignal"-  shutdownHaskellAndSignal :: CInt -> CInt -> IO ()-#endif--exitInterrupted :: IO a-exitInterrupted =-#ifdef mingw32_HOST_OS-  safeExit 252-#else-  -- we must exit via the default action for SIGINT, so that the-  -- parent of this process can take appropriate action (see #2301)-  safeExit (-CONST_SIGINT)-#endif---- NOTE: shutdownHaskellAndExit must be called "safe", because it *can*--- re-enter Haskell land through finalizers.-foreign import ccall "Rts.h shutdownHaskellAndExit"-  shutdownHaskellAndExit :: CInt -> CInt -> IO ()--useFastExit, useSafeExit :: CInt-useFastExit = 1-useSafeExit = 0
− GHC/TypeLits.hs
@@ -1,241 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE DataKinds #-}-{-# LANGUAGE KindSignatures #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE TypeOperators #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE ConstraintKinds #-}-{-# LANGUAGE ExistentialQuantification #-}-{-# LANGUAGE RankNTypes #-}-{-# LANGUAGE UndecidableInstances #-}  -- for compiling instances of (==)-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE MagicHash #-}--{-| This module is an internal GHC module.  It declares the constants used-in the implementation of type-level natural numbers.  The programmer interface-for working with type-level naturals should be defined in a separate library.--@since 4.6.0.0--}--module GHC.TypeLits-  ( -- * Kinds-    Nat, Symbol--    -- * Linking type and value level-  , KnownNat, natVal, natVal'-  , KnownSymbol, symbolVal, symbolVal'-  , SomeNat(..), SomeSymbol(..)-  , someNatVal, someSymbolVal-  , sameNat, sameSymbol---    -- * Functions on type literals-  , type (<=), type (<=?), type (+), type (*), type (^), type (-)-  , CmpNat, CmpSymbol--  ) where--import GHC.Base(Eq(..), Ord(..), Bool(True,False), Ordering(..), otherwise)-import GHC.Num(Integer)-import GHC.Base(String)-import GHC.Show(Show(..))-import GHC.Read(Read(..))-import GHC.Prim(magicDict, Proxy#)-import Data.Maybe(Maybe(..))-import Data.Proxy (Proxy(..))-import Data.Type.Equality(type (==), (:~:)(Refl))-import Unsafe.Coerce(unsafeCoerce)---- | (Kind) This is the kind of type-level natural numbers.-data Nat---- | (Kind) This is the kind of type-level symbols.-data Symbol--------------------------------------------------------------------------------------- | This class gives the integer associated with a type-level natural.--- There are instances of the class for every concrete literal: 0, 1, 2, etc.------ @since 4.7.0.0-class KnownNat (n :: Nat) where-  natSing :: SNat n---- | This class gives the string associated with a type-level symbol.--- There are instances of the class for every concrete literal: "hello", etc.------ @since 4.7.0.0-class KnownSymbol (n :: Symbol) where-  symbolSing :: SSymbol n---- | @since 4.7.0.0-natVal :: forall n proxy. KnownNat n => proxy n -> Integer-natVal _ = case natSing :: SNat n of-             SNat x -> x---- | @since 4.7.0.0-symbolVal :: forall n proxy. KnownSymbol n => proxy n -> String-symbolVal _ = case symbolSing :: SSymbol n of-                SSymbol x -> x---- | @since 4.8.0.0-natVal' :: forall n. KnownNat n => Proxy# n -> Integer-natVal' _ = case natSing :: SNat n of-             SNat x -> x---- | @since 4.8.0.0-symbolVal' :: forall n. KnownSymbol n => Proxy# n -> String-symbolVal' _ = case symbolSing :: SSymbol n of-                SSymbol x -> x------ | This type represents unknown type-level natural numbers.-data SomeNat    = forall n. KnownNat n    => SomeNat    (Proxy n)-                  -- ^ @since 4.7.0.0---- | This type represents unknown type-level symbols.-data SomeSymbol = forall n. KnownSymbol n => SomeSymbol (Proxy n)-                  -- ^ @since 4.7.0.0---- | Convert an integer into an unknown type-level natural.------ @since 4.7.0.0-someNatVal :: Integer -> Maybe SomeNat-someNatVal n-  | n >= 0        = Just (withSNat SomeNat (SNat n) Proxy)-  | otherwise     = Nothing---- | Convert a string into an unknown type-level symbol.------ @since 4.7.0.0-someSymbolVal :: String -> SomeSymbol-someSymbolVal n   = withSSymbol SomeSymbol (SSymbol n) Proxy----instance Eq SomeNat where-  SomeNat x == SomeNat y = natVal x == natVal y--instance Ord SomeNat where-  compare (SomeNat x) (SomeNat y) = compare (natVal x) (natVal y)--instance Show SomeNat where-  showsPrec p (SomeNat x) = showsPrec p (natVal x)--instance Read SomeNat where-  readsPrec p xs = do (a,ys) <- readsPrec p xs-                      case someNatVal a of-                        Nothing -> []-                        Just n  -> [(n,ys)]---instance Eq SomeSymbol where-  SomeSymbol x == SomeSymbol y = symbolVal x == symbolVal y--instance Ord SomeSymbol where-  compare (SomeSymbol x) (SomeSymbol y) = compare (symbolVal x) (symbolVal y)--instance Show SomeSymbol where-  showsPrec p (SomeSymbol x) = showsPrec p (symbolVal x)--instance Read SomeSymbol where-  readsPrec p xs = [ (someSymbolVal a, ys) | (a,ys) <- readsPrec p xs ]--type family EqNat (a :: Nat) (b :: Nat) where-  EqNat a a = 'True-  EqNat a b = 'False-type instance a == b = EqNat a b--type family EqSymbol (a :: Symbol) (b :: Symbol) where-  EqSymbol a a = 'True-  EqSymbol a b = 'False-type instance a == b = EqSymbol a b------------------------------------------------------------------------------------infix  4 <=?, <=-infixl 6 +, --infixl 7 *-infixr 8 ^---- | Comparison of type-level naturals, as a constraint.-type x <= y = (x <=? y) ~ 'True---- | Comparison of type-level symbols, as a function.------ @since 4.7.0.0-type family CmpSymbol (m :: Symbol) (n :: Symbol) :: Ordering---- | Comparison of type-level naturals, as a function.------ @since 4.7.0.0-type family CmpNat    (m :: Nat)    (n :: Nat)    :: Ordering--{- | Comparison of type-level naturals, as a function.-NOTE: The functionality for this function should be subsumed-by 'CmpNat', so this might go away in the future.-Please let us know, if you encounter discrepancies between the two. -}-type family (m :: Nat) <=? (n :: Nat) :: Bool---- | Addition of type-level naturals.-type family (m :: Nat) + (n :: Nat) :: Nat---- | Multiplication of type-level naturals.-type family (m :: Nat) * (n :: Nat) :: Nat---- | Exponentiation of type-level naturals.-type family (m :: Nat) ^ (n :: Nat) :: Nat---- | Subtraction of type-level naturals.------ @since 4.7.0.0-type family (m :: Nat) - (n :: Nat) :: Nat--------------------------------------------------------------------------------------- | We either get evidence that this function was instantiated with the--- same type-level numbers, or 'Nothing'.------ @since 4.7.0.0-sameNat :: (KnownNat a, KnownNat b) =>-           Proxy a -> Proxy b -> Maybe (a :~: b)-sameNat x y-  | natVal x == natVal y = Just (unsafeCoerce Refl)-  | otherwise            = Nothing---- | We either get evidence that this function was instantiated with the--- same type-level symbols, or 'Nothing'.------ @since 4.7.0.0-sameSymbol :: (KnownSymbol a, KnownSymbol b) =>-              Proxy a -> Proxy b -> Maybe (a :~: b)-sameSymbol x y-  | symbolVal x == symbolVal y  = Just (unsafeCoerce Refl)-  | otherwise                   = Nothing------------------------------------------------------------------------------------- PRIVATE:--newtype SNat    (n :: Nat)    = SNat    Integer-newtype SSymbol (s :: Symbol) = SSymbol String--data WrapN a b = WrapN (KnownNat    a => Proxy a -> b)-data WrapS a b = WrapS (KnownSymbol a => Proxy a -> b)---- See Note [magicDictId magic] in "basicType/MkId.hs"-withSNat :: (KnownNat a => Proxy a -> b)-         -> SNat a      -> Proxy a -> b-withSNat f x y = magicDict (WrapN f) x y---- See Note [magicDictId magic] in "basicType/MkId.hs"-withSSymbol :: (KnownSymbol a => Proxy a -> b)-            -> SSymbol a      -> Proxy a -> b-withSSymbol f x y = magicDict (WrapS f) x y--
− GHC/Unicode.hs
@@ -1,184 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Unicode--- Copyright   :  (c) The University of Glasgow, 2003--- License     :  see libraries/base/LICENSE--- --- Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC extensions)------ Implementations for the character predicates (isLower, isUpper, etc.)--- and the conversions (toUpper, toLower).  The implementation uses--- libunicode on Unix systems if that is available.-----------------------------------------------------------------------------------module GHC.Unicode (-        isAscii, isLatin1, isControl,-        isAsciiUpper, isAsciiLower,-        isPrint, isSpace,  isUpper,-        isLower, isAlpha,  isDigit,-        isOctDigit, isHexDigit, isAlphaNum,-        toUpper, toLower, toTitle,-        wgencat-    ) where--import GHC.Base-import GHC.Char        (chr)-import GHC.Real-import GHC.Num--#include "HsBaseConfig.h"---- | Selects the first 128 characters of the Unicode character set,--- corresponding to the ASCII character set.-isAscii                 :: Char -> Bool-isAscii c               =  c <  '\x80'---- | Selects the first 256 characters of the Unicode character set,--- corresponding to the ISO 8859-1 (Latin-1) character set.-isLatin1                :: Char -> Bool-isLatin1 c              =  c <= '\xff'---- | Selects ASCII lower-case letters,--- i.e. characters satisfying both 'isAscii' and 'isLower'.-isAsciiLower :: Char -> Bool-isAsciiLower c          =  c >= 'a' && c <= 'z'---- | Selects ASCII upper-case letters,--- i.e. characters satisfying both 'isAscii' and 'isUpper'.-isAsciiUpper :: Char -> Bool-isAsciiUpper c          =  c >= 'A' && c <= 'Z'---- | Selects control characters, which are the non-printing characters of--- the Latin-1 subset of Unicode.-isControl               :: Char -> Bool---- | Selects printable Unicode characters--- (letters, numbers, marks, punctuation, symbols and spaces).-isPrint                 :: Char -> Bool---- | Returns 'True' for any Unicode space character, and the control--- characters @\\t@, @\\n@, @\\r@, @\\f@, @\\v@.-isSpace                 :: Char -> Bool--- isSpace includes non-breaking space--- The magic 0x377 isn't really that magical. As of 2014, all the codepoints--- at or below 0x377 have been assigned, so we shouldn't have to worry about--- any new spaces appearing below there. It would probably be best to--- use branchless ||, but currently the eqLit transformation will undo that,--- so we'll do it like this until there's a way around that.-isSpace c-  | uc <= 0x377 = uc == 32 || uc - 0x9 <= 4 || uc == 0xa0-  | otherwise = iswspace (ord c) /= 0-  where-    uc = fromIntegral (ord c) :: Word---- | Selects upper-case or title-case alphabetic Unicode characters (letters).--- Title case is used by a small number of letter ligatures like the--- single-character form of /Lj/.-isUpper                 :: Char -> Bool---- | Selects lower-case alphabetic Unicode characters (letters).-isLower                 :: Char -> Bool---- | Selects alphabetic Unicode characters (lower-case, upper-case and--- title-case letters, plus letters of caseless scripts and modifiers letters).--- This function is equivalent to 'Data.Char.isLetter'.-isAlpha                 :: Char -> Bool---- | Selects alphabetic or numeric digit Unicode characters.------ Note that numeric digits outside the ASCII range are selected by this--- function but not by 'isDigit'.  Such digits may be part of identifiers--- but are not used by the printer and reader to represent numbers.-isAlphaNum              :: Char -> Bool---- | Selects ASCII digits, i.e. @\'0\'@..@\'9\'@.-isDigit                 :: Char -> Bool-isDigit c               =  (fromIntegral (ord c - ord '0') :: Word) <= 9---- We use an addition and an unsigned comparison instead of two signed--- comparisons because it's usually faster and puts less strain on branch--- prediction. It likely also enables some CSE when combined with functions--- that follow up with an actual conversion.---- | Selects ASCII octal digits, i.e. @\'0\'@..@\'7\'@.-isOctDigit              :: Char -> Bool-isOctDigit c            =  (fromIntegral (ord c - ord '0') :: Word) <= 7---- | Selects ASCII hexadecimal digits,--- i.e. @\'0\'@..@\'9\'@, @\'a\'@..@\'f\'@, @\'A\'@..@\'F\'@.-isHexDigit              :: Char -> Bool-isHexDigit c            =  isDigit c ||-                           (fromIntegral (ord c - ord 'A')::Word) <= 5 ||-                           (fromIntegral (ord c - ord 'a')::Word) <= 5---- | Convert a letter to the corresponding upper-case letter, if any.--- Any other character is returned unchanged.-toUpper                 :: Char -> Char---- | Convert a letter to the corresponding lower-case letter, if any.--- Any other character is returned unchanged.-toLower                 :: Char -> Char---- | Convert a letter to the corresponding title-case or upper-case--- letter, if any.  (Title case differs from upper case only for a small--- number of ligature letters.)--- Any other character is returned unchanged.-toTitle                 :: Char -> Char---- -------------------------------------------------------------------------------- Implementation with the supplied auto-generated Unicode character properties--- table---- Regardless of the O/S and Library, use the functions contained in WCsubst.c--isAlpha    c = iswalpha (ord c) /= 0-isAlphaNum c = iswalnum (ord c) /= 0-isControl  c = iswcntrl (ord c) /= 0-isPrint    c = iswprint (ord c) /= 0-isUpper    c = iswupper (ord c) /= 0-isLower    c = iswlower (ord c) /= 0--toLower c = chr (towlower (ord c))-toUpper c = chr (towupper (ord c))-toTitle c = chr (towtitle (ord c))--foreign import ccall unsafe "u_iswalpha"-  iswalpha :: Int -> Int--foreign import ccall unsafe "u_iswalnum"-  iswalnum :: Int -> Int--foreign import ccall unsafe "u_iswcntrl"-  iswcntrl :: Int -> Int--foreign import ccall unsafe "u_iswspace"-  iswspace :: Int -> Int--foreign import ccall unsafe "u_iswprint"-  iswprint :: Int -> Int--foreign import ccall unsafe "u_iswlower"-  iswlower :: Int -> Int--foreign import ccall unsafe "u_iswupper"-  iswupper :: Int -> Int--foreign import ccall unsafe "u_towlower"-  towlower :: Int -> Int--foreign import ccall unsafe "u_towupper"-  towupper :: Int -> Int--foreign import ccall unsafe "u_towtitle"-  towtitle :: Int -> Int--foreign import ccall unsafe "u_gencat"-  wgencat :: Int -> Int-
− GHC/Weak.hs
@@ -1,157 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude-           , BangPatterns-           , MagicHash-           , UnboxedTuples-           , DeriveDataTypeable-           , StandaloneDeriving-  #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Weak--- Copyright   :  (c) The University of Glasgow, 1998-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Weak pointers.-----------------------------------------------------------------------------------module GHC.Weak (-        Weak(..),-        mkWeak,-        deRefWeak,-        finalize,-        runFinalizerBatch-    ) where--import GHC.Base-import Data.Typeable--{-|-A weak pointer object with a key and a value.  The value has type @v@.--A weak pointer expresses a relationship between two objects, the-/key/ and the /value/:  if the key is considered to be alive by the-garbage collector, then the value is also alive.  A reference from-the value to the key does /not/ keep the key alive.--A weak pointer may also have a finalizer of type @IO ()@; if it does,-then the finalizer will be run at most once, at a time after the key-has become unreachable by the program (\"dead\").  The storage manager-attempts to run the finalizer(s) for an object soon after the object-dies, but promptness is not guaranteed.--It is not guaranteed that a finalizer will eventually run, and no-attempt is made to run outstanding finalizers when the program exits.-Therefore finalizers should not be relied on to clean up resources --other methods (eg. exception handlers) should be employed, possibly in-addition to finalizers.--References from the finalizer to the key are treated in the same way-as references from the value to the key: they do not keep the key-alive.  A finalizer may therefore ressurrect the key, perhaps by-storing it in the same data structure.--The finalizer, and the relationship between the key and the value,-exist regardless of whether the program keeps a reference to the-'Weak' object or not.--There may be multiple weak pointers with the same key.  In this-case, the finalizers for each of these weak pointers will all be-run in some arbitrary order, or perhaps concurrently, when the key-dies.  If the programmer specifies a finalizer that assumes it has-the only reference to an object (for example, a file that it wishes-to close), then the programmer must ensure that there is only one-such finalizer.--If there are no other threads to run, the runtime system will check-for runnable finalizers before declaring the system to be deadlocked.--WARNING: weak pointers to ordinary non-primitive Haskell types are-particularly fragile, because the compiler is free to optimise away or-duplicate the underlying data structure.  Therefore attempting to-place a finalizer on an ordinary Haskell type may well result in the-finalizer running earlier than you expected.  This is not a problem-for caches and memo tables where early finalization is benign.--Finalizers /can/ be used reliably for types that are created explicitly-and have identity, such as @IORef@ and @MVar@.  However, to place a-finalizer on one of these types, you should use the specific operation-provided for that type, e.g. @mkWeakIORef@ and @addMVarFinalizer@-respectively (the non-uniformity is accidental).  These operations-attach the finalizer to the primitive object inside the box-(e.g. @MutVar#@ in the case of @IORef@), because attaching the-finalizer to the box itself fails when the outer box is optimised away-by the compiler.---}-data Weak v = Weak (Weak# v) deriving Typeable---- | Establishes a weak pointer to @k@, with value @v@ and a finalizer.------ This is the most general interface for building a weak pointer.----mkWeak  :: k                            -- ^ key-        -> v                            -- ^ value-        -> Maybe (IO ())                -- ^ finalizer-        -> IO (Weak v)                  -- ^ returns: a weak pointer object--mkWeak key val (Just finalizer) = IO $ \s ->-   case mkWeak# key val finalizer s of { (# s1, w #) -> (# s1, Weak w #) }-mkWeak key val Nothing = IO $ \s ->-   case mkWeakNoFinalizer# key val s of { (# s1, w #) -> (# s1, Weak w #) }--{-|-Dereferences a weak pointer.  If the key is still alive, then-@'Just' v@ is returned (where @v@ is the /value/ in the weak pointer), otherwise-'Nothing' is returned.--The return value of 'deRefWeak' depends on when the garbage collector-runs, hence it is in the 'IO' monad.--}-deRefWeak :: Weak v -> IO (Maybe v)-deRefWeak (Weak w) = IO $ \s ->-   case deRefWeak# w s of-        (# s1, flag, p #) -> case flag of-                                0# -> (# s1, Nothing #)-                                _  -> (# s1, Just p #)---- | Causes a the finalizer associated with a weak pointer to be run--- immediately.-finalize :: Weak v -> IO ()-finalize (Weak w) = IO $ \s ->-   case finalizeWeak# w s of-        (# s1, 0#, _ #) -> (# s1, () #) -- already dead, or no finalizer-        (# s1, _,  f #) -> f s1--{--Instance Eq (Weak v) where-  (Weak w1) == (Weak w2) = w1 `sameWeak#` w2--}----- run a batch of finalizers from the garbage collector.  We're given--- an array of finalizers and the length of the array, and we just--- call each one in turn.------ the IO primitives are inlined by hand here to get the optimal--- code (sigh) --SDM.--runFinalizerBatch :: Int -> Array# (IO ()) -> IO ()-runFinalizerBatch (I# n) arr =-   let  go m  = IO $ \s ->-                  case m of-                  0# -> (# s, () #)-                  _  -> let !m' = m -# 1# in-                        case indexArray# arr m' of { (# io #) ->-                        case unIO io s of          { (# s', _ #) ->-                        unIO (go m') s'-                        }}-   in-        go n
− GHC/Windows.hs
@@ -1,196 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Windows--- Copyright   :  (c) The University of Glasgow, 2009--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  internal--- Portability :  non-portable------ Windows functionality used by several modules.------ ToDo: this just duplicates part of System.Win32.Types, which isn't--- available yet.  We should move some Win32 functionality down here,--- maybe as part of the grand reorganisation of the base package...-----------------------------------------------------------------------------------module GHC.Windows (-        -- * Types-        BOOL,-        LPBOOL,-        BYTE,-        DWORD,-        UINT,-        ErrCode,-        HANDLE,-        LPWSTR,-        LPTSTR,--        -- * Constants-        iNFINITE,-        iNVALID_HANDLE_VALUE,--        -- * System errors-        throwGetLastError,-        failWith,-        getLastError,-        getErrorMessage,-        errCodeToIOError,--        -- ** Guards for system calls that might fail-        failIf,-        failIf_,-        failIfNull,-        failIfZero,-        failIfFalse_,-        failUnlessSuccess,-        failUnlessSuccessOr,--        -- ** Mapping system errors to errno-        -- $errno-        c_maperrno,-        c_maperrno_func,-    ) where--import Data.Char-import Data.OldList-import Data.Maybe-import Data.Word-import Foreign.C.Error-import Foreign.C.String-import Foreign.C.Types-import Foreign.Ptr-import GHC.Base-import GHC.IO-import GHC.Num-import System.IO.Error--import qualified Numeric--#if defined(i386_HOST_ARCH)-# define WINDOWS_CCONV stdcall-#elif defined(x86_64_HOST_ARCH)-# define WINDOWS_CCONV ccall-#else-# error Unknown mingw32 arch-#endif--type BOOL    = Bool-type LPBOOL  = Ptr BOOL-type BYTE    = Word8-type DWORD   = Word32-type UINT    = Word32-type ErrCode = DWORD-type HANDLE  = Ptr ()-type LPWSTR  = Ptr CWchar---- | Be careful with this.  LPTSTR can mean either WCHAR* or CHAR*, depending--- on whether the UNICODE macro is defined in the corresponding C code.--- Consider using LPWSTR instead.-type LPTSTR = LPWSTR--iNFINITE :: DWORD-iNFINITE = 0xFFFFFFFF -- urgh--iNVALID_HANDLE_VALUE :: HANDLE-iNVALID_HANDLE_VALUE = wordPtrToPtr (-1)---- | Get the last system error, and throw it as an 'IOError' exception.-throwGetLastError :: String -> IO a-throwGetLastError where_from =-    getLastError >>= failWith where_from---- | Convert a Windows error code to an exception, then throw it.-failWith :: String -> ErrCode -> IO a-failWith fn_name err_code =-    errCodeToIOError fn_name err_code >>= throwIO---- | Convert a Windows error code to an exception.-errCodeToIOError :: String -> ErrCode -> IO IOError-errCodeToIOError fn_name err_code = do-    msg <- getErrorMessage err_code--    -- turn GetLastError() into errno, which errnoToIOError knows-    -- how to convert to an IOException we can throw.-    -- XXX we should really do this directly.-    let errno = c_maperrno_func err_code--    let msg' = dropWhileEnd isSpace msg -- drop trailing \n-        ioerror = errnoToIOError fn_name errno Nothing Nothing-                    `ioeSetErrorString` msg'-    return ioerror---- | Get a string describing a Windows error code.  This uses the--- @FormatMessage@ system call.-getErrorMessage :: ErrCode -> IO String-getErrorMessage err_code =-    mask_ $ do-        c_msg <- c_getErrorMessage err_code-        if c_msg == nullPtr-          then return $ "Error 0x" ++ Numeric.showHex err_code ""-          else do msg <- peekCWString c_msg-                  -- We ignore failure of freeing c_msg, given we're already failing-                  _ <- localFree c_msg-                  return msg--failIf :: (a -> Bool) -> String -> IO a -> IO a-failIf p wh act = do-    v <- act-    if p v then throwGetLastError wh else return v--failIf_ :: (a -> Bool) -> String -> IO a -> IO ()-failIf_ p wh act = do-    v <- act-    if p v then throwGetLastError wh else return ()--failIfNull :: String -> IO (Ptr a) -> IO (Ptr a)-failIfNull = failIf (== nullPtr)--failIfZero :: (Eq a, Num a) => String -> IO a -> IO a-failIfZero = failIf (== 0)--failIfFalse_ :: String -> IO Bool -> IO ()-failIfFalse_ = failIf_ not--failUnlessSuccess :: String -> IO ErrCode -> IO ()-failUnlessSuccess fn_name act = do-    r <- act-    if r == 0 then return () else failWith fn_name r--failUnlessSuccessOr :: ErrCode -> String -> IO ErrCode -> IO Bool-failUnlessSuccessOr val fn_name act = do-    r <- act-    if r == 0 then return False-        else if r == val then return True-        else failWith fn_name r---- $errno------ On Windows, @errno@ is defined by msvcrt.dll for compatibility with other--- systems, and is distinct from the system error as returned--- by @GetLastError@.---- | Map the last system error to an errno value, and assign it to @errno@.-foreign import ccall unsafe "maperrno"             -- in Win32Utils.c-   c_maperrno :: IO ()---- | Pure function variant of 'c_maperrno' that does not call @GetLastError@--- or modify @errno@.-foreign import ccall unsafe "maperrno_func"        -- in Win32Utils.c-   c_maperrno_func :: ErrCode -> Errno--foreign import ccall unsafe "base_getErrorMessage" -- in Win32Utils.c-    c_getErrorMessage :: DWORD -> IO LPWSTR--foreign import WINDOWS_CCONV unsafe "windows.h LocalFree"-    localFree :: Ptr a -> IO (Ptr a)---- | Get the last system error produced in the current thread.-foreign import WINDOWS_CCONV unsafe "windows.h GetLastError"-    getLastError :: IO ErrCode
− GHC/Word.hs
@@ -1,804 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash, UnboxedTuples #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  GHC.Word--- Copyright   :  (c) The University of Glasgow, 1997-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (GHC Extensions)------ Sized unsigned integral types: 'Word', 'Word8', 'Word16', 'Word32', and--- 'Word64'.-----------------------------------------------------------------------------------#include "MachDeps.h"--module GHC.Word (-    Word(..), Word8(..), Word16(..), Word32(..), Word64(..),-    uncheckedShiftL64#,-    uncheckedShiftRL64#,-    byteSwap16,-    byteSwap32,-    byteSwap64-    ) where--import Data.Bits-import Data.Maybe--#if WORD_SIZE_IN_BITS < 64-import GHC.IntWord64-#endif--import GHC.Base-import GHC.Enum-import GHC.Num-import GHC.Real-import GHC.Read-import GHC.Arr-import GHC.Show----------------------------------------------------------------------------- type Word8----------------------------------------------------------------------------- Word8 is represented in the same way as Word. Operations may assume--- and must ensure that it holds only values from its logical range.--data {-# CTYPE "HsWord8" #-} Word8 = W8# Word# deriving (Eq, Ord)--- ^ 8-bit unsigned integer type--instance Show Word8 where-    showsPrec p x = showsPrec p (fromIntegral x :: Int)--instance Num Word8 where-    (W8# x#) + (W8# y#)    = W8# (narrow8Word# (x# `plusWord#` y#))-    (W8# x#) - (W8# y#)    = W8# (narrow8Word# (x# `minusWord#` y#))-    (W8# x#) * (W8# y#)    = W8# (narrow8Word# (x# `timesWord#` y#))-    negate (W8# x#)        = W8# (narrow8Word# (int2Word# (negateInt# (word2Int# x#))))-    abs x                  = x-    signum 0               = 0-    signum _               = 1-    fromInteger i          = W8# (narrow8Word# (integerToWord i))--instance Real Word8 where-    toRational x = toInteger x % 1--instance Enum Word8 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Word8"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Word8"-    toEnum i@(I# i#)-        | i >= 0 && i <= fromIntegral (maxBound::Word8)-                        = W8# (int2Word# i#)-        | otherwise     = toEnumError "Word8" i (minBound::Word8, maxBound::Word8)-    fromEnum (W8# x#)   = I# (word2Int# x#)-    enumFrom            = boundedEnumFrom-    enumFromThen        = boundedEnumFromThen--instance Integral Word8 where-    quot    (W8# x#) y@(W8# y#)-        | y /= 0                  = W8# (x# `quotWord#` y#)-        | otherwise               = divZeroError-    rem     (W8# x#) y@(W8# y#)-        | y /= 0                  = W8# (x# `remWord#` y#)-        | otherwise               = divZeroError-    div     (W8# x#) y@(W8# y#)-        | y /= 0                  = W8# (x# `quotWord#` y#)-        | otherwise               = divZeroError-    mod     (W8# x#) y@(W8# y#)-        | y /= 0                  = W8# (x# `remWord#` y#)-        | otherwise               = divZeroError-    quotRem (W8# x#) y@(W8# y#)-        | y /= 0                  = case x# `quotRemWord#` y# of-                                    (# q, r #) ->-                                        (W8# q, W8# r)-        | otherwise               = divZeroError-    divMod  (W8# x#) y@(W8# y#)-        | y /= 0                  = (W8# (x# `quotWord#` y#), W8# (x# `remWord#` y#))-        | otherwise               = divZeroError-    toInteger (W8# x#)            = smallInteger (word2Int# x#)--instance Bounded Word8 where-    minBound = 0-    maxBound = 0xFF--instance Ix Word8 where-    range (m,n)         = [m..n]-    unsafeIndex (m,_) i = fromIntegral (i - m)-    inRange (m,n) i     = m <= i && i <= n--instance Read Word8 where-    readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]--instance Bits Word8 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (W8# x#) .&.   (W8# y#)   = W8# (x# `and#` y#)-    (W8# x#) .|.   (W8# y#)   = W8# (x# `or#`  y#)-    (W8# x#) `xor` (W8# y#)   = W8# (x# `xor#` y#)-    complement (W8# x#)       = W8# (x# `xor#` mb#)-        where !(W8# mb#) = maxBound-    (W8# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#) = W8# (narrow8Word# (x# `shiftL#` i#))-        | otherwise           = W8# (x# `shiftRL#` negateInt# i#)-    (W8# x#) `shiftL`       (I# i#) = W8# (narrow8Word# (x# `shiftL#` i#))-    (W8# x#) `unsafeShiftL` (I# i#) =-        W8# (narrow8Word# (x# `uncheckedShiftL#` i#))-    (W8# x#) `shiftR`       (I# i#) = W8# (x# `shiftRL#` i#)-    (W8# x#) `unsafeShiftR` (I# i#) = W8# (x# `uncheckedShiftRL#` i#)-    (W8# x#) `rotate`       (I# i#)-        | isTrue# (i'# ==# 0#) = W8# x#-        | otherwise  = W8# (narrow8Word# ((x# `uncheckedShiftL#` i'#) `or#`-                                          (x# `uncheckedShiftRL#` (8# -# i'#))))-        where-        !i'# = word2Int# (int2Word# i# `and#` 7##)-    bitSizeMaybe i            = Just (finiteBitSize i)-    bitSize i                 = finiteBitSize i-    isSigned _                = False-    popCount (W8# x#)         = I# (word2Int# (popCnt8# x#))-    bit                       = bitDefault-    testBit                   = testBitDefault--instance FiniteBits Word8 where-    finiteBitSize _ = 8-    countLeadingZeros  (W8# x#) = I# (word2Int# (clz8# x#))-    countTrailingZeros (W8# x#) = I# (word2Int# (ctz8# x#))--{-# RULES-"fromIntegral/Word8->Word8"   fromIntegral = id :: Word8 -> Word8-"fromIntegral/Word8->Integer" fromIntegral = toInteger :: Word8 -> Integer-"fromIntegral/a->Word8"       fromIntegral = \x -> case fromIntegral x of W# x# -> W8# (narrow8Word# x#)-"fromIntegral/Word8->a"       fromIntegral = \(W8# x#) -> fromIntegral (W# x#)-  #-}--{-# RULES-"properFraction/Float->(Word8,Float)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Float) }-"truncate/Float->Word8"-    truncate = (fromIntegral :: Int -> Word8) . (truncate :: Float -> Int)-"floor/Float->Word8"-    floor    = (fromIntegral :: Int -> Word8) . (floor :: Float -> Int)-"ceiling/Float->Word8"-    ceiling  = (fromIntegral :: Int -> Word8) . (ceiling :: Float -> Int)-"round/Float->Word8"-    round    = (fromIntegral :: Int -> Word8) . (round  :: Float -> Int)-  #-}--{-# RULES-"properFraction/Double->(Word8,Double)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Double) }-"truncate/Double->Word8"-    truncate = (fromIntegral :: Int -> Word8) . (truncate :: Double -> Int)-"floor/Double->Word8"-    floor    = (fromIntegral :: Int -> Word8) . (floor :: Double -> Int)-"ceiling/Double->Word8"-    ceiling  = (fromIntegral :: Int -> Word8) . (ceiling :: Double -> Int)-"round/Double->Word8"-    round    = (fromIntegral :: Int -> Word8) . (round  :: Double -> Int)-  #-}----------------------------------------------------------------------------- type Word16----------------------------------------------------------------------------- Word16 is represented in the same way as Word. Operations may assume--- and must ensure that it holds only values from its logical range.--data {-# CTYPE "HsWord16" #-} Word16 = W16# Word# deriving (Eq, Ord)--- ^ 16-bit unsigned integer type--instance Show Word16 where-    showsPrec p x = showsPrec p (fromIntegral x :: Int)--instance Num Word16 where-    (W16# x#) + (W16# y#)  = W16# (narrow16Word# (x# `plusWord#` y#))-    (W16# x#) - (W16# y#)  = W16# (narrow16Word# (x# `minusWord#` y#))-    (W16# x#) * (W16# y#)  = W16# (narrow16Word# (x# `timesWord#` y#))-    negate (W16# x#)       = W16# (narrow16Word# (int2Word# (negateInt# (word2Int# x#))))-    abs x                  = x-    signum 0               = 0-    signum _               = 1-    fromInteger i          = W16# (narrow16Word# (integerToWord i))--instance Real Word16 where-    toRational x = toInteger x % 1--instance Enum Word16 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Word16"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Word16"-    toEnum i@(I# i#)-        | i >= 0 && i <= fromIntegral (maxBound::Word16)-                        = W16# (int2Word# i#)-        | otherwise     = toEnumError "Word16" i (minBound::Word16, maxBound::Word16)-    fromEnum (W16# x#)  = I# (word2Int# x#)-    enumFrom            = boundedEnumFrom-    enumFromThen        = boundedEnumFromThen--instance Integral Word16 where-    quot    (W16# x#) y@(W16# y#)-        | y /= 0                    = W16# (x# `quotWord#` y#)-        | otherwise                 = divZeroError-    rem     (W16# x#) y@(W16# y#)-        | y /= 0                    = W16# (x# `remWord#` y#)-        | otherwise                 = divZeroError-    div     (W16# x#) y@(W16# y#)-        | y /= 0                    = W16# (x# `quotWord#` y#)-        | otherwise                 = divZeroError-    mod     (W16# x#) y@(W16# y#)-        | y /= 0                    = W16# (x# `remWord#` y#)-        | otherwise                 = divZeroError-    quotRem (W16# x#) y@(W16# y#)-        | y /= 0                  = case x# `quotRemWord#` y# of-                                    (# q, r #) ->-                                        (W16# q, W16# r)-        | otherwise                 = divZeroError-    divMod  (W16# x#) y@(W16# y#)-        | y /= 0                    = (W16# (x# `quotWord#` y#), W16# (x# `remWord#` y#))-        | otherwise                 = divZeroError-    toInteger (W16# x#)             = smallInteger (word2Int# x#)--instance Bounded Word16 where-    minBound = 0-    maxBound = 0xFFFF--instance Ix Word16 where-    range (m,n)         = [m..n]-    unsafeIndex (m,_) i = fromIntegral (i - m)-    inRange (m,n) i     = m <= i && i <= n--instance Read Word16 where-    readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]--instance Bits Word16 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (W16# x#) .&.   (W16# y#)  = W16# (x# `and#` y#)-    (W16# x#) .|.   (W16# y#)  = W16# (x# `or#`  y#)-    (W16# x#) `xor` (W16# y#)  = W16# (x# `xor#` y#)-    complement (W16# x#)       = W16# (x# `xor#` mb#)-        where !(W16# mb#) = maxBound-    (W16# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)  = W16# (narrow16Word# (x# `shiftL#` i#))-        | otherwise            = W16# (x# `shiftRL#` negateInt# i#)-    (W16# x#) `shiftL` (I# i#)       = W16# (narrow16Word# (x# `shiftL#` i#))-    (W16# x#) `unsafeShiftL` (I# i#) =-        W16# (narrow16Word# (x# `uncheckedShiftL#` i#))-    (W16# x#) `shiftR`       (I# i#) = W16# (x# `shiftRL#` i#)-    (W16# x#) `unsafeShiftR` (I# i#) = W16# (x# `uncheckedShiftRL#` i#)-    (W16# x#) `rotate`       (I# i#)-        | isTrue# (i'# ==# 0#) = W16# x#-        | otherwise  = W16# (narrow16Word# ((x# `uncheckedShiftL#` i'#) `or#`-                                            (x# `uncheckedShiftRL#` (16# -# i'#))))-        where-        !i'# = word2Int# (int2Word# i# `and#` 15##)-    bitSizeMaybe i            = Just (finiteBitSize i)-    bitSize i                 = finiteBitSize i-    isSigned _                = False-    popCount (W16# x#)        = I# (word2Int# (popCnt16# x#))-    bit                       = bitDefault-    testBit                   = testBitDefault--instance FiniteBits Word16 where-    finiteBitSize _ = 16-    countLeadingZeros  (W16# x#) = I# (word2Int# (clz16# x#))-    countTrailingZeros (W16# x#) = I# (word2Int# (ctz16# x#))---- | Swap bytes in 'Word16'.------ @since 4.7.0.0-byteSwap16 :: Word16 -> Word16-byteSwap16 (W16# w#) = W16# (narrow16Word# (byteSwap16# w#))--{-# RULES-"fromIntegral/Word8->Word16"   fromIntegral = \(W8# x#) -> W16# x#-"fromIntegral/Word16->Word16"  fromIntegral = id :: Word16 -> Word16-"fromIntegral/Word16->Integer" fromIntegral = toInteger :: Word16 -> Integer-"fromIntegral/a->Word16"       fromIntegral = \x -> case fromIntegral x of W# x# -> W16# (narrow16Word# x#)-"fromIntegral/Word16->a"       fromIntegral = \(W16# x#) -> fromIntegral (W# x#)-  #-}--{-# RULES-"properFraction/Float->(Word16,Float)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Float) }-"truncate/Float->Word16"-    truncate = (fromIntegral :: Int -> Word16) . (truncate :: Float -> Int)-"floor/Float->Word16"-    floor    = (fromIntegral :: Int -> Word16) . (floor :: Float -> Int)-"ceiling/Float->Word16"-    ceiling  = (fromIntegral :: Int -> Word16) . (ceiling :: Float -> Int)-"round/Float->Word16"-    round    = (fromIntegral :: Int -> Word16) . (round  :: Float -> Int)-  #-}--{-# RULES-"properFraction/Double->(Word16,Double)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Double) }-"truncate/Double->Word16"-    truncate = (fromIntegral :: Int -> Word16) . (truncate :: Double -> Int)-"floor/Double->Word16"-    floor    = (fromIntegral :: Int -> Word16) . (floor :: Double -> Int)-"ceiling/Double->Word16"-    ceiling  = (fromIntegral :: Int -> Word16) . (ceiling :: Double -> Int)-"round/Double->Word16"-    round    = (fromIntegral :: Int -> Word16) . (round  :: Double -> Int)-  #-}----------------------------------------------------------------------------- type Word32----------------------------------------------------------------------------- Word32 is represented in the same way as Word.-#if WORD_SIZE_IN_BITS > 32--- Operations may assume and must ensure that it holds only values--- from its logical range.---- We can use rewrite rules for the RealFrac methods--{-# RULES-"properFraction/Float->(Word32,Float)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Float) }-"truncate/Float->Word32"-    truncate = (fromIntegral :: Int -> Word32) . (truncate :: Float -> Int)-"floor/Float->Word32"-    floor    = (fromIntegral :: Int -> Word32) . (floor :: Float -> Int)-"ceiling/Float->Word32"-    ceiling  = (fromIntegral :: Int -> Word32) . (ceiling :: Float -> Int)-"round/Float->Word32"-    round    = (fromIntegral :: Int -> Word32) . (round  :: Float -> Int)-  #-}--{-# RULES-"properFraction/Double->(Word32,Double)"-    properFraction = \x ->-                      case properFraction x of {-                        (n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Double) }-"truncate/Double->Word32"-    truncate = (fromIntegral :: Int -> Word32) . (truncate :: Double -> Int)-"floor/Double->Word32"-    floor    = (fromIntegral :: Int -> Word32) . (floor :: Double -> Int)-"ceiling/Double->Word32"-    ceiling  = (fromIntegral :: Int -> Word32) . (ceiling :: Double -> Int)-"round/Double->Word32"-    round    = (fromIntegral :: Int -> Word32) . (round  :: Double -> Int)-  #-}--#endif--data {-# CTYPE "HsWord32" #-} Word32 = W32# Word# deriving (Eq, Ord)--- ^ 32-bit unsigned integer type--instance Num Word32 where-    (W32# x#) + (W32# y#)  = W32# (narrow32Word# (x# `plusWord#` y#))-    (W32# x#) - (W32# y#)  = W32# (narrow32Word# (x# `minusWord#` y#))-    (W32# x#) * (W32# y#)  = W32# (narrow32Word# (x# `timesWord#` y#))-    negate (W32# x#)       = W32# (narrow32Word# (int2Word# (negateInt# (word2Int# x#))))-    abs x                  = x-    signum 0               = 0-    signum _               = 1-    fromInteger i          = W32# (narrow32Word# (integerToWord i))--instance Enum Word32 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Word32"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Word32"-    toEnum i@(I# i#)-        | i >= 0-#if WORD_SIZE_IN_BITS > 32-          && i <= fromIntegral (maxBound::Word32)-#endif-                        = W32# (int2Word# i#)-        | otherwise     = toEnumError "Word32" i (minBound::Word32, maxBound::Word32)-#if WORD_SIZE_IN_BITS == 32-    fromEnum x@(W32# x#)-        | x <= fromIntegral (maxBound::Int)-                        = I# (word2Int# x#)-        | otherwise     = fromEnumError "Word32" x-    enumFrom            = integralEnumFrom-    enumFromThen        = integralEnumFromThen-    enumFromTo          = integralEnumFromTo-    enumFromThenTo      = integralEnumFromThenTo-#else-    fromEnum (W32# x#)  = I# (word2Int# x#)-    enumFrom            = boundedEnumFrom-    enumFromThen        = boundedEnumFromThen-#endif--instance Integral Word32 where-    quot    (W32# x#) y@(W32# y#)-        | y /= 0                    = W32# (x# `quotWord#` y#)-        | otherwise                 = divZeroError-    rem     (W32# x#) y@(W32# y#)-        | y /= 0                    = W32# (x# `remWord#` y#)-        | otherwise                 = divZeroError-    div     (W32# x#) y@(W32# y#)-        | y /= 0                    = W32# (x# `quotWord#` y#)-        | otherwise                 = divZeroError-    mod     (W32# x#) y@(W32# y#)-        | y /= 0                    = W32# (x# `remWord#` y#)-        | otherwise                 = divZeroError-    quotRem (W32# x#) y@(W32# y#)-        | y /= 0                  = case x# `quotRemWord#` y# of-                                    (# q, r #) ->-                                        (W32# q, W32# r)-        | otherwise                 = divZeroError-    divMod  (W32# x#) y@(W32# y#)-        | y /= 0                    = (W32# (x# `quotWord#` y#), W32# (x# `remWord#` y#))-        | otherwise                 = divZeroError-    toInteger (W32# x#)-#if WORD_SIZE_IN_BITS == 32-        | isTrue# (i# >=# 0#)       = smallInteger i#-        | otherwise                 = wordToInteger x#-        where-        !i# = word2Int# x#-#else-                                    = smallInteger (word2Int# x#)-#endif--instance Bits Word32 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (W32# x#) .&.   (W32# y#)  = W32# (x# `and#` y#)-    (W32# x#) .|.   (W32# y#)  = W32# (x# `or#`  y#)-    (W32# x#) `xor` (W32# y#)  = W32# (x# `xor#` y#)-    complement (W32# x#)       = W32# (x# `xor#` mb#)-        where !(W32# mb#) = maxBound-    (W32# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)  = W32# (narrow32Word# (x# `shiftL#` i#))-        | otherwise            = W32# (x# `shiftRL#` negateInt# i#)-    (W32# x#) `shiftL`       (I# i#) = W32# (narrow32Word# (x# `shiftL#` i#))-    (W32# x#) `unsafeShiftL` (I# i#) =-        W32# (narrow32Word# (x# `uncheckedShiftL#` i#))-    (W32# x#) `shiftR`       (I# i#) = W32# (x# `shiftRL#` i#)-    (W32# x#) `unsafeShiftR` (I# i#) = W32# (x# `uncheckedShiftRL#` i#)-    (W32# x#) `rotate`       (I# i#)-        | isTrue# (i'# ==# 0#) = W32# x#-        | otherwise   = W32# (narrow32Word# ((x# `uncheckedShiftL#` i'#) `or#`-                                            (x# `uncheckedShiftRL#` (32# -# i'#))))-        where-        !i'# = word2Int# (int2Word# i# `and#` 31##)-    bitSizeMaybe i            = Just (finiteBitSize i)-    bitSize i                 = finiteBitSize i-    isSigned _                = False-    popCount (W32# x#)        = I# (word2Int# (popCnt32# x#))-    bit                       = bitDefault-    testBit                   = testBitDefault--instance FiniteBits Word32 where-    finiteBitSize _ = 32-    countLeadingZeros  (W32# x#) = I# (word2Int# (clz32# x#))-    countTrailingZeros (W32# x#) = I# (word2Int# (ctz32# x#))--{-# RULES-"fromIntegral/Word8->Word32"   fromIntegral = \(W8# x#) -> W32# x#-"fromIntegral/Word16->Word32"  fromIntegral = \(W16# x#) -> W32# x#-"fromIntegral/Word32->Word32"  fromIntegral = id :: Word32 -> Word32-"fromIntegral/Word32->Integer" fromIntegral = toInteger :: Word32 -> Integer-"fromIntegral/a->Word32"       fromIntegral = \x -> case fromIntegral x of W# x# -> W32# (narrow32Word# x#)-"fromIntegral/Word32->a"       fromIntegral = \(W32# x#) -> fromIntegral (W# x#)-  #-}--instance Show Word32 where-#if WORD_SIZE_IN_BITS < 33-    showsPrec p x = showsPrec p (toInteger x)-#else-    showsPrec p x = showsPrec p (fromIntegral x :: Int)-#endif---instance Real Word32 where-    toRational x = toInteger x % 1--instance Bounded Word32 where-    minBound = 0-    maxBound = 0xFFFFFFFF--instance Ix Word32 where-    range (m,n)         = [m..n]-    unsafeIndex (m,_) i = fromIntegral (i - m)-    inRange (m,n) i     = m <= i && i <= n--instance Read Word32 where-#if WORD_SIZE_IN_BITS < 33-    readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]-#else-    readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]-#endif---- | Reverse order of bytes in 'Word32'.------ @since 4.7.0.0-byteSwap32 :: Word32 -> Word32-byteSwap32 (W32# w#) = W32# (narrow32Word# (byteSwap32# w#))----------------------------------------------------------------------------- type Word64---------------------------------------------------------------------------#if WORD_SIZE_IN_BITS < 64--data {-# CTYPE "HsWord64" #-} Word64 = W64# Word64#--- ^ 64-bit unsigned integer type--instance Eq Word64 where-    (W64# x#) == (W64# y#) = isTrue# (x# `eqWord64#` y#)-    (W64# x#) /= (W64# y#) = isTrue# (x# `neWord64#` y#)--instance Ord Word64 where-    (W64# x#) <  (W64# y#) = isTrue# (x# `ltWord64#` y#)-    (W64# x#) <= (W64# y#) = isTrue# (x# `leWord64#` y#)-    (W64# x#) >  (W64# y#) = isTrue# (x# `gtWord64#` y#)-    (W64# x#) >= (W64# y#) = isTrue# (x# `geWord64#` y#)--instance Num Word64 where-    (W64# x#) + (W64# y#)  = W64# (int64ToWord64# (word64ToInt64# x# `plusInt64#` word64ToInt64# y#))-    (W64# x#) - (W64# y#)  = W64# (int64ToWord64# (word64ToInt64# x# `minusInt64#` word64ToInt64# y#))-    (W64# x#) * (W64# y#)  = W64# (int64ToWord64# (word64ToInt64# x# `timesInt64#` word64ToInt64# y#))-    negate (W64# x#)       = W64# (int64ToWord64# (negateInt64# (word64ToInt64# x#)))-    abs x                  = x-    signum 0               = 0-    signum _               = 1-    fromInteger i          = W64# (integerToWord64 i)--instance Enum Word64 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Word64"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Word64"-    toEnum i@(I# i#)-        | i >= 0        = W64# (wordToWord64# (int2Word# i#))-        | otherwise     = toEnumError "Word64" i (minBound::Word64, maxBound::Word64)-    fromEnum x@(W64# x#)-        | x <= fromIntegral (maxBound::Int)-                        = I# (word2Int# (word64ToWord# x#))-        | otherwise     = fromEnumError "Word64" x-    enumFrom            = integralEnumFrom-    enumFromThen        = integralEnumFromThen-    enumFromTo          = integralEnumFromTo-    enumFromThenTo      = integralEnumFromThenTo--instance Integral Word64 where-    quot    (W64# x#) y@(W64# y#)-        | y /= 0                    = W64# (x# `quotWord64#` y#)-        | otherwise                 = divZeroError-    rem     (W64# x#) y@(W64# y#)-        | y /= 0                    = W64# (x# `remWord64#` y#)-        | otherwise                 = divZeroError-    div     (W64# x#) y@(W64# y#)-        | y /= 0                    = W64# (x# `quotWord64#` y#)-        | otherwise                 = divZeroError-    mod     (W64# x#) y@(W64# y#)-        | y /= 0                    = W64# (x# `remWord64#` y#)-        | otherwise                 = divZeroError-    quotRem (W64# x#) y@(W64# y#)-        | y /= 0                    = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#))-        | otherwise                 = divZeroError-    divMod  (W64# x#) y@(W64# y#)-        | y /= 0                    = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#))-        | otherwise                 = divZeroError-    toInteger (W64# x#)             = word64ToInteger x#--instance Bits Word64 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (W64# x#) .&.   (W64# y#)  = W64# (x# `and64#` y#)-    (W64# x#) .|.   (W64# y#)  = W64# (x# `or64#`  y#)-    (W64# x#) `xor` (W64# y#)  = W64# (x# `xor64#` y#)-    complement (W64# x#)       = W64# (not64# x#)-    (W64# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)  = W64# (x# `shiftL64#` i#)-        | otherwise            = W64# (x# `shiftRL64#` negateInt# i#)-    (W64# x#) `shiftL`       (I# i#) = W64# (x# `shiftL64#` i#)-    (W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL64#` i#)-    (W64# x#) `shiftR`       (I# i#) = W64# (x# `shiftRL64#` i#)-    (W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL64#` i#)-    (W64# x#) `rotate` (I# i#)-        | isTrue# (i'# ==# 0#) = W64# x#-        | otherwise            = W64# ((x# `uncheckedShiftL64#` i'#) `or64#`-                                       (x# `uncheckedShiftRL64#` (64# -# i'#)))-        where-        !i'# = word2Int# (int2Word# i# `and#` 63##)-    bitSizeMaybe i            = Just (finiteBitSize i)-    bitSize i                 = finiteBitSize i-    isSigned _                = False-    popCount (W64# x#)        = I# (word2Int# (popCnt64# x#))-    bit                       = bitDefault-    testBit                   = testBitDefault---- give the 64-bit shift operations the same treatment as the 32-bit--- ones (see GHC.Base), namely we wrap them in tests to catch the--- cases when we're shifting more than 64 bits to avoid unspecified--- behaviour in the C shift operations.--shiftL64#, shiftRL64# :: Word64# -> Int# -> Word64#--a `shiftL64#` b  | isTrue# (b >=# 64#) = wordToWord64# 0##-                 | otherwise           = a `uncheckedShiftL64#` b--a `shiftRL64#` b | isTrue# (b >=# 64#) = wordToWord64# 0##-                 | otherwise           = a `uncheckedShiftRL64#` b--{-# RULES-"fromIntegral/Int->Word64"    fromIntegral = \(I#   x#) -> W64# (int64ToWord64# (intToInt64# x#))-"fromIntegral/Word->Word64"   fromIntegral = \(W#   x#) -> W64# (wordToWord64# x#)-"fromIntegral/Word64->Int"    fromIntegral = \(W64# x#) -> I#   (word2Int# (word64ToWord# x#))-"fromIntegral/Word64->Word"   fromIntegral = \(W64# x#) -> W#   (word64ToWord# x#)-"fromIntegral/Word64->Word64" fromIntegral = id :: Word64 -> Word64-  #-}--#else---- Word64 is represented in the same way as Word.--- Operations may assume and must ensure that it holds only values--- from its logical range.--data {-# CTYPE "HsWord64" #-} Word64 = W64# Word# deriving (Eq, Ord)--- ^ 64-bit unsigned integer type--instance Num Word64 where-    (W64# x#) + (W64# y#)  = W64# (x# `plusWord#` y#)-    (W64# x#) - (W64# y#)  = W64# (x# `minusWord#` y#)-    (W64# x#) * (W64# y#)  = W64# (x# `timesWord#` y#)-    negate (W64# x#)       = W64# (int2Word# (negateInt# (word2Int# x#)))-    abs x                  = x-    signum 0               = 0-    signum _               = 1-    fromInteger i          = W64# (integerToWord i)--instance Enum Word64 where-    succ x-        | x /= maxBound = x + 1-        | otherwise     = succError "Word64"-    pred x-        | x /= minBound = x - 1-        | otherwise     = predError "Word64"-    toEnum i@(I# i#)-        | i >= 0        = W64# (int2Word# i#)-        | otherwise     = toEnumError "Word64" i (minBound::Word64, maxBound::Word64)-    fromEnum x@(W64# x#)-        | x <= fromIntegral (maxBound::Int)-                        = I# (word2Int# x#)-        | otherwise     = fromEnumError "Word64" x-    enumFrom            = integralEnumFrom-    enumFromThen        = integralEnumFromThen-    enumFromTo          = integralEnumFromTo-    enumFromThenTo      = integralEnumFromThenTo--instance Integral Word64 where-    quot    (W64# x#) y@(W64# y#)-        | y /= 0                    = W64# (x# `quotWord#` y#)-        | otherwise                 = divZeroError-    rem     (W64# x#) y@(W64# y#)-        | y /= 0                    = W64# (x# `remWord#` y#)-        | otherwise                 = divZeroError-    div     (W64# x#) y@(W64# y#)-        | y /= 0                    = W64# (x# `quotWord#` y#)-        | otherwise                 = divZeroError-    mod     (W64# x#) y@(W64# y#)-        | y /= 0                    = W64# (x# `remWord#` y#)-        | otherwise                 = divZeroError-    quotRem (W64# x#) y@(W64# y#)-        | y /= 0                  = case x# `quotRemWord#` y# of-                                    (# q, r #) ->-                                        (W64# q, W64# r)-        | otherwise                 = divZeroError-    divMod  (W64# x#) y@(W64# y#)-        | y /= 0                    = (W64# (x# `quotWord#` y#), W64# (x# `remWord#` y#))-        | otherwise                 = divZeroError-    toInteger (W64# x#)-        | isTrue# (i# >=# 0#)       = smallInteger i#-        | otherwise                 = wordToInteger x#-        where-        !i# = word2Int# x#--instance Bits Word64 where-    {-# INLINE shift #-}-    {-# INLINE bit #-}-    {-# INLINE testBit #-}--    (W64# x#) .&.   (W64# y#)  = W64# (x# `and#` y#)-    (W64# x#) .|.   (W64# y#)  = W64# (x# `or#`  y#)-    (W64# x#) `xor` (W64# y#)  = W64# (x# `xor#` y#)-    complement (W64# x#)       = W64# (x# `xor#` mb#)-        where !(W64# mb#) = maxBound-    (W64# x#) `shift` (I# i#)-        | isTrue# (i# >=# 0#)  = W64# (x# `shiftL#` i#)-        | otherwise            = W64# (x# `shiftRL#` negateInt# i#)-    (W64# x#) `shiftL`       (I# i#) = W64# (x# `shiftL#` i#)-    (W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL#` i#)-    (W64# x#) `shiftR`       (I# i#) = W64# (x# `shiftRL#` i#)-    (W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL#` i#)-    (W64# x#) `rotate` (I# i#)-        | isTrue# (i'# ==# 0#) = W64# x#-        | otherwise            = W64# ((x# `uncheckedShiftL#` i'#) `or#`-                                       (x# `uncheckedShiftRL#` (64# -# i'#)))-        where-        !i'# = word2Int# (int2Word# i# `and#` 63##)-    bitSizeMaybe i            = Just (finiteBitSize i)-    bitSize i                 = finiteBitSize i-    isSigned _                = False-    popCount (W64# x#)        = I# (word2Int# (popCnt64# x#))-    bit                       = bitDefault-    testBit                   = testBitDefault--{-# RULES-"fromIntegral/a->Word64" fromIntegral = \x -> case fromIntegral x of W# x# -> W64# x#-"fromIntegral/Word64->a" fromIntegral = \(W64# x#) -> fromIntegral (W# x#)-  #-}--uncheckedShiftL64# :: Word# -> Int# -> Word#-uncheckedShiftL64#  = uncheckedShiftL#--uncheckedShiftRL64# :: Word# -> Int# -> Word#-uncheckedShiftRL64# = uncheckedShiftRL#--#endif--instance FiniteBits Word64 where-    finiteBitSize _ = 64-    countLeadingZeros  (W64# x#) = I# (word2Int# (clz64# x#))-    countTrailingZeros (W64# x#) = I# (word2Int# (ctz64# x#))--instance Show Word64 where-    showsPrec p x = showsPrec p (toInteger x)--instance Real Word64 where-    toRational x = toInteger x % 1--instance Bounded Word64 where-    minBound = 0-    maxBound = 0xFFFFFFFFFFFFFFFF--instance Ix Word64 where-    range (m,n)         = [m..n]-    unsafeIndex (m,_) i = fromIntegral (i - m)-    inRange (m,n) i     = m <= i && i <= n--instance Read Word64 where-    readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]---- | Reverse order of bytes in 'Word64'.------ @since 4.7.0.0-#if WORD_SIZE_IN_BITS < 64-byteSwap64 :: Word64 -> Word64-byteSwap64 (W64# w#) = W64# (byteSwap64# w#)-#else-byteSwap64 :: Word64 -> Word64-byteSwap64 (W64# w#) = W64# (byteSwap# w#)-#endif
− Numeric.hs
@@ -1,231 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash #-}---------------------------------------------------------------------------------- |--- Module      :  Numeric--- Copyright   :  (c) The University of Glasgow 2002--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Odds and ends, mostly functions for reading and showing--- 'RealFloat'-like kind of values.-----------------------------------------------------------------------------------module Numeric (--        -- * Showing--        showSigned,--        showIntAtBase,-        showInt,-        showHex,-        showOct,--        showEFloat,-        showFFloat,-        showGFloat,-        showFFloatAlt,-        showGFloatAlt,-        showFloat,--        floatToDigits,--        -- * Reading--        -- | /NB:/ 'readInt' is the \'dual\' of 'showIntAtBase',-        -- and 'readDec' is the \`dual\' of 'showInt'.-        -- The inconsistent naming is a historical accident.--        readSigned,--        readInt,-        readDec,-        readOct,-        readHex,--        readFloat,--        lexDigits,--        -- * Miscellaneous--        fromRat,--        ) where--import GHC.Base-import GHC.Read-import GHC.Real-import GHC.Float-import GHC.Num-import GHC.Show-import Text.ParserCombinators.ReadP( ReadP, readP_to_S, pfail )-import qualified Text.Read.Lex as L---- -------------------------------------------------------------------------------- Reading---- | Reads an /unsigned/ 'Integral' value in an arbitrary base.-readInt :: Num a-  => a                  -- ^ the base-  -> (Char -> Bool)     -- ^ a predicate distinguishing valid digits in this base-  -> (Char -> Int)      -- ^ a function converting a valid digit character to an 'Int'-  -> ReadS a-readInt base isDigit valDigit = readP_to_S (L.readIntP base isDigit valDigit)---- | Read an unsigned number in octal notation.-readOct :: (Eq a, Num a) => ReadS a-readOct = readP_to_S L.readOctP---- | Read an unsigned number in decimal notation.-readDec :: (Eq a, Num a) => ReadS a-readDec = readP_to_S L.readDecP---- | Read an unsigned number in hexadecimal notation.--- Both upper or lower case letters are allowed.-readHex :: (Eq a, Num a) => ReadS a-readHex = readP_to_S L.readHexP---- | Reads an /unsigned/ 'RealFrac' value,--- expressed in decimal scientific notation.-readFloat :: RealFrac a => ReadS a-readFloat = readP_to_S readFloatP--readFloatP :: RealFrac a => ReadP a-readFloatP =-  do tok <- L.lex-     case tok of-       L.Number n -> return $ fromRational $ L.numberToRational n-       _          -> pfail---- It's turgid to have readSigned work using list comprehensions,--- but it's specified as a ReadS to ReadS transformer--- With a bit of luck no one will use it.---- | Reads a /signed/ 'Real' value, given a reader for an unsigned value.-readSigned :: (Real a) => ReadS a -> ReadS a-readSigned readPos = readParen False read'-                     where read' r  = read'' r ++-                                      (do-                                        ("-",s) <- lex r-                                        (x,t)   <- read'' s-                                        return (-x,t))-                           read'' r = do-                               (str,s) <- lex r-                               (n,"")  <- readPos str-                               return (n,s)---- -------------------------------------------------------------------------------- Showing---- | Show /non-negative/ 'Integral' numbers in base 10.-showInt :: Integral a => a -> ShowS-showInt n0 cs0-    | n0 < 0    = error "Numeric.showInt: can't show negative numbers"-    | otherwise = go n0 cs0-    where-    go n cs-        | n < 10    = case unsafeChr (ord '0' + fromIntegral n) of-            c@(C# _) -> c:cs-        | otherwise = case unsafeChr (ord '0' + fromIntegral r) of-            c@(C# _) -> go q (c:cs)-        where-        (q,r) = n `quotRem` 10---- Controlling the format and precision of floats. The code that--- implements the formatting itself is in @PrelNum@ to avoid--- mutual module deps.--{-# SPECIALIZE showEFloat ::-        Maybe Int -> Float  -> ShowS,-        Maybe Int -> Double -> ShowS #-}-{-# SPECIALIZE showFFloat ::-        Maybe Int -> Float  -> ShowS,-        Maybe Int -> Double -> ShowS #-}-{-# SPECIALIZE showGFloat ::-        Maybe Int -> Float  -> ShowS,-        Maybe Int -> Double -> ShowS #-}---- | Show a signed 'RealFloat' value--- using scientific (exponential) notation (e.g. @2.45e2@, @1.5e-3@).------ In the call @'showEFloat' digs val@, if @digs@ is 'Nothing',--- the value is shown to full precision; if @digs@ is @'Just' d@,--- then at most @d@ digits after the decimal point are shown.-showEFloat    :: (RealFloat a) => Maybe Int -> a -> ShowS---- | Show a signed 'RealFloat' value--- using standard decimal notation (e.g. @245000@, @0.0015@).------ In the call @'showFFloat' digs val@, if @digs@ is 'Nothing',--- the value is shown to full precision; if @digs@ is @'Just' d@,--- then at most @d@ digits after the decimal point are shown.-showFFloat    :: (RealFloat a) => Maybe Int -> a -> ShowS---- | Show a signed 'RealFloat' value--- using standard decimal notation for arguments whose absolute value lies--- between @0.1@ and @9,999,999@, and scientific notation otherwise.------ In the call @'showGFloat' digs val@, if @digs@ is 'Nothing',--- the value is shown to full precision; if @digs@ is @'Just' d@,--- then at most @d@ digits after the decimal point are shown.-showGFloat    :: (RealFloat a) => Maybe Int -> a -> ShowS--showEFloat d x =  showString (formatRealFloat FFExponent d x)-showFFloat d x =  showString (formatRealFloat FFFixed d x)-showGFloat d x =  showString (formatRealFloat FFGeneric d x)---- | Show a signed 'RealFloat' value--- using standard decimal notation (e.g. @245000@, @0.0015@).------ This behaves as 'showFFloat', except that a decimal point--- is always guaranteed, even if not needed.------ @since 4.7.0.0-showFFloatAlt    :: (RealFloat a) => Maybe Int -> a -> ShowS---- | Show a signed 'RealFloat' value--- using standard decimal notation for arguments whose absolute value lies--- between @0.1@ and @9,999,999@, and scientific notation otherwise.------ This behaves as 'showFFloat', except that a decimal point--- is always guaranteed, even if not needed.------ @since 4.7.0.0-showGFloatAlt    :: (RealFloat a) => Maybe Int -> a -> ShowS--showFFloatAlt d x =  showString (formatRealFloatAlt FFFixed d True x)-showGFloatAlt d x =  showString (formatRealFloatAlt FFGeneric d True x)---- ------------------------------------------------------------------------------ Integer printing functions---- | Shows a /non-negative/ 'Integral' number using the base specified by the--- first argument, and the character representation specified by the second.-showIntAtBase :: (Integral a, Show a) => a -> (Int -> Char) -> a -> ShowS-showIntAtBase base toChr n0 r0-  | base <= 1 = error ("Numeric.showIntAtBase: applied to unsupported base " ++ show base)-  | n0 <  0   = error ("Numeric.showIntAtBase: applied to negative number " ++ show n0)-  | otherwise = showIt (quotRem n0 base) r0-   where-    showIt (n,d) r = seq c $ -- stricter than necessary-      case n of-        0 -> r'-        _ -> showIt (quotRem n base) r'-     where-      c  = toChr (fromIntegral d)-      r' = c : r---- | Show /non-negative/ 'Integral' numbers in base 16.-showHex :: (Integral a,Show a) => a -> ShowS-showHex = showIntAtBase 16 intToDigit---- | Show /non-negative/ 'Integral' numbers in base 8.-showOct :: (Integral a, Show a) => a -> ShowS-showOct = showIntAtBase 8  intToDigit
− Numeric/Natural.hs
@@ -1,24 +0,0 @@-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  Numeric.Natural--- Copyright   :  (C) 2014 Herbert Valerio Riedel,---                (C) 2011 Edward Kmett--- License     :  see libraries/base/LICENSE------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ The arbitrary-precision 'Natural' number type.------ @since 4.8.0.0--------------------------------------------------------------------------------module Numeric.Natural-    ( Natural-    ) where--import GHC.Natural
− Prelude.hs
@@ -1,172 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Prelude--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ The Prelude: a standard module. The Prelude is imported by default--- into all Haskell modules unless either there is an explicit import--- statement for it, or the NoImplicitPrelude extension is enabled.-----------------------------------------------------------------------------------module Prelude (--    -- * Standard types, classes and related functions--    -- ** Basic data types-    Bool(False, True),-    (&&), (||), not, otherwise,--    Maybe(Nothing, Just),-    maybe,--    Either(Left, Right),-    either,--    Ordering(LT, EQ, GT),-    Char, String,--    -- *** Tuples-    fst, snd, curry, uncurry,--    -- ** Basic type classes-    Eq((==), (/=)),-    Ord(compare, (<), (<=), (>=), (>), max, min),-    Enum(succ, pred, toEnum, fromEnum, enumFrom, enumFromThen,-         enumFromTo, enumFromThenTo),-    Bounded(minBound, maxBound),--    -- ** Numbers--    -- *** Numeric types-    Int, Integer, Float, Double,-    Rational, Word,--    -- *** Numeric type classes-    Num((+), (-), (*), negate, abs, signum, fromInteger),-    Real(toRational),-    Integral(quot, rem, div, mod, quotRem, divMod, toInteger),-    Fractional((/), recip, fromRational),-    Floating(pi, exp, log, sqrt, (**), logBase, sin, cos, tan,-             asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh),-    RealFrac(properFraction, truncate, round, ceiling, floor),-    RealFloat(floatRadix, floatDigits, floatRange, decodeFloat,-              encodeFloat, exponent, significand, scaleFloat, isNaN,-              isInfinite, isDenormalized, isIEEE, isNegativeZero, atan2),--    -- *** Numeric functions-    subtract, even, odd, gcd, lcm, (^), (^^),-    fromIntegral, realToFrac,--    -- ** Monoids-    Monoid(mempty, mappend, mconcat),--    -- ** Monads and functors-    Functor(fmap, (<$)), (<$>),-    Applicative(pure, (<*>), (*>), (<*)),-    Monad((>>=), (>>), return, fail),-    mapM_, sequence_, (=<<),--    -- ** Folds and traversals-    Foldable(elem,      -- :: (Foldable t, Eq a) => a -> t a -> Bool-             -- fold,   -- :: Monoid m => t m -> m-             foldMap,   -- :: Monoid m => (a -> m) -> t a -> m-             foldr,     -- :: (a -> b -> b) -> b -> t a -> b-             -- foldr', -- :: (a -> b -> b) -> b -> t a -> b-             foldl,     -- :: (b -> a -> b) -> b -> t a -> b-             -- foldl', -- :: (b -> a -> b) -> b -> t a -> b-             foldr1,    -- :: (a -> a -> a) -> t a -> a-             foldl1,    -- :: (a -> a -> a) -> t a -> a-             maximum,   -- :: (Foldable t, Ord a) => t a -> a-             minimum,   -- :: (Foldable t, Ord a) => t a -> a-             product,   -- :: (Foldable t, Num a) => t a -> a-             sum),      -- :: Num a => t a -> a-             -- toList) -- :: Foldable t => t a -> [a]--    Traversable(traverse, sequenceA, mapM, sequence),--    -- ** Miscellaneous functions-    id, const, (.), flip, ($), until,-    asTypeOf, error, undefined,-    seq, ($!),--    -- * List operations-    map, (++), filter,-    head, last, tail, init, null, length, (!!),-    reverse,-    -- *** Special folds-    and, or, any, all,-    concat, concatMap,-    -- ** Building lists-    -- *** Scans-    scanl, scanl1, scanr, scanr1,-    -- *** Infinite lists-    iterate, repeat, replicate, cycle,-    -- ** Sublists-    take, drop, splitAt, takeWhile, dropWhile, span, break,-    -- ** Searching lists-    notElem, lookup,-    -- ** Zipping and unzipping lists-    zip, zip3, zipWith, zipWith3, unzip, unzip3,-    -- ** Functions on strings-    lines, words, unlines, unwords,--    -- * Converting to and from @String@-    -- ** Converting to @String@-    ShowS,-    Show(showsPrec, showList, show),-    shows,-    showChar, showString, showParen,-    -- ** Converting from @String@-    ReadS,-    Read(readsPrec, readList),-    reads, readParen, read, lex,--    -- * Basic Input and output-    IO,-    -- ** Simple I\/O operations-    -- All I/O functions defined here are character oriented.  The-    -- treatment of the newline character will vary on different systems.-    -- For example, two characters of input, return and linefeed, may-    -- read as a single newline character.  These functions cannot be-    -- used portably for binary I/O.-    -- *** Output functions-    putChar,-    putStr, putStrLn, print,-    -- *** Input functions-    getChar,-    getLine, getContents, interact,-    -- *** Files-    FilePath,-    readFile, writeFile, appendFile, readIO, readLn,-    -- ** Exception handling in the I\/O monad-    IOError, ioError, userError,--  ) where--import Control.Monad-import System.IO-import System.IO.Error-import Data.List-import Data.Either-import Data.Foldable    ( Foldable(..) )-import Data.Functor     ( (<$>) )-import Data.Maybe-import Data.Traversable ( Traversable(..) )-import Data.Tuple--import GHC.Base hiding ( foldr, mapM, sequence )-import Text.Read-import GHC.Enum-import GHC.Num-import GHC.Real-import GHC.Float-import GHC.Show
− Setup.hs
@@ -1,6 +0,0 @@-module Main (main) where--import Distribution.Simple--main :: IO ()-main = defaultMainWithHooks autoconfUserHooks
− System/CPUTime.hsc
@@ -1,161 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NondecreasingIndentation, CApiFFI #-}---------------------------------------------------------------------------------- |--- Module      :  System.CPUTime--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ The standard CPUTime library.-----------------------------------------------------------------------------------#include "HsFFI.h"-#include "HsBaseConfig.h"--module System.CPUTime -        (-         getCPUTime,       -- :: IO Integer-         cpuTimePrecision  -- :: Integer-        ) where--import Data.Ratio--import Foreign-import Foreign.C---- For struct rusage-#if !defined(mingw32_HOST_OS) && !defined(irix_HOST_OS)-# if HAVE_SYS_RESOURCE_H-#  include <sys/resource.h>-# endif-#endif---- For FILETIME etc. on Windows-#if HAVE_WINDOWS_H-#include <windows.h>-#endif---- for struct tms-#if HAVE_SYS_TIMES_H-#include <sys/times.h>-#endif--##ifdef mingw32_HOST_OS-## if defined(i386_HOST_ARCH)-##  define WINDOWS_CCONV stdcall-## elif defined(x86_64_HOST_ARCH)-##  define WINDOWS_CCONV ccall-## else-##  error Unknown mingw32 arch-## endif-##else-##endif--#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS)-realToInteger :: Real a => a -> Integer-realToInteger ct = round (realToFrac ct :: Double)-  -- CTime, CClock, CUShort etc are in Real but not Fractional, -  -- so we must convert to Double before we can round it-#endif---- -------------------------------------------------------------------------------- |Computation 'getCPUTime' returns the number of picoseconds CPU time--- used by the current program.  The precision of this result is--- implementation-dependent.--getCPUTime :: IO Integer-getCPUTime = do--#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS)--- getrusage() is right royal pain to deal with when targetting multiple--- versions of Solaris, since some versions supply it in libc (2.3 and 2.5),--- while 2.4 has got it in libucb (I wouldn't be too surprised if it was back--- again in libucb in 2.6..)------ Avoid the problem by resorting to times() instead.----#if defined(HAVE_GETRUSAGE) && ! irix_HOST_OS && ! solaris2_HOST_OS-    allocaBytes (#const sizeof(struct rusage)) $ \ p_rusage -> do-    throwErrnoIfMinus1_ "getrusage" $ getrusage (#const RUSAGE_SELF) p_rusage--    let ru_utime = (#ptr struct rusage, ru_utime) p_rusage-    let ru_stime = (#ptr struct rusage, ru_stime) p_rusage-    u_sec  <- (#peek struct timeval,tv_sec)  ru_utime :: IO CTime-    u_usec <- (#peek struct timeval,tv_usec) ru_utime :: IO CSUSeconds-    s_sec  <- (#peek struct timeval,tv_sec)  ru_stime :: IO CTime-    s_usec <- (#peek struct timeval,tv_usec) ru_stime :: IO CSUSeconds-    return ((realToInteger u_sec * 1000000 + realToInteger u_usec + -             realToInteger s_sec * 1000000 + realToInteger s_usec) -                * 1000000)--type CRUsage = ()-foreign import capi unsafe "HsBase.h getrusage" getrusage :: CInt -> Ptr CRUsage -> IO CInt-#elif defined(HAVE_TIMES)-    allocaBytes (#const sizeof(struct tms)) $ \ p_tms -> do-    _ <- times p_tms-    u_ticks  <- (#peek struct tms,tms_utime) p_tms :: IO CClock-    s_ticks  <- (#peek struct tms,tms_stime) p_tms :: IO CClock-    return (( (realToInteger u_ticks + realToInteger s_ticks) * 1000000000000) -                        `div` fromIntegral clockTicks)--type CTms = ()-foreign import ccall unsafe times :: Ptr CTms -> IO CClock-#else-    ioException (IOError Nothing UnsupportedOperation -                         "getCPUTime"-                         "can't get CPU time"-                         Nothing)-#endif--#else /* win32 */-     -- NOTE: GetProcessTimes() is only supported on NT-based OSes.-     -- The counts reported by GetProcessTimes() are in 100-ns (10^-7) units.-    allocaBytes (#const sizeof(FILETIME)) $ \ p_creationTime -> do-    allocaBytes (#const sizeof(FILETIME)) $ \ p_exitTime -> do-    allocaBytes (#const sizeof(FILETIME)) $ \ p_kernelTime -> do-    allocaBytes (#const sizeof(FILETIME)) $ \ p_userTime -> do-    pid <- getCurrentProcess-    ok <- getProcessTimes pid p_creationTime p_exitTime p_kernelTime p_userTime-    if toBool ok then do-      ut <- ft2psecs p_userTime-      kt <- ft2psecs p_kernelTime-      return (ut + kt)-     else return 0-  where -        ft2psecs :: Ptr FILETIME -> IO Integer-        ft2psecs ft = do-          high <- (#peek FILETIME,dwHighDateTime) ft :: IO Word32-          low  <- (#peek FILETIME,dwLowDateTime)  ft :: IO Word32-            -- Convert 100-ns units to picosecs (10^-12) -            -- => multiply by 10^5.-          return (((fromIntegral high) * (2^(32::Int)) + (fromIntegral low)) * 100000)--    -- ToDo: pin down elapsed times to just the OS thread(s) that-    -- are evaluating/managing Haskell code.--type FILETIME = ()-type HANDLE = ()--- need proper Haskell names (initial lower-case character)-foreign import WINDOWS_CCONV unsafe "GetCurrentProcess" getCurrentProcess :: IO (Ptr HANDLE)-foreign import WINDOWS_CCONV unsafe "GetProcessTimes" getProcessTimes :: Ptr HANDLE -> Ptr FILETIME -> Ptr FILETIME -> Ptr FILETIME -> Ptr FILETIME -> IO CInt--#endif /* not _WIN32 */----- |The 'cpuTimePrecision' constant is the smallest measurable difference--- in CPU time that the implementation can record, and is given as an--- integral number of picoseconds.--cpuTimePrecision :: Integer-cpuTimePrecision = round ((1000000000000::Integer) % fromIntegral (clockTicks))--foreign import ccall unsafe clk_tck :: CLong--clockTicks :: Int-clockTicks = fromIntegral clk_tck
− System/Console/GetOpt.hs
@@ -1,407 +0,0 @@-{-# LANGUAGE Safe #-}---------------------------------------------------------------------------------- |--- Module      :  System.Console.GetOpt--- Copyright   :  (c) Sven Panne 2002-2005--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ This library provides facilities for parsing the command-line options--- in a standalone program.  It is essentially a Haskell port of the GNU --- @getopt@ library.-----------------------------------------------------------------------------------{--Sven Panne <Sven.Panne@informatik.uni-muenchen.de> Oct. 1996 (small-changes Dec. 1997)--Two rather obscure features are missing: The Bash 2.0 non-option hack-(if you don't already know it, you probably don't want to hear about-it...) and the recognition of long options with a single dash-(e.g. '-help' is recognised as '--help', as long as there is no short-option 'h').--Other differences between GNU's getopt and this implementation:--* To enforce a coherent description of options and arguments, there-  are explanation fields in the option/argument descriptor.--* Error messages are now more informative, but no longer POSIX-  compliant... :-(--And a final Haskell advertisement: The GNU C implementation uses well-over 1100 lines, we need only 195 here, including a 46 line example! -:-)--}--module System.Console.GetOpt (-   -- * GetOpt-   getOpt, getOpt',-   usageInfo,-   ArgOrder(..),-   OptDescr(..),-   ArgDescr(..),--   -- * Examples--   -- |To hopefully illuminate the role of the different data structures,-   -- here are the command-line options for a (very simple) compiler,-   -- done in two different ways.-   -- The difference arises because the type of 'getOpt' is-   -- parameterized by the type of values derived from flags.--   -- ** Interpreting flags as concrete values-   -- $example1--   -- ** Interpreting flags as transformations of an options record-   -- $example2-) where--import Data.List ( isPrefixOf, find )---- |What to do with options following non-options-data ArgOrder a-  = RequireOrder                -- ^ no option processing after first non-option-  | Permute                     -- ^ freely intersperse options and non-options-  | ReturnInOrder (String -> a) -- ^ wrap non-options into options--{-|-Each 'OptDescr' describes a single option.--The arguments to 'Option' are:--* list of short option characters--* list of long option strings (without \"--\")--* argument descriptor--* explanation of option for user--}-data OptDescr a =              -- description of a single options:-   Option [Char]                --    list of short option characters-          [String]              --    list of long option strings (without "--")-          (ArgDescr a)          --    argument descriptor-          String                --    explanation of option for user---- |Describes whether an option takes an argument or not, and if so--- how the argument is injected into a value of type @a@.-data ArgDescr a-   = NoArg                   a         -- ^   no argument expected-   | ReqArg (String       -> a) String -- ^   option requires argument-   | OptArg (Maybe String -> a) String -- ^   optional argument--instance Functor ArgOrder where-    fmap _ RequireOrder      = RequireOrder-    fmap _ Permute           = Permute-    fmap f (ReturnInOrder g) = ReturnInOrder (f . g)--instance Functor OptDescr where-    fmap f (Option a b argDescr c) = Option a b (fmap f argDescr) c--instance Functor ArgDescr where-    fmap f (NoArg a)    = NoArg (f a)-    fmap f (ReqArg g s) = ReqArg (f . g) s-    fmap f (OptArg g s) = OptArg (f . g) s--data OptKind a                -- kind of cmd line arg (internal use only):-   = Opt       a                --    an option-   | UnreqOpt  String           --    an un-recognized option-   | NonOpt    String           --    a non-option-   | EndOfOpts                  --    end-of-options marker (i.e. "--")-   | OptErr    String           --    something went wrong...---- | Return a string describing the usage of a command, derived from--- the header (first argument) and the options described by the --- second argument.-usageInfo :: String                    -- header-          -> [OptDescr a]              -- option descriptors-          -> String                    -- nicely formatted decription of options-usageInfo header optDescr = unlines (header:table)-   where (ss,ls,ds)     = (unzip3 . concatMap fmtOpt) optDescr-         table          = zipWith3 paste (sameLen ss) (sameLen ls) ds-         paste x y z    = "  " ++ x ++ "  " ++ y ++ "  " ++ z-         sameLen xs     = flushLeft ((maximum . map length) xs) xs-         flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]--fmtOpt :: OptDescr a -> [(String,String,String)]-fmtOpt (Option sos los ad descr) =-   case lines descr of-     []     -> [(sosFmt,losFmt,"")]-     (d:ds) ->  (sosFmt,losFmt,d) : [ ("","",d') | d' <- ds ]-   where sepBy _  []     = ""-         sepBy _  [x]    = x-         sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs-         sosFmt = sepBy ',' (map (fmtShort ad) sos)-         losFmt = sepBy ',' (map (fmtLong  ad) los)--fmtShort :: ArgDescr a -> Char -> String-fmtShort (NoArg  _   ) so = "-" ++ [so]-fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad-fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"--fmtLong :: ArgDescr a -> String -> String-fmtLong (NoArg  _   ) lo = "--" ++ lo-fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad-fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"--{-|-Process the command-line, and return the list of values that matched-(and those that didn\'t). The arguments are:--* The order requirements (see 'ArgOrder')--* The option descriptions (see 'OptDescr')--* The actual command line arguments (presumably got from -  'System.Environment.getArgs').--'getOpt' returns a triple consisting of the option arguments, a list-of non-options, and a list of error messages.--}-getOpt :: ArgOrder a                   -- non-option handling-       -> [OptDescr a]                 -- option descriptors-       -> [String]                     -- the command-line arguments-       -> ([a],[String],[String])      -- (options,non-options,error messages)-getOpt ordering optDescr args = (os,xs,es ++ map errUnrec us)-   where (os,xs,us,es) = getOpt' ordering optDescr args--{-|-This is almost the same as 'getOpt', but returns a quadruple-consisting of the option arguments, a list of non-options, a list of-unrecognized options, and a list of error messages.--}-getOpt' :: ArgOrder a                         -- non-option handling-        -> [OptDescr a]                       -- option descriptors-        -> [String]                           -- the command-line arguments-        -> ([a],[String], [String] ,[String]) -- (options,non-options,unrecognized,error messages)-getOpt' _        _        []         =  ([],[],[],[])-getOpt' ordering optDescr (arg:args) = procNextOpt opt ordering-   where procNextOpt (Opt o)      _                 = (o:os,xs,us,es)-         procNextOpt (UnreqOpt u) _                 = (os,xs,u:us,es)-         procNextOpt (NonOpt x)   RequireOrder      = ([],x:rest,[],[])-         procNextOpt (NonOpt x)   Permute           = (os,x:xs,us,es)-         procNextOpt (NonOpt x)   (ReturnInOrder f) = (f x :os, xs,us,es)-         procNextOpt EndOfOpts    RequireOrder      = ([],rest,[],[])-         procNextOpt EndOfOpts    Permute           = ([],rest,[],[])-         procNextOpt EndOfOpts    (ReturnInOrder f) = (map f rest,[],[],[])-         procNextOpt (OptErr e)   _                 = (os,xs,us,e:es)--         (opt,rest) = getNext arg args optDescr-         (os,xs,us,es) = getOpt' ordering optDescr rest---- take a look at the next cmd line arg and decide what to do with it-getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])-getNext ('-':'-':[]) rest _        = (EndOfOpts,rest)-getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr-getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr-getNext a            rest _        = (NonOpt a,rest)---- handle long option-longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])-longOpt ls rs optDescr = long ads arg rs-   where (opt,arg) = break (=='=') ls-         getWith p = [ o | o@(Option _ xs _ _) <- optDescr-                         , find (p opt) xs /= Nothing ]-         exact     = getWith (==)-         options   = if null exact then getWith isPrefixOf else exact-         ads       = [ ad | Option _ _ ad _ <- options ]-         optStr    = ("--"++opt)--         long (_:_:_)      _        rest     = (errAmbig options optStr,rest)-         long [NoArg  a  ] []       rest     = (Opt a,rest)-         long [NoArg  _  ] ('=':_)  rest     = (errNoArg optStr,rest)-         long [ReqArg _ d] []       []       = (errReq d optStr,[])-         long [ReqArg f _] []       (r:rest) = (Opt (f r),rest)-         long [ReqArg f _] ('=':xs) rest     = (Opt (f xs),rest)-         long [OptArg f _] []       rest     = (Opt (f Nothing),rest)-         long [OptArg f _] ('=':xs) rest     = (Opt (f (Just xs)),rest)-         long _            _        rest     = (UnreqOpt ("--"++ls),rest)---- handle short option-shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])-shortOpt y ys rs optDescr = short ads ys rs-  where options = [ o  | o@(Option ss _ _ _) <- optDescr, s <- ss, y == s ]-        ads     = [ ad | Option _ _ ad _ <- options ]-        optStr  = '-':[y]--        short (_:_:_)        _  rest     = (errAmbig options optStr,rest)-        short (NoArg  a  :_) [] rest     = (Opt a,rest)-        short (NoArg  a  :_) xs rest     = (Opt a,('-':xs):rest)-        short (ReqArg _ d:_) [] []       = (errReq d optStr,[])-        short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)-        short (ReqArg f _:_) xs rest     = (Opt (f xs),rest)-        short (OptArg f _:_) [] rest     = (Opt (f Nothing),rest)-        short (OptArg f _:_) xs rest     = (Opt (f (Just xs)),rest)-        short []             [] rest     = (UnreqOpt optStr,rest)-        short []             xs rest     = (UnreqOpt optStr,('-':xs):rest)---- miscellaneous error formatting--errAmbig :: [OptDescr a] -> String -> OptKind a-errAmbig ods optStr = OptErr (usageInfo header ods)-   where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"--errReq :: String -> String -> OptKind a-errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")--errUnrec :: String -> String-errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n"--errNoArg :: String -> OptKind a-errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")--{---------------------------------------------------------------------------------------------- and here a small and hopefully enlightening example:--data Flag = Verbose | Version | Name String | Output String | Arg String   deriving Show--options :: [OptDescr Flag]-options =-   [Option ['v']     ["verbose"]           (NoArg Verbose)      "verbosely list files",-    Option ['V','?'] ["version","release"] (NoArg Version)      "show version info",-    Option ['o']     ["output"]            (OptArg out "FILE")  "use FILE for dump",-    Option ['n']     ["name"]              (ReqArg Name "USER") "only dump USER's files"]--out :: Maybe String -> Flag-out Nothing  = Output "stdout"-out (Just o) = Output o--test :: ArgOrder Flag -> [String] -> String-test order cmdline = case getOpt order options cmdline of-                        (o,n,[]  ) -> "options=" ++ show o ++ "  args=" ++ show n ++ "\n"-                        (_,_,errs) -> concat errs ++ usageInfo header options-   where header = "Usage: foobar [OPTION...] files..."---- example runs:--- putStr (test RequireOrder ["foo","-v"])---    ==> options=[]  args=["foo", "-v"]--- putStr (test Permute ["foo","-v"])---    ==> options=[Verbose]  args=["foo"]--- putStr (test (ReturnInOrder Arg) ["foo","-v"])---    ==> options=[Arg "foo", Verbose]  args=[]--- putStr (test Permute ["foo","--","-v"])---    ==> options=[]  args=["foo", "-v"]--- putStr (test Permute ["-?o","--name","bar","--na=baz"])---    ==> options=[Version, Output "stdout", Name "bar", Name "baz"]  args=[]--- putStr (test Permute ["--ver","foo"])---    ==> option `--ver' is ambiguous; could be one of:---          -v      --verbose             verbosely list files---          -V, -?  --version, --release  show version info   ---        Usage: foobar [OPTION...] files...---          -v        --verbose             verbosely list files  ---          -V, -?    --version, --release  show version info     ---          -o[FILE]  --output[=FILE]       use FILE for dump     ---          -n USER   --name=USER           only dump USER's files--------------------------------------------------------------------------------------------}--{- $example1--A simple choice for the type associated with flags is to define a type-@Flag@ as an algebraic type representing the possible flags and their-arguments:-->    module Opts1 where->    ->    import System.Console.GetOpt->    import Data.Maybe ( fromMaybe )->    ->    data Flag ->     = Verbose  | Version ->     | Input String | Output String | LibDir String->       deriving Show->    ->    options :: [OptDescr Flag]->    options =->     [ Option ['v']     ["verbose"] (NoArg Verbose)       "chatty output on stderr"->     , Option ['V','?'] ["version"] (NoArg Version)       "show version number"->     , Option ['o']     ["output"]  (OptArg outp "FILE")  "output FILE"->     , Option ['c']     []          (OptArg inp  "FILE")  "input FILE"->     , Option ['L']     ["libdir"]  (ReqArg LibDir "DIR") "library directory"->     ]->    ->    inp,outp :: Maybe String -> Flag->    outp = Output . fromMaybe "stdout"->    inp  = Input  . fromMaybe "stdin"->    ->    compilerOpts :: [String] -> IO ([Flag], [String])->    compilerOpts argv = ->       case getOpt Permute options argv of->          (o,n,[]  ) -> return (o,n)->          (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))->      where header = "Usage: ic [OPTION...] files..."--Then the rest of the program will use the constructed list of flags-to determine it\'s behaviour.---}--{- $example2--A different approach is to group the option values in a record of type-@Options@, and have each flag yield a function of type-@Options -> Options@ transforming this record.-->    module Opts2 where->->    import System.Console.GetOpt->    import Data.Maybe ( fromMaybe )->->    data Options = Options->     { optVerbose     :: Bool->     , optShowVersion :: Bool->     , optOutput      :: Maybe FilePath->     , optInput       :: Maybe FilePath->     , optLibDirs     :: [FilePath]->     } deriving Show->->    defaultOptions    = Options->     { optVerbose     = False->     , optShowVersion = False->     , optOutput      = Nothing->     , optInput       = Nothing->     , optLibDirs     = []->     }->->    options :: [OptDescr (Options -> Options)]->    options =->     [ Option ['v']     ["verbose"]->         (NoArg (\ opts -> opts { optVerbose = True }))->         "chatty output on stderr"->     , Option ['V','?'] ["version"]->         (NoArg (\ opts -> opts { optShowVersion = True }))->         "show version number"->     , Option ['o']     ["output"]->         (OptArg ((\ f opts -> opts { optOutput = Just f }) . fromMaybe "output")->                 "FILE")->         "output FILE"->     , Option ['c']     []->         (OptArg ((\ f opts -> opts { optInput = Just f }) . fromMaybe "input")->                 "FILE")->         "input FILE"->     , Option ['L']     ["libdir"]->         (ReqArg (\ d opts -> opts { optLibDirs = optLibDirs opts ++ [d] }) "DIR")->         "library directory"->     ]->->    compilerOpts :: [String] -> IO (Options, [String])->    compilerOpts argv =->       case getOpt Permute options argv of->          (o,n,[]  ) -> return (foldl (flip id) defaultOptions o, n)->          (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))->      where header = "Usage: ic [OPTION...] files..."--Similarly, each flag could yield a monadic function transforming a record,-of type @Options -> IO Options@ (or any other monad), allowing option-processing to perform actions of the chosen monad, e.g. printing help or-version messages, checking that file arguments exist, etc.---}-
− System/Environment.hs
@@ -1,449 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE CPP #-}---------------------------------------------------------------------------------- |--- Module      :  System.Environment--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Miscellaneous information about the system environment.-----------------------------------------------------------------------------------module System.Environment-    (-      getArgs,-      getProgName,-      getExecutablePath,-      getEnv,-      lookupEnv,-      setEnv,-      unsetEnv,-      withArgs,-      withProgName,-      getEnvironment,-  ) where--import Foreign-import Foreign.C-import System.IO.Error (mkIOError)-import Control.Exception.Base (bracket, throwIO)--- import GHC.IO-import GHC.IO.Exception-import GHC.IO.Encoding (getFileSystemEncoding)-import qualified GHC.Foreign as GHC-import Data.List-import Control.Monad-#ifdef mingw32_HOST_OS-import GHC.Environment-import GHC.Windows-#else-import System.Posix.Internals (withFilePath)-#endif--import System.Environment.ExecutablePath--#ifdef mingw32_HOST_OS-# if defined(i386_HOST_ARCH)-#  define WINDOWS_CCONV stdcall-# elif defined(x86_64_HOST_ARCH)-#  define WINDOWS_CCONV ccall-# else-#  error Unknown mingw32 arch-# endif-#endif--#include "HsBaseConfig.h"---- ------------------------------------------------------------------------------ getArgs, getProgName, getEnv--#ifdef mingw32_HOST_OS---- Ignore the arguments to hs_init on Windows for the sake of Unicode compat--getWin32ProgArgv_certainly :: IO [String]-getWin32ProgArgv_certainly = do-        mb_argv <- getWin32ProgArgv-        case mb_argv of-          Nothing   -> fmap dropRTSArgs getFullArgs-          Just argv -> return argv--withWin32ProgArgv :: [String] -> IO a -> IO a-withWin32ProgArgv argv act = bracket begin setWin32ProgArgv (\_ -> act)-  where-    begin = do-          mb_old_argv <- getWin32ProgArgv-          setWin32ProgArgv (Just argv)-          return mb_old_argv--getWin32ProgArgv :: IO (Maybe [String])-getWin32ProgArgv = alloca $ \p_argc -> alloca $ \p_argv -> do-        c_getWin32ProgArgv p_argc p_argv-        argc <- peek p_argc-        argv_p <- peek p_argv-        if argv_p == nullPtr-         then return Nothing-         else do-          argv_ps <- peekArray (fromIntegral argc) argv_p-          fmap Just $ mapM peekCWString argv_ps--setWin32ProgArgv :: Maybe [String] -> IO ()-setWin32ProgArgv Nothing = c_setWin32ProgArgv 0 nullPtr-setWin32ProgArgv (Just argv) = withMany withCWString argv $ \argv_ps -> withArrayLen argv_ps $ \argc argv_p -> do-        c_setWin32ProgArgv (fromIntegral argc) argv_p--foreign import ccall unsafe "getWin32ProgArgv"-  c_getWin32ProgArgv :: Ptr CInt -> Ptr (Ptr CWString) -> IO ()--foreign import ccall unsafe "setWin32ProgArgv"-  c_setWin32ProgArgv :: CInt -> Ptr CWString -> IO ()--dropRTSArgs :: [String] -> [String]-dropRTSArgs []             = []-dropRTSArgs ("+RTS":rest)  = dropRTSArgs (dropWhile (/= "-RTS") rest)-dropRTSArgs ("--RTS":rest) = rest-dropRTSArgs ("-RTS":rest)  = dropRTSArgs rest-dropRTSArgs (arg:rest)     = arg : dropRTSArgs rest--#endif---- | Computation 'getArgs' returns a list of the program's command--- line arguments (not including the program name).-getArgs :: IO [String]--#ifdef mingw32_HOST_OS-getArgs =  fmap tail getWin32ProgArgv_certainly-#else-getArgs =-  alloca $ \ p_argc ->-  alloca $ \ p_argv -> do-   getProgArgv p_argc p_argv-   p    <- fromIntegral `liftM` peek p_argc-   argv <- peek p_argv-   enc <- getFileSystemEncoding-   peekArray (p - 1) (advancePtr argv 1) >>= mapM (GHC.peekCString enc)--foreign import ccall unsafe "getProgArgv"-  getProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()-#endif--{-|-Computation 'getProgName' returns the name of the program as it was-invoked.--However, this is hard-to-impossible to implement on some non-Unix-OSes, so instead, for maximum portability, we just return the leafname-of the program as invoked. Even then there are some differences-between platforms: on Windows, for example, a program invoked as foo-is probably really @FOO.EXE@, and that is what 'getProgName' will return.--}-getProgName :: IO String-#ifdef mingw32_HOST_OS--- Ignore the arguments to hs_init on Windows for the sake of Unicode compat-getProgName = fmap (basename . head) getWin32ProgArgv_certainly-#else-getProgName =-  alloca $ \ p_argc ->-  alloca $ \ p_argv -> do-     getProgArgv p_argc p_argv-     argv <- peek p_argv-     unpackProgName argv--unpackProgName  :: Ptr (Ptr CChar) -> IO String   -- argv[0]-unpackProgName argv = do-  enc <- getFileSystemEncoding-  s <- peekElemOff argv 0 >>= GHC.peekCString enc-  return (basename s)-#endif--basename :: FilePath -> FilePath-basename f = go f f- where-  go acc [] = acc-  go acc (x:xs)-    | isPathSeparator x = go xs xs-    | otherwise         = go acc xs--  isPathSeparator :: Char -> Bool-  isPathSeparator '/'  = True-#ifdef mingw32_HOST_OS-  isPathSeparator '\\' = True-#endif-  isPathSeparator _    = False----- | Computation 'getEnv' @var@ returns the value--- of the environment variable @var@. For the inverse, POSIX users--- can use 'System.Posix.Env.putEnv'.------ This computation may fail with:------  * 'System.IO.Error.isDoesNotExistError' if the environment variable---    does not exist.--getEnv :: String -> IO String-getEnv name = lookupEnv name >>= maybe handleError return-  where-#ifdef mingw32_HOST_OS-    handleError = do-        err <- c_GetLastError-        if err == eRROR_ENVVAR_NOT_FOUND-            then ioe_missingEnvVar name-            else throwGetLastError "getEnv"--eRROR_ENVVAR_NOT_FOUND :: DWORD-eRROR_ENVVAR_NOT_FOUND = 203--foreign import WINDOWS_CCONV unsafe "windows.h GetLastError"-  c_GetLastError:: IO DWORD--#else-    handleError = ioe_missingEnvVar name-#endif---- | Return the value of the environment variable @var@, or @Nothing@ if--- there is no such value.------ For POSIX users, this is equivalent to 'System.Posix.Env.getEnv'.------ @since 4.6.0.0-lookupEnv :: String -> IO (Maybe String)-#ifdef mingw32_HOST_OS-lookupEnv name = withCWString name $ \s -> try_size s 256-  where-    try_size s size = allocaArray (fromIntegral size) $ \p_value -> do-      res <- c_GetEnvironmentVariable s p_value size-      case res of-        0 -> return Nothing-        _ | res > size -> try_size s res -- Rare: size increased between calls to GetEnvironmentVariable-          | otherwise  -> peekCWString p_value >>= return . Just--foreign import WINDOWS_CCONV unsafe "windows.h GetEnvironmentVariableW"-  c_GetEnvironmentVariable :: LPWSTR -> LPWSTR -> DWORD -> IO DWORD-#else-lookupEnv name =-    withCString name $ \s -> do-      litstring <- c_getenv s-      if litstring /= nullPtr-        then do enc <- getFileSystemEncoding-                result <- GHC.peekCString enc litstring-                return $ Just result-        else return Nothing--foreign import ccall unsafe "getenv"-   c_getenv :: CString -> IO (Ptr CChar)-#endif--ioe_missingEnvVar :: String -> IO a-ioe_missingEnvVar name = ioException (IOError Nothing NoSuchThing "getEnv"-    "no environment variable" Nothing (Just name))---- | @setEnv name value@ sets the specified environment variable to @value@.------ On Windows setting an environment variable to the /empty string/ removes--- that environment variable from the environment.  For the sake of--- compatibility we adopt that behavior.  In particular------ @--- setEnv name \"\"--- @------ has the same effect as------ @--- `unsetEnv` name--- @------ If you don't care about Windows support and want to set an environment--- variable to the empty string use @System.Posix.Env.setEnv@ from the @unix@--- package instead.------ Throws `Control.Exception.IOException` if @name@ is the empty string or--- contains an equals sign.------ @since 4.7.0.0-setEnv :: String -> String -> IO ()-setEnv key_ value_-  | null key       = throwIO (mkIOError InvalidArgument "setEnv" Nothing Nothing)-  | '=' `elem` key = throwIO (mkIOError InvalidArgument "setEnv" Nothing Nothing)-  | null value     = unsetEnv key-  | otherwise      = setEnv_ key value-  where-    key   = takeWhile (/= '\NUL') key_-    value = takeWhile (/= '\NUL') value_--setEnv_ :: String -> String -> IO ()-#ifdef mingw32_HOST_OS-setEnv_ key value = withCWString key $ \k -> withCWString value $ \v -> do-  success <- c_SetEnvironmentVariable k v-  unless success (throwGetLastError "setEnv")--foreign import WINDOWS_CCONV unsafe "windows.h SetEnvironmentVariableW"-  c_SetEnvironmentVariable :: LPTSTR -> LPTSTR -> IO Bool-#else---- NOTE: The 'setenv()' function is not available on all systems, hence we use--- 'putenv()'.  This leaks memory, but so do common implementations of--- 'setenv()' (AFAIK).-setEnv_ k v = putEnv (k ++ "=" ++ v)--putEnv :: String -> IO ()-putEnv keyvalue = do-  s <- getFileSystemEncoding >>= (`GHC.newCString` keyvalue)-  -- IMPORTANT: Do not free `s` after calling putenv!-  ---  -- According to SUSv2, the string passed to putenv becomes part of the-  -- enviroment.-  throwErrnoIf_ (/= 0) "putenv" (c_putenv s)--foreign import ccall unsafe "putenv" c_putenv :: CString -> IO CInt-#endif---- | @unSet name@ removes the specified environment variable from the--- environment of the current process.------ Throws `Control.Exception.IOException` if @name@ is the empty string or--- contains an equals sign.------ @since 4.7.0.0-unsetEnv :: String -> IO ()-#ifdef mingw32_HOST_OS-unsetEnv key = withCWString key $ \k -> do-  success <- c_SetEnvironmentVariable k nullPtr-  unless success $ do-    -- We consider unsetting an environment variable that does not exist not as-    -- an error, hence we ignore eRROR_ENVVAR_NOT_FOUND.-    err <- c_GetLastError-    unless (err == eRROR_ENVVAR_NOT_FOUND) $ do-      throwGetLastError "unsetEnv"-#else--#ifdef HAVE_UNSETENV-unsetEnv key = withFilePath key (throwErrnoIf_ (/= 0) "unsetEnv" . c_unsetenv)-foreign import ccall unsafe "__hsbase_unsetenv" c_unsetenv :: CString -> IO CInt-#else-unsetEnv key = setEnv_ key ""-#endif--#endif--{-|-'withArgs' @args act@ - while executing action @act@, have 'getArgs'-return @args@.--}-withArgs :: [String] -> IO a -> IO a-withArgs xs act = do-   p <- System.Environment.getProgName-   withArgv (p:xs) act--{-|-'withProgName' @name act@ - while executing action @act@,-have 'getProgName' return @name@.--}-withProgName :: String -> IO a -> IO a-withProgName nm act = do-   xs <- System.Environment.getArgs-   withArgv (nm:xs) act---- Worker routine which marshals and replaces an argv vector for--- the duration of an action.--withArgv :: [String] -> IO a -> IO a--#ifdef mingw32_HOST_OS--- We have to reflect the updated arguments in the RTS-side variables as--- well, because the RTS still consults them for error messages and the like.--- If we don't do this then ghc-e005 fails.-withArgv new_args act = withWin32ProgArgv new_args $ withProgArgv new_args act-#else-withArgv = withProgArgv-#endif--withProgArgv :: [String] -> IO a -> IO a-withProgArgv new_args act = do-  pName <- System.Environment.getProgName-  existing_args <- System.Environment.getArgs-  bracket (setProgArgv new_args)-          (\argv -> do _ <- setProgArgv (pName:existing_args)-                       freeProgArgv argv)-          (const act)--freeProgArgv :: Ptr CString -> IO ()-freeProgArgv argv = do-  size <- lengthArray0 nullPtr argv-  sequence_ [ peek (argv `advancePtr` i) >>= free-            | i <- [size - 1, size - 2 .. 0]]-  free argv--setProgArgv :: [String] -> IO (Ptr CString)-setProgArgv argv = do-  enc <- getFileSystemEncoding-  vs <- mapM (GHC.newCString enc) argv >>= newArray0 nullPtr-  c_setProgArgv (genericLength argv) vs-  return vs--foreign import ccall unsafe "setProgArgv"-  c_setProgArgv  :: CInt -> Ptr CString -> IO ()---- |'getEnvironment' retrieves the entire environment as a--- list of @(key,value)@ pairs.------ If an environment entry does not contain an @\'=\'@ character,--- the @key@ is the whole entry and the @value@ is the empty string.-getEnvironment :: IO [(String, String)]--#ifdef mingw32_HOST_OS-getEnvironment = bracket c_GetEnvironmentStrings c_FreeEnvironmentStrings $ \pBlock ->-    if pBlock == nullPtr then return []-     else go pBlock-  where-    go pBlock = do-        -- The block is terminated by a null byte where there-        -- should be an environment variable of the form X=Y-        c <- peek pBlock-        if c == 0 then return []-         else do-          -- Seek the next pair (or terminating null):-          pBlock' <- seekNull pBlock False-          -- We now know the length in bytes, but ignore it when-          -- getting the actual String:-          str <- peekCWString pBlock-          fmap (divvy str :) $ go pBlock'--    -- Returns pointer to the byte *after* the next null-    seekNull pBlock done = do-        let pBlock' = pBlock `plusPtr` sizeOf (undefined :: CWchar)-        if done then return pBlock'-         else do-           c <- peek pBlock'-           seekNull pBlock' (c == (0 :: Word8 ))--foreign import WINDOWS_CCONV unsafe "windows.h GetEnvironmentStringsW"-  c_GetEnvironmentStrings :: IO (Ptr CWchar)--foreign import WINDOWS_CCONV unsafe "windows.h FreeEnvironmentStringsW"-  c_FreeEnvironmentStrings :: Ptr CWchar -> IO Bool-#else-getEnvironment = do-   pBlock <- getEnvBlock-   if pBlock == nullPtr then return []-    else do-      enc <- getFileSystemEncoding-      stuff <- peekArray0 nullPtr pBlock >>= mapM (GHC.peekCString enc)-      return (map divvy stuff)--foreign import ccall unsafe "__hscore_environ"-  getEnvBlock :: IO (Ptr CString)-#endif--divvy :: String -> (String, String)-divvy str =-  case break (=='=') str of-    (xs,[])        -> (xs,[]) -- don't barf (like Posix.getEnvironment)-    (name,_:value) -> (name,value)
− System/Environment/ExecutablePath.hsc
@@ -1,175 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE CPP #-}---------------------------------------------------------------------------------- |--- Module      :  System.Environment.ExecutablePath--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Function to retrieve the absolute filepath of the current executable.------ @since 4.6.0.0--------------------------------------------------------------------------------module System.Environment.ExecutablePath ( getExecutablePath ) where---- The imports are purposely kept completely disjoint to prevent edits--- to one OS implementation from breaking another.--#if defined(darwin_HOST_OS)-import Data.Word-import Foreign.C-import Foreign.Marshal.Alloc-import Foreign.Ptr-import Foreign.Storable-import System.Posix.Internals-#elif defined(linux_HOST_OS)-import Foreign.C-import Foreign.Marshal.Array-import System.Posix.Internals-#elif defined(mingw32_HOST_OS)-import Data.Word-import Foreign.C-import Foreign.Marshal.Array-import Foreign.Ptr-import System.Posix.Internals-#else-import Foreign.C-import Foreign.Marshal.Alloc-import Foreign.Ptr-import Foreign.Storable-import System.Posix.Internals-#endif---- The exported function is defined outside any if-guard to make sure--- every OS implements it with the same type.---- | Returns the absolute pathname of the current executable.------ Note that for scripts and interactive sessions, this is the path to--- the interpreter (e.g. ghci.)------ @since 4.6.0.0-getExecutablePath :: IO FilePath------------------------------------------------------------------------------------- Mac OS X--#if defined(darwin_HOST_OS)--type UInt32 = Word32--foreign import ccall unsafe "mach-o/dyld.h _NSGetExecutablePath"-    c__NSGetExecutablePath :: CString -> Ptr UInt32 -> IO CInt---- | Returns the path of the main executable. The path may be a--- symbolic link and not the real file.------ See dyld(3)-_NSGetExecutablePath :: IO FilePath-_NSGetExecutablePath =-    allocaBytes 1024 $ \ buf ->  -- PATH_MAX is 1024 on OS X-    alloca $ \ bufsize -> do-        poke bufsize 1024-        status <- c__NSGetExecutablePath buf bufsize-        if status == 0-            then peekFilePath buf-            else do reqBufsize <- fromIntegral `fmap` peek bufsize-                    allocaBytes reqBufsize $ \ newBuf -> do-                        status2 <- c__NSGetExecutablePath newBuf bufsize-                        if status2 == 0-                             then peekFilePath newBuf-                             else error "_NSGetExecutablePath: buffer too small"--foreign import ccall unsafe "stdlib.h realpath"-    c_realpath :: CString -> CString -> IO CString---- | Resolves all symbolic links, extra \/ characters, and references--- to \/.\/ and \/..\/. Returns an absolute pathname.------ See realpath(3)-realpath :: FilePath -> IO FilePath-realpath path =-    withFilePath path $ \ fileName ->-    allocaBytes 1024 $ \ resolvedName -> do-        _ <- throwErrnoIfNull "realpath" $ c_realpath fileName resolvedName-        peekFilePath resolvedName--getExecutablePath = _NSGetExecutablePath >>= realpath------------------------------------------------------------------------------------- Linux--#elif defined(linux_HOST_OS)--foreign import ccall unsafe "readlink"-    c_readlink :: CString -> CString -> CSize -> IO CInt---- | Reads the @FilePath@ pointed to by the symbolic link and returns--- it.------ See readlink(2)-readSymbolicLink :: FilePath -> IO FilePath-readSymbolicLink file =-    allocaArray0 4096 $ \buf -> do-        withFilePath file $ \s -> do-            len <- throwErrnoPathIfMinus1 "readSymbolicLink" file $-                   c_readlink s buf 4096-            peekFilePathLen (buf,fromIntegral len)--getExecutablePath = readSymbolicLink $ "/proc/self/exe"------------------------------------------------------------------------------------- Windows--#elif defined(mingw32_HOST_OS)--# if defined(i386_HOST_ARCH)-##  define WINDOWS_CCONV stdcall-# elif defined(x86_64_HOST_ARCH)-##  define WINDOWS_CCONV ccall-# else-#  error Unknown mingw32 arch-# endif--foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW"-    c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32--getExecutablePath = go 2048  -- plenty, PATH_MAX is 512 under Win32-  where-    go size = allocaArray (fromIntegral size) $ \ buf -> do-        ret <- c_GetModuleFileName nullPtr buf size-        case ret of-            0 -> error "getExecutablePath: GetModuleFileNameW returned an error"-            _ | ret < size -> peekFilePath buf-              | otherwise  -> go (size * 2)------------------------------------------------------------------------------------- Fallback to argv[0]--#else--foreign import ccall unsafe "getFullProgArgv"-    c_getFullProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()--getExecutablePath =-    alloca $ \ p_argc ->-    alloca $ \ p_argv -> do-        c_getFullProgArgv p_argc p_argv-        argc <- peek p_argc-        if argc > 0-            -- If argc > 0 then argv[0] is guaranteed by the standard-            -- to be a pointer to a null-terminated string.-            then peek p_argv >>= peek >>= peekFilePath-            else error $ "getExecutablePath: " ++ msg-  where msg = "no OS specific implementation and program name couldn't be " ++-              "found in argv"------------------------------------------------------------------------------------#endif
− System/Exit.hs
@@ -1,82 +0,0 @@-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  System.Exit--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Exiting the program.-----------------------------------------------------------------------------------module System.Exit-    (-      ExitCode(ExitSuccess,ExitFailure)-    , exitWith-    , exitFailure-    , exitSuccess-    , die-  ) where--import System.IO--import GHC.IO-import GHC.IO.Exception---- ------------------------------------------------------------------------------ exitWith---- | Computation 'exitWith' @code@ throws 'ExitCode' @code@.--- Normally this terminates the program, returning @code@ to the--- program's caller.------ On program termination, the standard 'Handle's 'stdout' and--- 'stderr' are flushed automatically; any other buffered 'Handle's--- need to be flushed manually, otherwise the buffered data will be--- discarded.------ A program that fails in any other way is treated as if it had--- called 'exitFailure'.--- A program that terminates successfully without calling 'exitWith'--- explicitly is treated as it it had called 'exitWith' 'ExitSuccess'.------ As an 'ExitCode' is not an 'IOError', 'exitWith' bypasses--- the error handling in the 'IO' monad and cannot be intercepted by--- 'catch' from the "Prelude".  However it is a 'SomeException', and can--- be caught using the functions of "Control.Exception".  This means--- that cleanup computations added with 'Control.Exception.bracket'--- (from "Control.Exception") are also executed properly on 'exitWith'.------ Note: in GHC, 'exitWith' should be called from the main program--- thread in order to exit the process.  When called from another--- thread, 'exitWith' will throw an 'ExitException' as normal, but the--- exception will not cause the process itself to exit.----exitWith :: ExitCode -> IO a-exitWith ExitSuccess = throwIO ExitSuccess-exitWith code@(ExitFailure n)-  | n /= 0 = throwIO code-  | otherwise = ioError (IOError Nothing InvalidArgument "exitWith" "ExitFailure 0" Nothing Nothing)---- | The computation 'exitFailure' is equivalent to--- 'exitWith' @(@'ExitFailure' /exitfail/@)@,--- where /exitfail/ is implementation-dependent.-exitFailure :: IO a-exitFailure = exitWith (ExitFailure 1)---- | The computation 'exitSuccess' is equivalent to--- 'exitWith' 'ExitSuccess', It terminates the program--- successfully.-exitSuccess :: IO a-exitSuccess = exitWith ExitSuccess---- | Write given error message to `stderr` and terminate with `exitFailure`.------ @since 4.8.0.0-die :: String -> IO a-die err = hPutStrLn stderr err >> exitFailure
− System/IO.hs
@@ -1,596 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, CApiFFI #-}---------------------------------------------------------------------------------- |--- Module      :  System.IO--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  stable--- Portability :  portable------ The standard IO library.-----------------------------------------------------------------------------------module System.IO (-    -- * The IO monad--    IO,-    fixIO,--    -- * Files and handles--    FilePath,--    Handle,             -- abstract, instance of: Eq, Show.--    -- | GHC note: a 'Handle' will be automatically closed when the garbage-    -- collector detects that it has become unreferenced by the program.-    -- However, relying on this behaviour is not generally recommended:-    -- the garbage collector is unpredictable.  If possible, use-    -- an explicit 'hClose' to close 'Handle's when they are no longer-    -- required.  GHC does not currently attempt to free up file-    -- descriptors when they have run out, it is your responsibility to-    -- ensure that this doesn't happen.--    -- ** Standard handles--    -- | Three handles are allocated during program initialisation,-    -- and are initially open.--    stdin, stdout, stderr,--    -- * Opening and closing files--    -- ** Opening files--    withFile,-    openFile,-    IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),--    -- ** Closing files--    hClose,--    -- ** Special cases--    -- | These functions are also exported by the "Prelude".--    readFile,-    writeFile,-    appendFile,--    -- ** File locking--    -- $locking--    -- * Operations on handles--    -- ** Determining and changing the size of a file--    hFileSize,-    hSetFileSize,--    -- ** Detecting the end of input--    hIsEOF,-    isEOF,--    -- ** Buffering operations--    BufferMode(NoBuffering,LineBuffering,BlockBuffering),-    hSetBuffering,-    hGetBuffering,-    hFlush,--    -- ** Repositioning handles--    hGetPosn,-    hSetPosn,-    HandlePosn,                -- abstract, instance of: Eq, Show.--    hSeek,-    SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),-    hTell,--    -- ** Handle properties--    hIsOpen, hIsClosed,-    hIsReadable, hIsWritable,-    hIsSeekable,--    -- ** Terminal operations (not portable: GHC only)--    hIsTerminalDevice,--    hSetEcho,-    hGetEcho,--    -- ** Showing handle state (not portable: GHC only)--    hShow,--    -- * Text input and output--    -- ** Text input--    hWaitForInput,-    hReady,-    hGetChar,-    hGetLine,-    hLookAhead,-    hGetContents,--    -- ** Text output--    hPutChar,-    hPutStr,-    hPutStrLn,-    hPrint,--    -- ** Special cases for standard input and output--    -- | These functions are also exported by the "Prelude".--    interact,-    putChar,-    putStr,-    putStrLn,-    print,-    getChar,-    getLine,-    getContents,-    readIO,-    readLn,--    -- * Binary input and output--    withBinaryFile,-    openBinaryFile,-    hSetBinaryMode,-    hPutBuf,-    hGetBuf,-    hGetBufSome,-    hPutBufNonBlocking,-    hGetBufNonBlocking,--    -- * Temporary files--    openTempFile,-    openBinaryTempFile,-    openTempFileWithDefaultPermissions,-    openBinaryTempFileWithDefaultPermissions,--    -- * Unicode encoding\/decoding--    -- | A text-mode 'Handle' has an associated 'TextEncoding', which-    -- is used to decode bytes into Unicode characters when reading,-    -- and encode Unicode characters into bytes when writing.-    ---    -- The default 'TextEncoding' is the same as the default encoding-    -- on your system, which is also available as 'localeEncoding'.-    -- (GHC note: on Windows, we currently do not support double-byte-    -- encodings; if the console\'s code page is unsupported, then-    -- 'localeEncoding' will be 'latin1'.)-    ---    -- Encoding and decoding errors are always detected and reported,-    -- except during lazy I/O ('hGetContents', 'getContents', and-    -- 'readFile'), where a decoding error merely results in-    -- termination of the character stream, as with other I/O errors.--    hSetEncoding,-    hGetEncoding,--    -- ** Unicode encodings-    TextEncoding,-    latin1,-    utf8, utf8_bom,-    utf16, utf16le, utf16be,-    utf32, utf32le, utf32be,-    localeEncoding,-    char8,-    mkTextEncoding,--    -- * Newline conversion--    -- | In Haskell, a newline is always represented by the character-    -- '\n'.  However, in files and external character streams, a-    -- newline may be represented by another character sequence, such-    -- as '\r\n'.-    ---    -- A text-mode 'Handle' has an associated 'NewlineMode' that-    -- specifies how to transate newline characters.  The-    -- 'NewlineMode' specifies the input and output translation-    -- separately, so that for instance you can translate '\r\n'-    -- to '\n' on input, but leave newlines as '\n' on output.-    ---    -- The default 'NewlineMode' for a 'Handle' is-    -- 'nativeNewlineMode', which does no translation on Unix systems,-    -- but translates '\r\n' to '\n' and back on Windows.-    ---    -- Binary-mode 'Handle's do no newline translation at all.-    ---    hSetNewlineMode,-    Newline(..), nativeNewline,-    NewlineMode(..),-    noNewlineTranslation, universalNewlineMode, nativeNewlineMode,-  ) where--import Control.Exception.Base--import Data.Bits-import Data.Maybe-import Foreign.C.Error-#ifdef mingw32_HOST_OS-import Foreign.C.String-#endif-import Foreign.C.Types-import System.Posix.Internals-import System.Posix.Types--import GHC.Base-import GHC.List-import GHC.IO hiding ( bracket, onException )-import GHC.IO.IOMode-import GHC.IO.Handle.FD-import qualified GHC.IO.FD as FD-import GHC.IO.Handle-import GHC.IO.Handle.Text ( hGetBufSome, hPutStrLn )-import GHC.IO.Exception ( userError )-import GHC.IO.Encoding-import Text.Read-import GHC.Show-import GHC.MVar---- -------------------------------------------------------------------------------- Standard IO---- | Write a character to the standard output device--- (same as 'hPutChar' 'stdout').--putChar         :: Char -> IO ()-putChar c       =  hPutChar stdout c---- | Write a string to the standard output device--- (same as 'hPutStr' 'stdout').--putStr          :: String -> IO ()-putStr s        =  hPutStr stdout s---- | The same as 'putStr', but adds a newline character.--putStrLn        :: String -> IO ()-putStrLn s      =  hPutStrLn stdout s---- | The 'print' function outputs a value of any printable type to the--- standard output device.--- Printable types are those that are instances of class 'Show'; 'print'--- converts values to strings for output using the 'show' operation and--- adds a newline.------ For example, a program to print the first 20 integers and their--- powers of 2 could be written as:------ > main = print ([(n, 2^n) | n <- [0..19]])--print           :: Show a => a -> IO ()-print x         =  putStrLn (show x)---- | Read a character from the standard input device--- (same as 'hGetChar' 'stdin').--getChar         :: IO Char-getChar         =  hGetChar stdin---- | Read a line from the standard input device--- (same as 'hGetLine' 'stdin').--getLine         :: IO String-getLine         =  hGetLine stdin---- | The 'getContents' operation returns all user input as a single string,--- which is read lazily as it is needed--- (same as 'hGetContents' 'stdin').--getContents     :: IO String-getContents     =  hGetContents stdin---- | The 'interact' function takes a function of type @String->String@--- as its argument.  The entire input from the standard input device is--- passed to this function as its argument, and the resulting string is--- output on the standard output device.--interact        ::  (String -> String) -> IO ()-interact f      =   do s <- getContents-                       putStr (f s)---- | The 'readFile' function reads a file and--- returns the contents of the file as a string.--- The file is read lazily, on demand, as with 'getContents'.--readFile        :: FilePath -> IO String-readFile name   =  openFile name ReadMode >>= hGetContents---- | The computation 'writeFile' @file str@ function writes the string @str@,--- to the file @file@.-writeFile :: FilePath -> String -> IO ()-writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)---- | The computation 'appendFile' @file str@ function appends the string @str@,--- to the file @file@.------ Note that 'writeFile' and 'appendFile' write a literal string--- to a file.  To write a value of any printable type, as with 'print',--- use the 'show' function to convert the value to a string first.------ > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])--appendFile      :: FilePath -> String -> IO ()-appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)---- | The 'readLn' function combines 'getLine' and 'readIO'.--readLn          :: Read a => IO a-readLn          =  do l <- getLine-                      r <- readIO l-                      return r---- | The 'readIO' function is similar to 'read' except that it signals--- parse failure to the 'IO' monad instead of terminating the program.--readIO          :: Read a => String -> IO a-readIO s        =  case (do { (x,t) <- reads s ;-                              ("","") <- lex t ;-                              return x }) of-                        [x]    -> return x-                        []     -> ioError (userError "Prelude.readIO: no parse")-                        _      -> ioError (userError "Prelude.readIO: ambiguous parse")---- | The Unicode encoding of the current locale------ This is the initial locale encoding: if it has been subsequently changed by--- 'GHC.IO.Encoding.setLocaleEncoding' this value will not reflect that change.-localeEncoding :: TextEncoding-localeEncoding = initLocaleEncoding---- | Computation 'hReady' @hdl@ indicates whether at least one item is--- available for input from handle @hdl@.------ This operation may fail with:------  * 'System.IO.Error.isEOFError' if the end of file has been reached.--hReady          :: Handle -> IO Bool-hReady h        =  hWaitForInput h 0---- | Computation 'hPrint' @hdl t@ writes the string representation of @t@--- given by the 'shows' function to the file or channel managed by @hdl@--- and appends a newline.------ This operation may fail with:------  * 'System.IO.Error.isFullError' if the device is full; or------  * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.--hPrint          :: Show a => Handle -> a -> IO ()-hPrint hdl      =  hPutStrLn hdl . show---- | @'withFile' name mode act@ opens a file using 'openFile' and passes--- the resulting handle to the computation @act@.  The handle will be--- closed on exit from 'withFile', whether by normal termination or by--- raising an exception.  If closing the handle raises an exception, then--- this exception will be raised by 'withFile' rather than any exception--- raised by 'act'.-withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r-withFile name mode = bracket (openFile name mode) hClose---- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'--- and passes the resulting handle to the computation @act@.  The handle--- will be closed on exit from 'withBinaryFile', whether by normal--- termination or by raising an exception.-withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r-withBinaryFile name mode = bracket (openBinaryFile name mode) hClose---- ------------------------------------------------------------------------------ fixIO--fixIO :: (a -> IO a) -> IO a-fixIO k = do-    m <- newEmptyMVar-    ans <- unsafeInterleaveIO (takeMVar m)-    result <- k ans-    putMVar m result-    return result---- NOTE: we do our own explicit black holing here, because GHC's lazy--- blackholing isn't enough.  In an infinite loop, GHC may run the IO--- computation a few times before it notices the loop, which is wrong.------ NOTE2: the explicit black-holing with an IORef ran into trouble--- with multiple threads (see #5421), so now we use an MVar.  I'm--- actually wondering whether we should use readMVar rather than--- takeMVar, just in case it ends up being executed multiple times,--- but even then it would have to be masked to protect against async--- exceptions.  Ugh.  What we really need here is an IVar, or an--- atomic readMVar, or even STM.  All these seem like overkill.------ See also System.IO.Unsafe.unsafeFixIO.------- | The function creates a temporary file in ReadWrite mode.--- The created file isn\'t deleted automatically, so you need to delete it manually.------ The file is creates with permissions such that only the current--- user can read\/write it.------ With some exceptions (see below), the file will be created securely--- in the sense that an attacker should not be able to cause--- openTempFile to overwrite another file on the filesystem using your--- credentials, by putting symbolic links (on Unix) in the place where--- the temporary file is to be created.  On Unix the @O_CREAT@ and--- @O_EXCL@ flags are used to prevent this attack, but note that--- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you--- rely on this behaviour it is best to use local filesystems only.----openTempFile :: FilePath   -- ^ Directory in which to create the file-             -> String     -- ^ File name template. If the template is \"foo.ext\" then-                           -- the created file will be \"fooXXX.ext\" where XXX is some-                           -- random number.-             -> IO (FilePath, Handle)-openTempFile tmp_dir template-    = openTempFile' "openTempFile" tmp_dir template False 0o600---- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.-openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)-openBinaryTempFile tmp_dir template-    = openTempFile' "openBinaryTempFile" tmp_dir template True 0o600---- | Like 'openTempFile', but uses the default file permissions-openTempFileWithDefaultPermissions :: FilePath -> String-                                   -> IO (FilePath, Handle)-openTempFileWithDefaultPermissions tmp_dir template-    = openTempFile' "openTempFileWithDefaultPermissions" tmp_dir template False 0o666---- | Like 'openBinaryTempFile', but uses the default file permissions-openBinaryTempFileWithDefaultPermissions :: FilePath -> String-                                         -> IO (FilePath, Handle)-openBinaryTempFileWithDefaultPermissions tmp_dir template-    = openTempFile' "openBinaryTempFileWithDefaultPermissions" tmp_dir template True 0o666--openTempFile' :: String -> FilePath -> String -> Bool -> CMode-              -> IO (FilePath, Handle)-openTempFile' loc tmp_dir template binary mode = findTempName-  where-    -- We split off the last extension, so we can use .foo.ext files-    -- for temporary files (hidden on Unix OSes). Unfortunately we're-    -- below filepath in the hierarchy here.-    (prefix,suffix) =-       case break (== '.') $ reverse template of-         -- First case: template contains no '.'s. Just re-reverse it.-         (rev_suffix, "")       -> (reverse rev_suffix, "")-         -- Second case: template contains at least one '.'. Strip the-         -- dot from the prefix and prepend it to the suffix (if we don't-         -- do this, the unique number will get added after the '.' and-         -- thus be part of the extension, which is wrong.)-         (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)-         -- Otherwise, something is wrong, because (break (== '.')) should-         -- always return a pair with either the empty string or a string-         -- beginning with '.' as the second component.-         _                      -> error "bug in System.IO.openTempFile"--    findTempName = do-      rs <- rand_string-      let filename = prefix ++ rs ++ suffix-          filepath = tmp_dir `combine` filename-      r <- openNewFile filepath binary mode-      case r of-        FileExists -> findTempName-        OpenNewError errno -> ioError (errnoToIOError loc errno Nothing (Just tmp_dir))-        NewFileCreated fd -> do-          (fD,fd_type) <- FD.mkFD fd ReadWriteMode Nothing{-no stat-}-                               False{-is_socket-}-                               True{-is_nonblock-}--          enc <- getLocaleEncoding-          h <- mkHandleFromFD fD fd_type filepath ReadWriteMode False{-set non-block-} (Just enc)--          return (filepath, h)--      where-        -- XXX bits copied from System.FilePath, since that's not available here-        combine a b-                  | null b = a-                  | null a = b-                  | last a == pathSeparator = a ++ b-                  | otherwise = a ++ [pathSeparator] ++ b---- int rand(void) from <stdlib.h>, limited by RAND_MAX (small value, 32768)-foreign import capi "stdlib.h rand" c_rand :: IO CInt---- build large digit-alike number-rand_string :: IO String-rand_string = do-  r1 <- c_rand-  r2 <- c_rand-  return $ show r1 ++ show r2--data OpenNewFileResult-  = NewFileCreated CInt-  | FileExists-  | OpenNewError Errno--openNewFile :: FilePath -> Bool -> CMode -> IO OpenNewFileResult-openNewFile filepath binary mode = do-  let oflags1 = rw_flags .|. o_EXCL--      binary_flags-        | binary    = o_BINARY-        | otherwise = 0--      oflags = oflags1 .|. binary_flags-  fd <- withFilePath filepath $ \ f ->-          c_open f oflags mode-  if fd < 0-    then do-      errno <- getErrno-      case errno of-        _ | errno == eEXIST -> return FileExists-#ifdef mingw32_HOST_OS-        -- If c_open throws EACCES on windows, it could mean that filepath is a-        -- directory. In this case, we want to return FileExists so that the-        -- enclosing openTempFile can try again instead of failing outright.-        -- See bug #4968.-        _ | errno == eACCES -> do-          withCString filepath $ \path -> do-            -- There is a race here: the directory might have been moved or-            -- deleted between the c_open call and the next line, but there-            -- doesn't seem to be any direct way to detect that the c_open call-            -- failed because of an existing directory.-            exists <- c_fileExists path-            return $ if exists-              then FileExists-              else OpenNewError errno-#endif-        _ -> return (OpenNewError errno)-    else return (NewFileCreated fd)--#ifdef mingw32_HOST_OS-foreign import ccall "file_exists" c_fileExists :: CString -> IO Bool-#endif---- XXX Should use filepath library-pathSeparator :: Char-#ifdef mingw32_HOST_OS-pathSeparator = '\\'-#else-pathSeparator = '/'-#endif---- XXX Copied from GHC.Handle-std_flags, output_flags, rw_flags :: CInt-std_flags    = o_NONBLOCK   .|. o_NOCTTY-output_flags = std_flags    .|. o_CREAT-rw_flags     = output_flags .|. o_RDWR---- $locking--- Implementations should enforce as far as possible, at least locally to the--- Haskell process, multiple-reader single-writer locking on files.--- That is, /there may either be many handles on the same file which manage input, or just one handle on the file which manages output/.  If any--- open or semi-closed handle is managing a file for output, no new--- handle can be allocated for that file.  If any open or semi-closed--- handle is managing a file for input, new handles can only be allocated--- if they do not manage output.  Whether two files are the same is--- implementation-dependent, but they should normally be the same if they--- have the same absolute path name and neither has been renamed, for--- example.------ /Warning/: the 'readFile' operation holds a semi-closed handle on--- the file until the entire contents of the file have been consumed.--- It follows that an attempt to write to a file (using 'writeFile', for--- example) that was earlier opened by 'readFile' will usually result in--- failure with 'System.IO.Error.isAlreadyInUseError'.-
− System/IO/Error.hs
@@ -1,337 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  System.IO.Error--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Standard IO Errors.-----------------------------------------------------------------------------------module System.IO.Error (--    -- * I\/O errors-    IOError,--    userError,--    mkIOError,--    annotateIOError,--    -- ** Classifying I\/O errors-    isAlreadyExistsError,-    isDoesNotExistError,-    isAlreadyInUseError,-    isFullError,-    isEOFError,-    isIllegalOperation,-    isPermissionError,-    isUserError,--    -- ** Attributes of I\/O errors-    ioeGetErrorType,-    ioeGetLocation,-    ioeGetErrorString,-    ioeGetHandle,-    ioeGetFileName,--    ioeSetErrorType,-    ioeSetErrorString,-    ioeSetLocation,-    ioeSetHandle,-    ioeSetFileName,--    -- * Types of I\/O error-    IOErrorType,                -- abstract--    alreadyExistsErrorType,-    doesNotExistErrorType,-    alreadyInUseErrorType,-    fullErrorType,-    eofErrorType,-    illegalOperationErrorType,-    permissionErrorType,-    userErrorType,--    -- ** 'IOErrorType' predicates-    isAlreadyExistsErrorType,-    isDoesNotExistErrorType,-    isAlreadyInUseErrorType,-    isFullErrorType,-    isEOFErrorType,-    isIllegalOperationErrorType,-    isPermissionErrorType,-    isUserErrorType,--    -- * Throwing and catching I\/O errors--    ioError,--    catchIOError,-    tryIOError,--    modifyIOError,-  ) where--import Control.Exception.Base--import Data.Either-import Data.Maybe--import GHC.Base-import GHC.IO-import GHC.IO.Exception-import GHC.IO.Handle.Types-import Text.Show---- | The construct 'tryIOError' @comp@ exposes IO errors which occur within a--- computation, and which are not fully handled.------ Non-I\/O exceptions are not caught by this variant; to catch all--- exceptions, use 'Control.Exception.try' from "Control.Exception".------ @since 4.4.0.0-tryIOError     :: IO a -> IO (Either IOError a)-tryIOError f   =  catch (do r <- f-                            return (Right r))-                        (return . Left)---- -------------------------------------------------------------------------------- Constructing an IOError---- | Construct an 'IOError' of the given type where the second argument--- describes the error location and the third and fourth argument--- contain the file handle and file path of the file involved in the--- error if applicable.-mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError-mkIOError t location maybe_hdl maybe_filename =-               IOError{ ioe_type = t,-                        ioe_location = location,-                        ioe_description = "",-                        ioe_errno = Nothing,-                        ioe_handle = maybe_hdl,-                        ioe_filename = maybe_filename-                        }---- -------------------------------------------------------------------------------- IOErrorType---- | An error indicating that an 'IO' operation failed because--- one of its arguments already exists.-isAlreadyExistsError :: IOError -> Bool-isAlreadyExistsError = isAlreadyExistsErrorType    . ioeGetErrorType---- | An error indicating that an 'IO' operation failed because--- one of its arguments does not exist.-isDoesNotExistError :: IOError -> Bool-isDoesNotExistError  = isDoesNotExistErrorType     . ioeGetErrorType---- | An error indicating that an 'IO' operation failed because--- one of its arguments is a single-use resource, which is already--- being used (for example, opening the same file twice for writing--- might give this error).-isAlreadyInUseError :: IOError -> Bool-isAlreadyInUseError  = isAlreadyInUseErrorType     . ioeGetErrorType---- | An error indicating that an 'IO' operation failed because--- the device is full.-isFullError         :: IOError -> Bool-isFullError          = isFullErrorType             . ioeGetErrorType---- | An error indicating that an 'IO' operation failed because--- the end of file has been reached.-isEOFError          :: IOError -> Bool-isEOFError           = isEOFErrorType              . ioeGetErrorType---- | An error indicating that an 'IO' operation failed because--- the operation was not possible.--- Any computation which returns an 'IO' result may fail with--- 'isIllegalOperation'.  In some cases, an implementation will not be--- able to distinguish between the possible error causes.  In this case--- it should fail with 'isIllegalOperation'.-isIllegalOperation  :: IOError -> Bool-isIllegalOperation   = isIllegalOperationErrorType . ioeGetErrorType---- | An error indicating that an 'IO' operation failed because--- the user does not have sufficient operating system privilege--- to perform that operation.-isPermissionError   :: IOError -> Bool-isPermissionError    = isPermissionErrorType       . ioeGetErrorType---- | A programmer-defined error value constructed using 'userError'.-isUserError         :: IOError -> Bool-isUserError          = isUserErrorType             . ioeGetErrorType---- -------------------------------------------------------------------------------- IOErrorTypes---- | I\/O error where the operation failed because one of its arguments--- already exists.-alreadyExistsErrorType   :: IOErrorType-alreadyExistsErrorType    = AlreadyExists---- | I\/O error where the operation failed because one of its arguments--- does not exist.-doesNotExistErrorType    :: IOErrorType-doesNotExistErrorType     = NoSuchThing---- | I\/O error where the operation failed because one of its arguments--- is a single-use resource, which is already being used.-alreadyInUseErrorType    :: IOErrorType-alreadyInUseErrorType     = ResourceBusy---- | I\/O error where the operation failed because the device is full.-fullErrorType            :: IOErrorType-fullErrorType             = ResourceExhausted---- | I\/O error where the operation failed because the end of file has--- been reached.-eofErrorType             :: IOErrorType-eofErrorType              = EOF---- | I\/O error where the operation is not possible.-illegalOperationErrorType :: IOErrorType-illegalOperationErrorType = IllegalOperation---- | I\/O error where the operation failed because the user does not--- have sufficient operating system privilege to perform that operation.-permissionErrorType      :: IOErrorType-permissionErrorType       = PermissionDenied---- | I\/O error that is programmer-defined.-userErrorType            :: IOErrorType-userErrorType             = UserError---- -------------------------------------------------------------------------------- IOErrorType predicates---- | I\/O error where the operation failed because one of its arguments--- already exists.-isAlreadyExistsErrorType :: IOErrorType -> Bool-isAlreadyExistsErrorType AlreadyExists = True-isAlreadyExistsErrorType _ = False---- | I\/O error where the operation failed because one of its arguments--- does not exist.-isDoesNotExistErrorType :: IOErrorType -> Bool-isDoesNotExistErrorType NoSuchThing = True-isDoesNotExistErrorType _ = False---- | I\/O error where the operation failed because one of its arguments--- is a single-use resource, which is already being used.-isAlreadyInUseErrorType :: IOErrorType -> Bool-isAlreadyInUseErrorType ResourceBusy = True-isAlreadyInUseErrorType _ = False---- | I\/O error where the operation failed because the device is full.-isFullErrorType :: IOErrorType -> Bool-isFullErrorType ResourceExhausted = True-isFullErrorType _ = False---- | I\/O error where the operation failed because the end of file has--- been reached.-isEOFErrorType :: IOErrorType -> Bool-isEOFErrorType EOF = True-isEOFErrorType _ = False---- | I\/O error where the operation is not possible.-isIllegalOperationErrorType :: IOErrorType -> Bool-isIllegalOperationErrorType IllegalOperation = True-isIllegalOperationErrorType _ = False---- | I\/O error where the operation failed because the user does not--- have sufficient operating system privilege to perform that operation.-isPermissionErrorType :: IOErrorType -> Bool-isPermissionErrorType PermissionDenied = True-isPermissionErrorType _ = False---- | I\/O error that is programmer-defined.-isUserErrorType :: IOErrorType -> Bool-isUserErrorType UserError = True-isUserErrorType _ = False---- -------------------------------------------------------------------------------- Miscellaneous--ioeGetErrorType       :: IOError -> IOErrorType-ioeGetErrorString     :: IOError -> String-ioeGetLocation        :: IOError -> String-ioeGetHandle          :: IOError -> Maybe Handle-ioeGetFileName        :: IOError -> Maybe FilePath--ioeGetErrorType ioe = ioe_type ioe--ioeGetErrorString ioe-   | isUserErrorType (ioe_type ioe) = ioe_description ioe-   | otherwise                      = show (ioe_type ioe)--ioeGetLocation ioe = ioe_location ioe--ioeGetHandle ioe = ioe_handle ioe--ioeGetFileName ioe = ioe_filename ioe--ioeSetErrorType   :: IOError -> IOErrorType -> IOError-ioeSetErrorString :: IOError -> String      -> IOError-ioeSetLocation    :: IOError -> String      -> IOError-ioeSetHandle      :: IOError -> Handle      -> IOError-ioeSetFileName    :: IOError -> FilePath    -> IOError--ioeSetErrorType   ioe errtype  = ioe{ ioe_type = errtype }-ioeSetErrorString ioe str      = ioe{ ioe_description = str }-ioeSetLocation    ioe str      = ioe{ ioe_location = str }-ioeSetHandle      ioe hdl      = ioe{ ioe_handle = Just hdl }-ioeSetFileName    ioe filename = ioe{ ioe_filename = Just filename }---- | Catch any 'IOError' that occurs in the computation and throw a--- modified version.-modifyIOError :: (IOError -> IOError) -> IO a -> IO a-modifyIOError f io = catch io (\e -> ioError (f e))---- -------------------------------------------------------------------------------- annotating an IOError---- | Adds a location description and maybe a file path and file handle--- to an 'IOError'.  If any of the file handle or file path is not given--- the corresponding value in the 'IOError' remains unaltered.-annotateIOError :: IOError-              -> String-              -> Maybe Handle-              -> Maybe FilePath-              -> IOError-annotateIOError ioe loc hdl path =-  ioe{ ioe_handle = hdl `mplus` ioe_handle ioe,-       ioe_location = loc, ioe_filename = path `mplus` ioe_filename ioe }---- | The 'catchIOError' function establishes a handler that receives any--- 'IOError' raised in the action protected by 'catchIOError'.--- An 'IOError' is caught by--- the most recent handler established by one of the exception handling--- functions.  These handlers are--- not selective: all 'IOError's are caught.  Exception propagation--- must be explicitly provided in a handler by re-raising any unwanted--- exceptions.  For example, in------ > f = catchIOError g (\e -> if IO.isEOFError e then return [] else ioError e)------ the function @f@ returns @[]@ when an end-of-file exception--- (cf. 'System.IO.Error.isEOFError') occurs in @g@; otherwise, the--- exception is propagated to the next outer handler.------ When an exception propagates outside the main program, the Haskell--- system prints the associated 'IOError' value and exits the program.------ Non-I\/O exceptions are not caught by this variant; to catch all--- exceptions, use 'Control.Exception.catch' from "Control.Exception".------ @since 4.4.0.0-catchIOError :: IO a -> (IOError -> IO a) -> IO a-catchIOError = catch
− System/IO/Unsafe.hs
@@ -1,50 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  System.IO.Unsafe--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ \"Unsafe\" IO operations.-----------------------------------------------------------------------------------module System.IO.Unsafe (-   -- * Unsafe 'System.IO.IO' operations-   unsafePerformIO,-   unsafeDupablePerformIO,-   unsafeInterleaveIO,-   unsafeFixIO,-  ) where--import GHC.Base-import GHC.IO-import GHC.IORef-import GHC.Exception-import Control.Exception---- | A slightly faster version of `System.IO.fixIO` that may not be--- safe to use with multiple threads.  The unsafety arises when used--- like this:------ >  unsafeFixIO $ \r -> do--- >     forkIO (print r)--- >     return (...)------ In this case, the child thread will receive a @NonTermination@--- exception instead of waiting for the value of @r@ to be computed.------ @since 4.5.0.0-unsafeFixIO :: (a -> IO a) -> IO a-unsafeFixIO k = do-  ref <- newIORef (throw NonTermination)-  ans <- unsafeDupableInterleaveIO (readIORef ref)-  result <- k ans-  writeIORef ref result-  return result
− System/Info.hs
@@ -1,51 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE CPP #-}---------------------------------------------------------------------------------- |--- Module      :  System.Info--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ Information about the characteristics of the host --- system lucky enough to run your program.-----------------------------------------------------------------------------------module System.Info-   (-       os,-       arch,-       compilerName,-       compilerVersion-   ) where--import Data.Version---- | The version of 'compilerName' with which the program was compiled--- or is being interpreted.-compilerVersion :: Version-compilerVersion = Version [major, minor] []-  where (major, minor) = compilerVersionRaw `divMod` 100--#include "ghcplatform.h"---- | The operating system on which the program is running.-os :: String-os = HOST_OS---- | The machine architecture on which the program is running.-arch :: String-arch = HOST_ARCH---- | The Haskell implementation with which the program was compiled--- or is being interpreted.-compilerName :: String-compilerName = "ghc"--compilerVersionRaw :: Int-compilerVersionRaw = __GLASGOW_HASKELL__
− System/Mem.hs
@@ -1,35 +0,0 @@-{-# LANGUAGE Safe #-}---------------------------------------------------------------------------------- |--- Module      :  System.Mem--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Memory-related system things.-----------------------------------------------------------------------------------module System.Mem-       ( performGC-       , performMajorGC-       , performMinorGC-       ) where---- | Triggers an immediate garbage collection.-performGC :: IO ()-performGC = performMajorGC---- | Triggers an immediate garbage collection.------ @since 4.7.0.0-foreign import ccall "performMajorGC" performMajorGC :: IO ()---- | Triggers an immediate minor garbage collection.------ @since 4.7.0.0-foreign import ccall "performGC" performMinorGC :: IO ()
− System/Mem/StableName.hs
@@ -1,126 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP #-}-{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}-{-# LANGUAGE MagicHash #-}-#if !defined(__PARALLEL_HASKELL__)-{-# LANGUAGE UnboxedTuples #-}-#endif---------------------------------------------------------------------------------- |--- Module      :  System.Mem.StableName--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable------ Stable names are a way of performing fast (O(1)), not-quite-exact--- comparison between objects.------ Stable names solve the following problem: suppose you want to build--- a hash table with Haskell objects as keys, but you want to use--- pointer equality for comparison; maybe because the keys are large--- and hashing would be slow, or perhaps because the keys are infinite--- in size.  We can\'t build a hash table using the address of the--- object as the key, because objects get moved around by the garbage--- collector, meaning a re-hash would be necessary after every garbage--- collection.-------------------------------------------------------------------------------------module System.Mem.StableName (-  -- * Stable Names-  StableName,-  makeStableName,-  hashStableName,-  eqStableName-  ) where--import Data.Typeable--import GHC.IO           ( IO(..) )-import GHC.Base         ( Int(..), StableName#, makeStableName#-                        , eqStableName#, stableNameToInt# )---------------------------------------------------------------------------------- Stable Names--{-|-  An abstract name for an object, that supports equality and hashing.--  Stable names have the following property:--  * If @sn1 :: StableName@ and @sn2 :: StableName@ and @sn1 == sn2@-   then @sn1@ and @sn2@ were created by calls to @makeStableName@ on-   the same object.--  The reverse is not necessarily true: if two stable names are not-  equal, then the objects they name may still be equal.  Note in particular-  that `mkStableName` may return a different `StableName` after an-  object is evaluated.--  Stable Names are similar to Stable Pointers ("Foreign.StablePtr"),-  but differ in the following ways:--  * There is no @freeStableName@ operation, unlike "Foreign.StablePtr"s.-    Stable names are reclaimed by the runtime system when they are no-    longer needed.--  * There is no @deRefStableName@ operation.  You can\'t get back from-    a stable name to the original Haskell object.  The reason for-    this is that the existence of a stable name for an object does not-    guarantee the existence of the object itself; it can still be garbage-    collected.--}--data StableName a = StableName (StableName# a)-                    deriving Typeable---- | Makes a 'StableName' for an arbitrary object.  The object passed as--- the first argument is not evaluated by 'makeStableName'.-makeStableName  :: a -> IO (StableName a)-#if defined(__PARALLEL_HASKELL__)-makeStableName a =-  error "makeStableName not implemented in parallel Haskell"-#else-makeStableName a = IO $ \ s ->-    case makeStableName# a s of (# s', sn #) -> (# s', StableName sn #)-#endif---- | Convert a 'StableName' to an 'Int'.  The 'Int' returned is not--- necessarily unique; several 'StableName's may map to the same 'Int'--- (in practice however, the chances of this are small, so the result--- of 'hashStableName' makes a good hash key).-hashStableName :: StableName a -> Int-#if defined(__PARALLEL_HASKELL__)-hashStableName (StableName sn) =-  error "hashStableName not implemented in parallel Haskell"-#else-hashStableName (StableName sn) = I# (stableNameToInt# sn)-#endif--instance Eq (StableName a) where-#if defined(__PARALLEL_HASKELL__)-    (StableName sn1) == (StableName sn2) =-      error "eqStableName not implemented in parallel Haskell"-#else-    (StableName sn1) == (StableName sn2) =-       case eqStableName# sn1 sn2 of-         0# -> False-         _  -> True-#endif---- | Equality on 'StableName' that does not require that the types of--- the arguments match.------ @since 4.7.0.0-eqStableName :: StableName a -> StableName b -> Bool-eqStableName (StableName sn1) (StableName sn2) =-       case eqStableName# sn1 sn2 of-         0# -> False-         _  -> True-  -- Requested by Emil Axelsson on glasgow-haskell-users, who wants to-  -- use it for implementing observable sharing.-
− System/Mem/Weak.hs
@@ -1,142 +0,0 @@-{-# LANGUAGE Trustworthy #-}---------------------------------------------------------------------------------- |--- Module      :  System.Mem.Weak--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable------ In general terms, a weak pointer is a reference to an object that is--- not followed by the garbage collector - that is, the existence of a--- weak pointer to an object has no effect on the lifetime of that--- object.  A weak pointer can be de-referenced to find out--- whether the object it refers to is still alive or not, and if so--- to return the object itself.------ Weak pointers are particularly useful for caches and memo tables.--- To build a memo table, you build a data structure--- mapping from the function argument (the key) to its result (the--- value).  When you apply the function to a new argument you first--- check whether the key\/value pair is already in the memo table.--- The key point is that the memo table itself should not keep the--- key and value alive.  So the table should contain a weak pointer--- to the key, not an ordinary pointer.  The pointer to the value must--- not be weak, because the only reference to the value might indeed be--- from the memo table.------ So it looks as if the memo table will keep all its values--- alive for ever.  One way to solve this is to purge the table--- occasionally, by deleting entries whose keys have died.------ The weak pointers in this library--- support another approach, called /finalization/.--- When the key referred to by a weak pointer dies, the storage manager--- arranges to run a programmer-specified finalizer.  In the case of memo--- tables, for example, the finalizer could remove the key\/value pair--- from the memo table.------ Another difficulty with the memo table is that the value of a--- key\/value pair might itself contain a pointer to the key.--- So the memo table keeps the value alive, which keeps the key alive,--- even though there may be no other references to the key so both should--- die.  The weak pointers in this library provide a slight--- generalisation of the basic weak-pointer idea, in which each--- weak pointer actually contains both a key and a value.-----------------------------------------------------------------------------------module System.Mem.Weak (-        -- * The @Weak@ type-        Weak,                   -- abstract--        -- * The general interface-        mkWeak,-        deRefWeak,-        finalize,--        -- * Specialised versions-        mkWeakPtr,-        addFinalizer,-        mkWeakPair,-        -- replaceFinaliser--        -- * A precise semantics--        -- $precise-   ) where--import GHC.Weak---- | A specialised version of 'mkWeak', where the key and the value are--- the same object:------ > mkWeakPtr key finalizer = mkWeak key key finalizer----mkWeakPtr :: k -> Maybe (IO ()) -> IO (Weak k)-mkWeakPtr key finalizer = mkWeak key key finalizer--{-|-  A specialised version of 'mkWeakPtr', where the 'Weak' object-  returned is simply thrown away (however the finalizer will be-  remembered by the garbage collector, and will still be run-  when the key becomes unreachable).--  Note: adding a finalizer to a 'Foreign.ForeignPtr.ForeignPtr' using-  'addFinalizer' won't work; use the specialised version-  'Foreign.ForeignPtr.addForeignPtrFinalizer' instead.  For discussion-  see the 'Weak' type.-.--}-addFinalizer :: key -> IO () -> IO ()-addFinalizer key finalizer = do-   _ <- mkWeakPtr key (Just finalizer) -- throw it away-   return ()---- | A specialised version of 'mkWeak' where the value is actually a pair--- of the key and value passed to 'mkWeakPair':------ > mkWeakPair key val finalizer = mkWeak key (key,val) finalizer------ The advantage of this is that the key can be retrieved by 'deRefWeak'--- in addition to the value.-mkWeakPair :: k -> v -> Maybe (IO ()) -> IO (Weak (k,v))-mkWeakPair key val finalizer = mkWeak key (key,val) finalizer---{- $precise--The above informal specification is fine for simple situations, but-matters can get complicated.  In particular, it needs to be clear-exactly when a key dies, so that any weak pointers that refer to it-can be finalized.  Suppose, for example, the value of one weak pointer-refers to the key of another...does that keep the key alive?--The behaviour is simply this:-- *  If a weak pointer (object) refers to an /unreachable/-    key, it may be finalized.-- *  Finalization means (a) arrange that subsequent calls-    to 'deRefWeak' return 'Nothing'; and (b) run the finalizer.--This behaviour depends on what it means for a key to be reachable.-Informally, something is reachable if it can be reached by following-ordinary pointers from the root set, but not following weak pointers.-We define reachability more precisely as follows.--A heap object is /reachable/ if:-- * It is a member of the /root set/.-- * It is directly pointed to by a reachable object, other than-   a weak pointer object.-- * It is a weak pointer object whose key is reachable.-- * It is the value or finalizer of a weak pointer object whose key is reachable.--}-
− System/Posix/Internals.hs
@@ -1,565 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP, NoImplicitPrelude, CApiFFI #-}-{-# OPTIONS_HADDOCK hide #-}---------------------------------------------------------------------------------- |--- Module      :  System.Posix.Internals--- Copyright   :  (c) The University of Glasgow, 1992-2002--- License     :  see libraries/base/LICENSE------ Maintainer  :  cvs-ghc@haskell.org--- Stability   :  internal--- Portability :  non-portable (requires POSIX)------ POSIX support layer for the standard libraries.--- This library is built on *every* platform, including Win32.------ Non-posix compliant in order to support the following features:---      * S_ISSOCK (no sockets in POSIX)-----------------------------------------------------------------------------------module System.Posix.Internals where--#include "HsBaseConfig.h"--import System.Posix.Types--import Foreign-import Foreign.C---- import Data.Bits-import Data.Maybe--#if !defined(HTYPE_TCFLAG_T)-import System.IO.Error-#endif--import GHC.Base-import GHC.Num-import GHC.Real-import GHC.IO-import GHC.IO.IOMode-import GHC.IO.Exception-import GHC.IO.Device-#ifndef mingw32_HOST_OS-import {-# SOURCE #-} GHC.IO.Encoding (getFileSystemEncoding)-import qualified GHC.Foreign as GHC-#endif---- ------------------------------------------------------------------------------ Debugging the base package--puts :: String -> IO ()-puts s = withCAStringLen (s ++ "\n") $ \(p, len) -> do-            -- In reality should be withCString, but assume ASCII to avoid loop-            -- if this is called by GHC.Foreign-           _ <- c_write 1 (castPtr p) (fromIntegral len)-           return ()----- ------------------------------------------------------------------------------ Types--type CFLock     = ()-data {-# CTYPE "struct group" #-} CGroup-type CLconv     = ()-type CPasswd    = ()-type CSigaction = ()-data {-# CTYPE "sigset_t" #-} CSigset-type CStat      = ()-type CTermios   = ()-type CTm        = ()-type CTms       = ()-type CUtimbuf   = ()-type CUtsname   = ()--type FD = CInt---- ------------------------------------------------------------------------------ stat()-related stuff--fdFileSize :: FD -> IO Integer-fdFileSize fd =-  allocaBytes sizeof_stat $ \ p_stat -> do-    throwErrnoIfMinus1Retry_ "fileSize" $-        c_fstat fd p_stat-    c_mode <- st_mode p_stat :: IO CMode-    if not (s_isreg c_mode)-        then return (-1)-        else do-      c_size <- st_size p_stat-      return (fromIntegral c_size)--fileType :: FilePath -> IO IODeviceType-fileType file =-  allocaBytes sizeof_stat $ \ p_stat -> do-  withFilePath file $ \p_file -> do-    throwErrnoIfMinus1Retry_ "fileType" $-      c_stat p_file p_stat-    statGetType p_stat---- NOTE: On Win32 platforms, this will only work with file descriptors--- referring to file handles. i.e., it'll fail for socket FDs.-fdStat :: FD -> IO (IODeviceType, CDev, CIno)-fdStat fd =-  allocaBytes sizeof_stat $ \ p_stat -> do-    throwErrnoIfMinus1Retry_ "fdType" $-        c_fstat fd p_stat-    ty <- statGetType p_stat-    dev <- st_dev p_stat-    ino <- st_ino p_stat-    return (ty,dev,ino)--fdType :: FD -> IO IODeviceType-fdType fd = do (ty,_,_) <- fdStat fd; return ty--statGetType :: Ptr CStat -> IO IODeviceType-statGetType p_stat = do-  c_mode <- st_mode p_stat :: IO CMode-  case () of-      _ | s_isdir c_mode        -> return Directory-        | s_isfifo c_mode || s_issock c_mode || s_ischr  c_mode-                                -> return Stream-        | s_isreg c_mode        -> return RegularFile-         -- Q: map char devices to RawDevice too?-        | s_isblk c_mode        -> return RawDevice-        | otherwise             -> ioError ioe_unknownfiletype--ioe_unknownfiletype :: IOException-ioe_unknownfiletype = IOError Nothing UnsupportedOperation "fdType"-                        "unknown file type"-                        Nothing-                        Nothing--fdGetMode :: FD -> IO IOMode-#if defined(mingw32_HOST_OS) || defined(__MINGW32__)-fdGetMode _ = do-    -- We don't have a way of finding out which flags are set on FDs-    -- on Windows, so make a handle that thinks that anything goes.-    let flags = o_RDWR-#else-fdGetMode fd = do-    flags <- throwErrnoIfMinus1Retry "fdGetMode"-                (c_fcntl_read fd const_f_getfl)-#endif-    let-       wH  = (flags .&. o_WRONLY) /= 0-       aH  = (flags .&. o_APPEND) /= 0-       rwH = (flags .&. o_RDWR) /= 0--       mode-         | wH && aH  = AppendMode-         | wH        = WriteMode-         | rwH       = ReadWriteMode-         | otherwise = ReadMode--    return mode--#ifdef mingw32_HOST_OS-withFilePath :: FilePath -> (CWString -> IO a) -> IO a-withFilePath = withCWString--newFilePath :: FilePath -> IO CWString-newFilePath = newCWString--peekFilePath :: CWString -> IO FilePath-peekFilePath = peekCWString-#else--withFilePath :: FilePath -> (CString -> IO a) -> IO a-newFilePath :: FilePath -> IO CString-peekFilePath :: CString -> IO FilePath-peekFilePathLen :: CStringLen -> IO FilePath--withFilePath fp f = getFileSystemEncoding >>= \enc -> GHC.withCString enc fp f-newFilePath fp = getFileSystemEncoding >>= \enc -> GHC.newCString enc fp-peekFilePath fp = getFileSystemEncoding >>= \enc -> GHC.peekCString enc fp-peekFilePathLen fp = getFileSystemEncoding >>= \enc -> GHC.peekCStringLen enc fp--#endif---- ------------------------------------------------------------------------------ Terminal-related stuff--#if defined(HTYPE_TCFLAG_T)--setEcho :: FD -> Bool -> IO ()-setEcho fd on = do-  tcSetAttr fd $ \ p_tios -> do-    lflag <- c_lflag p_tios :: IO CTcflag-    let new_lflag-         | on        = lflag .|. fromIntegral const_echo-         | otherwise = lflag .&. complement (fromIntegral const_echo)-    poke_c_lflag p_tios (new_lflag :: CTcflag)--getEcho :: FD -> IO Bool-getEcho fd = do-  tcSetAttr fd $ \ p_tios -> do-    lflag <- c_lflag p_tios :: IO CTcflag-    return ((lflag .&. fromIntegral const_echo) /= 0)--setCooked :: FD -> Bool -> IO ()-setCooked fd cooked =-  tcSetAttr fd $ \ p_tios -> do--    -- turn on/off ICANON-    lflag <- c_lflag p_tios :: IO CTcflag-    let new_lflag | cooked    = lflag .|. (fromIntegral const_icanon)-                  | otherwise = lflag .&. complement (fromIntegral const_icanon)-    poke_c_lflag p_tios (new_lflag :: CTcflag)--    -- set VMIN & VTIME to 1/0 respectively-    when (not cooked) $ do-            c_cc <- ptr_c_cc p_tios-            let vmin  = (c_cc `plusPtr` (fromIntegral const_vmin))  :: Ptr Word8-                vtime = (c_cc `plusPtr` (fromIntegral const_vtime)) :: Ptr Word8-            poke vmin  1-            poke vtime 0--tcSetAttr :: FD -> (Ptr CTermios -> IO a) -> IO a-tcSetAttr fd fun = do-     allocaBytes sizeof_termios  $ \p_tios -> do-        throwErrnoIfMinus1Retry_ "tcSetAttr"-           (c_tcgetattr fd p_tios)--        -- Save a copy of termios, if this is a standard file descriptor.-        -- These terminal settings are restored in hs_exit().-        when (fd <= 2) $ do-          p <- get_saved_termios fd-          when (p == nullPtr) $ do-             saved_tios <- mallocBytes sizeof_termios-             copyBytes saved_tios p_tios sizeof_termios-             set_saved_termios fd saved_tios--        -- tcsetattr() when invoked by a background process causes the process-        -- to be sent SIGTTOU regardless of whether the process has TOSTOP set-        -- in its terminal flags (try it...).  This function provides a-        -- wrapper which temporarily blocks SIGTTOU around the call, making it-        -- transparent.-        allocaBytes sizeof_sigset_t $ \ p_sigset -> do-          allocaBytes sizeof_sigset_t $ \ p_old_sigset -> do-             throwErrnoIfMinus1_ "sigemptyset" $-                 c_sigemptyset p_sigset-             throwErrnoIfMinus1_ "sigaddset" $-                 c_sigaddset   p_sigset const_sigttou-             throwErrnoIfMinus1_ "sigprocmask" $-                 c_sigprocmask const_sig_block p_sigset p_old_sigset-             r <- fun p_tios  -- do the business-             throwErrnoIfMinus1Retry_ "tcSetAttr" $-                 c_tcsetattr fd const_tcsanow p_tios-             throwErrnoIfMinus1_ "sigprocmask" $-                 c_sigprocmask const_sig_setmask p_old_sigset nullPtr-             return r--foreign import ccall unsafe "HsBase.h __hscore_get_saved_termios"-   get_saved_termios :: CInt -> IO (Ptr CTermios)--foreign import ccall unsafe "HsBase.h __hscore_set_saved_termios"-   set_saved_termios :: CInt -> (Ptr CTermios) -> IO ()--#else---- 'raw' mode for Win32 means turn off 'line input' (=> buffering and--- character translation for the console.) The Win32 API for doing--- this is GetConsoleMode(), which also requires echoing to be disabled--- when turning off 'line input' processing. Notice that turning off--- 'line input' implies enter/return is reported as '\r' (and it won't--- report that character until another character is input..odd.) This--- latter feature doesn't sit too well with IO actions like IO.hGetLine..--- consider yourself warned.-setCooked :: FD -> Bool -> IO ()-setCooked fd cooked = do-  x <- set_console_buffering fd (if cooked then 1 else 0)-  if (x /= 0)-   then ioError (ioe_unk_error "setCooked" "failed to set buffering")-   else return ()--ioe_unk_error :: String -> String -> IOException-ioe_unk_error loc msg- = ioeSetErrorString (mkIOError OtherError loc Nothing Nothing) msg---- Note: echoing goes hand in hand with enabling 'line input' / raw-ness--- for Win32 consoles, hence setEcho ends up being the inverse of setCooked.-setEcho :: FD -> Bool -> IO ()-setEcho fd on = do-  x <- set_console_echo fd (if on then 1 else 0)-  if (x /= 0)-   then ioError (ioe_unk_error "setEcho" "failed to set echoing")-   else return ()--getEcho :: FD -> IO Bool-getEcho fd = do-  r <- get_console_echo fd-  if (r == (-1))-   then ioError (ioe_unk_error "getEcho" "failed to get echoing")-   else return (r == 1)--foreign import ccall unsafe "consUtils.h set_console_buffering__"-   set_console_buffering :: CInt -> CInt -> IO CInt--foreign import ccall unsafe "consUtils.h set_console_echo__"-   set_console_echo :: CInt -> CInt -> IO CInt--foreign import ccall unsafe "consUtils.h get_console_echo__"-   get_console_echo :: CInt -> IO CInt--foreign import ccall unsafe "consUtils.h is_console__"-   is_console :: CInt -> IO CInt--#endif---- ------------------------------------------------------------------------------ Turning on non-blocking for a file descriptor--setNonBlockingFD :: FD -> Bool -> IO ()-#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)-setNonBlockingFD fd set = do-  flags <- throwErrnoIfMinus1Retry "setNonBlockingFD"-                 (c_fcntl_read fd const_f_getfl)-  let flags' | set       = flags .|. o_NONBLOCK-             | otherwise = flags .&. complement o_NONBLOCK-  when (flags /= flags') $ do-    -- An error when setting O_NONBLOCK isn't fatal: on some systems-    -- there are certain file handles on which this will fail (eg. /dev/null-    -- on FreeBSD) so we throw away the return code from fcntl_write.-    _ <- c_fcntl_write fd const_f_setfl (fromIntegral flags')-    return ()-#else---- bogus defns for win32-setNonBlockingFD _ _ = return ()--#endif---- -------------------------------------------------------------------------------- Set close-on-exec for a file descriptor--#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)-setCloseOnExec :: FD -> IO ()-setCloseOnExec fd = do-  throwErrnoIfMinus1_ "setCloseOnExec" $-    c_fcntl_write fd const_f_setfd const_fd_cloexec-#endif---- -------------------------------------------------------------------------------- foreign imports--#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)-type CFilePath = CString-#else-type CFilePath = CWString-#endif--foreign import ccall unsafe "HsBase.h access"-   c_access :: CString -> CInt -> IO CInt--foreign import ccall unsafe "HsBase.h chmod"-   c_chmod :: CString -> CMode -> IO CInt--foreign import ccall unsafe "HsBase.h close"-   c_close :: CInt -> IO CInt--foreign import ccall unsafe "HsBase.h creat"-   c_creat :: CString -> CMode -> IO CInt--foreign import ccall unsafe "HsBase.h dup"-   c_dup :: CInt -> IO CInt--foreign import ccall unsafe "HsBase.h dup2"-   c_dup2 :: CInt -> CInt -> IO CInt--foreign import ccall unsafe "HsBase.h __hscore_fstat"-   c_fstat :: CInt -> Ptr CStat -> IO CInt--foreign import ccall unsafe "HsBase.h isatty"-   c_isatty :: CInt -> IO CInt--#if defined(mingw32_HOST_OS) || defined(__MINGW32__)-foreign import ccall unsafe "io.h _lseeki64"-   c_lseek :: CInt -> Int64 -> CInt -> IO Int64-#else--- We use CAPI as on some OSs (eg. Linux) this is wrapped by a macro--- which redirects to the 64-bit-off_t versions when large file--- support is enabled.-foreign import capi unsafe "unistd.h lseek"-   c_lseek :: CInt -> COff -> CInt -> IO COff-#endif--foreign import ccall unsafe "HsBase.h __hscore_lstat"-   lstat :: CFilePath -> Ptr CStat -> IO CInt--foreign import ccall unsafe "HsBase.h __hscore_open"-   c_open :: CFilePath -> CInt -> CMode -> IO CInt--foreign import ccall safe "HsBase.h __hscore_open"-   c_safe_open :: CFilePath -> CInt -> CMode -> IO CInt---- See Note: CSsize-foreign import capi unsafe "HsBase.h read"-   c_read :: CInt -> Ptr Word8 -> CSize -> IO CSsize---- See Note: CSsize-foreign import capi safe "HsBase.h read"-   c_safe_read :: CInt -> Ptr Word8 -> CSize -> IO CSsize--foreign import ccall unsafe "HsBase.h __hscore_stat"-   c_stat :: CFilePath -> Ptr CStat -> IO CInt--foreign import ccall unsafe "HsBase.h umask"-   c_umask :: CMode -> IO CMode---- See Note: CSsize-foreign import capi unsafe "HsBase.h write"-   c_write :: CInt -> Ptr Word8 -> CSize -> IO CSsize---- See Note: CSsize-foreign import capi safe "HsBase.h write"-   c_safe_write :: CInt -> Ptr Word8 -> CSize -> IO CSsize--foreign import ccall unsafe "HsBase.h __hscore_ftruncate"-   c_ftruncate :: CInt -> COff -> IO CInt--foreign import ccall unsafe "HsBase.h unlink"-   c_unlink :: CString -> IO CInt--foreign import ccall unsafe "HsBase.h getpid"-   c_getpid :: IO CPid--#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)-foreign import capi unsafe "HsBase.h fcntl"-   c_fcntl_read  :: CInt -> CInt -> IO CInt--foreign import capi unsafe "HsBase.h fcntl"-   c_fcntl_write :: CInt -> CInt -> CLong -> IO CInt--foreign import capi unsafe "HsBase.h fcntl"-   c_fcntl_lock  :: CInt -> CInt -> Ptr CFLock -> IO CInt--foreign import ccall unsafe "HsBase.h fork"-   c_fork :: IO CPid--foreign import ccall unsafe "HsBase.h link"-   c_link :: CString -> CString -> IO CInt---- capi is required at least on Android-foreign import capi unsafe "HsBase.h mkfifo"-   c_mkfifo :: CString -> CMode -> IO CInt--foreign import ccall unsafe "HsBase.h pipe"-   c_pipe :: Ptr CInt -> IO CInt--foreign import capi unsafe "signal.h sigemptyset"-   c_sigemptyset :: Ptr CSigset -> IO CInt--foreign import capi unsafe "signal.h sigaddset"-   c_sigaddset :: Ptr CSigset -> CInt -> IO CInt--foreign import capi unsafe "signal.h sigprocmask"-   c_sigprocmask :: CInt -> Ptr CSigset -> Ptr CSigset -> IO CInt---- capi is required at least on Android-foreign import capi unsafe "HsBase.h tcgetattr"-   c_tcgetattr :: CInt -> Ptr CTermios -> IO CInt---- capi is required at least on Android-foreign import capi unsafe "HsBase.h tcsetattr"-   c_tcsetattr :: CInt -> CInt -> Ptr CTermios -> IO CInt--foreign import capi unsafe "HsBase.h utime"-   c_utime :: CString -> Ptr CUtimbuf -> IO CInt--foreign import ccall unsafe "HsBase.h waitpid"-   c_waitpid :: CPid -> Ptr CInt -> CInt -> IO CPid-#endif---- POSIX flags only:-foreign import ccall unsafe "HsBase.h __hscore_o_rdonly" o_RDONLY :: CInt-foreign import ccall unsafe "HsBase.h __hscore_o_wronly" o_WRONLY :: CInt-foreign import ccall unsafe "HsBase.h __hscore_o_rdwr"   o_RDWR   :: CInt-foreign import ccall unsafe "HsBase.h __hscore_o_append" o_APPEND :: CInt-foreign import ccall unsafe "HsBase.h __hscore_o_creat"  o_CREAT  :: CInt-foreign import ccall unsafe "HsBase.h __hscore_o_excl"   o_EXCL   :: CInt-foreign import ccall unsafe "HsBase.h __hscore_o_trunc"  o_TRUNC  :: CInt---- non-POSIX flags.-foreign import ccall unsafe "HsBase.h __hscore_o_noctty"   o_NOCTTY   :: CInt-foreign import ccall unsafe "HsBase.h __hscore_o_nonblock" o_NONBLOCK :: CInt-foreign import ccall unsafe "HsBase.h __hscore_o_binary"   o_BINARY   :: CInt--foreign import capi unsafe "sys/stat.h S_ISREG"  c_s_isreg  :: CMode -> CInt-foreign import capi unsafe "sys/stat.h S_ISCHR"  c_s_ischr  :: CMode -> CInt-foreign import capi unsafe "sys/stat.h S_ISBLK"  c_s_isblk  :: CMode -> CInt-foreign import capi unsafe "sys/stat.h S_ISDIR"  c_s_isdir  :: CMode -> CInt-foreign import capi unsafe "sys/stat.h S_ISFIFO" c_s_isfifo :: CMode -> CInt--s_isreg  :: CMode -> Bool-s_isreg cm = c_s_isreg cm /= 0-s_ischr  :: CMode -> Bool-s_ischr cm = c_s_ischr cm /= 0-s_isblk  :: CMode -> Bool-s_isblk cm = c_s_isblk cm /= 0-s_isdir  :: CMode -> Bool-s_isdir cm = c_s_isdir cm /= 0-s_isfifo :: CMode -> Bool-s_isfifo cm = c_s_isfifo cm /= 0--foreign import ccall unsafe "HsBase.h __hscore_sizeof_stat" sizeof_stat :: Int-foreign import ccall unsafe "HsBase.h __hscore_st_mtime" st_mtime :: Ptr CStat -> IO CTime-#ifdef mingw32_HOST_OS-foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO Int64-#else-foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO COff-#endif-foreign import ccall unsafe "HsBase.h __hscore_st_mode" st_mode :: Ptr CStat -> IO CMode-foreign import ccall unsafe "HsBase.h __hscore_st_dev" st_dev :: Ptr CStat -> IO CDev-foreign import ccall unsafe "HsBase.h __hscore_st_ino" st_ino :: Ptr CStat -> IO CIno--foreign import ccall unsafe "HsBase.h __hscore_echo"         const_echo :: CInt-foreign import ccall unsafe "HsBase.h __hscore_tcsanow"      const_tcsanow :: CInt-foreign import ccall unsafe "HsBase.h __hscore_icanon"       const_icanon :: CInt-foreign import ccall unsafe "HsBase.h __hscore_vmin"         const_vmin   :: CInt-foreign import ccall unsafe "HsBase.h __hscore_vtime"        const_vtime  :: CInt-foreign import ccall unsafe "HsBase.h __hscore_sigttou"      const_sigttou :: CInt-foreign import ccall unsafe "HsBase.h __hscore_sig_block"    const_sig_block :: CInt-foreign import ccall unsafe "HsBase.h __hscore_sig_setmask"  const_sig_setmask :: CInt-foreign import ccall unsafe "HsBase.h __hscore_f_getfl"      const_f_getfl :: CInt-foreign import ccall unsafe "HsBase.h __hscore_f_setfl"      const_f_setfl :: CInt-foreign import ccall unsafe "HsBase.h __hscore_f_setfd"      const_f_setfd :: CInt-foreign import ccall unsafe "HsBase.h __hscore_fd_cloexec"   const_fd_cloexec :: CLong--#if defined(HTYPE_TCFLAG_T)-foreign import ccall unsafe "HsBase.h __hscore_sizeof_termios"  sizeof_termios :: Int-foreign import ccall unsafe "HsBase.h __hscore_sizeof_sigset_t" sizeof_sigset_t :: Int--foreign import ccall unsafe "HsBase.h __hscore_lflag" c_lflag :: Ptr CTermios -> IO CTcflag-foreign import ccall unsafe "HsBase.h __hscore_poke_lflag" poke_c_lflag :: Ptr CTermios -> CTcflag -> IO ()-foreign import ccall unsafe "HsBase.h __hscore_ptr_c_cc" ptr_c_cc  :: Ptr CTermios -> IO (Ptr Word8)-#endif--s_issock :: CMode -> Bool-#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)-s_issock cmode = c_s_issock cmode /= 0-foreign import capi unsafe "sys/stat.h S_ISSOCK" c_s_issock :: CMode -> CInt-#else-s_issock _ = False-#endif--foreign import ccall unsafe "__hscore_bufsiz"  dEFAULT_BUFFER_SIZE :: Int-foreign import capi  unsafe "stdio.h value SEEK_CUR" sEEK_CUR :: CInt-foreign import capi  unsafe "stdio.h value SEEK_SET" sEEK_SET :: CInt-foreign import capi  unsafe "stdio.h value SEEK_END" sEEK_END :: CInt--{--Note: CSsize--On Win64, ssize_t is 64 bit, but functions like read return 32 bit-ints. The CAPI wrapper means the C compiler takes care of doing all-the necessary casting.--When using ccall instead, when the functions failed with -1, we thought-they were returning with 4294967295, and so didn't throw an exception.-This lead to a segfault in echo001(ghci).--}-
− System/Posix/Types.hs
@@ -1,178 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE CPP-           , NoImplicitPrelude-           , MagicHash-           , GeneralizedNewtypeDeriving-  #-}-{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}---------------------------------------------------------------------------------- |--- Module      :  System.Posix.Types--- Copyright   :  (c) The University of Glasgow 2002--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  non-portable (requires POSIX)------ POSIX data types: Haskell equivalents of the types defined by the--- @\<sys\/types.h>@ C header on a POSIX system.----------------------------------------------------------------------------------#include "HsBaseConfig.h"--module System.Posix.Types (--  -- * POSIX data types-#if defined(HTYPE_DEV_T)-  CDev(..),-#endif-#if defined(HTYPE_INO_T)-  CIno(..),-#endif-#if defined(HTYPE_MODE_T)-  CMode(..),-#endif-#if defined(HTYPE_OFF_T)-  COff(..),-#endif-#if defined(HTYPE_PID_T)-  CPid(..),-#endif-#if defined(HTYPE_SSIZE_T)-  CSsize(..),-#endif--#if defined(HTYPE_GID_T)-  CGid(..),-#endif-#if defined(HTYPE_NLINK_T)-  CNlink(..),-#endif-#if defined(HTYPE_UID_T)-  CUid(..),-#endif-#if defined(HTYPE_CC_T)-  CCc(..),-#endif-#if defined(HTYPE_SPEED_T)-  CSpeed(..),-#endif-#if defined(HTYPE_TCFLAG_T)-  CTcflag(..),-#endif-#if defined(HTYPE_RLIM_T)-  CRLim(..),-#endif--  Fd(..),--#if defined(HTYPE_NLINK_T)-  LinkCount,-#endif-#if defined(HTYPE_UID_T)-  UserID,-#endif-#if defined(HTYPE_GID_T)-  GroupID,-#endif--  ByteCount,-  ClockTick,-  EpochTime,-  FileOffset,-  ProcessID,-  ProcessGroupID,-  DeviceID,-  FileID,-  FileMode,-  Limit- ) where--import Foreign-import Foreign.C-import Data.Typeable--- import Data.Bits--import GHC.Base-import GHC.Enum-import GHC.Num-import GHC.Real--- import GHC.Prim-import GHC.Read-import GHC.Show--#include "CTypes.h"--#if defined(HTYPE_DEV_T)-INTEGRAL_TYPE(CDev,HTYPE_DEV_T)-#endif-#if defined(HTYPE_INO_T)-INTEGRAL_TYPE(CIno,HTYPE_INO_T)-#endif-#if defined(HTYPE_MODE_T)-INTEGRAL_TYPE_WITH_CTYPE(CMode,mode_t,HTYPE_MODE_T)-#endif-#if defined(HTYPE_OFF_T)-INTEGRAL_TYPE(COff,HTYPE_OFF_T)-#endif-#if defined(HTYPE_PID_T)-INTEGRAL_TYPE(CPid,HTYPE_PID_T)-#endif--#if defined(HTYPE_SSIZE_T)-INTEGRAL_TYPE(CSsize,HTYPE_SSIZE_T)-#endif--#if defined(HTYPE_GID_T)-INTEGRAL_TYPE(CGid,HTYPE_GID_T)-#endif-#if defined(HTYPE_NLINK_T)-INTEGRAL_TYPE(CNlink,HTYPE_NLINK_T)-#endif--#if defined(HTYPE_UID_T)-INTEGRAL_TYPE(CUid,HTYPE_UID_T)-#endif-#if defined(HTYPE_CC_T)-ARITHMETIC_TYPE(CCc,HTYPE_CC_T)-#endif-#if defined(HTYPE_SPEED_T)-ARITHMETIC_TYPE(CSpeed,HTYPE_SPEED_T)-#endif-#if defined(HTYPE_TCFLAG_T)-INTEGRAL_TYPE(CTcflag,HTYPE_TCFLAG_T)-#endif-#if defined(HTYPE_RLIM_T)-INTEGRAL_TYPE(CRLim,HTYPE_RLIM_T)-#endif---- ToDo: blksize_t, clockid_t, blkcnt_t, fsblkcnt_t, fsfilcnt_t, id_t, key_t--- suseconds_t, timer_t, useconds_t---- Make an Fd type rather than using CInt everywhere-INTEGRAL_TYPE(Fd,CInt)---- nicer names, and backwards compatibility with POSIX library:-#if defined(HTYPE_NLINK_T)-type LinkCount      = CNlink-#endif-#if defined(HTYPE_UID_T)-type UserID         = CUid-#endif-#if defined(HTYPE_GID_T)-type GroupID        = CGid-#endif--type ByteCount      = CSize-type ClockTick      = CClock-type EpochTime      = CTime-type DeviceID       = CDev-type FileID         = CIno-type FileMode       = CMode-type ProcessID      = CPid-type FileOffset     = COff-type ProcessGroupID = CPid-type Limit          = CLong-
− System/Timeout.hs
@@ -1,122 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE CPP #-}-{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}------------------------------------------------------------------------------------ |--- Module      :  System.Timeout--- Copyright   :  (c) The University of Glasgow 2007--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  non-portable------ Attach a timeout event to arbitrary 'IO' computations.-------------------------------------------------------------------------------------module System.Timeout ( timeout ) where--#ifndef mingw32_HOST_OS-import Control.Monad-import GHC.Event           (getSystemTimerManager,-                            registerTimeout, unregisterTimeout)-#endif--import Control.Concurrent-import Control.Exception   (Exception(..), handleJust, bracket,-                            uninterruptibleMask_,-                            asyncExceptionToException,-                            asyncExceptionFromException)-import Data.Typeable-import Data.Unique         (Unique, newUnique)---- An internal type that is thrown as a dynamic exception to--- interrupt the running IO computation when the timeout has--- expired.--newtype Timeout = Timeout Unique deriving (Eq, Typeable)--instance Show Timeout where-    show _ = "<<timeout>>"---- Timeout is a child of SomeAsyncException-instance Exception Timeout where-  toException = asyncExceptionToException-  fromException = asyncExceptionFromException---- |Wrap an 'IO' computation to time out and return @Nothing@ in case no result--- is available within @n@ microseconds (@1\/10^6@ seconds). In case a result--- is available before the timeout expires, @Just a@ is returned. A negative--- timeout interval means \"wait indefinitely\". When specifying long timeouts,--- be careful not to exceed @maxBound :: Int@.------ The design of this combinator was guided by the objective that @timeout n f@--- should behave exactly the same as @f@ as long as @f@ doesn't time out. This--- means that @f@ has the same 'myThreadId' it would have without the timeout--- wrapper. Any exceptions @f@ might throw cancel the timeout and propagate--- further up. It also possible for @f@ to receive exceptions thrown to it by--- another thread.------ A tricky implementation detail is the question of how to abort an @IO@--- computation. This combinator relies on asynchronous exceptions internally.--- The technique works very well for computations executing inside of the--- Haskell runtime system, but it doesn't work at all for non-Haskell code.--- Foreign function calls, for example, cannot be timed out with this--- combinator simply because an arbitrary C function cannot receive--- asynchronous exceptions. When @timeout@ is used to wrap an FFI call that--- blocks, no timeout event can be delivered until the FFI call returns, which--- pretty much negates the purpose of the combinator. In practice, however,--- this limitation is less severe than it may sound. Standard I\/O functions--- like 'System.IO.hGetBuf', 'System.IO.hPutBuf', Network.Socket.accept, or--- 'System.IO.hWaitForInput' appear to be blocking, but they really don't--- because the runtime system uses scheduling mechanisms like @select(2)@ to--- perform asynchronous I\/O, so it is possible to interrupt standard socket--- I\/O or file I\/O using this combinator.--timeout :: Int -> IO a -> IO (Maybe a)-timeout n f-    | n <  0    = fmap Just f-    | n == 0    = return Nothing-#ifndef mingw32_HOST_OS-    | rtsSupportsBoundThreads = do-        -- In the threaded RTS, we use the Timer Manager to delay the-        -- (fairly expensive) 'forkIO' call until the timeout has expired.-        ---        -- An additional thread is required for the actual delivery of-        -- the Timeout exception because killThread (or another throwTo)-        -- is the only way to reliably interrupt a throwTo in flight.-        pid <- myThreadId-        ex  <- fmap Timeout newUnique-        tm  <- getSystemTimerManager-        -- 'lock' synchronizes the timeout handler and the main thread:-        --  * the main thread can disable the handler by writing to 'lock';-        --  * the handler communicates the spawned thread's id through 'lock'.-        -- These two cases are mutually exclusive.-        lock <- newEmptyMVar-        let handleTimeout = do-                v <- isEmptyMVar lock-                when v $ void $ forkIOWithUnmask $ \unmask -> unmask $ do-                    v2 <- tryPutMVar lock =<< myThreadId-                    when v2 $ throwTo pid ex-            cleanupTimeout key = uninterruptibleMask_ $ do-                v <- tryPutMVar lock undefined-                if v then unregisterTimeout tm key-                     else takeMVar lock >>= killThread-        handleJust (\e -> if e == ex then Just () else Nothing)-                   (\_ -> return Nothing)-                   (bracket (registerTimeout tm n handleTimeout)-                            cleanupTimeout-                            (\_ -> fmap Just f))-#endif-    | otherwise = do-        pid <- myThreadId-        ex  <- fmap Timeout newUnique-        handleJust (\e -> if e == ex then Just () else Nothing)-                   (\_ -> return Nothing)-                   (bracket (forkIOWithUnmask $ \unmask ->-                                 unmask $ threadDelay n >> throwTo pid ex)-                            (uninterruptibleMask_ . killThread)-                            (\_ -> fmap Just f))-        -- #7719 explains why we need uninterruptibleMask_ above.
− Text/ParserCombinators/ReadP.hs
@@ -1,510 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}-{-# LANGUAGE RankNTypes #-}-{-# LANGUAGE MagicHash #-}-{-# LANGUAGE DeriveFunctor #-}---------------------------------------------------------------------------------- |--- Module      :  Text.ParserCombinators.ReadP--- Copyright   :  (c) The University of Glasgow 2002--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  non-portable (local universal quantification)------ This is a library of parser combinators, originally written by Koen Claessen.--- It parses all alternatives in parallel, so it never keeps hold of--- the beginning of the input string, a common source of space leaks with--- other parsers.  The '(+++)' choice combinator is genuinely commutative;--- it makes no difference which branch is \"shorter\".---------------------------------------------------------------------------------module Text.ParserCombinators.ReadP-  (-  -- * The 'ReadP' type-  ReadP,--  -- * Primitive operations-  get,-  look,-  (+++),-  (<++),-  gather,--  -- * Other operations-  pfail,-  eof,-  satisfy,-  char,-  string,-  munch,-  munch1,-  skipSpaces,-  choice,-  count,-  between,-  option,-  optional,-  many,-  many1,-  skipMany,-  skipMany1,-  sepBy,-  sepBy1,-  endBy,-  endBy1,-  chainr,-  chainl,-  chainl1,-  chainr1,-  manyTill,--  -- * Running a parser-  ReadS,-  readP_to_S,-  readS_to_P,--  -- * Properties-  -- $properties-  )- where--import GHC.Unicode ( isSpace )-import GHC.List ( replicate, null )-import GHC.Base hiding ( many )--infixr 5 +++, <++----------------------------------------------------------------------------- ReadS---- | A parser for a type @a@, represented as a function that takes a--- 'String' and returns a list of possible parses as @(a,'String')@ pairs.------ Note that this kind of backtracking parser is very inefficient;--- reading a large structure may be quite slow (cf 'ReadP').-type ReadS a = String -> [(a,String)]---- ------------------------------------------------------------------------------ The P type--- is representation type -- should be kept abstract--data P a-  = Get (Char -> P a)-  | Look (String -> P a)-  | Fail-  | Result a (P a)-  | Final [(a,String)] -- invariant: list is non-empty!-  deriving Functor---- Monad, MonadPlus--instance Applicative P where-  pure  = return-  (<*>) = ap--instance MonadPlus P where-  mzero = empty-  mplus = (<|>)--instance Monad P where-  return x = Result x Fail--  (Get f)      >>= k = Get (\c -> f c >>= k)-  (Look f)     >>= k = Look (\s -> f s >>= k)-  Fail         >>= _ = Fail-  (Result x p) >>= k = k x <|> (p >>= k)-  (Final r)    >>= k = final [ys' | (x,s) <- r, ys' <- run (k x) s]--  fail _ = Fail--instance Alternative P where-  empty = Fail--  -- most common case: two gets are combined-  Get f1     <|> Get f2     = Get (\c -> f1 c <|> f2 c)--  -- results are delivered as soon as possible-  Result x p <|> q          = Result x (p <|> q)-  p          <|> Result x q = Result x (p <|> q)--  -- fail disappears-  Fail       <|> p          = p-  p          <|> Fail       = p--  -- two finals are combined-  -- final + look becomes one look and one final (=optimization)-  -- final + sthg else becomes one look and one final-  Final r    <|> Final t    = Final (r ++ t)-  Final r    <|> Look f     = Look (\s -> Final (r ++ run (f s) s))-  Final r    <|> p          = Look (\s -> Final (r ++ run p s))-  Look f     <|> Final r    = Look (\s -> Final (run (f s) s ++ r))-  p          <|> Final r    = Look (\s -> Final (run p s ++ r))--  -- two looks are combined (=optimization)-  -- look + sthg else floats upwards-  Look f     <|> Look g     = Look (\s -> f s <|> g s)-  Look f     <|> p          = Look (\s -> f s <|> p)-  p          <|> Look f     = Look (\s -> p <|> f s)---- ------------------------------------------------------------------------------ The ReadP type--newtype ReadP a = R (forall b . (a -> P b) -> P b)---- Functor, Monad, MonadPlus--instance Functor ReadP where-  fmap h (R f) = R (\k -> f (k . h))--instance Applicative ReadP where-    pure = return-    (<*>) = ap--instance Monad ReadP where-  return x  = R (\k -> k x)-  fail _    = R (\_ -> Fail)-  R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k))--instance Alternative ReadP where-    empty = mzero-    (<|>) = mplus--instance MonadPlus ReadP where-  mzero = pfail-  mplus = (+++)---- ------------------------------------------------------------------------------ Operations over P--final :: [(a,String)] -> P a--- Maintains invariant for Final constructor-final [] = Fail-final r  = Final r--run :: P a -> ReadS a-run (Get f)      (c:s) = run (f c) s-run (Look f)     s     = run (f s) s-run (Result x p) s     = (x,s) : run p s-run (Final r)    _     = r-run _            _     = []---- ------------------------------------------------------------------------------ Operations over ReadP--get :: ReadP Char--- ^ Consumes and returns the next character.---   Fails if there is no input left.-get = R Get--look :: ReadP String--- ^ Look-ahead: returns the part of the input that is left, without---   consuming it.-look = R Look--pfail :: ReadP a--- ^ Always fails.-pfail = R (\_ -> Fail)--(+++) :: ReadP a -> ReadP a -> ReadP a--- ^ Symmetric choice.-R f1 +++ R f2 = R (\k -> f1 k <|> f2 k)--(<++) :: ReadP a -> ReadP a -> ReadP a--- ^ Local, exclusive, left-biased choice: If left parser---   locally produces any result at all, then right parser is---   not used.-R f0 <++ q =-  do s <- look-     probe (f0 return) s 0#- where-  probe (Get f)        (c:s) n = probe (f c) s (n+#1#)-  probe (Look f)       s     n = probe (f s) s n-  probe p@(Result _ _) _     n = discard n >> R (p >>=)-  probe (Final r)      _     _ = R (Final r >>=)-  probe _              _     _ = q--  discard 0# = return ()-  discard n  = get >> discard (n-#1#)--gather :: ReadP a -> ReadP (String, a)--- ^ Transforms a parser into one that does the same, but---   in addition returns the exact characters read.---   IMPORTANT NOTE: 'gather' gives a runtime error if its first argument---   is built using any occurrences of readS_to_P.-gather (R m)-  = R (\k -> gath id (m (\a -> return (\s -> k (s,a)))))- where-  gath :: (String -> String) -> P (String -> P b) -> P b-  gath l (Get f)      = Get (\c -> gath (l.(c:)) (f c))-  gath _ Fail         = Fail-  gath l (Look f)     = Look (\s -> gath l (f s))-  gath l (Result k p) = k (l []) <|> gath l p-  gath _ (Final _)    = error "do not use readS_to_P in gather!"---- ------------------------------------------------------------------------------ Derived operations--satisfy :: (Char -> Bool) -> ReadP Char--- ^ Consumes and returns the next character, if it satisfies the---   specified predicate.-satisfy p = do c <- get; if p c then return c else pfail--char :: Char -> ReadP Char--- ^ Parses and returns the specified character.-char c = satisfy (c ==)--eof :: ReadP ()--- ^ Succeeds iff we are at the end of input-eof = do { s <- look-         ; if null s then return ()-                     else pfail }--string :: String -> ReadP String--- ^ Parses and returns the specified string.-string this = do s <- look; scan this s- where-  scan []     _               = do return this-  scan (x:xs) (y:ys) | x == y = do _ <- get; scan xs ys-  scan _      _               = do pfail--munch :: (Char -> Bool) -> ReadP String--- ^ Parses the first zero or more characters satisfying the predicate.---   Always succeds, exactly once having consumed all the characters---   Hence NOT the same as (many (satisfy p))-munch p =-  do s <- look-     scan s- where-  scan (c:cs) | p c = do _ <- get; s <- scan cs; return (c:s)-  scan _            = do return ""--munch1 :: (Char -> Bool) -> ReadP String--- ^ Parses the first one or more characters satisfying the predicate.---   Fails if none, else succeeds exactly once having consumed all the characters---   Hence NOT the same as (many1 (satisfy p))-munch1 p =-  do c <- get-     if p c then do s <- munch p; return (c:s)-            else pfail--choice :: [ReadP a] -> ReadP a--- ^ Combines all parsers in the specified list.-choice []     = pfail-choice [p]    = p-choice (p:ps) = p +++ choice ps--skipSpaces :: ReadP ()--- ^ Skips all whitespace.-skipSpaces =-  do s <- look-     skip s- where-  skip (c:s) | isSpace c = do _ <- get; skip s-  skip _                 = do return ()--count :: Int -> ReadP a -> ReadP [a]--- ^ @count n p@ parses @n@ occurrences of @p@ in sequence. A list of---   results is returned.-count n p = sequence (replicate n p)--between :: ReadP open -> ReadP close -> ReadP a -> ReadP a--- ^ @between open close p@ parses @open@, followed by @p@ and finally---   @close@. Only the value of @p@ is returned.-between open close p = do _ <- open-                          x <- p-                          _ <- close-                          return x--option :: a -> ReadP a -> ReadP a--- ^ @option x p@ will either parse @p@ or return @x@ without consuming---   any input.-option x p = p +++ return x--optional :: ReadP a -> ReadP ()--- ^ @optional p@ optionally parses @p@ and always returns @()@.-optional p = (p >> return ()) +++ return ()--many :: ReadP a -> ReadP [a]--- ^ Parses zero or more occurrences of the given parser.-many p = return [] +++ many1 p--many1 :: ReadP a -> ReadP [a]--- ^ Parses one or more occurrences of the given parser.-many1 p = liftM2 (:) p (many p)--skipMany :: ReadP a -> ReadP ()--- ^ Like 'many', but discards the result.-skipMany p = many p >> return ()--skipMany1 :: ReadP a -> ReadP ()--- ^ Like 'many1', but discards the result.-skipMany1 p = p >> skipMany p--sepBy :: ReadP a -> ReadP sep -> ReadP [a]--- ^ @sepBy p sep@ parses zero or more occurrences of @p@, separated by @sep@.---   Returns a list of values returned by @p@.-sepBy p sep = sepBy1 p sep +++ return []--sepBy1 :: ReadP a -> ReadP sep -> ReadP [a]--- ^ @sepBy1 p sep@ parses one or more occurrences of @p@, separated by @sep@.---   Returns a list of values returned by @p@.-sepBy1 p sep = liftM2 (:) p (many (sep >> p))--endBy :: ReadP a -> ReadP sep -> ReadP [a]--- ^ @endBy p sep@ parses zero or more occurrences of @p@, separated and ended---   by @sep@.-endBy p sep = many (do x <- p ; _ <- sep ; return x)--endBy1 :: ReadP a -> ReadP sep -> ReadP [a]--- ^ @endBy p sep@ parses one or more occurrences of @p@, separated and ended---   by @sep@.-endBy1 p sep = many1 (do x <- p ; _ <- sep ; return x)--chainr :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a--- ^ @chainr p op x@ parses zero or more occurrences of @p@, separated by @op@.---   Returns a value produced by a /right/ associative application of all---   functions returned by @op@. If there are no occurrences of @p@, @x@ is---   returned.-chainr p op x = chainr1 p op +++ return x--chainl :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a--- ^ @chainl p op x@ parses zero or more occurrences of @p@, separated by @op@.---   Returns a value produced by a /left/ associative application of all---   functions returned by @op@. If there are no occurrences of @p@, @x@ is---   returned.-chainl p op x = chainl1 p op +++ return x--chainr1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a--- ^ Like 'chainr', but parses one or more occurrences of @p@.-chainr1 p op = scan-  where scan   = p >>= rest-        rest x = do f <- op-                    y <- scan-                    return (f x y)-                 +++ return x--chainl1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a--- ^ Like 'chainl', but parses one or more occurrences of @p@.-chainl1 p op = p >>= rest-  where rest x = do f <- op-                    y <- p-                    rest (f x y)-                 +++ return x--manyTill :: ReadP a -> ReadP end -> ReadP [a]--- ^ @manyTill p end@ parses zero or more occurrences of @p@, until @end@---   succeeds. Returns a list of values returned by @p@.-manyTill p end = scan-  where scan = (end >> return []) <++ (liftM2 (:) p scan)---- ------------------------------------------------------------------------------ Converting between ReadP and Read--readP_to_S :: ReadP a -> ReadS a--- ^ Converts a parser into a Haskell ReadS-style function.---   This is the main way in which you can \"run\" a 'ReadP' parser:---   the expanded type is--- @ readP_to_S :: ReadP a -> String -> [(a,String)] @-readP_to_S (R f) = run (f return)--readS_to_P :: ReadS a -> ReadP a--- ^ Converts a Haskell ReadS-style function into a parser.---   Warning: This introduces local backtracking in the resulting---   parser, and therefore a possible inefficiency.-readS_to_P r =-  R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s']))---- ------------------------------------------------------------------------------ QuickCheck properties that hold for the combinators--{- $properties-The following are QuickCheck specifications of what the combinators do.-These can be seen as formal specifications of the behavior of the-combinators.--We use bags to give semantics to the combinators.-->  type Bag a = [a]--Equality on bags does not care about the order of elements.-->  (=~) :: Ord a => Bag a -> Bag a -> Bool->  xs =~ ys = sort xs == sort ys--A special equality operator to avoid unresolved overloading-when testing the properties.-->  (=~.) :: Bag (Int,String) -> Bag (Int,String) -> Bool->  (=~.) = (=~)--Here follow the properties:-->  prop_Get_Nil =->    readP_to_S get [] =~ []->->  prop_Get_Cons c s =->    readP_to_S get (c:s) =~ [(c,s)]->->  prop_Look s =->    readP_to_S look s =~ [(s,s)]->->  prop_Fail s =->    readP_to_S pfail s =~. []->->  prop_Return x s =->    readP_to_S (return x) s =~. [(x,s)]->->  prop_Bind p k s =->    readP_to_S (p >>= k) s =~.->      [ ys''->      | (x,s') <- readP_to_S p s->      , ys''   <- readP_to_S (k (x::Int)) s'->      ]->->  prop_Plus p q s =->    readP_to_S (p +++ q) s =~.->      (readP_to_S p s ++ readP_to_S q s)->->  prop_LeftPlus p q s =->    readP_to_S (p <++ q) s =~.->      (readP_to_S p s +<+ readP_to_S q s)->   where->    [] +<+ ys = ys->    xs +<+ _  = xs->->  prop_Gather s =->    forAll readPWithoutReadS $ \p ->->      readP_to_S (gather p) s =~->        [ ((pre,x::Int),s')->        | (x,s') <- readP_to_S p s->        , let pre = take (length s - length s') s->        ]->->  prop_String_Yes this s =->    readP_to_S (string this) (this ++ s) =~->      [(this,s)]->->  prop_String_Maybe this s =->    readP_to_S (string this) s =~->      [(this, drop (length this) s) | this `isPrefixOf` s]->->  prop_Munch p s =->    readP_to_S (munch p) s =~->      [(takeWhile p s, dropWhile p s)]->->  prop_Munch1 p s =->    readP_to_S (munch1 p) s =~->      [(res,s') | let (res,s') = (takeWhile p s, dropWhile p s), not (null res)]->->  prop_Choice ps s =->    readP_to_S (choice ps) s =~.->      readP_to_S (foldr (+++) pfail ps) s->->  prop_ReadS r s =->    readP_to_S (readS_to_P r) s =~. r s--}-
− Text/ParserCombinators/ReadPrec.hs
@@ -1,169 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Text.ParserCombinators.ReadPrec--- Copyright   :  (c) The University of Glasgow 2002--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  non-portable (uses Text.ParserCombinators.ReadP)------ This library defines parser combinators for precedence parsing.---------------------------------------------------------------------------------module Text.ParserCombinators.ReadPrec-  (-  ReadPrec,--  -- * Precedences-  Prec,-  minPrec,--  -- * Precedence operations-  lift,-  prec,-  step,-  reset,--  -- * Other operations-  -- | All are based directly on their similarly-named 'ReadP' counterparts.-  get,-  look,-  (+++),-  (<++),-  pfail,-  choice,--  -- * Converters-  readPrec_to_P,-  readP_to_Prec,-  readPrec_to_S,-  readS_to_Prec,-  )- where---import Text.ParserCombinators.ReadP-  ( ReadP-  , ReadS-  , readP_to_S-  , readS_to_P-  )--import qualified Text.ParserCombinators.ReadP as ReadP-  ( get-  , look-  , (+++), (<++)-  , pfail-  )--import GHC.Num( Num(..) )-import GHC.Base---- ------------------------------------------------------------------------------ The readPrec type--newtype ReadPrec a = P (Prec -> ReadP a)---- Functor, Monad, MonadPlus--instance Functor ReadPrec where-  fmap h (P f) = P (\n -> fmap h (f n))--instance Applicative ReadPrec where-    pure = return-    (<*>) = ap--instance Monad ReadPrec where-  return x  = P (\_ -> return x)-  fail s    = P (\_ -> fail s)-  P f >>= k = P (\n -> do a <- f n; let P f' = k a in f' n)--instance MonadPlus ReadPrec where-  mzero = pfail-  mplus = (+++)--instance Alternative ReadPrec where-    empty = mzero-    (<|>) = mplus---- precedences-type Prec = Int--minPrec :: Prec-minPrec = 0---- ------------------------------------------------------------------------------ Operations over ReadPrec--lift :: ReadP a -> ReadPrec a--- ^ Lift a precedence-insensitive 'ReadP' to a 'ReadPrec'.-lift m = P (\_ -> m)--step :: ReadPrec a -> ReadPrec a--- ^ Increases the precedence context by one.-step (P f) = P (\n -> f (n+1))--reset :: ReadPrec a -> ReadPrec a--- ^ Resets the precedence context to zero.-reset (P f) = P (\_ -> f minPrec)--prec :: Prec -> ReadPrec a -> ReadPrec a--- ^ @(prec n p)@ checks whether the precedence context is---   less than or equal to @n@, and------   * if not, fails------   * if so, parses @p@ in context @n@.-prec n (P f) = P (\c -> if c <= n then f n else ReadP.pfail)---- ------------------------------------------------------------------------------ Derived operations--get :: ReadPrec Char--- ^ Consumes and returns the next character.---   Fails if there is no input left.-get = lift ReadP.get--look :: ReadPrec String--- ^ Look-ahead: returns the part of the input that is left, without---   consuming it.-look = lift ReadP.look--(+++) :: ReadPrec a -> ReadPrec a -> ReadPrec a--- ^ Symmetric choice.-P f1 +++ P f2 = P (\n -> f1 n ReadP.+++ f2 n)--(<++) :: ReadPrec a -> ReadPrec a -> ReadPrec a--- ^ Local, exclusive, left-biased choice: If left parser---   locally produces any result at all, then right parser is---   not used.-P f1 <++ P f2 = P (\n -> f1 n ReadP.<++ f2 n)--pfail :: ReadPrec a--- ^ Always fails.-pfail = lift ReadP.pfail--choice :: [ReadPrec a] -> ReadPrec a--- ^ Combines all parsers in the specified list.-choice ps = foldr (+++) pfail ps---- ------------------------------------------------------------------------------ Converting between ReadPrec and Read--readPrec_to_P :: ReadPrec a -> (Int -> ReadP a)-readPrec_to_P (P f) = f--readP_to_Prec :: (Int -> ReadP a) -> ReadPrec a-readP_to_Prec f = P f--readPrec_to_S :: ReadPrec a -> (Int -> ReadS a)-readPrec_to_S (P f) n = readP_to_S (f n)--readS_to_Prec :: (Int -> ReadS a) -> ReadPrec a-readS_to_Prec f = P (\n -> readS_to_P (f n))-
− Text/Printf.hs
@@ -1,898 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE GADTs #-}---------------------------------------------------------------------------------- |--- Module      :  Text.Printf--- Copyright   :  (c) Lennart Augustsson and Bart Massey 2013--- License     :  BSD-style (see the file LICENSE in this distribution)------ Maintainer  :  Bart Massey <bart@cs.pdx.edu>--- Stability   :  provisional--- Portability :  portable------ A C @printf(3)@-like formatter. This version has been--- extended by Bart Massey as per the recommendations of--- John Meacham and Simon Marlow--- \<<http://comments.gmane.org/gmane.comp.lang.haskell.libraries/4726>\>--- to support extensible formatting for new datatypes.  It--- has also been extended to support almost all C--- @printf(3)@ syntax.--------------------------------------------------------------------------------module Text.Printf(--- * Printing Functions-   printf, hPrintf,--- * Extending To New Types------ | This 'printf' can be extended to format types--- other than those provided for by default. This--- is done by instancing 'PrintfArg' and providing--- a 'formatArg' for the type. It is possible to--- provide a 'parseFormat' to process type-specific--- modifiers, but the default instance is usually--- the best choice.------ For example:------ > instance PrintfArg () where--- >   formatArg x fmt | fmtChar (vFmt 'U' fmt) == 'U' =--- >     formatString "()" (fmt { fmtChar = 's', fmtPrecision = Nothing })--- >   formatArg _ fmt = errorBadFormat $ fmtChar fmt--- >--- > main :: IO ()--- > main = printf "[%-3.1U]\n" ()------ prints \"@[() ]@\". Note the use of 'formatString' to--- take care of field formatting specifications in a convenient--- way.-   PrintfArg(..),-   FieldFormatter,-   FieldFormat(..),-   FormatAdjustment(..), FormatSign(..),-   vFmt,--- ** Handling Type-specific Modifiers------ | In the unlikely case that modifier characters of--- some kind are desirable for a user-provided type,--- a 'ModifierParser' can be provided to process these--- characters. The resulting modifiers will appear in--- the 'FieldFormat' for use by the type-specific formatter.-   ModifierParser, FormatParse(..),--- ** Standard Formatters------ | These formatters for standard types are provided for--- convenience in writting new type-specific formatters:--- a common pattern is to throw to 'formatString' or--- 'formatInteger' to do most of the format handling for--- a new type.-   formatString, formatChar, formatInt,-   formatInteger, formatRealFloat,--- ** Raising Errors------ | These functions are used internally to raise various--- errors, and are exported for use by new type-specific--- formatters.-  errorBadFormat, errorShortFormat, errorMissingArgument,-  errorBadArgument,-  perror,--- * Implementation Internals--- | These types are needed for implementing processing--- variable numbers of arguments to 'printf' and 'hPrintf'.--- Their implementation is intentionally not visible from--- this module. If you attempt to pass an argument of a type--- which is not an instance of the appropriate class to--- 'printf' or 'hPrintf', then the compiler will report it--- as a missing instance of 'PrintfArg'.  (All 'PrintfArg'--- instances are 'PrintfType' instances.)-  PrintfType, HPrintfType,--- | This class is needed as a Haskell98 compatibility--- workaround for the lack of FlexibleInstances.-  IsChar(..)-) where--import Data.Char-import Data.Int-import Data.List-import Data.Word-import Numeric-import Numeric.Natural-import System.IO------------------------- | Format a variable number of arguments with the C-style formatting string.--- The return value is either 'String' or @('IO' a)@ (which--- should be @('IO' '()')@, but Haskell's type system--- makes this hard).------ The format string consists of ordinary characters and--- /conversion specifications/, which specify how to format--- one of the arguments to 'printf' in the output string. A--- format specification is introduced by the @%@ character;--- this character can be self-escaped into the format string--- using @%%@. A format specification ends with a /format--- character/ that provides the primary information about--- how to format the value. The rest of the conversion--- specification is optional.  In order, one may have flag--- characters, a width specifier, a precision specifier, and--- type-specific modifier characters.------ Unlike C @printf(3)@, the formatting of this 'printf'--- is driven by the argument type; formatting is type specific. The--- types formatted by 'printf' \"out of the box\" are:------   * 'Integral' types, including 'Char'------   * 'String'------   * 'RealFloat' types------ 'printf' is also extensible to support other types: see below.------ A conversion specification begins with the--- character @%@, followed by zero or more of the following flags:------ >    -      left adjust (default is right adjust)--- >    +      always use a sign (+ or -) for signed conversions--- >    space  leading space for positive numbers in signed conversions--- >    0      pad with zeros rather than spaces--- >    #      use an \"alternate form\": see below------ When both flags are given, @-@ overrides @0@ and @+@ overrides space.--- A negative width specifier in a @*@ conversion is treated as--- positive but implies the left adjust flag.------ The \"alternate form\" for unsigned radix conversions is--- as in C @printf(3)@:------ >    %o           prefix with a leading 0 if needed--- >    %x           prefix with a leading 0x if nonzero--- >    %X           prefix with a leading 0X if nonzero--- >    %b           prefix with a leading 0b if nonzero--- >    %[eEfFgG]    ensure that the number contains a decimal point------ Any flags are followed optionally by a field width:------ >    num    field width--- >    *      as num, but taken from argument list------ The field width is a minimum, not a maximum: it will be--- expanded as needed to avoid mutilating a value.------ Any field width is followed optionally by a precision:------ >    .num   precision--- >    .      same as .0--- >    .*     as num, but taken from argument list------ Negative precision is taken as 0. The meaning of the--- precision depends on the conversion type.------ >    Integral    minimum number of digits to show--- >    RealFloat   number of digits after the decimal point--- >    String      maximum number of characters------ The precision for Integral types is accomplished by zero-padding.--- If both precision and zero-pad are given for an Integral field,--- the zero-pad is ignored.------ Any precision is followed optionally for Integral types--- by a width modifier; the only use of this modifier being--- to set the implicit size of the operand for conversion of--- a negative operand to unsigned:------ >    hh     Int8--- >    h      Int16--- >    l      Int32--- >    ll     Int64--- >    L      Int64------ The specification ends with a format character:------ >    c      character               Integral--- >    d      decimal                 Integral--- >    o      octal                   Integral--- >    x      hexadecimal             Integral--- >    X      hexadecimal             Integral--- >    b      binary                  Integral--- >    u      unsigned decimal        Integral--- >    f      floating point          RealFloat--- >    F      floating point          RealFloat--- >    g      general format float    RealFloat--- >    G      general format float    RealFloat--- >    e      exponent format float   RealFloat--- >    E      exponent format float   RealFloat--- >    s      string                  String--- >    v      default format          any type------ The \"%v\" specifier is provided for all built-in types,--- and should be provided for user-defined type formatters--- as well. It picks a \"best\" representation for the given--- type. For the built-in types the \"%v\" specifier is--- converted as follows:------ >    c      Char--- >    u      other unsigned Integral--- >    d      other signed Integral--- >    g      RealFloat--- >    s      String------ Mismatch between the argument types and the format--- string, as well as any other syntactic or semantic errors--- in the format string, will cause an exception to be--- thrown at runtime.------ Note that the formatting for 'RealFloat' types is--- currently a bit different from that of C @printf(3)@,--- conforming instead to 'Numeric.showEFloat',--- 'Numeric.showFFloat' and 'Numeric.showGFloat' (and their--- alternate versions 'Numeric.showFFloatAlt' and--- 'Numeric.showGFloatAlt'). This is hard to fix: the fixed--- versions would format in a backward-incompatible way.--- In any case the Haskell behavior is generally more--- sensible than the C behavior.  A brief summary of some--- key differences:------ * Haskell 'printf' never uses the default \"6-digit\" precision---   used by C printf.------ * Haskell 'printf' treats the \"precision\" specifier as---   indicating the number of digits after the decimal point.------ * Haskell 'printf' prints the exponent of e-format---   numbers without a gratuitous plus sign, and with the---   minimum possible number of digits.------ * Haskell 'printf' will place a zero after a decimal point when---   possible.------ ==== __Examples__------ >   > printf "%d\n" (23::Int)--- >   23--- >   > printf "%s %s\n" "Hello" "World"--- >   Hello World--- >   > printf "%.2f\n" pi--- >   3.14----printf :: (PrintfType r) => String -> r-printf fmts = spr fmts []---- | Similar to 'printf', except that output is via the specified--- 'Handle'.  The return type is restricted to @('IO' a)@.-hPrintf :: (HPrintfType r) => Handle -> String -> r-hPrintf hdl fmts = hspr hdl fmts []---- |The 'PrintfType' class provides the variable argument magic for--- 'printf'.  Its implementation is intentionally not visible from--- this module. If you attempt to pass an argument of a type which--- is not an instance of this class to 'printf' or 'hPrintf', then--- the compiler will report it as a missing instance of 'PrintfArg'.-class PrintfType t where-    spr :: String -> [UPrintf] -> t---- | The 'HPrintfType' class provides the variable argument magic for--- 'hPrintf'.  Its implementation is intentionally not visible from--- this module.-class HPrintfType t where-    hspr :: Handle -> String -> [UPrintf] -> t--{- not allowed in Haskell 2010-instance PrintfType String where-    spr fmt args = uprintf fmt (reverse args)--}-instance (IsChar c) => PrintfType [c] where-    spr fmts args = map fromChar (uprintf fmts (reverse args))---- Note that this should really be (IO ()), but GHC's--- type system won't readily let us say that without--- bringing the GADTs. So we go conditional for these defs.--instance (a ~ ()) => PrintfType (IO a) where-    spr fmts args =-        putStr $ map fromChar $ uprintf fmts $ reverse args--instance (a ~ ()) => HPrintfType (IO a) where-    hspr hdl fmts args = do-        hPutStr hdl (uprintf fmts (reverse args))--instance (PrintfArg a, PrintfType r) => PrintfType (a -> r) where-    spr fmts args = \ a -> spr fmts-                             ((parseFormat a, formatArg a) : args)--instance (PrintfArg a, HPrintfType r) => HPrintfType (a -> r) where-    hspr hdl fmts args = \ a -> hspr hdl fmts-                                  ((parseFormat a, formatArg a) : args)---- | Typeclass of 'printf'-formattable values. The 'formatArg' method--- takes a value and a field format descriptor and either fails due--- to a bad descriptor or produces a 'ShowS' as the result. The--- default 'parseFormat' expects no modifiers: this is the normal--- case. Minimal instance: 'formatArg'.-class PrintfArg a where-    -- | @since 4.7.0.0-    formatArg :: a -> FieldFormatter-    -- | @since 4.7.0.0-    parseFormat :: a -> ModifierParser-    parseFormat _ (c : cs) = FormatParse "" c cs-    parseFormat _ "" = errorShortFormat--instance PrintfArg Char where-    formatArg = formatChar-    parseFormat _ cf = parseIntFormat (undefined :: Int) cf--instance (IsChar c) => PrintfArg [c] where-    formatArg = formatString--instance PrintfArg Int where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Int8 where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Int16 where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Int32 where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Int64 where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Word where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Word8 where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Word16 where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Word32 where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Word64 where-    formatArg = formatInt-    parseFormat = parseIntFormat--instance PrintfArg Integer where-    formatArg = formatInteger-    parseFormat = parseIntFormat--instance PrintfArg Natural where-    formatArg = formatInteger . toInteger-    parseFormat = parseIntFormat--instance PrintfArg Float where-    formatArg = formatRealFloat--instance PrintfArg Double where-    formatArg = formatRealFloat---- | This class, with only the one instance, is used as--- a workaround for the fact that 'String', as a concrete--- type, is not allowable as a typeclass instance. 'IsChar'--- is exported for backward-compatibility.-class IsChar c where-    -- | @since 4.7.0.0-    toChar :: c -> Char-    -- | @since 4.7.0.0-    fromChar :: Char -> c--instance IsChar Char where-    toChar c = c-    fromChar c = c------------------------- | Whether to left-adjust or zero-pad a field. These are--- mutually exclusive, with 'LeftAdjust' taking precedence.------ @since 4.7.0.0-data FormatAdjustment = LeftAdjust | ZeroPad---- | How to handle the sign of a numeric field.  These are--- mutually exclusive, with 'SignPlus' taking precedence.------ @since 4.7.0.0-data FormatSign = SignPlus | SignSpace---- | Description of field formatting for 'formatArg'. See UNIX `printf`(3)--- for a description of how field formatting works.------ @since 4.7.0.0-data FieldFormat = FieldFormat {-  fmtWidth :: Maybe Int,       -- ^ Total width of the field.-  fmtPrecision :: Maybe Int,   -- ^ Secondary field width specifier.-  fmtAdjust :: Maybe FormatAdjustment,  -- ^ Kind of filling or padding-                                        --   to be done.-  fmtSign :: Maybe FormatSign, -- ^ Whether to insist on a-                               -- plus sign for positive-                               -- numbers.-  fmtAlternate :: Bool,        -- ^ Indicates an "alternate-                               -- format".  See printf(3)-                               -- for the details, which-                               -- vary by argument spec.-  fmtModifiers :: String,      -- ^ Characters that appeared-                               -- immediately to the left of-                               -- 'fmtChar' in the format-                               -- and were accepted by the-                               -- type's 'parseFormat'.-                               -- Normally the empty string.-  fmtChar :: Char              -- ^ The format character-                               -- 'printf' was invoked-                               -- with. 'formatArg' should-                               -- fail unless this character-                               -- matches the type. It is-                               -- normal to handle many-                               -- different format-                               -- characters for a single-                               -- type.-  }---- | The \"format parser\" walks over argument-type-specific--- modifier characters to find the primary format character.--- This is the type of its result.------ @since 4.7.0.0-data FormatParse = FormatParse {-  fpModifiers :: String,   -- ^ Any modifiers found.-  fpChar :: Char,          -- ^ Primary format character.-  fpRest :: String         -- ^ Rest of the format string.-  }---- Contains the "modifier letters" that can precede an--- integer type.-intModifierMap :: [(String, Integer)]-intModifierMap = [-  ("hh", toInteger (minBound :: Int8)),-  ("h", toInteger (minBound :: Int16)),-  ("l", toInteger (minBound :: Int32)),-  ("ll", toInteger (minBound :: Int64)),-  ("L", toInteger (minBound :: Int64)) ]--parseIntFormat :: Integral a => a -> String -> FormatParse-parseIntFormat _ s =-  case foldr matchPrefix Nothing intModifierMap of-    Just m -> m-    Nothing ->-      case s of-        c : cs -> FormatParse "" c cs-        "" -> errorShortFormat-  where-    matchPrefix (p, _) m@(Just (FormatParse p0 _ _))-      | length p0 >= length p = m-      | otherwise = case getFormat p of-          Nothing -> m-          Just fp -> Just fp-    matchPrefix (p, _) Nothing =-      getFormat p-    getFormat p =-      stripPrefix p s >>= fp-      where-        fp (c : cs) = Just $ FormatParse p c cs-        fp "" = errorShortFormat---- | This is the type of a field formatter reified over its--- argument.------ @since 4.7.0.0-type FieldFormatter = FieldFormat -> ShowS---- | Type of a function that will parse modifier characters--- from the format string.------ @since 4.7.0.0-type ModifierParser = String -> FormatParse---- | Substitute a \'v\' format character with the given--- default format character in the 'FieldFormat'. A--- convenience for user-implemented types, which should--- support \"%v\".------ @since 4.7.0.0-vFmt :: Char -> FieldFormat -> FieldFormat-vFmt c ufmt@(FieldFormat {fmtChar = 'v'}) = ufmt {fmtChar = c}-vFmt _ ufmt = ufmt---- | Formatter for 'Char' values.------ @since 4.7.0.0-formatChar :: Char -> FieldFormatter-formatChar x ufmt =-  formatIntegral (Just 0) (toInteger $ ord x) $ vFmt 'c' ufmt---- | Formatter for 'String' values.------ @since 4.7.0.0-formatString :: IsChar a => [a] -> FieldFormatter-formatString x ufmt =-  case fmtChar $ vFmt 's' ufmt of-    's' -> map toChar . (adjust ufmt ("", ts) ++)-           where-             ts = map toChar $ trunc $ fmtPrecision ufmt-               where-                 trunc Nothing = x-                 trunc (Just n) = take n x-    c   -> errorBadFormat c---- Possibly apply the int modifiers to get a new--- int width for conversion.-fixupMods :: FieldFormat -> Maybe Integer -> Maybe Integer-fixupMods ufmt m =-  let mods = fmtModifiers ufmt in-  case mods of-    "" -> m-    _ -> case lookup mods intModifierMap of-      Just m0 -> Just m0-      Nothing -> perror "unknown format modifier"---- | Formatter for 'Int' values.------ @since 4.7.0.0-formatInt :: (Integral a, Bounded a) => a -> FieldFormatter-formatInt x ufmt =-  let lb = toInteger $ minBound `asTypeOf` x-      m = fixupMods ufmt (Just lb)-      ufmt' = case lb of-        0 -> vFmt 'u' ufmt-        _ -> ufmt-  in-  formatIntegral m (toInteger x) ufmt'---- | Formatter for 'Integer' values.------ @since 4.7.0.0-formatInteger :: Integer -> FieldFormatter-formatInteger x ufmt =-  let m = fixupMods ufmt Nothing in-  formatIntegral m x ufmt---- All formatting for integral types is handled--- consistently.  The only difference is between Integer and--- bounded types; this difference is handled by the 'm'--- argument containing the lower bound.-formatIntegral :: Maybe Integer -> Integer -> FieldFormatter-formatIntegral m x ufmt0 =-  let prec = fmtPrecision ufmt0 in-  case fmtChar ufmt of-    'd' -> (adjustSigned ufmt (fmti prec x) ++)-    'i' -> (adjustSigned ufmt (fmti prec x) ++)-    'x' -> (adjust ufmt (fmtu 16 (alt "0x" x) prec m x) ++)-    'X' -> (adjust ufmt (upcase $ fmtu 16 (alt "0X" x) prec m x) ++)-    'b' -> (adjust ufmt (fmtu 2 (alt "0b" x) prec m x) ++)-    'o' -> (adjust ufmt (fmtu 8 (alt "0" x) prec m x) ++)-    'u' -> (adjust ufmt (fmtu 10 Nothing prec m x) ++)-    'c' | x >= fromIntegral (ord (minBound :: Char)) &&-          x <= fromIntegral (ord (maxBound :: Char)) &&-          fmtPrecision ufmt == Nothing &&-          fmtModifiers ufmt == "" ->-            formatString [chr $ fromIntegral x] (ufmt { fmtChar = 's' })-    'c' -> perror "illegal char conversion"-    c   -> errorBadFormat c-  where-    ufmt = vFmt 'd' $ case ufmt0 of-      FieldFormat { fmtPrecision = Just _, fmtAdjust = Just ZeroPad } ->-        ufmt0 { fmtAdjust = Nothing }-      _ -> ufmt0-    alt _ 0 = Nothing-    alt p _ = case fmtAlternate ufmt of-      True -> Just p-      False -> Nothing-    upcase (s1, s2) = (s1, map toUpper s2)---- | Formatter for 'RealFloat' values.------ @since 4.7.0.0-formatRealFloat :: RealFloat a => a -> FieldFormatter-formatRealFloat x ufmt =-  let c = fmtChar $ vFmt 'g' ufmt-      prec = fmtPrecision ufmt-      alt = fmtAlternate ufmt-  in-   case c of-     'e' -> (adjustSigned ufmt (dfmt c prec alt x) ++)-     'E' -> (adjustSigned ufmt (dfmt c prec alt x) ++)-     'f' -> (adjustSigned ufmt (dfmt c prec alt x) ++)-     'F' -> (adjustSigned ufmt (dfmt c prec alt x) ++)-     'g' -> (adjustSigned ufmt (dfmt c prec alt x) ++)-     'G' -> (adjustSigned ufmt (dfmt c prec alt x) ++)-     _   -> errorBadFormat c---- This is the type carried around for arguments in--- the varargs code.-type UPrintf = (ModifierParser, FieldFormatter)---- Given a format string and a list of formatting functions--- (the actual argument value having already been baked into--- each of these functions before delivery), return the--- actual formatted text string.-uprintf :: String -> [UPrintf] -> String-uprintf s us = uprintfs s us ""---- This function does the actual work, producing a ShowS--- instead of a string, for future expansion and for--- misguided efficiency.-uprintfs :: String -> [UPrintf] -> ShowS-uprintfs ""       []       = id-uprintfs ""       (_:_)    = errorShortFormat-uprintfs ('%':'%':cs) us   = ('%' :) . uprintfs cs us-uprintfs ('%':_)  []       = errorMissingArgument-uprintfs ('%':cs) us@(_:_) = fmt cs us-uprintfs (c:cs)   us       = (c :) . uprintfs cs us---- Given a suffix of the format string starting just after--- the percent sign, and the list of remaining unprocessed--- arguments in the form described above, format the portion--- of the output described by this field description, and--- then continue with 'uprintfs'.-fmt :: String -> [UPrintf] -> ShowS-fmt cs0 us0 =-  case getSpecs False False Nothing False cs0 us0 of-    (_, _, []) -> errorMissingArgument-    (ufmt, cs, (_, u) : us) -> u ufmt . uprintfs cs us---- Given field formatting information, and a tuple--- consisting of a prefix (for example, a minus sign) that--- is supposed to go before the argument value and a string--- representing the value, return the properly padded and--- formatted result.-adjust :: FieldFormat -> (String, String) -> String-adjust ufmt (pre, str) =-  let naturalWidth = length pre + length str-      zero = case fmtAdjust ufmt of-        Just ZeroPad -> True-        _ -> False-      left = case fmtAdjust ufmt of-        Just LeftAdjust -> True-        _ -> False-      fill = case fmtWidth ufmt of-        Just width | naturalWidth < width ->-          let fillchar = if zero then '0' else ' ' in-          replicate (width - naturalWidth) fillchar-        _ -> ""-  in-   if left-   then pre ++ str ++ fill-   else if zero-        then pre ++ fill ++ str-        else fill ++ pre ++ str---- For positive numbers with an explicit sign field ("+" or--- " "), adjust accordingly.-adjustSigned :: FieldFormat -> (String, String) -> String-adjustSigned ufmt@(FieldFormat {fmtSign = Just SignPlus}) ("", str) =-  adjust ufmt ("+", str)-adjustSigned ufmt@(FieldFormat {fmtSign = Just SignSpace}) ("", str) =-  adjust ufmt (" ", str)-adjustSigned ufmt ps =-  adjust ufmt ps---- Format a signed integer in the "default" fashion.--- This will be subjected to adjust subsequently.-fmti :: Maybe Int -> Integer -> (String, String)-fmti prec i-  | i < 0 = ("-", integral_prec prec (show (-i)))-  | otherwise = ("", integral_prec prec (show i))---- Format an unsigned integer in the "default" fashion.--- This will be subjected to adjust subsequently.  The 'b'--- argument is the base, the 'pre' argument is the prefix,--- and the '(Just m)' argument is the implicit lower-bound--- size of the operand for conversion from signed to--- unsigned. Thus, this function will refuse to convert an--- unbounded negative integer to an unsigned string.-fmtu :: Integer -> Maybe String -> Maybe Int -> Maybe Integer -> Integer-     -> (String, String)-fmtu b (Just pre) prec m i =-  let ("", s) = fmtu b Nothing prec m i in-  case pre of-    "0" -> case s of-      '0' : _ -> ("", s)-      _ -> (pre, s)-    _ -> (pre, s)-fmtu b Nothing prec0 m0 i0 =-  case fmtu' prec0 m0 i0 of-    Just s -> ("", s)-    Nothing -> errorBadArgument-  where-    fmtu' :: Maybe Int -> Maybe Integer -> Integer -> Maybe String-    fmtu' prec (Just m) i | i < 0 =-      fmtu' prec Nothing (-2 * m + i)-    fmtu' (Just prec) _ i | i >= 0 =-      fmap (integral_prec (Just prec)) $ fmtu' Nothing Nothing i-    fmtu' Nothing _ i | i >= 0 =-      Just $ showIntAtBase b intToDigit i ""-    fmtu' _ _ _ = Nothing----- This is used by 'fmtu' and 'fmti' to zero-pad an--- int-string to a required precision.-integral_prec :: Maybe Int -> String -> String-integral_prec Nothing integral = integral-integral_prec (Just 0) "0" = ""-integral_prec (Just prec) integral =-  replicate (prec - length integral) '0' ++ integral--stoi :: String -> (Int, String)-stoi cs =-  let (as, cs') = span isDigit cs in-  case as of-    "" -> (0, cs')-    _ -> (read as, cs')---- Figure out the FormatAdjustment, given:---   width, precision, left-adjust, zero-fill-adjustment :: Maybe Int -> Maybe a -> Bool -> Bool-           -> Maybe FormatAdjustment-adjustment w p l z =-  case w of-    Just n | n < 0 -> adjl p True z-    _ -> adjl p l z-  where-    adjl _ True _ = Just LeftAdjust-    adjl _ False True = Just ZeroPad-    adjl _ _ _ = Nothing---- Parse the various format controls to get a format specification.-getSpecs :: Bool -> Bool -> Maybe FormatSign -> Bool -> String -> [UPrintf]-         -> (FieldFormat, String, [UPrintf])-getSpecs _ z s a ('-' : cs0) us = getSpecs True z s a cs0 us-getSpecs l z _ a ('+' : cs0) us = getSpecs l z (Just SignPlus) a cs0 us-getSpecs l z s a (' ' : cs0) us =-  getSpecs l z ss a cs0 us-  where-    ss = case s of-      Just SignPlus -> Just SignPlus-      _ -> Just SignSpace-getSpecs l _ s a ('0' : cs0) us = getSpecs l True s a cs0 us-getSpecs l z s _ ('#' : cs0) us = getSpecs l z s True cs0 us-getSpecs l z s a ('*' : cs0) us =-  let (us', n) = getStar us-      ((p, cs''), us'') = case cs0 of-        '.':'*':r ->-          let (us''', p') = getStar us' in ((Just p', r), us''')-        '.':r ->-          let (p', r') = stoi r in ((Just p', r'), us')-        _ ->-          ((Nothing, cs0), us')-      FormatParse ms c cs =-        case us'' of-          (ufmt, _) : _ -> ufmt cs''-          [] -> errorMissingArgument-  in-   (FieldFormat {-       fmtWidth = Just (abs n),-       fmtPrecision = p,-       fmtAdjust = adjustment (Just n) p l z,-       fmtSign = s,-       fmtAlternate = a,-       fmtModifiers = ms,-       fmtChar = c}, cs, us'')-getSpecs l z s a ('.' : cs0) us =-  let ((p, cs'), us') = case cs0 of-        '*':cs'' -> let (us'', p') = getStar us in ((p', cs''), us'')-        _ ->        (stoi cs0, us)-      FormatParse ms c cs =-        case us' of-          (ufmt, _) : _ -> ufmt cs'-          [] -> errorMissingArgument-  in-   (FieldFormat {-       fmtWidth = Nothing,-       fmtPrecision = Just p,-       fmtAdjust = adjustment Nothing (Just p) l z,-       fmtSign = s,-       fmtAlternate = a,-       fmtModifiers = ms,-       fmtChar = c}, cs, us')-getSpecs l z s a cs0@(c0 : _) us | isDigit c0 =-  let (n, cs') = stoi cs0-      ((p, cs''), us') = case cs' of-        '.' : '*' : r ->-          let (us'', p') = getStar us in ((Just p', r), us'')-        '.' : r ->-          let (p', r') = stoi r in ((Just p', r'), us)-        _ ->-          ((Nothing, cs'), us)-      FormatParse ms c cs =-        case us' of-          (ufmt, _) : _ -> ufmt cs''-          [] -> errorMissingArgument-  in-   (FieldFormat {-       fmtWidth = Just (abs n),-       fmtPrecision = p,-       fmtAdjust = adjustment (Just n) p l z,-       fmtSign = s,-       fmtAlternate = a,-       fmtModifiers = ms,-       fmtChar = c}, cs, us')-getSpecs l z s a cs0@(_ : _) us =-  let FormatParse ms c cs =-        case us of-          (ufmt, _) : _ -> ufmt cs0-          [] -> errorMissingArgument-  in-   (FieldFormat {-       fmtWidth = Nothing,-       fmtPrecision = Nothing,-       fmtAdjust = adjustment Nothing Nothing l z,-       fmtSign = s,-       fmtAlternate = a,-       fmtModifiers = ms,-       fmtChar = c}, cs, us)-getSpecs _ _ _ _ ""       _  =-  errorShortFormat---- Process a star argument in a format specification.-getStar :: [UPrintf] -> ([UPrintf], Int)-getStar us =-  let ufmt = FieldFormat {-        fmtWidth = Nothing,-        fmtPrecision = Nothing,-        fmtAdjust = Nothing,-        fmtSign = Nothing,-        fmtAlternate = False,-        fmtModifiers = "",-        fmtChar = 'd' } in-  case us of-    [] -> errorMissingArgument-    (_, nu) : us' -> (us', read (nu ufmt ""))---- Format a RealFloat value.-dfmt :: (RealFloat a) => Char -> Maybe Int -> Bool -> a -> (String, String)-dfmt c p a d =-  let caseConvert = if isUpper c then map toUpper else id-      showFunction = case toLower c of-        'e' -> showEFloat-        'f' -> if a then showFFloatAlt else showFFloat-        'g' -> if a then showGFloatAlt else showGFloat-        _   -> perror "internal error: impossible dfmt"-      result = caseConvert $ showFunction p d ""-  in-   case result of-     '-' : cs -> ("-", cs)-     cs       -> ("" , cs)----- | Raises an 'error' with a printf-specific prefix on the--- message string.------ @since 4.7.0.0-perror :: String -> a-perror s = error $ "printf: " ++ s---- | Calls 'perror' to indicate an unknown format letter for--- a given type.------ @since 4.7.0.0-errorBadFormat :: Char -> a-errorBadFormat c = perror $ "bad formatting char " ++ show c--errorShortFormat, errorMissingArgument, errorBadArgument :: a--- | Calls 'perror' to indicate that the format string ended--- early.------ @since 4.7.0.0-errorShortFormat = perror "formatting string ended prematurely"--- | Calls 'perror' to indicate that there is a missing--- argument in the argument list.------ @since 4.7.0.0-errorMissingArgument = perror "argument list ended prematurely"--- | Calls 'perror' to indicate that there is a type--- error or similar in the given argument.------ @since 4.7.0.0-errorBadArgument = perror "bad argument"
− Text/Read.hs
@@ -1,90 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Text.Read--- 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 (uses Text.ParserCombinators.ReadP)------ Converting strings to values.------ The "Text.Read" library is the canonical library to import for--- 'Read'-class facilities.  For GHC only, it offers an extended and much--- improved 'Read' class, which constitutes a proposed alternative to the--- Haskell 2010 'Read'.  In particular, writing parsers is easier, and--- the parsers are much more efficient.-----------------------------------------------------------------------------------module Text.Read (-   -- * The 'Read' class-   Read(..),-   ReadS,--   -- * Haskell 2010 functions-   reads,-   read,-   readParen,-   lex,--   -- * New parsing functions-   module Text.ParserCombinators.ReadPrec,-   L.Lexeme(..),-   lexP,-   parens,-   readListDefault,-   readListPrecDefault,-   readEither,-   readMaybe-- ) where--import GHC.Base-import GHC.Read-import Data.Either-import Text.ParserCombinators.ReadP as P-import Text.ParserCombinators.ReadPrec-import qualified Text.Read.Lex as L----------------------------------------------------------------------------- utility functions---- | equivalent to 'readsPrec' with a precedence of 0.-reads :: Read a => ReadS a-reads = readsPrec minPrec---- | Parse a string using the 'Read' instance.--- Succeeds if there is exactly one valid result.--- A 'Left' value indicates a parse error.------ @since 4.6.0.0-readEither :: Read a => String -> Either String a-readEither s =-  case [ x | (x,"") <- readPrec_to_S read' minPrec s ] of-    [x] -> Right x-    []  -> Left "Prelude.read: no parse"-    _   -> Left "Prelude.read: ambiguous parse"- where-  read' =-    do x <- readPrec-       lift P.skipSpaces-       return x---- | Parse a string using the 'Read' instance.--- Succeeds if there is exactly one valid result.------ @since 4.6.0.0-readMaybe :: Read a => String -> Maybe a-readMaybe s = case readEither s of-                Left _  -> Nothing-                Right a -> Just a---- | The 'read' function reads input from a string, which must be--- completely consumed by the input process.-read :: Read a => String -> a-read s = either error id (readEither s)
− Text/Read/Lex.hs
@@ -1,558 +0,0 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Text.Read.Lex--- Copyright   :  (c) The University of Glasgow 2002--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  non-portable (uses Text.ParserCombinators.ReadP)------ The cut-down Haskell lexer, used by Text.Read-----------------------------------------------------------------------------------module Text.Read.Lex-  -- lexing types-  ( Lexeme(..), Number--  , numberToInteger, numberToFixed, numberToRational, numberToRangedRational--  -- lexer-  , lex, expect-  , hsLex-  , lexChar--  , readIntP-  , readOctP-  , readDecP-  , readHexP-  )- where--import Text.ParserCombinators.ReadP--import GHC.Base-import GHC.Char-import GHC.Num( Num(..), Integer )-import GHC.Show( Show(..) )-import GHC.Unicode( isSpace, isAlpha, isAlphaNum )-import GHC.Real( Rational, (%), fromIntegral, Integral,-                 toInteger, (^), quot, even )-import GHC.List-import GHC.Enum( minBound, maxBound )-import Data.Maybe---- local copy to break import-cycle--- | @'guard' b@ is @'return' ()@ if @b@ is 'True',--- and 'mzero' if @b@ is 'False'.-guard           :: (MonadPlus m) => Bool -> m ()-guard True      =  return ()-guard False     =  mzero---- -------------------------------------------------------------------------------- Lexing types---- ^ Haskell lexemes.-data Lexeme-  = Char   Char         -- ^ Character literal-  | String String       -- ^ String literal, with escapes interpreted-  | Punc   String       -- ^ Punctuation or reserved symbol, e.g. @(@, @::@-  | Ident  String       -- ^ Haskell identifier, e.g. @foo@, @Baz@-  | Symbol String       -- ^ Haskell symbol, e.g. @>>@, @:%@-  | Number Number       -- ^ @since 4.6.0.0-  | EOF- deriving (Eq, Show)---- | @since 4.7.0.0-data Number = MkNumber Int              -- Base-                       Digits           -- Integral part-            | MkDecimal Digits          -- Integral part-                        (Maybe Digits)  -- Fractional part-                        (Maybe Integer) -- Exponent- deriving (Eq, Show)---- | @since 4.5.1.0-numberToInteger :: Number -> Maybe Integer-numberToInteger (MkNumber base iPart) = Just (val (fromIntegral base) iPart)-numberToInteger (MkDecimal iPart Nothing Nothing) = Just (val 10 iPart)-numberToInteger _ = Nothing---- | @since 4.7.0.0-numberToFixed :: Integer -> Number -> Maybe (Integer, Integer)-numberToFixed _ (MkNumber base iPart) = Just (val (fromIntegral base) iPart, 0)-numberToFixed _ (MkDecimal iPart Nothing Nothing) = Just (val 10 iPart, 0)-numberToFixed p (MkDecimal iPart (Just fPart) Nothing)-    = let i = val 10 iPart-          f = val 10 (integerTake p (fPart ++ repeat 0))-          -- Sigh, we really want genericTake, but that's above us in-          -- the hierarchy, so we define our own version here (actually-          -- specialised to Integer)-          integerTake             :: Integer -> [a] -> [a]-          integerTake n _ | n <= 0 = []-          integerTake _ []        =  []-          integerTake n (x:xs)    =  x : integerTake (n-1) xs-      in Just (i, f)-numberToFixed _ _ = Nothing---- This takes a floatRange, and if the Rational would be outside of--- the floatRange then it may return Nothing. Not that it will not--- /necessarily/ return Nothing, but it is good enough to fix the--- space problems in #5688--- Ways this is conservative:--- * the floatRange is in base 2, but we pretend it is in base 10--- * we pad the floateRange a bit, just in case it is very small---   and we would otherwise hit an edge case--- * We only worry about numbers that have an exponent. If they don't---   have an exponent then the Rational won't be much larger than the---   Number, so there is no problem--- | @since 4.5.1.0-numberToRangedRational :: (Int, Int) -> Number-                       -> Maybe Rational -- Nothing = Inf-numberToRangedRational (neg, pos) n@(MkDecimal iPart mFPart (Just exp))-    -- if exp is out of integer bounds,-    -- then the number is definitely out of range-    | exp > fromIntegral (maxBound :: Int) ||-      exp < fromIntegral (minBound :: Int)-    = Nothing-    | otherwise-    = let mFirstDigit = case dropWhile (0 ==) iPart of-                        iPart'@(_ : _) -> Just (length iPart')-                        [] -> case mFPart of-                              Nothing -> Nothing-                              Just fPart ->-                                  case span (0 ==) fPart of-                                  (_, []) -> Nothing-                                  (zeroes, _) ->-                                      Just (negate (length zeroes))-      in case mFirstDigit of-         Nothing -> Just 0-         Just firstDigit ->-             let firstDigit' = firstDigit + fromInteger exp-             in if firstDigit' > (pos + 3)-                then Nothing-                else if firstDigit' < (neg - 3)-                then Just 0-                else Just (numberToRational n)-numberToRangedRational _ n = Just (numberToRational n)---- | @since 4.6.0.0-numberToRational :: Number -> Rational-numberToRational (MkNumber base iPart) = val (fromIntegral base) iPart % 1-numberToRational (MkDecimal iPart mFPart mExp)- = let i = val 10 iPart-   in case (mFPart, mExp) of-      (Nothing, Nothing)     -> i % 1-      (Nothing, Just exp)-       | exp >= 0            -> (i * (10 ^ exp)) % 1-       | otherwise           -> i % (10 ^ (- exp))-      (Just fPart, Nothing)  -> fracExp 0   i fPart-      (Just fPart, Just exp) -> fracExp exp i fPart-      -- fracExp is a bit more efficient in calculating the Rational.-      -- Instead of calculating the fractional part alone, then-      -- adding the integral part and finally multiplying with-      -- 10 ^ exp if an exponent was given, do it all at once.---- -------------------------------------------------------------------------------- Lexing--lex :: ReadP Lexeme-lex = skipSpaces >> lexToken---- | @since 4.7.0.0-expect :: Lexeme -> ReadP ()-expect lexeme = do { skipSpaces-                   ; thing <- lexToken-                   ; if thing == lexeme then return () else pfail }--hsLex :: ReadP String--- ^ Haskell lexer: returns the lexed string, rather than the lexeme-hsLex = do skipSpaces-           (s,_) <- gather lexToken-           return s--lexToken :: ReadP Lexeme-lexToken = lexEOF     +++-           lexLitChar +++-           lexString  +++-           lexPunc    +++-           lexSymbol  +++-           lexId      +++-           lexNumber----- ------------------------------------------------------------------------- End of file-lexEOF :: ReadP Lexeme-lexEOF = do s <- look-            guard (null s)-            return EOF---- ------------------------------------------------------------------------------ Single character lexemes--lexPunc :: ReadP Lexeme-lexPunc =-  do c <- satisfy isPuncChar-     return (Punc [c])- where-  isPuncChar c = c `elem` ",;()[]{}`"---- ------------------------------------------------------------------------- Symbols--lexSymbol :: ReadP Lexeme-lexSymbol =-  do s <- munch1 isSymbolChar-     if s `elem` reserved_ops then-        return (Punc s)         -- Reserved-ops count as punctuation-      else-        return (Symbol s)- where-  isSymbolChar c = c `elem` "!@#$%&*+./<=>?\\^|:-~"-  reserved_ops   = ["..", "::", "=", "\\", "|", "<-", "->", "@", "~", "=>"]---- ------------------------------------------------------------------------- identifiers--lexId :: ReadP Lexeme-lexId = do c <- satisfy isIdsChar-           s <- munch isIdfChar-           return (Ident (c:s))-  where-          -- Identifiers can start with a '_'-    isIdsChar c = isAlpha c || c == '_'-    isIdfChar c = isAlphaNum c || c `elem` "_'"---- ------------------------------------------------------------------------------ Lexing character literals--lexLitChar :: ReadP Lexeme-lexLitChar =-  do _ <- char '\''-     (c,esc) <- lexCharE-     guard (esc || c /= '\'')   -- Eliminate '' possibility-     _ <- char '\''-     return (Char c)--lexChar :: ReadP Char-lexChar = do { (c,_) <- lexCharE; return c }--lexCharE :: ReadP (Char, Bool)  -- "escaped or not"?-lexCharE =-  do c1 <- get-     if c1 == '\\'-       then do c2 <- lexEsc; return (c2, True)-       else do return (c1, False)- where-  lexEsc =-    lexEscChar-      +++ lexNumeric-        +++ lexCntrlChar-          +++ lexAscii--  lexEscChar =-    do c <- get-       case c of-         'a'  -> return '\a'-         'b'  -> return '\b'-         'f'  -> return '\f'-         'n'  -> return '\n'-         'r'  -> return '\r'-         't'  -> return '\t'-         'v'  -> return '\v'-         '\\' -> return '\\'-         '\"' -> return '\"'-         '\'' -> return '\''-         _    -> pfail--  lexNumeric =-    do base <- lexBaseChar <++ return 10-       n    <- lexInteger base-       guard (n <= toInteger (ord maxBound))-       return (chr (fromInteger n))--  lexCntrlChar =-    do _ <- char '^'-       c <- get-       case c of-         '@'  -> return '\^@'-         'A'  -> return '\^A'-         'B'  -> return '\^B'-         'C'  -> return '\^C'-         'D'  -> return '\^D'-         'E'  -> return '\^E'-         'F'  -> return '\^F'-         'G'  -> return '\^G'-         'H'  -> return '\^H'-         'I'  -> return '\^I'-         'J'  -> return '\^J'-         'K'  -> return '\^K'-         'L'  -> return '\^L'-         'M'  -> return '\^M'-         'N'  -> return '\^N'-         'O'  -> return '\^O'-         'P'  -> return '\^P'-         'Q'  -> return '\^Q'-         'R'  -> return '\^R'-         'S'  -> return '\^S'-         'T'  -> return '\^T'-         'U'  -> return '\^U'-         'V'  -> return '\^V'-         'W'  -> return '\^W'-         'X'  -> return '\^X'-         'Y'  -> return '\^Y'-         'Z'  -> return '\^Z'-         '['  -> return '\^['-         '\\' -> return '\^\'-         ']'  -> return '\^]'-         '^'  -> return '\^^'-         '_'  -> return '\^_'-         _    -> pfail--  lexAscii =-    do choice-         [ (string "SOH" >> return '\SOH') <++-           (string "SO"  >> return '\SO')-                -- \SO and \SOH need maximal-munch treatment-                -- See the Haskell report Sect 2.6--         , string "NUL" >> return '\NUL'-         , string "STX" >> return '\STX'-         , string "ETX" >> return '\ETX'-         , string "EOT" >> return '\EOT'-         , string "ENQ" >> return '\ENQ'-         , string "ACK" >> return '\ACK'-         , string "BEL" >> return '\BEL'-         , string "BS"  >> return '\BS'-         , string "HT"  >> return '\HT'-         , string "LF"  >> return '\LF'-         , string "VT"  >> return '\VT'-         , string "FF"  >> return '\FF'-         , string "CR"  >> return '\CR'-         , string "SI"  >> return '\SI'-         , string "DLE" >> return '\DLE'-         , string "DC1" >> return '\DC1'-         , string "DC2" >> return '\DC2'-         , string "DC3" >> return '\DC3'-         , string "DC4" >> return '\DC4'-         , string "NAK" >> return '\NAK'-         , string "SYN" >> return '\SYN'-         , string "ETB" >> return '\ETB'-         , string "CAN" >> return '\CAN'-         , string "EM"  >> return '\EM'-         , string "SUB" >> return '\SUB'-         , string "ESC" >> return '\ESC'-         , string "FS"  >> return '\FS'-         , string "GS"  >> return '\GS'-         , string "RS"  >> return '\RS'-         , string "US"  >> return '\US'-         , string "SP"  >> return '\SP'-         , string "DEL" >> return '\DEL'-         ]----- ------------------------------------------------------------------------------ string literal--lexString :: ReadP Lexeme-lexString =-  do _ <- char '"'-     body id- where-  body f =-    do (c,esc) <- lexStrItem-       if c /= '"' || esc-         then body (f.(c:))-         else let s = f "" in-              return (String s)--  lexStrItem = (lexEmpty >> lexStrItem)-               +++ lexCharE--  lexEmpty =-    do _ <- char '\\'-       c <- get-       case c of-         '&'           -> do return ()-         _ | isSpace c -> do skipSpaces; _ <- char '\\'; return ()-         _             -> do pfail---- ------------------------------------------------------------------------------  Lexing numbers--type Base   = Int-type Digits = [Int]--lexNumber :: ReadP Lexeme-lexNumber-  = lexHexOct  <++      -- First try for hex or octal 0x, 0o etc-                        -- If that fails, try for a decimal number-    lexDecNumber        -- Start with ordinary digits--lexHexOct :: ReadP Lexeme-lexHexOct-  = do  _ <- char '0'-        base <- lexBaseChar-        digits <- lexDigits base-        return (Number (MkNumber base digits))--lexBaseChar :: ReadP Int--- Lex a single character indicating the base; fail if not there-lexBaseChar = do { c <- get;-                   case c of-                        'o' -> return 8-                        'O' -> return 8-                        'x' -> return 16-                        'X' -> return 16-                        _   -> pfail }--lexDecNumber :: ReadP Lexeme-lexDecNumber =-  do xs    <- lexDigits 10-     mFrac <- lexFrac <++ return Nothing-     mExp  <- lexExp  <++ return Nothing-     return (Number (MkDecimal xs mFrac mExp))--lexFrac :: ReadP (Maybe Digits)--- Read the fractional part; fail if it doesn't--- start ".d" where d is a digit-lexFrac = do _ <- char '.'-             fraction <- lexDigits 10-             return (Just fraction)--lexExp :: ReadP (Maybe Integer)-lexExp = do _ <- char 'e' +++ char 'E'-            exp <- signedExp +++ lexInteger 10-            return (Just exp)- where-   signedExp-     = do c <- char '-' +++ char '+'-          n <- lexInteger 10-          return (if c == '-' then -n else n)--lexDigits :: Int -> ReadP Digits--- Lex a non-empty sequence of digits in specified base-lexDigits base =-  do s  <- look-     xs <- scan s id-     guard (not (null xs))-     return xs- where-  scan (c:cs) f = case valDig base c of-                    Just n  -> do _ <- get; scan cs (f.(n:))-                    Nothing -> do return (f [])-  scan []     f = do return (f [])--lexInteger :: Base -> ReadP Integer-lexInteger base =-  do xs <- lexDigits base-     return (val (fromIntegral base) xs)--val :: Num a => a -> Digits -> a-val = valSimple-{-# RULES-"val/Integer" val = valInteger-  #-}-{-# INLINE [1] val #-}---- The following algorithm is only linear for types whose Num operations--- are in constant time.-valSimple :: (Num a, Integral d) => a -> [d] -> a-valSimple base = go 0-  where-    go r [] = r-    go r (d : ds) = r' `seq` go r' ds-      where-        r' = r * base + fromIntegral d-{-# INLINE valSimple #-}---- A sub-quadratic algorithm for Integer. Pairs of adjacent radix b--- digits are combined into a single radix b^2 digit. This process is--- repeated until we are left with a single digit. This algorithm--- performs well only on large inputs, so we use the simple algorithm--- for smaller inputs.-valInteger :: Integer -> Digits -> Integer-valInteger b0 ds0 = go b0 (length ds0) $ map fromIntegral ds0-  where-    go _ _ []  = 0-    go _ _ [d] = d-    go b l ds-        | l > 40 = b' `seq` go b' l' (combine b ds')-        | otherwise = valSimple b ds-      where-        -- ensure that we have an even number of digits-        -- before we call combine:-        ds' = if even l then ds else 0 : ds-        b' = b * b-        l' = (l + 1) `quot` 2-    combine b (d1 : d2 : ds) = d `seq` (d : combine b ds)-      where-        d = d1 * b + d2-    combine _ []  = []-    combine _ [_] = error "this should not happen"---- Calculate a Rational from the exponent [of 10 to multiply with],--- the integral part of the mantissa and the digits of the fractional--- part. Leaving the calculation of the power of 10 until the end,--- when we know the effective exponent, saves multiplications.--- More importantly, this way we need at most one gcd instead of three.------ frac was never used with anything but Integer and base 10, so--- those are hardcoded now (trivial to change if necessary).-fracExp :: Integer -> Integer -> Digits -> Rational-fracExp exp mant []-  | exp < 0     = mant % (10 ^ (-exp))-  | otherwise   = fromInteger (mant * 10 ^ exp)-fracExp exp mant (d:ds) = exp' `seq` mant' `seq` fracExp exp' mant' ds-  where-    exp'  = exp - 1-    mant' = mant * 10 + fromIntegral d--valDig :: (Eq a, Num a) => a -> Char -> Maybe Int-valDig 8 c-  | '0' <= c && c <= '7' = Just (ord c - ord '0')-  | otherwise            = Nothing--valDig 10 c = valDecDig c--valDig 16 c-  | '0' <= c && c <= '9' = Just (ord c - ord '0')-  | 'a' <= c && c <= 'f' = Just (ord c - ord 'a' + 10)-  | 'A' <= c && c <= 'F' = Just (ord c - ord 'A' + 10)-  | otherwise            = Nothing--valDig _ _ = error "valDig: Bad base"--valDecDig :: Char -> Maybe Int-valDecDig c-  | '0' <= c && c <= '9' = Just (ord c - ord '0')-  | otherwise            = Nothing---- ------------------------------------------------------------------------- other numeric lexing functions--readIntP :: Num a => a -> (Char -> Bool) -> (Char -> Int) -> ReadP a-readIntP base isDigit valDigit =-  do s <- munch1 isDigit-     return (val base (map valDigit s))-{-# SPECIALISE readIntP-        :: Integer -> (Char -> Bool) -> (Char -> Int) -> ReadP Integer #-}--readIntP' :: (Eq a, Num a) => a -> ReadP a-readIntP' base = readIntP base isDigit valDigit- where-  isDigit  c = maybe False (const True) (valDig base c)-  valDigit c = maybe 0     id           (valDig base c)-{-# SPECIALISE readIntP' :: Integer -> ReadP Integer #-}--readOctP, readDecP, readHexP :: (Eq a, Num a) => ReadP a-readOctP = readIntP' 8-readDecP = readIntP' 10-readHexP = readIntP' 16-{-# SPECIALISE readOctP :: ReadP Integer #-}-{-# SPECIALISE readDecP :: ReadP Integer #-}-{-# SPECIALISE readHexP :: ReadP Integer #-}
− Text/Show.hs
@@ -1,34 +0,0 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE NoImplicitPrelude #-}---------------------------------------------------------------------------------- |--- Module      :  Text.Show--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)--- --- Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Converting values to readable strings:--- the 'Show' class and associated functions.-----------------------------------------------------------------------------------module Text.Show (-   ShowS,-   Show(showsPrec, show, showList),-   shows,-   showChar,-   showString,-   showParen,-   showListWith,- ) where--import GHC.Show---- | Show a list (using square brackets and commas), given a function--- for showing elements.-showListWith :: (a -> ShowS) -> [a] -> ShowS-showListWith = showList__
− Text/Show/Functions.hs
@@ -1,26 +0,0 @@-{-# LANGUAGE Safe #-}--- This module deliberately declares orphan instances:-{-# OPTIONS_GHC -fno-warn-orphans #-}---------------------------------------------------------------------------------- |--- Module      :  Text.Show.Functions--- Copyright   :  (c) The University of Glasgow 2001--- License     :  BSD-style (see the file libraries/base/LICENSE)------ Maintainer  :  libraries@haskell.org--- Stability   :  provisional--- Portability :  portable------ Optional instance of 'Text.Show.Show' for functions:------ > instance Show (a -> b) where--- >    showsPrec _ _ = showString \"\<function\>\"-----------------------------------------------------------------------------------module Text.Show.Functions () where--instance Show (a -> b) where-        showsPrec _ _ = showString "<function>"-
− Unsafe/Coerce.hs
@@ -1,62 +0,0 @@-{-# LANGUAGE Unsafe #-}-{-# LANGUAGE NoImplicitPrelude, MagicHash #-}---------------------------------------------------------------------------------- |--- Module      :  Unsafe.Coerce--- Copyright   :  Malcolm Wallace 2006--- License     :  BSD-style (see the LICENSE file in the distribution)------ Maintainer  :  libraries@haskell.org--- Stability   :  experimental--- Portability :  portable------ The highly unsafe primitive 'unsafeCoerce' converts a value from any--- type to any other type.  Needless to say, if you use this function,--- it is your responsibility to ensure that the old and new types have--- identical internal representations, in order to prevent runtime corruption.------ The types for which 'unsafeCoerce' is representation-safe may differ--- from compiler to compiler (and version to version).------   * Documentation for correct usage in GHC will be found under---     'unsafeCoerce#' in GHC.Base (around which 'unsafeCoerce' is just a---     trivial wrapper).------   * In nhc98, the only representation-safe coercions are between Enum---     types with the same range (e.g. Int, Int32, Char, Word32),---     or between a newtype and the type that it wraps.-----------------------------------------------------------------------------------module Unsafe.Coerce (unsafeCoerce) where--import GHC.Integer () -- for build ordering-import GHC.Prim (unsafeCoerce#)--local_id :: a -> a-local_id x = x   -- See Note [Mega-hack for coerce]--{- Note [Mega-hack for coerce]--If we just say-  unsafeCoerce x = unsafeCoerce# x-then the simple-optimiser that the desugarer runs will eta-reduce to-  unsafeCoerce :: forall (a:*) (b:*). a -> b-  unsafeCoerce = unsafeCoerce#-And that, sadly, is ill-typed because unsafeCoerce# has OpenKind type variables-And rightly so, because we shouldn't be calling unsafeCoerce# in a higher-order way; it has a compulsory unfolding -   unsafeCoerce# a b x = x |> UnsafeCo a b-and we really rely on it being inlined pronto. But the simple-optimiser doesn't.-The identity function local_id delays the eta reduction just long enough-for unsafeCoerce# to get inlined.--Sigh. This is horrible, but then so is unsafeCoerce.--}--unsafeCoerce :: a -> b-unsafeCoerce x = local_id (unsafeCoerce# x)-  -- See Note [Unsafe coerce magic] in basicTypes/MkId-  -- NB: Do not eta-reduce this definition, else the type checker -  -- give usafeCoerce the same (dangerous) type as unsafeCoerce#
− aclocal.m4
@@ -1,229 +0,0 @@-# FP_COMPUTE_INT(EXPRESSION, VARIABLE, INCLUDES, IF-FAILS)-# ---------------------------------------------------------# Assign VARIABLE the value of the compile-time EXPRESSION using INCLUDES for-# compilation. Execute IF-FAILS when unable to determine the value. Works for-# cross-compilation, too.-#-# Implementation note: We are lazy and use an internal autoconf macro, but it-# is supported in autoconf versions 2.50 up to the actual 2.57, so there is-# little risk.-# The public AC_COMPUTE_INT macro isn't supported by some versions of-# autoconf.-AC_DEFUN([FP_COMPUTE_INT],-[_AC_COMPUTE_INT([$2], [$1], [$3], [$4])[]dnl-])# FP_COMPUTE_INT---# FP_CHECK_CONST(EXPRESSION, [INCLUDES = DEFAULT-INCLUDES], [VALUE-IF-FAIL = -1])-# --------------------------------------------------------------------------------# Defines CONST_EXPRESSION to the value of the compile-time EXPRESSION, using-# INCLUDES. If the value cannot be determined, use VALUE-IF-FAIL.-AC_DEFUN([FP_CHECK_CONST],-[AS_VAR_PUSHDEF([fp_Cache], [fp_cv_const_$1])[]dnl-AC_CACHE_CHECK([value of $1], fp_Cache,-[FP_COMPUTE_INT(fp_check_const_result, [$1], [AC_INCLUDES_DEFAULT([$2])],-                [fp_check_const_result=m4_default([$3], ['-1'])])-AS_VAR_SET(fp_Cache, [$fp_check_const_result])])[]dnl-AC_DEFINE_UNQUOTED(AS_TR_CPP([CONST_$1]), AS_VAR_GET(fp_Cache), [The value of $1.])[]dnl-AS_VAR_POPDEF([fp_Cache])[]dnl-])# FP_CHECK_CONST---# FP_CHECK_CONSTS_TEMPLATE(EXPRESSION...)-# ----------------------------------------# autoheader helper for FP_CHECK_CONSTS-m4_define([FP_CHECK_CONSTS_TEMPLATE],-[AC_FOREACH([fp_Const], [$1],-  [AH_TEMPLATE(AS_TR_CPP(CONST_[]fp_Const),-               [The value of ]fp_Const[.])])[]dnl-])# FP_CHECK_CONSTS_TEMPLATE---# FP_CHECK_CONSTS(EXPRESSION..., [INCLUDES = DEFAULT-INCLUDES], [VALUE-IF-FAIL = -1])-# ------------------------------------------------------------------------------------# List version of FP_CHECK_CONST-AC_DEFUN([FP_CHECK_CONSTS],-[FP_CHECK_CONSTS_TEMPLATE([$1])dnl-for fp_const_name in $1-do-FP_CHECK_CONST([$fp_const_name], [$2], [$3])-done-])# FP_CHECK_CONSTS---dnl FPTOOLS_HTYPE_INCLUDES-AC_DEFUN([FPTOOLS_HTYPE_INCLUDES],-[-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-])---dnl ** Map an arithmetic C type to a Haskell type.-dnl    Based on autconf's AC_CHECK_SIZEOF.--dnl FPTOOLS_CHECK_HTYPE_ELSE(TYPE, WHAT_TO_DO_IF_TYPE_DOES_NOT_EXIST)-AC_DEFUN([FPTOOLS_CHECK_HTYPE_ELSE],[-    changequote(<<, >>)-    dnl The name to #define.-    define(<<AC_TYPE_NAME>>, translit(htype_$1, [a-z *], [A-Z_P]))-    dnl The cache variable names.-    define(<<AC_CV_NAME>>, translit(fptools_cv_htype_$1, [ *], [_p]))-    define(<<AC_CV_NAME_supported>>, translit(fptools_cv_htype_sup_$1, [ *], [_p]))-    changequote([, ])--    AC_MSG_CHECKING(Haskell type for $1)-    AC_CACHE_VAL(AC_CV_NAME,[-        AC_CV_NAME_supported=yes-        FP_COMPUTE_INT([HTYPE_IS_INTEGRAL],-                       [($1)0.2 - ($1)0.4 < 0 ? 0 : 1],-                       [FPTOOLS_HTYPE_INCLUDES],[HTYPE_IS_INTEGRAL=0])--        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            FP_COMPUTE_INT([HTYPE_IS_FLOAT],[sizeof($1) == sizeof(float)],-                           [FPTOOLS_HTYPE_INCLUDES],-                           [AC_CV_NAME_supported=no])-            FP_COMPUTE_INT([HTYPE_IS_DOUBLE],[sizeof($1) == sizeof(double)],-                           [FPTOOLS_HTYPE_INCLUDES],-                           [AC_CV_NAME_supported=no])-            FP_COMPUTE_INT([HTYPE_IS_LDOUBLE],[sizeof($1) == sizeof(long double)],-                           [FPTOOLS_HTYPE_INCLUDES],-                           [AC_CV_NAME_supported=no])-            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                AC_CV_NAME=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                AC_CV_NAME=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                AC_CV_NAME=LDouble-            else-                AC_CV_NAME_supported=no-            fi-        else-            FP_COMPUTE_INT([HTYPE_IS_SIGNED],[(($1)(-1)) < (($1)0)],-                           [FPTOOLS_HTYPE_INCLUDES],-                           [AC_CV_NAME_supported=no])-            FP_COMPUTE_INT([HTYPE_SIZE],[sizeof($1) * 8],-                           [FPTOOLS_HTYPE_INCLUDES],-                           [AC_CV_NAME_supported=no])-            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                AC_CV_NAME="Word$HTYPE_SIZE"-            else-                AC_CV_NAME="Int$HTYPE_SIZE"-            fi-        fi-    ])-    if test "$AC_CV_NAME_supported" = no-    then-        $2-    fi--    dnl Note: evaluating dollar-2 can change the value of-    dnl $AC_CV_NAME_supported, so we might now get a different answer-    if test "$AC_CV_NAME_supported" = yes; then-        AC_MSG_RESULT($AC_CV_NAME)-        AC_DEFINE_UNQUOTED(AC_TYPE_NAME, $AC_CV_NAME,-                           [Define to Haskell type for $1])-    fi-    undefine([AC_TYPE_NAME])dnl-    undefine([AC_CV_NAME])dnl-    undefine([AC_CV_NAME_supported])dnl-])--dnl FPTOOLS_CHECK_HTYPE(TYPE)-AC_DEFUN([FPTOOLS_CHECK_HTYPE],[-    FPTOOLS_CHECK_HTYPE_ELSE([$1],[-        AC_CV_NAME=NotReallyAType-        AC_MSG_RESULT([not supported])-    ])-])---# FP_SEARCH_LIBS_PROTO(WHAT, PROTOTYPE, FUNCTION, SEARCH-LIBS,-#                [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND],-#                [OTHER-LIBRARIES])-# ---------------------------------------------------------# Search for a library defining FUNC, if it's not already available.-# This is a copy of the AC_SEARCH_LIBS definition, but extended to take-# the name of the thing we are looking for as its first argument, and-# prototype text as its second argument. It also calls AC_LANG_PROGRAM-# instead of AC_LANG_CALL-AC_DEFUN([FP_SEARCH_LIBS_PROTO],-[AS_VAR_PUSHDEF([ac_Search], [ac_cv_search_$1])dnl-AC_CACHE_CHECK([for library containing $1], [ac_Search],-[ac_func_search_save_LIBS=$LIBS-AC_LANG_CONFTEST([AC_LANG_PROGRAM([$2], [$3])])-for ac_lib in '' $4; do-  if test -z "$ac_lib"; then-    ac_res="none required"-  else-    ac_res=-l$ac_lib-    LIBS="-l$ac_lib $7 $ac_func_search_save_LIBS"-  fi-  AC_LINK_IFELSE([], [AS_VAR_SET([ac_Search], [$ac_res])])-  AS_VAR_SET_IF([ac_Search], [break])-done-AS_VAR_SET_IF([ac_Search], , [AS_VAR_SET([ac_Search], [no])])-rm conftest.$ac_ext-LIBS=$ac_func_search_save_LIBS])-ac_res=AS_VAR_GET([ac_Search])-AS_IF([test "$ac_res" != no],-  [test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"-  $5],-      [$6])dnl-AS_VAR_POPDEF([ac_Search])dnl-])
− base.buildinfo.in
@@ -1,4 +0,0 @@-extra-lib-dirs: @ICONV_LIB_DIRS@-extra-libraries: @EXTRA_LIBS@-include-dirs: @ICONV_INCLUDE_DIRS@-install-includes: HsBaseConfig.h EventConfig.h
base.cabal view
@@ -1,357 +1,320 @@+cabal-version:  3.0++-- WARNING: ghc-experimental.cabal is automatically generated from ghc-experimental.cabal.in+-- Make sure you are editing ghc-experimental.cabal.in, not ghc-experimental.cabal+ name:           base-version:        4.8.2.0+version:        4.22.0.0 -- NOTE: Don't forget to update ./changelog.md-license:        BSD3++license:        BSD-3-Clause license-file:   LICENSE-maintainer:     libraries@haskell.org-bug-reports:    http://ghc.haskell.org/trac/ghc/newticket?component=libraries/base-synopsis:       Basic libraries+maintainer:     Core Libraries Committee <core-libraries-committee@haskell.org>+bug-reports:    https://github.com/haskell/core-libraries-committee/issues+synopsis:       Core data structures and operations category:       Prelude-description:-    This package contains the "Prelude" and its support libraries,-    and a large collection of useful libraries ranging from data-    structures to parsing combinators and debugging utilities.-cabal-version:  >=1.10-build-type:     Configure+build-type:     Simple+description:    Haskell's base library provides, among other things, core types (e.g. [Bool]("Data.Bool") and [Int]("Data.Int")),+                data structures (e.g. [List]("Data.List"), [Tuple]("Data.Tuple") and [Maybe]("Data.Maybe")),+                the [Exception]("Control.Exception") mechanism, and the [IO]("System.IO") & [Concurrency]("Control.Concurrent") operations.+                The "Prelude" module, which is imported by default, exposes a curated set of types and functions from other modules. -extra-tmp-files:-    autom4te.cache-    base.buildinfo-    config.log-    config.status-    include/EventConfig.h-    include/HsBaseConfig.h+                Other data structures like [Map](https://hackage.haskell.org/package/containers/docs/Data-Map.html),+                [Set](https://hackage.haskell.org/package/containers/docs/Data-Set.html) are available in the [containers](https://hackage.haskell.org/package/containers) library.+                To work with textual data, use the [text](https://hackage.haskell.org/package/text/docs/Data-Text.html) library. -extra-source-files:-    aclocal.m4-    base.buildinfo.in+extra-doc-files:     changelog.md-    config.guess-    config.sub-    configure-    configure.ac-    include/CTypes.h-    include/EventConfig.h.in-    include/HsBaseConfig.h.in-    include/ieee-flpt.h-    include/md5.h-    install-sh -source-repository head-    type:     git-    location: http://git.haskell.org/ghc.git-    subdir:   libraries/base--Flag integer-simple-    Description: Use integer-simple-    Manual: True-    Default: False--Flag integer-gmp-    Description: Use integer-gmp-    Manual: True-    Default: False--Flag integer-gmp2-    Description: Use integer-gmp2-    Manual: True-    Default: False- Library     default-language: Haskell2010-    other-extensions:-        AutoDeriveTypeable-        BangPatterns-        CApiFFI-        CPP-        ConstraintKinds-        DataKinds-        DeriveDataTypeable-        DeriveGeneric-        ExistentialQuantification-        ExplicitForAll-        FlexibleContexts-        FlexibleInstances-        FunctionalDependencies-        GADTs-        GeneralizedNewtypeDeriving-        KindSignatures-        MagicHash-        MultiParamTypeClasses-        NegativeLiterals-        NoImplicitPrelude-        NondecreasingIndentation-        OverloadedStrings-        ParallelArrays-        PolyKinds-        RankNTypes-        RecordWildCards-        RoleAnnotations-        Safe-        ScopedTypeVariables-        StandaloneDeriving-        Trustworthy-        TypeFamilies-        TypeOperators-        TypeSynonymInstances-        UnboxedTuples-        UndecidableInstances-        UnliftedFFITypes-        Unsafe--    build-depends: rts == 1.0.*, ghc-prim == 0.4.*-    if flag(integer-simple)-        build-depends: integer-simple >= 0.1.1 && < 0.2--    if flag(integer-gmp)-        build-depends: integer-gmp >= 0.5.1 && < 0.6-        cpp-options: -DOPTIMISE_INTEGER_GCD_LCM--    if flag(integer-gmp2)-        build-depends: integer-gmp >= 1.0 && < 1.1-        cpp-options: -DOPTIMISE_INTEGER_GCD_LCM+    default-extensions: NoImplicitPrelude+    build-depends:+        ghc-internal == 9.1401.*,+        ghc-prim,      exposed-modules:-        Control.Applicative-        Control.Arrow-        Control.Category-        Control.Concurrent-        Control.Concurrent.Chan-        Control.Concurrent.MVar-        Control.Concurrent.QSem-        Control.Concurrent.QSemN-        Control.Exception-        Control.Exception.Base-        Control.Monad-        Control.Monad.Fix-        Control.Monad.Instances-        Control.Monad.ST-        Control.Monad.ST.Lazy-        Control.Monad.ST.Lazy.Safe-        Control.Monad.ST.Lazy.Unsafe-        Control.Monad.ST.Safe-        Control.Monad.ST.Strict-        Control.Monad.ST.Unsafe-        Control.Monad.Zip-        Data.Bifunctor-        Data.Bits-        Data.Bool-        Data.Char-        Data.Coerce-        Data.Complex-        Data.Data-        Data.Dynamic-        Data.Either-        Data.Eq-        Data.Fixed-        Data.Foldable-        Data.Function-        Data.Functor-        Data.Functor.Identity-        Data.IORef-        Data.Int-        Data.Ix-        Data.List-        Data.Maybe-        Data.Monoid-        Data.Ord-        Data.Proxy-        Data.Ratio-        Data.STRef-        Data.STRef.Lazy-        Data.STRef.Strict-        Data.String-        Data.Traversable-        Data.Tuple-        Data.Type.Bool-        Data.Type.Coercion-        Data.Type.Equality-        Data.Typeable-        Data.Typeable.Internal-        Data.Unique-        Data.Version-        Data.Void-        Data.Word-        Debug.Trace-        Foreign-        Foreign.C-        Foreign.C.Error-        Foreign.C.String-        Foreign.C.Types-        Foreign.Concurrent-        Foreign.ForeignPtr-        Foreign.ForeignPtr.Safe-        Foreign.ForeignPtr.Unsafe-        Foreign.Marshal-        Foreign.Marshal.Alloc-        Foreign.Marshal.Array-        Foreign.Marshal.Error-        Foreign.Marshal.Pool-        Foreign.Marshal.Safe-        Foreign.Marshal.Unsafe-        Foreign.Marshal.Utils-        Foreign.Ptr-        Foreign.Safe-        Foreign.StablePtr-        Foreign.Storable-        GHC.Arr-        GHC.Base-        GHC.Char-        GHC.Conc-        GHC.Conc.IO-        GHC.Conc.Signal-        GHC.Conc.Sync-        GHC.ConsoleHandler-        GHC.Constants-        GHC.Desugar-        GHC.Enum-        GHC.Environment-        GHC.Err-        GHC.Exception-        GHC.Exts-        GHC.Fingerprint-        GHC.Fingerprint.Type-        GHC.Float-        GHC.Float.ConversionUtils-        GHC.Float.RealFracMethods-        GHC.Foreign-        GHC.ForeignPtr-        GHC.GHCi-        GHC.Generics-        GHC.IO-        GHC.IO.Buffer-        GHC.IO.BufferedIO-        GHC.IO.Device-        GHC.IO.Encoding-        GHC.IO.Encoding.CodePage-        GHC.IO.Encoding.Failure-        GHC.IO.Encoding.Iconv-        GHC.IO.Encoding.Latin1-        GHC.IO.Encoding.Types-        GHC.IO.Encoding.UTF16-        GHC.IO.Encoding.UTF32-        GHC.IO.Encoding.UTF8-        GHC.IO.Exception-        GHC.IO.FD-        GHC.IO.Handle-        GHC.IO.Handle.FD-        GHC.IO.Handle.Internals-        GHC.IO.Handle.Text-        GHC.IO.Handle.Types-        GHC.IO.IOMode-        GHC.IOArray-        GHC.IORef-        GHC.IP-        GHC.Int-        GHC.List-        GHC.MVar-        GHC.Natural-        GHC.Num-        GHC.OldList-        GHC.PArr-        GHC.Pack-        GHC.Profiling-        GHC.Ptr-        GHC.Read-        GHC.Real-        GHC.RTS.Flags-        GHC.ST-        GHC.StaticPtr-        GHC.STRef-        GHC.Show-        GHC.SrcLoc-        GHC.Stable-        GHC.Stack-        GHC.Stats-        GHC.Storable-        GHC.TopHandler-        GHC.TypeLits-        GHC.Unicode-        GHC.Weak-        GHC.Word-        Numeric-        Numeric.Natural-        Prelude-        System.CPUTime-        System.Console.GetOpt-        System.Environment-        System.Exit-        System.IO-        System.IO.Error-        System.IO.Unsafe-        System.Info-        System.Mem-        System.Mem.StableName-        System.Mem.Weak-        System.Posix.Internals-        System.Posix.Types-        System.Timeout-        Text.ParserCombinators.ReadP-        Text.ParserCombinators.ReadPrec-        Text.Printf-        Text.Read-        Text.Read.Lex-        Text.Show-        Text.Show.Functions-        Unsafe.Coerce--    other-modules:-        Control.Monad.ST.Imp-        Control.Monad.ST.Lazy.Imp-        Data.OldList-        Foreign.ForeignPtr.Imp-        System.Environment.ExecutablePath--    c-sources:-        cbits/DarwinUtils.c-        cbits/PrelIOUtils.c-        cbits/SetEnv.c-        cbits/WCsubst.c-        cbits/Win32Utils.c-        cbits/consUtils.c-        cbits/iconv.c-        cbits/inputReady.c-        cbits/md5.c-        cbits/primFloat.c-        cbits/rts.c-        cbits/sysconf.c+          Control.Applicative+        , Control.Concurrent+        , Control.Concurrent.Chan+        , Control.Concurrent.QSem+        , Control.Concurrent.QSemN+        , Control.Monad.IO.Class+        , Control.Monad.Zip+        , Data.Array.Byte+        , Data.Bifoldable+        , Data.Bifoldable1+        , Data.Bifunctor+        , Data.Bitraversable+        , Data.Bounded+        , Data.Char+        , Data.Complex+        , Data.Enum+        , Data.Fixed+        , Data.Foldable1+        , Data.Functor.Classes+        , Data.Functor.Compose+        , Data.Functor.Contravariant+        , Data.Functor.Sum+        , Data.Functor.Product+        , Data.List.NonEmpty+        , Data.Ratio+        , Data.STRef.Lazy+        , Data.Semigroup+        , Prelude+        , Text.Printf+        , System.CPUTime+        , System.Console.GetOpt+        , System.IO.Unsafe+        , System.Info+        , System.Mem.Weak+        , System.Timeout -    include-dirs: include-    includes:-        HsBase.h-    install-includes:-        HsBase.h-        WCsubst.h-        consUtils.h-        Typeable.h+    exposed-modules:+        , Control.Arrow+        , Control.Category+        , Control.Concurrent.MVar+        , Control.Exception+        , Control.Exception.Annotation+        , Control.Exception.Backtrace+        , Control.Exception.Base+        , Control.Exception.Context+        , Control.Monad+        , Control.Monad.Fail+        , Control.Monad.Fix+        , Control.Monad.Instances+        , Control.Monad.ST+        , Control.Monad.ST.Lazy+        , Control.Monad.ST.Lazy.Safe+        , Control.Monad.ST.Lazy.Unsafe+        , Control.Monad.ST.Safe+        , Control.Monad.ST.Strict+        , Control.Monad.ST.Unsafe+        , Data.Bits+        , Data.Bool+        , Data.Coerce+        , Data.Data+        , Data.Dynamic+        , Data.Either+        , Data.Eq+        , Data.Foldable+        , Data.Function+        , Data.Functor+        , Data.Functor.Const+        , Data.Functor.Identity+        , Data.IORef+        , Data.Int+        , Data.Ix+        , Data.Kind+        , Data.List+        , Data.Maybe+        , Data.Monoid+        , Data.Ord+        , Data.Proxy+        , Data.STRef+        , Data.STRef.Strict+        , Data.String+        , Data.Traversable+        , Data.Tuple+        , Data.Type.Bool+        , Data.Type.Coercion+        , Data.Type.Equality+        , Data.Type.Ord+        , Data.Typeable+        , Data.Unique+        , Data.Version+        , Data.Void+        , Data.Word+        , Debug.Trace+        , Foreign+        , Foreign.C+        , Foreign.C.ConstPtr+        , Foreign.C.Error+        , Foreign.C.String+        , Foreign.C.Types+        , Foreign.Concurrent+        , Foreign.ForeignPtr+        , Foreign.ForeignPtr.Safe+        , Foreign.ForeignPtr.Unsafe+        , Foreign.Marshal+        , Foreign.Marshal.Alloc+        , Foreign.Marshal.Array+        , Foreign.Marshal.Error+        , Foreign.Marshal.Pool+        , Foreign.Marshal.Safe+        , Foreign.Marshal.Unsafe+        , Foreign.Marshal.Utils+        , Foreign.Ptr+        , Foreign.Safe+        , Foreign.StablePtr+        , Foreign.Storable+        , GHC.Arr+        , GHC.ArrayArray+        , GHC.Base+        , GHC.Bits+        , GHC.ByteOrder+        , GHC.Char+        , GHC.Clock+        , GHC.Conc+        , GHC.Conc.IO+        , GHC.Conc.Signal+        , GHC.Conc.Sync+        , GHC.ConsoleHandler+        , GHC.Constants+        , GHC.Desugar+        , GHC.Encoding.UTF8+        , GHC.Enum+        , GHC.Environment+        , GHC.Err+        , GHC.Event.TimeOut+        , GHC.Exception+        , GHC.Exception.Type+        , GHC.ExecutionStack+        , GHC.Exts+        , GHC.Fingerprint+        , GHC.Fingerprint.Type+        , GHC.Float+        , GHC.Float.ConversionUtils+        , GHC.Float.RealFracMethods+        , GHC.Foreign+        , GHC.ForeignPtr+        , GHC.GHCi+        , GHC.GHCi.Helpers+        , GHC.Generics+        , GHC.InfoProv+        , GHC.IO+        , GHC.IO.Buffer+        , GHC.IO.BufferedIO+        , GHC.IO.Device+        , GHC.IO.Encoding+        , GHC.IO.Encoding.CodePage+        , GHC.IO.Encoding.Failure+        , GHC.IO.Encoding.Iconv+        , GHC.IO.Encoding.Latin1+        , GHC.IO.Encoding.Types+        , GHC.IO.Encoding.UTF16+        , GHC.IO.Encoding.UTF32+        , GHC.IO.Encoding.UTF8+        , GHC.IO.Exception+        , GHC.IO.FD+        , GHC.IO.Handle+        , GHC.IO.Handle.FD+        , GHC.IO.Handle.Internals+        , GHC.IO.Handle.Lock+        , GHC.IO.Handle.Text+        , GHC.IO.Handle.Types+        , GHC.IO.IOMode+        , GHC.IO.Unsafe+        , GHC.IO.StdHandles+        , GHC.IO.SubSystem+        , GHC.IOArray+        , GHC.IORef+        , GHC.Int+        , GHC.Integer+        , GHC.Integer.Logarithms+        , GHC.IsList+        , GHC.Ix+        , GHC.List+        , GHC.Maybe+        , GHC.MVar+        , GHC.Natural+        , GHC.Num+        , GHC.Num.Integer+        , GHC.Num.Natural+        , GHC.Num.BigNat+        , GHC.OldList+        , GHC.OverloadedLabels+        , GHC.Profiling+        , GHC.Ptr+        , GHC.Read+        , GHC.Real+        , GHC.Records+        , GHC.ResponseFile+        , GHC.RTS.Flags+        , GHC.ST+        , GHC.Stack.CloneStack+        , GHC.StaticPtr+        , GHC.STRef+        , GHC.Show+        , GHC.Stable+        , GHC.StableName+        , GHC.Stack+        , GHC.Stack.CCS+        , GHC.Stack.Types+        , GHC.Stats+        , GHC.Storable+        , GHC.TopHandler+        , GHC.TypeError+        , GHC.TypeLits+        , GHC.TypeNats+        , GHC.Unicode+        , GHC.Weak+        , GHC.Weak.Finalize+        , GHC.Word+        , Numeric+        , Numeric.Natural+        , System.Environment+        , System.Environment.Blank+        , System.Exit+        , System.IO+        , System.IO.Error+        , System.Mem+        , System.Mem.StableName+        , System.Posix.Internals+        , System.Posix.Types+        , Text.ParserCombinators.ReadP+        , Text.ParserCombinators.ReadPrec+        , Text.Read+        , Text.Read.Lex+        , Text.Show+        , Text.Show.Functions+        , Type.Reflection+        , Type.Reflection.Unsafe+        , Unsafe.Coerce -    -- OS Specific     if os(windows)-        extra-libraries: wsock32, user32, shell32         exposed-modules:-            GHC.IO.Encoding.CodePage.API-            GHC.IO.Encoding.CodePage.Table-            GHC.Conc.Windows-            GHC.Windows+              GHC.IO.Encoding.CodePage.API+            , GHC.IO.Encoding.CodePage.Table+            , GHC.Conc.Windows+            , GHC.Conc.WinIO+            , GHC.Conc.POSIX+            , GHC.Conc.POSIX.Const+            , GHC.Windows+            , GHC.Event.Windows+            , GHC.Event.Windows.Clock+            , GHC.Event.Windows.ConsoleEvent+            , GHC.Event.Windows.FFI+            , GHC.Event.Windows.ManagedThreadPool+            , GHC.Event.Windows.Thread+            , GHC.IO.Handle.Windows+            , GHC.IO.Windows.Handle+            , GHC.IO.Windows.Encoding+            , GHC.IO.Windows.Paths     else         exposed-modules:             GHC.Event-        other-modules:-            GHC.Event.Arr-            GHC.Event.Array-            GHC.Event.Clock-            GHC.Event.Control-            GHC.Event.EPoll-            GHC.Event.IntTable-            GHC.Event.Internal-            GHC.Event.KQueue-            GHC.Event.Manager-            GHC.Event.PSQ-            GHC.Event.Poll-            GHC.Event.Thread-            GHC.Event.TimerManager-            GHC.Event.Unique -    -- We need to set the package key to base (without a version number)-    -- as it's magic.-    ghc-options: -this-package-key base+    if arch(javascript)+        exposed-modules:+              GHC.JS.Prim+            , GHC.JS.Prim.Internal+            , GHC.JS.Prim.Internal.Build+            , GHC.JS.Foreign.Callback++    other-modules:+        System.CPUTime.Unsupported+        System.CPUTime.Utils+    if os(windows)+      other-modules:+        System.CPUTime.Windows+    elif arch(javascript)+      other-modules:+        System.CPUTime.Javascript+    else+      other-modules:+        System.CPUTime.Posix.ClockGetTime+        System.CPUTime.Posix.Times+        System.CPUTime.Posix.RUsage++    hs-source-dirs: src
− cbits/DarwinUtils.c
@@ -1,22 +0,0 @@-#include "HsBase.h"--#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)-#include <mach/mach_time.h>--static double scaling_factor = 0.0;--void initialize_timer()-{-    mach_timebase_info_data_t info;-    (void) mach_timebase_info(&info);-    scaling_factor = (double)info.numer / (double)info.denom;-    scaling_factor *= 1e-9;-}--void absolute_time(double *result)-{-    uint64_t time = mach_absolute_time();-    *result = (double)time * scaling_factor;-}--#endif
− cbits/PrelIOUtils.c
@@ -1,45 +0,0 @@-/*- * (c) The University of Glasgow 2002- *- * static versions of the inline functions in HsBase.h- */--#define INLINE--#include "Rts.h"-#include "HsBase.h"--void errorBelch2(const char*s, char *t)-{-    errorBelch(s,t);-}--void debugBelch2(const char*s, char *t)-{-    debugBelch(s,t);-}--#if defined(HAVE_LIBCHARSET)-#  include <libcharset.h>-#elif defined(HAVE_LANGINFO_H)-#  include <langinfo.h>-#endif--#if !defined(mingw32_HOST_OS)-const char* localeEncoding(void)-{-#if defined(HAVE_LIBCHARSET)-    return locale_charset();--#elif defined(HAVE_LANGINFO_H)-    return nl_langinfo(CODESET);--#else-#warning Depending on the unportable behavior of GNU iconv due to absence of both libcharset and langinfo.h-    /* GNU iconv accepts "" to mean the current locale's-     * encoding. Warning: This isn't portable.-     */-    return "";-#endif-}-#endif
− cbits/SetEnv.c
@@ -1,11 +0,0 @@-#include "HsBase.h"-#ifdef HAVE_UNSETENV-int __hsbase_unsetenv(const char *name) {-#ifdef UNSETENV_RETURNS_VOID-    unsetenv(name);-    return 0;-#else-    return unsetenv(name);-#endif-}-#endif
− cbits/WCsubst.c
@@ -1,4748 +0,0 @@-/*--------------------------------------------------------------------------This is an automatically generated file: do not edit-Generated by ubconfc at Wed Oct 15 14:24:39 EDT 2014-@generated--------------------------------------------------------------------------*/--#include "WCsubst.h"--/* Unicode general categories, listed in the same order as in the Unicode- * standard -- this must be the same order as in GHC.Unicode.- */--enum {-    NUMCAT_LU,  /* Letter, Uppercase */-    NUMCAT_LL,  /* Letter, Lowercase */-    NUMCAT_LT,  /* Letter, Titlecase */-    NUMCAT_LM,  /* Letter, Modifier */-    NUMCAT_LO,  /* Letter, Other */-    NUMCAT_MN,  /* Mark, Non-Spacing */-    NUMCAT_MC,  /* Mark, Spacing Combining */-    NUMCAT_ME,  /* Mark, Enclosing */-    NUMCAT_ND,  /* Number, Decimal */-    NUMCAT_NL,  /* Number, Letter */-    NUMCAT_NO,  /* Number, Other */-    NUMCAT_PC,  /* Punctuation, Connector */-    NUMCAT_PD,  /* Punctuation, Dash */-    NUMCAT_PS,  /* Punctuation, Open */-    NUMCAT_PE,  /* Punctuation, Close */-    NUMCAT_PI,  /* Punctuation, Initial quote */-    NUMCAT_PF,  /* Punctuation, Final quote */-    NUMCAT_PO,  /* Punctuation, Other */-    NUMCAT_SM,  /* Symbol, Math */-    NUMCAT_SC,  /* Symbol, Currency */-    NUMCAT_SK,  /* Symbol, Modifier */-    NUMCAT_SO,  /* Symbol, Other */-    NUMCAT_ZS,  /* Separator, Space */-    NUMCAT_ZL,  /* Separator, Line */-    NUMCAT_ZP,  /* Separator, Paragraph */-    NUMCAT_CC,  /* Other, Control */-    NUMCAT_CF,  /* Other, Format */-    NUMCAT_CS,  /* Other, Surrogate */-    NUMCAT_CO,  /* Other, Private Use */-    NUMCAT_CN   /* Other, Not Assigned */-};--struct _convrule_ -{ -	unsigned int category;-	unsigned int catnumber;-	int possible;-	int updist;-	int lowdist; -	int titledist;-};--struct _charblock_ -{ -	int start;-	int length;-	const struct _convrule_ *rule;-};--#define GENCAT_ZP 67108864-#define GENCAT_MC 8388608-#define GENCAT_NO 131072-#define GENCAT_SK 1024-#define GENCAT_CO 268435456-#define GENCAT_ME 4194304-#define GENCAT_ND 256-#define GENCAT_PO 4-#define GENCAT_LT 524288-#define GENCAT_PC 2048-#define GENCAT_SM 64-#define GENCAT_ZS 2-#define GENCAT_CC 1-#define GENCAT_LU 512-#define GENCAT_PD 128-#define GENCAT_SO 8192-#define GENCAT_PE 32-#define GENCAT_CS 134217728-#define GENCAT_PF 262144-#define GENCAT_CF 65536-#define GENCAT_PS 16-#define GENCAT_SC 8-#define GENCAT_LL 4096-#define GENCAT_ZL 33554432-#define GENCAT_LM 1048576-#define GENCAT_PI 32768-#define GENCAT_NL 16777216-#define GENCAT_MN 2097152-#define GENCAT_LO 16384-#define MAX_UNI_CHAR 1114109-#define NUM_BLOCKS 3073-#define NUM_CONVBLOCKS 1276-#define NUM_SPACEBLOCKS 7-#define NUM_LAT1BLOCKS 63-#define NUM_RULES 181-static const struct _convrule_ rule169={GENCAT_LU, NUMCAT_LU, 1, 0, -35332, 0};-static const struct _convrule_ rule157={GENCAT_SO, NUMCAT_SO, 1, -26, 0, -26};-static const struct _convrule_ rule168={GENCAT_LL, NUMCAT_LL, 1, -7264, 0, -7264};-static const struct _convrule_ rule173={GENCAT_LU, NUMCAT_LU, 1, 0, -42315, 0};-static const struct _convrule_ rule129={GENCAT_LL, NUMCAT_LL, 1, 8, 0, 8};-static const struct _convrule_ rule88={GENCAT_LL, NUMCAT_LL, 1, 42258, 0, 42258};-static const struct _convrule_ rule20={GENCAT_LL, NUMCAT_LL, 0, 0, 0, 0};-static const struct _convrule_ rule76={GENCAT_LL, NUMCAT_LL, 1, 10743, 0, 10743};-static const struct _convrule_ rule61={GENCAT_LL, NUMCAT_LL, 1, 10783, 0, 10783};-static const struct _convrule_ rule37={GENCAT_LU, NUMCAT_LU, 1, 0, 211, 0};-static const struct _convrule_ rule80={GENCAT_LL, NUMCAT_LL, 1, -214, 0, -214};-static const struct _convrule_ rule75={GENCAT_LL, NUMCAT_LL, 1, -211, 0, -211};-static const struct _convrule_ rule121={GENCAT_LL, NUMCAT_LL, 1, -48, 0, -48};-static const struct _convrule_ rule52={GENCAT_LU, NUMCAT_LU, 1, 0, -56, 0};-static const struct _convrule_ rule135={GENCAT_LL, NUMCAT_LL, 1, 112, 0, 112};-static const struct _convrule_ rule71={GENCAT_LL, NUMCAT_LL, 1, -207, 0, -207};-static const struct _convrule_ rule123={GENCAT_LU, NUMCAT_LU, 1, 0, 7264, 0};-static const struct _convrule_ rule152={GENCAT_LU, NUMCAT_LU, 1, 0, 28, 0};-static const struct _convrule_ rule159={GENCAT_LU, NUMCAT_LU, 1, 0, -3814, 0};-static const struct _convrule_ rule45={GENCAT_LU, NUMCAT_LU, 1, 0, 219, 0};-static const struct _convrule_ rule7={GENCAT_PD, NUMCAT_PD, 0, 0, 0, 0};-static const struct _convrule_ rule180={GENCAT_LL, NUMCAT_LL, 1, -40, 0, -40};-static const struct _convrule_ rule97={GENCAT_LL, NUMCAT_LL, 1, -38, 0, -38};-static const struct _convrule_ rule95={GENCAT_LU, NUMCAT_LU, 1, 0, 64, 0};-static const struct _convrule_ rule1={GENCAT_ZS, NUMCAT_ZS, 0, 0, 0, 0};-static const struct _convrule_ rule29={GENCAT_LU, NUMCAT_LU, 1, 0, 210, 0};-static const struct _convrule_ rule35={GENCAT_LU, NUMCAT_LU, 1, 0, 207, 0};-static const struct _convrule_ rule154={GENCAT_NL, NUMCAT_NL, 1, 0, 16, 0};-static const struct _convrule_ rule13={GENCAT_SO, NUMCAT_SO, 0, 0, 0, 0};-static const struct _convrule_ rule149={GENCAT_LU, NUMCAT_LU, 1, 0, -7517, 0};-static const struct _convrule_ rule128={GENCAT_LU, NUMCAT_LU, 1, 0, -7615, 0};-static const struct _convrule_ rule98={GENCAT_LL, NUMCAT_LL, 1, -37, 0, -37};-static const struct _convrule_ rule2={GENCAT_PO, NUMCAT_PO, 0, 0, 0, 0};-static const struct _convrule_ rule69={GENCAT_LL, NUMCAT_LL, 1, 42319, 0, 42319};-static const struct _convrule_ rule56={GENCAT_LU, NUMCAT_LU, 1, 0, 10792, 0};-static const struct _convrule_ rule25={GENCAT_LL, NUMCAT_LL, 1, -232, 0, -232};-static const struct _convrule_ rule43={GENCAT_LU, NUMCAT_LU, 1, 0, 218, 0};-static const struct _convrule_ rule165={GENCAT_LU, NUMCAT_LU, 1, 0, -10783, 0};-static const struct _convrule_ rule133={GENCAT_LL, NUMCAT_LL, 1, 100, 0, 100};-static const struct _convrule_ rule96={GENCAT_LU, NUMCAT_LU, 1, 0, 63, 0};-static const struct _convrule_ rule90={GENCAT_MN, NUMCAT_MN, 0, 0, 0, 0};-static const struct _convrule_ rule12={GENCAT_LL, NUMCAT_LL, 1, -32, 0, -32};-static const struct _convrule_ rule93={GENCAT_LU, NUMCAT_LU, 1, 0, 38, 0};-static const struct _convrule_ rule99={GENCAT_LL, NUMCAT_LL, 1, -31, 0, -31};-static const struct _convrule_ rule105={GENCAT_LU, NUMCAT_LU, 0, 0, 0, 0};-static const struct _convrule_ rule11={GENCAT_PC, NUMCAT_PC, 0, 0, 0, 0};-static const struct _convrule_ rule175={GENCAT_LU, NUMCAT_LU, 1, 0, -42258, 0};-static const struct _convrule_ rule144={GENCAT_LU, NUMCAT_LU, 1, 0, -112, 0};-static const struct _convrule_ rule15={GENCAT_PI, NUMCAT_PI, 0, 0, 0, 0};-static const struct _convrule_ rule132={GENCAT_LL, NUMCAT_LL, 1, 86, 0, 86};-static const struct _convrule_ rule122={GENCAT_MC, NUMCAT_MC, 0, 0, 0, 0};-static const struct _convrule_ rule126={GENCAT_LL, NUMCAT_LL, 1, 3814, 0, 3814};-static const struct _convrule_ rule44={GENCAT_LU, NUMCAT_LU, 1, 0, 217, 0};-static const struct _convrule_ rule153={GENCAT_LL, NUMCAT_LL, 1, -28, 0, -28};-static const struct _convrule_ rule178={GENCAT_CO, NUMCAT_CO, 0, 0, 0, 0};-static const struct _convrule_ rule114={GENCAT_LL, NUMCAT_LL, 1, -96, 0, -96};-static const struct _convrule_ rule51={GENCAT_LU, NUMCAT_LU, 1, 0, -97, 0};-static const struct _convrule_ rule39={GENCAT_LL, NUMCAT_LL, 1, 163, 0, 163};-static const struct _convrule_ rule179={GENCAT_LU, NUMCAT_LU, 1, 0, 40, 0};-static const struct _convrule_ rule124={GENCAT_NL, NUMCAT_NL, 0, 0, 0, 0};-static const struct _convrule_ rule94={GENCAT_LU, NUMCAT_LU, 1, 0, 37, 0};-static const struct _convrule_ rule82={GENCAT_LL, NUMCAT_LL, 1, -218, 0, -218};-static const struct _convrule_ rule118={GENCAT_LU, NUMCAT_LU, 1, 0, 15, 0};-static const struct _convrule_ rule67={GENCAT_LL, NUMCAT_LL, 1, -202, 0, -202};-static const struct _convrule_ rule66={GENCAT_LL, NUMCAT_LL, 1, -205, 0, -205};-static const struct _convrule_ rule47={GENCAT_LU, NUMCAT_LU, 1, 0, 2, 1};-static const struct _convrule_ rule30={GENCAT_LU, NUMCAT_LU, 1, 0, 206, 0};-static const struct _convrule_ rule109={GENCAT_LL, NUMCAT_LL, 1, -86, 0, -86};-static const struct _convrule_ rule4={GENCAT_PS, NUMCAT_PS, 0, 0, 0, 0};-static const struct _convrule_ rule3={GENCAT_SC, NUMCAT_SC, 0, 0, 0, 0};-static const struct _convrule_ rule150={GENCAT_LU, NUMCAT_LU, 1, 0, -8383, 0};-static const struct _convrule_ rule120={GENCAT_LU, NUMCAT_LU, 1, 0, 48, 0};-static const struct _convrule_ rule14={GENCAT_LO, NUMCAT_LO, 0, 0, 0, 0};-static const struct _convrule_ rule18={GENCAT_LL, NUMCAT_LL, 1, 743, 0, 743};-static const struct _convrule_ rule147={GENCAT_ZL, NUMCAT_ZL, 0, 0, 0, 0};-static const struct _convrule_ rule142={GENCAT_LU, NUMCAT_LU, 1, 0, -86, 0};-static const struct _convrule_ rule171={GENCAT_LU, NUMCAT_LU, 1, 0, -42308, 0};-static const struct _convrule_ rule162={GENCAT_LL, NUMCAT_LL, 1, -10792, 0, -10792};-static const struct _convrule_ rule166={GENCAT_LU, NUMCAT_LU, 1, 0, -10782, 0};-static const struct _convrule_ rule139={GENCAT_LU, NUMCAT_LU, 1, 0, -74, 0};-static const struct _convrule_ rule24={GENCAT_LU, NUMCAT_LU, 1, 0, -199, 0};-static const struct _convrule_ rule143={GENCAT_LU, NUMCAT_LU, 1, 0, -100, 0};-static const struct _convrule_ rule125={GENCAT_LL, NUMCAT_LL, 1, 35332, 0, 35332};-static const struct _convrule_ rule141={GENCAT_LL, NUMCAT_LL, 1, -7205, 0, -7205};-static const struct _convrule_ rule138={GENCAT_LL, NUMCAT_LL, 1, 9, 0, 9};-static const struct _convrule_ rule27={GENCAT_LL, NUMCAT_LL, 1, -300, 0, -300};-static const struct _convrule_ rule172={GENCAT_LU, NUMCAT_LU, 1, 0, -42319, 0};-static const struct _convrule_ rule31={GENCAT_LU, NUMCAT_LU, 1, 0, 205, 0};-static const struct _convrule_ rule59={GENCAT_LU, NUMCAT_LU, 1, 0, 69, 0};-static const struct _convrule_ rule6={GENCAT_SM, NUMCAT_SM, 0, 0, 0, 0};-static const struct _convrule_ rule119={GENCAT_LL, NUMCAT_LL, 1, -15, 0, -15};-static const struct _convrule_ rule110={GENCAT_LL, NUMCAT_LL, 1, -80, 0, -80};-static const struct _convrule_ rule176={GENCAT_LU, NUMCAT_LU, 1, 0, -42282, 0};-static const struct _convrule_ rule151={GENCAT_LU, NUMCAT_LU, 1, 0, -8262, 0};-static const struct _convrule_ rule130={GENCAT_LU, NUMCAT_LU, 1, 0, -8, 0};-static const struct _convrule_ rule26={GENCAT_LU, NUMCAT_LU, 1, 0, -121, 0};-static const struct _convrule_ rule0={GENCAT_CC, NUMCAT_CC, 0, 0, 0, 0};-static const struct _convrule_ rule111={GENCAT_LL, NUMCAT_LL, 1, 7, 0, 7};-static const struct _convrule_ rule91={GENCAT_MN, NUMCAT_MN, 1, 84, 0, 84};-static const struct _convrule_ rule78={GENCAT_LL, NUMCAT_LL, 1, 10749, 0, 10749};-static const struct _convrule_ rule77={GENCAT_LL, NUMCAT_LL, 1, 42305, 0, 42305};-static const struct _convrule_ rule70={GENCAT_LL, NUMCAT_LL, 1, 42315, 0, 42315};-static const struct _convrule_ rule50={GENCAT_LL, NUMCAT_LL, 1, -79, 0, -79};-static const struct _convrule_ rule60={GENCAT_LU, NUMCAT_LU, 1, 0, 71, 0};-static const struct _convrule_ rule22={GENCAT_LU, NUMCAT_LU, 1, 0, 1, 0};-static const struct _convrule_ rule49={GENCAT_LL, NUMCAT_LL, 1, -2, 0, -1};-static const struct _convrule_ rule92={GENCAT_LU, NUMCAT_LU, 1, 0, 116, 0};-static const struct _convrule_ rule83={GENCAT_LL, NUMCAT_LL, 1, 42282, 0, 42282};-static const struct _convrule_ rule155={GENCAT_NL, NUMCAT_NL, 1, -16, 0, -16};-static const struct _convrule_ rule102={GENCAT_LU, NUMCAT_LU, 1, 0, 8, 0};-static const struct _convrule_ rule23={GENCAT_LL, NUMCAT_LL, 1, -1, 0, -1};-static const struct _convrule_ rule87={GENCAT_LL, NUMCAT_LL, 1, -219, 0, -219};-static const struct _convrule_ rule79={GENCAT_LL, NUMCAT_LL, 1, -213, 0, -213};-static const struct _convrule_ rule64={GENCAT_LL, NUMCAT_LL, 1, -210, 0, -210};-static const struct _convrule_ rule163={GENCAT_LU, NUMCAT_LU, 1, 0, -10780, 0};-static const struct _convrule_ rule86={GENCAT_LL, NUMCAT_LL, 1, -71, 0, -71};-static const struct _convrule_ rule84={GENCAT_LL, NUMCAT_LL, 1, -69, 0, -69};-static const struct _convrule_ rule32={GENCAT_LU, NUMCAT_LU, 1, 0, 79, 0};-static const struct _convrule_ rule115={GENCAT_LU, NUMCAT_LU, 1, 0, -7, 0};-static const struct _convrule_ rule74={GENCAT_LL, NUMCAT_LL, 1, -209, 0, -209};-static const struct _convrule_ rule177={GENCAT_CS, NUMCAT_CS, 0, 0, 0, 0};-static const struct _convrule_ rule140={GENCAT_LT, NUMCAT_LT, 1, 0, -9, 0};-static const struct _convrule_ rule57={GENCAT_LL, NUMCAT_LL, 1, 10815, 0, 10815};-static const struct _convrule_ rule72={GENCAT_LL, NUMCAT_LL, 1, 42280, 0, 42280};-static const struct _convrule_ rule34={GENCAT_LU, NUMCAT_LU, 1, 0, 203, 0};-static const struct _convrule_ rule63={GENCAT_LL, NUMCAT_LL, 1, 10782, 0, 10782};-static const struct _convrule_ rule170={GENCAT_LU, NUMCAT_LU, 1, 0, -42280, 0};-static const struct _convrule_ rule145={GENCAT_LU, NUMCAT_LU, 1, 0, -128, 0};-static const struct _convrule_ rule100={GENCAT_LL, NUMCAT_LL, 1, -64, 0, -64};-static const struct _convrule_ rule17={GENCAT_NO, NUMCAT_NO, 0, 0, 0, 0};-static const struct _convrule_ rule89={GENCAT_LM, NUMCAT_LM, 0, 0, 0, 0};-static const struct _convrule_ rule46={GENCAT_LL, NUMCAT_LL, 1, 56, 0, 56};-static const struct _convrule_ rule131={GENCAT_LL, NUMCAT_LL, 1, 74, 0, 74};-static const struct _convrule_ rule42={GENCAT_LU, NUMCAT_LU, 1, 0, 214, 0};-static const struct _convrule_ rule148={GENCAT_ZP, NUMCAT_ZP, 0, 0, 0, 0};-static const struct _convrule_ rule101={GENCAT_LL, NUMCAT_LL, 1, -63, 0, -63};-static const struct _convrule_ rule36={GENCAT_LL, NUMCAT_LL, 1, 97, 0, 97};-static const struct _convrule_ rule137={GENCAT_LT, NUMCAT_LT, 1, 0, -8, 0};-static const struct _convrule_ rule134={GENCAT_LL, NUMCAT_LL, 1, 128, 0, 128};-static const struct _convrule_ rule81={GENCAT_LL, NUMCAT_LL, 1, 10727, 0, 10727};-static const struct _convrule_ rule62={GENCAT_LL, NUMCAT_LL, 1, 10780, 0, 10780};-static const struct _convrule_ rule41={GENCAT_LL, NUMCAT_LL, 1, 130, 0, 130};-static const struct _convrule_ rule68={GENCAT_LL, NUMCAT_LL, 1, -203, 0, -203};-static const struct _convrule_ rule65={GENCAT_LL, NUMCAT_LL, 1, -206, 0, -206};-static const struct _convrule_ rule48={GENCAT_LT, NUMCAT_LT, 1, -1, 1, 0};-static const struct _convrule_ rule19={GENCAT_PF, NUMCAT_PF, 0, 0, 0, 0};-static const struct _convrule_ rule33={GENCAT_LU, NUMCAT_LU, 1, 0, 202, 0};-static const struct _convrule_ rule103={GENCAT_LL, NUMCAT_LL, 1, -62, 0, -62};-static const struct _convrule_ rule8={GENCAT_ND, NUMCAT_ND, 0, 0, 0, 0};-static const struct _convrule_ rule53={GENCAT_LU, NUMCAT_LU, 1, 0, -130, 0};-static const struct _convrule_ rule28={GENCAT_LL, NUMCAT_LL, 1, 195, 0, 195};-static const struct _convrule_ rule158={GENCAT_LU, NUMCAT_LU, 1, 0, -10743, 0};-static const struct _convrule_ rule127={GENCAT_LL, NUMCAT_LL, 1, -59, 0, -59};-static const struct _convrule_ rule113={GENCAT_LU, NUMCAT_LU, 1, 0, -60, 0};-static const struct _convrule_ rule108={GENCAT_LL, NUMCAT_LL, 1, -8, 0, -8};-static const struct _convrule_ rule73={GENCAT_LL, NUMCAT_LL, 1, 42308, 0, 42308};-static const struct _convrule_ rule40={GENCAT_LU, NUMCAT_LU, 1, 0, 213, 0};-static const struct _convrule_ rule136={GENCAT_LL, NUMCAT_LL, 1, 126, 0, 126};-static const struct _convrule_ rule116={GENCAT_LU, NUMCAT_LU, 1, 0, 80, 0};-static const struct _convrule_ rule55={GENCAT_LU, NUMCAT_LU, 1, 0, -163, 0};-static const struct _convrule_ rule174={GENCAT_LU, NUMCAT_LU, 1, 0, -42305, 0};-static const struct _convrule_ rule161={GENCAT_LL, NUMCAT_LL, 1, -10795, 0, -10795};-static const struct _convrule_ rule58={GENCAT_LU, NUMCAT_LU, 1, 0, -195, 0};-static const struct _convrule_ rule54={GENCAT_LU, NUMCAT_LU, 1, 0, 10795, 0};-static const struct _convrule_ rule107={GENCAT_LL, NUMCAT_LL, 1, -54, 0, -54};-static const struct _convrule_ rule146={GENCAT_LU, NUMCAT_LU, 1, 0, -126, 0};-static const struct _convrule_ rule104={GENCAT_LL, NUMCAT_LL, 1, -57, 0, -57};-static const struct _convrule_ rule21={GENCAT_LL, NUMCAT_LL, 1, 121, 0, 121};-static const struct _convrule_ rule156={GENCAT_SO, NUMCAT_SO, 1, 0, 26, 0};-static const struct _convrule_ rule85={GENCAT_LL, NUMCAT_LL, 1, -217, 0, -217};-static const struct _convrule_ rule16={GENCAT_CF, NUMCAT_CF, 0, 0, 0, 0};-static const struct _convrule_ rule112={GENCAT_LL, NUMCAT_LL, 1, -116, 0, -116};-static const struct _convrule_ rule38={GENCAT_LU, NUMCAT_LU, 1, 0, 209, 0};-static const struct _convrule_ rule10={GENCAT_SK, NUMCAT_SK, 0, 0, 0, 0};-static const struct _convrule_ rule167={GENCAT_LU, NUMCAT_LU, 1, 0, -10815, 0};-static const struct _convrule_ rule5={GENCAT_PE, NUMCAT_PE, 0, 0, 0, 0};-static const struct _convrule_ rule164={GENCAT_LU, NUMCAT_LU, 1, 0, -10749, 0};-static const struct _convrule_ rule117={GENCAT_ME, NUMCAT_ME, 0, 0, 0, 0};-static const struct _convrule_ rule106={GENCAT_LL, NUMCAT_LL, 1, -47, 0, -47};-static const struct _convrule_ rule160={GENCAT_LU, NUMCAT_LU, 1, 0, -10727, 0};-static const struct _convrule_ rule9={GENCAT_LU, NUMCAT_LU, 1, 0, 32, 0};-static const struct _charblock_ allchars[]={-	{0, 32, &rule0},-	{32, 1, &rule1},-	{33, 3, &rule2},-	{36, 1, &rule3},-	{37, 3, &rule2},-	{40, 1, &rule4},-	{41, 1, &rule5},-	{42, 1, &rule2},-	{43, 1, &rule6},-	{44, 1, &rule2},-	{45, 1, &rule7},-	{46, 2, &rule2},-	{48, 10, &rule8},-	{58, 2, &rule2},-	{60, 3, &rule6},-	{63, 2, &rule2},-	{65, 26, &rule9},-	{91, 1, &rule4},-	{92, 1, &rule2},-	{93, 1, &rule5},-	{94, 1, &rule10},-	{95, 1, &rule11},-	{96, 1, &rule10},-	{97, 26, &rule12},-	{123, 1, &rule4},-	{124, 1, &rule6},-	{125, 1, &rule5},-	{126, 1, &rule6},-	{127, 33, &rule0},-	{160, 1, &rule1},-	{161, 1, &rule2},-	{162, 4, &rule3},-	{166, 1, &rule13},-	{167, 1, &rule2},-	{168, 1, &rule10},-	{169, 1, &rule13},-	{170, 1, &rule14},-	{171, 1, &rule15},-	{172, 1, &rule6},-	{173, 1, &rule16},-	{174, 1, &rule13},-	{175, 1, &rule10},-	{176, 1, &rule13},-	{177, 1, &rule6},-	{178, 2, &rule17},-	{180, 1, &rule10},-	{181, 1, &rule18},-	{182, 2, &rule2},-	{184, 1, &rule10},-	{185, 1, &rule17},-	{186, 1, &rule14},-	{187, 1, &rule19},-	{188, 3, &rule17},-	{191, 1, &rule2},-	{192, 23, &rule9},-	{215, 1, &rule6},-	{216, 7, &rule9},-	{223, 1, &rule20},-	{224, 23, &rule12},-	{247, 1, &rule6},-	{248, 7, &rule12},-	{255, 1, &rule21},-	{256, 1, &rule22},-	{257, 1, &rule23},-	{258, 1, &rule22},-	{259, 1, &rule23},-	{260, 1, &rule22},-	{261, 1, &rule23},-	{262, 1, &rule22},-	{263, 1, &rule23},-	{264, 1, &rule22},-	{265, 1, &rule23},-	{266, 1, &rule22},-	{267, 1, &rule23},-	{268, 1, &rule22},-	{269, 1, &rule23},-	{270, 1, &rule22},-	{271, 1, &rule23},-	{272, 1, &rule22},-	{273, 1, &rule23},-	{274, 1, &rule22},-	{275, 1, &rule23},-	{276, 1, &rule22},-	{277, 1, &rule23},-	{278, 1, &rule22},-	{279, 1, &rule23},-	{280, 1, &rule22},-	{281, 1, &rule23},-	{282, 1, &rule22},-	{283, 1, &rule23},-	{284, 1, &rule22},-	{285, 1, &rule23},-	{286, 1, &rule22},-	{287, 1, &rule23},-	{288, 1, &rule22},-	{289, 1, &rule23},-	{290, 1, &rule22},-	{291, 1, &rule23},-	{292, 1, &rule22},-	{293, 1, &rule23},-	{294, 1, &rule22},-	{295, 1, &rule23},-	{296, 1, &rule22},-	{297, 1, &rule23},-	{298, 1, &rule22},-	{299, 1, &rule23},-	{300, 1, &rule22},-	{301, 1, &rule23},-	{302, 1, &rule22},-	{303, 1, &rule23},-	{304, 1, &rule24},-	{305, 1, &rule25},-	{306, 1, &rule22},-	{307, 1, &rule23},-	{308, 1, &rule22},-	{309, 1, &rule23},-	{310, 1, &rule22},-	{311, 1, &rule23},-	{312, 1, &rule20},-	{313, 1, &rule22},-	{314, 1, &rule23},-	{315, 1, &rule22},-	{316, 1, &rule23},-	{317, 1, &rule22},-	{318, 1, &rule23},-	{319, 1, &rule22},-	{320, 1, &rule23},-	{321, 1, &rule22},-	{322, 1, &rule23},-	{323, 1, &rule22},-	{324, 1, &rule23},-	{325, 1, &rule22},-	{326, 1, &rule23},-	{327, 1, &rule22},-	{328, 1, &rule23},-	{329, 1, &rule20},-	{330, 1, &rule22},-	{331, 1, &rule23},-	{332, 1, &rule22},-	{333, 1, &rule23},-	{334, 1, &rule22},-	{335, 1, &rule23},-	{336, 1, &rule22},-	{337, 1, &rule23},-	{338, 1, &rule22},-	{339, 1, &rule23},-	{340, 1, &rule22},-	{341, 1, &rule23},-	{342, 1, &rule22},-	{343, 1, &rule23},-	{344, 1, &rule22},-	{345, 1, &rule23},-	{346, 1, &rule22},-	{347, 1, &rule23},-	{348, 1, &rule22},-	{349, 1, &rule23},-	{350, 1, &rule22},-	{351, 1, &rule23},-	{352, 1, &rule22},-	{353, 1, &rule23},-	{354, 1, &rule22},-	{355, 1, &rule23},-	{356, 1, &rule22},-	{357, 1, &rule23},-	{358, 1, &rule22},-	{359, 1, &rule23},-	{360, 1, &rule22},-	{361, 1, &rule23},-	{362, 1, &rule22},-	{363, 1, &rule23},-	{364, 1, &rule22},-	{365, 1, &rule23},-	{366, 1, &rule22},-	{367, 1, &rule23},-	{368, 1, &rule22},-	{369, 1, &rule23},-	{370, 1, &rule22},-	{371, 1, &rule23},-	{372, 1, &rule22},-	{373, 1, &rule23},-	{374, 1, &rule22},-	{375, 1, &rule23},-	{376, 1, &rule26},-	{377, 1, &rule22},-	{378, 1, &rule23},-	{379, 1, &rule22},-	{380, 1, &rule23},-	{381, 1, &rule22},-	{382, 1, &rule23},-	{383, 1, &rule27},-	{384, 1, &rule28},-	{385, 1, &rule29},-	{386, 1, &rule22},-	{387, 1, &rule23},-	{388, 1, &rule22},-	{389, 1, &rule23},-	{390, 1, &rule30},-	{391, 1, &rule22},-	{392, 1, &rule23},-	{393, 2, &rule31},-	{395, 1, &rule22},-	{396, 1, &rule23},-	{397, 1, &rule20},-	{398, 1, &rule32},-	{399, 1, &rule33},-	{400, 1, &rule34},-	{401, 1, &rule22},-	{402, 1, &rule23},-	{403, 1, &rule31},-	{404, 1, &rule35},-	{405, 1, &rule36},-	{406, 1, &rule37},-	{407, 1, &rule38},-	{408, 1, &rule22},-	{409, 1, &rule23},-	{410, 1, &rule39},-	{411, 1, &rule20},-	{412, 1, &rule37},-	{413, 1, &rule40},-	{414, 1, &rule41},-	{415, 1, &rule42},-	{416, 1, &rule22},-	{417, 1, &rule23},-	{418, 1, &rule22},-	{419, 1, &rule23},-	{420, 1, &rule22},-	{421, 1, &rule23},-	{422, 1, &rule43},-	{423, 1, &rule22},-	{424, 1, &rule23},-	{425, 1, &rule43},-	{426, 2, &rule20},-	{428, 1, &rule22},-	{429, 1, &rule23},-	{430, 1, &rule43},-	{431, 1, &rule22},-	{432, 1, &rule23},-	{433, 2, &rule44},-	{435, 1, &rule22},-	{436, 1, &rule23},-	{437, 1, &rule22},-	{438, 1, &rule23},-	{439, 1, &rule45},-	{440, 1, &rule22},-	{441, 1, &rule23},-	{442, 1, &rule20},-	{443, 1, &rule14},-	{444, 1, &rule22},-	{445, 1, &rule23},-	{446, 1, &rule20},-	{447, 1, &rule46},-	{448, 4, &rule14},-	{452, 1, &rule47},-	{453, 1, &rule48},-	{454, 1, &rule49},-	{455, 1, &rule47},-	{456, 1, &rule48},-	{457, 1, &rule49},-	{458, 1, &rule47},-	{459, 1, &rule48},-	{460, 1, &rule49},-	{461, 1, &rule22},-	{462, 1, &rule23},-	{463, 1, &rule22},-	{464, 1, &rule23},-	{465, 1, &rule22},-	{466, 1, &rule23},-	{467, 1, &rule22},-	{468, 1, &rule23},-	{469, 1, &rule22},-	{470, 1, &rule23},-	{471, 1, &rule22},-	{472, 1, &rule23},-	{473, 1, &rule22},-	{474, 1, &rule23},-	{475, 1, &rule22},-	{476, 1, &rule23},-	{477, 1, &rule50},-	{478, 1, &rule22},-	{479, 1, &rule23},-	{480, 1, &rule22},-	{481, 1, &rule23},-	{482, 1, &rule22},-	{483, 1, &rule23},-	{484, 1, &rule22},-	{485, 1, &rule23},-	{486, 1, &rule22},-	{487, 1, &rule23},-	{488, 1, &rule22},-	{489, 1, &rule23},-	{490, 1, &rule22},-	{491, 1, &rule23},-	{492, 1, &rule22},-	{493, 1, &rule23},-	{494, 1, &rule22},-	{495, 1, &rule23},-	{496, 1, &rule20},-	{497, 1, &rule47},-	{498, 1, &rule48},-	{499, 1, &rule49},-	{500, 1, &rule22},-	{501, 1, &rule23},-	{502, 1, &rule51},-	{503, 1, &rule52},-	{504, 1, &rule22},-	{505, 1, &rule23},-	{506, 1, &rule22},-	{507, 1, &rule23},-	{508, 1, &rule22},-	{509, 1, &rule23},-	{510, 1, &rule22},-	{511, 1, &rule23},-	{512, 1, &rule22},-	{513, 1, &rule23},-	{514, 1, &rule22},-	{515, 1, &rule23},-	{516, 1, &rule22},-	{517, 1, &rule23},-	{518, 1, &rule22},-	{519, 1, &rule23},-	{520, 1, &rule22},-	{521, 1, &rule23},-	{522, 1, &rule22},-	{523, 1, &rule23},-	{524, 1, &rule22},-	{525, 1, &rule23},-	{526, 1, &rule22},-	{527, 1, &rule23},-	{528, 1, &rule22},-	{529, 1, &rule23},-	{530, 1, &rule22},-	{531, 1, &rule23},-	{532, 1, &rule22},-	{533, 1, &rule23},-	{534, 1, &rule22},-	{535, 1, &rule23},-	{536, 1, &rule22},-	{537, 1, &rule23},-	{538, 1, &rule22},-	{539, 1, &rule23},-	{540, 1, &rule22},-	{541, 1, &rule23},-	{542, 1, &rule22},-	{543, 1, &rule23},-	{544, 1, &rule53},-	{545, 1, &rule20},-	{546, 1, &rule22},-	{547, 1, &rule23},-	{548, 1, &rule22},-	{549, 1, &rule23},-	{550, 1, &rule22},-	{551, 1, &rule23},-	{552, 1, &rule22},-	{553, 1, &rule23},-	{554, 1, &rule22},-	{555, 1, &rule23},-	{556, 1, &rule22},-	{557, 1, &rule23},-	{558, 1, &rule22},-	{559, 1, &rule23},-	{560, 1, &rule22},-	{561, 1, &rule23},-	{562, 1, &rule22},-	{563, 1, &rule23},-	{564, 6, &rule20},-	{570, 1, &rule54},-	{571, 1, &rule22},-	{572, 1, &rule23},-	{573, 1, &rule55},-	{574, 1, &rule56},-	{575, 2, &rule57},-	{577, 1, &rule22},-	{578, 1, &rule23},-	{579, 1, &rule58},-	{580, 1, &rule59},-	{581, 1, &rule60},-	{582, 1, &rule22},-	{583, 1, &rule23},-	{584, 1, &rule22},-	{585, 1, &rule23},-	{586, 1, &rule22},-	{587, 1, &rule23},-	{588, 1, &rule22},-	{589, 1, &rule23},-	{590, 1, &rule22},-	{591, 1, &rule23},-	{592, 1, &rule61},-	{593, 1, &rule62},-	{594, 1, &rule63},-	{595, 1, &rule64},-	{596, 1, &rule65},-	{597, 1, &rule20},-	{598, 2, &rule66},-	{600, 1, &rule20},-	{601, 1, &rule67},-	{602, 1, &rule20},-	{603, 1, &rule68},-	{604, 1, &rule69},-	{605, 3, &rule20},-	{608, 1, &rule66},-	{609, 1, &rule70},-	{610, 1, &rule20},-	{611, 1, &rule71},-	{612, 1, &rule20},-	{613, 1, &rule72},-	{614, 1, &rule73},-	{615, 1, &rule20},-	{616, 1, &rule74},-	{617, 1, &rule75},-	{618, 1, &rule20},-	{619, 1, &rule76},-	{620, 1, &rule77},-	{621, 2, &rule20},-	{623, 1, &rule75},-	{624, 1, &rule20},-	{625, 1, &rule78},-	{626, 1, &rule79},-	{627, 2, &rule20},-	{629, 1, &rule80},-	{630, 7, &rule20},-	{637, 1, &rule81},-	{638, 2, &rule20},-	{640, 1, &rule82},-	{641, 2, &rule20},-	{643, 1, &rule82},-	{644, 3, &rule20},-	{647, 1, &rule83},-	{648, 1, &rule82},-	{649, 1, &rule84},-	{650, 2, &rule85},-	{652, 1, &rule86},-	{653, 5, &rule20},-	{658, 1, &rule87},-	{659, 1, &rule20},-	{660, 1, &rule14},-	{661, 9, &rule20},-	{670, 1, &rule88},-	{671, 17, &rule20},-	{688, 18, &rule89},-	{706, 4, &rule10},-	{710, 12, &rule89},-	{722, 14, &rule10},-	{736, 5, &rule89},-	{741, 7, &rule10},-	{748, 1, &rule89},-	{749, 1, &rule10},-	{750, 1, &rule89},-	{751, 17, &rule10},-	{768, 69, &rule90},-	{837, 1, &rule91},-	{838, 42, &rule90},-	{880, 1, &rule22},-	{881, 1, &rule23},-	{882, 1, &rule22},-	{883, 1, &rule23},-	{884, 1, &rule89},-	{885, 1, &rule10},-	{886, 1, &rule22},-	{887, 1, &rule23},-	{890, 1, &rule89},-	{891, 3, &rule41},-	{894, 1, &rule2},-	{895, 1, &rule92},-	{900, 2, &rule10},-	{902, 1, &rule93},-	{903, 1, &rule2},-	{904, 3, &rule94},-	{908, 1, &rule95},-	{910, 2, &rule96},-	{912, 1, &rule20},-	{913, 17, &rule9},-	{931, 9, &rule9},-	{940, 1, &rule97},-	{941, 3, &rule98},-	{944, 1, &rule20},-	{945, 17, &rule12},-	{962, 1, &rule99},-	{963, 9, &rule12},-	{972, 1, &rule100},-	{973, 2, &rule101},-	{975, 1, &rule102},-	{976, 1, &rule103},-	{977, 1, &rule104},-	{978, 3, &rule105},-	{981, 1, &rule106},-	{982, 1, &rule107},-	{983, 1, &rule108},-	{984, 1, &rule22},-	{985, 1, &rule23},-	{986, 1, &rule22},-	{987, 1, &rule23},-	{988, 1, &rule22},-	{989, 1, &rule23},-	{990, 1, &rule22},-	{991, 1, &rule23},-	{992, 1, &rule22},-	{993, 1, &rule23},-	{994, 1, &rule22},-	{995, 1, &rule23},-	{996, 1, &rule22},-	{997, 1, &rule23},-	{998, 1, &rule22},-	{999, 1, &rule23},-	{1000, 1, &rule22},-	{1001, 1, &rule23},-	{1002, 1, &rule22},-	{1003, 1, &rule23},-	{1004, 1, &rule22},-	{1005, 1, &rule23},-	{1006, 1, &rule22},-	{1007, 1, &rule23},-	{1008, 1, &rule109},-	{1009, 1, &rule110},-	{1010, 1, &rule111},-	{1011, 1, &rule112},-	{1012, 1, &rule113},-	{1013, 1, &rule114},-	{1014, 1, &rule6},-	{1015, 1, &rule22},-	{1016, 1, &rule23},-	{1017, 1, &rule115},-	{1018, 1, &rule22},-	{1019, 1, &rule23},-	{1020, 1, &rule20},-	{1021, 3, &rule53},-	{1024, 16, &rule116},-	{1040, 32, &rule9},-	{1072, 32, &rule12},-	{1104, 16, &rule110},-	{1120, 1, &rule22},-	{1121, 1, &rule23},-	{1122, 1, &rule22},-	{1123, 1, &rule23},-	{1124, 1, &rule22},-	{1125, 1, &rule23},-	{1126, 1, &rule22},-	{1127, 1, &rule23},-	{1128, 1, &rule22},-	{1129, 1, &rule23},-	{1130, 1, &rule22},-	{1131, 1, &rule23},-	{1132, 1, &rule22},-	{1133, 1, &rule23},-	{1134, 1, &rule22},-	{1135, 1, &rule23},-	{1136, 1, &rule22},-	{1137, 1, &rule23},-	{1138, 1, &rule22},-	{1139, 1, &rule23},-	{1140, 1, &rule22},-	{1141, 1, &rule23},-	{1142, 1, &rule22},-	{1143, 1, &rule23},-	{1144, 1, &rule22},-	{1145, 1, &rule23},-	{1146, 1, &rule22},-	{1147, 1, &rule23},-	{1148, 1, &rule22},-	{1149, 1, &rule23},-	{1150, 1, &rule22},-	{1151, 1, &rule23},-	{1152, 1, &rule22},-	{1153, 1, &rule23},-	{1154, 1, &rule13},-	{1155, 5, &rule90},-	{1160, 2, &rule117},-	{1162, 1, &rule22},-	{1163, 1, &rule23},-	{1164, 1, &rule22},-	{1165, 1, &rule23},-	{1166, 1, &rule22},-	{1167, 1, &rule23},-	{1168, 1, &rule22},-	{1169, 1, &rule23},-	{1170, 1, &rule22},-	{1171, 1, &rule23},-	{1172, 1, &rule22},-	{1173, 1, &rule23},-	{1174, 1, &rule22},-	{1175, 1, &rule23},-	{1176, 1, &rule22},-	{1177, 1, &rule23},-	{1178, 1, &rule22},-	{1179, 1, &rule23},-	{1180, 1, &rule22},-	{1181, 1, &rule23},-	{1182, 1, &rule22},-	{1183, 1, &rule23},-	{1184, 1, &rule22},-	{1185, 1, &rule23},-	{1186, 1, &rule22},-	{1187, 1, &rule23},-	{1188, 1, &rule22},-	{1189, 1, &rule23},-	{1190, 1, &rule22},-	{1191, 1, &rule23},-	{1192, 1, &rule22},-	{1193, 1, &rule23},-	{1194, 1, &rule22},-	{1195, 1, &rule23},-	{1196, 1, &rule22},-	{1197, 1, &rule23},-	{1198, 1, &rule22},-	{1199, 1, &rule23},-	{1200, 1, &rule22},-	{1201, 1, &rule23},-	{1202, 1, &rule22},-	{1203, 1, &rule23},-	{1204, 1, &rule22},-	{1205, 1, &rule23},-	{1206, 1, &rule22},-	{1207, 1, &rule23},-	{1208, 1, &rule22},-	{1209, 1, &rule23},-	{1210, 1, &rule22},-	{1211, 1, &rule23},-	{1212, 1, &rule22},-	{1213, 1, &rule23},-	{1214, 1, &rule22},-	{1215, 1, &rule23},-	{1216, 1, &rule118},-	{1217, 1, &rule22},-	{1218, 1, &rule23},-	{1219, 1, &rule22},-	{1220, 1, &rule23},-	{1221, 1, &rule22},-	{1222, 1, &rule23},-	{1223, 1, &rule22},-	{1224, 1, &rule23},-	{1225, 1, &rule22},-	{1226, 1, &rule23},-	{1227, 1, &rule22},-	{1228, 1, &rule23},-	{1229, 1, &rule22},-	{1230, 1, &rule23},-	{1231, 1, &rule119},-	{1232, 1, &rule22},-	{1233, 1, &rule23},-	{1234, 1, &rule22},-	{1235, 1, &rule23},-	{1236, 1, &rule22},-	{1237, 1, &rule23},-	{1238, 1, &rule22},-	{1239, 1, &rule23},-	{1240, 1, &rule22},-	{1241, 1, &rule23},-	{1242, 1, &rule22},-	{1243, 1, &rule23},-	{1244, 1, &rule22},-	{1245, 1, &rule23},-	{1246, 1, &rule22},-	{1247, 1, &rule23},-	{1248, 1, &rule22},-	{1249, 1, &rule23},-	{1250, 1, &rule22},-	{1251, 1, &rule23},-	{1252, 1, &rule22},-	{1253, 1, &rule23},-	{1254, 1, &rule22},-	{1255, 1, &rule23},-	{1256, 1, &rule22},-	{1257, 1, &rule23},-	{1258, 1, &rule22},-	{1259, 1, &rule23},-	{1260, 1, &rule22},-	{1261, 1, &rule23},-	{1262, 1, &rule22},-	{1263, 1, &rule23},-	{1264, 1, &rule22},-	{1265, 1, &rule23},-	{1266, 1, &rule22},-	{1267, 1, &rule23},-	{1268, 1, &rule22},-	{1269, 1, &rule23},-	{1270, 1, &rule22},-	{1271, 1, &rule23},-	{1272, 1, &rule22},-	{1273, 1, &rule23},-	{1274, 1, &rule22},-	{1275, 1, &rule23},-	{1276, 1, &rule22},-	{1277, 1, &rule23},-	{1278, 1, &rule22},-	{1279, 1, &rule23},-	{1280, 1, &rule22},-	{1281, 1, &rule23},-	{1282, 1, &rule22},-	{1283, 1, &rule23},-	{1284, 1, &rule22},-	{1285, 1, &rule23},-	{1286, 1, &rule22},-	{1287, 1, &rule23},-	{1288, 1, &rule22},-	{1289, 1, &rule23},-	{1290, 1, &rule22},-	{1291, 1, &rule23},-	{1292, 1, &rule22},-	{1293, 1, &rule23},-	{1294, 1, &rule22},-	{1295, 1, &rule23},-	{1296, 1, &rule22},-	{1297, 1, &rule23},-	{1298, 1, &rule22},-	{1299, 1, &rule23},-	{1300, 1, &rule22},-	{1301, 1, &rule23},-	{1302, 1, &rule22},-	{1303, 1, &rule23},-	{1304, 1, &rule22},-	{1305, 1, &rule23},-	{1306, 1, &rule22},-	{1307, 1, &rule23},-	{1308, 1, &rule22},-	{1309, 1, &rule23},-	{1310, 1, &rule22},-	{1311, 1, &rule23},-	{1312, 1, &rule22},-	{1313, 1, &rule23},-	{1314, 1, &rule22},-	{1315, 1, &rule23},-	{1316, 1, &rule22},-	{1317, 1, &rule23},-	{1318, 1, &rule22},-	{1319, 1, &rule23},-	{1320, 1, &rule22},-	{1321, 1, &rule23},-	{1322, 1, &rule22},-	{1323, 1, &rule23},-	{1324, 1, &rule22},-	{1325, 1, &rule23},-	{1326, 1, &rule22},-	{1327, 1, &rule23},-	{1329, 38, &rule120},-	{1369, 1, &rule89},-	{1370, 6, &rule2},-	{1377, 38, &rule121},-	{1415, 1, &rule20},-	{1417, 1, &rule2},-	{1418, 1, &rule7},-	{1421, 2, &rule13},-	{1423, 1, &rule3},-	{1425, 45, &rule90},-	{1470, 1, &rule7},-	{1471, 1, &rule90},-	{1472, 1, &rule2},-	{1473, 2, &rule90},-	{1475, 1, &rule2},-	{1476, 2, &rule90},-	{1478, 1, &rule2},-	{1479, 1, &rule90},-	{1488, 27, &rule14},-	{1520, 3, &rule14},-	{1523, 2, &rule2},-	{1536, 6, &rule16},-	{1542, 3, &rule6},-	{1545, 2, &rule2},-	{1547, 1, &rule3},-	{1548, 2, &rule2},-	{1550, 2, &rule13},-	{1552, 11, &rule90},-	{1563, 1, &rule2},-	{1564, 1, &rule16},-	{1566, 2, &rule2},-	{1568, 32, &rule14},-	{1600, 1, &rule89},-	{1601, 10, &rule14},-	{1611, 21, &rule90},-	{1632, 10, &rule8},-	{1642, 4, &rule2},-	{1646, 2, &rule14},-	{1648, 1, &rule90},-	{1649, 99, &rule14},-	{1748, 1, &rule2},-	{1749, 1, &rule14},-	{1750, 7, &rule90},-	{1757, 1, &rule16},-	{1758, 1, &rule13},-	{1759, 6, &rule90},-	{1765, 2, &rule89},-	{1767, 2, &rule90},-	{1769, 1, &rule13},-	{1770, 4, &rule90},-	{1774, 2, &rule14},-	{1776, 10, &rule8},-	{1786, 3, &rule14},-	{1789, 2, &rule13},-	{1791, 1, &rule14},-	{1792, 14, &rule2},-	{1807, 1, &rule16},-	{1808, 1, &rule14},-	{1809, 1, &rule90},-	{1810, 30, &rule14},-	{1840, 27, &rule90},-	{1869, 89, &rule14},-	{1958, 11, &rule90},-	{1969, 1, &rule14},-	{1984, 10, &rule8},-	{1994, 33, &rule14},-	{2027, 9, &rule90},-	{2036, 2, &rule89},-	{2038, 1, &rule13},-	{2039, 3, &rule2},-	{2042, 1, &rule89},-	{2048, 22, &rule14},-	{2070, 4, &rule90},-	{2074, 1, &rule89},-	{2075, 9, &rule90},-	{2084, 1, &rule89},-	{2085, 3, &rule90},-	{2088, 1, &rule89},-	{2089, 5, &rule90},-	{2096, 15, &rule2},-	{2112, 25, &rule14},-	{2137, 3, &rule90},-	{2142, 1, &rule2},-	{2208, 19, &rule14},-	{2276, 31, &rule90},-	{2307, 1, &rule122},-	{2308, 54, &rule14},-	{2362, 1, &rule90},-	{2363, 1, &rule122},-	{2364, 1, &rule90},-	{2365, 1, &rule14},-	{2366, 3, &rule122},-	{2369, 8, &rule90},-	{2377, 4, &rule122},-	{2381, 1, &rule90},-	{2382, 2, &rule122},-	{2384, 1, &rule14},-	{2385, 7, &rule90},-	{2392, 10, &rule14},-	{2402, 2, &rule90},-	{2404, 2, &rule2},-	{2406, 10, &rule8},-	{2416, 1, &rule2},-	{2417, 1, &rule89},-	{2418, 15, &rule14},-	{2433, 1, &rule90},-	{2434, 2, &rule122},-	{2437, 8, &rule14},-	{2447, 2, &rule14},-	{2451, 22, &rule14},-	{2474, 7, &rule14},-	{2482, 1, &rule14},-	{2486, 4, &rule14},-	{2492, 1, &rule90},-	{2493, 1, &rule14},-	{2494, 3, &rule122},-	{2497, 4, &rule90},-	{2503, 2, &rule122},-	{2507, 2, &rule122},-	{2509, 1, &rule90},-	{2510, 1, &rule14},-	{2519, 1, &rule122},-	{2524, 2, &rule14},-	{2527, 3, &rule14},-	{2530, 2, &rule90},-	{2534, 10, &rule8},-	{2544, 2, &rule14},-	{2546, 2, &rule3},-	{2548, 6, &rule17},-	{2554, 1, &rule13},-	{2555, 1, &rule3},-	{2561, 2, &rule90},-	{2563, 1, &rule122},-	{2565, 6, &rule14},-	{2575, 2, &rule14},-	{2579, 22, &rule14},-	{2602, 7, &rule14},-	{2610, 2, &rule14},-	{2613, 2, &rule14},-	{2616, 2, &rule14},-	{2620, 1, &rule90},-	{2622, 3, &rule122},-	{2625, 2, &rule90},-	{2631, 2, &rule90},-	{2635, 3, &rule90},-	{2641, 1, &rule90},-	{2649, 4, &rule14},-	{2654, 1, &rule14},-	{2662, 10, &rule8},-	{2672, 2, &rule90},-	{2674, 3, &rule14},-	{2677, 1, &rule90},-	{2689, 2, &rule90},-	{2691, 1, &rule122},-	{2693, 9, &rule14},-	{2703, 3, &rule14},-	{2707, 22, &rule14},-	{2730, 7, &rule14},-	{2738, 2, &rule14},-	{2741, 5, &rule14},-	{2748, 1, &rule90},-	{2749, 1, &rule14},-	{2750, 3, &rule122},-	{2753, 5, &rule90},-	{2759, 2, &rule90},-	{2761, 1, &rule122},-	{2763, 2, &rule122},-	{2765, 1, &rule90},-	{2768, 1, &rule14},-	{2784, 2, &rule14},-	{2786, 2, &rule90},-	{2790, 10, &rule8},-	{2800, 1, &rule2},-	{2801, 1, &rule3},-	{2817, 1, &rule90},-	{2818, 2, &rule122},-	{2821, 8, &rule14},-	{2831, 2, &rule14},-	{2835, 22, &rule14},-	{2858, 7, &rule14},-	{2866, 2, &rule14},-	{2869, 5, &rule14},-	{2876, 1, &rule90},-	{2877, 1, &rule14},-	{2878, 1, &rule122},-	{2879, 1, &rule90},-	{2880, 1, &rule122},-	{2881, 4, &rule90},-	{2887, 2, &rule122},-	{2891, 2, &rule122},-	{2893, 1, &rule90},-	{2902, 1, &rule90},-	{2903, 1, &rule122},-	{2908, 2, &rule14},-	{2911, 3, &rule14},-	{2914, 2, &rule90},-	{2918, 10, &rule8},-	{2928, 1, &rule13},-	{2929, 1, &rule14},-	{2930, 6, &rule17},-	{2946, 1, &rule90},-	{2947, 1, &rule14},-	{2949, 6, &rule14},-	{2958, 3, &rule14},-	{2962, 4, &rule14},-	{2969, 2, &rule14},-	{2972, 1, &rule14},-	{2974, 2, &rule14},-	{2979, 2, &rule14},-	{2984, 3, &rule14},-	{2990, 12, &rule14},-	{3006, 2, &rule122},-	{3008, 1, &rule90},-	{3009, 2, &rule122},-	{3014, 3, &rule122},-	{3018, 3, &rule122},-	{3021, 1, &rule90},-	{3024, 1, &rule14},-	{3031, 1, &rule122},-	{3046, 10, &rule8},-	{3056, 3, &rule17},-	{3059, 6, &rule13},-	{3065, 1, &rule3},-	{3066, 1, &rule13},-	{3072, 1, &rule90},-	{3073, 3, &rule122},-	{3077, 8, &rule14},-	{3086, 3, &rule14},-	{3090, 23, &rule14},-	{3114, 16, &rule14},-	{3133, 1, &rule14},-	{3134, 3, &rule90},-	{3137, 4, &rule122},-	{3142, 3, &rule90},-	{3146, 4, &rule90},-	{3157, 2, &rule90},-	{3160, 2, &rule14},-	{3168, 2, &rule14},-	{3170, 2, &rule90},-	{3174, 10, &rule8},-	{3192, 7, &rule17},-	{3199, 1, &rule13},-	{3201, 1, &rule90},-	{3202, 2, &rule122},-	{3205, 8, &rule14},-	{3214, 3, &rule14},-	{3218, 23, &rule14},-	{3242, 10, &rule14},-	{3253, 5, &rule14},-	{3260, 1, &rule90},-	{3261, 1, &rule14},-	{3262, 1, &rule122},-	{3263, 1, &rule90},-	{3264, 5, &rule122},-	{3270, 1, &rule90},-	{3271, 2, &rule122},-	{3274, 2, &rule122},-	{3276, 2, &rule90},-	{3285, 2, &rule122},-	{3294, 1, &rule14},-	{3296, 2, &rule14},-	{3298, 2, &rule90},-	{3302, 10, &rule8},-	{3313, 2, &rule14},-	{3329, 1, &rule90},-	{3330, 2, &rule122},-	{3333, 8, &rule14},-	{3342, 3, &rule14},-	{3346, 41, &rule14},-	{3389, 1, &rule14},-	{3390, 3, &rule122},-	{3393, 4, &rule90},-	{3398, 3, &rule122},-	{3402, 3, &rule122},-	{3405, 1, &rule90},-	{3406, 1, &rule14},-	{3415, 1, &rule122},-	{3424, 2, &rule14},-	{3426, 2, &rule90},-	{3430, 10, &rule8},-	{3440, 6, &rule17},-	{3449, 1, &rule13},-	{3450, 6, &rule14},-	{3458, 2, &rule122},-	{3461, 18, &rule14},-	{3482, 24, &rule14},-	{3507, 9, &rule14},-	{3517, 1, &rule14},-	{3520, 7, &rule14},-	{3530, 1, &rule90},-	{3535, 3, &rule122},-	{3538, 3, &rule90},-	{3542, 1, &rule90},-	{3544, 8, &rule122},-	{3558, 10, &rule8},-	{3570, 2, &rule122},-	{3572, 1, &rule2},-	{3585, 48, &rule14},-	{3633, 1, &rule90},-	{3634, 2, &rule14},-	{3636, 7, &rule90},-	{3647, 1, &rule3},-	{3648, 6, &rule14},-	{3654, 1, &rule89},-	{3655, 8, &rule90},-	{3663, 1, &rule2},-	{3664, 10, &rule8},-	{3674, 2, &rule2},-	{3713, 2, &rule14},-	{3716, 1, &rule14},-	{3719, 2, &rule14},-	{3722, 1, &rule14},-	{3725, 1, &rule14},-	{3732, 4, &rule14},-	{3737, 7, &rule14},-	{3745, 3, &rule14},-	{3749, 1, &rule14},-	{3751, 1, &rule14},-	{3754, 2, &rule14},-	{3757, 4, &rule14},-	{3761, 1, &rule90},-	{3762, 2, &rule14},-	{3764, 6, &rule90},-	{3771, 2, &rule90},-	{3773, 1, &rule14},-	{3776, 5, &rule14},-	{3782, 1, &rule89},-	{3784, 6, &rule90},-	{3792, 10, &rule8},-	{3804, 4, &rule14},-	{3840, 1, &rule14},-	{3841, 3, &rule13},-	{3844, 15, &rule2},-	{3859, 1, &rule13},-	{3860, 1, &rule2},-	{3861, 3, &rule13},-	{3864, 2, &rule90},-	{3866, 6, &rule13},-	{3872, 10, &rule8},-	{3882, 10, &rule17},-	{3892, 1, &rule13},-	{3893, 1, &rule90},-	{3894, 1, &rule13},-	{3895, 1, &rule90},-	{3896, 1, &rule13},-	{3897, 1, &rule90},-	{3898, 1, &rule4},-	{3899, 1, &rule5},-	{3900, 1, &rule4},-	{3901, 1, &rule5},-	{3902, 2, &rule122},-	{3904, 8, &rule14},-	{3913, 36, &rule14},-	{3953, 14, &rule90},-	{3967, 1, &rule122},-	{3968, 5, &rule90},-	{3973, 1, &rule2},-	{3974, 2, &rule90},-	{3976, 5, &rule14},-	{3981, 11, &rule90},-	{3993, 36, &rule90},-	{4030, 8, &rule13},-	{4038, 1, &rule90},-	{4039, 6, &rule13},-	{4046, 2, &rule13},-	{4048, 5, &rule2},-	{4053, 4, &rule13},-	{4057, 2, &rule2},-	{4096, 43, &rule14},-	{4139, 2, &rule122},-	{4141, 4, &rule90},-	{4145, 1, &rule122},-	{4146, 6, &rule90},-	{4152, 1, &rule122},-	{4153, 2, &rule90},-	{4155, 2, &rule122},-	{4157, 2, &rule90},-	{4159, 1, &rule14},-	{4160, 10, &rule8},-	{4170, 6, &rule2},-	{4176, 6, &rule14},-	{4182, 2, &rule122},-	{4184, 2, &rule90},-	{4186, 4, &rule14},-	{4190, 3, &rule90},-	{4193, 1, &rule14},-	{4194, 3, &rule122},-	{4197, 2, &rule14},-	{4199, 7, &rule122},-	{4206, 3, &rule14},-	{4209, 4, &rule90},-	{4213, 13, &rule14},-	{4226, 1, &rule90},-	{4227, 2, &rule122},-	{4229, 2, &rule90},-	{4231, 6, &rule122},-	{4237, 1, &rule90},-	{4238, 1, &rule14},-	{4239, 1, &rule122},-	{4240, 10, &rule8},-	{4250, 3, &rule122},-	{4253, 1, &rule90},-	{4254, 2, &rule13},-	{4256, 38, &rule123},-	{4295, 1, &rule123},-	{4301, 1, &rule123},-	{4304, 43, &rule14},-	{4347, 1, &rule2},-	{4348, 1, &rule89},-	{4349, 332, &rule14},-	{4682, 4, &rule14},-	{4688, 7, &rule14},-	{4696, 1, &rule14},-	{4698, 4, &rule14},-	{4704, 41, &rule14},-	{4746, 4, &rule14},-	{4752, 33, &rule14},-	{4786, 4, &rule14},-	{4792, 7, &rule14},-	{4800, 1, &rule14},-	{4802, 4, &rule14},-	{4808, 15, &rule14},-	{4824, 57, &rule14},-	{4882, 4, &rule14},-	{4888, 67, &rule14},-	{4957, 3, &rule90},-	{4960, 9, &rule2},-	{4969, 20, &rule17},-	{4992, 16, &rule14},-	{5008, 10, &rule13},-	{5024, 85, &rule14},-	{5120, 1, &rule7},-	{5121, 620, &rule14},-	{5741, 2, &rule2},-	{5743, 17, &rule14},-	{5760, 1, &rule1},-	{5761, 26, &rule14},-	{5787, 1, &rule4},-	{5788, 1, &rule5},-	{5792, 75, &rule14},-	{5867, 3, &rule2},-	{5870, 3, &rule124},-	{5873, 8, &rule14},-	{5888, 13, &rule14},-	{5902, 4, &rule14},-	{5906, 3, &rule90},-	{5920, 18, &rule14},-	{5938, 3, &rule90},-	{5941, 2, &rule2},-	{5952, 18, &rule14},-	{5970, 2, &rule90},-	{5984, 13, &rule14},-	{5998, 3, &rule14},-	{6002, 2, &rule90},-	{6016, 52, &rule14},-	{6068, 2, &rule90},-	{6070, 1, &rule122},-	{6071, 7, &rule90},-	{6078, 8, &rule122},-	{6086, 1, &rule90},-	{6087, 2, &rule122},-	{6089, 11, &rule90},-	{6100, 3, &rule2},-	{6103, 1, &rule89},-	{6104, 3, &rule2},-	{6107, 1, &rule3},-	{6108, 1, &rule14},-	{6109, 1, &rule90},-	{6112, 10, &rule8},-	{6128, 10, &rule17},-	{6144, 6, &rule2},-	{6150, 1, &rule7},-	{6151, 4, &rule2},-	{6155, 3, &rule90},-	{6158, 1, &rule16},-	{6160, 10, &rule8},-	{6176, 35, &rule14},-	{6211, 1, &rule89},-	{6212, 52, &rule14},-	{6272, 41, &rule14},-	{6313, 1, &rule90},-	{6314, 1, &rule14},-	{6320, 70, &rule14},-	{6400, 31, &rule14},-	{6432, 3, &rule90},-	{6435, 4, &rule122},-	{6439, 2, &rule90},-	{6441, 3, &rule122},-	{6448, 2, &rule122},-	{6450, 1, &rule90},-	{6451, 6, &rule122},-	{6457, 3, &rule90},-	{6464, 1, &rule13},-	{6468, 2, &rule2},-	{6470, 10, &rule8},-	{6480, 30, &rule14},-	{6512, 5, &rule14},-	{6528, 44, &rule14},-	{6576, 17, &rule122},-	{6593, 7, &rule14},-	{6600, 2, &rule122},-	{6608, 10, &rule8},-	{6618, 1, &rule17},-	{6622, 34, &rule13},-	{6656, 23, &rule14},-	{6679, 2, &rule90},-	{6681, 2, &rule122},-	{6683, 1, &rule90},-	{6686, 2, &rule2},-	{6688, 53, &rule14},-	{6741, 1, &rule122},-	{6742, 1, &rule90},-	{6743, 1, &rule122},-	{6744, 7, &rule90},-	{6752, 1, &rule90},-	{6753, 1, &rule122},-	{6754, 1, &rule90},-	{6755, 2, &rule122},-	{6757, 8, &rule90},-	{6765, 6, &rule122},-	{6771, 10, &rule90},-	{6783, 1, &rule90},-	{6784, 10, &rule8},-	{6800, 10, &rule8},-	{6816, 7, &rule2},-	{6823, 1, &rule89},-	{6824, 6, &rule2},-	{6832, 14, &rule90},-	{6846, 1, &rule117},-	{6912, 4, &rule90},-	{6916, 1, &rule122},-	{6917, 47, &rule14},-	{6964, 1, &rule90},-	{6965, 1, &rule122},-	{6966, 5, &rule90},-	{6971, 1, &rule122},-	{6972, 1, &rule90},-	{6973, 5, &rule122},-	{6978, 1, &rule90},-	{6979, 2, &rule122},-	{6981, 7, &rule14},-	{6992, 10, &rule8},-	{7002, 7, &rule2},-	{7009, 10, &rule13},-	{7019, 9, &rule90},-	{7028, 9, &rule13},-	{7040, 2, &rule90},-	{7042, 1, &rule122},-	{7043, 30, &rule14},-	{7073, 1, &rule122},-	{7074, 4, &rule90},-	{7078, 2, &rule122},-	{7080, 2, &rule90},-	{7082, 1, &rule122},-	{7083, 3, &rule90},-	{7086, 2, &rule14},-	{7088, 10, &rule8},-	{7098, 44, &rule14},-	{7142, 1, &rule90},-	{7143, 1, &rule122},-	{7144, 2, &rule90},-	{7146, 3, &rule122},-	{7149, 1, &rule90},-	{7150, 1, &rule122},-	{7151, 3, &rule90},-	{7154, 2, &rule122},-	{7164, 4, &rule2},-	{7168, 36, &rule14},-	{7204, 8, &rule122},-	{7212, 8, &rule90},-	{7220, 2, &rule122},-	{7222, 2, &rule90},-	{7227, 5, &rule2},-	{7232, 10, &rule8},-	{7245, 3, &rule14},-	{7248, 10, &rule8},-	{7258, 30, &rule14},-	{7288, 6, &rule89},-	{7294, 2, &rule2},-	{7360, 8, &rule2},-	{7376, 3, &rule90},-	{7379, 1, &rule2},-	{7380, 13, &rule90},-	{7393, 1, &rule122},-	{7394, 7, &rule90},-	{7401, 4, &rule14},-	{7405, 1, &rule90},-	{7406, 4, &rule14},-	{7410, 2, &rule122},-	{7412, 1, &rule90},-	{7413, 2, &rule14},-	{7416, 2, &rule90},-	{7424, 44, &rule20},-	{7468, 63, &rule89},-	{7531, 13, &rule20},-	{7544, 1, &rule89},-	{7545, 1, &rule125},-	{7546, 3, &rule20},-	{7549, 1, &rule126},-	{7550, 29, &rule20},-	{7579, 37, &rule89},-	{7616, 54, &rule90},-	{7676, 4, &rule90},-	{7680, 1, &rule22},-	{7681, 1, &rule23},-	{7682, 1, &rule22},-	{7683, 1, &rule23},-	{7684, 1, &rule22},-	{7685, 1, &rule23},-	{7686, 1, &rule22},-	{7687, 1, &rule23},-	{7688, 1, &rule22},-	{7689, 1, &rule23},-	{7690, 1, &rule22},-	{7691, 1, &rule23},-	{7692, 1, &rule22},-	{7693, 1, &rule23},-	{7694, 1, &rule22},-	{7695, 1, &rule23},-	{7696, 1, &rule22},-	{7697, 1, &rule23},-	{7698, 1, &rule22},-	{7699, 1, &rule23},-	{7700, 1, &rule22},-	{7701, 1, &rule23},-	{7702, 1, &rule22},-	{7703, 1, &rule23},-	{7704, 1, &rule22},-	{7705, 1, &rule23},-	{7706, 1, &rule22},-	{7707, 1, &rule23},-	{7708, 1, &rule22},-	{7709, 1, &rule23},-	{7710, 1, &rule22},-	{7711, 1, &rule23},-	{7712, 1, &rule22},-	{7713, 1, &rule23},-	{7714, 1, &rule22},-	{7715, 1, &rule23},-	{7716, 1, &rule22},-	{7717, 1, &rule23},-	{7718, 1, &rule22},-	{7719, 1, &rule23},-	{7720, 1, &rule22},-	{7721, 1, &rule23},-	{7722, 1, &rule22},-	{7723, 1, &rule23},-	{7724, 1, &rule22},-	{7725, 1, &rule23},-	{7726, 1, &rule22},-	{7727, 1, &rule23},-	{7728, 1, &rule22},-	{7729, 1, &rule23},-	{7730, 1, &rule22},-	{7731, 1, &rule23},-	{7732, 1, &rule22},-	{7733, 1, &rule23},-	{7734, 1, &rule22},-	{7735, 1, &rule23},-	{7736, 1, &rule22},-	{7737, 1, &rule23},-	{7738, 1, &rule22},-	{7739, 1, &rule23},-	{7740, 1, &rule22},-	{7741, 1, &rule23},-	{7742, 1, &rule22},-	{7743, 1, &rule23},-	{7744, 1, &rule22},-	{7745, 1, &rule23},-	{7746, 1, &rule22},-	{7747, 1, &rule23},-	{7748, 1, &rule22},-	{7749, 1, &rule23},-	{7750, 1, &rule22},-	{7751, 1, &rule23},-	{7752, 1, &rule22},-	{7753, 1, &rule23},-	{7754, 1, &rule22},-	{7755, 1, &rule23},-	{7756, 1, &rule22},-	{7757, 1, &rule23},-	{7758, 1, &rule22},-	{7759, 1, &rule23},-	{7760, 1, &rule22},-	{7761, 1, &rule23},-	{7762, 1, &rule22},-	{7763, 1, &rule23},-	{7764, 1, &rule22},-	{7765, 1, &rule23},-	{7766, 1, &rule22},-	{7767, 1, &rule23},-	{7768, 1, &rule22},-	{7769, 1, &rule23},-	{7770, 1, &rule22},-	{7771, 1, &rule23},-	{7772, 1, &rule22},-	{7773, 1, &rule23},-	{7774, 1, &rule22},-	{7775, 1, &rule23},-	{7776, 1, &rule22},-	{7777, 1, &rule23},-	{7778, 1, &rule22},-	{7779, 1, &rule23},-	{7780, 1, &rule22},-	{7781, 1, &rule23},-	{7782, 1, &rule22},-	{7783, 1, &rule23},-	{7784, 1, &rule22},-	{7785, 1, &rule23},-	{7786, 1, &rule22},-	{7787, 1, &rule23},-	{7788, 1, &rule22},-	{7789, 1, &rule23},-	{7790, 1, &rule22},-	{7791, 1, &rule23},-	{7792, 1, &rule22},-	{7793, 1, &rule23},-	{7794, 1, &rule22},-	{7795, 1, &rule23},-	{7796, 1, &rule22},-	{7797, 1, &rule23},-	{7798, 1, &rule22},-	{7799, 1, &rule23},-	{7800, 1, &rule22},-	{7801, 1, &rule23},-	{7802, 1, &rule22},-	{7803, 1, &rule23},-	{7804, 1, &rule22},-	{7805, 1, &rule23},-	{7806, 1, &rule22},-	{7807, 1, &rule23},-	{7808, 1, &rule22},-	{7809, 1, &rule23},-	{7810, 1, &rule22},-	{7811, 1, &rule23},-	{7812, 1, &rule22},-	{7813, 1, &rule23},-	{7814, 1, &rule22},-	{7815, 1, &rule23},-	{7816, 1, &rule22},-	{7817, 1, &rule23},-	{7818, 1, &rule22},-	{7819, 1, &rule23},-	{7820, 1, &rule22},-	{7821, 1, &rule23},-	{7822, 1, &rule22},-	{7823, 1, &rule23},-	{7824, 1, &rule22},-	{7825, 1, &rule23},-	{7826, 1, &rule22},-	{7827, 1, &rule23},-	{7828, 1, &rule22},-	{7829, 1, &rule23},-	{7830, 5, &rule20},-	{7835, 1, &rule127},-	{7836, 2, &rule20},-	{7838, 1, &rule128},-	{7839, 1, &rule20},-	{7840, 1, &rule22},-	{7841, 1, &rule23},-	{7842, 1, &rule22},-	{7843, 1, &rule23},-	{7844, 1, &rule22},-	{7845, 1, &rule23},-	{7846, 1, &rule22},-	{7847, 1, &rule23},-	{7848, 1, &rule22},-	{7849, 1, &rule23},-	{7850, 1, &rule22},-	{7851, 1, &rule23},-	{7852, 1, &rule22},-	{7853, 1, &rule23},-	{7854, 1, &rule22},-	{7855, 1, &rule23},-	{7856, 1, &rule22},-	{7857, 1, &rule23},-	{7858, 1, &rule22},-	{7859, 1, &rule23},-	{7860, 1, &rule22},-	{7861, 1, &rule23},-	{7862, 1, &rule22},-	{7863, 1, &rule23},-	{7864, 1, &rule22},-	{7865, 1, &rule23},-	{7866, 1, &rule22},-	{7867, 1, &rule23},-	{7868, 1, &rule22},-	{7869, 1, &rule23},-	{7870, 1, &rule22},-	{7871, 1, &rule23},-	{7872, 1, &rule22},-	{7873, 1, &rule23},-	{7874, 1, &rule22},-	{7875, 1, &rule23},-	{7876, 1, &rule22},-	{7877, 1, &rule23},-	{7878, 1, &rule22},-	{7879, 1, &rule23},-	{7880, 1, &rule22},-	{7881, 1, &rule23},-	{7882, 1, &rule22},-	{7883, 1, &rule23},-	{7884, 1, &rule22},-	{7885, 1, &rule23},-	{7886, 1, &rule22},-	{7887, 1, &rule23},-	{7888, 1, &rule22},-	{7889, 1, &rule23},-	{7890, 1, &rule22},-	{7891, 1, &rule23},-	{7892, 1, &rule22},-	{7893, 1, &rule23},-	{7894, 1, &rule22},-	{7895, 1, &rule23},-	{7896, 1, &rule22},-	{7897, 1, &rule23},-	{7898, 1, &rule22},-	{7899, 1, &rule23},-	{7900, 1, &rule22},-	{7901, 1, &rule23},-	{7902, 1, &rule22},-	{7903, 1, &rule23},-	{7904, 1, &rule22},-	{7905, 1, &rule23},-	{7906, 1, &rule22},-	{7907, 1, &rule23},-	{7908, 1, &rule22},-	{7909, 1, &rule23},-	{7910, 1, &rule22},-	{7911, 1, &rule23},-	{7912, 1, &rule22},-	{7913, 1, &rule23},-	{7914, 1, &rule22},-	{7915, 1, &rule23},-	{7916, 1, &rule22},-	{7917, 1, &rule23},-	{7918, 1, &rule22},-	{7919, 1, &rule23},-	{7920, 1, &rule22},-	{7921, 1, &rule23},-	{7922, 1, &rule22},-	{7923, 1, &rule23},-	{7924, 1, &rule22},-	{7925, 1, &rule23},-	{7926, 1, &rule22},-	{7927, 1, &rule23},-	{7928, 1, &rule22},-	{7929, 1, &rule23},-	{7930, 1, &rule22},-	{7931, 1, &rule23},-	{7932, 1, &rule22},-	{7933, 1, &rule23},-	{7934, 1, &rule22},-	{7935, 1, &rule23},-	{7936, 8, &rule129},-	{7944, 8, &rule130},-	{7952, 6, &rule129},-	{7960, 6, &rule130},-	{7968, 8, &rule129},-	{7976, 8, &rule130},-	{7984, 8, &rule129},-	{7992, 8, &rule130},-	{8000, 6, &rule129},-	{8008, 6, &rule130},-	{8016, 1, &rule20},-	{8017, 1, &rule129},-	{8018, 1, &rule20},-	{8019, 1, &rule129},-	{8020, 1, &rule20},-	{8021, 1, &rule129},-	{8022, 1, &rule20},-	{8023, 1, &rule129},-	{8025, 1, &rule130},-	{8027, 1, &rule130},-	{8029, 1, &rule130},-	{8031, 1, &rule130},-	{8032, 8, &rule129},-	{8040, 8, &rule130},-	{8048, 2, &rule131},-	{8050, 4, &rule132},-	{8054, 2, &rule133},-	{8056, 2, &rule134},-	{8058, 2, &rule135},-	{8060, 2, &rule136},-	{8064, 8, &rule129},-	{8072, 8, &rule137},-	{8080, 8, &rule129},-	{8088, 8, &rule137},-	{8096, 8, &rule129},-	{8104, 8, &rule137},-	{8112, 2, &rule129},-	{8114, 1, &rule20},-	{8115, 1, &rule138},-	{8116, 1, &rule20},-	{8118, 2, &rule20},-	{8120, 2, &rule130},-	{8122, 2, &rule139},-	{8124, 1, &rule140},-	{8125, 1, &rule10},-	{8126, 1, &rule141},-	{8127, 3, &rule10},-	{8130, 1, &rule20},-	{8131, 1, &rule138},-	{8132, 1, &rule20},-	{8134, 2, &rule20},-	{8136, 4, &rule142},-	{8140, 1, &rule140},-	{8141, 3, &rule10},-	{8144, 2, &rule129},-	{8146, 2, &rule20},-	{8150, 2, &rule20},-	{8152, 2, &rule130},-	{8154, 2, &rule143},-	{8157, 3, &rule10},-	{8160, 2, &rule129},-	{8162, 3, &rule20},-	{8165, 1, &rule111},-	{8166, 2, &rule20},-	{8168, 2, &rule130},-	{8170, 2, &rule144},-	{8172, 1, &rule115},-	{8173, 3, &rule10},-	{8178, 1, &rule20},-	{8179, 1, &rule138},-	{8180, 1, &rule20},-	{8182, 2, &rule20},-	{8184, 2, &rule145},-	{8186, 2, &rule146},-	{8188, 1, &rule140},-	{8189, 2, &rule10},-	{8192, 11, &rule1},-	{8203, 5, &rule16},-	{8208, 6, &rule7},-	{8214, 2, &rule2},-	{8216, 1, &rule15},-	{8217, 1, &rule19},-	{8218, 1, &rule4},-	{8219, 2, &rule15},-	{8221, 1, &rule19},-	{8222, 1, &rule4},-	{8223, 1, &rule15},-	{8224, 8, &rule2},-	{8232, 1, &rule147},-	{8233, 1, &rule148},-	{8234, 5, &rule16},-	{8239, 1, &rule1},-	{8240, 9, &rule2},-	{8249, 1, &rule15},-	{8250, 1, &rule19},-	{8251, 4, &rule2},-	{8255, 2, &rule11},-	{8257, 3, &rule2},-	{8260, 1, &rule6},-	{8261, 1, &rule4},-	{8262, 1, &rule5},-	{8263, 11, &rule2},-	{8274, 1, &rule6},-	{8275, 1, &rule2},-	{8276, 1, &rule11},-	{8277, 10, &rule2},-	{8287, 1, &rule1},-	{8288, 5, &rule16},-	{8294, 10, &rule16},-	{8304, 1, &rule17},-	{8305, 1, &rule89},-	{8308, 6, &rule17},-	{8314, 3, &rule6},-	{8317, 1, &rule4},-	{8318, 1, &rule5},-	{8319, 1, &rule89},-	{8320, 10, &rule17},-	{8330, 3, &rule6},-	{8333, 1, &rule4},-	{8334, 1, &rule5},-	{8336, 13, &rule89},-	{8352, 30, &rule3},-	{8400, 13, &rule90},-	{8413, 4, &rule117},-	{8417, 1, &rule90},-	{8418, 3, &rule117},-	{8421, 12, &rule90},-	{8448, 2, &rule13},-	{8450, 1, &rule105},-	{8451, 4, &rule13},-	{8455, 1, &rule105},-	{8456, 2, &rule13},-	{8458, 1, &rule20},-	{8459, 3, &rule105},-	{8462, 2, &rule20},-	{8464, 3, &rule105},-	{8467, 1, &rule20},-	{8468, 1, &rule13},-	{8469, 1, &rule105},-	{8470, 2, &rule13},-	{8472, 1, &rule6},-	{8473, 5, &rule105},-	{8478, 6, &rule13},-	{8484, 1, &rule105},-	{8485, 1, &rule13},-	{8486, 1, &rule149},-	{8487, 1, &rule13},-	{8488, 1, &rule105},-	{8489, 1, &rule13},-	{8490, 1, &rule150},-	{8491, 1, &rule151},-	{8492, 2, &rule105},-	{8494, 1, &rule13},-	{8495, 1, &rule20},-	{8496, 2, &rule105},-	{8498, 1, &rule152},-	{8499, 1, &rule105},-	{8500, 1, &rule20},-	{8501, 4, &rule14},-	{8505, 1, &rule20},-	{8506, 2, &rule13},-	{8508, 2, &rule20},-	{8510, 2, &rule105},-	{8512, 5, &rule6},-	{8517, 1, &rule105},-	{8518, 4, &rule20},-	{8522, 1, &rule13},-	{8523, 1, &rule6},-	{8524, 2, &rule13},-	{8526, 1, &rule153},-	{8527, 1, &rule13},-	{8528, 16, &rule17},-	{8544, 16, &rule154},-	{8560, 16, &rule155},-	{8576, 3, &rule124},-	{8579, 1, &rule22},-	{8580, 1, &rule23},-	{8581, 4, &rule124},-	{8585, 1, &rule17},-	{8592, 5, &rule6},-	{8597, 5, &rule13},-	{8602, 2, &rule6},-	{8604, 4, &rule13},-	{8608, 1, &rule6},-	{8609, 2, &rule13},-	{8611, 1, &rule6},-	{8612, 2, &rule13},-	{8614, 1, &rule6},-	{8615, 7, &rule13},-	{8622, 1, &rule6},-	{8623, 31, &rule13},-	{8654, 2, &rule6},-	{8656, 2, &rule13},-	{8658, 1, &rule6},-	{8659, 1, &rule13},-	{8660, 1, &rule6},-	{8661, 31, &rule13},-	{8692, 268, &rule6},-	{8960, 8, &rule13},-	{8968, 1, &rule4},-	{8969, 1, &rule5},-	{8970, 1, &rule4},-	{8971, 1, &rule5},-	{8972, 20, &rule13},-	{8992, 2, &rule6},-	{8994, 7, &rule13},-	{9001, 1, &rule4},-	{9002, 1, &rule5},-	{9003, 81, &rule13},-	{9084, 1, &rule6},-	{9085, 30, &rule13},-	{9115, 25, &rule6},-	{9140, 40, &rule13},-	{9180, 6, &rule6},-	{9186, 25, &rule13},-	{9216, 39, &rule13},-	{9280, 11, &rule13},-	{9312, 60, &rule17},-	{9372, 26, &rule13},-	{9398, 26, &rule156},-	{9424, 26, &rule157},-	{9450, 22, &rule17},-	{9472, 183, &rule13},-	{9655, 1, &rule6},-	{9656, 9, &rule13},-	{9665, 1, &rule6},-	{9666, 54, &rule13},-	{9720, 8, &rule6},-	{9728, 111, &rule13},-	{9839, 1, &rule6},-	{9840, 248, &rule13},-	{10088, 1, &rule4},-	{10089, 1, &rule5},-	{10090, 1, &rule4},-	{10091, 1, &rule5},-	{10092, 1, &rule4},-	{10093, 1, &rule5},-	{10094, 1, &rule4},-	{10095, 1, &rule5},-	{10096, 1, &rule4},-	{10097, 1, &rule5},-	{10098, 1, &rule4},-	{10099, 1, &rule5},-	{10100, 1, &rule4},-	{10101, 1, &rule5},-	{10102, 30, &rule17},-	{10132, 44, &rule13},-	{10176, 5, &rule6},-	{10181, 1, &rule4},-	{10182, 1, &rule5},-	{10183, 31, &rule6},-	{10214, 1, &rule4},-	{10215, 1, &rule5},-	{10216, 1, &rule4},-	{10217, 1, &rule5},-	{10218, 1, &rule4},-	{10219, 1, &rule5},-	{10220, 1, &rule4},-	{10221, 1, &rule5},-	{10222, 1, &rule4},-	{10223, 1, &rule5},-	{10224, 16, &rule6},-	{10240, 256, &rule13},-	{10496, 131, &rule6},-	{10627, 1, &rule4},-	{10628, 1, &rule5},-	{10629, 1, &rule4},-	{10630, 1, &rule5},-	{10631, 1, &rule4},-	{10632, 1, &rule5},-	{10633, 1, &rule4},-	{10634, 1, &rule5},-	{10635, 1, &rule4},-	{10636, 1, &rule5},-	{10637, 1, &rule4},-	{10638, 1, &rule5},-	{10639, 1, &rule4},-	{10640, 1, &rule5},-	{10641, 1, &rule4},-	{10642, 1, &rule5},-	{10643, 1, &rule4},-	{10644, 1, &rule5},-	{10645, 1, &rule4},-	{10646, 1, &rule5},-	{10647, 1, &rule4},-	{10648, 1, &rule5},-	{10649, 63, &rule6},-	{10712, 1, &rule4},-	{10713, 1, &rule5},-	{10714, 1, &rule4},-	{10715, 1, &rule5},-	{10716, 32, &rule6},-	{10748, 1, &rule4},-	{10749, 1, &rule5},-	{10750, 258, &rule6},-	{11008, 48, &rule13},-	{11056, 21, &rule6},-	{11077, 2, &rule13},-	{11079, 6, &rule6},-	{11085, 39, &rule13},-	{11126, 32, &rule13},-	{11160, 34, &rule13},-	{11197, 12, &rule13},-	{11210, 8, &rule13},-	{11264, 47, &rule120},-	{11312, 47, &rule121},-	{11360, 1, &rule22},-	{11361, 1, &rule23},-	{11362, 1, &rule158},-	{11363, 1, &rule159},-	{11364, 1, &rule160},-	{11365, 1, &rule161},-	{11366, 1, &rule162},-	{11367, 1, &rule22},-	{11368, 1, &rule23},-	{11369, 1, &rule22},-	{11370, 1, &rule23},-	{11371, 1, &rule22},-	{11372, 1, &rule23},-	{11373, 1, &rule163},-	{11374, 1, &rule164},-	{11375, 1, &rule165},-	{11376, 1, &rule166},-	{11377, 1, &rule20},-	{11378, 1, &rule22},-	{11379, 1, &rule23},-	{11380, 1, &rule20},-	{11381, 1, &rule22},-	{11382, 1, &rule23},-	{11383, 5, &rule20},-	{11388, 2, &rule89},-	{11390, 2, &rule167},-	{11392, 1, &rule22},-	{11393, 1, &rule23},-	{11394, 1, &rule22},-	{11395, 1, &rule23},-	{11396, 1, &rule22},-	{11397, 1, &rule23},-	{11398, 1, &rule22},-	{11399, 1, &rule23},-	{11400, 1, &rule22},-	{11401, 1, &rule23},-	{11402, 1, &rule22},-	{11403, 1, &rule23},-	{11404, 1, &rule22},-	{11405, 1, &rule23},-	{11406, 1, &rule22},-	{11407, 1, &rule23},-	{11408, 1, &rule22},-	{11409, 1, &rule23},-	{11410, 1, &rule22},-	{11411, 1, &rule23},-	{11412, 1, &rule22},-	{11413, 1, &rule23},-	{11414, 1, &rule22},-	{11415, 1, &rule23},-	{11416, 1, &rule22},-	{11417, 1, &rule23},-	{11418, 1, &rule22},-	{11419, 1, &rule23},-	{11420, 1, &rule22},-	{11421, 1, &rule23},-	{11422, 1, &rule22},-	{11423, 1, &rule23},-	{11424, 1, &rule22},-	{11425, 1, &rule23},-	{11426, 1, &rule22},-	{11427, 1, &rule23},-	{11428, 1, &rule22},-	{11429, 1, &rule23},-	{11430, 1, &rule22},-	{11431, 1, &rule23},-	{11432, 1, &rule22},-	{11433, 1, &rule23},-	{11434, 1, &rule22},-	{11435, 1, &rule23},-	{11436, 1, &rule22},-	{11437, 1, &rule23},-	{11438, 1, &rule22},-	{11439, 1, &rule23},-	{11440, 1, &rule22},-	{11441, 1, &rule23},-	{11442, 1, &rule22},-	{11443, 1, &rule23},-	{11444, 1, &rule22},-	{11445, 1, &rule23},-	{11446, 1, &rule22},-	{11447, 1, &rule23},-	{11448, 1, &rule22},-	{11449, 1, &rule23},-	{11450, 1, &rule22},-	{11451, 1, &rule23},-	{11452, 1, &rule22},-	{11453, 1, &rule23},-	{11454, 1, &rule22},-	{11455, 1, &rule23},-	{11456, 1, &rule22},-	{11457, 1, &rule23},-	{11458, 1, &rule22},-	{11459, 1, &rule23},-	{11460, 1, &rule22},-	{11461, 1, &rule23},-	{11462, 1, &rule22},-	{11463, 1, &rule23},-	{11464, 1, &rule22},-	{11465, 1, &rule23},-	{11466, 1, &rule22},-	{11467, 1, &rule23},-	{11468, 1, &rule22},-	{11469, 1, &rule23},-	{11470, 1, &rule22},-	{11471, 1, &rule23},-	{11472, 1, &rule22},-	{11473, 1, &rule23},-	{11474, 1, &rule22},-	{11475, 1, &rule23},-	{11476, 1, &rule22},-	{11477, 1, &rule23},-	{11478, 1, &rule22},-	{11479, 1, &rule23},-	{11480, 1, &rule22},-	{11481, 1, &rule23},-	{11482, 1, &rule22},-	{11483, 1, &rule23},-	{11484, 1, &rule22},-	{11485, 1, &rule23},-	{11486, 1, &rule22},-	{11487, 1, &rule23},-	{11488, 1, &rule22},-	{11489, 1, &rule23},-	{11490, 1, &rule22},-	{11491, 1, &rule23},-	{11492, 1, &rule20},-	{11493, 6, &rule13},-	{11499, 1, &rule22},-	{11500, 1, &rule23},-	{11501, 1, &rule22},-	{11502, 1, &rule23},-	{11503, 3, &rule90},-	{11506, 1, &rule22},-	{11507, 1, &rule23},-	{11513, 4, &rule2},-	{11517, 1, &rule17},-	{11518, 2, &rule2},-	{11520, 38, &rule168},-	{11559, 1, &rule168},-	{11565, 1, &rule168},-	{11568, 56, &rule14},-	{11631, 1, &rule89},-	{11632, 1, &rule2},-	{11647, 1, &rule90},-	{11648, 23, &rule14},-	{11680, 7, &rule14},-	{11688, 7, &rule14},-	{11696, 7, &rule14},-	{11704, 7, &rule14},-	{11712, 7, &rule14},-	{11720, 7, &rule14},-	{11728, 7, &rule14},-	{11736, 7, &rule14},-	{11744, 32, &rule90},-	{11776, 2, &rule2},-	{11778, 1, &rule15},-	{11779, 1, &rule19},-	{11780, 1, &rule15},-	{11781, 1, &rule19},-	{11782, 3, &rule2},-	{11785, 1, &rule15},-	{11786, 1, &rule19},-	{11787, 1, &rule2},-	{11788, 1, &rule15},-	{11789, 1, &rule19},-	{11790, 9, &rule2},-	{11799, 1, &rule7},-	{11800, 2, &rule2},-	{11802, 1, &rule7},-	{11803, 1, &rule2},-	{11804, 1, &rule15},-	{11805, 1, &rule19},-	{11806, 2, &rule2},-	{11808, 1, &rule15},-	{11809, 1, &rule19},-	{11810, 1, &rule4},-	{11811, 1, &rule5},-	{11812, 1, &rule4},-	{11813, 1, &rule5},-	{11814, 1, &rule4},-	{11815, 1, &rule5},-	{11816, 1, &rule4},-	{11817, 1, &rule5},-	{11818, 5, &rule2},-	{11823, 1, &rule89},-	{11824, 10, &rule2},-	{11834, 2, &rule7},-	{11836, 4, &rule2},-	{11840, 1, &rule7},-	{11841, 1, &rule2},-	{11842, 1, &rule4},-	{11904, 26, &rule13},-	{11931, 89, &rule13},-	{12032, 214, &rule13},-	{12272, 12, &rule13},-	{12288, 1, &rule1},-	{12289, 3, &rule2},-	{12292, 1, &rule13},-	{12293, 1, &rule89},-	{12294, 1, &rule14},-	{12295, 1, &rule124},-	{12296, 1, &rule4},-	{12297, 1, &rule5},-	{12298, 1, &rule4},-	{12299, 1, &rule5},-	{12300, 1, &rule4},-	{12301, 1, &rule5},-	{12302, 1, &rule4},-	{12303, 1, &rule5},-	{12304, 1, &rule4},-	{12305, 1, &rule5},-	{12306, 2, &rule13},-	{12308, 1, &rule4},-	{12309, 1, &rule5},-	{12310, 1, &rule4},-	{12311, 1, &rule5},-	{12312, 1, &rule4},-	{12313, 1, &rule5},-	{12314, 1, &rule4},-	{12315, 1, &rule5},-	{12316, 1, &rule7},-	{12317, 1, &rule4},-	{12318, 2, &rule5},-	{12320, 1, &rule13},-	{12321, 9, &rule124},-	{12330, 4, &rule90},-	{12334, 2, &rule122},-	{12336, 1, &rule7},-	{12337, 5, &rule89},-	{12342, 2, &rule13},-	{12344, 3, &rule124},-	{12347, 1, &rule89},-	{12348, 1, &rule14},-	{12349, 1, &rule2},-	{12350, 2, &rule13},-	{12353, 86, &rule14},-	{12441, 2, &rule90},-	{12443, 2, &rule10},-	{12445, 2, &rule89},-	{12447, 1, &rule14},-	{12448, 1, &rule7},-	{12449, 90, &rule14},-	{12539, 1, &rule2},-	{12540, 3, &rule89},-	{12543, 1, &rule14},-	{12549, 41, &rule14},-	{12593, 94, &rule14},-	{12688, 2, &rule13},-	{12690, 4, &rule17},-	{12694, 10, &rule13},-	{12704, 27, &rule14},-	{12736, 36, &rule13},-	{12784, 16, &rule14},-	{12800, 31, &rule13},-	{12832, 10, &rule17},-	{12842, 30, &rule13},-	{12872, 8, &rule17},-	{12880, 1, &rule13},-	{12881, 15, &rule17},-	{12896, 32, &rule13},-	{12928, 10, &rule17},-	{12938, 39, &rule13},-	{12977, 15, &rule17},-	{12992, 63, &rule13},-	{13056, 256, &rule13},-	{13312, 6582, &rule14},-	{19904, 64, &rule13},-	{19968, 20941, &rule14},-	{40960, 21, &rule14},-	{40981, 1, &rule89},-	{40982, 1143, &rule14},-	{42128, 55, &rule13},-	{42192, 40, &rule14},-	{42232, 6, &rule89},-	{42238, 2, &rule2},-	{42240, 268, &rule14},-	{42508, 1, &rule89},-	{42509, 3, &rule2},-	{42512, 16, &rule14},-	{42528, 10, &rule8},-	{42538, 2, &rule14},-	{42560, 1, &rule22},-	{42561, 1, &rule23},-	{42562, 1, &rule22},-	{42563, 1, &rule23},-	{42564, 1, &rule22},-	{42565, 1, &rule23},-	{42566, 1, &rule22},-	{42567, 1, &rule23},-	{42568, 1, &rule22},-	{42569, 1, &rule23},-	{42570, 1, &rule22},-	{42571, 1, &rule23},-	{42572, 1, &rule22},-	{42573, 1, &rule23},-	{42574, 1, &rule22},-	{42575, 1, &rule23},-	{42576, 1, &rule22},-	{42577, 1, &rule23},-	{42578, 1, &rule22},-	{42579, 1, &rule23},-	{42580, 1, &rule22},-	{42581, 1, &rule23},-	{42582, 1, &rule22},-	{42583, 1, &rule23},-	{42584, 1, &rule22},-	{42585, 1, &rule23},-	{42586, 1, &rule22},-	{42587, 1, &rule23},-	{42588, 1, &rule22},-	{42589, 1, &rule23},-	{42590, 1, &rule22},-	{42591, 1, &rule23},-	{42592, 1, &rule22},-	{42593, 1, &rule23},-	{42594, 1, &rule22},-	{42595, 1, &rule23},-	{42596, 1, &rule22},-	{42597, 1, &rule23},-	{42598, 1, &rule22},-	{42599, 1, &rule23},-	{42600, 1, &rule22},-	{42601, 1, &rule23},-	{42602, 1, &rule22},-	{42603, 1, &rule23},-	{42604, 1, &rule22},-	{42605, 1, &rule23},-	{42606, 1, &rule14},-	{42607, 1, &rule90},-	{42608, 3, &rule117},-	{42611, 1, &rule2},-	{42612, 10, &rule90},-	{42622, 1, &rule2},-	{42623, 1, &rule89},-	{42624, 1, &rule22},-	{42625, 1, &rule23},-	{42626, 1, &rule22},-	{42627, 1, &rule23},-	{42628, 1, &rule22},-	{42629, 1, &rule23},-	{42630, 1, &rule22},-	{42631, 1, &rule23},-	{42632, 1, &rule22},-	{42633, 1, &rule23},-	{42634, 1, &rule22},-	{42635, 1, &rule23},-	{42636, 1, &rule22},-	{42637, 1, &rule23},-	{42638, 1, &rule22},-	{42639, 1, &rule23},-	{42640, 1, &rule22},-	{42641, 1, &rule23},-	{42642, 1, &rule22},-	{42643, 1, &rule23},-	{42644, 1, &rule22},-	{42645, 1, &rule23},-	{42646, 1, &rule22},-	{42647, 1, &rule23},-	{42648, 1, &rule22},-	{42649, 1, &rule23},-	{42650, 1, &rule22},-	{42651, 1, &rule23},-	{42652, 2, &rule89},-	{42655, 1, &rule90},-	{42656, 70, &rule14},-	{42726, 10, &rule124},-	{42736, 2, &rule90},-	{42738, 6, &rule2},-	{42752, 23, &rule10},-	{42775, 9, &rule89},-	{42784, 2, &rule10},-	{42786, 1, &rule22},-	{42787, 1, &rule23},-	{42788, 1, &rule22},-	{42789, 1, &rule23},-	{42790, 1, &rule22},-	{42791, 1, &rule23},-	{42792, 1, &rule22},-	{42793, 1, &rule23},-	{42794, 1, &rule22},-	{42795, 1, &rule23},-	{42796, 1, &rule22},-	{42797, 1, &rule23},-	{42798, 1, &rule22},-	{42799, 1, &rule23},-	{42800, 2, &rule20},-	{42802, 1, &rule22},-	{42803, 1, &rule23},-	{42804, 1, &rule22},-	{42805, 1, &rule23},-	{42806, 1, &rule22},-	{42807, 1, &rule23},-	{42808, 1, &rule22},-	{42809, 1, &rule23},-	{42810, 1, &rule22},-	{42811, 1, &rule23},-	{42812, 1, &rule22},-	{42813, 1, &rule23},-	{42814, 1, &rule22},-	{42815, 1, &rule23},-	{42816, 1, &rule22},-	{42817, 1, &rule23},-	{42818, 1, &rule22},-	{42819, 1, &rule23},-	{42820, 1, &rule22},-	{42821, 1, &rule23},-	{42822, 1, &rule22},-	{42823, 1, &rule23},-	{42824, 1, &rule22},-	{42825, 1, &rule23},-	{42826, 1, &rule22},-	{42827, 1, &rule23},-	{42828, 1, &rule22},-	{42829, 1, &rule23},-	{42830, 1, &rule22},-	{42831, 1, &rule23},-	{42832, 1, &rule22},-	{42833, 1, &rule23},-	{42834, 1, &rule22},-	{42835, 1, &rule23},-	{42836, 1, &rule22},-	{42837, 1, &rule23},-	{42838, 1, &rule22},-	{42839, 1, &rule23},-	{42840, 1, &rule22},-	{42841, 1, &rule23},-	{42842, 1, &rule22},-	{42843, 1, &rule23},-	{42844, 1, &rule22},-	{42845, 1, &rule23},-	{42846, 1, &rule22},-	{42847, 1, &rule23},-	{42848, 1, &rule22},-	{42849, 1, &rule23},-	{42850, 1, &rule22},-	{42851, 1, &rule23},-	{42852, 1, &rule22},-	{42853, 1, &rule23},-	{42854, 1, &rule22},-	{42855, 1, &rule23},-	{42856, 1, &rule22},-	{42857, 1, &rule23},-	{42858, 1, &rule22},-	{42859, 1, &rule23},-	{42860, 1, &rule22},-	{42861, 1, &rule23},-	{42862, 1, &rule22},-	{42863, 1, &rule23},-	{42864, 1, &rule89},-	{42865, 8, &rule20},-	{42873, 1, &rule22},-	{42874, 1, &rule23},-	{42875, 1, &rule22},-	{42876, 1, &rule23},-	{42877, 1, &rule169},-	{42878, 1, &rule22},-	{42879, 1, &rule23},-	{42880, 1, &rule22},-	{42881, 1, &rule23},-	{42882, 1, &rule22},-	{42883, 1, &rule23},-	{42884, 1, &rule22},-	{42885, 1, &rule23},-	{42886, 1, &rule22},-	{42887, 1, &rule23},-	{42888, 1, &rule89},-	{42889, 2, &rule10},-	{42891, 1, &rule22},-	{42892, 1, &rule23},-	{42893, 1, &rule170},-	{42894, 1, &rule20},-	{42896, 1, &rule22},-	{42897, 1, &rule23},-	{42898, 1, &rule22},-	{42899, 1, &rule23},-	{42900, 2, &rule20},-	{42902, 1, &rule22},-	{42903, 1, &rule23},-	{42904, 1, &rule22},-	{42905, 1, &rule23},-	{42906, 1, &rule22},-	{42907, 1, &rule23},-	{42908, 1, &rule22},-	{42909, 1, &rule23},-	{42910, 1, &rule22},-	{42911, 1, &rule23},-	{42912, 1, &rule22},-	{42913, 1, &rule23},-	{42914, 1, &rule22},-	{42915, 1, &rule23},-	{42916, 1, &rule22},-	{42917, 1, &rule23},-	{42918, 1, &rule22},-	{42919, 1, &rule23},-	{42920, 1, &rule22},-	{42921, 1, &rule23},-	{42922, 1, &rule171},-	{42923, 1, &rule172},-	{42924, 1, &rule173},-	{42925, 1, &rule174},-	{42928, 1, &rule175},-	{42929, 1, &rule176},-	{42999, 1, &rule14},-	{43000, 2, &rule89},-	{43002, 1, &rule20},-	{43003, 7, &rule14},-	{43010, 1, &rule90},-	{43011, 3, &rule14},-	{43014, 1, &rule90},-	{43015, 4, &rule14},-	{43019, 1, &rule90},-	{43020, 23, &rule14},-	{43043, 2, &rule122},-	{43045, 2, &rule90},-	{43047, 1, &rule122},-	{43048, 4, &rule13},-	{43056, 6, &rule17},-	{43062, 2, &rule13},-	{43064, 1, &rule3},-	{43065, 1, &rule13},-	{43072, 52, &rule14},-	{43124, 4, &rule2},-	{43136, 2, &rule122},-	{43138, 50, &rule14},-	{43188, 16, &rule122},-	{43204, 1, &rule90},-	{43214, 2, &rule2},-	{43216, 10, &rule8},-	{43232, 18, &rule90},-	{43250, 6, &rule14},-	{43256, 3, &rule2},-	{43259, 1, &rule14},-	{43264, 10, &rule8},-	{43274, 28, &rule14},-	{43302, 8, &rule90},-	{43310, 2, &rule2},-	{43312, 23, &rule14},-	{43335, 11, &rule90},-	{43346, 2, &rule122},-	{43359, 1, &rule2},-	{43360, 29, &rule14},-	{43392, 3, &rule90},-	{43395, 1, &rule122},-	{43396, 47, &rule14},-	{43443, 1, &rule90},-	{43444, 2, &rule122},-	{43446, 4, &rule90},-	{43450, 2, &rule122},-	{43452, 1, &rule90},-	{43453, 4, &rule122},-	{43457, 13, &rule2},-	{43471, 1, &rule89},-	{43472, 10, &rule8},-	{43486, 2, &rule2},-	{43488, 5, &rule14},-	{43493, 1, &rule90},-	{43494, 1, &rule89},-	{43495, 9, &rule14},-	{43504, 10, &rule8},-	{43514, 5, &rule14},-	{43520, 41, &rule14},-	{43561, 6, &rule90},-	{43567, 2, &rule122},-	{43569, 2, &rule90},-	{43571, 2, &rule122},-	{43573, 2, &rule90},-	{43584, 3, &rule14},-	{43587, 1, &rule90},-	{43588, 8, &rule14},-	{43596, 1, &rule90},-	{43597, 1, &rule122},-	{43600, 10, &rule8},-	{43612, 4, &rule2},-	{43616, 16, &rule14},-	{43632, 1, &rule89},-	{43633, 6, &rule14},-	{43639, 3, &rule13},-	{43642, 1, &rule14},-	{43643, 1, &rule122},-	{43644, 1, &rule90},-	{43645, 1, &rule122},-	{43646, 50, &rule14},-	{43696, 1, &rule90},-	{43697, 1, &rule14},-	{43698, 3, &rule90},-	{43701, 2, &rule14},-	{43703, 2, &rule90},-	{43705, 5, &rule14},-	{43710, 2, &rule90},-	{43712, 1, &rule14},-	{43713, 1, &rule90},-	{43714, 1, &rule14},-	{43739, 2, &rule14},-	{43741, 1, &rule89},-	{43742, 2, &rule2},-	{43744, 11, &rule14},-	{43755, 1, &rule122},-	{43756, 2, &rule90},-	{43758, 2, &rule122},-	{43760, 2, &rule2},-	{43762, 1, &rule14},-	{43763, 2, &rule89},-	{43765, 1, &rule122},-	{43766, 1, &rule90},-	{43777, 6, &rule14},-	{43785, 6, &rule14},-	{43793, 6, &rule14},-	{43808, 7, &rule14},-	{43816, 7, &rule14},-	{43824, 43, &rule20},-	{43867, 1, &rule10},-	{43868, 4, &rule89},-	{43876, 2, &rule20},-	{43968, 35, &rule14},-	{44003, 2, &rule122},-	{44005, 1, &rule90},-	{44006, 2, &rule122},-	{44008, 1, &rule90},-	{44009, 2, &rule122},-	{44011, 1, &rule2},-	{44012, 1, &rule122},-	{44013, 1, &rule90},-	{44016, 10, &rule8},-	{44032, 11172, &rule14},-	{55216, 23, &rule14},-	{55243, 49, &rule14},-	{55296, 896, &rule177},-	{56192, 128, &rule177},-	{56320, 1024, &rule177},-	{57344, 6400, &rule178},-	{63744, 366, &rule14},-	{64112, 106, &rule14},-	{64256, 7, &rule20},-	{64275, 5, &rule20},-	{64285, 1, &rule14},-	{64286, 1, &rule90},-	{64287, 10, &rule14},-	{64297, 1, &rule6},-	{64298, 13, &rule14},-	{64312, 5, &rule14},-	{64318, 1, &rule14},-	{64320, 2, &rule14},-	{64323, 2, &rule14},-	{64326, 108, &rule14},-	{64434, 16, &rule10},-	{64467, 363, &rule14},-	{64830, 1, &rule5},-	{64831, 1, &rule4},-	{64848, 64, &rule14},-	{64914, 54, &rule14},-	{65008, 12, &rule14},-	{65020, 1, &rule3},-	{65021, 1, &rule13},-	{65024, 16, &rule90},-	{65040, 7, &rule2},-	{65047, 1, &rule4},-	{65048, 1, &rule5},-	{65049, 1, &rule2},-	{65056, 14, &rule90},-	{65072, 1, &rule2},-	{65073, 2, &rule7},-	{65075, 2, &rule11},-	{65077, 1, &rule4},-	{65078, 1, &rule5},-	{65079, 1, &rule4},-	{65080, 1, &rule5},-	{65081, 1, &rule4},-	{65082, 1, &rule5},-	{65083, 1, &rule4},-	{65084, 1, &rule5},-	{65085, 1, &rule4},-	{65086, 1, &rule5},-	{65087, 1, &rule4},-	{65088, 1, &rule5},-	{65089, 1, &rule4},-	{65090, 1, &rule5},-	{65091, 1, &rule4},-	{65092, 1, &rule5},-	{65093, 2, &rule2},-	{65095, 1, &rule4},-	{65096, 1, &rule5},-	{65097, 4, &rule2},-	{65101, 3, &rule11},-	{65104, 3, &rule2},-	{65108, 4, &rule2},-	{65112, 1, &rule7},-	{65113, 1, &rule4},-	{65114, 1, &rule5},-	{65115, 1, &rule4},-	{65116, 1, &rule5},-	{65117, 1, &rule4},-	{65118, 1, &rule5},-	{65119, 3, &rule2},-	{65122, 1, &rule6},-	{65123, 1, &rule7},-	{65124, 3, &rule6},-	{65128, 1, &rule2},-	{65129, 1, &rule3},-	{65130, 2, &rule2},-	{65136, 5, &rule14},-	{65142, 135, &rule14},-	{65279, 1, &rule16},-	{65281, 3, &rule2},-	{65284, 1, &rule3},-	{65285, 3, &rule2},-	{65288, 1, &rule4},-	{65289, 1, &rule5},-	{65290, 1, &rule2},-	{65291, 1, &rule6},-	{65292, 1, &rule2},-	{65293, 1, &rule7},-	{65294, 2, &rule2},-	{65296, 10, &rule8},-	{65306, 2, &rule2},-	{65308, 3, &rule6},-	{65311, 2, &rule2},-	{65313, 26, &rule9},-	{65339, 1, &rule4},-	{65340, 1, &rule2},-	{65341, 1, &rule5},-	{65342, 1, &rule10},-	{65343, 1, &rule11},-	{65344, 1, &rule10},-	{65345, 26, &rule12},-	{65371, 1, &rule4},-	{65372, 1, &rule6},-	{65373, 1, &rule5},-	{65374, 1, &rule6},-	{65375, 1, &rule4},-	{65376, 1, &rule5},-	{65377, 1, &rule2},-	{65378, 1, &rule4},-	{65379, 1, &rule5},-	{65380, 2, &rule2},-	{65382, 10, &rule14},-	{65392, 1, &rule89},-	{65393, 45, &rule14},-	{65438, 2, &rule89},-	{65440, 31, &rule14},-	{65474, 6, &rule14},-	{65482, 6, &rule14},-	{65490, 6, &rule14},-	{65498, 3, &rule14},-	{65504, 2, &rule3},-	{65506, 1, &rule6},-	{65507, 1, &rule10},-	{65508, 1, &rule13},-	{65509, 2, &rule3},-	{65512, 1, &rule13},-	{65513, 4, &rule6},-	{65517, 2, &rule13},-	{65529, 3, &rule16},-	{65532, 2, &rule13},-	{65536, 12, &rule14},-	{65549, 26, &rule14},-	{65576, 19, &rule14},-	{65596, 2, &rule14},-	{65599, 15, &rule14},-	{65616, 14, &rule14},-	{65664, 123, &rule14},-	{65792, 3, &rule2},-	{65799, 45, &rule17},-	{65847, 9, &rule13},-	{65856, 53, &rule124},-	{65909, 4, &rule17},-	{65913, 17, &rule13},-	{65930, 2, &rule17},-	{65932, 1, &rule13},-	{65936, 12, &rule13},-	{65952, 1, &rule13},-	{66000, 45, &rule13},-	{66045, 1, &rule90},-	{66176, 29, &rule14},-	{66208, 49, &rule14},-	{66272, 1, &rule90},-	{66273, 27, &rule17},-	{66304, 32, &rule14},-	{66336, 4, &rule17},-	{66352, 17, &rule14},-	{66369, 1, &rule124},-	{66370, 8, &rule14},-	{66378, 1, &rule124},-	{66384, 38, &rule14},-	{66422, 5, &rule90},-	{66432, 30, &rule14},-	{66463, 1, &rule2},-	{66464, 36, &rule14},-	{66504, 8, &rule14},-	{66512, 1, &rule2},-	{66513, 5, &rule124},-	{66560, 40, &rule179},-	{66600, 40, &rule180},-	{66640, 78, &rule14},-	{66720, 10, &rule8},-	{66816, 40, &rule14},-	{66864, 52, &rule14},-	{66927, 1, &rule2},-	{67072, 311, &rule14},-	{67392, 22, &rule14},-	{67424, 8, &rule14},-	{67584, 6, &rule14},-	{67592, 1, &rule14},-	{67594, 44, &rule14},-	{67639, 2, &rule14},-	{67644, 1, &rule14},-	{67647, 23, &rule14},-	{67671, 1, &rule2},-	{67672, 8, &rule17},-	{67680, 23, &rule14},-	{67703, 2, &rule13},-	{67705, 7, &rule17},-	{67712, 31, &rule14},-	{67751, 9, &rule17},-	{67840, 22, &rule14},-	{67862, 6, &rule17},-	{67871, 1, &rule2},-	{67872, 26, &rule14},-	{67903, 1, &rule2},-	{67968, 56, &rule14},-	{68030, 2, &rule14},-	{68096, 1, &rule14},-	{68097, 3, &rule90},-	{68101, 2, &rule90},-	{68108, 4, &rule90},-	{68112, 4, &rule14},-	{68117, 3, &rule14},-	{68121, 27, &rule14},-	{68152, 3, &rule90},-	{68159, 1, &rule90},-	{68160, 8, &rule17},-	{68176, 9, &rule2},-	{68192, 29, &rule14},-	{68221, 2, &rule17},-	{68223, 1, &rule2},-	{68224, 29, &rule14},-	{68253, 3, &rule17},-	{68288, 8, &rule14},-	{68296, 1, &rule13},-	{68297, 28, &rule14},-	{68325, 2, &rule90},-	{68331, 5, &rule17},-	{68336, 7, &rule2},-	{68352, 54, &rule14},-	{68409, 7, &rule2},-	{68416, 22, &rule14},-	{68440, 8, &rule17},-	{68448, 19, &rule14},-	{68472, 8, &rule17},-	{68480, 18, &rule14},-	{68505, 4, &rule2},-	{68521, 7, &rule17},-	{68608, 73, &rule14},-	{69216, 31, &rule17},-	{69632, 1, &rule122},-	{69633, 1, &rule90},-	{69634, 1, &rule122},-	{69635, 53, &rule14},-	{69688, 15, &rule90},-	{69703, 7, &rule2},-	{69714, 20, &rule17},-	{69734, 10, &rule8},-	{69759, 3, &rule90},-	{69762, 1, &rule122},-	{69763, 45, &rule14},-	{69808, 3, &rule122},-	{69811, 4, &rule90},-	{69815, 2, &rule122},-	{69817, 2, &rule90},-	{69819, 2, &rule2},-	{69821, 1, &rule16},-	{69822, 4, &rule2},-	{69840, 25, &rule14},-	{69872, 10, &rule8},-	{69888, 3, &rule90},-	{69891, 36, &rule14},-	{69927, 5, &rule90},-	{69932, 1, &rule122},-	{69933, 8, &rule90},-	{69942, 10, &rule8},-	{69952, 4, &rule2},-	{69968, 35, &rule14},-	{70003, 1, &rule90},-	{70004, 2, &rule2},-	{70006, 1, &rule14},-	{70016, 2, &rule90},-	{70018, 1, &rule122},-	{70019, 48, &rule14},-	{70067, 3, &rule122},-	{70070, 9, &rule90},-	{70079, 2, &rule122},-	{70081, 4, &rule14},-	{70085, 4, &rule2},-	{70093, 1, &rule2},-	{70096, 10, &rule8},-	{70106, 1, &rule14},-	{70113, 20, &rule17},-	{70144, 18, &rule14},-	{70163, 25, &rule14},-	{70188, 3, &rule122},-	{70191, 3, &rule90},-	{70194, 2, &rule122},-	{70196, 1, &rule90},-	{70197, 1, &rule122},-	{70198, 2, &rule90},-	{70200, 6, &rule2},-	{70320, 47, &rule14},-	{70367, 1, &rule90},-	{70368, 3, &rule122},-	{70371, 8, &rule90},-	{70384, 10, &rule8},-	{70401, 1, &rule90},-	{70402, 2, &rule122},-	{70405, 8, &rule14},-	{70415, 2, &rule14},-	{70419, 22, &rule14},-	{70442, 7, &rule14},-	{70450, 2, &rule14},-	{70453, 5, &rule14},-	{70460, 1, &rule90},-	{70461, 1, &rule14},-	{70462, 2, &rule122},-	{70464, 1, &rule90},-	{70465, 4, &rule122},-	{70471, 2, &rule122},-	{70475, 3, &rule122},-	{70487, 1, &rule122},-	{70493, 5, &rule14},-	{70498, 2, &rule122},-	{70502, 7, &rule90},-	{70512, 5, &rule90},-	{70784, 48, &rule14},-	{70832, 3, &rule122},-	{70835, 6, &rule90},-	{70841, 1, &rule122},-	{70842, 1, &rule90},-	{70843, 4, &rule122},-	{70847, 2, &rule90},-	{70849, 1, &rule122},-	{70850, 2, &rule90},-	{70852, 2, &rule14},-	{70854, 1, &rule2},-	{70855, 1, &rule14},-	{70864, 10, &rule8},-	{71040, 47, &rule14},-	{71087, 3, &rule122},-	{71090, 4, &rule90},-	{71096, 4, &rule122},-	{71100, 2, &rule90},-	{71102, 1, &rule122},-	{71103, 2, &rule90},-	{71105, 9, &rule2},-	{71168, 48, &rule14},-	{71216, 3, &rule122},-	{71219, 8, &rule90},-	{71227, 2, &rule122},-	{71229, 1, &rule90},-	{71230, 1, &rule122},-	{71231, 2, &rule90},-	{71233, 3, &rule2},-	{71236, 1, &rule14},-	{71248, 10, &rule8},-	{71296, 43, &rule14},-	{71339, 1, &rule90},-	{71340, 1, &rule122},-	{71341, 1, &rule90},-	{71342, 2, &rule122},-	{71344, 6, &rule90},-	{71350, 1, &rule122},-	{71351, 1, &rule90},-	{71360, 10, &rule8},-	{71840, 32, &rule9},-	{71872, 32, &rule12},-	{71904, 10, &rule8},-	{71914, 9, &rule17},-	{71935, 1, &rule14},-	{72384, 57, &rule14},-	{73728, 921, &rule14},-	{74752, 111, &rule124},-	{74864, 5, &rule2},-	{77824, 1071, &rule14},-	{92160, 569, &rule14},-	{92736, 31, &rule14},-	{92768, 10, &rule8},-	{92782, 2, &rule2},-	{92880, 30, &rule14},-	{92912, 5, &rule90},-	{92917, 1, &rule2},-	{92928, 48, &rule14},-	{92976, 7, &rule90},-	{92983, 5, &rule2},-	{92988, 4, &rule13},-	{92992, 4, &rule89},-	{92996, 1, &rule2},-	{92997, 1, &rule13},-	{93008, 10, &rule8},-	{93019, 7, &rule17},-	{93027, 21, &rule14},-	{93053, 19, &rule14},-	{93952, 69, &rule14},-	{94032, 1, &rule14},-	{94033, 46, &rule122},-	{94095, 4, &rule90},-	{94099, 13, &rule89},-	{110592, 2, &rule14},-	{113664, 107, &rule14},-	{113776, 13, &rule14},-	{113792, 9, &rule14},-	{113808, 10, &rule14},-	{113820, 1, &rule13},-	{113821, 2, &rule90},-	{113823, 1, &rule2},-	{113824, 4, &rule16},-	{118784, 246, &rule13},-	{119040, 39, &rule13},-	{119081, 60, &rule13},-	{119141, 2, &rule122},-	{119143, 3, &rule90},-	{119146, 3, &rule13},-	{119149, 6, &rule122},-	{119155, 8, &rule16},-	{119163, 8, &rule90},-	{119171, 2, &rule13},-	{119173, 7, &rule90},-	{119180, 30, &rule13},-	{119210, 4, &rule90},-	{119214, 48, &rule13},-	{119296, 66, &rule13},-	{119362, 3, &rule90},-	{119365, 1, &rule13},-	{119552, 87, &rule13},-	{119648, 18, &rule17},-	{119808, 26, &rule105},-	{119834, 26, &rule20},-	{119860, 26, &rule105},-	{119886, 7, &rule20},-	{119894, 18, &rule20},-	{119912, 26, &rule105},-	{119938, 26, &rule20},-	{119964, 1, &rule105},-	{119966, 2, &rule105},-	{119970, 1, &rule105},-	{119973, 2, &rule105},-	{119977, 4, &rule105},-	{119982, 8, &rule105},-	{119990, 4, &rule20},-	{119995, 1, &rule20},-	{119997, 7, &rule20},-	{120005, 11, &rule20},-	{120016, 26, &rule105},-	{120042, 26, &rule20},-	{120068, 2, &rule105},-	{120071, 4, &rule105},-	{120077, 8, &rule105},-	{120086, 7, &rule105},-	{120094, 26, &rule20},-	{120120, 2, &rule105},-	{120123, 4, &rule105},-	{120128, 5, &rule105},-	{120134, 1, &rule105},-	{120138, 7, &rule105},-	{120146, 26, &rule20},-	{120172, 26, &rule105},-	{120198, 26, &rule20},-	{120224, 26, &rule105},-	{120250, 26, &rule20},-	{120276, 26, &rule105},-	{120302, 26, &rule20},-	{120328, 26, &rule105},-	{120354, 26, &rule20},-	{120380, 26, &rule105},-	{120406, 26, &rule20},-	{120432, 26, &rule105},-	{120458, 28, &rule20},-	{120488, 25, &rule105},-	{120513, 1, &rule6},-	{120514, 25, &rule20},-	{120539, 1, &rule6},-	{120540, 6, &rule20},-	{120546, 25, &rule105},-	{120571, 1, &rule6},-	{120572, 25, &rule20},-	{120597, 1, &rule6},-	{120598, 6, &rule20},-	{120604, 25, &rule105},-	{120629, 1, &rule6},-	{120630, 25, &rule20},-	{120655, 1, &rule6},-	{120656, 6, &rule20},-	{120662, 25, &rule105},-	{120687, 1, &rule6},-	{120688, 25, &rule20},-	{120713, 1, &rule6},-	{120714, 6, &rule20},-	{120720, 25, &rule105},-	{120745, 1, &rule6},-	{120746, 25, &rule20},-	{120771, 1, &rule6},-	{120772, 6, &rule20},-	{120778, 1, &rule105},-	{120779, 1, &rule20},-	{120782, 50, &rule8},-	{124928, 197, &rule14},-	{125127, 9, &rule17},-	{125136, 7, &rule90},-	{126464, 4, &rule14},-	{126469, 27, &rule14},-	{126497, 2, &rule14},-	{126500, 1, &rule14},-	{126503, 1, &rule14},-	{126505, 10, &rule14},-	{126516, 4, &rule14},-	{126521, 1, &rule14},-	{126523, 1, &rule14},-	{126530, 1, &rule14},-	{126535, 1, &rule14},-	{126537, 1, &rule14},-	{126539, 1, &rule14},-	{126541, 3, &rule14},-	{126545, 2, &rule14},-	{126548, 1, &rule14},-	{126551, 1, &rule14},-	{126553, 1, &rule14},-	{126555, 1, &rule14},-	{126557, 1, &rule14},-	{126559, 1, &rule14},-	{126561, 2, &rule14},-	{126564, 1, &rule14},-	{126567, 4, &rule14},-	{126572, 7, &rule14},-	{126580, 4, &rule14},-	{126585, 4, &rule14},-	{126590, 1, &rule14},-	{126592, 10, &rule14},-	{126603, 17, &rule14},-	{126625, 3, &rule14},-	{126629, 5, &rule14},-	{126635, 17, &rule14},-	{126704, 2, &rule6},-	{126976, 44, &rule13},-	{127024, 100, &rule13},-	{127136, 15, &rule13},-	{127153, 15, &rule13},-	{127169, 15, &rule13},-	{127185, 37, &rule13},-	{127232, 13, &rule17},-	{127248, 31, &rule13},-	{127280, 60, &rule13},-	{127344, 43, &rule13},-	{127462, 29, &rule13},-	{127504, 43, &rule13},-	{127552, 9, &rule13},-	{127568, 2, &rule13},-	{127744, 45, &rule13},-	{127792, 78, &rule13},-	{127872, 79, &rule13},-	{127956, 36, &rule13},-	{128000, 255, &rule13},-	{128256, 75, &rule13},-	{128336, 42, &rule13},-	{128379, 41, &rule13},-	{128421, 158, &rule13},-	{128581, 139, &rule13},-	{128736, 13, &rule13},-	{128752, 4, &rule13},-	{128768, 116, &rule13},-	{128896, 85, &rule13},-	{129024, 12, &rule13},-	{129040, 56, &rule13},-	{129104, 10, &rule13},-	{129120, 40, &rule13},-	{129168, 30, &rule13},-	{131072, 42711, &rule14},-	{173824, 4149, &rule14},-	{177984, 222, &rule14},-	{194560, 542, &rule14},-	{917505, 1, &rule16},-	{917536, 96, &rule16},-	{917760, 240, &rule90},-	{983040, 65534, &rule178},-	{1048576, 65534, &rule178}-};-static const struct _charblock_ convchars[]={-	{65, 26, &rule9},-	{97, 26, &rule12},-	{181, 1, &rule18},-	{192, 23, &rule9},-	{216, 7, &rule9},-	{224, 23, &rule12},-	{248, 7, &rule12},-	{255, 1, &rule21},-	{256, 1, &rule22},-	{257, 1, &rule23},-	{258, 1, &rule22},-	{259, 1, &rule23},-	{260, 1, &rule22},-	{261, 1, &rule23},-	{262, 1, &rule22},-	{263, 1, &rule23},-	{264, 1, &rule22},-	{265, 1, &rule23},-	{266, 1, &rule22},-	{267, 1, &rule23},-	{268, 1, &rule22},-	{269, 1, &rule23},-	{270, 1, &rule22},-	{271, 1, &rule23},-	{272, 1, &rule22},-	{273, 1, &rule23},-	{274, 1, &rule22},-	{275, 1, &rule23},-	{276, 1, &rule22},-	{277, 1, &rule23},-	{278, 1, &rule22},-	{279, 1, &rule23},-	{280, 1, &rule22},-	{281, 1, &rule23},-	{282, 1, &rule22},-	{283, 1, &rule23},-	{284, 1, &rule22},-	{285, 1, &rule23},-	{286, 1, &rule22},-	{287, 1, &rule23},-	{288, 1, &rule22},-	{289, 1, &rule23},-	{290, 1, &rule22},-	{291, 1, &rule23},-	{292, 1, &rule22},-	{293, 1, &rule23},-	{294, 1, &rule22},-	{295, 1, &rule23},-	{296, 1, &rule22},-	{297, 1, &rule23},-	{298, 1, &rule22},-	{299, 1, &rule23},-	{300, 1, &rule22},-	{301, 1, &rule23},-	{302, 1, &rule22},-	{303, 1, &rule23},-	{304, 1, &rule24},-	{305, 1, &rule25},-	{306, 1, &rule22},-	{307, 1, &rule23},-	{308, 1, &rule22},-	{309, 1, &rule23},-	{310, 1, &rule22},-	{311, 1, &rule23},-	{313, 1, &rule22},-	{314, 1, &rule23},-	{315, 1, &rule22},-	{316, 1, &rule23},-	{317, 1, &rule22},-	{318, 1, &rule23},-	{319, 1, &rule22},-	{320, 1, &rule23},-	{321, 1, &rule22},-	{322, 1, &rule23},-	{323, 1, &rule22},-	{324, 1, &rule23},-	{325, 1, &rule22},-	{326, 1, &rule23},-	{327, 1, &rule22},-	{328, 1, &rule23},-	{330, 1, &rule22},-	{331, 1, &rule23},-	{332, 1, &rule22},-	{333, 1, &rule23},-	{334, 1, &rule22},-	{335, 1, &rule23},-	{336, 1, &rule22},-	{337, 1, &rule23},-	{338, 1, &rule22},-	{339, 1, &rule23},-	{340, 1, &rule22},-	{341, 1, &rule23},-	{342, 1, &rule22},-	{343, 1, &rule23},-	{344, 1, &rule22},-	{345, 1, &rule23},-	{346, 1, &rule22},-	{347, 1, &rule23},-	{348, 1, &rule22},-	{349, 1, &rule23},-	{350, 1, &rule22},-	{351, 1, &rule23},-	{352, 1, &rule22},-	{353, 1, &rule23},-	{354, 1, &rule22},-	{355, 1, &rule23},-	{356, 1, &rule22},-	{357, 1, &rule23},-	{358, 1, &rule22},-	{359, 1, &rule23},-	{360, 1, &rule22},-	{361, 1, &rule23},-	{362, 1, &rule22},-	{363, 1, &rule23},-	{364, 1, &rule22},-	{365, 1, &rule23},-	{366, 1, &rule22},-	{367, 1, &rule23},-	{368, 1, &rule22},-	{369, 1, &rule23},-	{370, 1, &rule22},-	{371, 1, &rule23},-	{372, 1, &rule22},-	{373, 1, &rule23},-	{374, 1, &rule22},-	{375, 1, &rule23},-	{376, 1, &rule26},-	{377, 1, &rule22},-	{378, 1, &rule23},-	{379, 1, &rule22},-	{380, 1, &rule23},-	{381, 1, &rule22},-	{382, 1, &rule23},-	{383, 1, &rule27},-	{384, 1, &rule28},-	{385, 1, &rule29},-	{386, 1, &rule22},-	{387, 1, &rule23},-	{388, 1, &rule22},-	{389, 1, &rule23},-	{390, 1, &rule30},-	{391, 1, &rule22},-	{392, 1, &rule23},-	{393, 2, &rule31},-	{395, 1, &rule22},-	{396, 1, &rule23},-	{398, 1, &rule32},-	{399, 1, &rule33},-	{400, 1, &rule34},-	{401, 1, &rule22},-	{402, 1, &rule23},-	{403, 1, &rule31},-	{404, 1, &rule35},-	{405, 1, &rule36},-	{406, 1, &rule37},-	{407, 1, &rule38},-	{408, 1, &rule22},-	{409, 1, &rule23},-	{410, 1, &rule39},-	{412, 1, &rule37},-	{413, 1, &rule40},-	{414, 1, &rule41},-	{415, 1, &rule42},-	{416, 1, &rule22},-	{417, 1, &rule23},-	{418, 1, &rule22},-	{419, 1, &rule23},-	{420, 1, &rule22},-	{421, 1, &rule23},-	{422, 1, &rule43},-	{423, 1, &rule22},-	{424, 1, &rule23},-	{425, 1, &rule43},-	{428, 1, &rule22},-	{429, 1, &rule23},-	{430, 1, &rule43},-	{431, 1, &rule22},-	{432, 1, &rule23},-	{433, 2, &rule44},-	{435, 1, &rule22},-	{436, 1, &rule23},-	{437, 1, &rule22},-	{438, 1, &rule23},-	{439, 1, &rule45},-	{440, 1, &rule22},-	{441, 1, &rule23},-	{444, 1, &rule22},-	{445, 1, &rule23},-	{447, 1, &rule46},-	{452, 1, &rule47},-	{453, 1, &rule48},-	{454, 1, &rule49},-	{455, 1, &rule47},-	{456, 1, &rule48},-	{457, 1, &rule49},-	{458, 1, &rule47},-	{459, 1, &rule48},-	{460, 1, &rule49},-	{461, 1, &rule22},-	{462, 1, &rule23},-	{463, 1, &rule22},-	{464, 1, &rule23},-	{465, 1, &rule22},-	{466, 1, &rule23},-	{467, 1, &rule22},-	{468, 1, &rule23},-	{469, 1, &rule22},-	{470, 1, &rule23},-	{471, 1, &rule22},-	{472, 1, &rule23},-	{473, 1, &rule22},-	{474, 1, &rule23},-	{475, 1, &rule22},-	{476, 1, &rule23},-	{477, 1, &rule50},-	{478, 1, &rule22},-	{479, 1, &rule23},-	{480, 1, &rule22},-	{481, 1, &rule23},-	{482, 1, &rule22},-	{483, 1, &rule23},-	{484, 1, &rule22},-	{485, 1, &rule23},-	{486, 1, &rule22},-	{487, 1, &rule23},-	{488, 1, &rule22},-	{489, 1, &rule23},-	{490, 1, &rule22},-	{491, 1, &rule23},-	{492, 1, &rule22},-	{493, 1, &rule23},-	{494, 1, &rule22},-	{495, 1, &rule23},-	{497, 1, &rule47},-	{498, 1, &rule48},-	{499, 1, &rule49},-	{500, 1, &rule22},-	{501, 1, &rule23},-	{502, 1, &rule51},-	{503, 1, &rule52},-	{504, 1, &rule22},-	{505, 1, &rule23},-	{506, 1, &rule22},-	{507, 1, &rule23},-	{508, 1, &rule22},-	{509, 1, &rule23},-	{510, 1, &rule22},-	{511, 1, &rule23},-	{512, 1, &rule22},-	{513, 1, &rule23},-	{514, 1, &rule22},-	{515, 1, &rule23},-	{516, 1, &rule22},-	{517, 1, &rule23},-	{518, 1, &rule22},-	{519, 1, &rule23},-	{520, 1, &rule22},-	{521, 1, &rule23},-	{522, 1, &rule22},-	{523, 1, &rule23},-	{524, 1, &rule22},-	{525, 1, &rule23},-	{526, 1, &rule22},-	{527, 1, &rule23},-	{528, 1, &rule22},-	{529, 1, &rule23},-	{530, 1, &rule22},-	{531, 1, &rule23},-	{532, 1, &rule22},-	{533, 1, &rule23},-	{534, 1, &rule22},-	{535, 1, &rule23},-	{536, 1, &rule22},-	{537, 1, &rule23},-	{538, 1, &rule22},-	{539, 1, &rule23},-	{540, 1, &rule22},-	{541, 1, &rule23},-	{542, 1, &rule22},-	{543, 1, &rule23},-	{544, 1, &rule53},-	{546, 1, &rule22},-	{547, 1, &rule23},-	{548, 1, &rule22},-	{549, 1, &rule23},-	{550, 1, &rule22},-	{551, 1, &rule23},-	{552, 1, &rule22},-	{553, 1, &rule23},-	{554, 1, &rule22},-	{555, 1, &rule23},-	{556, 1, &rule22},-	{557, 1, &rule23},-	{558, 1, &rule22},-	{559, 1, &rule23},-	{560, 1, &rule22},-	{561, 1, &rule23},-	{562, 1, &rule22},-	{563, 1, &rule23},-	{570, 1, &rule54},-	{571, 1, &rule22},-	{572, 1, &rule23},-	{573, 1, &rule55},-	{574, 1, &rule56},-	{575, 2, &rule57},-	{577, 1, &rule22},-	{578, 1, &rule23},-	{579, 1, &rule58},-	{580, 1, &rule59},-	{581, 1, &rule60},-	{582, 1, &rule22},-	{583, 1, &rule23},-	{584, 1, &rule22},-	{585, 1, &rule23},-	{586, 1, &rule22},-	{587, 1, &rule23},-	{588, 1, &rule22},-	{589, 1, &rule23},-	{590, 1, &rule22},-	{591, 1, &rule23},-	{592, 1, &rule61},-	{593, 1, &rule62},-	{594, 1, &rule63},-	{595, 1, &rule64},-	{596, 1, &rule65},-	{598, 2, &rule66},-	{601, 1, &rule67},-	{603, 1, &rule68},-	{604, 1, &rule69},-	{608, 1, &rule66},-	{609, 1, &rule70},-	{611, 1, &rule71},-	{613, 1, &rule72},-	{614, 1, &rule73},-	{616, 1, &rule74},-	{617, 1, &rule75},-	{619, 1, &rule76},-	{620, 1, &rule77},-	{623, 1, &rule75},-	{625, 1, &rule78},-	{626, 1, &rule79},-	{629, 1, &rule80},-	{637, 1, &rule81},-	{640, 1, &rule82},-	{643, 1, &rule82},-	{647, 1, &rule83},-	{648, 1, &rule82},-	{649, 1, &rule84},-	{650, 2, &rule85},-	{652, 1, &rule86},-	{658, 1, &rule87},-	{670, 1, &rule88},-	{837, 1, &rule91},-	{880, 1, &rule22},-	{881, 1, &rule23},-	{882, 1, &rule22},-	{883, 1, &rule23},-	{886, 1, &rule22},-	{887, 1, &rule23},-	{891, 3, &rule41},-	{895, 1, &rule92},-	{902, 1, &rule93},-	{904, 3, &rule94},-	{908, 1, &rule95},-	{910, 2, &rule96},-	{913, 17, &rule9},-	{931, 9, &rule9},-	{940, 1, &rule97},-	{941, 3, &rule98},-	{945, 17, &rule12},-	{962, 1, &rule99},-	{963, 9, &rule12},-	{972, 1, &rule100},-	{973, 2, &rule101},-	{975, 1, &rule102},-	{976, 1, &rule103},-	{977, 1, &rule104},-	{981, 1, &rule106},-	{982, 1, &rule107},-	{983, 1, &rule108},-	{984, 1, &rule22},-	{985, 1, &rule23},-	{986, 1, &rule22},-	{987, 1, &rule23},-	{988, 1, &rule22},-	{989, 1, &rule23},-	{990, 1, &rule22},-	{991, 1, &rule23},-	{992, 1, &rule22},-	{993, 1, &rule23},-	{994, 1, &rule22},-	{995, 1, &rule23},-	{996, 1, &rule22},-	{997, 1, &rule23},-	{998, 1, &rule22},-	{999, 1, &rule23},-	{1000, 1, &rule22},-	{1001, 1, &rule23},-	{1002, 1, &rule22},-	{1003, 1, &rule23},-	{1004, 1, &rule22},-	{1005, 1, &rule23},-	{1006, 1, &rule22},-	{1007, 1, &rule23},-	{1008, 1, &rule109},-	{1009, 1, &rule110},-	{1010, 1, &rule111},-	{1011, 1, &rule112},-	{1012, 1, &rule113},-	{1013, 1, &rule114},-	{1015, 1, &rule22},-	{1016, 1, &rule23},-	{1017, 1, &rule115},-	{1018, 1, &rule22},-	{1019, 1, &rule23},-	{1021, 3, &rule53},-	{1024, 16, &rule116},-	{1040, 32, &rule9},-	{1072, 32, &rule12},-	{1104, 16, &rule110},-	{1120, 1, &rule22},-	{1121, 1, &rule23},-	{1122, 1, &rule22},-	{1123, 1, &rule23},-	{1124, 1, &rule22},-	{1125, 1, &rule23},-	{1126, 1, &rule22},-	{1127, 1, &rule23},-	{1128, 1, &rule22},-	{1129, 1, &rule23},-	{1130, 1, &rule22},-	{1131, 1, &rule23},-	{1132, 1, &rule22},-	{1133, 1, &rule23},-	{1134, 1, &rule22},-	{1135, 1, &rule23},-	{1136, 1, &rule22},-	{1137, 1, &rule23},-	{1138, 1, &rule22},-	{1139, 1, &rule23},-	{1140, 1, &rule22},-	{1141, 1, &rule23},-	{1142, 1, &rule22},-	{1143, 1, &rule23},-	{1144, 1, &rule22},-	{1145, 1, &rule23},-	{1146, 1, &rule22},-	{1147, 1, &rule23},-	{1148, 1, &rule22},-	{1149, 1, &rule23},-	{1150, 1, &rule22},-	{1151, 1, &rule23},-	{1152, 1, &rule22},-	{1153, 1, &rule23},-	{1162, 1, &rule22},-	{1163, 1, &rule23},-	{1164, 1, &rule22},-	{1165, 1, &rule23},-	{1166, 1, &rule22},-	{1167, 1, &rule23},-	{1168, 1, &rule22},-	{1169, 1, &rule23},-	{1170, 1, &rule22},-	{1171, 1, &rule23},-	{1172, 1, &rule22},-	{1173, 1, &rule23},-	{1174, 1, &rule22},-	{1175, 1, &rule23},-	{1176, 1, &rule22},-	{1177, 1, &rule23},-	{1178, 1, &rule22},-	{1179, 1, &rule23},-	{1180, 1, &rule22},-	{1181, 1, &rule23},-	{1182, 1, &rule22},-	{1183, 1, &rule23},-	{1184, 1, &rule22},-	{1185, 1, &rule23},-	{1186, 1, &rule22},-	{1187, 1, &rule23},-	{1188, 1, &rule22},-	{1189, 1, &rule23},-	{1190, 1, &rule22},-	{1191, 1, &rule23},-	{1192, 1, &rule22},-	{1193, 1, &rule23},-	{1194, 1, &rule22},-	{1195, 1, &rule23},-	{1196, 1, &rule22},-	{1197, 1, &rule23},-	{1198, 1, &rule22},-	{1199, 1, &rule23},-	{1200, 1, &rule22},-	{1201, 1, &rule23},-	{1202, 1, &rule22},-	{1203, 1, &rule23},-	{1204, 1, &rule22},-	{1205, 1, &rule23},-	{1206, 1, &rule22},-	{1207, 1, &rule23},-	{1208, 1, &rule22},-	{1209, 1, &rule23},-	{1210, 1, &rule22},-	{1211, 1, &rule23},-	{1212, 1, &rule22},-	{1213, 1, &rule23},-	{1214, 1, &rule22},-	{1215, 1, &rule23},-	{1216, 1, &rule118},-	{1217, 1, &rule22},-	{1218, 1, &rule23},-	{1219, 1, &rule22},-	{1220, 1, &rule23},-	{1221, 1, &rule22},-	{1222, 1, &rule23},-	{1223, 1, &rule22},-	{1224, 1, &rule23},-	{1225, 1, &rule22},-	{1226, 1, &rule23},-	{1227, 1, &rule22},-	{1228, 1, &rule23},-	{1229, 1, &rule22},-	{1230, 1, &rule23},-	{1231, 1, &rule119},-	{1232, 1, &rule22},-	{1233, 1, &rule23},-	{1234, 1, &rule22},-	{1235, 1, &rule23},-	{1236, 1, &rule22},-	{1237, 1, &rule23},-	{1238, 1, &rule22},-	{1239, 1, &rule23},-	{1240, 1, &rule22},-	{1241, 1, &rule23},-	{1242, 1, &rule22},-	{1243, 1, &rule23},-	{1244, 1, &rule22},-	{1245, 1, &rule23},-	{1246, 1, &rule22},-	{1247, 1, &rule23},-	{1248, 1, &rule22},-	{1249, 1, &rule23},-	{1250, 1, &rule22},-	{1251, 1, &rule23},-	{1252, 1, &rule22},-	{1253, 1, &rule23},-	{1254, 1, &rule22},-	{1255, 1, &rule23},-	{1256, 1, &rule22},-	{1257, 1, &rule23},-	{1258, 1, &rule22},-	{1259, 1, &rule23},-	{1260, 1, &rule22},-	{1261, 1, &rule23},-	{1262, 1, &rule22},-	{1263, 1, &rule23},-	{1264, 1, &rule22},-	{1265, 1, &rule23},-	{1266, 1, &rule22},-	{1267, 1, &rule23},-	{1268, 1, &rule22},-	{1269, 1, &rule23},-	{1270, 1, &rule22},-	{1271, 1, &rule23},-	{1272, 1, &rule22},-	{1273, 1, &rule23},-	{1274, 1, &rule22},-	{1275, 1, &rule23},-	{1276, 1, &rule22},-	{1277, 1, &rule23},-	{1278, 1, &rule22},-	{1279, 1, &rule23},-	{1280, 1, &rule22},-	{1281, 1, &rule23},-	{1282, 1, &rule22},-	{1283, 1, &rule23},-	{1284, 1, &rule22},-	{1285, 1, &rule23},-	{1286, 1, &rule22},-	{1287, 1, &rule23},-	{1288, 1, &rule22},-	{1289, 1, &rule23},-	{1290, 1, &rule22},-	{1291, 1, &rule23},-	{1292, 1, &rule22},-	{1293, 1, &rule23},-	{1294, 1, &rule22},-	{1295, 1, &rule23},-	{1296, 1, &rule22},-	{1297, 1, &rule23},-	{1298, 1, &rule22},-	{1299, 1, &rule23},-	{1300, 1, &rule22},-	{1301, 1, &rule23},-	{1302, 1, &rule22},-	{1303, 1, &rule23},-	{1304, 1, &rule22},-	{1305, 1, &rule23},-	{1306, 1, &rule22},-	{1307, 1, &rule23},-	{1308, 1, &rule22},-	{1309, 1, &rule23},-	{1310, 1, &rule22},-	{1311, 1, &rule23},-	{1312, 1, &rule22},-	{1313, 1, &rule23},-	{1314, 1, &rule22},-	{1315, 1, &rule23},-	{1316, 1, &rule22},-	{1317, 1, &rule23},-	{1318, 1, &rule22},-	{1319, 1, &rule23},-	{1320, 1, &rule22},-	{1321, 1, &rule23},-	{1322, 1, &rule22},-	{1323, 1, &rule23},-	{1324, 1, &rule22},-	{1325, 1, &rule23},-	{1326, 1, &rule22},-	{1327, 1, &rule23},-	{1329, 38, &rule120},-	{1377, 38, &rule121},-	{4256, 38, &rule123},-	{4295, 1, &rule123},-	{4301, 1, &rule123},-	{7545, 1, &rule125},-	{7549, 1, &rule126},-	{7680, 1, &rule22},-	{7681, 1, &rule23},-	{7682, 1, &rule22},-	{7683, 1, &rule23},-	{7684, 1, &rule22},-	{7685, 1, &rule23},-	{7686, 1, &rule22},-	{7687, 1, &rule23},-	{7688, 1, &rule22},-	{7689, 1, &rule23},-	{7690, 1, &rule22},-	{7691, 1, &rule23},-	{7692, 1, &rule22},-	{7693, 1, &rule23},-	{7694, 1, &rule22},-	{7695, 1, &rule23},-	{7696, 1, &rule22},-	{7697, 1, &rule23},-	{7698, 1, &rule22},-	{7699, 1, &rule23},-	{7700, 1, &rule22},-	{7701, 1, &rule23},-	{7702, 1, &rule22},-	{7703, 1, &rule23},-	{7704, 1, &rule22},-	{7705, 1, &rule23},-	{7706, 1, &rule22},-	{7707, 1, &rule23},-	{7708, 1, &rule22},-	{7709, 1, &rule23},-	{7710, 1, &rule22},-	{7711, 1, &rule23},-	{7712, 1, &rule22},-	{7713, 1, &rule23},-	{7714, 1, &rule22},-	{7715, 1, &rule23},-	{7716, 1, &rule22},-	{7717, 1, &rule23},-	{7718, 1, &rule22},-	{7719, 1, &rule23},-	{7720, 1, &rule22},-	{7721, 1, &rule23},-	{7722, 1, &rule22},-	{7723, 1, &rule23},-	{7724, 1, &rule22},-	{7725, 1, &rule23},-	{7726, 1, &rule22},-	{7727, 1, &rule23},-	{7728, 1, &rule22},-	{7729, 1, &rule23},-	{7730, 1, &rule22},-	{7731, 1, &rule23},-	{7732, 1, &rule22},-	{7733, 1, &rule23},-	{7734, 1, &rule22},-	{7735, 1, &rule23},-	{7736, 1, &rule22},-	{7737, 1, &rule23},-	{7738, 1, &rule22},-	{7739, 1, &rule23},-	{7740, 1, &rule22},-	{7741, 1, &rule23},-	{7742, 1, &rule22},-	{7743, 1, &rule23},-	{7744, 1, &rule22},-	{7745, 1, &rule23},-	{7746, 1, &rule22},-	{7747, 1, &rule23},-	{7748, 1, &rule22},-	{7749, 1, &rule23},-	{7750, 1, &rule22},-	{7751, 1, &rule23},-	{7752, 1, &rule22},-	{7753, 1, &rule23},-	{7754, 1, &rule22},-	{7755, 1, &rule23},-	{7756, 1, &rule22},-	{7757, 1, &rule23},-	{7758, 1, &rule22},-	{7759, 1, &rule23},-	{7760, 1, &rule22},-	{7761, 1, &rule23},-	{7762, 1, &rule22},-	{7763, 1, &rule23},-	{7764, 1, &rule22},-	{7765, 1, &rule23},-	{7766, 1, &rule22},-	{7767, 1, &rule23},-	{7768, 1, &rule22},-	{7769, 1, &rule23},-	{7770, 1, &rule22},-	{7771, 1, &rule23},-	{7772, 1, &rule22},-	{7773, 1, &rule23},-	{7774, 1, &rule22},-	{7775, 1, &rule23},-	{7776, 1, &rule22},-	{7777, 1, &rule23},-	{7778, 1, &rule22},-	{7779, 1, &rule23},-	{7780, 1, &rule22},-	{7781, 1, &rule23},-	{7782, 1, &rule22},-	{7783, 1, &rule23},-	{7784, 1, &rule22},-	{7785, 1, &rule23},-	{7786, 1, &rule22},-	{7787, 1, &rule23},-	{7788, 1, &rule22},-	{7789, 1, &rule23},-	{7790, 1, &rule22},-	{7791, 1, &rule23},-	{7792, 1, &rule22},-	{7793, 1, &rule23},-	{7794, 1, &rule22},-	{7795, 1, &rule23},-	{7796, 1, &rule22},-	{7797, 1, &rule23},-	{7798, 1, &rule22},-	{7799, 1, &rule23},-	{7800, 1, &rule22},-	{7801, 1, &rule23},-	{7802, 1, &rule22},-	{7803, 1, &rule23},-	{7804, 1, &rule22},-	{7805, 1, &rule23},-	{7806, 1, &rule22},-	{7807, 1, &rule23},-	{7808, 1, &rule22},-	{7809, 1, &rule23},-	{7810, 1, &rule22},-	{7811, 1, &rule23},-	{7812, 1, &rule22},-	{7813, 1, &rule23},-	{7814, 1, &rule22},-	{7815, 1, &rule23},-	{7816, 1, &rule22},-	{7817, 1, &rule23},-	{7818, 1, &rule22},-	{7819, 1, &rule23},-	{7820, 1, &rule22},-	{7821, 1, &rule23},-	{7822, 1, &rule22},-	{7823, 1, &rule23},-	{7824, 1, &rule22},-	{7825, 1, &rule23},-	{7826, 1, &rule22},-	{7827, 1, &rule23},-	{7828, 1, &rule22},-	{7829, 1, &rule23},-	{7835, 1, &rule127},-	{7838, 1, &rule128},-	{7840, 1, &rule22},-	{7841, 1, &rule23},-	{7842, 1, &rule22},-	{7843, 1, &rule23},-	{7844, 1, &rule22},-	{7845, 1, &rule23},-	{7846, 1, &rule22},-	{7847, 1, &rule23},-	{7848, 1, &rule22},-	{7849, 1, &rule23},-	{7850, 1, &rule22},-	{7851, 1, &rule23},-	{7852, 1, &rule22},-	{7853, 1, &rule23},-	{7854, 1, &rule22},-	{7855, 1, &rule23},-	{7856, 1, &rule22},-	{7857, 1, &rule23},-	{7858, 1, &rule22},-	{7859, 1, &rule23},-	{7860, 1, &rule22},-	{7861, 1, &rule23},-	{7862, 1, &rule22},-	{7863, 1, &rule23},-	{7864, 1, &rule22},-	{7865, 1, &rule23},-	{7866, 1, &rule22},-	{7867, 1, &rule23},-	{7868, 1, &rule22},-	{7869, 1, &rule23},-	{7870, 1, &rule22},-	{7871, 1, &rule23},-	{7872, 1, &rule22},-	{7873, 1, &rule23},-	{7874, 1, &rule22},-	{7875, 1, &rule23},-	{7876, 1, &rule22},-	{7877, 1, &rule23},-	{7878, 1, &rule22},-	{7879, 1, &rule23},-	{7880, 1, &rule22},-	{7881, 1, &rule23},-	{7882, 1, &rule22},-	{7883, 1, &rule23},-	{7884, 1, &rule22},-	{7885, 1, &rule23},-	{7886, 1, &rule22},-	{7887, 1, &rule23},-	{7888, 1, &rule22},-	{7889, 1, &rule23},-	{7890, 1, &rule22},-	{7891, 1, &rule23},-	{7892, 1, &rule22},-	{7893, 1, &rule23},-	{7894, 1, &rule22},-	{7895, 1, &rule23},-	{7896, 1, &rule22},-	{7897, 1, &rule23},-	{7898, 1, &rule22},-	{7899, 1, &rule23},-	{7900, 1, &rule22},-	{7901, 1, &rule23},-	{7902, 1, &rule22},-	{7903, 1, &rule23},-	{7904, 1, &rule22},-	{7905, 1, &rule23},-	{7906, 1, &rule22},-	{7907, 1, &rule23},-	{7908, 1, &rule22},-	{7909, 1, &rule23},-	{7910, 1, &rule22},-	{7911, 1, &rule23},-	{7912, 1, &rule22},-	{7913, 1, &rule23},-	{7914, 1, &rule22},-	{7915, 1, &rule23},-	{7916, 1, &rule22},-	{7917, 1, &rule23},-	{7918, 1, &rule22},-	{7919, 1, &rule23},-	{7920, 1, &rule22},-	{7921, 1, &rule23},-	{7922, 1, &rule22},-	{7923, 1, &rule23},-	{7924, 1, &rule22},-	{7925, 1, &rule23},-	{7926, 1, &rule22},-	{7927, 1, &rule23},-	{7928, 1, &rule22},-	{7929, 1, &rule23},-	{7930, 1, &rule22},-	{7931, 1, &rule23},-	{7932, 1, &rule22},-	{7933, 1, &rule23},-	{7934, 1, &rule22},-	{7935, 1, &rule23},-	{7936, 8, &rule129},-	{7944, 8, &rule130},-	{7952, 6, &rule129},-	{7960, 6, &rule130},-	{7968, 8, &rule129},-	{7976, 8, &rule130},-	{7984, 8, &rule129},-	{7992, 8, &rule130},-	{8000, 6, &rule129},-	{8008, 6, &rule130},-	{8017, 1, &rule129},-	{8019, 1, &rule129},-	{8021, 1, &rule129},-	{8023, 1, &rule129},-	{8025, 1, &rule130},-	{8027, 1, &rule130},-	{8029, 1, &rule130},-	{8031, 1, &rule130},-	{8032, 8, &rule129},-	{8040, 8, &rule130},-	{8048, 2, &rule131},-	{8050, 4, &rule132},-	{8054, 2, &rule133},-	{8056, 2, &rule134},-	{8058, 2, &rule135},-	{8060, 2, &rule136},-	{8064, 8, &rule129},-	{8072, 8, &rule137},-	{8080, 8, &rule129},-	{8088, 8, &rule137},-	{8096, 8, &rule129},-	{8104, 8, &rule137},-	{8112, 2, &rule129},-	{8115, 1, &rule138},-	{8120, 2, &rule130},-	{8122, 2, &rule139},-	{8124, 1, &rule140},-	{8126, 1, &rule141},-	{8131, 1, &rule138},-	{8136, 4, &rule142},-	{8140, 1, &rule140},-	{8144, 2, &rule129},-	{8152, 2, &rule130},-	{8154, 2, &rule143},-	{8160, 2, &rule129},-	{8165, 1, &rule111},-	{8168, 2, &rule130},-	{8170, 2, &rule144},-	{8172, 1, &rule115},-	{8179, 1, &rule138},-	{8184, 2, &rule145},-	{8186, 2, &rule146},-	{8188, 1, &rule140},-	{8486, 1, &rule149},-	{8490, 1, &rule150},-	{8491, 1, &rule151},-	{8498, 1, &rule152},-	{8526, 1, &rule153},-	{8544, 16, &rule154},-	{8560, 16, &rule155},-	{8579, 1, &rule22},-	{8580, 1, &rule23},-	{9398, 26, &rule156},-	{9424, 26, &rule157},-	{11264, 47, &rule120},-	{11312, 47, &rule121},-	{11360, 1, &rule22},-	{11361, 1, &rule23},-	{11362, 1, &rule158},-	{11363, 1, &rule159},-	{11364, 1, &rule160},-	{11365, 1, &rule161},-	{11366, 1, &rule162},-	{11367, 1, &rule22},-	{11368, 1, &rule23},-	{11369, 1, &rule22},-	{11370, 1, &rule23},-	{11371, 1, &rule22},-	{11372, 1, &rule23},-	{11373, 1, &rule163},-	{11374, 1, &rule164},-	{11375, 1, &rule165},-	{11376, 1, &rule166},-	{11378, 1, &rule22},-	{11379, 1, &rule23},-	{11381, 1, &rule22},-	{11382, 1, &rule23},-	{11390, 2, &rule167},-	{11392, 1, &rule22},-	{11393, 1, &rule23},-	{11394, 1, &rule22},-	{11395, 1, &rule23},-	{11396, 1, &rule22},-	{11397, 1, &rule23},-	{11398, 1, &rule22},-	{11399, 1, &rule23},-	{11400, 1, &rule22},-	{11401, 1, &rule23},-	{11402, 1, &rule22},-	{11403, 1, &rule23},-	{11404, 1, &rule22},-	{11405, 1, &rule23},-	{11406, 1, &rule22},-	{11407, 1, &rule23},-	{11408, 1, &rule22},-	{11409, 1, &rule23},-	{11410, 1, &rule22},-	{11411, 1, &rule23},-	{11412, 1, &rule22},-	{11413, 1, &rule23},-	{11414, 1, &rule22},-	{11415, 1, &rule23},-	{11416, 1, &rule22},-	{11417, 1, &rule23},-	{11418, 1, &rule22},-	{11419, 1, &rule23},-	{11420, 1, &rule22},-	{11421, 1, &rule23},-	{11422, 1, &rule22},-	{11423, 1, &rule23},-	{11424, 1, &rule22},-	{11425, 1, &rule23},-	{11426, 1, &rule22},-	{11427, 1, &rule23},-	{11428, 1, &rule22},-	{11429, 1, &rule23},-	{11430, 1, &rule22},-	{11431, 1, &rule23},-	{11432, 1, &rule22},-	{11433, 1, &rule23},-	{11434, 1, &rule22},-	{11435, 1, &rule23},-	{11436, 1, &rule22},-	{11437, 1, &rule23},-	{11438, 1, &rule22},-	{11439, 1, &rule23},-	{11440, 1, &rule22},-	{11441, 1, &rule23},-	{11442, 1, &rule22},-	{11443, 1, &rule23},-	{11444, 1, &rule22},-	{11445, 1, &rule23},-	{11446, 1, &rule22},-	{11447, 1, &rule23},-	{11448, 1, &rule22},-	{11449, 1, &rule23},-	{11450, 1, &rule22},-	{11451, 1, &rule23},-	{11452, 1, &rule22},-	{11453, 1, &rule23},-	{11454, 1, &rule22},-	{11455, 1, &rule23},-	{11456, 1, &rule22},-	{11457, 1, &rule23},-	{11458, 1, &rule22},-	{11459, 1, &rule23},-	{11460, 1, &rule22},-	{11461, 1, &rule23},-	{11462, 1, &rule22},-	{11463, 1, &rule23},-	{11464, 1, &rule22},-	{11465, 1, &rule23},-	{11466, 1, &rule22},-	{11467, 1, &rule23},-	{11468, 1, &rule22},-	{11469, 1, &rule23},-	{11470, 1, &rule22},-	{11471, 1, &rule23},-	{11472, 1, &rule22},-	{11473, 1, &rule23},-	{11474, 1, &rule22},-	{11475, 1, &rule23},-	{11476, 1, &rule22},-	{11477, 1, &rule23},-	{11478, 1, &rule22},-	{11479, 1, &rule23},-	{11480, 1, &rule22},-	{11481, 1, &rule23},-	{11482, 1, &rule22},-	{11483, 1, &rule23},-	{11484, 1, &rule22},-	{11485, 1, &rule23},-	{11486, 1, &rule22},-	{11487, 1, &rule23},-	{11488, 1, &rule22},-	{11489, 1, &rule23},-	{11490, 1, &rule22},-	{11491, 1, &rule23},-	{11499, 1, &rule22},-	{11500, 1, &rule23},-	{11501, 1, &rule22},-	{11502, 1, &rule23},-	{11506, 1, &rule22},-	{11507, 1, &rule23},-	{11520, 38, &rule168},-	{11559, 1, &rule168},-	{11565, 1, &rule168},-	{42560, 1, &rule22},-	{42561, 1, &rule23},-	{42562, 1, &rule22},-	{42563, 1, &rule23},-	{42564, 1, &rule22},-	{42565, 1, &rule23},-	{42566, 1, &rule22},-	{42567, 1, &rule23},-	{42568, 1, &rule22},-	{42569, 1, &rule23},-	{42570, 1, &rule22},-	{42571, 1, &rule23},-	{42572, 1, &rule22},-	{42573, 1, &rule23},-	{42574, 1, &rule22},-	{42575, 1, &rule23},-	{42576, 1, &rule22},-	{42577, 1, &rule23},-	{42578, 1, &rule22},-	{42579, 1, &rule23},-	{42580, 1, &rule22},-	{42581, 1, &rule23},-	{42582, 1, &rule22},-	{42583, 1, &rule23},-	{42584, 1, &rule22},-	{42585, 1, &rule23},-	{42586, 1, &rule22},-	{42587, 1, &rule23},-	{42588, 1, &rule22},-	{42589, 1, &rule23},-	{42590, 1, &rule22},-	{42591, 1, &rule23},-	{42592, 1, &rule22},-	{42593, 1, &rule23},-	{42594, 1, &rule22},-	{42595, 1, &rule23},-	{42596, 1, &rule22},-	{42597, 1, &rule23},-	{42598, 1, &rule22},-	{42599, 1, &rule23},-	{42600, 1, &rule22},-	{42601, 1, &rule23},-	{42602, 1, &rule22},-	{42603, 1, &rule23},-	{42604, 1, &rule22},-	{42605, 1, &rule23},-	{42624, 1, &rule22},-	{42625, 1, &rule23},-	{42626, 1, &rule22},-	{42627, 1, &rule23},-	{42628, 1, &rule22},-	{42629, 1, &rule23},-	{42630, 1, &rule22},-	{42631, 1, &rule23},-	{42632, 1, &rule22},-	{42633, 1, &rule23},-	{42634, 1, &rule22},-	{42635, 1, &rule23},-	{42636, 1, &rule22},-	{42637, 1, &rule23},-	{42638, 1, &rule22},-	{42639, 1, &rule23},-	{42640, 1, &rule22},-	{42641, 1, &rule23},-	{42642, 1, &rule22},-	{42643, 1, &rule23},-	{42644, 1, &rule22},-	{42645, 1, &rule23},-	{42646, 1, &rule22},-	{42647, 1, &rule23},-	{42648, 1, &rule22},-	{42649, 1, &rule23},-	{42650, 1, &rule22},-	{42651, 1, &rule23},-	{42786, 1, &rule22},-	{42787, 1, &rule23},-	{42788, 1, &rule22},-	{42789, 1, &rule23},-	{42790, 1, &rule22},-	{42791, 1, &rule23},-	{42792, 1, &rule22},-	{42793, 1, &rule23},-	{42794, 1, &rule22},-	{42795, 1, &rule23},-	{42796, 1, &rule22},-	{42797, 1, &rule23},-	{42798, 1, &rule22},-	{42799, 1, &rule23},-	{42802, 1, &rule22},-	{42803, 1, &rule23},-	{42804, 1, &rule22},-	{42805, 1, &rule23},-	{42806, 1, &rule22},-	{42807, 1, &rule23},-	{42808, 1, &rule22},-	{42809, 1, &rule23},-	{42810, 1, &rule22},-	{42811, 1, &rule23},-	{42812, 1, &rule22},-	{42813, 1, &rule23},-	{42814, 1, &rule22},-	{42815, 1, &rule23},-	{42816, 1, &rule22},-	{42817, 1, &rule23},-	{42818, 1, &rule22},-	{42819, 1, &rule23},-	{42820, 1, &rule22},-	{42821, 1, &rule23},-	{42822, 1, &rule22},-	{42823, 1, &rule23},-	{42824, 1, &rule22},-	{42825, 1, &rule23},-	{42826, 1, &rule22},-	{42827, 1, &rule23},-	{42828, 1, &rule22},-	{42829, 1, &rule23},-	{42830, 1, &rule22},-	{42831, 1, &rule23},-	{42832, 1, &rule22},-	{42833, 1, &rule23},-	{42834, 1, &rule22},-	{42835, 1, &rule23},-	{42836, 1, &rule22},-	{42837, 1, &rule23},-	{42838, 1, &rule22},-	{42839, 1, &rule23},-	{42840, 1, &rule22},-	{42841, 1, &rule23},-	{42842, 1, &rule22},-	{42843, 1, &rule23},-	{42844, 1, &rule22},-	{42845, 1, &rule23},-	{42846, 1, &rule22},-	{42847, 1, &rule23},-	{42848, 1, &rule22},-	{42849, 1, &rule23},-	{42850, 1, &rule22},-	{42851, 1, &rule23},-	{42852, 1, &rule22},-	{42853, 1, &rule23},-	{42854, 1, &rule22},-	{42855, 1, &rule23},-	{42856, 1, &rule22},-	{42857, 1, &rule23},-	{42858, 1, &rule22},-	{42859, 1, &rule23},-	{42860, 1, &rule22},-	{42861, 1, &rule23},-	{42862, 1, &rule22},-	{42863, 1, &rule23},-	{42873, 1, &rule22},-	{42874, 1, &rule23},-	{42875, 1, &rule22},-	{42876, 1, &rule23},-	{42877, 1, &rule169},-	{42878, 1, &rule22},-	{42879, 1, &rule23},-	{42880, 1, &rule22},-	{42881, 1, &rule23},-	{42882, 1, &rule22},-	{42883, 1, &rule23},-	{42884, 1, &rule22},-	{42885, 1, &rule23},-	{42886, 1, &rule22},-	{42887, 1, &rule23},-	{42891, 1, &rule22},-	{42892, 1, &rule23},-	{42893, 1, &rule170},-	{42896, 1, &rule22},-	{42897, 1, &rule23},-	{42898, 1, &rule22},-	{42899, 1, &rule23},-	{42902, 1, &rule22},-	{42903, 1, &rule23},-	{42904, 1, &rule22},-	{42905, 1, &rule23},-	{42906, 1, &rule22},-	{42907, 1, &rule23},-	{42908, 1, &rule22},-	{42909, 1, &rule23},-	{42910, 1, &rule22},-	{42911, 1, &rule23},-	{42912, 1, &rule22},-	{42913, 1, &rule23},-	{42914, 1, &rule22},-	{42915, 1, &rule23},-	{42916, 1, &rule22},-	{42917, 1, &rule23},-	{42918, 1, &rule22},-	{42919, 1, &rule23},-	{42920, 1, &rule22},-	{42921, 1, &rule23},-	{42922, 1, &rule171},-	{42923, 1, &rule172},-	{42924, 1, &rule173},-	{42925, 1, &rule174},-	{42928, 1, &rule175},-	{42929, 1, &rule176},-	{65313, 26, &rule9},-	{65345, 26, &rule12},-	{66560, 40, &rule179},-	{66600, 40, &rule180},-	{71840, 32, &rule9},-	{71872, 32, &rule12}-};-static const struct _charblock_ spacechars[]={-	{32, 1, &rule1},-	{160, 1, &rule1},-	{5760, 1, &rule1},-	{8192, 11, &rule1},-	{8239, 1, &rule1},-	{8287, 1, &rule1},-	{12288, 1, &rule1}-};--/*-	Obtain the reference to character rule by doing-	binary search over the specified array of blocks.-	To make checkattr shorter, the address of-	nullrule is returned if the search fails:-	this rule defines no category and no conversion-	distances. The compare function returns 0 when-	key->start is within the block. Otherwise-	result of comparison of key->start and start of the-	current block is returned as usual.-*/--static const struct _convrule_ nullrule={0,NUMCAT_CN,0,0,0,0};--static int blkcmp(const void *vk,const void *vb)-{-	const struct _charblock_ *key,*cur;-	key=vk;-	cur=vb;-	if((key->start>=cur->start)&&(key->start<(cur->start+cur->length)))-	{-		return 0;-	}-	if(key->start>cur->start) return 1;-	return -1;-}--static const struct _convrule_ *getrule(-	const struct _charblock_ *blocks,-	int numblocks,-	int unichar)-{-	struct _charblock_ key={unichar,1,(void *)0};-	struct _charblock_ *cb=bsearch(&key,blocks,numblocks,sizeof(key),blkcmp);-	if(cb==(void *)0) return &nullrule;-	return cb->rule;-}-	---/*-	Check whether a character (internal code) has certain attributes.-	Attributes (category flags) may be ORed. The function ANDs-	character category flags and the mask and returns the result.-	If the character belongs to one of the categories requested,-	the result will be nonzero.-*/--inline static int checkattr(int c,unsigned int catmask)-{-	return (catmask & (getrule(allchars,(c<256)?NUM_LAT1BLOCKS:NUM_BLOCKS,c)->category));-}--inline static int checkattr_s(int c,unsigned int catmask)-{-        return (catmask & (getrule(spacechars,NUM_SPACEBLOCKS,c)->category));-}--/*-	Define predicate functions for some combinations of categories.-*/--#define unipred(p,m) \-HsInt p(HsInt c) \-{ \-	return checkattr(c,m); \-}--#define unipred_s(p,m) \-HsInt p(HsInt c) \-{ \-        return checkattr_s(c,m); \-}--/*-	Make these rules as close to Hugs as possible.-*/--unipred(u_iswcntrl,GENCAT_CC)-unipred(u_iswprint, (GENCAT_MC | GENCAT_NO | GENCAT_SK | GENCAT_ME | GENCAT_ND |   GENCAT_PO | GENCAT_LT | GENCAT_PC | GENCAT_SM | GENCAT_ZS |   GENCAT_LU | GENCAT_PD | GENCAT_SO | GENCAT_PE | GENCAT_PF |   GENCAT_PS | GENCAT_SC | GENCAT_LL | GENCAT_LM | GENCAT_PI |   GENCAT_NL | GENCAT_MN | GENCAT_LO))-unipred_s(u_iswspace,GENCAT_ZS)-unipred(u_iswupper,(GENCAT_LU|GENCAT_LT))-unipred(u_iswlower,GENCAT_LL)-unipred(u_iswalpha,(GENCAT_LL|GENCAT_LU|GENCAT_LT|GENCAT_LM|GENCAT_LO))-unipred(u_iswdigit,GENCAT_ND)--unipred(u_iswalnum,(GENCAT_LT|GENCAT_LU|GENCAT_LL|GENCAT_LM|GENCAT_LO|-		    GENCAT_MC|GENCAT_ME|GENCAT_MN|-		    GENCAT_NO|GENCAT_ND|GENCAT_NL))--#define caseconv(p,to) \-HsInt p(HsInt c) \-{ \-	const struct _convrule_ *rule=getrule(convchars,NUM_CONVBLOCKS,c);\-	if(rule==&nullrule) return c;\-	return c+rule->to;\-}--caseconv(u_towupper,updist)-caseconv(u_towlower,lowdist)-caseconv(u_towtitle,titledist)--HsInt u_gencat(HsInt c)-{-	return getrule(allchars,NUM_BLOCKS,c)->catnumber;-}-
− cbits/Win32Utils.c
@@ -1,151 +0,0 @@-/* -----------------------------------------------------------------------------   (c) The University of Glasgow 2006-   -   Useful Win32 bits-   ------------------------------------------------------------------------- */--#if defined(_MSC_VER) || defined(__MINGW32__) || defined(_WIN32)--#include "HsBase.h"--/* This is the error table that defines the mapping between OS error-   codes and errno values */--struct errentry {-        unsigned long oscode;           /* OS return value */-        int errnocode;  /* System V error code */-};--static struct errentry errtable[] = {-        {  ERROR_INVALID_FUNCTION,       EINVAL    },  /* 1 */-        {  ERROR_FILE_NOT_FOUND,         ENOENT    },  /* 2 */-        {  ERROR_PATH_NOT_FOUND,         ENOENT    },  /* 3 */-        {  ERROR_TOO_MANY_OPEN_FILES,    EMFILE    },  /* 4 */-        {  ERROR_ACCESS_DENIED,          EACCES    },  /* 5 */-        {  ERROR_INVALID_HANDLE,         EBADF     },  /* 6 */-        {  ERROR_ARENA_TRASHED,          ENOMEM    },  /* 7 */-        {  ERROR_NOT_ENOUGH_MEMORY,      ENOMEM    },  /* 8 */-        {  ERROR_INVALID_BLOCK,          ENOMEM    },  /* 9 */-        {  ERROR_BAD_ENVIRONMENT,        E2BIG     },  /* 10 */-        {  ERROR_BAD_FORMAT,             ENOEXEC   },  /* 11 */-        {  ERROR_INVALID_ACCESS,         EINVAL    },  /* 12 */-        {  ERROR_INVALID_DATA,           EINVAL    },  /* 13 */-        {  ERROR_INVALID_DRIVE,          ENOENT    },  /* 15 */-        {  ERROR_CURRENT_DIRECTORY,      EACCES    },  /* 16 */-        {  ERROR_NOT_SAME_DEVICE,        EXDEV     },  /* 17 */-        {  ERROR_NO_MORE_FILES,          ENOENT    },  /* 18 */-        {  ERROR_LOCK_VIOLATION,         EACCES    },  /* 33 */-        {  ERROR_BAD_NETPATH,            ENOENT    },  /* 53 */-        {  ERROR_NETWORK_ACCESS_DENIED,  EACCES    },  /* 65 */-        {  ERROR_BAD_NET_NAME,           ENOENT    },  /* 67 */-        {  ERROR_FILE_EXISTS,            EEXIST    },  /* 80 */-        {  ERROR_CANNOT_MAKE,            EACCES    },  /* 82 */-        {  ERROR_FAIL_I24,               EACCES    },  /* 83 */-        {  ERROR_INVALID_PARAMETER,      EINVAL    },  /* 87 */-        {  ERROR_NO_PROC_SLOTS,          EAGAIN    },  /* 89 */-        {  ERROR_DRIVE_LOCKED,           EACCES    },  /* 108 */-        {  ERROR_BROKEN_PIPE,            EPIPE     },  /* 109 */-        {  ERROR_DISK_FULL,              ENOSPC    },  /* 112 */-        {  ERROR_INVALID_TARGET_HANDLE,  EBADF     },  /* 114 */-        {  ERROR_INVALID_HANDLE,         EINVAL    },  /* 124 */-        {  ERROR_WAIT_NO_CHILDREN,       ECHILD    },  /* 128 */-        {  ERROR_CHILD_NOT_COMPLETE,     ECHILD    },  /* 129 */-        {  ERROR_DIRECT_ACCESS_HANDLE,   EBADF     },  /* 130 */-        {  ERROR_NEGATIVE_SEEK,          EINVAL    },  /* 131 */-        {  ERROR_SEEK_ON_DEVICE,         EACCES    },  /* 132 */-        {  ERROR_DIR_NOT_EMPTY,          ENOTEMPTY },  /* 145 */-        {  ERROR_NOT_LOCKED,             EACCES    },  /* 158 */-        {  ERROR_BAD_PATHNAME,           ENOENT    },  /* 161 */-        {  ERROR_MAX_THRDS_REACHED,      EAGAIN    },  /* 164 */-        {  ERROR_LOCK_FAILED,            EACCES    },  /* 167 */-        {  ERROR_ALREADY_EXISTS,         EEXIST    },  /* 183 */-        {  ERROR_FILENAME_EXCED_RANGE,   ENOENT    },  /* 206 */-        {  ERROR_NESTING_NOT_ALLOWED,    EAGAIN    },  /* 215 */-           /* Windows returns this when the read end of a pipe is-            * closed (or closing) and we write to it. */-        {  ERROR_NO_DATA,                EPIPE     },  /* 232 */-        {  ERROR_NOT_ENOUGH_QUOTA,       ENOMEM    }  /* 1816 */-};--/* size of the table */-#define ERRTABLESIZE (sizeof(errtable)/sizeof(errtable[0]))--/* The following two constants must be the minimum and maximum-   values in the (contiguous) range of Exec Failure errors. */-#define MIN_EXEC_ERROR ERROR_INVALID_STARTING_CODESEG-#define MAX_EXEC_ERROR ERROR_INFLOOP_IN_RELOC_CHAIN--/* These are the low and high value in the range of errors that are-   access violations */-#define MIN_EACCES_RANGE ERROR_WRITE_PROTECT-#define MAX_EACCES_RANGE ERROR_SHARING_BUFFER_EXCEEDED--void maperrno(void)-{-    errno = maperrno_func(GetLastError());-}--int maperrno_func(DWORD dwErrorCode)-{-    int i;--    /* check the table for the OS error code */-    for (i = 0; i < ERRTABLESIZE; ++i)-        if (dwErrorCode == errtable[i].oscode)-            return errtable[i].errnocode;--    /* The error code wasn't in the table.  We check for a range of */-    /* EACCES errors or exec failure errors (ENOEXEC).  Otherwise   */-    /* EINVAL is returned.                                          */--    if (dwErrorCode >= MIN_EACCES_RANGE && dwErrorCode <= MAX_EACCES_RANGE)-        return EACCES;-    else if (dwErrorCode >= MIN_EXEC_ERROR && dwErrorCode <= MAX_EXEC_ERROR)-        return ENOEXEC;-    else-        return EINVAL;-}--LPWSTR base_getErrorMessage(DWORD err)-{-    LPWSTR what;-    DWORD res;--    res = FormatMessageW(-              (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER),-              NULL,-              err,-              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */-              (LPWSTR) &what,-              0,-              NULL-          );-    if (res == 0)-        return NULL;-    return what;-}--int get_unique_file_info(int fd, HsWord64 *dev, HsWord64 *ino)-{-    HANDLE h = (HANDLE)_get_osfhandle(fd);-    BY_HANDLE_FILE_INFORMATION info;--    if (GetFileInformationByHandle(h, &info))-    {-        *dev = info.dwVolumeSerialNumber;-        *ino = info.nFileIndexLow-             | ((HsWord64)info.nFileIndexHigh << 32);--        return 0;-    }--    return -1;-}--BOOL file_exists(LPCTSTR path)-{-    DWORD r = GetFileAttributes(path);-    return r != INVALID_FILE_ATTRIBUTES;-}--#endif
− cbits/consUtils.c
@@ -1,111 +0,0 @@-/* - * (c) The University of Glasgow 2002- *- * Win32 Console API support- */-#if defined(_MSC_VER) || defined(__MINGW32__) || defined(_WIN32) || defined(__CYGWIN__)-/* to the end */--#include "consUtils.h"-#include <windows.h>-#include <io.h>--#if defined(__CYGWIN__)-#define _get_osfhandle get_osfhandle-#endif--int is_console__(int fd) {-    DWORD st;-    HANDLE h;-    if (!_isatty(fd)) {-        /* TTY must be a character device */-        return 0;-    }-    h = (HANDLE)_get_osfhandle(fd);-    if (h == INVALID_HANDLE_VALUE) {-        /* Broken handle can't be terminal */-        return 0;-    }-    if (!GetConsoleMode(h, &st)) {-        /* GetConsoleMode appears to fail when it's not a TTY.  In-           particular, it's what most of our terminal functions-           assume works, so if it doesn't work for all intents-           and purposes we're not dealing with a terminal. */-        return 0;-    }-    return 1;-}---int-set_console_buffering__(int fd, int cooked)-{-    HANDLE h;-    DWORD  st;-    /* According to GetConsoleMode() docs, it is not possible to-       leave ECHO_INPUT enabled without also having LINE_INPUT,-       so we have to turn both off here. */-    DWORD flgs = ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT;-    -    if ( (h = (HANDLE)_get_osfhandle(fd)) != INVALID_HANDLE_VALUE ) {-	if ( GetConsoleMode(h,&st) &&-	     SetConsoleMode(h, cooked ? (st | ENABLE_LINE_INPUT) : st & ~flgs)  ) {-	    return 0;-	}-    }-    return -1;-}--int-set_console_echo__(int fd, int on)-{-    HANDLE h;-    DWORD  st;-    DWORD flgs = ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT;-    -    if ( (h = (HANDLE)_get_osfhandle(fd)) != INVALID_HANDLE_VALUE ) {-	if ( GetConsoleMode(h,&st) && -	     SetConsoleMode(h,( on ? (st | flgs) : (st & ~ENABLE_ECHO_INPUT))) ) {-	    return 0;-	}-    }-    return -1;-}--int-get_console_echo__(int fd)-{-    HANDLE h;-    DWORD  st;-    -    if ( (h = (HANDLE)_get_osfhandle(fd)) != INVALID_HANDLE_VALUE ) {-	if ( GetConsoleMode(h,&st) ) {-	    return (st & ENABLE_ECHO_INPUT ? 1 : 0);-	}-    }-    return -1;-}--int-flush_input_console__(int fd)-{-    HANDLE h = (HANDLE)_get_osfhandle(fd);-    -    if ( h != INVALID_HANDLE_VALUE ) {-	/* If the 'fd' isn't connected to a console; treat the flush-	 * operation as a NOP.-	 */-	DWORD unused;-	if ( !GetConsoleMode(h,&unused) &&-	     GetLastError() == ERROR_INVALID_HANDLE ) {-	    return 0;-	}-	if ( FlushConsoleInputBuffer(h) ) {-	    return 0;-	}-    }-    /* ToDo: translate GetLastError() into something errno-friendly */-    return -1;-}--#endif /* defined(__MINGW32__) || ... */
− cbits/iconv.c
@@ -1,25 +0,0 @@-#ifndef __MINGW32__--#include <stdlib.h>-#include <iconv.h>--iconv_t hs_iconv_open(const char* tocode,-		      const char* fromcode)-{-	return iconv_open(tocode, fromcode);-}--size_t hs_iconv(iconv_t cd,-		const char* * inbuf, size_t * inbytesleft,-		char* * outbuf, size_t * outbytesleft)-{-    // (void*) cast avoids a warning.  Some iconvs use (const-    // char**inbuf), other use (char **inbuf).-    return iconv(cd, (void*)inbuf, inbytesleft, outbuf, outbytesleft);-}--int hs_iconv_close(iconv_t cd) {-	return iconv_close(cd);-}--#endif
− cbits/inputReady.c
@@ -1,172 +0,0 @@-/* - * (c) The GRASP/AQUA Project, Glasgow University, 1994-2002- *- * hWaitForInput Runtime Support- */--/* select and supporting types is not Posix */-/* #include "PosixSource.h" */-#include "HsBase.h"--/*- * inputReady(fd) checks to see whether input is available on the file- * descriptor 'fd'.  Input meaning 'can I safely read at least a- * *character* from this file object without blocking?'- */-int-fdReady(int fd, int write, int msecs, int isSock)-{-    if -#if defined(_MSC_VER) || defined(__MINGW32__) || defined(_WIN32)-    ( isSock ) {-#else-    ( 1 ) {-#endif-	int maxfd, ready;-	fd_set rfd, wfd;-	struct timeval tv;-        if ((fd >= (int)FD_SETSIZE) || (fd < 0)) {-            /* avoid memory corruption on too large FDs */-            errno = EINVAL;-            return -1;-        }-	FD_ZERO(&rfd);-	FD_ZERO(&wfd);-        if (write) {-            FD_SET(fd, &wfd);-        } else {-            FD_SET(fd, &rfd);-        }-	-	/* select() will consider the descriptor set in the range of 0 to-	 * (maxfd-1) -	 */-	maxfd = fd + 1;-	tv.tv_sec  = msecs / 1000;-	tv.tv_usec = (msecs % 1000) * 1000;-	-	while ((ready = select(maxfd, &rfd, &wfd, NULL, &tv)) < 0 ) {-	    if (errno != EINTR ) {-		return -1;-	    }-	}-	-	/* 1 => Input ready, 0 => not ready, -1 => error */-	return (ready);-    }-#if defined(_MSC_VER) || defined(__MINGW32__) || defined(_WIN32)-    else {-	DWORD rc;-	HANDLE hFile = (HANDLE)_get_osfhandle(fd);-	DWORD avail;--        switch (GetFileType(hFile)) {--        case FILE_TYPE_CHAR:-        {-            INPUT_RECORD buf[1];-            DWORD count;--            // nightmare.  A Console Handle will appear to be ready-            // (WaitForSingleObject() returned WAIT_OBJECT_0) when-            // it has events in its input buffer, but these events might-            // not be keyboard events, so when we read from the Handle the-            // read() will block.  So here we try to discard non-keyboard-            // events from a console handle's input buffer and then try-            // the WaitForSingleObject() again.--            while (1) // keep trying until we find a real key event-            {-                rc = WaitForSingleObject( hFile, msecs );-                switch (rc) {-                case WAIT_TIMEOUT: return 0;-                case WAIT_OBJECT_0: break;-                default: /* WAIT_FAILED */ maperrno(); return -1;-                }--                while (1) // discard non-key events-                {-                    rc = PeekConsoleInput(hFile, buf, 1, &count);-                    // printf("peek, rc=%d, count=%d, type=%d\n", rc, count, buf[0].EventType);-                    if (rc == 0) {-                        rc = GetLastError();-                        if (rc == ERROR_INVALID_HANDLE || rc == ERROR_INVALID_FUNCTION) {-                            return 1;-                        } else {-                            maperrno();-                            return -1;-                        }-                    }--                    if (count == 0) break; // no more events => wait again--                    // discard console events that are not "key down", because-                    // these will also be discarded by ReadFile().-                    if (buf[0].EventType == KEY_EVENT &&-                        buf[0].Event.KeyEvent.bKeyDown &&-                        buf[0].Event.KeyEvent.uChar.AsciiChar != '\0')-                    {-                        // it's a proper keypress:-                        return 1;-                    }-                    else-                    {-                        // it's a non-key event, a key up event, or a-                        // non-character key (e.g. shift).  discard it.-                        rc = ReadConsoleInput(hFile, buf, 1, &count);-                        if (rc == 0) {-                            rc = GetLastError();-                            if (rc == ERROR_INVALID_HANDLE || rc == ERROR_INVALID_FUNCTION) {-                                return 1;-                            } else {-                                maperrno();-                                return -1;-                            }-                        }-                    }-                }-            }-        }--        case FILE_TYPE_DISK:-            // assume that disk files are always ready:-            return 1;--        case FILE_TYPE_PIPE:-            // WaitForMultipleObjects() doesn't work for pipes (it-            // always returns WAIT_OBJECT_0 even when no data is-            // available).  If the HANDLE is a pipe, therefore, we try-            // PeekNamedPipe:-            //-            rc = PeekNamedPipe( hFile, NULL, 0, NULL, &avail, NULL );-            if (rc != 0) {-                if (avail != 0) {-                    return 1;-                } else {-                    return 0;-                }-            } else {-                rc = GetLastError();-                if (rc == ERROR_BROKEN_PIPE) {-                    return 1; // this is probably what we want-                }-                if (rc != ERROR_INVALID_HANDLE && rc != ERROR_INVALID_FUNCTION) {-                    maperrno();-                    return -1;-                }-            }-            /* PeekNamedPipe didn't work - fall through to the general case */--        default:-            rc = WaitForSingleObject( hFile, msecs );--            /* 1 => Input ready, 0 => not ready, -1 => error */-            switch (rc) {-            case WAIT_TIMEOUT: return 0;-            case WAIT_OBJECT_0: return 1;-            default: /* WAIT_FAILED */ maperrno(); return -1;-            }-        }-    }-#endif-}    
− cbits/md5.c
@@ -1,238 +0,0 @@-/*- * This code implements the MD5 message-digest algorithm.- * The algorithm is due to Ron Rivest.  This code was- * written by Colin Plumb in 1993, no copyright is claimed.- * This code is in the public domain; do with it what you wish.- *- * Equivalent code is available from RSA Data Security, Inc.- * This code has been tested against that, and is equivalent,- * except that you don't need to include two pages of legalese- * with every copy.- *- * To compute the message digest of a chunk of bytes, declare an- * MD5Context structure, pass it to MD5Init, call MD5Update as- * needed on buffers full of bytes, and then call MD5Final, which- * will fill a supplied 16-byte array with the digest.- */--#include "HsFFI.h"-#include "md5.h"-#include <string.h>--void __hsbase_MD5Init(struct MD5Context *context);-void __hsbase_MD5Update(struct MD5Context *context, byte const *buf, int len);-void __hsbase_MD5Final(byte digest[16], struct MD5Context *context);-void __hsbase_MD5Transform(word32 buf[4], word32 const in[16]);---/*- * Shuffle the bytes into little-endian order within words, as per the- * MD5 spec.  Note: this code works regardless of the byte order.- */-static void-byteSwap(word32 *buf, unsigned words)-{-	byte *p = (byte *)buf;--	do {-		*buf++ = (word32)((unsigned)p[3] << 8 | p[2]) << 16 |-			((unsigned)p[1] << 8 | p[0]);-		p += 4;-	} while (--words);-}--/*- * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious- * initialization constants.- */-void-__hsbase_MD5Init(struct MD5Context *ctx)-{-	ctx->buf[0] = 0x67452301;-	ctx->buf[1] = 0xefcdab89;-	ctx->buf[2] = 0x98badcfe;-	ctx->buf[3] = 0x10325476;--	ctx->bytes[0] = 0;-	ctx->bytes[1] = 0;-}--/*- * Update context to reflect the concatenation of another buffer full- * of bytes.- */-void-__hsbase_MD5Update(struct MD5Context *ctx, byte const *buf, int len)-{-	word32 t;--	/* Update byte count */--	t = ctx->bytes[0];-	if ((ctx->bytes[0] = t + len) < t)-		ctx->bytes[1]++;	/* Carry from low to high */--	t = 64 - (t & 0x3f);	/* Space available in ctx->in (at least 1) */-	if ((unsigned)t > len) {-		memcpy((byte *)ctx->in + 64 - (unsigned)t, buf, len);-		return;-	}-	/* First chunk is an odd size */-	memcpy((byte *)ctx->in + 64 - (unsigned)t, buf, (unsigned)t);-	byteSwap(ctx->in, 16);-        __hsbase_MD5Transform(ctx->buf, ctx->in);-	buf += (unsigned)t;-	len -= (unsigned)t;--	/* Process data in 64-byte chunks */-	while (len >= 64) {-		memcpy(ctx->in, buf, 64);-		byteSwap(ctx->in, 16);-                __hsbase_MD5Transform(ctx->buf, ctx->in);-		buf += 64;-		len -= 64;-	}--	/* Handle any remaining bytes of data. */-	memcpy(ctx->in, buf, len);-}--/*- * Final wrapup - pad to 64-byte boundary with the bit pattern - * 1 0* (64-bit count of bits processed, MSB-first)- */-void-__hsbase_MD5Final(byte digest[16], struct MD5Context *ctx)-{-	int count = (int)(ctx->bytes[0] & 0x3f); /* Bytes in ctx->in */-	byte *p = (byte *)ctx->in + count;	/* First unused byte */--	/* Set the first char of padding to 0x80.  There is always room. */-	*p++ = 0x80;--	/* Bytes of padding needed to make 56 bytes (-8..55) */-	count = 56 - 1 - count;--	if (count < 0) {	/* Padding forces an extra block */-		memset(p, 0, count+8);-		byteSwap(ctx->in, 16);-                __hsbase_MD5Transform(ctx->buf, ctx->in);-		p = (byte *)ctx->in;-		count = 56;-	}-	memset(p, 0, count+8);-	byteSwap(ctx->in, 14);--	/* Append length in bits and transform */-	ctx->in[14] = ctx->bytes[0] << 3;-	ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;-        __hsbase_MD5Transform(ctx->buf, ctx->in);--	byteSwap(ctx->buf, 4);-	memcpy(digest, ctx->buf, 16);-	memset(ctx, 0, sizeof(*ctx));-}---/* The four core functions - F1 is optimized somewhat */--/* #define F1(x, y, z) (x & y | ~x & z) */-#define F1(x, y, z) (z ^ (x & (y ^ z)))-#define F2(x, y, z) F1(z, x, y)-#define F3(x, y, z) (x ^ y ^ z)-#define F4(x, y, z) (y ^ (x | ~z))--/* This is the central step in the MD5 algorithm. */-#define MD5STEP(f,w,x,y,z,in,s) \-	 (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)--/*- * The core of the MD5 algorithm, this alters an existing MD5 hash to- * reflect the addition of 16 longwords of new data.  MD5Update blocks- * the data and converts bytes into longwords for this routine.- */--void-__hsbase_MD5Transform(word32 buf[4], word32 const in[16])-{-	register word32 a, b, c, d;--	a = buf[0];-	b = buf[1];-	c = buf[2];-	d = buf[3];--	MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);-	MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);-	MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);-	MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);-	MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);-	MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);-	MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);-	MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);-	MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);-	MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);-	MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);-	MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);-	MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);-	MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);-	MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);-	MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);--	MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);-	MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);-	MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);-	MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);-	MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);-	MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);-	MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);-	MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);-	MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);-	MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);-	MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);-	MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);-	MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);-	MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);-	MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);-	MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);--	MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);-	MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);-	MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);-	MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);-	MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);-	MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);-	MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);-	MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);-	MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);-	MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);-	MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);-	MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);-	MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);-	MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);-	MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);-	MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);--	MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);-	MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);-	MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);-	MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);-	MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);-	MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);-	MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);-	MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);-	MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);-	MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);-	MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);-	MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);-	MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);-	MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);-	MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);-	MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);--	buf[0] += a;-	buf[1] += b;-	buf[2] += c;-	buf[3] += d;-}-
− cbits/primFloat.c
@@ -1,532 +0,0 @@-/* ------------------------------------------------------------------------------ *- * (c) Lennart Augustsson- * (c) The GHC Team, 1998-2000- *- * Miscellaneous support for floating-point primitives- *- * ---------------------------------------------------------------------------*/--#include "HsFFI.h"-#include "Rts.h" // XXX wrong (for IEEE_FLOATING_POINT and WORDS_BIGENDIAN)--#define IEEE_FLOATING_POINT 1--union stg_ieee754_flt-{-   float f;-   struct {--#if WORDS_BIGENDIAN-	unsigned int negative:1;-	unsigned int exponent:8;-	unsigned int mantissa:23;-#else-	unsigned int mantissa:23;-	unsigned int exponent:8;-	unsigned int negative:1;-#endif-   } ieee;-   struct {--#if WORDS_BIGENDIAN-	unsigned int negative:1;-	unsigned int exponent:8;-	unsigned int quiet_nan:1;-	unsigned int mantissa:22;-#else-	unsigned int mantissa:22;-	unsigned int quiet_nan:1;-	unsigned int exponent:8;-	unsigned int negative:1;-#endif-   } ieee_nan;-};--/*-- To recap, here's the representation of a double precision- IEEE floating point number:-- sign         63           sign bit (0==positive, 1==negative)- exponent     62-52        exponent (biased by 1023)- fraction     51-0         fraction (bits to right of binary point)-*/--union stg_ieee754_dbl-{-   double d;-   struct {--#if WORDS_BIGENDIAN-	unsigned int negative:1;-	unsigned int exponent:11;-	unsigned int mantissa0:20;-	unsigned int mantissa1:32;-#else-#if FLOAT_WORDS_BIGENDIAN-	unsigned int mantissa0:20;-	unsigned int exponent:11;-	unsigned int negative:1;-	unsigned int mantissa1:32;-#else-	unsigned int mantissa1:32;-	unsigned int mantissa0:20;-	unsigned int exponent:11;-	unsigned int negative:1;-#endif-#endif-   } ieee;-    /* This format makes it easier to see if a NaN is a signalling NaN.  */-   struct {--#if WORDS_BIGENDIAN-	unsigned int negative:1;-	unsigned int exponent:11;-	unsigned int quiet_nan:1;-	unsigned int mantissa0:19;-	unsigned int mantissa1:32;-#else-#if FLOAT_WORDS_BIGENDIAN-	unsigned int mantissa0:19;-	unsigned int quiet_nan:1;-	unsigned int exponent:11;-	unsigned int negative:1;-	unsigned int mantissa1:32;-#else-	unsigned int mantissa1:32;-	unsigned int mantissa0:19;-	unsigned int quiet_nan:1;-	unsigned int exponent:11;-	unsigned int negative:1;-#endif-#endif-   } ieee_nan;-};--/*- * Predicates for testing for extreme IEEE fp values.- */--/* In case you don't suppport IEEE, you'll just get dummy defs.. */-#ifdef IEEE_FLOATING_POINT--HsInt-isDoubleFinite(HsDouble d)-{-  union stg_ieee754_dbl u;--  u.d = d;--  return u.ieee.exponent != 2047;-}--HsInt-isDoubleNaN(HsDouble d)-{-  union stg_ieee754_dbl u;--  u.d = d;--  return (-    u.ieee.exponent  == 2047 /* 2^11 - 1 */ &&  /* Is the exponent all ones? */-    (u.ieee.mantissa0 != 0 || u.ieee.mantissa1 != 0)-    	/* and the mantissa non-zero? */-    );-}--HsInt-isDoubleInfinite(HsDouble d)-{-    union stg_ieee754_dbl u;--    u.d = d;--    /* Inf iff exponent is all ones, mantissa all zeros */-    return (-        u.ieee.exponent  == 2047 /* 2^11 - 1 */ &&-	u.ieee.mantissa0 == 0 		        &&-	u.ieee.mantissa1 == 0-      );-}--HsInt-isDoubleDenormalized(HsDouble d)-{-    union stg_ieee754_dbl u;--    u.d = d;--    /* A (single/double/quad) precision floating point number-       is denormalised iff:-        - exponent is zero-	- mantissa is non-zero.-        - (don't care about setting of sign bit.)--    */-    return (-	u.ieee.exponent  == 0 &&-	(u.ieee.mantissa0 != 0 ||-	 u.ieee.mantissa1 != 0)-      );--}--HsInt-isDoubleNegativeZero(HsDouble d)-{-    union stg_ieee754_dbl u;--    u.d = d;-    /* sign (bit 63) set (only) => negative zero */--    return (-    	u.ieee.negative  == 1 &&-	u.ieee.exponent  == 0 &&-	u.ieee.mantissa0 == 0 &&-	u.ieee.mantissa1 == 0);-}--/* Same tests, this time for HsFloats. */--/*- To recap, here's the representation of a single precision- IEEE floating point number:-- sign         31           sign bit (0 == positive, 1 == negative)- exponent     30-23        exponent (biased by 127)- fraction     22-0         fraction (bits to right of binary point)-*/---HsInt-isFloatFinite(HsFloat f)-{-    union stg_ieee754_flt u;-    u.f = f;-    return u.ieee.exponent != 255;-}--HsInt-isFloatNaN(HsFloat f)-{-    union stg_ieee754_flt u;-    u.f = f;--   /* Floating point NaN iff exponent is all ones, mantissa is-      non-zero (but see below.) */-   return (-   	u.ieee.exponent == 255 /* 2^8 - 1 */ &&-	u.ieee.mantissa != 0);-}--HsInt-isFloatInfinite(HsFloat f)-{-    union stg_ieee754_flt u;-    u.f = f;--    /* A float is Inf iff exponent is max (all ones),-       and mantissa is min(all zeros.) */-    return (-    	u.ieee.exponent == 255 /* 2^8 - 1 */ &&-	u.ieee.mantissa == 0);-}--HsInt-isFloatDenormalized(HsFloat f)-{-    union stg_ieee754_flt u;-    u.f = f;--    /* A (single/double/quad) precision floating point number-       is denormalised iff:-        - exponent is zero-	- mantissa is non-zero.-        - (don't care about setting of sign bit.)--    */-    return (-    	u.ieee.exponent == 0 &&-	u.ieee.mantissa != 0);-}--HsInt-isFloatNegativeZero(HsFloat f)-{-    union stg_ieee754_flt u;-    u.f = f;--    /* sign (bit 31) set (only) => negative zero */-    return (-	u.ieee.negative      &&-	u.ieee.exponent == 0 &&-	u.ieee.mantissa == 0);-}--/*- There are glibc versions around with buggy rintf or rint, hence we- provide our own. We always round ties to even, so we can be simpler.-*/--#define FLT_HIDDEN 0x800000-#define FLT_POWER2 0x1000000--HsFloat-rintFloat(HsFloat f)-{-    union stg_ieee754_flt u;-    u.f = f;-    /* if real exponent > 22, it's already integral, infinite or nan */-    if (u.ieee.exponent > 149)  /* 22 + 127 */-    {-        return u.f;-    }-    if (u.ieee.exponent < 126)  /* (-1) + 127, abs(f) < 0.5 */-    {-        /* only used for rounding to Integral a, so don't care about -0.0 */-        return 0.0;-    }-    /* 0.5 <= abs(f) < 2^23 */-    unsigned int half, mask, mant, frac;-    half = 1 << (149 - u.ieee.exponent);    /* bit for 0.5 */-    mask = 2*half - 1;                      /* fraction bits */-    mant = u.ieee.mantissa | FLT_HIDDEN;    /* add hidden bit */-    frac = mant & mask;                     /* get fraction */-    mant ^= frac;                           /* truncate mantissa */-    if ((frac < half) || ((frac == half) && ((mant & (2*half)) == 0)))-    {-        /* this means we have to truncate */-        if (mant == 0)-        {-            /* f == ±0.5, return 0.0 */-            return 0.0;-        }-        else-        {-            /* remove hidden bit and set mantissa */-            u.ieee.mantissa = mant ^ FLT_HIDDEN;-            return u.f;-        }-    }-    else-    {-        /* round away from zero, increment mantissa */-        mant += 2*half;-        if (mant == FLT_POWER2)-        {-            /* next power of 2, increase exponent an set mantissa to 0 */-            u.ieee.mantissa = 0;-            u.ieee.exponent += 1;-            return u.f;-        }-        else-        {-            /* remove hidden bit and set mantissa */-            u.ieee.mantissa = mant ^ FLT_HIDDEN;-            return u.f;-        }-    }-}--#define DBL_HIDDEN 0x100000-#define DBL_POWER2 0x200000-#define LTOP_BIT 0x80000000--HsDouble-rintDouble(HsDouble d)-{-    union stg_ieee754_dbl u;-    u.d = d;-    /* if real exponent > 51, it's already integral, infinite or nan */-    if (u.ieee.exponent > 1074) /* 51 + 1023 */-    {-        return u.d;-    }-    if (u.ieee.exponent < 1022)  /* (-1) + 1023, abs(d) < 0.5 */-    {-        /* only used for rounding to Integral a, so don't care about -0.0 */-        return 0.0;-    }-    unsigned int half, mask, mant, frac;-    if (u.ieee.exponent < 1043) /* 20 + 1023, real exponent < 20 */-    {-        /* the fractional part meets the higher part of the mantissa */-        half = 1 << (1042 - u.ieee.exponent);   /* bit for 0.5 */-        mask = 2*half - 1;                      /* fraction bits */-        mant = u.ieee.mantissa0 | DBL_HIDDEN;   /* add hidden bit */-        frac = mant & mask;                     /* get fraction */-        mant ^= frac;                           /* truncate mantissa */-        if ((frac < half) ||-            ((frac == half) && (u.ieee.mantissa1 == 0)  /* a tie */-                && ((mant & (2*half)) == 0)))-        {-            /* truncate */-            if (mant == 0)-            {-                /* d = ±0.5, return 0.0 */-                return 0.0;-            }-            /* remove hidden bit and set mantissa */-            u.ieee.mantissa0 = mant ^ DBL_HIDDEN;-            u.ieee.mantissa1 = 0;-            return u.d;-        }-        else    /* round away from zero */-        {-            /* zero low mantissa bits */-            u.ieee.mantissa1 = 0;-            /* increment integer part of mantissa */-            mant += 2*half;-            if (mant == DBL_POWER2)-            {-                /* power of 2, increment exponent and zero mantissa */-                u.ieee.mantissa0 = 0;-                u.ieee.exponent += 1;-                return u.d;-            }-            /* remove hidden bit */-            u.ieee.mantissa0 = mant ^ DBL_HIDDEN;-            return u.d;-        }-    }-    else-    {-        /* 20 <= real exponent < 52, fractional part entirely in mantissa1 */-        half = 1 << (1074 - u.ieee.exponent);   /* bit for 0.5 */-        mask = 2*half - 1;                      /* fraction bits */-        mant = u.ieee.mantissa1;                /* no hidden bit here */-        frac = mant & mask;                     /* get fraction */-        mant ^= frac;                           /* truncate mantissa */-        if ((frac < half) ||-            ((frac == half) &&                  /* tie */-            (((half == LTOP_BIT) ? (u.ieee.mantissa0 & 1)  /* yuck */-                                : (mant & (2*half)))-                                        == 0)))-        {-            /* truncate */-            u.ieee.mantissa1 = mant;-            return u.d;-        }-        else-        {-            /* round away from zero */-            /* increment mantissa */-            mant += 2*half;-            u.ieee.mantissa1 = mant;-            if (mant == 0)-            {-                /* low part of mantissa overflowed */-                /* increment high part of mantissa */-                mant = u.ieee.mantissa0 + 1;-                if (mant == DBL_HIDDEN)-                {-                    /* hit power of 2 */-                    /* zero mantissa */-                    u.ieee.mantissa0 = 0;-                    /* and increment exponent */-                    u.ieee.exponent += 1;-                    return u.d;-                }-                else-                {-                    u.ieee.mantissa0 = mant;-                    return u.d;-                }-            }-            else-            {-                return u.d;-            }-        }-    }-}--#else /* ! IEEE_FLOATING_POINT */--/* Dummy definitions of predicates - they all return "normal" values */-HsInt isDoubleFinite(HsDouble d) { return 1;}-HsInt isDoubleNaN(HsDouble d) { return 0; }-HsInt isDoubleInfinite(HsDouble d) { return 0; }-HsInt isDoubleDenormalized(HsDouble d) { return 0; }-HsInt isDoubleNegativeZero(HsDouble d) { return 0; }-HsInt isFloatFinite(HsFloat f) { return 1; }-HsInt isFloatNaN(HsFloat f) { return 0; }-HsInt isFloatInfinite(HsFloat f) { return 0; }-HsInt isFloatDenormalized(HsFloat f) { return 0; }-HsInt isFloatNegativeZero(HsFloat f) { return 0; }---/* For exotic floating point formats, we can't do much */-/* We suppose the format has not too many bits */-/* I hope nobody tries to build GHC where this is wrong */--#define FLT_UPP 536870912.0--HsFloat-rintFloat(HsFloat f)-{-    if ((f > FLT_UPP) || (f < (-FLT_UPP)))-    {-        return f;-    }-    else-    {-        int i = (int)f;-        float g = i;-        float d = f - g;-        if (d > 0.5)-        {-            return g + 1.0;-        }-        if (d == 0.5)-        {-            return (i & 1) ? (g + 1.0) : g;-        }-        if (d == -0.5)-        {-            return (i & 1) ? (g - 1.0) : g;-        }-        if (d < -0.5)-        {-            return g - 1.0;-        }-        return g;-    }-}--#define DBL_UPP 2305843009213693952.0--HsDouble-rintDouble(HsDouble d)-{-    if ((d > DBL_UPP) || (d < (-DBL_UPP)))-    {-        return d;-    }-    else-    {-        HsInt64 i = (HsInt64)d;-        double e = i;-        double r = d - e;-        if (r > 0.5)-        {-            return e + 1.0;-        }-        if (r == 0.5)-        {-            return (i & 1) ? (e + 1.0) : e;-        }-        if (r == -0.5)-        {-            return (i & 1) ? (e - 1.0) : e;-        }-        if (r < -0.5)-        {-            return e - 1.0;-        }-        return e;-    }-}--#endif /* ! IEEE_FLOATING_POINT */
− cbits/rts.c
@@ -1,42 +0,0 @@-#include "Rts.h"-#include "rts/Flags.h"--GC_FLAGS *getGcFlags()-{-    return &RtsFlags.GcFlags;-}--CONCURRENT_FLAGS *getConcFlags()-{-    return &RtsFlags.ConcFlags;-}--MISC_FLAGS *getMiscFlags()-{-    return &RtsFlags.MiscFlags;-}--DEBUG_FLAGS *getDebugFlags()-{-    return &RtsFlags.DebugFlags;-}--COST_CENTRE_FLAGS *getCcFlags()-{-    return &RtsFlags.CcFlags;-}--PROFILING_FLAGS *getProfFlags()-{-    return &RtsFlags.ProfFlags;-}--TRACE_FLAGS *getTraceFlags()-{-    return &RtsFlags.TraceFlags;-}--TICKY_FLAGS *getTickyFlags()-{-    return &RtsFlags.TickyFlags;-}
− cbits/sysconf.c
@@ -1,19 +0,0 @@-#include "HsBaseConfig.h"--/* For _SC_CLK_TCK */-#if HAVE_UNISTD_H-#include <unistd.h>-#endif--/* for CLK_TCK */-#if HAVE_TIME_H-#include <time.h>-#endif--long clk_tck(void) {-#if defined(CLK_TCK)-    return (CLK_TCK);-#else-    return sysconf(_SC_CLK_TCK);-#endif-}
changelog.md view
@@ -1,5 +1,989 @@ # Changelog for [`base` package](http://hackage.haskell.org/package/base) +## 4.22.0.0 *December 2025*+  * Shipped with GHC 9.14.1+  * The internal `GHC.Weak.Finalize.runFinalizerBatch` function has been deprecated ([CLC proposal #342](https://github.com/haskell/core-libraries-committee/issues/342))+  * Define `displayException` of `SomeAsyncException` to unwrap the exception.+      ([CLC proposal #309](https://github.com/haskell/core-libraries-committee/issues/309))+  * Restrict `Data.List.NonEmpty.unzip` to `NonEmpty (a, b) -> (NonEmpty a, NonEmpty b)`. ([CLC proposal #86](https://github.com/haskell/core-libraries-committee/issues/86))+  * Modify the implementation of `Control.Exception.throw` to avoid call-sites being inferred as diverging via precise exception.+    ([GHC #25066](https://gitlab.haskell.org/ghc/ghc/-/issues/25066), [CLC proposal #290](https://github.com/haskell/core-libraries-committee/issues/290))+  * `Data.List.NonEmpty.{init,last,tails1}` are now defined using only total functions (rather than partial ones). ([CLC proposal #293](https://github.com/haskell/core-libraries-committee/issues/293))+  * `Data.List.NonEmpty` functions now have the same laziness as their `Data.List` counterparts (i.e. make them more strict than they currently are) ([CLC proposal #107](https://github.com/haskell/core-libraries-committee/issues/107))+  * `instance Functor NonEmpty` is now specified using `map` (rather than duplicating code). ([CLC proposal #300](https://github.com/haskell/core-libraries-committee/issues/300))+  * `fail` from `MonadFail` now carries `HasCallStack` constraint. ([CLC proposal #327](https://github.com/haskell/core-libraries-committee/issues/327))+  * The `Data.Enum.enumerate` function was introduced ([CLC #306](https://github.com/haskell/core-libraries-committee/issues/306))+  * Worker threads used by various `base` facilities are now labelled with descriptive thread labels ([CLC proposal #305](https://github.com/haskell/core-libraries-committee/issues/305), [GHC #25452](https://gitlab.haskell.org/ghc/ghc/-/issues/25452)). Specifically, these include:+    * `Control.Concurrent.threadWaitRead`+    * `Control.Concurrent.threadWaitWrite`+    * `Control.Concurrent.threadWaitReadSTM`+    * `Control.Concurrent.threadWaitWriteSTM`+    * `System.Timeout.timeout`+    * `GHC.Conc.Signal.runHandlers`+  * The following internal modules have been removed from `base`, as per [CLC #217](https://github.com/haskell/core-libraries-committee/issues/217):+      * `GHC.TypeLits.Internal`+      * `GHC.TypeNats.Internal`+      * `GHC.ExecutionStack.Internal`.+  * Deprecate `GHC.JS.Prim.Internal.Build`, as per [CLC #329](https://github.com/haskell/core-libraries-committee/issues/329)+  * Fix incorrect results of `integerPowMod` when the base is 0 and the exponent is negative, and `integerRecipMod` when the modulus is zero ([#26017](https://gitlab.haskell.org/ghc/ghc/-/issues/26017)).+  * Fix the rewrite rule for `scanl'` not being strict in the first element of the output list ([#26143](https://gitlab.haskell.org/ghc/ghc/-/issues/26143)).+  * `GHC.Exts.IOPort#` and its related operations have been removed  ([CLC #213](https://github.com/haskell/core-libraries-committee/issues/213))+  * Remove deprecated, unstable heap representation details from `GHC.Exts` ([CLC proposal #212](https://github.com/haskell/core-libraries-committee/issues/212))++## 4.21.0.0 *December 2024*+  * Shipped with GHC 9.12.1+  * Change `SrcLoc` to be a strict and unboxed (finishing [CLC proposal #55](https://github.com/haskell/core-libraries-committee/issues/55))+  * Introduce `Data.Bounded` module exporting the `Bounded` typeclass (finishing [CLC proposal #208](https://github.com/haskell/core-libraries-committee/issues/208))+  * Deprecate export of `Bounded` class from `Data.Enum` ([CLC proposal #208](https://github.com/haskell/core-libraries-committee/issues/208))+  * `GHC.Desugar` has been deprecated and should be removed in GHC 9.14. ([CLC proposal #216](https://github.com/haskell/core-libraries-committee/issues/216))+  * Add a `readTixFile` field to the `HpcFlags` record in `GHC.RTS.Flags` ([CLC proposal #276](https://github.com/haskell/core-libraries-committee/issues/276))+  * Add `compareLength` to `Data.List` and `Data.List.NonEmpty` ([CLC proposal #257](https://github.com/haskell/core-libraries-committee/issues/257))+  * Add `INLINE[1]` to `compareInt` / `compareWord` ([CLC proposal #179](https://github.com/haskell/core-libraries-committee/issues/179))+  * Refactor `GHC.RTS.Flags` in preparation for new I/O managers: introduce `data IoManagerFlag` and use it in `MiscFlags`, remove `getIoManagerFlag`, deprecate re-export of `IoSubSystem` ([CLC proposal #263](https://github.com/haskell/core-libraries-committee/issues/263))+  * Add the `MonadFix` instance for `(,) a`, similar to the one for `Writer a` ([CLC proposal #238](https://github.com/haskell/core-libraries-committee/issues/238))+  * Improve `toInteger :: Word32 -> Integer` on 64-bit platforms ([CLC proposal #259](https://github.com/haskell/core-libraries-committee/issues/259))+  * Make `flip` representation polymorphic ([CLC proposal #245](https://github.com/haskell/core-libraries-committee/issues/245))+  * The `HasField` class now supports representation polymorphism ([CLC proposal #194](https://github.com/haskell/core-libraries-committee/issues/194))+  * Make `read` accept binary integer notation ([CLC proposal #177](https://github.com/haskell/core-libraries-committee/issues/177))+  * Improve the performance of `Data.List.sort` using an improved merging strategy. Instead of `compare`, `sort` now uses `(>)` which may break *malformed* `Ord` instances ([CLC proposal #236](https://github.com/haskell/core-libraries-committee/issues/236))+  * Add `inits1` and `tails1` to `Data.List`, factored from the corresponding functions in `Data.List.NonEmpty` ([CLC proposal #252](https://github.com/haskell/core-libraries-committee/issues/252))+  * Add `firstA` and `secondA` to `Data.Bitraversable`. ([CLC proposal #172](https://github.com/haskell/core-libraries-committee/issues/172))+  * Deprecate `GHC.TypeNats.Internal`, `GHC.TypeLits.Internal`, `GHC.ExecutionStack.Internal` ([CLC proposal #217](https://github.com/haskell/core-libraries-committee/issues/217))+  * `System.IO.Error.ioError` and `Control.Exception.ioError` now both carry `HasCallStack` constraints ([CLC proposal #275](https://github.com/haskell/core-libraries-committee/issues/275))+  * Define `Eq1`, `Ord1`, `Show1` and `Read1` instances for basic `Generic` representation types. ([CLC proposal #273](https://github.com/haskell/core-libraries-committee/issues/273))+  * `setNonBlockingMode` will no longer throw an exception when called on a FD associated with a unknown device type. ([CLC proposal #282](https://github.com/haskell/core-libraries-committee/issues/282))+  * Add exception type metadata to default exception handler output.+    ([CLC proposal #231](https://github.com/haskell/core-libraries-committee/issues/231)+    and [CLC proposal #261](https://github.com/haskell/core-libraries-committee/issues/261))+  * The [deprecation process of GHC.Pack](https://gitlab.haskell.org/ghc/ghc/-/issues/21461) has come its term. The module has now been removed from `base`.+  * Propagate HasCallStack from `errorCallWithCallStackException` to exception backtraces, fixing a bug in the implementation of [CLC proposal #164](https://github.com/haskell/core-libraries-committee/issues/164).+  * Annotate re-thrown exceptions with the backtrace as per [CLC proposal #202](https://github.com/haskell/core-libraries-committee/issues/202) (introduces `WhileHandling` and modifies such as `catch` and `onException` accordingly to propagate or rethrow exceptions)+  * Introduced `catchNoPropagate`, `rethrowIO` and `tryWithContext` as part of+      [CLC proposal #202](https://github.com/haskell/core-libraries-committee/issues/202) to+      facilitate *re*throwing exceptions without adding a `WhileHandling`+      context -- if *re*throwing `e`, you don't want to add `WhileHandling e` to+      the context since it will be redundant. These functions are mostly useful+      for libraries that define exception-handling combinators like `catch` and+      `onException`, such as `base`, or the `exceptions` package.+  * Move `Lift ByteArray` and `Lift Fixed` instances into `base` from `template-haskell`. See [CLC proposal #287](https://github.com/haskell/core-libraries-committee/issues/287).+  * Make `Debug.Trace.{traceEventIO,traceMarkerIO}` faster when tracing is disabled. See [CLC proposal #291](https://github.com/haskell/core-libraries-committee/issues/291).+  * The exception messages were improved according to [CLC proposal #285](https://github.com/haskell/core-libraries-committee/issues/285). In particular:+      * Improve the message of the uncaught exception handler+      * Make `displayException (SomeException e) = displayException e`. The+          additional information that is printed when exceptions are surfaced to+          the top-level is added by `uncaughtExceptionHandler`.+      * Get rid of the HasCallStack mechanism manually propagated by `ErrorCall`+          in favour of the more general HasCallStack exception backtrace+          mechanism, to remove duplicate call stacks for uncaught exceptions.+      * Freeze the callstack of `error`, `undefined`, `throwIO`, `ioException`,+          `ioError` to prevent leaking the implementation of these error functions+          into the callstack.++## 4.20.0.0 *May 2024*+  * Shipped with GHC 9.10.1+  * Introduce `Data.Enum` module exporting both `Enum` and `Bounded`. Note that the export of `Bounded` will be deprecated in a future release ([CLC proposal #208](https://github.com/haskell/core-libraries-committee/issues/208))+  * Deprecate `GHC.Pack` ([#21461](https://gitlab.haskell.org/ghc/ghc/-/issues/21461))+  * Export `foldl'` from `Prelude` ([CLC proposal #167](https://github.com/haskell/core-libraries-committee/issues/167))+  * The top-level handler for uncaught exceptions now displays the output of `displayException` rather than `show`  ([CLC proposal #198](https://github.com/haskell/core-libraries-committee/issues/198))+  * Add `permutations` and `permutations1` to `Data.List.NonEmpty` ([CLC proposal #68](https://github.com/haskell/core-libraries-committee/issues/68))+  * Add a `RULE` to `Prelude.lookup`, allowing it to participate in list fusion ([CLC proposal #175](https://github.com/haskell/core-libraries-committee/issues/175))+  * Implement `stimes` for `instance Semigroup (Endo a)` explicitly ([CLC proposal #4](https://github.com/haskell/core-libraries-committee/issues/4))+  * Add `startTimeProfileAtStartup` to `GHC.RTS.Flags` to expose new RTS flag+    `--no-automatic-heap-samples` in the Haskell API ([CLC proposal #243](https://github.com/haskell/core-libraries-committee/issues/243)).+  * Implement `sconcat` for `instance Semigroup Data.Semigroup.First` and `instance Semigroup Data.Monoid.First` explicitly, increasing laziness ([CLC proposal #246](https://github.com/haskell/core-libraries-committee/issues/246))+  * Add laws relating between `Foldable` / `Traversable` with `Bifoldable` / `Bitraversable` ([CLC proposal #205](https://github.com/haskell/core-libraries-committee/issues/205))+  * The `Enum Int64` and `Enum Word64` instances now use native operations on 32-bit platforms, increasing performance by up to 1.5x on i386 and up to 5.6x with the JavaScript backend. ([CLC proposal #187](https://github.com/haskell/core-libraries-committee/issues/187))+  * Exceptions can now be decorated with user-defined annotations via `ExceptionContext` ([CLC proposal #200](https://github.com/haskell/core-libraries-committee/issues/200))+  * Exceptions now capture backtrace information via their `ExceptionContext`. GHC+    supports several mechanisms by which backtraces can be collected which can be+    individually enabled and disabled via+    `GHC.Exception.Backtrace.setBacktraceMechanismState` ([CLC proposal #199](https://github.com/haskell/core-libraries-committee/issues/199))+  * Add `HasCallStack` constraint to `Control.Exception.throw{,IO}` ([CLC proposal #201](https://github.com/haskell/core-libraries-committee/issues/201))+  * Update to [Unicode 15.1.0](https://www.unicode.org/versions/Unicode15.1.0/).+  * Fix `withFile`, `withFileBlocking`, and `withBinaryFile` to not incorrectly annotate exceptions raised in wrapped computation. ([CLC proposal #237](https://github.com/haskell/core-libraries-committee/issues/237))+  * Fix `fdIsNonBlocking` to always be `0` for regular files and block devices on unix, regardless of `O_NONBLOCK`+  * Always use `safe` call to `read` for regular files and block devices on unix if the RTS is multi-threaded, regardless of `O_NONBLOCK`.+    ([CLC proposal #166](https://github.com/haskell/core-libraries-committee/issues/166))+  * Export List from Data.List ([CLC proposal #182](https://github.com/haskell/core-libraries-committee/issues/182)).+  * Add `{-# WARNING in "x-data-list-nonempty-unzip" #-}` to `Data.List.NonEmpty.unzip`.+    Use `{-# OPTIONS_GHC -Wno-x-data-list-nonempty-unzip #-}` to disable it.+     ([CLC proposal #86](https://github.com/haskell/core-libraries-committee/issues/86)+     and [CLC proposal #258](https://github.com/haskell/core-libraries-committee/issues/258))+  * Add `System.Mem.performMajorGC` ([CLC proposal #230](https://github.com/haskell/core-libraries-committee/issues/230))+  * Fix exponent overflow/underflow bugs in the `Read` instances for `Float` and `Double` ([CLC proposal #192](https://github.com/haskell/core-libraries-committee/issues/192))+  * `Foreign.C.Error.errnoToIOError` now uses the reentrant `strerror_r` to render system errors when possible ([CLC proposal #249](https://github.com/haskell/core-libraries-committee/issues/249))+  * Implement `many` and `some` methods of `instance Alternative (Compose f g)` explicitly. ([CLC proposal #181](https://github.com/haskell/core-libraries-committee/issues/181))+  * Change the types of the `GHC.Stack.StackEntry.closureType` and `GHC.InfoProv.InfoProv.ipDesc` record fields to use `GHC.Exts.Heap.ClosureType` rather than an `Int`.+    To recover the old value use `fromEnum`. ([CLC proposal #210](https://github.com/haskell/core-libraries-committee/issues/210))+  * The functions `GHC.Exts.dataToTag#` and `GHC.Base.getTag` have had+    their types changed to the following:++    ```haskell+    dataToTag#, getTag+      :: forall {lev :: Levity} (a :: TYPE (BoxedRep lev))+      .  DataToTag a => a -> Int#+    ```++    In particular, they are now applicable only at some (not all)+    lifted types.  However, if `t` is an algebraic data type (i.e. `t`+    matches a `data` or `data instance` declaration) with all of its+    constructors in scope and the levity of `t` is statically known,+    then the constraint `DataToTag t` can always be solved.+    ([CLC proposal #104](https://github.com/haskell/core-libraries-committee/issues/104))+  * `GHC.Exts` no longer exports the GHC-internal `whereFrom#` primop ([CLC proposal #214](https://github.com/haskell/core-libraries-committee/issues/214))+  * `GHC.InfoProv.InfoProv` now provides a `ipUnitId :: String` field encoding the unit ID of the unit defining the info table ([CLC proposal #214](https://github.com/haskell/core-libraries-committee/issues/214))+  * Add `sortOn` to `Data.List.NonEmpty`+    ([CLC proposal #227](https://github.com/haskell/core-libraries-committee/issues/227))+  * Add more instances for `Compose`: `Fractional`, `RealFrac`, `Floating`, `RealFloat` ([CLC proposal #226](https://github.com/haskell/core-libraries-committee/issues/226))+  * Treat all FDs as "nonblocking" on wasm32 ([CLC proposal #234](https://github.com/haskell/core-libraries-committee/issues/234))+  * Add `HeapByEra`, `eraSelector` and `automaticEraIncrement` to `GHC.RTS.Flags` to+    reflect the new RTS flags: `-he` profiling mode, `-he` selector and `--automatic-era-increment`.+    ([CLC proposal #254](https://github.com/haskell/core-libraries-committee/issues/254))+  * Document that certain modules are unstable and not meant to be consumed by the general public ([CLC proposal #146](https://github.com/haskell/core-libraries-committee/issues/146))+  * Add unaligned `Addr#` primops ([CLC proposal #154](https://github.com/haskell/core-libraries-committee/issues/154))+  * Deprecate `stgDoubleToWord{32,64}` and `stgWord{32,64}ToDouble` in favor of new primops `castDoubleToWord{32,64}#` and `castWord{32,64}ToDouble#` ([CLC proposal #253](https://github.com/haskell/core-libraries-committee/issues/253))+  * Add `unsafeThawByteArray#`, opposite to the existing `unsafeFreezeByteArray#` ([CLC proposal #184](https://github.com/haskell/core-libraries-committee/issues/184))++## 4.19.0.0 *October 2023*+  * Shipped with GHC 9.8.1+  * Add `{-# WARNING in "x-partial" #-}` to `Data.List.{head,tail}`.+    Use `{-# OPTIONS_GHC -Wno-x-partial #-}` to disable it.+    ([CLC proposal #87](https://github.com/haskell/core-libraries-committee/issues/87) and [#114](https://github.com/haskell/core-libraries-committee/issues/114))+  * Add `fromThreadId :: ThreadId -> Word64` to `GHC.Conc.Sync`, which maps a thread to a per-process-unique identifier ([CLC proposal #117](https://github.com/haskell/core-libraries-committee/issues/117))+  * Add `Data.List.!?` ([CLC proposal #110](https://github.com/haskell/core-libraries-committee/issues/110))+  * Mark `maximumBy`/`minimumBy` as `INLINE` improving performance for unpackable+    types significantly.+  * Add INLINABLE pragmas to `generic*` functions in Data.OldList ([CLC proposal #129](https://github.com/haskell/core-libraries-committee/issues/130))+  * Export `getSolo` from `Data.Tuple`.+      ([CLC proposal #113](https://github.com/haskell/core-libraries-committee/issues/113))+  * Add `Type.Reflection.decTypeRep`, `Data.Typeable.decT` and `Data.Typeable.hdecT` equality decisions functions.+      ([CLC proposal #98](https://github.com/haskell/core-libraries-committee/issues/98))+  * Add `Data.Functor.unzip` ([CLC proposal #88](https://github.com/haskell/core-libraries-committee/issues/88))+  * Add `System.Mem.Weak.{get,set}FinalizerExceptionHandler`, which allows the user to set the global handler invoked by when a `Weak` pointer finalizer throws an exception. ([CLC proposal #126](https://github.com/haskell/core-libraries-committee/issues/126))+  * Add `System.Mem.Weak.printToHandleFinalizerExceptionHandler`, which can be used with `setFinalizerExceptionHandler` to print exceptions thrown by finalizers to the given `Handle`. ([CLC proposal #126](https://github.com/haskell/core-libraries-committee/issues/126))+  * Add `Data.List.unsnoc` ([CLC proposal #165](https://github.com/haskell/core-libraries-committee/issues/165))+  * Implement more members of `instance Foldable (Compose f g)` explicitly.+      ([CLC proposal #57](https://github.com/haskell/core-libraries-committee/issues/57))+  * Add `Eq` and `Ord` instances for `SSymbol`, `SChar`, and `SNat`.+      ([CLC proposal #148](https://github.com/haskell/core-libraries-committee/issues/148))+  * Add `COMPLETE` pragmas to the `TypeRep`, `SSymbol`, `SChar`, and `SNat` pattern synonyms.+      ([CLC proposal #149](https://github.com/haskell/core-libraries-committee/issues/149))+  * Make `($)` representation polymorphic ([CLC proposal #132](https://github.com/haskell/core-libraries-committee/issues/132))+  * Implement [GHC Proposal #433](https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0433-unsatisfiable.rst),+    adding the class `Unsatisfiable :: ErrorMessage -> TypeError` to `GHC.TypeError`,+    which provides a mechanism for custom type errors that reports the errors in+    a more predictable behaviour than `TypeError`.+  * Add more instances for `Compose`: `Enum`, `Bounded`, `Num`, `Real`, `Integral` ([CLC proposal #160](https://github.com/haskell/core-libraries-committee/issues/160))+  * Make `(&)` representation polymorphic in the return type ([CLC proposal #158](https://github.com/haskell/core-libraries-committee/issues/158))+  * Implement `GHC.IORef.atomicSwapIORef` via a new dedicated primop `atomicSwapMutVar#` ([CLC proposal #139](https://github.com/haskell/core-libraries-committee/issues/139))+  * Change `BufferCodec` to use an unboxed implementation, while providing a compatibility layer using pattern synonyms. ([CLC proposal #134](https://github.com/haskell/core-libraries-committee/issues/134) and [#178](https://github.com/haskell/core-libraries-committee/issues/178))+  * Add nominal role annotations to `SNat` / `SSymbol` / `SChar` ([CLC proposal #170](https://github.com/haskell/core-libraries-committee/issues/170))+  * Make `Semigroup`'s `stimes` specializable. ([CLC proposal #8](https://github.com/haskell/core-libraries-committee/issues/8))+  * Implement `copyBytes`, `fillBytes`, `moveBytes` and `stimes` for `Data.Array.Byte.ByteArray` using primops ([CLC proposal #188](https://github.com/haskell/core-libraries-committee/issues/188))+  * Add rewrite rules for conversion between `Int64` / `Word64` and `Float` / `Double` on 64-bit architectures ([CLC proposal #203](https://github.com/haskell/core-libraries-committee/issues/203)).+  * `Generic` instances for tuples now expose `Unit`, `Tuple2`, `Tuple3`, ..., `Tuple64` as the actual names for tuple type constructors ([GHC proposal #475](https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0475-tuple-syntax.rst)).+  * Reject `FilePath`s containing interior `NUL`s ([CLC proposal #144](https://github.com/haskell/core-libraries-committee/issues/144))+  * Add `GHC.JS.Foreign.Callback` module for JavaScript backend ([CLC proposal #150](https://github.com/haskell/core-libraries-committee/issues/150))+  * Generalize the type of `keepAlive#` and `touch#` ([CLC proposal #152](https://github.com/haskell/core-libraries-committee/issues/152))++## 4.18.0.0 *March 2023*+  * Shipped with GHC 9.6.1+  * `Foreign.C.ConstPtr.ConstrPtr` was added to encode `const`-qualified+    pointer types in foreign declarations when using `CApiFFI` extension. ([CLC proposal #117](https://github.com/haskell/core-libraries-committee/issues/117))+  * Add `forall a. Functor (p a)` superclass for `Bifunctor p` ([CLC proposal #91](https://github.com/haskell/core-libraries-committee/issues/91))+  * Add `forall a. Functor (p a)` superclass for `Bifunctor p`.+  * Add Functor instances for `(,,,,) a b c d`, `(,,,,,) a b c d e` and+    `(,,,,,) a b c d e f`.+  * Exceptions thrown by weak pointer finalizers can now be reported by setting+    a global exception handler, using `System.Mem.Weak.setFinalizerExceptionHandler`.+    The default behaviour is unchanged (exceptions are ignored and not reported).+  * `Numeric.Natural` re-exports `GHC.Natural.minusNaturalMaybe`+    ([CLC proposal #45](https://github.com/haskell/core-libraries-committee/issues/45))+  * Add `Data.Foldable1` and `Data.Bifoldable1`+    ([CLC proposal #9](https://github.com/haskell/core-libraries-committee/issues/9))+  * Add `applyWhen` to `Data.Function`+    ([CLC proposal #71](https://github.com/haskell/core-libraries-committee/issues/71))+  * Add functions `mapAccumM` and `forAccumM` to `Data.Traversable`+    ([CLC proposal #65](https://github.com/haskell/core-libraries-committee/issues/65))+  * Add default implementation of `(<>)` in terms of `sconcat` and `mempty` in+    terms of `mconcat` ([CLC proposal #61](https://github.com/haskell/core-libraries-committee/issues/61)).+  * `GHC.Conc.Sync.listThreads` was added, allowing the user to list the threads+    (both running and blocked) of the program.+  * `GHC.Conc.Sync.labelThreadByteArray#` was added, allowing the user to specify+    a thread label by way of a `ByteArray#` containing a UTF-8-encoded string.+    The old `GHC.Conc.Sync.labelThread` is now implemented in terms of this+    function.+  * `GHC.Conc.Sync.threadLabel` was added, allowing the user to query the label+    of a given `ThreadId`.+  * Add `inits1` and `tails1` to `Data.List.NonEmpty`+    ([CLC proposal #67](https://github.com/haskell/core-libraries-committee/issues/67))+  * Change default `Ord` implementation of `(>=)`, `(>)`, and `(<)` to use+    `(<=)` instead of `compare` ([CLC proposal #24](https://github.com/haskell/core-libraries-committee/issues/24)).+  * Export `liftA2` from `Prelude`. This means that the entirety of `Applicative`+    is now exported from `Prelude`+    ([CLC proposal #50](https://github.com/haskell/core-libraries-committee/issues/50),+    [the migration+    guide](https://github.com/haskell/core-libraries-committee/blob/main/guides/export-lifta2-prelude.md))+  * Switch to a pure Haskell implementation of `GHC.Unicode`+    ([CLC proposals #59](https://github.com/haskell/core-libraries-committee/issues/59)+    and [#130](https://github.com/haskell/core-libraries-committee/issues/130))+  * Update to [Unicode 15.0.0](https://www.unicode.org/versions/Unicode15.0.0/).+  * Add standard Unicode case predicates `isUpperCase` and `isLowerCase` to+    `GHC.Unicode` and `Data.Char`. These predicates use the standard Unicode+    case properties and are more intuitive than `isUpper` and `isLower`+    ([CLC proposal #90](https://github.com/haskell/core-libraries-committee/issues/90))+  * Add `Eq` and `Ord` instances for `Generically1`.+  * Relax instances for Functor combinators; put superclass on Class1 and Class2+    to make non-breaking ([CLC proposal #10](https://github.com/haskell/core-libraries-committee/issues/10),+    [migration guide](https://github.com/haskell/core-libraries-committee/blob/main/guides/functor-combinator-instances-and-class1s.md))+  * Add `gcdetails_block_fragmentation_bytes` to `GHC.Stats.GCDetails` to track heap fragmentation.+  * `GHC.TypeLits` and `GHC.TypeNats` now export the `natSing`, `symbolSing`,+    and `charSing` methods of `KnownNat`, `KnownSymbol`, and `KnownChar`,+    respectively. They also export the `SNat`, `SSymbol`, and `SChar` types+    that are used in these methods and provide an API to interact with these+    types, per+    [CLC proposal #85](https://github.com/haskell/core-libraries-committee/issues/85).+  * The `Enum` instance of `Down a` now enumerates values in the opposite+    order as the `Enum a` instance ([CLC proposal #51](https://github.com/haskell/core-libraries-committee/issues/51))+  * `Foreign.Marshal.Pool` now uses the RTS internal arena instead of libc+    `malloc` for allocation. It avoids the O(n) overhead of maintaining a list+    of individually allocated pointers as well as freeing each one of them when+    freeing a `Pool` (#14762, #18338)+  * `Type.Reflection.Unsafe` is now marked as unsafe.+  * Add `Data.Typeable.heqT`, a kind-heterogeneous version of+    `Data.Typeable.eqT`+    ([CLC proposal #99](https://github.com/haskell/core-libraries-committee/issues/99))+  * Various declarations GHC's new info-table provenance feature have been+    moved from `GHC.Stack.CCS` to a new `GHC.InfoProv` module:+    * The `InfoProv`, along its `ipName`, `ipDesc`, `ipTyDesc`, `ipLabel`,+      `ipMod`, and `ipLoc` fields, have been moved.+    * `InfoProv` now has additional `ipSrcFile` and `ipSrcSpan` fields. `ipLoc`+      is now a function computed from these fields.+    * The `whereFrom` function has been moved+  * Add functions `traceWith`, `traceShowWith`, `traceEventWith` to+    `Debug.Trace`, per+    [CLC proposal #36](https://github.com/haskell/core-libraries-committee/issues/36).+  * Export `List` from `GHC.List`+    ([CLC proposal #186](https://github.com/haskell/core-libraries-committee/issues/186)).++## 4.17.0.0 *August 2022*++  * Shipped with GHC 9.4.1++  * Add explicitly bidirectional `pattern TypeRep` to `Type.Reflection`.++  * Add `Generically` and `Generically1` to `GHC.Generics` for deriving generic+    instances with `DerivingVia`. `Generically` instances include `Semigroup` and+    `Monoid`. `Generically1` instances: `Functor`, `Applicative`, `Alternative`,+    `Eq1` and `Ord1`.++  * Introduce `GHC.ExecutablePath.executablePath`, which is more robust than+    `getExecutablePath` in cases when the executable has been deleted.++  * Add `Data.Array.Byte` module, providing boxed `ByteArray#` and `MutableByteArray#` wrappers.++  * `fromEnum` for `Natural` now throws an error for any number that cannot be+    repesented exactly by an `Int` (#20291).++  * `returnA` is defined as `Control.Category.id` instead of `arr id`.++  * Added symbolic synonyms for `xor` and shift operators to `Data.Bits`:++    - `.^.` (`xor`),+    - `.>>.` and `!>>.` (`shiftR` and `unsafeShiftR`),+    - `.<<.` and `!<<.` (`shiftL` and `unsafeShiftL`).++    These new operators have the same fixity as the originals.++  * `GHC.Exts` now re-exports `Multiplicity` and `MultMul`.++  * A large number of partial functions in `Data.List` and `Data.List.NonEmpty` now+    have an HasCallStack constraint. Hopefully providing better error messages in case+    they are used in unexpected ways.++  * Fix the `Ord1` instance for `Data.Ord.Down` to reverse sort order.++  * Any Haskell type that wraps a C pointer type has been changed from+    `Ptr ()` to `CUIntPtr`. For typical glibc based platforms, the+    affected type is `CTimer`.++  * Remove instances of `MonadFail` for the `ST` monad (lazy and strict) as per+    the [Core Libraries proposal](https://github.com/haskell/core-libraries-committee/issues/33).+    A [migration guide](https://github.com/haskell/core-libraries-committee/blob/main/guides/no-monadfail-st-inst.md)+    is available.++  * Re-export `augment` and `build` function from `GHC.List`++  * Re-export the `IsList` typeclass from the new `GHC.IsList` module.++  * There's a new special function `withDict` in `GHC.Exts`: ::++        withDict :: forall {rr :: RuntimeRep} cls meth (r :: TYPE rr). WithDict cls meth => meth -> (cls => r) -> r++    where `cls` must be a class containing exactly one method, whose type+    must be `meth`.++    This function converts `meth` to a type class dictionary.+    It removes the need for `unsafeCoerce` in implementation of reflection+    libraries. It should be used with care, because it can introduce+    incoherent instances.++    For example, the `withTypeable` function from the+    `Type.Reflection` module can now be defined as: ::++          withTypeable :: forall k (a :: k) rep (r :: TYPE rep). ()+                       => TypeRep a -> (Typeable a => r) -> r+          withTypeable rep k = withDict @(Typeable a) rep k++    Note that the explicit type application is required, as the call to+    `withDict` would be ambiguous otherwise.++    This replaces the old `GHC.Exts.magicDict`, which required+    an intermediate data type and was less reliable.++  * `Data.Word.Word64` and `Data.Int.Int64` are now always represented by+    `Word64#` and `Int64#`, respectively. Previously on 32-bit platforms these+    were rather represented by `Word#` and `Int#`. See GHC #11953.++  * Add `GHC.TypeError` module to contain functionality related to custom type+    errors. `TypeError` is re-exported from `GHC.TypeLits` for backwards+    compatibility.++  * Comparison constraints in `Data.Type.Ord` (e.g. `<=`) now use the new+    `GHC.TypeError.Assert` type family instead of type equality with `~`.++## 4.16.3.0 *May 2022*++  * Shipped with GHC 9.2.4++  * winio: make `consoleReadNonBlocking` not wait for any events at all.++  * winio: Add support to console handles to `handleToHANDLE`++## 4.16.2.0 *May 2022*++  * Shipped with GHC 9.2.2++  * Export `GHC.Event.Internal` on Windows (#21245)++  * Documentation Fixes++## 4.16.1.0 *Feb 2022*++  * Shipped with GHC 9.2.2++  * The following Foreign C types now have an instance of `Ix`:+    CChar, CSChar, CUChar, CShort, CUShort, CInt, CUInt, CLong, CULong,+    CPtrdiff, CSize, CWchar, CSigAtomic, CLLong, CULLong, CBool, CIntPtr, CUIntPtr,+    CIntMax, CUIntMax.++## 4.16.0.0 *Nov 2021*++  * Shipped with GHC 9.2.1++  * The unary tuple type, `Solo`, is now exported by `Data.Tuple`.++  * Add a `Typeable` constraint to `fromStaticPtr` in the class `GHC.StaticPtr.IsStatic`.++  * Make it possible to promote `Natural`s and remove the separate `Nat` kind.+    For backwards compatibility, `Nat` is now a type synonym for `Natural`.+    As a consequence, one must enable `TypeSynonymInstances`+    in order to define instances for `Nat`. Also, different instances for `Nat` and `Natural`+    won't typecheck anymore.++  * Add `Data.Type.Ord` as a module for type-level comparison operations.  The+    `(<=?)` type operator from `GHC.TypeNats`, previously kind-specific to+    `Nat`, is now kind-polymorphic and governed by the `Compare` type family in+    `Data.Type.Ord`.  Note that this means GHC will no longer deduce `0 <= n`+    for all `n` any more.++  * Add `cmpNat`, `cmpSymbol`, and `cmpChar` to `GHC.TypeNats` and `GHC.TypeLits`.++  * Add `CmpChar`, `ConsSymbol`, `UnconsSymbol`, `CharToNat`, and `NatToChar`+    type families to `GHC.TypeLits`.++  * Add the `KnownChar` class, `charVal` and `charVal'` to `GHC.TypeLits`.++  * Add `Semigroup` and `Monoid` instances for `Data.Functor.Product` and+    `Data.Functor.Compose`.++  * Add `Functor`, `Applicative`, `Monad`, `MonadFix`, `Foldable`, `Traversable`,+    `Eq`, `Ord`, `Show`, `Read`, `Eq1`, `Ord1`, `Show1`, `Read1`, `Generic`,+    `Generic1`, and `Data` instances for `GHC.Tuple.Solo`.++  * Add `Eq1`, `Read1` and `Show1` instances for `Complex`;+    add `Eq1/2`, `Ord1/2`, `Show1/2` and `Read1/2` instances for 3 and 4-tuples.++  * Remove `Data.Semigroup.Option` and the accompanying `option` function.++  * Make `allocaBytesAligned` and `alloca` throw an IOError when the+    alignment is not a power-of-two. The underlying primop+    `newAlignedPinnedByteArray#` actually always assumed this but we didn't+    document this fact in the user facing API until now.++    `Generic1`, and `Data` instances for `GHC.Tuple.Solo`.++  * Under POSIX, `System.IO.openFile` will no longer leak a file descriptor if it+    is interrupted by an asynchronous exception (#19114, #19115).++  * Additionally export `asum` from `Control.Applicative`++  * `fromInteger :: Integer -> Float/Double` now consistently round to the+    nearest value, with ties to even.++  * Additions to `Data.Bits`:++    - Newtypes `And`, `Ior`, `Xor` and `Iff` which wrap their argument,+      and whose `Semigroup` instances are defined using `(.&.)`, `(.|.)`, `xor`+      and `\x y -> complement (x `xor` y)`, respectively.++    - `oneBits :: FiniteBits a => a`, `oneBits = complement zeroBits`.++  * Various folding operations in `GHC.List` are now implemented via strict+    folds:+    - `sum`+    - `product`+    - `maximum`+    - `minimum`++## 4.15.0.0 *Feb 2021*++  * Shipped with GHC 9.0.1++  * `openFile` now calls the `open` system call with an `interruptible` FFI+    call, ensuring that the call can be interrupted with `SIGINT` on POSIX+    systems.++  * Make `openFile` more tolerant of asynchronous exceptions: more care taken+    to release the file descriptor and the read/write lock (#18832)++  * Add `hGetContents'`, `getContents'`, and `readFile'` in `System.IO`:+    Strict IO variants of `hGetContents`, `getContents`, and `readFile`.++  * Add `singleton` function for `Data.List.NonEmpty`.++  * The planned deprecation of `Data.Monoid.First` and `Data.Monoid.Last`+    is scrapped due to difficulties with the suggested migration path.++  * `Data.Semigroup.Option` and the accompanying `option` function are+    deprecated and scheduled for removal in 4.16.++  * Add `Generic` instances to `Fingerprint`, `GiveGCStats`, `GCFlags`,+    `ConcFlags`, `DebugFlags`, `CCFlags`, `DoHeapProfile`, `ProfFlags`,+    `DoTrace`, `TraceFlags`, `TickyFlags`, `ParFlags`, `RTSFlags`, `RTSStats`,+    `GCStats`, `ByteOrder`, `GeneralCategory`, `SrcLoc`++  * Add rules `unpackUtf8`, `unpack-listUtf8` and `unpack-appendUtf8` to `GHC.Base`.+    They correspond to their ascii versions and hopefully make it easier+    for libraries to handle utf8 encoded strings efficiently.++  * An issue with list fusion and `elem` was fixed. `elem` applied to known+    small lists will now compile to a simple case statement more often.++  * Add `MonadFix` and `MonadZip` instances for `Complex`++  * Add `Ix` instances for tuples of size 6 through 15++  * Correct `Bounded` instance and remove `Enum` and `Integral` instances for+    `Data.Ord.Down`.++  * `catMaybes` is now implemented using `mapMaybe`, so that it is both a "good+    consumer" and "good producer" for list-fusion (#18574)++  * `Foreign.ForeignPtr.withForeignPtr` is now less aggressively optimised,+    avoiding the soundness issue reported in+    [#17760](https://gitlab.haskell.org/ghc/ghc/-/issues/17760) in exchange for+    a small amount more allocation. If your application regresses significantly+    *and* the continuation given to `withForeignPtr` will *not* provably+    diverge then the previous optimisation behavior can be recovered by instead+    using `GHC.ForeignPtr.unsafeWithForeignPtr`.++  * Correct `Bounded` instance and remove `Enum` and `Integral` instances for+    `Data.Ord.Down`.++  * `Data.Foldable` methods `maximum{,By}`, `minimum{,By}`, `product` and `sum`+    are now stricter by default, as well as in the class implementation for List.++## 4.14.0.0 *Jan 2020*+  * Bundled with GHC 8.10.1++  * Add a `TestEquality` instance for the `Compose` newtype.++  * `Data.Ord.Down` now has a field name, `getDown`++  * Add `Bits`, `Bounded`, `Enum`, `FiniteBits`, `Floating`, `Fractional`,+    `Integral`, `Ix`, `Real`, `RealFrac`, `RealFloat` and `Storable` instances+    to `Data.Ord.Down`.++  * Fix the `integer-gmp` variant of `isValidNatural`: Previously it would fail+    to detect values `<= maxBound::Word` that were incorrectly encoded using+    the `NatJ#` constructor.++  * The type of `coerce` has been generalized. It is now runtime-representation+    polymorphic:+    `forall {r :: RuntimeRep} (a :: TYPE r) (b :: TYPE r). Coercible a b => a -> b`.+    The type argument `r` is marked as `Inferred` to prevent it from+    interfering with visible type application.++  * Make `Fixed` and `HasResolution` poly-kinded.++  * Add `HasResolution` instances for `Nat`s.++  * Add `Functor`, `Applicative`, `Monad`, `Alternative`, `MonadPlus`,+    `Generic` and `Generic1` instances to `Kleisli`++  * `openTempFile` is now fully atomic and thread-safe on Windows.++  * Add `isResourceVanishedError`, `resourceVanishedErrorType`, and+    `isResourceVanishedErrorType` to `System.IO.Error`.++  * Add newtypes for `CSocklen` (`socklen_t`) and `CNfds` (`nfds_t`) to+    `System.Posix.Types`.++  * Add `Functor`, `Applicative` and `Monad` instances to `(,,) a b`+    and `(,,,) a b c`.++  * Add `resizeSmallMutableArray#` to `GHC.Exts`.++  * Add a `Data` instance to `WrappedArrow`, `WrappedMonad`, and `ZipList`.++  * Add `IsList` instance for `ZipList`.++## 4.13.0.0 *July 2019*+  * Bundled with GHC 8.8.1++  * The final phase of the `MonadFail` proposal has been implemented:++    * The `fail` method of `Monad` has been removed in favor of the method of+      the same name in the `MonadFail` class.++    * `MonadFail(fail)` is now re-exported from the `Prelude` and+      `Control.Monad` modules.++  * Fix `Show` instance of `Data.Fixed`: Negative numbers are now parenthesized+    according to their surrounding context. I.e. `Data.Fixed.show` produces+    syntactically correct Haskell for expressions like `Just (-1 :: Fixed E2)`.+    (#16031)++  * Support the characters from recent versions of Unicode (up to v. 12) in+    literals (#5518).++  * The `StableName` type parameter now has a phantom role instead of+    a representational one. There is really no reason to care about the+    type of the underlying object.++  * Add `foldMap'`, a strict version of `foldMap`, to `Foldable`.++  * The `shiftL` and `shiftR` methods in the `Bits` instances of `Int`, `IntN`,+    `Word`, and `WordN` now throw an overflow exception for negative shift+    values (instead of being undefined behaviour).++  * `scanr` no longer crashes when passed a fusable, infinite list. (#16943)++## 4.12.0.0 *21 September 2018*+  * Bundled with GHC 8.6.1++  * The STM invariant-checking mechanism (`always` and `alwaysSucceeds`), which+    was deprecated in GHC 8.4, has been removed (as proposed in+    <https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0011-deprecate-stm-invariants.rst>).+    This is a bit earlier than proposed in the deprecation pragma included in+    GHC 8.4, but due to community feedback we decided to move ahead with the+    early removal.++    Existing users are encouraged to encapsulate their STM operations in safe+    abstractions which can perform the invariant checking without help from the+    runtime system.++  * Add a new module `GHC.ResponseFile` (previously defined in the `haddock`+    package). (#13896)++  * Move the module `Data.Functor.Contravariant` from the+    `contravariant` package to `base`.++  * `($!)` is now representation-polymorphic like `($)`.++  * Add `Applicative` (for `K1`), `Semigroup` and `Monoid` instances in+    `GHC.Generics`. (#14849)++  * `asinh` for `Float` and `Double` is now numerically stable in the face of+    non-small negative arguments and enormous arguments of either sign. (#14927)++  * `Numeric.showEFloat (Just 0)` now respects the user's requested precision.+    (#15115)++  * `Data.Monoid.Alt` now has `Foldable` and `Traversable` instances. (#15099)++  * `Data.Monoid.Ap` has been introduced++  * `Control.Exception.throw` is now levity polymorphic. (#15180)++  * `Data.Ord.Down` now has a number of new instances. These include:+    `MonadFix`, `MonadZip`, `Data`, `Foldable`, `Traversable`, `Eq1`, `Ord1`,+    `Read1`, `Show1`, `Generic`, `Generic1`. (#15098)+++## 4.11.1.0 *19 April 2018*+  * Bundled with GHC 8.4.2++  * Add the `readFieldHash` function to `GHC.Read` which behaves like+    `readField`, but for a field that ends with a `#` symbol (#14918).++## 4.11.0.0 *8 March 2018*+  * Bundled with GHC 8.4.1++  * `System.IO.openTempFile` is now thread-safe on Windows.++  * Deprecated `GHC.Stats.GCStats` interface has been removed.++  * Add `showHFloat` to `Numeric`++  * Add `Div`, `Mod`, and `Log2` functions on type-level naturals+    in `GHC.TypeLits`.++  * Add `Alternative` instance for `ZipList` (#13520)++  * Add instances `Num`, `Functor`, `Applicative`, `Monad`, `Semigroup`+    and `Monoid` for `Data.Ord.Down` (#13097).++  * Add `Semigroup` instance for `EventLifetime`.++  * Make `Semigroup` a superclass of `Monoid`;+    export `Semigroup((<>))` from `Prelude`; remove `Monoid` reexport+    from `Data.Semigroup` (#14191).++  * Generalise `instance Monoid a => Monoid (Maybe a)` to+    `instance Semigroup a => Monoid (Maybe a)`.++  * Add `infixl 9 !!` declaration for `Data.List.NonEmpty.!!`++  * Add `<&>` operator to `Data.Functor` (#14029)++  * Remove the deprecated `Typeable{1..7}` type synonyms (#14047)++  * Make `Data.Type.Equality.==` a closed type family. It now works for all+  kinds out of the box. Any modules that previously declared instances of this+  family will need to remove them. Whereas the previous definition was somewhat+  ad hoc, the behavior is now completely uniform. As a result, some applications+  that used to reduce no longer do, and conversely. Most notably, `(==)` no+  longer treats the `*`, `j -> k`, or `()` kinds specially; equality is+  tested structurally in all cases.++  * Add instances `Semigroup` and `Monoid` for `Control.Monad.ST` (#14107).++  * The `Read` instances for `Proxy`, `Coercion`, `(:~:)`, `(:~~:)`, and `U1`+    now ignore the parsing precedence. The effect of this is that `read` will+    be able to successfully parse more strings containing `"Proxy"` _et al._+    without surrounding parentheses (e.g., `"Thing Proxy"`) (#12874).++  * Add `iterate'`, a strict version of `iterate`, to `Data.List`+    and `Data.OldList` (#3474)++  * Add `Data` instances for `IntPtr` and `WordPtr` (#13115)++  * Add missing `MonadFail` instance for `Control.Monad.Strict.ST.ST`++  * Make `zipWith` and `zipWith3` inlinable (#14224)++  * `Type.Reflection.App` now matches on function types (fixes #14236)++  * `Type.Reflection.withTypeable` is now polymorphic in the `RuntimeRep` of+    its result.++  * Add `installSEHHandlers` to `MiscFlags` in `GHC.RTS.Flags` to determine if+    exception handling is enabled.++  * The deprecated functions `isEmptyChan` and `unGetChan` in+    `Control.Concurrent.Chan` have been removed (#13561).++  * Add `generateCrashDumpFile` to `MiscFlags` in `GHC.RTS.Flags` to determine+    if a core dump will be generated on crashes.++  * Add `generateStackTrace` to `MiscFlags` in `GHC.RTS.Flags` to determine if+    stack traces will be generated on unhandled exceptions by the RTS.++  * `getExecutablePath` now resolves symlinks on Windows (#14483)++  * Deprecated STM invariant checking primitives (`checkInv`, `always`, and+    `alwaysSucceeds`) in `GHC.Conc.Sync` (#14324).++  * Add a `FixIOException` data type to `Control.Exception.Base`, and change+    `fixIO` to throw that instead of a `BlockedIndefinitelyOnMVar` exception+    (#14356).++## 4.10.1.0 *November 2017*+  * Bundled with GHC 8.2.2++  * The file locking primitives provided by `GHC.IO.Handle` now use+    Linux open file descriptor locking if available.++  * Fixed bottoming definition of `clearBit` for `Natural`++## 4.10.0.0 *July 2017*+  * Bundled with GHC 8.2.1++  * `Data.Type.Bool.Not` given a type family dependency (#12057).++  * `Foreign.Ptr` now exports the constructors for `IntPtr` and `WordPtr`+    (#11983)++  * `Generic1`, as well as the associated datatypes and typeclasses in+    `GHC.Generics`, are now poly-kinded (#10604)++  * `New modules `Data.Bifoldable` and `Data.Bitraversable` (previously defined+    in the `bifunctors` package) (#10448)++  * `Data.Either` now provides `fromLeft` and `fromRight` (#12402)++  * `Data.Type.Coercion` now provides `gcoerceWith` (#12493)++  * New methods `liftReadList(2)` and `liftReadListPrec(2)` in the+    `Read1`/`Read2` classes that are defined in terms of `ReadPrec` instead of+    `ReadS`, as well as related combinators, have been added to+    `Data.Functor.Classes` (#12358)++  * Add `Semigroup` instance for `IO`, as well as for `Event` and `Lifetime`+    from `GHC.Event` (#12464)++  * Add `Data` instance for `Const` (#12438)++  * Added `Eq1`, `Ord1`, `Read1` and `Show1` instances for `NonEmpty`.++  * Add wrappers for `blksize_t`, `blkcnt_t`, `clockid_t`, `fsblkcnt_t`,+    `fsfilcnt_t`, `id_t`, `key_t`, and `timer_t` to System.Posix.Types (#12795)++  * Add `CBool`, a wrapper around C's `bool` type, to `Foreign.C.Types`+    (#13136)++  * Raw buffer operations in `GHC.IO.FD` are now strict in the buffer, offset, and length operations (#9696)++  * Add `plusForeignPtr` to `Foreign.ForeignPtr`.++  * Add `type family AppendSymbol (m :: Symbol) (n :: Symbol) :: Symbol` to `GHC.TypeLits`+    (#12162)++  * Add `GHC.TypeNats` module with `Natural`-based `KnownNat`. The `Nat`+    operations in `GHC.TypeLits` are a thin compatibility layer on top.+    Note: the `KnownNat` evidence is changed from an `Integer` to a `Natural`.++  * The type of `asProxyTypeOf` in `Data.Proxy` has been generalized (#12805)++  * `liftA2` is now a method of the `Applicative` class. `liftA2` and+    `<*>` each have a default implementation based on the other. Various+    library functions have been updated to use `liftA2` where it might offer+    some benefit. `liftA2` is not yet in the `Prelude`, and must currently be+    imported from `Control.Applicative`. It is likely to be added to the+    `Prelude` in the future. (#13191)++  * A new module, `Type.Reflection`, exposing GHC's new type-indexed type+    representation mechanism is now provided.++  * `Data.Dynamic` now exports the `Dyn` data constructor, enabled by the new+    type-indexed type representation mechanism.++  * `Data.Type.Equality` now provides a kind heterogeneous type equality+    evidence type, `(:~~:)`.++  * The `CostCentresXML` constructor of `GHC.RTS.Flags.DoCostCentres` has been+    replaced by `CostCentresJSON` due to the new JSON export format supported by+    the cost centre profiler.++  * The `ErrorCall` pattern synonym has been given a `COMPLETE` pragma so that+    functions which solely match again `ErrorCall` do not produce+    non-exhaustive pattern-match warnings (#8779)++  * Change the implementations of `maximumBy` and `minimumBy` from+    `Data.Foldable` to use `foldl1` instead of `foldr1`. This makes them run+    in constant space when applied to lists. (#10830)++  * `mkFunTy`, `mkAppTy`, and `mkTyConApp` from `Data.Typeable` no longer exist.+    This functionality is superceded by the interfaces provided by+    `Type.Reflection`.++  * `mkTyCon3` is no longer exported by `Data.Typeable`. This function is+    replaced by `Type.Reflection.Unsafe.mkTyCon`.++  * `Data.List.NonEmpty.unfold` has been deprecated in favor of `unfoldr`,+    which is functionally equivalent.++## 4.9.0.0  *May 2016*++  * Bundled with GHC 8.0++  * `error` and `undefined` now print a partial stack-trace alongside the error message.++  * New `errorWithoutStackTrace` function throws an error without printing the stack trace.++  * The restore operation provided by `mask` and `uninterruptibleMask` now+    restores the previous masking state whatever the current masking state is.++  * New `GHC.Generics.packageName` operation++  * Redesigned `GHC.Stack.CallStack` data type. As a result, `CallStack`'s+    `Show` instance produces different output, and `CallStack` no longer has an+    `Eq` instance.++  * New `GHC.Generics.packageName` operation++  * New `GHC.Stack.Types` module now contains the definition of+    `CallStack` and `SrcLoc`++  * New `GHC.Stack.Types.emptyCallStack` function builds an empty `CallStack`++  * New `GHC.Stack.Types.freezeCallStack` function freezes a `CallStack` preventing future `pushCallStack` operations from having any effect++  * New `GHC.Stack.Types.pushCallStack` function pushes a call-site onto a `CallStack`++  * New `GHC.Stack.Types.fromCallSiteList` function creates a `CallStack` from+    a list of call-sites (i.e., `[(String, SrcLoc)]`)++  * `GHC.SrcLoc` has been removed++  * `GHC.Stack.showCallStack` and `GHC.SrcLoc.showSrcLoc` are now called+    `GHC.Stack.prettyCallStack` and `GHC.Stack.prettySrcLoc` respectively++  * add `Data.List.NonEmpty` and `Data.Semigroup` (to become+    super-class of `Monoid` in the future). These modules were+    provided by the `semigroups` package previously. (#10365)++  * Add `selSourceUnpackedness`, `selSourceStrictness`, and+    `selDecidedStrictness`, three functions which look up strictness+    information of a field in a data constructor, to the `Selector` type class+    in `GHC.Generics` (#10716)++  * Add `URec`, `UAddr`, `UChar`, `UDouble`, `UFloat`, `UInt`, and `UWord` to+    `GHC.Generics` as part of making GHC generics capable of handling+    unlifted types (#10868)++  * The `Eq`, `Ord`, `Read`, and `Show` instances for `U1` now use lazier+    pattern-matching++  * Keep `shift{L,R}` on `Integer` with negative shift-arguments from+    segfaulting (#10571)++  * Add `forkOSWithUnmask` to `Control.Concurrent`, which is like+    `forkIOWithUnmask`, but the child is run in a bound thread.++  * The `MINIMAL` definition of `Arrow` is now `arr AND (first OR (***))`.++  * The `MINIMAL` definition of `ArrowChoice` is now `left OR (+++)`.++  * Exported `GiveGCStats`, `DoCostCentres`, `DoHeapProfile`, `DoTrace`,+    `RtsTime`, and `RtsNat` from `GHC.RTS.Flags`++  * New function `GHC.IO.interruptible` used to correctly implement+    `Control.Exception.allowInterrupt` (#9516)++  * Made `PatternMatchFail`, `RecSelError`, `RecConError`, `RecUpdError`,+    `NoMethodError`, and `AssertionFailed` newtypes (#10738)++  * New module `Control.Monad.IO.Class` (previously provided by `transformers`+    package). (#10773)++  * New modules `Data.Functor.Classes`, `Data.Functor.Compose`,+    `Data.Functor.Product`, and `Data.Functor.Sum` (previously provided by+    `transformers` package). (#11135)++  * New instances for `Proxy`: `Eq1`, `Ord1`, `Show1`, `Read1`. All+    of the classes are from `Data.Functor.Classes` (#11756).++  * New module `Control.Monad.Fail` providing new `MonadFail(fail)`+    class (#10751)++  * Add `GHC.TypeLits.TypeError` and `ErrorMessage` to allow users+    to define custom compile-time error messages.++  * Redesign `GHC.Generics` to use type-level literals to represent the+    metadata of generic representation types (#9766)++  * The `IsString` instance for `[Char]` has been modified to eliminate+    ambiguity arising from overloaded strings and functions like `(++)`.++  * Move `Const` from `Control.Applicative` to its own module in+   `Data.Functor.Const`. (#11135)++  * Re-export `Const` from `Control.Applicative` for backwards compatibility.++  * Expand `Floating` class to include operations that allow for better+    precision: `log1p`, `expm1`, `log1pexp` and `log1mexp`. These are not+    available from `Prelude`, but the full class is exported from `Numeric`.++  * New `Control.Exception.TypeError` datatype, which is thrown when an+    expression fails to typecheck when run using `-fdefer-type-errors` (#10284)++  * The `bitSize` method of `Data.Bits.Bits` now has a (partial!)+    default implementation based on `bitSizeMaybe`. (#12970)++### New instances++  * `Alt`, `Dual`, `First`, `Last`, `Product`, and `Sum` now have `Data`,+    `MonadZip`, and `MonadFix` instances++  * The datatypes in `GHC.Generics` now have `Enum`, `Bounded`, `Ix`,+    `Functor`, `Applicative`, `Monad`, `MonadFix`, `MonadPlus`, `MonadZip`,+    `Foldable`, `Foldable`, `Traversable`, `Generic1`, and `Data` instances+    as appropriate.++  * `Maybe` now has a `MonadZip` instance++  * `All` and `Any` now have `Data` instances++  * `Dual`, `First`, `Last`, `Product`, and `Sum` now have `Foldable` and+    `Traversable` instances++  * `Dual`, `Product`, and `Sum` now have `Functor`, `Applicative`, and+    `Monad` instances++  * `(,) a` now has a `Monad` instance++  * `ZipList` now has `Foldable` and `Traversable` instances++  * `Identity` now has `Semigroup` and `Monoid` instances++  * `Identity` and `Const` now have `Bits`, `Bounded`, `Enum`, `FiniteBits`,+    `Floating`, `Fractional`, `Integral`, `IsString`, `Ix`, `Num`, `Real`,+    `RealFloat`, `RealFrac` and `Storable` instances. (#11210, #11790)++  * `()` now has a `Storable` instance++  * `Complex` now has `Generic`, `Generic1`, `Functor`, `Foldable`, `Traversable`,+    `Applicative`, and `Monad` instances++  * `System.Exit.ExitCode` now has a `Generic` instance++  * `Data.Version.Version` now has a `Generic` instance++  * `IO` now has a `Monoid` instance++  * Add `MonadPlus IO` and `Alternative IO` instances+    (previously orphans in `transformers`) (#10755)++  * `CallStack` now has an `IsList` instance++  * The field `spInfoName` of `GHC.StaticPtr.StaticPtrInfo` has been removed.+    The value is no longer available when constructing the `StaticPtr`.++  * `VecElem` and `VecCount` now have `Enum` and `Bounded` instances.++### Generalizations++  * Generalize `Debug.Trace.{traceM, traceShowM}` from `Monad` to `Applicative`+    (#10023)++  * Redundant typeclass constraints have been removed:+     - `Data.Ratio.{denominator,numerator}` have no `Integral` constraint anymore+     - **TODO**++  * Generalise `forever` from `Monad` to `Applicative`++  * Generalize `filterM`, `mapAndUnzipM`, `zipWithM`, `zipWithM_`, `replicateM`,+    `replicateM_` from `Monad` to `Applicative` (#10168)++  * The `Generic` instance for `Proxy` is now poly-kinded (#10775)++  * Enable `PolyKinds` in the `Data.Functor.Const` module to give `Const`+    the kind `* -> k -> *`. (#10039)++ ## 4.8.2.0  *Oct 2015*    * Bundled with GHC 7.10.3@@ -16,7 +1000,7 @@    * `Lifetime` is now exported from `GHC.Event` -  * Implicit-parameter based source location support exposed in `GHC.SrcLoc`.+  * Implicit-parameter based source location support exposed in `GHC.SrcLoc` and `GHC.Stack`.     See GHC User's Manual for more information.  ## 4.8.0.0  *Mar 2015*
− config.guess
@@ -1,1420 +0,0 @@-#! /bin/sh-# Attempt to guess a canonical system name.-#   Copyright 1992-2014 Free Software Foundation, Inc.--timestamp='2014-03-23'--# This file is free software; you can redistribute it and/or modify it-# under the terms of the GNU General Public License as published by-# the Free Software Foundation; either version 3 of the License, or-# (at your option) any later version.-#-# This program is distributed in the hope that it will be useful, but-# WITHOUT ANY WARRANTY; without even the implied warranty of-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU-# General Public License for more details.-#-# You should have received a copy of the GNU General Public License-# along with this program; if not, see <http://www.gnu.org/licenses/>.-#-# As a special exception to the GNU General Public License, if you-# distribute this file as part of a program that contains a-# configuration script generated by Autoconf, you may include it under-# the same distribution terms that you use for the rest of that-# program.  This Exception is an additional permission under section 7-# of the GNU General Public License, version 3 ("GPLv3").-#-# Originally written by Per Bothner.-#-# You can get the latest version of this script from:-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD-#-# Please send patches with a ChangeLog entry to config-patches@gnu.org.---me=`echo "$0" | sed -e 's,.*/,,'`--usage="\-Usage: $0 [OPTION]--Output the configuration name of the system \`$me' is run on.--Operation modes:-  -h, --help         print this help, then exit-  -t, --time-stamp   print date of last modification, then exit-  -v, --version      print version number, then exit--Report bugs and patches to <config-patches@gnu.org>."--version="\-GNU config.guess ($timestamp)--Originally written by Per Bothner.-Copyright 1992-2014 Free Software Foundation, Inc.--This is free software; see the source for copying conditions.  There is NO-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."--help="-Try \`$me --help' for more information."--# Parse command line-while test $# -gt 0 ; do-  case $1 in-    --time-stamp | --time* | -t )-       echo "$timestamp" ; exit ;;-    --version | -v )-       echo "$version" ; exit ;;-    --help | --h* | -h )-       echo "$usage"; exit ;;-    -- )     # Stop option processing-       shift; break ;;-    - )	# Use stdin as input.-       break ;;-    -* )-       echo "$me: invalid option $1$help" >&2-       exit 1 ;;-    * )-       break ;;-  esac-done--if test $# != 0; then-  echo "$me: too many arguments$help" >&2-  exit 1-fi--trap 'exit 1' 1 2 15--# CC_FOR_BUILD -- compiler used by this script. Note that the use of a-# compiler to aid in system detection is discouraged as it requires-# temporary files to be created and, as you can see below, it is a-# headache to deal with in a portable fashion.--# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still-# use `HOST_CC' if defined, but it is deprecated.--# Portable tmp directory creation inspired by the Autoconf team.--set_cc_for_build='-trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;-trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;-: ${TMPDIR=/tmp} ;- { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||- { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||- { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||- { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;-dummy=$tmp/dummy ;-tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;-case $CC_FOR_BUILD,$HOST_CC,$CC in- ,,)    echo "int x;" > $dummy.c ;-	for c in cc gcc c89 c99 ; do-	  if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then-	     CC_FOR_BUILD="$c"; break ;-	  fi ;-	done ;-	if test x"$CC_FOR_BUILD" = x ; then-	  CC_FOR_BUILD=no_compiler_found ;-	fi-	;;- ,,*)   CC_FOR_BUILD=$CC ;;- ,*,*)  CC_FOR_BUILD=$HOST_CC ;;-esac ; set_cc_for_build= ;'--# This is needed to find uname on a Pyramid OSx when run in the BSD universe.-# (ghazi@noc.rutgers.edu 1994-08-24)-if (test -f /.attbin/uname) >/dev/null 2>&1 ; then-	PATH=$PATH:/.attbin ; export PATH-fi--UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown-UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown-UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown-UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown--case "${UNAME_SYSTEM}" in-Linux|GNU|GNU/*)-	# If the system lacks a compiler, then just pick glibc.-	# We could probably try harder.-	LIBC=gnu--	eval $set_cc_for_build-	cat <<-EOF > $dummy.c-	#include <features.h>-	#if defined(__UCLIBC__)-	LIBC=uclibc-	#elif defined(__dietlibc__)-	LIBC=dietlibc-	#else-	LIBC=gnu-	#endif-	EOF-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`-	;;-esac--# Note: order is significant - the case branches are not exclusive.--case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in-    *:NetBSD:*:*)-	# NetBSD (nbsd) targets should (where applicable) match one or-	# more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*,-	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently-	# switched to ELF, *-*-netbsd* would select the old-	# object file format.  This provides both forward-	# compatibility and a consistent mechanism for selecting the-	# object file format.-	#-	# Note: NetBSD doesn't particularly care about the vendor-	# portion of the name.  We always set it to "unknown".-	sysctl="sysctl -n hw.machine_arch"-	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \-	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`-	case "${UNAME_MACHINE_ARCH}" in-	    armeb) machine=armeb-unknown ;;-	    arm*) machine=arm-unknown ;;-	    sh3el) machine=shl-unknown ;;-	    sh3eb) machine=sh-unknown ;;-	    sh5el) machine=sh5le-unknown ;;-	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;-	esac-	# The Operating System including object format, if it has switched-	# to ELF recently, or will in the future.-	case "${UNAME_MACHINE_ARCH}" in-	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)-		eval $set_cc_for_build-		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \-			| grep -q __ELF__-		then-		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).-		    # Return netbsd for either.  FIX?-		    os=netbsd-		else-		    os=netbsdelf-		fi-		;;-	    *)-		os=netbsd-		;;-	esac-	# The OS release-	# Debian GNU/NetBSD machines have a different userland, and-	# thus, need a distinct triplet. However, they do not need-	# kernel version information, so it can be replaced with a-	# suitable tag, in the style of linux-gnu.-	case "${UNAME_VERSION}" in-	    Debian*)-		release='-gnu'-		;;-	    *)-		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`-		;;-	esac-	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:-	# contains redundant information, the shorter form:-	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.-	echo "${machine}-${os}${release}"-	exit ;;-    *:Bitrig:*:*)-	UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`-	echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE}-	exit ;;-    *:OpenBSD:*:*)-	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`-	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}-	exit ;;-    *:ekkoBSD:*:*)-	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}-	exit ;;-    *:SolidBSD:*:*)-	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}-	exit ;;-    macppc:MirBSD:*:*)-	echo powerpc-unknown-mirbsd${UNAME_RELEASE}-	exit ;;-    *:MirBSD:*:*)-	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}-	exit ;;-    alpha:OSF1:*:*)-	case $UNAME_RELEASE in-	*4.0)-		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`-		;;-	*5.*)-		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`-		;;-	esac-	# According to Compaq, /usr/sbin/psrinfo has been available on-	# OSF/1 and Tru64 systems produced since 1995.  I hope that-	# covers most systems running today.  This code pipes the CPU-	# types through head -n 1, so we only detect the type of CPU 0.-	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`-	case "$ALPHA_CPU_TYPE" in-	    "EV4 (21064)")-		UNAME_MACHINE="alpha" ;;-	    "EV4.5 (21064)")-		UNAME_MACHINE="alpha" ;;-	    "LCA4 (21066/21068)")-		UNAME_MACHINE="alpha" ;;-	    "EV5 (21164)")-		UNAME_MACHINE="alphaev5" ;;-	    "EV5.6 (21164A)")-		UNAME_MACHINE="alphaev56" ;;-	    "EV5.6 (21164PC)")-		UNAME_MACHINE="alphapca56" ;;-	    "EV5.7 (21164PC)")-		UNAME_MACHINE="alphapca57" ;;-	    "EV6 (21264)")-		UNAME_MACHINE="alphaev6" ;;-	    "EV6.7 (21264A)")-		UNAME_MACHINE="alphaev67" ;;-	    "EV6.8CB (21264C)")-		UNAME_MACHINE="alphaev68" ;;-	    "EV6.8AL (21264B)")-		UNAME_MACHINE="alphaev68" ;;-	    "EV6.8CX (21264D)")-		UNAME_MACHINE="alphaev68" ;;-	    "EV6.9A (21264/EV69A)")-		UNAME_MACHINE="alphaev69" ;;-	    "EV7 (21364)")-		UNAME_MACHINE="alphaev7" ;;-	    "EV7.9 (21364A)")-		UNAME_MACHINE="alphaev79" ;;-	esac-	# A Pn.n version is a patched version.-	# A Vn.n version is a released version.-	# A Tn.n version is a released field test version.-	# A Xn.n version is an unreleased experimental baselevel.-	# 1.2 uses "1.2" for uname -r.-	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`-	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.-	exitcode=$?-	trap '' 0-	exit $exitcode ;;-    Alpha\ *:Windows_NT*:*)-	# How do we know it's Interix rather than the generic POSIX subsystem?-	# Should we change UNAME_MACHINE based on the output of uname instead-	# of the specific Alpha model?-	echo alpha-pc-interix-	exit ;;-    21064:Windows_NT:50:3)-	echo alpha-dec-winnt3.5-	exit ;;-    Amiga*:UNIX_System_V:4.0:*)-	echo m68k-unknown-sysv4-	exit ;;-    *:[Aa]miga[Oo][Ss]:*:*)-	echo ${UNAME_MACHINE}-unknown-amigaos-	exit ;;-    *:[Mm]orph[Oo][Ss]:*:*)-	echo ${UNAME_MACHINE}-unknown-morphos-	exit ;;-    *:OS/390:*:*)-	echo i370-ibm-openedition-	exit ;;-    *:z/VM:*:*)-	echo s390-ibm-zvmoe-	exit ;;-    *:OS400:*:*)-	echo powerpc-ibm-os400-	exit ;;-    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)-	echo arm-acorn-riscix${UNAME_RELEASE}-	exit ;;-    arm*:riscos:*:*|arm*:RISCOS:*:*)-	echo arm-unknown-riscos-	exit ;;-    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)-	echo hppa1.1-hitachi-hiuxmpp-	exit ;;-    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)-	# akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.-	if test "`(/bin/universe) 2>/dev/null`" = att ; then-		echo pyramid-pyramid-sysv3-	else-		echo pyramid-pyramid-bsd-	fi-	exit ;;-    NILE*:*:*:dcosx)-	echo pyramid-pyramid-svr4-	exit ;;-    DRS?6000:unix:4.0:6*)-	echo sparc-icl-nx6-	exit ;;-    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)-	case `/usr/bin/uname -p` in-	    sparc) echo sparc-icl-nx7; exit ;;-	esac ;;-    s390x:SunOS:*:*)-	echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`-	exit ;;-    sun4H:SunOS:5.*:*)-	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`-	exit ;;-    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)-	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`-	exit ;;-    i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)-	echo i386-pc-auroraux${UNAME_RELEASE}-	exit ;;-    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)-	eval $set_cc_for_build-	SUN_ARCH="i386"-	# If there is a compiler, see if it is configured for 64-bit objects.-	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.-	# This test works for both compilers.-	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then-	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \-		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \-		grep IS_64BIT_ARCH >/dev/null-	    then-		SUN_ARCH="x86_64"-	    fi-	fi-	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`-	exit ;;-    sun4*:SunOS:6*:*)-	# According to config.sub, this is the proper way to canonicalize-	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but-	# it's likely to be more like Solaris than SunOS4.-	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`-	exit ;;-    sun4*:SunOS:*:*)-	case "`/usr/bin/arch -k`" in-	    Series*|S4*)-		UNAME_RELEASE=`uname -v`-		;;-	esac-	# Japanese Language versions have a version number like `4.1.3-JL'.-	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`-	exit ;;-    sun3*:SunOS:*:*)-	echo m68k-sun-sunos${UNAME_RELEASE}-	exit ;;-    sun*:*:4.2BSD:*)-	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`-	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3-	case "`/bin/arch`" in-	    sun3)-		echo m68k-sun-sunos${UNAME_RELEASE}-		;;-	    sun4)-		echo sparc-sun-sunos${UNAME_RELEASE}-		;;-	esac-	exit ;;-    aushp:SunOS:*:*)-	echo sparc-auspex-sunos${UNAME_RELEASE}-	exit ;;-    # The situation for MiNT is a little confusing.  The machine name-    # can be virtually everything (everything which is not-    # "atarist" or "atariste" at least should have a processor-    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"-    # to the lowercase version "mint" (or "freemint").  Finally-    # the system name "TOS" denotes a system which is actually not-    # MiNT.  But MiNT is downward compatible to TOS, so this should-    # be no problem.-    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)-	echo m68k-atari-mint${UNAME_RELEASE}-	exit ;;-    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)-	echo m68k-atari-mint${UNAME_RELEASE}-	exit ;;-    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)-	echo m68k-atari-mint${UNAME_RELEASE}-	exit ;;-    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)-	echo m68k-milan-mint${UNAME_RELEASE}-	exit ;;-    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)-	echo m68k-hades-mint${UNAME_RELEASE}-	exit ;;-    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)-	echo m68k-unknown-mint${UNAME_RELEASE}-	exit ;;-    m68k:machten:*:*)-	echo m68k-apple-machten${UNAME_RELEASE}-	exit ;;-    powerpc:machten:*:*)-	echo powerpc-apple-machten${UNAME_RELEASE}-	exit ;;-    RISC*:Mach:*:*)-	echo mips-dec-mach_bsd4.3-	exit ;;-    RISC*:ULTRIX:*:*)-	echo mips-dec-ultrix${UNAME_RELEASE}-	exit ;;-    VAX*:ULTRIX*:*:*)-	echo vax-dec-ultrix${UNAME_RELEASE}-	exit ;;-    2020:CLIX:*:* | 2430:CLIX:*:*)-	echo clipper-intergraph-clix${UNAME_RELEASE}-	exit ;;-    mips:*:*:UMIPS | mips:*:*:RISCos)-	eval $set_cc_for_build-	sed 's/^	//' << EOF >$dummy.c-#ifdef __cplusplus-#include <stdio.h>  /* for printf() prototype */-	int main (int argc, char *argv[]) {-#else-	int main (argc, argv) int argc; char *argv[]; {-#endif-	#if defined (host_mips) && defined (MIPSEB)-	#if defined (SYSTYPE_SYSV)-	  printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);-	#endif-	#if defined (SYSTYPE_SVR4)-	  printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);-	#endif-	#if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)-	  printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);-	#endif-	#endif-	  exit (-1);-	}-EOF-	$CC_FOR_BUILD -o $dummy $dummy.c &&-	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&-	  SYSTEM_NAME=`$dummy $dummyarg` &&-	    { echo "$SYSTEM_NAME"; exit; }-	echo mips-mips-riscos${UNAME_RELEASE}-	exit ;;-    Motorola:PowerMAX_OS:*:*)-	echo powerpc-motorola-powermax-	exit ;;-    Motorola:*:4.3:PL8-*)-	echo powerpc-harris-powermax-	exit ;;-    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)-	echo powerpc-harris-powermax-	exit ;;-    Night_Hawk:Power_UNIX:*:*)-	echo powerpc-harris-powerunix-	exit ;;-    m88k:CX/UX:7*:*)-	echo m88k-harris-cxux7-	exit ;;-    m88k:*:4*:R4*)-	echo m88k-motorola-sysv4-	exit ;;-    m88k:*:3*:R3*)-	echo m88k-motorola-sysv3-	exit ;;-    AViiON:dgux:*:*)-	# DG/UX returns AViiON for all architectures-	UNAME_PROCESSOR=`/usr/bin/uname -p`-	if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]-	then-	    if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \-	       [ ${TARGET_BINARY_INTERFACE}x = x ]-	    then-		echo m88k-dg-dgux${UNAME_RELEASE}-	    else-		echo m88k-dg-dguxbcs${UNAME_RELEASE}-	    fi-	else-	    echo i586-dg-dgux${UNAME_RELEASE}-	fi-	exit ;;-    M88*:DolphinOS:*:*)	# DolphinOS (SVR3)-	echo m88k-dolphin-sysv3-	exit ;;-    M88*:*:R3*:*)-	# Delta 88k system running SVR3-	echo m88k-motorola-sysv3-	exit ;;-    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)-	echo m88k-tektronix-sysv3-	exit ;;-    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)-	echo m68k-tektronix-bsd-	exit ;;-    *:IRIX*:*:*)-	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`-	exit ;;-    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.-	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id-	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '-    i*86:AIX:*:*)-	echo i386-ibm-aix-	exit ;;-    ia64:AIX:*:*)-	if [ -x /usr/bin/oslevel ] ; then-		IBM_REV=`/usr/bin/oslevel`-	else-		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}-	fi-	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}-	exit ;;-    *:AIX:2:3)-	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then-		eval $set_cc_for_build-		sed 's/^		//' << EOF >$dummy.c-		#include <sys/systemcfg.h>--		main()-			{-			if (!__power_pc())-				exit(1);-			puts("powerpc-ibm-aix3.2.5");-			exit(0);-			}-EOF-		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`-		then-			echo "$SYSTEM_NAME"-		else-			echo rs6000-ibm-aix3.2.5-		fi-	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then-		echo rs6000-ibm-aix3.2.4-	else-		echo rs6000-ibm-aix3.2-	fi-	exit ;;-    *:AIX:*:[4567])-	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`-	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then-		IBM_ARCH=rs6000-	else-		IBM_ARCH=powerpc-	fi-	if [ -x /usr/bin/oslevel ] ; then-		IBM_REV=`/usr/bin/oslevel`-	else-		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}-	fi-	echo ${IBM_ARCH}-ibm-aix${IBM_REV}-	exit ;;-    *:AIX:*:*)-	echo rs6000-ibm-aix-	exit ;;-    ibmrt:4.4BSD:*|romp-ibm:BSD:*)-	echo romp-ibm-bsd4.4-	exit ;;-    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and-	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to-	exit ;;                             # report: romp-ibm BSD 4.3-    *:BOSX:*:*)-	echo rs6000-bull-bosx-	exit ;;-    DPX/2?00:B.O.S.:*:*)-	echo m68k-bull-sysv3-	exit ;;-    9000/[34]??:4.3bsd:1.*:*)-	echo m68k-hp-bsd-	exit ;;-    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)-	echo m68k-hp-bsd4.4-	exit ;;-    9000/[34678]??:HP-UX:*:*)-	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`-	case "${UNAME_MACHINE}" in-	    9000/31? )            HP_ARCH=m68000 ;;-	    9000/[34]?? )         HP_ARCH=m68k ;;-	    9000/[678][0-9][0-9])-		if [ -x /usr/bin/getconf ]; then-		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`-		    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`-		    case "${sc_cpu_version}" in-		      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0-		      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1-		      532)                      # CPU_PA_RISC2_0-			case "${sc_kernel_bits}" in-			  32) HP_ARCH="hppa2.0n" ;;-			  64) HP_ARCH="hppa2.0w" ;;-			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20-			esac ;;-		    esac-		fi-		if [ "${HP_ARCH}" = "" ]; then-		    eval $set_cc_for_build-		    sed 's/^		//' << EOF >$dummy.c--		#define _HPUX_SOURCE-		#include <stdlib.h>-		#include <unistd.h>--		int main ()-		{-		#if defined(_SC_KERNEL_BITS)-		    long bits = sysconf(_SC_KERNEL_BITS);-		#endif-		    long cpu  = sysconf (_SC_CPU_VERSION);--		    switch (cpu)-			{-			case CPU_PA_RISC1_0: puts ("hppa1.0"); break;-			case CPU_PA_RISC1_1: puts ("hppa1.1"); break;-			case CPU_PA_RISC2_0:-		#if defined(_SC_KERNEL_BITS)-			    switch (bits)-				{-				case 64: puts ("hppa2.0w"); break;-				case 32: puts ("hppa2.0n"); break;-				default: puts ("hppa2.0"); break;-				} break;-		#else  /* !defined(_SC_KERNEL_BITS) */-			    puts ("hppa2.0"); break;-		#endif-			default: puts ("hppa1.0"); break;-			}-		    exit (0);-		}-EOF-		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`-		    test -z "$HP_ARCH" && HP_ARCH=hppa-		fi ;;-	esac-	if [ ${HP_ARCH} = "hppa2.0w" ]-	then-	    eval $set_cc_for_build--	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating-	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler-	    # generating 64-bit code.  GNU and HP use different nomenclature:-	    #-	    # $ CC_FOR_BUILD=cc ./config.guess-	    # => hppa2.0w-hp-hpux11.23-	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess-	    # => hppa64-hp-hpux11.23--	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |-		grep -q __LP64__-	    then-		HP_ARCH="hppa2.0w"-	    else-		HP_ARCH="hppa64"-	    fi-	fi-	echo ${HP_ARCH}-hp-hpux${HPUX_REV}-	exit ;;-    ia64:HP-UX:*:*)-	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`-	echo ia64-hp-hpux${HPUX_REV}-	exit ;;-    3050*:HI-UX:*:*)-	eval $set_cc_for_build-	sed 's/^	//' << EOF >$dummy.c-	#include <unistd.h>-	int-	main ()-	{-	  long cpu = sysconf (_SC_CPU_VERSION);-	  /* The order matters, because CPU_IS_HP_MC68K erroneously returns-	     true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct-	     results, however.  */-	  if (CPU_IS_PA_RISC (cpu))-	    {-	      switch (cpu)-		{-		  case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;-		  case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;-		  case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;-		  default: puts ("hppa-hitachi-hiuxwe2"); break;-		}-	    }-	  else if (CPU_IS_HP_MC68K (cpu))-	    puts ("m68k-hitachi-hiuxwe2");-	  else puts ("unknown-hitachi-hiuxwe2");-	  exit (0);-	}-EOF-	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&-		{ echo "$SYSTEM_NAME"; exit; }-	echo unknown-hitachi-hiuxwe2-	exit ;;-    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )-	echo hppa1.1-hp-bsd-	exit ;;-    9000/8??:4.3bsd:*:*)-	echo hppa1.0-hp-bsd-	exit ;;-    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)-	echo hppa1.0-hp-mpeix-	exit ;;-    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )-	echo hppa1.1-hp-osf-	exit ;;-    hp8??:OSF1:*:*)-	echo hppa1.0-hp-osf-	exit ;;-    i*86:OSF1:*:*)-	if [ -x /usr/sbin/sysversion ] ; then-	    echo ${UNAME_MACHINE}-unknown-osf1mk-	else-	    echo ${UNAME_MACHINE}-unknown-osf1-	fi-	exit ;;-    parisc*:Lites*:*:*)-	echo hppa1.1-hp-lites-	exit ;;-    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)-	echo c1-convex-bsd-	exit ;;-    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)-	if getsysinfo -f scalar_acc-	then echo c32-convex-bsd-	else echo c2-convex-bsd-	fi-	exit ;;-    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)-	echo c34-convex-bsd-	exit ;;-    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)-	echo c38-convex-bsd-	exit ;;-    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)-	echo c4-convex-bsd-	exit ;;-    CRAY*Y-MP:*:*:*)-	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'-	exit ;;-    CRAY*[A-Z]90:*:*:*)-	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \-	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \-	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \-	      -e 's/\.[^.]*$/.X/'-	exit ;;-    CRAY*TS:*:*:*)-	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'-	exit ;;-    CRAY*T3E:*:*:*)-	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'-	exit ;;-    CRAY*SV1:*:*:*)-	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'-	exit ;;-    *:UNICOS/mp:*:*)-	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'-	exit ;;-    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)-	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`-	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`-	FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`-	echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"-	exit ;;-    5000:UNIX_System_V:4.*:*)-	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`-	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`-	echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"-	exit ;;-    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)-	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}-	exit ;;-    sparc*:BSD/OS:*:*)-	echo sparc-unknown-bsdi${UNAME_RELEASE}-	exit ;;-    *:BSD/OS:*:*)-	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}-	exit ;;-    *:FreeBSD:*:*)-	UNAME_PROCESSOR=`/usr/bin/uname -p`-	case ${UNAME_PROCESSOR} in-	    amd64)-		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;-	    *)-		echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;-	esac-	exit ;;-    i*:CYGWIN*:*)-	echo ${UNAME_MACHINE}-pc-cygwin-	exit ;;-    *:MINGW64*:*)-	echo ${UNAME_MACHINE}-pc-mingw64-	exit ;;-    *:MINGW*:*)-	echo ${UNAME_MACHINE}-pc-mingw32-	exit ;;-    *:MSYS*:*)-	echo ${UNAME_MACHINE}-pc-msys-	exit ;;-    i*:windows32*:*)-	# uname -m includes "-pc" on this system.-	echo ${UNAME_MACHINE}-mingw32-	exit ;;-    i*:PW*:*)-	echo ${UNAME_MACHINE}-pc-pw32-	exit ;;-    *:Interix*:*)-	case ${UNAME_MACHINE} in-	    x86)-		echo i586-pc-interix${UNAME_RELEASE}-		exit ;;-	    authenticamd | genuineintel | EM64T)-		echo x86_64-unknown-interix${UNAME_RELEASE}-		exit ;;-	    IA64)-		echo ia64-unknown-interix${UNAME_RELEASE}-		exit ;;-	esac ;;-    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)-	echo i${UNAME_MACHINE}-pc-mks-	exit ;;-    8664:Windows_NT:*)-	echo x86_64-pc-mks-	exit ;;-    i*:Windows_NT*:* | Pentium*:Windows_NT*:*)-	# How do we know it's Interix rather than the generic POSIX subsystem?-	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we-	# UNAME_MACHINE based on the output of uname instead of i386?-	echo i586-pc-interix-	exit ;;-    i*:UWIN*:*)-	echo ${UNAME_MACHINE}-pc-uwin-	exit ;;-    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)-	echo x86_64-unknown-cygwin-	exit ;;-    p*:CYGWIN*:*)-	echo powerpcle-unknown-cygwin-	exit ;;-    prep*:SunOS:5.*:*)-	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`-	exit ;;-    *:GNU:*:*)-	# the GNU system-	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`-	exit ;;-    *:GNU/*:*:*)-	# other systems with GNU libc and userland-	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}-	exit ;;-    i*86:Minix:*:*)-	echo ${UNAME_MACHINE}-pc-minix-	exit ;;-    aarch64:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    aarch64_be:Linux:*:*)-	UNAME_MACHINE=aarch64_be-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    alpha:Linux:*:*)-	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in-	  EV5)   UNAME_MACHINE=alphaev5 ;;-	  EV56)  UNAME_MACHINE=alphaev56 ;;-	  PCA56) UNAME_MACHINE=alphapca56 ;;-	  PCA57) UNAME_MACHINE=alphapca56 ;;-	  EV6)   UNAME_MACHINE=alphaev6 ;;-	  EV67)  UNAME_MACHINE=alphaev67 ;;-	  EV68*) UNAME_MACHINE=alphaev68 ;;-	esac-	objdump --private-headers /bin/sh | grep -q ld.so.1-	if test "$?" = 0 ; then LIBC="gnulibc1" ; fi-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    arc:Linux:*:* | arceb:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    arm*:Linux:*:*)-	eval $set_cc_for_build-	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \-	    | grep -q __ARM_EABI__-	then-	    echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	else-	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \-		| grep -q __ARM_PCS_VFP-	    then-		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi-	    else-		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf-	    fi-	fi-	exit ;;-    avr32*:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    cris:Linux:*:*)-	echo ${UNAME_MACHINE}-axis-linux-${LIBC}-	exit ;;-    crisv32:Linux:*:*)-	echo ${UNAME_MACHINE}-axis-linux-${LIBC}-	exit ;;-    frv:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    hexagon:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    i*86:Linux:*:*)-	echo ${UNAME_MACHINE}-pc-linux-${LIBC}-	exit ;;-    ia64:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    m32r*:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    m68*:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    mips:Linux:*:* | mips64:Linux:*:*)-	eval $set_cc_for_build-	sed 's/^	//' << EOF >$dummy.c-	#undef CPU-	#undef ${UNAME_MACHINE}-	#undef ${UNAME_MACHINE}el-	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)-	CPU=${UNAME_MACHINE}el-	#else-	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)-	CPU=${UNAME_MACHINE}-	#else-	CPU=-	#endif-	#endif-EOF-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`-	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }-	;;-    openrisc*:Linux:*:*)-	echo or1k-unknown-linux-${LIBC}-	exit ;;-    or32:Linux:*:* | or1k*:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    padre:Linux:*:*)-	echo sparc-unknown-linux-${LIBC}-	exit ;;-    parisc64:Linux:*:* | hppa64:Linux:*:*)-	echo hppa64-unknown-linux-${LIBC}-	exit ;;-    parisc:Linux:*:* | hppa:Linux:*:*)-	# Look for CPU level-	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in-	  PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;-	  PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;-	  *)    echo hppa-unknown-linux-${LIBC} ;;-	esac-	exit ;;-    ppc64:Linux:*:*)-	echo powerpc64-unknown-linux-${LIBC}-	exit ;;-    ppc:Linux:*:*)-	echo powerpc-unknown-linux-${LIBC}-	exit ;;-    ppc64le:Linux:*:*)-	echo powerpc64le-unknown-linux-${LIBC}-	exit ;;-    ppcle:Linux:*:*)-	echo powerpcle-unknown-linux-${LIBC}-	exit ;;-    s390:Linux:*:* | s390x:Linux:*:*)-	echo ${UNAME_MACHINE}-ibm-linux-${LIBC}-	exit ;;-    sh64*:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    sh*:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    sparc:Linux:*:* | sparc64:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    tile*:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    vax:Linux:*:*)-	echo ${UNAME_MACHINE}-dec-linux-${LIBC}-	exit ;;-    x86_64:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    xtensa*:Linux:*:*)-	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}-	exit ;;-    i*86:DYNIX/ptx:4*:*)-	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.-	# earlier versions are messed up and put the nodename in both-	# sysname and nodename.-	echo i386-sequent-sysv4-	exit ;;-    i*86:UNIX_SV:4.2MP:2.*)-	# Unixware is an offshoot of SVR4, but it has its own version-	# number series starting with 2...-	# I am not positive that other SVR4 systems won't match this,-	# I just have to hope.  -- rms.-	# Use sysv4.2uw... so that sysv4* matches it.-	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}-	exit ;;-    i*86:OS/2:*:*)-	# If we were able to find `uname', then EMX Unix compatibility-	# is probably installed.-	echo ${UNAME_MACHINE}-pc-os2-emx-	exit ;;-    i*86:XTS-300:*:STOP)-	echo ${UNAME_MACHINE}-unknown-stop-	exit ;;-    i*86:atheos:*:*)-	echo ${UNAME_MACHINE}-unknown-atheos-	exit ;;-    i*86:syllable:*:*)-	echo ${UNAME_MACHINE}-pc-syllable-	exit ;;-    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)-	echo i386-unknown-lynxos${UNAME_RELEASE}-	exit ;;-    i*86:*DOS:*:*)-	echo ${UNAME_MACHINE}-pc-msdosdjgpp-	exit ;;-    i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)-	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`-	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then-		echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}-	else-		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}-	fi-	exit ;;-    i*86:*:5:[678]*)-	# UnixWare 7.x, OpenUNIX and OpenServer 6.-	case `/bin/uname -X | grep "^Machine"` in-	    *486*)	     UNAME_MACHINE=i486 ;;-	    *Pentium)	     UNAME_MACHINE=i586 ;;-	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;-	esac-	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}-	exit ;;-    i*86:*:3.2:*)-	if test -f /usr/options/cb.name; then-		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`-		echo ${UNAME_MACHINE}-pc-isc$UNAME_REL-	elif /bin/uname -X 2>/dev/null >/dev/null ; then-		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`-		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486-		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \-			&& UNAME_MACHINE=i586-		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \-			&& UNAME_MACHINE=i686-		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \-			&& UNAME_MACHINE=i686-		echo ${UNAME_MACHINE}-pc-sco$UNAME_REL-	else-		echo ${UNAME_MACHINE}-pc-sysv32-	fi-	exit ;;-    pc:*:*:*)-	# Left here for compatibility:-	# uname -m prints for DJGPP always 'pc', but it prints nothing about-	# the processor, so we play safe by assuming i586.-	# Note: whatever this is, it MUST be the same as what config.sub-	# prints for the "djgpp" host, or else GDB configury will decide that-	# this is a cross-build.-	echo i586-pc-msdosdjgpp-	exit ;;-    Intel:Mach:3*:*)-	echo i386-pc-mach3-	exit ;;-    paragon:*:*:*)-	echo i860-intel-osf1-	exit ;;-    i860:*:4.*:*) # i860-SVR4-	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then-	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4-	else # Add other i860-SVR4 vendors below as they are discovered.-	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4-	fi-	exit ;;-    mini*:CTIX:SYS*5:*)-	# "miniframe"-	echo m68010-convergent-sysv-	exit ;;-    mc68k:UNIX:SYSTEM5:3.51m)-	echo m68k-convergent-sysv-	exit ;;-    M680?0:D-NIX:5.3:*)-	echo m68k-diab-dnix-	exit ;;-    M68*:*:R3V[5678]*:*)-	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;-    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)-	OS_REL=''-	test -r /etc/.relid \-	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`-	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \-	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }-	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \-	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;-    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)-	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \-	  && { echo i486-ncr-sysv4; exit; } ;;-    NCR*:*:4.2:* | MPRAS*:*:4.2:*)-	OS_REL='.3'-	test -r /etc/.relid \-	    && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`-	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \-	    && { echo i486-ncr-sysv4.3${OS_REL}; exit; }-	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \-	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; }-	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \-	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;-    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)-	echo m68k-unknown-lynxos${UNAME_RELEASE}-	exit ;;-    mc68030:UNIX_System_V:4.*:*)-	echo m68k-atari-sysv4-	exit ;;-    TSUNAMI:LynxOS:2.*:*)-	echo sparc-unknown-lynxos${UNAME_RELEASE}-	exit ;;-    rs6000:LynxOS:2.*:*)-	echo rs6000-unknown-lynxos${UNAME_RELEASE}-	exit ;;-    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)-	echo powerpc-unknown-lynxos${UNAME_RELEASE}-	exit ;;-    SM[BE]S:UNIX_SV:*:*)-	echo mips-dde-sysv${UNAME_RELEASE}-	exit ;;-    RM*:ReliantUNIX-*:*:*)-	echo mips-sni-sysv4-	exit ;;-    RM*:SINIX-*:*:*)-	echo mips-sni-sysv4-	exit ;;-    *:SINIX-*:*:*)-	if uname -p 2>/dev/null >/dev/null ; then-		UNAME_MACHINE=`(uname -p) 2>/dev/null`-		echo ${UNAME_MACHINE}-sni-sysv4-	else-		echo ns32k-sni-sysv-	fi-	exit ;;-    PENTIUM:*:4.0*:*)	# Unisys `ClearPath HMP IX 4000' SVR4/MP effort-			# says <Richard.M.Bartel@ccMail.Census.GOV>-	echo i586-unisys-sysv4-	exit ;;-    *:UNIX_System_V:4*:FTX*)-	# From Gerald Hewes <hewes@openmarket.com>.-	# How about differentiating between stratus architectures? -djm-	echo hppa1.1-stratus-sysv4-	exit ;;-    *:*:*:FTX*)-	# From seanf@swdc.stratus.com.-	echo i860-stratus-sysv4-	exit ;;-    i*86:VOS:*:*)-	# From Paul.Green@stratus.com.-	echo ${UNAME_MACHINE}-stratus-vos-	exit ;;-    *:VOS:*:*)-	# From Paul.Green@stratus.com.-	echo hppa1.1-stratus-vos-	exit ;;-    mc68*:A/UX:*:*)-	echo m68k-apple-aux${UNAME_RELEASE}-	exit ;;-    news*:NEWS-OS:6*:*)-	echo mips-sony-newsos6-	exit ;;-    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)-	if [ -d /usr/nec ]; then-		echo mips-nec-sysv${UNAME_RELEASE}-	else-		echo mips-unknown-sysv${UNAME_RELEASE}-	fi-	exit ;;-    BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.-	echo powerpc-be-beos-	exit ;;-    BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.-	echo powerpc-apple-beos-	exit ;;-    BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.-	echo i586-pc-beos-	exit ;;-    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.-	echo i586-pc-haiku-	exit ;;-    x86_64:Haiku:*:*)-	echo x86_64-unknown-haiku-	exit ;;-    SX-4:SUPER-UX:*:*)-	echo sx4-nec-superux${UNAME_RELEASE}-	exit ;;-    SX-5:SUPER-UX:*:*)-	echo sx5-nec-superux${UNAME_RELEASE}-	exit ;;-    SX-6:SUPER-UX:*:*)-	echo sx6-nec-superux${UNAME_RELEASE}-	exit ;;-    SX-7:SUPER-UX:*:*)-	echo sx7-nec-superux${UNAME_RELEASE}-	exit ;;-    SX-8:SUPER-UX:*:*)-	echo sx8-nec-superux${UNAME_RELEASE}-	exit ;;-    SX-8R:SUPER-UX:*:*)-	echo sx8r-nec-superux${UNAME_RELEASE}-	exit ;;-    Power*:Rhapsody:*:*)-	echo powerpc-apple-rhapsody${UNAME_RELEASE}-	exit ;;-    *:Rhapsody:*:*)-	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}-	exit ;;-    *:Darwin:*:*)-	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown-	eval $set_cc_for_build-	if test "$UNAME_PROCESSOR" = unknown ; then-	    UNAME_PROCESSOR=powerpc-	fi-	if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then-	    if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then-		if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \-		    (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \-		    grep IS_64BIT_ARCH >/dev/null-		then-		    case $UNAME_PROCESSOR in-			i386) UNAME_PROCESSOR=x86_64 ;;-			powerpc) UNAME_PROCESSOR=powerpc64 ;;-		    esac-		fi-	    fi-	elif test "$UNAME_PROCESSOR" = i386 ; then-	    # Avoid executing cc on OS X 10.9, as it ships with a stub-	    # that puts up a graphical alert prompting to install-	    # developer tools.  Any system running Mac OS X 10.7 or-	    # later (Darwin 11 and later) is required to have a 64-bit-	    # processor. This is not true of the ARM version of Darwin-	    # that Apple uses in portable devices.-	    UNAME_PROCESSOR=x86_64-	fi-	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}-	exit ;;-    *:procnto*:*:* | *:QNX:[0123456789]*:*)-	UNAME_PROCESSOR=`uname -p`-	if test "$UNAME_PROCESSOR" = "x86"; then-		UNAME_PROCESSOR=i386-		UNAME_MACHINE=pc-	fi-	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}-	exit ;;-    *:QNX:*:4*)-	echo i386-pc-qnx-	exit ;;-    NEO-?:NONSTOP_KERNEL:*:*)-	echo neo-tandem-nsk${UNAME_RELEASE}-	exit ;;-    NSE-*:NONSTOP_KERNEL:*:*)-	echo nse-tandem-nsk${UNAME_RELEASE}-	exit ;;-    NSR-?:NONSTOP_KERNEL:*:*)-	echo nsr-tandem-nsk${UNAME_RELEASE}-	exit ;;-    *:NonStop-UX:*:*)-	echo mips-compaq-nonstopux-	exit ;;-    BS2000:POSIX*:*:*)-	echo bs2000-siemens-sysv-	exit ;;-    DS/*:UNIX_System_V:*:*)-	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}-	exit ;;-    *:Plan9:*:*)-	# "uname -m" is not consistent, so use $cputype instead. 386-	# is converted to i386 for consistency with other x86-	# operating systems.-	if test "$cputype" = "386"; then-	    UNAME_MACHINE=i386-	else-	    UNAME_MACHINE="$cputype"-	fi-	echo ${UNAME_MACHINE}-unknown-plan9-	exit ;;-    *:TOPS-10:*:*)-	echo pdp10-unknown-tops10-	exit ;;-    *:TENEX:*:*)-	echo pdp10-unknown-tenex-	exit ;;-    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)-	echo pdp10-dec-tops20-	exit ;;-    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)-	echo pdp10-xkl-tops20-	exit ;;-    *:TOPS-20:*:*)-	echo pdp10-unknown-tops20-	exit ;;-    *:ITS:*:*)-	echo pdp10-unknown-its-	exit ;;-    SEI:*:*:SEIUX)-	echo mips-sei-seiux${UNAME_RELEASE}-	exit ;;-    *:DragonFly:*:*)-	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-	exit ;;-    *:*VMS:*:*)-	UNAME_MACHINE=`(uname -p) 2>/dev/null`-	case "${UNAME_MACHINE}" in-	    A*) echo alpha-dec-vms ; exit ;;-	    I*) echo ia64-dec-vms ; exit ;;-	    V*) echo vax-dec-vms ; exit ;;-	esac ;;-    *:XENIX:*:SysV)-	echo i386-pc-xenix-	exit ;;-    i*86:skyos:*:*)-	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'-	exit ;;-    i*86:rdos:*:*)-	echo ${UNAME_MACHINE}-pc-rdos-	exit ;;-    i*86:AROS:*:*)-	echo ${UNAME_MACHINE}-pc-aros-	exit ;;-    x86_64:VMkernel:*:*)-	echo ${UNAME_MACHINE}-unknown-esx-	exit ;;-esac--cat >&2 <<EOF-$0: unable to guess system type--This script, last modified $timestamp, has failed to recognize-the operating system you are using. It is advised that you-download the most up to date version of the config scripts from--  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD-and-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD--If the version you run ($0) is already up to date, please-send the following data and any information you think might be-pertinent to <config-patches@gnu.org> in order to provide the needed-information to handle your system.--config.guess timestamp = $timestamp--uname -m = `(uname -m) 2>/dev/null || echo unknown`-uname -r = `(uname -r) 2>/dev/null || echo unknown`-uname -s = `(uname -s) 2>/dev/null || echo unknown`-uname -v = `(uname -v) 2>/dev/null || echo unknown`--/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`-/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`--hostinfo               = `(hostinfo) 2>/dev/null`-/bin/universe          = `(/bin/universe) 2>/dev/null`-/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`-/bin/arch              = `(/bin/arch) 2>/dev/null`-/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`--UNAME_MACHINE = ${UNAME_MACHINE}-UNAME_RELEASE = ${UNAME_RELEASE}-UNAME_SYSTEM  = ${UNAME_SYSTEM}-UNAME_VERSION = ${UNAME_VERSION}-EOF--exit 1--# Local variables:-# eval: (add-hook 'write-file-hooks 'time-stamp)-# time-stamp-start: "timestamp='"-# time-stamp-format: "%:y-%02m-%02d"-# time-stamp-end: "'"-# End:
− config.sub
@@ -1,1794 +0,0 @@-#! /bin/sh-# Configuration validation subroutine script.-#   Copyright 1992-2014 Free Software Foundation, Inc.--timestamp='2014-05-01'--# This file is free software; you can redistribute it and/or modify it-# under the terms of the GNU General Public License as published by-# the Free Software Foundation; either version 3 of the License, or-# (at your option) any later version.-#-# This program is distributed in the hope that it will be useful, but-# WITHOUT ANY WARRANTY; without even the implied warranty of-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU-# General Public License for more details.-#-# You should have received a copy of the GNU General Public License-# along with this program; if not, see <http://www.gnu.org/licenses/>.-#-# As a special exception to the GNU General Public License, if you-# distribute this file as part of a program that contains a-# configuration script generated by Autoconf, you may include it under-# the same distribution terms that you use for the rest of that-# program.  This Exception is an additional permission under section 7-# of the GNU General Public License, version 3 ("GPLv3").---# Please send patches with a ChangeLog entry to config-patches@gnu.org.-#-# Configuration subroutine to validate and canonicalize a configuration type.-# Supply the specified configuration type as an argument.-# If it is invalid, we print an error message on stderr and exit with code 1.-# Otherwise, we print the canonical config type on stdout and succeed.--# You can get the latest version of this script from:-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD--# This file is supposed to be the same for all GNU packages-# and recognize all the CPU types, system types and aliases-# that are meaningful with *any* GNU software.-# Each package is responsible for reporting which valid configurations-# it does not support.  The user should be able to distinguish-# a failure to support a valid configuration from a meaningless-# configuration.--# The goal of this file is to map all the various variations of a given-# machine specification into a single specification in the form:-#	CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM-# or in some cases, the newer four-part form:-#	CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM-# It is wrong to echo any other type of specification.--me=`echo "$0" | sed -e 's,.*/,,'`--usage="\-Usage: $0 [OPTION] CPU-MFR-OPSYS-       $0 [OPTION] ALIAS--Canonicalize a configuration name.--Operation modes:-  -h, --help         print this help, then exit-  -t, --time-stamp   print date of last modification, then exit-  -v, --version      print version number, then exit--Report bugs and patches to <config-patches@gnu.org>."--version="\-GNU config.sub ($timestamp)--Copyright 1992-2014 Free Software Foundation, Inc.--This is free software; see the source for copying conditions.  There is NO-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."--help="-Try \`$me --help' for more information."--# Parse command line-while test $# -gt 0 ; do-  case $1 in-    --time-stamp | --time* | -t )-       echo "$timestamp" ; exit ;;-    --version | -v )-       echo "$version" ; exit ;;-    --help | --h* | -h )-       echo "$usage"; exit ;;-    -- )     # Stop option processing-       shift; break ;;-    - )	# Use stdin as input.-       break ;;-    -* )-       echo "$me: invalid option $1$help"-       exit 1 ;;--    *local*)-       # First pass through any local machine types.-       echo $1-       exit ;;--    * )-       break ;;-  esac-done--case $# in- 0) echo "$me: missing argument$help" >&2-    exit 1;;- 1) ;;- *) echo "$me: too many arguments$help" >&2-    exit 1;;-esac--# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).-# Here we must recognize all the valid KERNEL-OS combinations.-maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`-case $maybe_os in-  nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \-  linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \-  knetbsd*-gnu* | netbsd*-gnu* | \-  kopensolaris*-gnu* | \-  storm-chaos* | os2-emx* | rtmk-nova*)-    os=-$maybe_os-    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-    ;;-  android-linux)-    os=-linux-android-    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown-    ;;-  *)-    basic_machine=`echo $1 | sed 's/-[^-]*$//'`-    if [ $basic_machine != $1 ]-    then os=`echo $1 | sed 's/.*-/-/'`-    else os=; fi-    ;;-esac--### Let's recognize common machines as not being operating systems so-### that things like config.sub decstation-3100 work.  We also-### recognize some manufacturers as not being operating systems, so we-### can provide default operating systems below.-case $os in-	-sun*os*)-		# Prevent following clause from handling this invalid input.-		;;-	-dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \-	-att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \-	-unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \-	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\-	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \-	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \-	-apple | -axis | -knuth | -cray | -microblaze*)-		os=-		basic_machine=$1-		;;-	-bluegene*)-		os=-cnk-		;;-	-sim | -cisco | -oki | -wec | -winbond)-		os=-		basic_machine=$1-		;;-	-scout)-		;;-	-wrs)-		os=-vxworks-		basic_machine=$1-		;;-	-chorusos*)-		os=-chorusos-		basic_machine=$1-		;;-	-chorusrdb)-		os=-chorusrdb-		basic_machine=$1-		;;-	-hiux*)-		os=-hiuxwe2-		;;-	-sco6)-		os=-sco5v6-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-sco5)-		os=-sco3.2v5-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-sco4)-		os=-sco3.2v4-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-sco3.2.[4-9]*)-		os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-sco3.2v[4-9]*)-		# Don't forget version if it is 3.2v4 or newer.-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-sco5v6*)-		# Don't forget version if it is 3.2v4 or newer.-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-sco*)-		os=-sco3.2v2-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-udk*)-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-isc)-		os=-isc2.2-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-clix*)-		basic_machine=clipper-intergraph-		;;-	-isc*)-		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`-		;;-	-lynx*178)-		os=-lynxos178-		;;-	-lynx*5)-		os=-lynxos5-		;;-	-lynx*)-		os=-lynxos-		;;-	-ptx*)-		basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`-		;;-	-windowsnt*)-		os=`echo $os | sed -e 's/windowsnt/winnt/'`-		;;-	-psos*)-		os=-psos-		;;-	-mint | -mint[0-9]*)-		basic_machine=m68k-atari-		os=-mint-		;;-esac--# Decode aliases for certain CPU-COMPANY combinations.-case $basic_machine in-	# Recognize the basic CPU types without company name.-	# Some are omitted here because they have special meanings below.-	1750a | 580 \-	| a29k \-	| aarch64 | aarch64_be \-	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \-	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \-	| am33_2.0 \-	| arc | arceb \-	| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \-	| avr | avr32 \-	| be32 | be64 \-	| bfin \-	| c4x | c8051 | clipper \-	| d10v | d30v | dlx | dsp16xx \-	| epiphany \-	| fido | fr30 | frv \-	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \-	| hexagon \-	| i370 | i860 | i960 | ia64 \-	| ip2k | iq2000 \-	| k1om \-	| le32 | le64 \-	| lm32 \-	| m32c | m32r | m32rle | m68000 | m68k | m88k \-	| maxq | mb | microblaze | microblazeel | mcore | mep | metag \-	| mips | mipsbe | mipseb | mipsel | mipsle \-	| mips16 \-	| mips64 | mips64el \-	| mips64octeon | mips64octeonel \-	| mips64orion | mips64orionel \-	| mips64r5900 | mips64r5900el \-	| mips64vr | mips64vrel \-	| mips64vr4100 | mips64vr4100el \-	| mips64vr4300 | mips64vr4300el \-	| mips64vr5000 | mips64vr5000el \-	| mips64vr5900 | mips64vr5900el \-	| mipsisa32 | mipsisa32el \-	| mipsisa32r2 | mipsisa32r2el \-	| mipsisa32r6 | mipsisa32r6el \-	| mipsisa64 | mipsisa64el \-	| mipsisa64r2 | mipsisa64r2el \-	| mipsisa64r6 | mipsisa64r6el \-	| mipsisa64sb1 | mipsisa64sb1el \-	| mipsisa64sr71k | mipsisa64sr71kel \-	| mipsr5900 | mipsr5900el \-	| mipstx39 | mipstx39el \-	| mn10200 | mn10300 \-	| moxie \-	| mt \-	| msp430 \-	| nds32 | nds32le | nds32be \-	| nios | nios2 | nios2eb | nios2el \-	| ns16k | ns32k \-	| open8 | or1k | or1knd | or32 \-	| pdp10 | pdp11 | pj | pjl \-	| powerpc | powerpc64 | powerpc64le | powerpcle \-	| pyramid \-	| rl78 | rx \-	| score \-	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \-	| sh64 | sh64le \-	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \-	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \-	| spu \-	| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \-	| ubicom32 \-	| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \-	| we32k \-	| x86 | xc16x | xstormy16 | xtensa \-	| z8k | z80)-		basic_machine=$basic_machine-unknown-		;;-	c54x)-		basic_machine=tic54x-unknown-		;;-	c55x)-		basic_machine=tic55x-unknown-		;;-	c6x)-		basic_machine=tic6x-unknown-		;;-	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)-		basic_machine=$basic_machine-unknown-		os=-none-		;;-	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)-		;;-	ms1)-		basic_machine=mt-unknown-		;;--	strongarm | thumb | xscale)-		basic_machine=arm-unknown-		;;-	xgate)-		basic_machine=$basic_machine-unknown-		os=-none-		;;-	xscaleeb)-		basic_machine=armeb-unknown-		;;--	xscaleel)-		basic_machine=armel-unknown-		;;--	# We use `pc' rather than `unknown'-	# because (1) that's what they normally are, and-	# (2) the word "unknown" tends to confuse beginning users.-	i*86 | x86_64)-	  basic_machine=$basic_machine-pc-	  ;;-	# Object if more than one company name word.-	*-*-*)-		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2-		exit 1-		;;-	# Recognize the basic CPU types with company name.-	580-* \-	| a29k-* \-	| aarch64-* | aarch64_be-* \-	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \-	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \-	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \-	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \-	| avr-* | avr32-* \-	| be32-* | be64-* \-	| bfin-* | bs2000-* \-	| c[123]* | c30-* | [cjt]90-* | c4x-* \-	| c8051-* | clipper-* | craynv-* | cydra-* \-	| d10v-* | d30v-* | dlx-* \-	| elxsi-* \-	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \-	| h8300-* | h8500-* \-	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \-	| hexagon-* \-	| i*86-* | i860-* | i960-* | ia64-* \-	| ip2k-* | iq2000-* \-	| k1om-* \-	| le32-* | le64-* \-	| lm32-* \-	| m32c-* | m32r-* | m32rle-* \-	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \-	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* \-	| microblaze-* | microblazeel-* \-	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \-	| mips16-* \-	| mips64-* | mips64el-* \-	| mips64octeon-* | mips64octeonel-* \-	| mips64orion-* | mips64orionel-* \-	| mips64r5900-* | mips64r5900el-* \-	| mips64vr-* | mips64vrel-* \-	| mips64vr4100-* | mips64vr4100el-* \-	| mips64vr4300-* | mips64vr4300el-* \-	| mips64vr5000-* | mips64vr5000el-* \-	| mips64vr5900-* | mips64vr5900el-* \-	| mipsisa32-* | mipsisa32el-* \-	| mipsisa32r2-* | mipsisa32r2el-* \-	| mipsisa32r6-* | mipsisa32r6el-* \-	| mipsisa64-* | mipsisa64el-* \-	| mipsisa64r2-* | mipsisa64r2el-* \-	| mipsisa64r6-* | mipsisa64r6el-* \-	| mipsisa64sb1-* | mipsisa64sb1el-* \-	| mipsisa64sr71k-* | mipsisa64sr71kel-* \-	| mipsr5900-* | mipsr5900el-* \-	| mipstx39-* | mipstx39el-* \-	| mmix-* \-	| mt-* \-	| msp430-* \-	| nds32-* | nds32le-* | nds32be-* \-	| nios-* | nios2-* | nios2eb-* | nios2el-* \-	| none-* | np1-* | ns16k-* | ns32k-* \-	| open8-* \-	| or1k*-* \-	| orion-* \-	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \-	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \-	| pyramid-* \-	| rl78-* | romp-* | rs6000-* | rx-* \-	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \-	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \-	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \-	| sparclite-* \-	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \-	| tahoe-* \-	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \-	| tile*-* \-	| tron-* \-	| ubicom32-* \-	| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \-	| vax-* \-	| we32k-* \-	| x86-* | x86_64-* | xc16x-* | xps100-* \-	| xstormy16-* | xtensa*-* \-	| ymp-* \-	| z8k-* | z80-*)-		;;-	# Recognize the basic CPU types without company name, with glob match.-	xtensa*)-		basic_machine=$basic_machine-unknown-		;;-	# Recognize the various machine names and aliases which stand-	# for a CPU type and a company and sometimes even an OS.-	386bsd)-		basic_machine=i386-unknown-		os=-bsd-		;;-	3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)-		basic_machine=m68000-att-		;;-	3b*)-		basic_machine=we32k-att-		;;-	a29khif)-		basic_machine=a29k-amd-		os=-udi-		;;-	abacus)-		basic_machine=abacus-unknown-		;;-	adobe68k)-		basic_machine=m68010-adobe-		os=-scout-		;;-	alliant | fx80)-		basic_machine=fx80-alliant-		;;-	altos | altos3068)-		basic_machine=m68k-altos-		;;-	am29k)-		basic_machine=a29k-none-		os=-bsd-		;;-	amd64)-		basic_machine=x86_64-pc-		;;-	amd64-*)-		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	amdahl)-		basic_machine=580-amdahl-		os=-sysv-		;;-	amiga | amiga-*)-		basic_machine=m68k-unknown-		;;-	amigaos | amigados)-		basic_machine=m68k-unknown-		os=-amigaos-		;;-	amigaunix | amix)-		basic_machine=m68k-unknown-		os=-sysv4-		;;-	apollo68)-		basic_machine=m68k-apollo-		os=-sysv-		;;-	apollo68bsd)-		basic_machine=m68k-apollo-		os=-bsd-		;;-	aros)-		basic_machine=i386-pc-		os=-aros-		;;-	aux)-		basic_machine=m68k-apple-		os=-aux-		;;-	balance)-		basic_machine=ns32k-sequent-		os=-dynix-		;;-	blackfin)-		basic_machine=bfin-unknown-		os=-linux-		;;-	blackfin-*)-		basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`-		os=-linux-		;;-	bluegene*)-		basic_machine=powerpc-ibm-		os=-cnk-		;;-	c54x-*)-		basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	c55x-*)-		basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	c6x-*)-		basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	c90)-		basic_machine=c90-cray-		os=-unicos-		;;-	cegcc)-		basic_machine=arm-unknown-		os=-cegcc-		;;-	convex-c1)-		basic_machine=c1-convex-		os=-bsd-		;;-	convex-c2)-		basic_machine=c2-convex-		os=-bsd-		;;-	convex-c32)-		basic_machine=c32-convex-		os=-bsd-		;;-	convex-c34)-		basic_machine=c34-convex-		os=-bsd-		;;-	convex-c38)-		basic_machine=c38-convex-		os=-bsd-		;;-	cray | j90)-		basic_machine=j90-cray-		os=-unicos-		;;-	craynv)-		basic_machine=craynv-cray-		os=-unicosmp-		;;-	cr16 | cr16-*)-		basic_machine=cr16-unknown-		os=-elf-		;;-	crds | unos)-		basic_machine=m68k-crds-		;;-	crisv32 | crisv32-* | etraxfs*)-		basic_machine=crisv32-axis-		;;-	cris | cris-* | etrax*)-		basic_machine=cris-axis-		;;-	crx)-		basic_machine=crx-unknown-		os=-elf-		;;-	da30 | da30-*)-		basic_machine=m68k-da30-		;;-	decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)-		basic_machine=mips-dec-		;;-	decsystem10* | dec10*)-		basic_machine=pdp10-dec-		os=-tops10-		;;-	decsystem20* | dec20*)-		basic_machine=pdp10-dec-		os=-tops20-		;;-	delta | 3300 | motorola-3300 | motorola-delta \-	      | 3300-motorola | delta-motorola)-		basic_machine=m68k-motorola-		;;-	delta88)-		basic_machine=m88k-motorola-		os=-sysv3-		;;-	dicos)-		basic_machine=i686-pc-		os=-dicos-		;;-	djgpp)-		basic_machine=i586-pc-		os=-msdosdjgpp-		;;-	dpx20 | dpx20-*)-		basic_machine=rs6000-bull-		os=-bosx-		;;-	dpx2* | dpx2*-bull)-		basic_machine=m68k-bull-		os=-sysv3-		;;-	ebmon29k)-		basic_machine=a29k-amd-		os=-ebmon-		;;-	elxsi)-		basic_machine=elxsi-elxsi-		os=-bsd-		;;-	encore | umax | mmax)-		basic_machine=ns32k-encore-		;;-	es1800 | OSE68k | ose68k | ose | OSE)-		basic_machine=m68k-ericsson-		os=-ose-		;;-	fx2800)-		basic_machine=i860-alliant-		;;-	genix)-		basic_machine=ns32k-ns-		;;-	gmicro)-		basic_machine=tron-gmicro-		os=-sysv-		;;-	go32)-		basic_machine=i386-pc-		os=-go32-		;;-	h3050r* | hiux*)-		basic_machine=hppa1.1-hitachi-		os=-hiuxwe2-		;;-	h8300hms)-		basic_machine=h8300-hitachi-		os=-hms-		;;-	h8300xray)-		basic_machine=h8300-hitachi-		os=-xray-		;;-	h8500hms)-		basic_machine=h8500-hitachi-		os=-hms-		;;-	harris)-		basic_machine=m88k-harris-		os=-sysv3-		;;-	hp300-*)-		basic_machine=m68k-hp-		;;-	hp300bsd)-		basic_machine=m68k-hp-		os=-bsd-		;;-	hp300hpux)-		basic_machine=m68k-hp-		os=-hpux-		;;-	hp3k9[0-9][0-9] | hp9[0-9][0-9])-		basic_machine=hppa1.0-hp-		;;-	hp9k2[0-9][0-9] | hp9k31[0-9])-		basic_machine=m68000-hp-		;;-	hp9k3[2-9][0-9])-		basic_machine=m68k-hp-		;;-	hp9k6[0-9][0-9] | hp6[0-9][0-9])-		basic_machine=hppa1.0-hp-		;;-	hp9k7[0-79][0-9] | hp7[0-79][0-9])-		basic_machine=hppa1.1-hp-		;;-	hp9k78[0-9] | hp78[0-9])-		# FIXME: really hppa2.0-hp-		basic_machine=hppa1.1-hp-		;;-	hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)-		# FIXME: really hppa2.0-hp-		basic_machine=hppa1.1-hp-		;;-	hp9k8[0-9][13679] | hp8[0-9][13679])-		basic_machine=hppa1.1-hp-		;;-	hp9k8[0-9][0-9] | hp8[0-9][0-9])-		basic_machine=hppa1.0-hp-		;;-	hppa-next)-		os=-nextstep3-		;;-	hppaosf)-		basic_machine=hppa1.1-hp-		os=-osf-		;;-	hppro)-		basic_machine=hppa1.1-hp-		os=-proelf-		;;-	i370-ibm* | ibm*)-		basic_machine=i370-ibm-		;;-	i*86v32)-		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`-		os=-sysv32-		;;-	i*86v4*)-		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`-		os=-sysv4-		;;-	i*86v)-		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`-		os=-sysv-		;;-	i*86sol2)-		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`-		os=-solaris2-		;;-	i386mach)-		basic_machine=i386-mach-		os=-mach-		;;-	i386-vsta | vsta)-		basic_machine=i386-unknown-		os=-vsta-		;;-	iris | iris4d)-		basic_machine=mips-sgi-		case $os in-		    -irix*)-			;;-		    *)-			os=-irix4-			;;-		esac-		;;-	isi68 | isi)-		basic_machine=m68k-isi-		os=-sysv-		;;-	m68knommu)-		basic_machine=m68k-unknown-		os=-linux-		;;-	m68knommu-*)-		basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`-		os=-linux-		;;-	m88k-omron*)-		basic_machine=m88k-omron-		;;-	magnum | m3230)-		basic_machine=mips-mips-		os=-sysv-		;;-	merlin)-		basic_machine=ns32k-utek-		os=-sysv-		;;-	microblaze*)-		basic_machine=microblaze-xilinx-		;;-	mingw64)-		basic_machine=x86_64-pc-		os=-mingw64-		;;-	mingw32)-		basic_machine=i686-pc-		os=-mingw32-		;;-	mingw32ce)-		basic_machine=arm-unknown-		os=-mingw32ce-		;;-	miniframe)-		basic_machine=m68000-convergent-		;;-	*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)-		basic_machine=m68k-atari-		os=-mint-		;;-	mips3*-*)-		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-		;;-	mips3*)-		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown-		;;-	monitor)-		basic_machine=m68k-rom68k-		os=-coff-		;;-	morphos)-		basic_machine=powerpc-unknown-		os=-morphos-		;;-	msdos)-		basic_machine=i386-pc-		os=-msdos-		;;-	ms1-*)-		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`-		;;-	msys)-		basic_machine=i686-pc-		os=-msys-		;;-	mvs)-		basic_machine=i370-ibm-		os=-mvs-		;;-	nacl)-		basic_machine=le32-unknown-		os=-nacl-		;;-	ncr3000)-		basic_machine=i486-ncr-		os=-sysv4-		;;-	netbsd386)-		basic_machine=i386-unknown-		os=-netbsd-		;;-	netwinder)-		basic_machine=armv4l-rebel-		os=-linux-		;;-	news | news700 | news800 | news900)-		basic_machine=m68k-sony-		os=-newsos-		;;-	news1000)-		basic_machine=m68030-sony-		os=-newsos-		;;-	news-3600 | risc-news)-		basic_machine=mips-sony-		os=-newsos-		;;-	necv70)-		basic_machine=v70-nec-		os=-sysv-		;;-	next | m*-next )-		basic_machine=m68k-next-		case $os in-		    -nextstep* )-			;;-		    -ns2*)-		      os=-nextstep2-			;;-		    *)-		      os=-nextstep3-			;;-		esac-		;;-	nh3000)-		basic_machine=m68k-harris-		os=-cxux-		;;-	nh[45]000)-		basic_machine=m88k-harris-		os=-cxux-		;;-	nindy960)-		basic_machine=i960-intel-		os=-nindy-		;;-	mon960)-		basic_machine=i960-intel-		os=-mon960-		;;-	nonstopux)-		basic_machine=mips-compaq-		os=-nonstopux-		;;-	np1)-		basic_machine=np1-gould-		;;-	neo-tandem)-		basic_machine=neo-tandem-		;;-	nse-tandem)-		basic_machine=nse-tandem-		;;-	nsr-tandem)-		basic_machine=nsr-tandem-		;;-	op50n-* | op60c-*)-		basic_machine=hppa1.1-oki-		os=-proelf-		;;-	openrisc | openrisc-*)-		basic_machine=or32-unknown-		;;-	os400)-		basic_machine=powerpc-ibm-		os=-os400-		;;-	OSE68000 | ose68000)-		basic_machine=m68000-ericsson-		os=-ose-		;;-	os68k)-		basic_machine=m68k-none-		os=-os68k-		;;-	pa-hitachi)-		basic_machine=hppa1.1-hitachi-		os=-hiuxwe2-		;;-	paragon)-		basic_machine=i860-intel-		os=-osf-		;;-	parisc)-		basic_machine=hppa-unknown-		os=-linux-		;;-	parisc-*)-		basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`-		os=-linux-		;;-	pbd)-		basic_machine=sparc-tti-		;;-	pbb)-		basic_machine=m68k-tti-		;;-	pc532 | pc532-*)-		basic_machine=ns32k-pc532-		;;-	pc98)-		basic_machine=i386-pc-		;;-	pc98-*)-		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	pentium | p5 | k5 | k6 | nexgen | viac3)-		basic_machine=i586-pc-		;;-	pentiumpro | p6 | 6x86 | athlon | athlon_*)-		basic_machine=i686-pc-		;;-	pentiumii | pentium2 | pentiumiii | pentium3)-		basic_machine=i686-pc-		;;-	pentium4)-		basic_machine=i786-pc-		;;-	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)-		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	pentiumpro-* | p6-* | 6x86-* | athlon-*)-		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)-		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	pentium4-*)-		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	pn)-		basic_machine=pn-gould-		;;-	power)	basic_machine=power-ibm-		;;-	ppc | ppcbe)	basic_machine=powerpc-unknown-		;;-	ppc-* | ppcbe-*)-		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	ppcle | powerpclittle | ppc-le | powerpc-little)-		basic_machine=powerpcle-unknown-		;;-	ppcle-* | powerpclittle-*)-		basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	ppc64)	basic_machine=powerpc64-unknown-		;;-	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	ppc64le | powerpc64little | ppc64-le | powerpc64-little)-		basic_machine=powerpc64le-unknown-		;;-	ppc64le-* | powerpc64little-*)-		basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	ps2)-		basic_machine=i386-ibm-		;;-	pw32)-		basic_machine=i586-unknown-		os=-pw32-		;;-	rdos | rdos64)-		basic_machine=x86_64-pc-		os=-rdos-		;;-	rdos32)-		basic_machine=i386-pc-		os=-rdos-		;;-	rom68k)-		basic_machine=m68k-rom68k-		os=-coff-		;;-	rm[46]00)-		basic_machine=mips-siemens-		;;-	rtpc | rtpc-*)-		basic_machine=romp-ibm-		;;-	s390 | s390-*)-		basic_machine=s390-ibm-		;;-	s390x | s390x-*)-		basic_machine=s390x-ibm-		;;-	sa29200)-		basic_machine=a29k-amd-		os=-udi-		;;-	sb1)-		basic_machine=mipsisa64sb1-unknown-		;;-	sb1el)-		basic_machine=mipsisa64sb1el-unknown-		;;-	sde)-		basic_machine=mipsisa32-sde-		os=-elf-		;;-	sei)-		basic_machine=mips-sei-		os=-seiux-		;;-	sequent)-		basic_machine=i386-sequent-		;;-	sh)-		basic_machine=sh-hitachi-		os=-hms-		;;-	sh5el)-		basic_machine=sh5le-unknown-		;;-	sh64)-		basic_machine=sh64-unknown-		;;-	sparclite-wrs | simso-wrs)-		basic_machine=sparclite-wrs-		os=-vxworks-		;;-	sps7)-		basic_machine=m68k-bull-		os=-sysv2-		;;-	spur)-		basic_machine=spur-unknown-		;;-	st2000)-		basic_machine=m68k-tandem-		;;-	stratus)-		basic_machine=i860-stratus-		os=-sysv4-		;;-	strongarm-* | thumb-*)-		basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`-		;;-	sun2)-		basic_machine=m68000-sun-		;;-	sun2os3)-		basic_machine=m68000-sun-		os=-sunos3-		;;-	sun2os4)-		basic_machine=m68000-sun-		os=-sunos4-		;;-	sun3os3)-		basic_machine=m68k-sun-		os=-sunos3-		;;-	sun3os4)-		basic_machine=m68k-sun-		os=-sunos4-		;;-	sun4os3)-		basic_machine=sparc-sun-		os=-sunos3-		;;-	sun4os4)-		basic_machine=sparc-sun-		os=-sunos4-		;;-	sun4sol2)-		basic_machine=sparc-sun-		os=-solaris2-		;;-	sun3 | sun3-*)-		basic_machine=m68k-sun-		;;-	sun4)-		basic_machine=sparc-sun-		;;-	sun386 | sun386i | roadrunner)-		basic_machine=i386-sun-		;;-	sv1)-		basic_machine=sv1-cray-		os=-unicos-		;;-	symmetry)-		basic_machine=i386-sequent-		os=-dynix-		;;-	t3e)-		basic_machine=alphaev5-cray-		os=-unicos-		;;-	t90)-		basic_machine=t90-cray-		os=-unicos-		;;-	tile*)-		basic_machine=$basic_machine-unknown-		os=-linux-gnu-		;;-	tx39)-		basic_machine=mipstx39-unknown-		;;-	tx39el)-		basic_machine=mipstx39el-unknown-		;;-	toad1)-		basic_machine=pdp10-xkl-		os=-tops20-		;;-	tower | tower-32)-		basic_machine=m68k-ncr-		;;-	tpf)-		basic_machine=s390x-ibm-		os=-tpf-		;;-	udi29k)-		basic_machine=a29k-amd-		os=-udi-		;;-	ultra3)-		basic_machine=a29k-nyu-		os=-sym1-		;;-	v810 | necv810)-		basic_machine=v810-nec-		os=-none-		;;-	vaxv)-		basic_machine=vax-dec-		os=-sysv-		;;-	vms)-		basic_machine=vax-dec-		os=-vms-		;;-	vpp*|vx|vx-*)-		basic_machine=f301-fujitsu-		;;-	vxworks960)-		basic_machine=i960-wrs-		os=-vxworks-		;;-	vxworks68)-		basic_machine=m68k-wrs-		os=-vxworks-		;;-	vxworks29k)-		basic_machine=a29k-wrs-		os=-vxworks-		;;-	w65*)-		basic_machine=w65-wdc-		os=-none-		;;-	w89k-*)-		basic_machine=hppa1.1-winbond-		os=-proelf-		;;-	xbox)-		basic_machine=i686-pc-		os=-mingw32-		;;-	xps | xps100)-		basic_machine=xps100-honeywell-		;;-	xscale-* | xscalee[bl]-*)-		basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`-		;;-	ymp)-		basic_machine=ymp-cray-		os=-unicos-		;;-	z8k-*-coff)-		basic_machine=z8k-unknown-		os=-sim-		;;-	z80-*-coff)-		basic_machine=z80-unknown-		os=-sim-		;;-	none)-		basic_machine=none-none-		os=-none-		;;--# Here we handle the default manufacturer of certain CPU types.  It is in-# some cases the only manufacturer, in others, it is the most popular.-	w89k)-		basic_machine=hppa1.1-winbond-		;;-	op50n)-		basic_machine=hppa1.1-oki-		;;-	op60c)-		basic_machine=hppa1.1-oki-		;;-	romp)-		basic_machine=romp-ibm-		;;-	mmix)-		basic_machine=mmix-knuth-		;;-	rs6000)-		basic_machine=rs6000-ibm-		;;-	vax)-		basic_machine=vax-dec-		;;-	pdp10)-		# there are many clones, so DEC is not a safe bet-		basic_machine=pdp10-unknown-		;;-	pdp11)-		basic_machine=pdp11-dec-		;;-	we32k)-		basic_machine=we32k-att-		;;-	sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)-		basic_machine=sh-unknown-		;;-	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)-		basic_machine=sparc-sun-		;;-	cydra)-		basic_machine=cydra-cydrome-		;;-	orion)-		basic_machine=orion-highlevel-		;;-	orion105)-		basic_machine=clipper-highlevel-		;;-	mac | mpw | mac-mpw)-		basic_machine=m68k-apple-		;;-	pmac | pmac-mpw)-		basic_machine=powerpc-apple-		;;-	*-unknown)-		# Make sure to match an already-canonicalized machine name.-		;;-	*)-		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2-		exit 1-		;;-esac--# Here we canonicalize certain aliases for manufacturers.-case $basic_machine in-	*-digital*)-		basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`-		;;-	*-commodore*)-		basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`-		;;-	*)-		;;-esac--# Decode manufacturer-specific aliases for certain operating systems.--if [ x"$os" != x"" ]-then-case $os in-	# First match some system type aliases-	# that might get confused with valid system types.-	# -solaris* is a basic system type, with this one exception.-	-auroraux)-		os=-auroraux-		;;-	-solaris1 | -solaris1.*)-		os=`echo $os | sed -e 's|solaris1|sunos4|'`-		;;-	-solaris)-		os=-solaris2-		;;-	-svr4*)-		os=-sysv4-		;;-	-unixware*)-		os=-sysv4.2uw-		;;-	-gnu/linux*)-		os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`-		;;-	# First accept the basic system types.-	# The portable systems comes first.-	# Each alternative MUST END IN A *, to match a version number.-	# -sysv* is not here because it comes later, after sysvr4.-	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \-	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\-	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \-	      | -sym* | -kopensolaris* | -plan9* \-	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \-	      | -aos* | -aros* \-	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \-	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \-	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \-	      | -bitrig* | -openbsd* | -solidbsd* \-	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \-	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \-	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \-	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \-	      | -chorusos* | -chorusrdb* | -cegcc* \-	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \-	      | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \-	      | -linux-newlib* | -linux-musl* | -linux-uclibc* \-	      | -uxpv* | -beos* | -mpeix* | -udk* \-	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \-	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \-	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \-	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \-	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \-	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \-	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*)-	# Remember, each alternative MUST END IN *, to match a version number.-		;;-	-qnx*)-		case $basic_machine in-		    x86-* | i*86-*)-			;;-		    *)-			os=-nto$os-			;;-		esac-		;;-	-nto-qnx*)-		;;-	-nto*)-		os=`echo $os | sed -e 's|nto|nto-qnx|'`-		;;-	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \-	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \-	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)-		;;-	-mac*)-		os=`echo $os | sed -e 's|mac|macos|'`-		;;-	-linux-dietlibc)-		os=-linux-dietlibc-		;;-	-linux*)-		os=`echo $os | sed -e 's|linux|linux-gnu|'`-		;;-	-sunos5*)-		os=`echo $os | sed -e 's|sunos5|solaris2|'`-		;;-	-sunos6*)-		os=`echo $os | sed -e 's|sunos6|solaris3|'`-		;;-	-opened*)-		os=-openedition-		;;-	-os400*)-		os=-os400-		;;-	-wince*)-		os=-wince-		;;-	-osfrose*)-		os=-osfrose-		;;-	-osf*)-		os=-osf-		;;-	-utek*)-		os=-bsd-		;;-	-dynix*)-		os=-bsd-		;;-	-acis*)-		os=-aos-		;;-	-atheos*)-		os=-atheos-		;;-	-syllable*)-		os=-syllable-		;;-	-386bsd)-		os=-bsd-		;;-	-ctix* | -uts*)-		os=-sysv-		;;-	-nova*)-		os=-rtmk-nova-		;;-	-ns2 )-		os=-nextstep2-		;;-	-nsk*)-		os=-nsk-		;;-	# Preserve the version number of sinix5.-	-sinix5.*)-		os=`echo $os | sed -e 's|sinix|sysv|'`-		;;-	-sinix*)-		os=-sysv4-		;;-	-tpf*)-		os=-tpf-		;;-	-triton*)-		os=-sysv3-		;;-	-oss*)-		os=-sysv3-		;;-	-svr4)-		os=-sysv4-		;;-	-svr3)-		os=-sysv3-		;;-	-sysvr4)-		os=-sysv4-		;;-	# This must come after -sysvr4.-	-sysv*)-		;;-	-ose*)-		os=-ose-		;;-	-es1800*)-		os=-ose-		;;-	-xenix)-		os=-xenix-		;;-	-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)-		os=-mint-		;;-	-aros*)-		os=-aros-		;;-	-zvmoe)-		os=-zvmoe-		;;-	-dicos*)-		os=-dicos-		;;-	-nacl*)-		;;-	-none)-		;;-	*)-		# Get rid of the `-' at the beginning of $os.-		os=`echo $os | sed 's/[^-]*-//'`-		echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2-		exit 1-		;;-esac-else--# Here we handle the default operating systems that come with various machines.-# The value should be what the vendor currently ships out the door with their-# machine or put another way, the most popular os provided with the machine.--# Note that if you're going to try to match "-MANUFACTURER" here (say,-# "-sun"), then you have to tell the case statement up towards the top-# that MANUFACTURER isn't an operating system.  Otherwise, code above-# will signal an error saying that MANUFACTURER isn't an operating-# system, and we'll never get to this point.--case $basic_machine in-	score-*)-		os=-elf-		;;-	spu-*)-		os=-elf-		;;-	*-acorn)-		os=-riscix1.2-		;;-	arm*-rebel)-		os=-linux-		;;-	arm*-semi)-		os=-aout-		;;-	c4x-* | tic4x-*)-		os=-coff-		;;-	c8051-*)-		os=-elf-		;;-	hexagon-*)-		os=-elf-		;;-	tic54x-*)-		os=-coff-		;;-	tic55x-*)-		os=-coff-		;;-	tic6x-*)-		os=-coff-		;;-	# This must come before the *-dec entry.-	pdp10-*)-		os=-tops20-		;;-	pdp11-*)-		os=-none-		;;-	*-dec | vax-*)-		os=-ultrix4.2-		;;-	m68*-apollo)-		os=-domain-		;;-	i386-sun)-		os=-sunos4.0.2-		;;-	m68000-sun)-		os=-sunos3-		;;-	m68*-cisco)-		os=-aout-		;;-	mep-*)-		os=-elf-		;;-	mips*-cisco)-		os=-elf-		;;-	mips*-*)-		os=-elf-		;;-	or32-*)-		os=-coff-		;;-	*-tti)	# must be before sparc entry or we get the wrong os.-		os=-sysv3-		;;-	sparc-* | *-sun)-		os=-sunos4.1.1-		;;-	*-be)-		os=-beos-		;;-	*-haiku)-		os=-haiku-		;;-	*-ibm)-		os=-aix-		;;-	*-knuth)-		os=-mmixware-		;;-	*-wec)-		os=-proelf-		;;-	*-winbond)-		os=-proelf-		;;-	*-oki)-		os=-proelf-		;;-	*-hp)-		os=-hpux-		;;-	*-hitachi)-		os=-hiux-		;;-	i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)-		os=-sysv-		;;-	*-cbm)-		os=-amigaos-		;;-	*-dg)-		os=-dgux-		;;-	*-dolphin)-		os=-sysv3-		;;-	m68k-ccur)-		os=-rtu-		;;-	m88k-omron*)-		os=-luna-		;;-	*-next )-		os=-nextstep-		;;-	*-sequent)-		os=-ptx-		;;-	*-crds)-		os=-unos-		;;-	*-ns)-		os=-genix-		;;-	i370-*)-		os=-mvs-		;;-	*-next)-		os=-nextstep3-		;;-	*-gould)-		os=-sysv-		;;-	*-highlevel)-		os=-bsd-		;;-	*-encore)-		os=-bsd-		;;-	*-sgi)-		os=-irix-		;;-	*-siemens)-		os=-sysv4-		;;-	*-masscomp)-		os=-rtu-		;;-	f30[01]-fujitsu | f700-fujitsu)-		os=-uxpv-		;;-	*-rom68k)-		os=-coff-		;;-	*-*bug)-		os=-coff-		;;-	*-apple)-		os=-macos-		;;-	*-atari*)-		os=-mint-		;;-	*)-		os=-none-		;;-esac-fi--# Here we handle the case where we know the os, and the CPU type, but not the-# manufacturer.  We pick the logical manufacturer.-vendor=unknown-case $basic_machine in-	*-unknown)-		case $os in-			-riscix*)-				vendor=acorn-				;;-			-sunos*)-				vendor=sun-				;;-			-cnk*|-aix*)-				vendor=ibm-				;;-			-beos*)-				vendor=be-				;;-			-hpux*)-				vendor=hp-				;;-			-mpeix*)-				vendor=hp-				;;-			-hiux*)-				vendor=hitachi-				;;-			-unos*)-				vendor=crds-				;;-			-dgux*)-				vendor=dg-				;;-			-luna*)-				vendor=omron-				;;-			-genix*)-				vendor=ns-				;;-			-mvs* | -opened*)-				vendor=ibm-				;;-			-os400*)-				vendor=ibm-				;;-			-ptx*)-				vendor=sequent-				;;-			-tpf*)-				vendor=ibm-				;;-			-vxsim* | -vxworks* | -windiss*)-				vendor=wrs-				;;-			-aux*)-				vendor=apple-				;;-			-hms*)-				vendor=hitachi-				;;-			-mpw* | -macos*)-				vendor=apple-				;;-			-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)-				vendor=atari-				;;-			-vos*)-				vendor=stratus-				;;-		esac-		basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`-		;;-esac--echo $basic_machine$os-exit--# Local variables:-# eval: (add-hook 'write-file-hooks 'time-stamp)-# time-stamp-start: "timestamp='"-# time-stamp-format: "%:y-%02m-%02d"-# time-stamp-end: "'"-# End:
− configure
@@ -1,21865 +0,0 @@-#! /bin/sh-# Guess values for system-dependent variables and create Makefiles.-# Generated by GNU Autoconf 2.69 for Haskell base package 1.0.-#-# Report bugs to <libraries@haskell.org>.-#-#-# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.-#-#-# This configure script is free software; the Free Software Foundation-# gives unlimited permission to copy, distribute and modify it.-## -------------------- ##-## M4sh Initialization. ##-## -------------------- ##--# Be more Bourne compatible-DUALCASE=1; export DUALCASE # for MKS sh-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :-  emulate sh-  NULLCMD=:-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which-  # is contrary to our usage.  Disable this feature.-  alias -g '${1+"$@"}'='"$@"'-  setopt NO_GLOB_SUBST-else-  case `(set -o) 2>/dev/null` in #(-  *posix*) :-    set -o posix ;; #(-  *) :-     ;;-esac-fi---as_nl='-'-export as_nl-# Printing a long string crashes Solaris 7 /usr/bin/printf.-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo-# Prefer a ksh shell builtin over an external printf program on Solaris,-# but without wasting forks for bash or zsh.-if test -z "$BASH_VERSION$ZSH_VERSION" \-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then-  as_echo='print -r --'-  as_echo_n='print -rn --'-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then-  as_echo='printf %s\n'-  as_echo_n='printf %s'-else-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'-    as_echo_n='/usr/ucb/echo -n'-  else-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'-    as_echo_n_body='eval-      arg=$1;-      case $arg in #(-      *"$as_nl"*)-	expr "X$arg" : "X\\(.*\\)$as_nl";-	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;-      esac;-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"-    '-    export as_echo_n_body-    as_echo_n='sh -c $as_echo_n_body as_echo'-  fi-  export as_echo_body-  as_echo='sh -c $as_echo_body as_echo'-fi--# The user is always right.-if test "${PATH_SEPARATOR+set}" != set; then-  PATH_SEPARATOR=:-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {-    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||-      PATH_SEPARATOR=';'-  }-fi---# IFS-# We need space, tab and new line, in precisely that order.  Quoting is-# there to prevent editors from complaining about space-tab.-# (If _AS_PATH_WALK were called with IFS unset, it would disable word-# splitting by setting IFS to empty value.)-IFS=" ""	$as_nl"--# Find who we are.  Look in the path if we contain no directory separator.-as_myself=-case $0 in #((-  *[\\/]* ) as_myself=$0 ;;-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break-  done-IFS=$as_save_IFS--     ;;-esac-# We did not find ourselves, most probably we were run as `sh COMMAND'-# in which case we are not to be found in the path.-if test "x$as_myself" = x; then-  as_myself=$0-fi-if test ! -f "$as_myself"; then-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2-  exit 1-fi--# Unset variables that we do not need and which cause bugs (e.g. in-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"-# suppresses any "Segmentation fault" message there.  '((' could-# trigger a bug in pdksh 5.2.14.-for as_var in BASH_ENV ENV MAIL MAILPATH-do eval test x\${$as_var+set} = xset \-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :-done-PS1='$ '-PS2='> '-PS4='+ '--# NLS nuisances.-LC_ALL=C-export LC_ALL-LANGUAGE=C-export LANGUAGE--# CDPATH.-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH--# Use a proper internal environment variable to ensure we don't fall-  # into an infinite loop, continuously re-executing ourselves.-  if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then-    _as_can_reexec=no; export _as_can_reexec;-    # We cannot yet assume a decent shell, so we have to provide a-# neutralization value for shells without unset; and this also-# works around shells that cannot unset nonexistent variables.-# Preserve -v and -x to the replacement shell.-BASH_ENV=/dev/null-ENV=/dev/null-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV-case $- in # ((((-  *v*x* | *x*v* ) as_opts=-vx ;;-  *v* ) as_opts=-v ;;-  *x* ) as_opts=-x ;;-  * ) as_opts= ;;-esac-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}-# Admittedly, this is quite paranoid, since all the known shells bail-# out after a failed `exec'.-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2-as_fn_exit 255-  fi-  # We don't want this to propagate to other subprocesses.-          { _as_can_reexec=; unset _as_can_reexec;}-if test "x$CONFIG_SHELL" = x; then-  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :-  emulate sh-  NULLCMD=:-  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which-  # is contrary to our usage.  Disable this feature.-  alias -g '\${1+\"\$@\"}'='\"\$@\"'-  setopt NO_GLOB_SUBST-else-  case \`(set -o) 2>/dev/null\` in #(-  *posix*) :-    set -o posix ;; #(-  *) :-     ;;-esac-fi-"-  as_required="as_fn_return () { (exit \$1); }-as_fn_success () { as_fn_return 0; }-as_fn_failure () { as_fn_return 1; }-as_fn_ret_success () { return 0; }-as_fn_ret_failure () { return 1; }--exitcode=0-as_fn_success || { exitcode=1; echo as_fn_success failed.; }-as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }-as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }-as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }-if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :--else-  exitcode=1; echo positional parameters were not saved.-fi-test x\$exitcode = x0 || exit 1-test -x / || exit 1"-  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO-  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO-  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&-  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1-test \$(( 1 + 1 )) = 2 || exit 1"-  if (eval "$as_required") 2>/dev/null; then :-  as_have_required=yes-else-  as_have_required=no-fi-  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :--else-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-as_found=false-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-  as_found=:-  case $as_dir in #(-	 /*)-	   for as_base in sh bash ksh sh5; do-	     # Try only shells that exist, to save several forks.-	     as_shell=$as_dir/$as_base-	     if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&-		    { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :-  CONFIG_SHELL=$as_shell as_have_required=yes-		   if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :-  break 2-fi-fi-	   done;;-       esac-  as_found=false-done-$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&-	      { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :-  CONFIG_SHELL=$SHELL as_have_required=yes-fi; }-IFS=$as_save_IFS---      if test "x$CONFIG_SHELL" != x; then :-  export CONFIG_SHELL-             # We cannot yet assume a decent shell, so we have to provide a-# neutralization value for shells without unset; and this also-# works around shells that cannot unset nonexistent variables.-# Preserve -v and -x to the replacement shell.-BASH_ENV=/dev/null-ENV=/dev/null-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV-case $- in # ((((-  *v*x* | *x*v* ) as_opts=-vx ;;-  *v* ) as_opts=-v ;;-  *x* ) as_opts=-x ;;-  * ) as_opts= ;;-esac-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}-# Admittedly, this is quite paranoid, since all the known shells bail-# out after a failed `exec'.-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2-exit 255-fi--    if test x$as_have_required = xno; then :-  $as_echo "$0: This script requires a shell more modern than all"-  $as_echo "$0: the shells that I found on your system."-  if test x${ZSH_VERSION+set} = xset ; then-    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"-    $as_echo "$0: be upgraded to zsh 4.3.4 or later."-  else-    $as_echo "$0: Please tell bug-autoconf@gnu.org and-$0: libraries@haskell.org about your system, including any-$0: error possibly output before this message. Then install-$0: a modern shell, or manually run the script under such a-$0: shell if you do have one."-  fi-  exit 1-fi-fi-fi-SHELL=${CONFIG_SHELL-/bin/sh}-export SHELL-# Unset more variables known to interfere with behavior of common tools.-CLICOLOR_FORCE= GREP_OPTIONS=-unset CLICOLOR_FORCE GREP_OPTIONS--## --------------------- ##-## M4sh Shell Functions. ##-## --------------------- ##-# as_fn_unset VAR-# ----------------# Portably unset VAR.-as_fn_unset ()-{-  { eval $1=; unset $1;}-}-as_unset=as_fn_unset--# as_fn_set_status STATUS-# ------------------------# Set $? to STATUS, without forking.-as_fn_set_status ()-{-  return $1-} # as_fn_set_status--# as_fn_exit STATUS-# ------------------# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.-as_fn_exit ()-{-  set +e-  as_fn_set_status $1-  exit $1-} # as_fn_exit--# as_fn_mkdir_p-# --------------# Create "$as_dir" as a directory, including parents if necessary.-as_fn_mkdir_p ()-{--  case $as_dir in #(-  -*) as_dir=./$as_dir;;-  esac-  test -d "$as_dir" || eval $as_mkdir_p || {-    as_dirs=-    while :; do-      case $as_dir in #(-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(-      *) as_qdir=$as_dir;;-      esac-      as_dirs="'$as_qdir' $as_dirs"-      as_dir=`$as_dirname -- "$as_dir" ||-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \-	 X"$as_dir" : 'X\(//\)[^/]' \| \-	 X"$as_dir" : 'X\(//\)$' \| \-	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||-$as_echo X"$as_dir" |-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{-	    s//\1/-	    q-	  }-	  /^X\(\/\/\)[^/].*/{-	    s//\1/-	    q-	  }-	  /^X\(\/\/\)$/{-	    s//\1/-	    q-	  }-	  /^X\(\/\).*/{-	    s//\1/-	    q-	  }-	  s/.*/./; q'`-      test -d "$as_dir" && break-    done-    test -z "$as_dirs" || eval "mkdir $as_dirs"-  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"---} # as_fn_mkdir_p--# as_fn_executable_p FILE-# ------------------------# Test if FILE is an executable regular file.-as_fn_executable_p ()-{-  test -f "$1" && test -x "$1"-} # as_fn_executable_p-# as_fn_append VAR VALUE-# -----------------------# Append the text in VALUE to the end of the definition contained in VAR. Take-# advantage of any shell optimizations that allow amortized linear growth over-# repeated appends, instead of the typical quadratic growth present in naive-# implementations.-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :-  eval 'as_fn_append ()-  {-    eval $1+=\$2-  }'-else-  as_fn_append ()-  {-    eval $1=\$$1\$2-  }-fi # as_fn_append--# as_fn_arith ARG...-# -------------------# Perform arithmetic evaluation on the ARGs, and store the result in the-# global $as_val. Take advantage of shells that can avoid forks. The arguments-# must be portable across $(()) and expr.-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :-  eval 'as_fn_arith ()-  {-    as_val=$(( $* ))-  }'-else-  as_fn_arith ()-  {-    as_val=`expr "$@" || test $? -eq 1`-  }-fi # as_fn_arith---# as_fn_error STATUS ERROR [LINENO LOG_FD]-# -----------------------------------------# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the-# script with STATUS, using 1 if that was 0.-as_fn_error ()-{-  as_status=$1; test $as_status -eq 0 && as_status=1-  if test "$4"; then-    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4-  fi-  $as_echo "$as_me: error: $2" >&2-  as_fn_exit $as_status-} # as_fn_error--if expr a : '\(a\)' >/dev/null 2>&1 &&-   test "X`expr 00001 : '.*\(...\)'`" = X001; then-  as_expr=expr-else-  as_expr=false-fi--if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then-  as_basename=basename-else-  as_basename=false-fi--if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then-  as_dirname=dirname-else-  as_dirname=false-fi--as_me=`$as_basename -- "$0" ||-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \-	 X"$0" : 'X\(//\)$' \| \-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||-$as_echo X/"$0" |-    sed '/^.*\/\([^/][^/]*\)\/*$/{-	    s//\1/-	    q-	  }-	  /^X\/\(\/\/\)$/{-	    s//\1/-	    q-	  }-	  /^X\/\(\/\).*/{-	    s//\1/-	    q-	  }-	  s/.*/./; q'`--# Avoid depending upon Character Ranges.-as_cr_letters='abcdefghijklmnopqrstuvwxyz'-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'-as_cr_Letters=$as_cr_letters$as_cr_LETTERS-as_cr_digits='0123456789'-as_cr_alnum=$as_cr_Letters$as_cr_digits---  as_lineno_1=$LINENO as_lineno_1a=$LINENO-  as_lineno_2=$LINENO as_lineno_2a=$LINENO-  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&-  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {-  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)-  sed -n '-    p-    /[$]LINENO/=-  ' <$as_myself |-    sed '-      s/[$]LINENO.*/&-/-      t lineno-      b-      :lineno-      N-      :loop-      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/-      t loop-      s/-\n.*//-    ' >$as_me.lineno &&-  chmod +x "$as_me.lineno" ||-    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }--  # If we had to re-execute with $CONFIG_SHELL, we're ensured to have-  # already done that, so ensure we don't try to do so again and fall-  # in an infinite loop.  This has already happened in practice.-  _as_can_reexec=no; export _as_can_reexec-  # Don't try to exec as it changes $[0], causing all sort of problems-  # (the dirname of $[0] is not the place where we might find the-  # original and so on.  Autoconf is especially sensitive to this).-  . "./$as_me.lineno"-  # Exit status is that of the last command.-  exit-}--ECHO_C= ECHO_N= ECHO_T=-case `echo -n x` in #(((((--n*)-  case `echo 'xy\c'` in-  *c*) ECHO_T='	';;	# ECHO_T is single tab character.-  xy)  ECHO_C='\c';;-  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null-       ECHO_T='	';;-  esac;;-*)-  ECHO_N='-n';;-esac--rm -f conf$$ conf$$.exe conf$$.file-if test -d conf$$.dir; then-  rm -f conf$$.dir/conf$$.file-else-  rm -f conf$$.dir-  mkdir conf$$.dir 2>/dev/null-fi-if (echo >conf$$.file) 2>/dev/null; then-  if ln -s conf$$.file conf$$ 2>/dev/null; then-    as_ln_s='ln -s'-    # ... but there are two gotchas:-    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.-    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.-    # In both cases, we have to default to `cp -pR'.-    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||-      as_ln_s='cp -pR'-  elif ln conf$$.file conf$$ 2>/dev/null; then-    as_ln_s=ln-  else-    as_ln_s='cp -pR'-  fi-else-  as_ln_s='cp -pR'-fi-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file-rmdir conf$$.dir 2>/dev/null--if mkdir -p . 2>/dev/null; then-  as_mkdir_p='mkdir -p "$as_dir"'-else-  test -d ./-p && rmdir ./-p-  as_mkdir_p=false-fi--as_test_x='test -x'-as_executable_p=as_fn_executable_p--# Sed expression to map a string onto a valid CPP name.-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"--# Sed expression to map a string onto a valid variable name.-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"---test -n "$DJDIR" || exec 7<&0 </dev/null-exec 6>&1--# Name of the host.-# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,-# so uname gets run too.-ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`--#-# Initializations.-#-ac_default_prefix=/usr/local-ac_clean_files=-ac_config_libobj_dir=.-LIBOBJS=-cross_compiling=no-subdirs=-MFLAGS=-MAKEFLAGS=--# Identity of this package.-PACKAGE_NAME='Haskell base package'-PACKAGE_TARNAME='base'-PACKAGE_VERSION='1.0'-PACKAGE_STRING='Haskell base package 1.0'-PACKAGE_BUGREPORT='libraries@haskell.org'-PACKAGE_URL=''--ac_unique_file="include/HsBase.h"-# Factoring default headers for most tests.-ac_includes_default="\-#include <stdio.h>-#ifdef HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif-#ifdef HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif-#ifdef STDC_HEADERS-# include <stdlib.h>-# include <stddef.h>-#else-# ifdef HAVE_STDLIB_H-#  include <stdlib.h>-# endif-#endif-#ifdef HAVE_STRING_H-# if !defined STDC_HEADERS && defined HAVE_MEMORY_H-#  include <memory.h>-# endif-# include <string.h>-#endif-#ifdef HAVE_STRINGS_H-# include <strings.h>-#endif-#ifdef HAVE_INTTYPES_H-# include <inttypes.h>-#endif-#ifdef HAVE_STDINT_H-# include <stdint.h>-#endif-#ifdef HAVE_UNISTD_H-# include <unistd.h>-#endif"--ac_subst_vars='LTLIBOBJS-LIBOBJS-EXTRA_LIBS-ICONV_LIB_DIRS-ICONV_INCLUDE_DIRS-EGREP-GREP-CPP-OBJEXT-EXEEXT-ac_ct_CC-CPPFLAGS-LDFLAGS-CFLAGS-CC-target_os-target_vendor-target_cpu-target-host_os-host_vendor-host_cpu-host-build_os-build_vendor-build_cpu-build-target_alias-host_alias-build_alias-LIBS-ECHO_T-ECHO_N-ECHO_C-DEFS-mandir-localedir-libdir-psdir-pdfdir-dvidir-htmldir-infodir-docdir-oldincludedir-includedir-localstatedir-sharedstatedir-sysconfdir-datadir-datarootdir-libexecdir-sbindir-bindir-program_transform_name-prefix-exec_prefix-PACKAGE_URL-PACKAGE_BUGREPORT-PACKAGE_STRING-PACKAGE_VERSION-PACKAGE_TARNAME-PACKAGE_NAME-PATH_SEPARATOR-SHELL'-ac_subst_files=''-ac_user_opts='-enable_option_checking-with_cc-enable_largefile-with_iconv_includes-with_iconv_libraries-'-      ac_precious_vars='build_alias-host_alias-target_alias-CC-CFLAGS-LDFLAGS-LIBS-CPPFLAGS-CPP'---# Initialize some variables set by options.-ac_init_help=-ac_init_version=false-ac_unrecognized_opts=-ac_unrecognized_sep=-# The variables have the same names as the options, with-# dashes changed to underlines.-cache_file=/dev/null-exec_prefix=NONE-no_create=-no_recursion=-prefix=NONE-program_prefix=NONE-program_suffix=NONE-program_transform_name=s,x,x,-silent=-site=-srcdir=-verbose=-x_includes=NONE-x_libraries=NONE--# Installation directory options.-# These are left unexpanded so users can "make install exec_prefix=/foo"-# and all the variables that are supposed to be based on exec_prefix-# by default will actually change.-# Use braces instead of parens because sh, perl, etc. also accept them.-# (The list follows the same order as the GNU Coding Standards.)-bindir='${exec_prefix}/bin'-sbindir='${exec_prefix}/sbin'-libexecdir='${exec_prefix}/libexec'-datarootdir='${prefix}/share'-datadir='${datarootdir}'-sysconfdir='${prefix}/etc'-sharedstatedir='${prefix}/com'-localstatedir='${prefix}/var'-includedir='${prefix}/include'-oldincludedir='/usr/include'-docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'-infodir='${datarootdir}/info'-htmldir='${docdir}'-dvidir='${docdir}'-pdfdir='${docdir}'-psdir='${docdir}'-libdir='${exec_prefix}/lib'-localedir='${datarootdir}/locale'-mandir='${datarootdir}/man'--ac_prev=-ac_dashdash=-for ac_option-do-  # If the previous option needs an argument, assign it.-  if test -n "$ac_prev"; then-    eval $ac_prev=\$ac_option-    ac_prev=-    continue-  fi--  case $ac_option in-  *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;-  *=)   ac_optarg= ;;-  *)    ac_optarg=yes ;;-  esac--  # Accept the important Cygnus configure options, so we can diagnose typos.--  case $ac_dashdash$ac_option in-  --)-    ac_dashdash=yes ;;--  -bindir | --bindir | --bindi | --bind | --bin | --bi)-    ac_prev=bindir ;;-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)-    bindir=$ac_optarg ;;--  -build | --build | --buil | --bui | --bu)-    ac_prev=build_alias ;;-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)-    build_alias=$ac_optarg ;;--  -cache-file | --cache-file | --cache-fil | --cache-fi \-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)-    ac_prev=cache_file ;;-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)-    cache_file=$ac_optarg ;;--  --config-cache | -C)-    cache_file=config.cache ;;--  -datadir | --datadir | --datadi | --datad)-    ac_prev=datadir ;;-  -datadir=* | --datadir=* | --datadi=* | --datad=*)-    datadir=$ac_optarg ;;--  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \-  | --dataroo | --dataro | --datar)-    ac_prev=datarootdir ;;-  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \-  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)-    datarootdir=$ac_optarg ;;--  -disable-* | --disable-*)-    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`-    # Reject names that are not valid shell variable names.-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&-      as_fn_error $? "invalid feature name: $ac_useropt"-    ac_useropt_orig=$ac_useropt-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`-    case $ac_user_opts in-      *"-"enable_$ac_useropt"-"*) ;;-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"-	 ac_unrecognized_sep=', ';;-    esac-    eval enable_$ac_useropt=no ;;--  -docdir | --docdir | --docdi | --doc | --do)-    ac_prev=docdir ;;-  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)-    docdir=$ac_optarg ;;--  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)-    ac_prev=dvidir ;;-  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)-    dvidir=$ac_optarg ;;--  -enable-* | --enable-*)-    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`-    # Reject names that are not valid shell variable names.-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&-      as_fn_error $? "invalid feature name: $ac_useropt"-    ac_useropt_orig=$ac_useropt-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`-    case $ac_user_opts in-      *"-"enable_$ac_useropt"-"*) ;;-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"-	 ac_unrecognized_sep=', ';;-    esac-    eval enable_$ac_useropt=\$ac_optarg ;;--  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \-  | --exec | --exe | --ex)-    ac_prev=exec_prefix ;;-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \-  | --exec=* | --exe=* | --ex=*)-    exec_prefix=$ac_optarg ;;--  -gas | --gas | --ga | --g)-    # Obsolete; use --with-gas.-    with_gas=yes ;;--  -help | --help | --hel | --he | -h)-    ac_init_help=long ;;-  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)-    ac_init_help=recursive ;;-  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)-    ac_init_help=short ;;--  -host | --host | --hos | --ho)-    ac_prev=host_alias ;;-  -host=* | --host=* | --hos=* | --ho=*)-    host_alias=$ac_optarg ;;--  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)-    ac_prev=htmldir ;;-  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \-  | --ht=*)-    htmldir=$ac_optarg ;;--  -includedir | --includedir | --includedi | --included | --include \-  | --includ | --inclu | --incl | --inc)-    ac_prev=includedir ;;-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \-  | --includ=* | --inclu=* | --incl=* | --inc=*)-    includedir=$ac_optarg ;;--  -infodir | --infodir | --infodi | --infod | --info | --inf)-    ac_prev=infodir ;;-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)-    infodir=$ac_optarg ;;--  -libdir | --libdir | --libdi | --libd)-    ac_prev=libdir ;;-  -libdir=* | --libdir=* | --libdi=* | --libd=*)-    libdir=$ac_optarg ;;--  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \-  | --libexe | --libex | --libe)-    ac_prev=libexecdir ;;-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \-  | --libexe=* | --libex=* | --libe=*)-    libexecdir=$ac_optarg ;;--  -localedir | --localedir | --localedi | --localed | --locale)-    ac_prev=localedir ;;-  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)-    localedir=$ac_optarg ;;--  -localstatedir | --localstatedir | --localstatedi | --localstated \-  | --localstate | --localstat | --localsta | --localst | --locals)-    ac_prev=localstatedir ;;-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \-  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)-    localstatedir=$ac_optarg ;;--  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)-    ac_prev=mandir ;;-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)-    mandir=$ac_optarg ;;--  -nfp | --nfp | --nf)-    # Obsolete; use --without-fp.-    with_fp=no ;;--  -no-create | --no-create | --no-creat | --no-crea | --no-cre \-  | --no-cr | --no-c | -n)-    no_create=yes ;;--  -no-recursion | --no-recursion | --no-recursio | --no-recursi \-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)-    no_recursion=yes ;;--  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \-  | --oldin | --oldi | --old | --ol | --o)-    ac_prev=oldincludedir ;;-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)-    oldincludedir=$ac_optarg ;;--  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)-    ac_prev=prefix ;;-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)-    prefix=$ac_optarg ;;--  -program-prefix | --program-prefix | --program-prefi | --program-pref \-  | --program-pre | --program-pr | --program-p)-    ac_prev=program_prefix ;;-  -program-prefix=* | --program-prefix=* | --program-prefi=* \-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)-    program_prefix=$ac_optarg ;;--  -program-suffix | --program-suffix | --program-suffi | --program-suff \-  | --program-suf | --program-su | --program-s)-    ac_prev=program_suffix ;;-  -program-suffix=* | --program-suffix=* | --program-suffi=* \-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)-    program_suffix=$ac_optarg ;;--  -program-transform-name | --program-transform-name \-  | --program-transform-nam | --program-transform-na \-  | --program-transform-n | --program-transform- \-  | --program-transform | --program-transfor \-  | --program-transfo | --program-transf \-  | --program-trans | --program-tran \-  | --progr-tra | --program-tr | --program-t)-    ac_prev=program_transform_name ;;-  -program-transform-name=* | --program-transform-name=* \-  | --program-transform-nam=* | --program-transform-na=* \-  | --program-transform-n=* | --program-transform-=* \-  | --program-transform=* | --program-transfor=* \-  | --program-transfo=* | --program-transf=* \-  | --program-trans=* | --program-tran=* \-  | --progr-tra=* | --program-tr=* | --program-t=*)-    program_transform_name=$ac_optarg ;;--  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)-    ac_prev=pdfdir ;;-  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)-    pdfdir=$ac_optarg ;;--  -psdir | --psdir | --psdi | --psd | --ps)-    ac_prev=psdir ;;-  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)-    psdir=$ac_optarg ;;--  -q | -quiet | --quiet | --quie | --qui | --qu | --q \-  | -silent | --silent | --silen | --sile | --sil)-    silent=yes ;;--  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)-    ac_prev=sbindir ;;-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \-  | --sbi=* | --sb=*)-    sbindir=$ac_optarg ;;--  -sharedstatedir | --sharedstatedir | --sharedstatedi \-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \-  | --sharedst | --shareds | --shared | --share | --shar \-  | --sha | --sh)-    ac_prev=sharedstatedir ;;-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \-  | --sha=* | --sh=*)-    sharedstatedir=$ac_optarg ;;--  -site | --site | --sit)-    ac_prev=site ;;-  -site=* | --site=* | --sit=*)-    site=$ac_optarg ;;--  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)-    ac_prev=srcdir ;;-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)-    srcdir=$ac_optarg ;;--  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \-  | --syscon | --sysco | --sysc | --sys | --sy)-    ac_prev=sysconfdir ;;-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)-    sysconfdir=$ac_optarg ;;--  -target | --target | --targe | --targ | --tar | --ta | --t)-    ac_prev=target_alias ;;-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)-    target_alias=$ac_optarg ;;--  -v | -verbose | --verbose | --verbos | --verbo | --verb)-    verbose=yes ;;--  -version | --version | --versio | --versi | --vers | -V)-    ac_init_version=: ;;--  -with-* | --with-*)-    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`-    # Reject names that are not valid shell variable names.-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&-      as_fn_error $? "invalid package name: $ac_useropt"-    ac_useropt_orig=$ac_useropt-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`-    case $ac_user_opts in-      *"-"with_$ac_useropt"-"*) ;;-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"-	 ac_unrecognized_sep=', ';;-    esac-    eval with_$ac_useropt=\$ac_optarg ;;--  -without-* | --without-*)-    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`-    # Reject names that are not valid shell variable names.-    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&-      as_fn_error $? "invalid package name: $ac_useropt"-    ac_useropt_orig=$ac_useropt-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`-    case $ac_user_opts in-      *"-"with_$ac_useropt"-"*) ;;-      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"-	 ac_unrecognized_sep=', ';;-    esac-    eval with_$ac_useropt=no ;;--  --x)-    # Obsolete; use --with-x.-    with_x=yes ;;--  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \-  | --x-incl | --x-inc | --x-in | --x-i)-    ac_prev=x_includes ;;-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)-    x_includes=$ac_optarg ;;--  -x-libraries | --x-libraries | --x-librarie | --x-librari \-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)-    ac_prev=x_libraries ;;-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)-    x_libraries=$ac_optarg ;;--  -*) as_fn_error $? "unrecognized option: \`$ac_option'-Try \`$0 --help' for more information"-    ;;--  *=*)-    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`-    # Reject names that are not valid shell variable names.-    case $ac_envvar in #(-      '' | [0-9]* | *[!_$as_cr_alnum]* )-      as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;-    esac-    eval $ac_envvar=\$ac_optarg-    export $ac_envvar ;;--  *)-    # FIXME: should be removed in autoconf 3.0.-    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2-    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&-      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2-    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"-    ;;--  esac-done--if test -n "$ac_prev"; then-  ac_option=--`echo $ac_prev | sed 's/_/-/g'`-  as_fn_error $? "missing argument to $ac_option"-fi--if test -n "$ac_unrecognized_opts"; then-  case $enable_option_checking in-    no) ;;-    fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;-    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;-  esac-fi--# Check all directory arguments for consistency.-for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \-		datadir sysconfdir sharedstatedir localstatedir includedir \-		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \-		libdir localedir mandir-do-  eval ac_val=\$$ac_var-  # Remove trailing slashes.-  case $ac_val in-    */ )-      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`-      eval $ac_var=\$ac_val;;-  esac-  # Be sure to have absolute directory names.-  case $ac_val in-    [\\/$]* | ?:[\\/]* )  continue;;-    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;-  esac-  as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"-done--# There might be people who depend on the old broken behavior: `$host'-# used to hold the argument of --host etc.-# FIXME: To remove some day.-build=$build_alias-host=$host_alias-target=$target_alias--# FIXME: To remove some day.-if test "x$host_alias" != x; then-  if test "x$build_alias" = x; then-    cross_compiling=maybe-  elif test "x$build_alias" != "x$host_alias"; then-    cross_compiling=yes-  fi-fi--ac_tool_prefix=-test -n "$host_alias" && ac_tool_prefix=$host_alias---test "$silent" = yes && exec 6>/dev/null---ac_pwd=`pwd` && test -n "$ac_pwd" &&-ac_ls_di=`ls -di .` &&-ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||-  as_fn_error $? "working directory cannot be determined"-test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||-  as_fn_error $? "pwd does not report name of working directory"---# Find the source files, if location was not specified.-if test -z "$srcdir"; then-  ac_srcdir_defaulted=yes-  # Try the directory containing this script, then the parent directory.-  ac_confdir=`$as_dirname -- "$as_myself" ||-$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \-	 X"$as_myself" : 'X\(//\)[^/]' \| \-	 X"$as_myself" : 'X\(//\)$' \| \-	 X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||-$as_echo X"$as_myself" |-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{-	    s//\1/-	    q-	  }-	  /^X\(\/\/\)[^/].*/{-	    s//\1/-	    q-	  }-	  /^X\(\/\/\)$/{-	    s//\1/-	    q-	  }-	  /^X\(\/\).*/{-	    s//\1/-	    q-	  }-	  s/.*/./; q'`-  srcdir=$ac_confdir-  if test ! -r "$srcdir/$ac_unique_file"; then-    srcdir=..-  fi-else-  ac_srcdir_defaulted=no-fi-if test ! -r "$srcdir/$ac_unique_file"; then-  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."-  as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"-fi-ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"-ac_abs_confdir=`(-	cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"-	pwd)`-# When building in place, set srcdir=.-if test "$ac_abs_confdir" = "$ac_pwd"; then-  srcdir=.-fi-# Remove unnecessary trailing slashes from srcdir.-# Double slashes in file names in object file debugging info-# mess up M-x gdb in Emacs.-case $srcdir in-*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;-esac-for ac_var in $ac_precious_vars; do-  eval ac_env_${ac_var}_set=\${${ac_var}+set}-  eval ac_env_${ac_var}_value=\$${ac_var}-  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}-  eval ac_cv_env_${ac_var}_value=\$${ac_var}-done--#-# Report the --help message.-#-if test "$ac_init_help" = "long"; then-  # Omit some internal or obsolete options to make the list less imposing.-  # This message is too long to be a string in the A/UX 3.1 sh.-  cat <<_ACEOF-\`configure' configures Haskell base package 1.0 to adapt to many kinds of systems.--Usage: $0 [OPTION]... [VAR=VALUE]...--To assign environment variables (e.g., CC, CFLAGS...), specify them as-VAR=VALUE.  See below for descriptions of some of the useful variables.--Defaults for the options are specified in brackets.--Configuration:-  -h, --help              display this help and exit-      --help=short        display options specific to this package-      --help=recursive    display the short help of all the included packages-  -V, --version           display version information and exit-  -q, --quiet, --silent   do not print \`checking ...' messages-      --cache-file=FILE   cache test results in FILE [disabled]-  -C, --config-cache      alias for \`--cache-file=config.cache'-  -n, --no-create         do not create output files-      --srcdir=DIR        find the sources in DIR [configure dir or \`..']--Installation directories:-  --prefix=PREFIX         install architecture-independent files in PREFIX-                          [$ac_default_prefix]-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX-                          [PREFIX]--By default, \`make install' will install all the files in-\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify-an installation prefix other than \`$ac_default_prefix' using \`--prefix',-for instance \`--prefix=\$HOME'.--For better control, use the options below.--Fine tuning of the installation directories:-  --bindir=DIR            user executables [EPREFIX/bin]-  --sbindir=DIR           system admin executables [EPREFIX/sbin]-  --libexecdir=DIR        program executables [EPREFIX/libexec]-  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]-  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]-  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]-  --libdir=DIR            object code libraries [EPREFIX/lib]-  --includedir=DIR        C header files [PREFIX/include]-  --oldincludedir=DIR     C header files for non-gcc [/usr/include]-  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]-  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]-  --infodir=DIR           info documentation [DATAROOTDIR/info]-  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]-  --mandir=DIR            man documentation [DATAROOTDIR/man]-  --docdir=DIR            documentation root [DATAROOTDIR/doc/base]-  --htmldir=DIR           html documentation [DOCDIR]-  --dvidir=DIR            dvi documentation [DOCDIR]-  --pdfdir=DIR            pdf documentation [DOCDIR]-  --psdir=DIR             ps documentation [DOCDIR]-_ACEOF--  cat <<\_ACEOF--System types:-  --build=BUILD     configure for building on BUILD [guessed]-  --host=HOST       cross-compile to build programs to run on HOST [BUILD]-  --target=TARGET   configure for building compilers for TARGET [HOST]-_ACEOF-fi--if test -n "$ac_init_help"; then-  case $ac_init_help in-     short | recursive ) echo "Configuration of Haskell base package 1.0:";;-   esac-  cat <<\_ACEOF--Optional Features:-  --disable-option-checking  ignore unrecognized --enable/--with options-  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)-  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]-  --disable-largefile     omit support for large files--Optional Packages:-  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]-  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)-C compiler-  --with-iconv-includes   directory containing iconv.h-  --with-iconv-libraries  directory containing iconv library--Some influential environment variables:-  CC          C compiler command-  CFLAGS      C compiler flags-  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a-              nonstandard directory <lib dir>-  LIBS        libraries to pass to the linker, e.g. -l<library>-  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if-              you have headers in a nonstandard directory <include dir>-  CPP         C preprocessor--Use these variables to override the choices made by `configure' or to help-it to find libraries and programs with nonstandard names/locations.--Report bugs to <libraries@haskell.org>.-_ACEOF-ac_status=$?-fi--if test "$ac_init_help" = "recursive"; then-  # If there are subdirs, report their specific --help.-  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue-    test -d "$ac_dir" ||-      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||-      continue-    ac_builddir=.--case "$ac_dir" in-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;-*)-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`-  # A ".." for each directory in $ac_dir_suffix.-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`-  case $ac_top_builddir_sub in-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;-  esac ;;-esac-ac_abs_top_builddir=$ac_pwd-ac_abs_builddir=$ac_pwd$ac_dir_suffix-# for backward compatibility:-ac_top_builddir=$ac_top_build_prefix--case $srcdir in-  .)  # We are building in place.-    ac_srcdir=.-    ac_top_srcdir=$ac_top_builddir_sub-    ac_abs_top_srcdir=$ac_pwd ;;-  [\\/]* | ?:[\\/]* )  # Absolute name.-    ac_srcdir=$srcdir$ac_dir_suffix;-    ac_top_srcdir=$srcdir-    ac_abs_top_srcdir=$srcdir ;;-  *) # Relative name.-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix-    ac_top_srcdir=$ac_top_build_prefix$srcdir-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;-esac-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix--    cd "$ac_dir" || { ac_status=$?; continue; }-    # Check for guested configure.-    if test -f "$ac_srcdir/configure.gnu"; then-      echo &&-      $SHELL "$ac_srcdir/configure.gnu" --help=recursive-    elif test -f "$ac_srcdir/configure"; then-      echo &&-      $SHELL "$ac_srcdir/configure" --help=recursive-    else-      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2-    fi || ac_status=$?-    cd "$ac_pwd" || { ac_status=$?; break; }-  done-fi--test -n "$ac_init_help" && exit $ac_status-if $ac_init_version; then-  cat <<\_ACEOF-Haskell base package configure 1.0-generated by GNU Autoconf 2.69--Copyright (C) 2012 Free Software Foundation, Inc.-This configure script is free software; the Free Software Foundation-gives unlimited permission to copy, distribute and modify it.-_ACEOF-  exit-fi--## ------------------------ ##-## Autoconf initialization. ##-## ------------------------ ##--# ac_fn_c_try_compile LINENO-# ---------------------------# Try to compile conftest.$ac_ext, and return whether this succeeded.-ac_fn_c_try_compile ()-{-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-  rm -f conftest.$ac_objext-  if { { ac_try="$ac_compile"-case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_compile") 2>conftest.err-  ac_status=$?-  if test -s conftest.err; then-    grep -v '^ *+' conftest.err >conftest.er1-    cat conftest.er1 >&5-    mv -f conftest.er1 conftest.err-  fi-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; } && {-	 test -z "$ac_c_werror_flag" ||-	 test ! -s conftest.err-       } && test -s conftest.$ac_objext; then :-  ac_retval=0-else-  $as_echo "$as_me: failed program was:" >&5-sed 's/^/| /' conftest.$ac_ext >&5--	ac_retval=1-fi-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno-  as_fn_set_status $ac_retval--} # ac_fn_c_try_compile--# ac_fn_c_check_type LINENO TYPE VAR INCLUDES-# --------------------------------------------# Tests whether TYPE exists after having included INCLUDES, setting cache-# variable VAR accordingly.-ac_fn_c_check_type ()-{-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5-$as_echo_n "checking for $2... " >&6; }-if eval \${$3+:} false; then :-  $as_echo_n "(cached) " >&6-else-  eval "$3=no"-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-int-main ()-{-if (sizeof ($2))-	 return 0;-  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-int-main ()-{-if (sizeof (($2)))-	    return 0;-  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :--else-  eval "$3=yes"-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-fi-eval ac_res=\$$3-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5-$as_echo "$ac_res" >&6; }-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno--} # ac_fn_c_check_type--# ac_fn_c_try_cpp LINENO-# -----------------------# Try to preprocess conftest.$ac_ext, and return whether this succeeded.-ac_fn_c_try_cpp ()-{-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-  if { { ac_try="$ac_cpp conftest.$ac_ext"-case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err-  ac_status=$?-  if test -s conftest.err; then-    grep -v '^ *+' conftest.err >conftest.er1-    cat conftest.er1 >&5-    mv -f conftest.er1 conftest.err-  fi-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; } > conftest.i && {-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||-	 test ! -s conftest.err-       }; then :-  ac_retval=0-else-  $as_echo "$as_me: failed program was:" >&5-sed 's/^/| /' conftest.$ac_ext >&5--    ac_retval=1-fi-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno-  as_fn_set_status $ac_retval--} # ac_fn_c_try_cpp--# ac_fn_c_try_run LINENO-# -----------------------# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes-# that executables *can* be run.-ac_fn_c_try_run ()-{-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-  if { { ac_try="$ac_link"-case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_link") 2>&5-  ac_status=$?-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'-  { { case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_try") 2>&5-  ac_status=$?-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; }; }; then :-  ac_retval=0-else-  $as_echo "$as_me: program exited with status $ac_status" >&5-       $as_echo "$as_me: failed program was:" >&5-sed 's/^/| /' conftest.$ac_ext >&5--       ac_retval=$ac_status-fi-  rm -rf conftest.dSYM conftest_ipa8_conftest.oo-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno-  as_fn_set_status $ac_retval--} # ac_fn_c_try_run--# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES-# --------------------------------------------------------# Tests whether HEADER exists and can be compiled using the include files in-# INCLUDES, setting the cache variable VAR accordingly.-ac_fn_c_check_header_compile ()-{-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5-$as_echo_n "checking for $2... " >&6; }-if eval \${$3+:} false; then :-  $as_echo_n "(cached) " >&6-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-#include <$2>-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  eval "$3=yes"-else-  eval "$3=no"-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-fi-eval ac_res=\$$3-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5-$as_echo "$ac_res" >&6; }-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno--} # ac_fn_c_check_header_compile--# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES-# --------------------------------------------------------# Tests whether HEADER exists, giving a warning if it cannot be compiled using-# the include files in INCLUDES and setting the cache variable VAR-# accordingly.-ac_fn_c_check_header_mongrel ()-{-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-  if eval \${$3+:} false; then :-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5-$as_echo_n "checking for $2... " >&6; }-if eval \${$3+:} false; then :-  $as_echo_n "(cached) " >&6-fi-eval ac_res=\$$3-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5-$as_echo "$ac_res" >&6; }-else-  # Is the header compilable?-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5-$as_echo_n "checking $2 usability... " >&6; }-cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-#include <$2>-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_header_compiler=yes-else-  ac_header_compiler=no-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5-$as_echo "$ac_header_compiler" >&6; }--# Is the header present?-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5-$as_echo_n "checking $2 presence... " >&6; }-cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <$2>-_ACEOF-if ac_fn_c_try_cpp "$LINENO"; then :-  ac_header_preproc=yes-else-  ac_header_preproc=no-fi-rm -f conftest.err conftest.i conftest.$ac_ext-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5-$as_echo "$ac_header_preproc" >&6; }--# So?  What about this header?-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((-  yes:no: )-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5-$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}-    ;;-  no:yes:* )-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5-$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for missing prerequisite headers?" >&5-$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?" >&2;}-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5-$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&5-$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}-( $as_echo "## ------------------------------------ ##-## Report this to libraries@haskell.org ##-## ------------------------------------ ##"-     ) | sed "s/^/$as_me: WARNING:     /" >&2-    ;;-esac-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5-$as_echo_n "checking for $2... " >&6; }-if eval \${$3+:} false; then :-  $as_echo_n "(cached) " >&6-else-  eval "$3=\$ac_header_compiler"-fi-eval ac_res=\$$3-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5-$as_echo "$ac_res" >&6; }-fi-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno--} # ac_fn_c_check_header_mongrel--# ac_fn_c_try_link LINENO-# ------------------------# Try to link conftest.$ac_ext, and return whether this succeeded.-ac_fn_c_try_link ()-{-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-  rm -f conftest.$ac_objext conftest$ac_exeext-  if { { ac_try="$ac_link"-case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_link") 2>conftest.err-  ac_status=$?-  if test -s conftest.err; then-    grep -v '^ *+' conftest.err >conftest.er1-    cat conftest.er1 >&5-    mv -f conftest.er1 conftest.err-  fi-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; } && {-	 test -z "$ac_c_werror_flag" ||-	 test ! -s conftest.err-       } && test -s conftest$ac_exeext && {-	 test "$cross_compiling" = yes ||-	 test -x conftest$ac_exeext-       }; then :-  ac_retval=0-else-  $as_echo "$as_me: failed program was:" >&5-sed 's/^/| /' conftest.$ac_ext >&5--	ac_retval=1-fi-  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information-  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would-  # interfere with the next link command; also delete a directory that is-  # left behind by Apple's compiler.  We do this before executing the actions.-  rm -rf conftest.dSYM conftest_ipa8_conftest.oo-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno-  as_fn_set_status $ac_retval--} # ac_fn_c_try_link--# ac_fn_c_check_func LINENO FUNC VAR-# -----------------------------------# Tests whether FUNC exists, setting the cache variable VAR accordingly-ac_fn_c_check_func ()-{-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5-$as_echo_n "checking for $2... " >&6; }-if eval \${$3+:} false; then :-  $as_echo_n "(cached) " >&6-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-/* Define $2 to an innocuous variant, in case <limits.h> declares $2.-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */-#define $2 innocuous_$2--/* System header to define __stub macros and hopefully few prototypes,-    which can conflict with char $2 (); below.-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since-    <limits.h> exists even on freestanding compilers.  */--#ifdef __STDC__-# include <limits.h>-#else-# include <assert.h>-#endif--#undef $2--/* Override any GCC internal prototype to avoid an error.-   Use char because int might match the return type of a GCC-   builtin and then its argument prototype would still apply.  */-#ifdef __cplusplus-extern "C"-#endif-char $2 ();-/* The GNU C library defines this for functions which it implements-    to always fail with ENOSYS.  Some functions are actually named-    something starting with __ and the normal name is an alias.  */-#if defined __stub_$2 || defined __stub___$2-choke me-#endif--int-main ()-{-return $2 ();-  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_link "$LINENO"; then :-  eval "$3=yes"-else-  eval "$3=no"-fi-rm -f core conftest.err conftest.$ac_objext \-    conftest$ac_exeext conftest.$ac_ext-fi-eval ac_res=\$$3-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5-$as_echo "$ac_res" >&6; }-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno--} # ac_fn_c_check_func--# ac_fn_c_compute_int LINENO EXPR VAR INCLUDES-# ---------------------------------------------# Tries to find the compile-time value of EXPR in a program that includes-# INCLUDES, setting VAR accordingly. Returns whether the value could be-# computed-ac_fn_c_compute_int ()-{-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-  if test "$cross_compiling" = yes; then-    # Depending upon the size, compute the lo and hi bounds.-cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-int-main ()-{-static int test_array [1 - 2 * !(($2) >= 0)];-test_array [0] = 0;-return test_array [0];--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_lo=0 ac_mid=0-  while :; do-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-int-main ()-{-static int test_array [1 - 2 * !(($2) <= $ac_mid)];-test_array [0] = 0;-return test_array [0];--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_hi=$ac_mid; break-else-  as_fn_arith $ac_mid + 1 && ac_lo=$as_val-			if test $ac_lo -le $ac_mid; then-			  ac_lo= ac_hi=-			  break-			fi-			as_fn_arith 2 '*' $ac_mid + 1 && ac_mid=$as_val-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-  done-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-int-main ()-{-static int test_array [1 - 2 * !(($2) < 0)];-test_array [0] = 0;-return test_array [0];--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_hi=-1 ac_mid=-1-  while :; do-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-int-main ()-{-static int test_array [1 - 2 * !(($2) >= $ac_mid)];-test_array [0] = 0;-return test_array [0];--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_lo=$ac_mid; break-else-  as_fn_arith '(' $ac_mid ')' - 1 && ac_hi=$as_val-			if test $ac_mid -le $ac_hi; then-			  ac_lo= ac_hi=-			  break-			fi-			as_fn_arith 2 '*' $ac_mid && ac_mid=$as_val-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-  done-else-  ac_lo= ac_hi=-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-# Binary search between lo and hi bounds.-while test "x$ac_lo" != "x$ac_hi"; do-  as_fn_arith '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo && ac_mid=$as_val-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-int-main ()-{-static int test_array [1 - 2 * !(($2) <= $ac_mid)];-test_array [0] = 0;-return test_array [0];--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_hi=$ac_mid-else-  as_fn_arith '(' $ac_mid ')' + 1 && ac_lo=$as_val-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-done-case $ac_lo in #((-?*) eval "$3=\$ac_lo"; ac_retval=0 ;;-'') ac_retval=1 ;;-esac-  else-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-$4-static long int longval () { return $2; }-static unsigned long int ulongval () { return $2; }-#include <stdio.h>-#include <stdlib.h>-int-main ()-{--  FILE *f = fopen ("conftest.val", "w");-  if (! f)-    return 1;-  if (($2) < 0)-    {-      long int i = longval ();-      if (i != ($2))-	return 1;-      fprintf (f, "%ld", i);-    }-  else-    {-      unsigned long int i = ulongval ();-      if (i != ($2))-	return 1;-      fprintf (f, "%lu", i);-    }-  /* Do not output a trailing newline, as this causes \r\n confusion-     on some platforms.  */-  return ferror (f) || fclose (f) != 0;--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_run "$LINENO"; then :-  echo >>conftest.val; read $3 <conftest.val; ac_retval=0-else-  ac_retval=1-fi-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \-  conftest.$ac_objext conftest.beam conftest.$ac_ext-rm -f conftest.val--  fi-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno-  as_fn_set_status $ac_retval--} # ac_fn_c_compute_int-cat >config.log <<_ACEOF-This file contains any messages produced by compilers while-running configure, to aid debugging if configure makes a mistake.--It was created by Haskell base package $as_me 1.0, which was-generated by GNU Autoconf 2.69.  Invocation command line was--  $ $0 $@--_ACEOF-exec 5>>config.log-{-cat <<_ASUNAME-## --------- ##-## Platform. ##-## --------- ##--hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`-uname -m = `(uname -m) 2>/dev/null || echo unknown`-uname -r = `(uname -r) 2>/dev/null || echo unknown`-uname -s = `(uname -s) 2>/dev/null || echo unknown`-uname -v = `(uname -v) 2>/dev/null || echo unknown`--/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`-/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`--/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`-/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`-/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`-/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`-/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`-/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`--_ASUNAME--as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    $as_echo "PATH: $as_dir"-  done-IFS=$as_save_IFS--} >&5--cat >&5 <<_ACEOF---## ----------- ##-## Core tests. ##-## ----------- ##--_ACEOF---# Keep a trace of the command line.-# Strip out --no-create and --no-recursion so they do not pile up.-# Strip out --silent because we don't want to record it for future runs.-# Also quote any args containing shell meta-characters.-# Make two passes to allow for proper duplicate-argument suppression.-ac_configure_args=-ac_configure_args0=-ac_configure_args1=-ac_must_keep_next=false-for ac_pass in 1 2-do-  for ac_arg-  do-    case $ac_arg in-    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;-    -q | -quiet | --quiet | --quie | --qui | --qu | --q \-    | -silent | --silent | --silen | --sile | --sil)-      continue ;;-    *\'*)-      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;-    esac-    case $ac_pass in-    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;-    2)-      as_fn_append ac_configure_args1 " '$ac_arg'"-      if test $ac_must_keep_next = true; then-	ac_must_keep_next=false # Got value, back to normal.-      else-	case $ac_arg in-	  *=* | --config-cache | -C | -disable-* | --disable-* \-	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \-	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \-	  | -with-* | --with-* | -without-* | --without-* | --x)-	    case "$ac_configure_args0 " in-	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;-	    esac-	    ;;-	  -* ) ac_must_keep_next=true ;;-	esac-      fi-      as_fn_append ac_configure_args " '$ac_arg'"-      ;;-    esac-  done-done-{ ac_configure_args0=; unset ac_configure_args0;}-{ ac_configure_args1=; unset ac_configure_args1;}--# When interrupted or exit'd, cleanup temporary files, and complete-# config.log.  We remove comments because anyway the quotes in there-# would cause problems or look ugly.-# WARNING: Use '\'' to represent an apostrophe within the trap.-# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.-trap 'exit_status=$?-  # Save into config.log some information that might help in debugging.-  {-    echo--    $as_echo "## ---------------- ##-## Cache variables. ##-## ---------------- ##"-    echo-    # The following way of writing the cache mishandles newlines in values,-(-  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do-    eval ac_val=\$$ac_var-    case $ac_val in #(-    *${as_nl}*)-      case $ac_var in #(-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;-      esac-      case $ac_var in #(-      _ | IFS | as_nl) ;; #(-      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(-      *) { eval $ac_var=; unset $ac_var;} ;;-      esac ;;-    esac-  done-  (set) 2>&1 |-    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(-    *${as_nl}ac_space=\ *)-      sed -n \-	"s/'\''/'\''\\\\'\'''\''/g;-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"-      ;; #(-    *)-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"-      ;;-    esac |-    sort-)-    echo--    $as_echo "## ----------------- ##-## Output variables. ##-## ----------------- ##"-    echo-    for ac_var in $ac_subst_vars-    do-      eval ac_val=\$$ac_var-      case $ac_val in-      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;-      esac-      $as_echo "$ac_var='\''$ac_val'\''"-    done | sort-    echo--    if test -n "$ac_subst_files"; then-      $as_echo "## ------------------- ##-## File substitutions. ##-## ------------------- ##"-      echo-      for ac_var in $ac_subst_files-      do-	eval ac_val=\$$ac_var-	case $ac_val in-	*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;-	esac-	$as_echo "$ac_var='\''$ac_val'\''"-      done | sort-      echo-    fi--    if test -s confdefs.h; then-      $as_echo "## ----------- ##-## confdefs.h. ##-## ----------- ##"-      echo-      cat confdefs.h-      echo-    fi-    test "$ac_signal" != 0 &&-      $as_echo "$as_me: caught signal $ac_signal"-    $as_echo "$as_me: exit $exit_status"-  } >&5-  rm -f core *.core core.conftest.* &&-    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&-    exit $exit_status-' 0-for ac_signal in 1 2 13 15; do-  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal-done-ac_signal=0--# confdefs.h avoids OS command line length limits that DEFS can exceed.-rm -f -r conftest* confdefs.h--$as_echo "/* confdefs.h */" > confdefs.h--# Predefined preprocessor variables.--cat >>confdefs.h <<_ACEOF-#define PACKAGE_NAME "$PACKAGE_NAME"-_ACEOF--cat >>confdefs.h <<_ACEOF-#define PACKAGE_TARNAME "$PACKAGE_TARNAME"-_ACEOF--cat >>confdefs.h <<_ACEOF-#define PACKAGE_VERSION "$PACKAGE_VERSION"-_ACEOF--cat >>confdefs.h <<_ACEOF-#define PACKAGE_STRING "$PACKAGE_STRING"-_ACEOF--cat >>confdefs.h <<_ACEOF-#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"-_ACEOF--cat >>confdefs.h <<_ACEOF-#define PACKAGE_URL "$PACKAGE_URL"-_ACEOF---# Let the site file select an alternate cache file if it wants to.-# Prefer an explicitly selected file to automatically selected ones.-ac_site_file1=NONE-ac_site_file2=NONE-if test -n "$CONFIG_SITE"; then-  # We do not want a PATH search for config.site.-  case $CONFIG_SITE in #((-    -*)  ac_site_file1=./$CONFIG_SITE;;-    */*) ac_site_file1=$CONFIG_SITE;;-    *)   ac_site_file1=./$CONFIG_SITE;;-  esac-elif test "x$prefix" != xNONE; then-  ac_site_file1=$prefix/share/config.site-  ac_site_file2=$prefix/etc/config.site-else-  ac_site_file1=$ac_default_prefix/share/config.site-  ac_site_file2=$ac_default_prefix/etc/config.site-fi-for ac_site_file in "$ac_site_file1" "$ac_site_file2"-do-  test "x$ac_site_file" = xNONE && continue-  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5-$as_echo "$as_me: loading site script $ac_site_file" >&6;}-    sed 's/^/| /' "$ac_site_file" >&5-    . "$ac_site_file" \-      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error $? "failed to load site script $ac_site_file-See \`config.log' for more details" "$LINENO" 5; }-  fi-done--if test -r "$cache_file"; then-  # Some versions of bash will fail to source /dev/null (special files-  # actually), so we avoid doing that.  DJGPP emulates it as a regular file.-  if test /dev/null != "$cache_file" && test -f "$cache_file"; then-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5-$as_echo "$as_me: loading cache $cache_file" >&6;}-    case $cache_file in-      [\\/]* | ?:[\\/]* ) . "$cache_file";;-      *)                      . "./$cache_file";;-    esac-  fi-else-  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5-$as_echo "$as_me: creating cache $cache_file" >&6;}-  >$cache_file-fi--# Check that the precious variables saved in the cache have kept the same-# value.-ac_cache_corrupted=false-for ac_var in $ac_precious_vars; do-  eval ac_old_set=\$ac_cv_env_${ac_var}_set-  eval ac_new_set=\$ac_env_${ac_var}_set-  eval ac_old_val=\$ac_cv_env_${ac_var}_value-  eval ac_new_val=\$ac_env_${ac_var}_value-  case $ac_old_set,$ac_new_set in-    set,)-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5-$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}-      ac_cache_corrupted=: ;;-    ,set)-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5-$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}-      ac_cache_corrupted=: ;;-    ,);;-    *)-      if test "x$ac_old_val" != "x$ac_new_val"; then-	# differences in whitespace do not lead to failure.-	ac_old_val_w=`echo x $ac_old_val`-	ac_new_val_w=`echo x $ac_new_val`-	if test "$ac_old_val_w" != "$ac_new_val_w"; then-	  { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5-$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}-	  ac_cache_corrupted=:-	else-	  { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5-$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}-	  eval $ac_var=\$ac_old_val-	fi-	{ $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5-$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}-	{ $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5-$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}-      fi;;-  esac-  # Pass precious variables to config.status.-  if test "$ac_new_set" = set; then-    case $ac_new_val in-    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;-    *) ac_arg=$ac_var=$ac_new_val ;;-    esac-    case " $ac_configure_args " in-      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.-      *) as_fn_append ac_configure_args " '$ac_arg'" ;;-    esac-  fi-done-if $ac_cache_corrupted; then-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5-$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}-  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5-fi-## -------------------- ##-## Main body of script. ##-## -------------------- ##--ac_ext=c-ac_cpp='$CPP $CPPFLAGS'-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'-ac_compiler_gnu=$ac_cv_c_compiler_gnu----# Safety check: Ensure that we are in the correct source directory.---ac_config_headers="$ac_config_headers include/HsBaseConfig.h include/EventConfig.h"---ac_aux_dir=-for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do-  if test -f "$ac_dir/install-sh"; then-    ac_aux_dir=$ac_dir-    ac_install_sh="$ac_aux_dir/install-sh -c"-    break-  elif test -f "$ac_dir/install.sh"; then-    ac_aux_dir=$ac_dir-    ac_install_sh="$ac_aux_dir/install.sh -c"-    break-  elif test -f "$ac_dir/shtool"; then-    ac_aux_dir=$ac_dir-    ac_install_sh="$ac_aux_dir/shtool install -c"-    break-  fi-done-if test -z "$ac_aux_dir"; then-  as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5-fi--# These three variables are undocumented and unsupported,-# and are intended to be withdrawn in a future Autoconf release.-# They can cause serious problems if a builder's source tree is in a directory-# whose full name contains unusual characters.-ac_config_guess="$SHELL $ac_aux_dir/config.guess"  # Please don't use this var.-ac_config_sub="$SHELL $ac_aux_dir/config.sub"  # Please don't use this var.-ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.---# Make sure we can run config.sub.-$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||-  as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5--{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5-$as_echo_n "checking build system type... " >&6; }-if ${ac_cv_build+:} false; then :-  $as_echo_n "(cached) " >&6-else-  ac_build_alias=$build_alias-test "x$ac_build_alias" = x &&-  ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`-test "x$ac_build_alias" = x &&-  as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5-ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||-  as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5--fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5-$as_echo "$ac_cv_build" >&6; }-case $ac_cv_build in-*-*-*) ;;-*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;;-esac-build=$ac_cv_build-ac_save_IFS=$IFS; IFS='-'-set x $ac_cv_build-shift-build_cpu=$1-build_vendor=$2-shift; shift-# Remember, the first character of IFS is used to create $*,-# except with old shells:-build_os=$*-IFS=$ac_save_IFS-case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac---{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5-$as_echo_n "checking host system type... " >&6; }-if ${ac_cv_host+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if test "x$host_alias" = x; then-  ac_cv_host=$ac_cv_build-else-  ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||-    as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5-fi--fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5-$as_echo "$ac_cv_host" >&6; }-case $ac_cv_host in-*-*-*) ;;-*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;;-esac-host=$ac_cv_host-ac_save_IFS=$IFS; IFS='-'-set x $ac_cv_host-shift-host_cpu=$1-host_vendor=$2-shift; shift-# Remember, the first character of IFS is used to create $*,-# except with old shells:-host_os=$*-IFS=$ac_save_IFS-case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac---{ $as_echo "$as_me:${as_lineno-$LINENO}: checking target system type" >&5-$as_echo_n "checking target system type... " >&6; }-if ${ac_cv_target+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if test "x$target_alias" = x; then-  ac_cv_target=$ac_cv_host-else-  ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` ||-    as_fn_error $? "$SHELL $ac_aux_dir/config.sub $target_alias failed" "$LINENO" 5-fi--fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_target" >&5-$as_echo "$ac_cv_target" >&6; }-case $ac_cv_target in-*-*-*) ;;-*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5;;-esac-target=$ac_cv_target-ac_save_IFS=$IFS; IFS='-'-set x $ac_cv_target-shift-target_cpu=$1-target_vendor=$2-shift; shift-# Remember, the first character of IFS is used to create $*,-# except with old shells:-target_os=$*-IFS=$ac_save_IFS-case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac---# The aliases save the names the user supplied, while $host etc.-# will get canonicalized.-test -n "$target_alias" &&-  test "$program_prefix$program_suffix$program_transform_name" = \-    NONENONEs,x,x, &&-  program_prefix=${target_alias}----# Check whether --with-cc was given.-if test "${with_cc+set}" = set; then :-  withval=$with_cc; CC=$withval-fi--ac_ext=c-ac_cpp='$CPP $CPPFLAGS'-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'-ac_compiler_gnu=$ac_cv_c_compiler_gnu-if test -n "$ac_tool_prefix"; then-  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.-set dummy ${ac_tool_prefix}gcc; ac_word=$2-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5-$as_echo_n "checking for $ac_word... " >&6; }-if ${ac_cv_prog_CC+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if test -n "$CC"; then-  ac_cv_prog_CC="$CC" # Let the user override the test.-else-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    for ac_exec_ext in '' $ac_executable_extensions; do-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then-    ac_cv_prog_CC="${ac_tool_prefix}gcc"-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5-    break 2-  fi-done-  done-IFS=$as_save_IFS--fi-fi-CC=$ac_cv_prog_CC-if test -n "$CC"; then-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5-$as_echo "$CC" >&6; }-else-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5-$as_echo "no" >&6; }-fi---fi-if test -z "$ac_cv_prog_CC"; then-  ac_ct_CC=$CC-  # Extract the first word of "gcc", so it can be a program name with args.-set dummy gcc; ac_word=$2-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5-$as_echo_n "checking for $ac_word... " >&6; }-if ${ac_cv_prog_ac_ct_CC+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if test -n "$ac_ct_CC"; then-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.-else-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    for ac_exec_ext in '' $ac_executable_extensions; do-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then-    ac_cv_prog_ac_ct_CC="gcc"-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5-    break 2-  fi-done-  done-IFS=$as_save_IFS--fi-fi-ac_ct_CC=$ac_cv_prog_ac_ct_CC-if test -n "$ac_ct_CC"; then-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5-$as_echo "$ac_ct_CC" >&6; }-else-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5-$as_echo "no" >&6; }-fi--  if test "x$ac_ct_CC" = x; then-    CC=""-  else-    case $cross_compiling:$ac_tool_warned in-yes:)-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}-ac_tool_warned=yes ;;-esac-    CC=$ac_ct_CC-  fi-else-  CC="$ac_cv_prog_CC"-fi--if test -z "$CC"; then-          if test -n "$ac_tool_prefix"; then-    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.-set dummy ${ac_tool_prefix}cc; ac_word=$2-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5-$as_echo_n "checking for $ac_word... " >&6; }-if ${ac_cv_prog_CC+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if test -n "$CC"; then-  ac_cv_prog_CC="$CC" # Let the user override the test.-else-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    for ac_exec_ext in '' $ac_executable_extensions; do-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then-    ac_cv_prog_CC="${ac_tool_prefix}cc"-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5-    break 2-  fi-done-  done-IFS=$as_save_IFS--fi-fi-CC=$ac_cv_prog_CC-if test -n "$CC"; then-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5-$as_echo "$CC" >&6; }-else-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5-$as_echo "no" >&6; }-fi---  fi-fi-if test -z "$CC"; then-  # Extract the first word of "cc", so it can be a program name with args.-set dummy cc; ac_word=$2-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5-$as_echo_n "checking for $ac_word... " >&6; }-if ${ac_cv_prog_CC+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if test -n "$CC"; then-  ac_cv_prog_CC="$CC" # Let the user override the test.-else-  ac_prog_rejected=no-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    for ac_exec_ext in '' $ac_executable_extensions; do-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then-    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then-       ac_prog_rejected=yes-       continue-     fi-    ac_cv_prog_CC="cc"-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5-    break 2-  fi-done-  done-IFS=$as_save_IFS--if test $ac_prog_rejected = yes; then-  # We found a bogon in the path, so make sure we never use it.-  set dummy $ac_cv_prog_CC-  shift-  if test $# != 0; then-    # We chose a different compiler from the bogus one.-    # However, it has the same basename, so the bogon will be chosen-    # first if we set CC to just the basename; use the full file name.-    shift-    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"-  fi-fi-fi-fi-CC=$ac_cv_prog_CC-if test -n "$CC"; then-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5-$as_echo "$CC" >&6; }-else-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5-$as_echo "no" >&6; }-fi---fi-if test -z "$CC"; then-  if test -n "$ac_tool_prefix"; then-  for ac_prog in cl.exe-  do-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.-set dummy $ac_tool_prefix$ac_prog; ac_word=$2-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5-$as_echo_n "checking for $ac_word... " >&6; }-if ${ac_cv_prog_CC+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if test -n "$CC"; then-  ac_cv_prog_CC="$CC" # Let the user override the test.-else-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    for ac_exec_ext in '' $ac_executable_extensions; do-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then-    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5-    break 2-  fi-done-  done-IFS=$as_save_IFS--fi-fi-CC=$ac_cv_prog_CC-if test -n "$CC"; then-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5-$as_echo "$CC" >&6; }-else-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5-$as_echo "no" >&6; }-fi---    test -n "$CC" && break-  done-fi-if test -z "$CC"; then-  ac_ct_CC=$CC-  for ac_prog in cl.exe-do-  # Extract the first word of "$ac_prog", so it can be a program name with args.-set dummy $ac_prog; ac_word=$2-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5-$as_echo_n "checking for $ac_word... " >&6; }-if ${ac_cv_prog_ac_ct_CC+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if test -n "$ac_ct_CC"; then-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.-else-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    for ac_exec_ext in '' $ac_executable_extensions; do-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then-    ac_cv_prog_ac_ct_CC="$ac_prog"-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5-    break 2-  fi-done-  done-IFS=$as_save_IFS--fi-fi-ac_ct_CC=$ac_cv_prog_ac_ct_CC-if test -n "$ac_ct_CC"; then-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5-$as_echo "$ac_ct_CC" >&6; }-else-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5-$as_echo "no" >&6; }-fi---  test -n "$ac_ct_CC" && break-done--  if test "x$ac_ct_CC" = x; then-    CC=""-  else-    case $cross_compiling:$ac_tool_warned in-yes:)-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}-ac_tool_warned=yes ;;-esac-    CC=$ac_ct_CC-  fi-fi--fi---test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error $? "no acceptable C compiler found in \$PATH-See \`config.log' for more details" "$LINENO" 5; }--# Provide some information about the compiler.-$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5-set X $ac_compile-ac_compiler=$2-for ac_option in --version -v -V -qversion; do-  { { ac_try="$ac_compiler $ac_option >&5"-case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_compiler $ac_option >&5") 2>conftest.err-  ac_status=$?-  if test -s conftest.err; then-    sed '10a\-... rest of stderr output deleted ...-         10q' conftest.err >conftest.er1-    cat conftest.er1 >&5-  fi-  rm -f conftest.er1 conftest.err-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; }-done--cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */--int-main ()-{--  ;-  return 0;-}-_ACEOF-ac_clean_files_save=$ac_clean_files-ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"-# Try to create an executable without -o first, disregard a.out.-# It will help us diagnose broken compilers, and finding out an intuition-# of exeext.-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5-$as_echo_n "checking whether the C compiler works... " >&6; }-ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`--# The possible output files:-ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"--ac_rmfiles=-for ac_file in $ac_files-do-  case $ac_file in-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;-    * ) ac_rmfiles="$ac_rmfiles $ac_file";;-  esac-done-rm -f $ac_rmfiles--if { { ac_try="$ac_link_default"-case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_link_default") 2>&5-  ac_status=$?-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; }; then :-  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.-# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'-# in a Makefile.  We should not override ac_cv_exeext if it was cached,-# so that the user can short-circuit this test for compilers unknown to-# Autoconf.-for ac_file in $ac_files ''-do-  test -f "$ac_file" || continue-  case $ac_file in-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )-	;;-    [ab].out )-	# We found the default executable, but exeext='' is most-	# certainly right.-	break;;-    *.* )-	if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;-	then :; else-	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`-	fi-	# We set ac_cv_exeext here because the later test for it is not-	# safe: cross compilers may not add the suffix if given an `-o'-	# argument, so we may need to know it at that point already.-	# Even if this section looks crufty: it has the advantage of-	# actually working.-	break;;-    * )-	break;;-  esac-done-test "$ac_cv_exeext" = no && ac_cv_exeext=--else-  ac_file=''-fi-if test -z "$ac_file"; then :-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5-$as_echo "no" >&6; }-$as_echo "$as_me: failed program was:" >&5-sed 's/^/| /' conftest.$ac_ext >&5--{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error 77 "C compiler cannot create executables-See \`config.log' for more details" "$LINENO" 5; }-else-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5-$as_echo "yes" >&6; }-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5-$as_echo_n "checking for C compiler default output file name... " >&6; }-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5-$as_echo "$ac_file" >&6; }-ac_exeext=$ac_cv_exeext--rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out-ac_clean_files=$ac_clean_files_save-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5-$as_echo_n "checking for suffix of executables... " >&6; }-if { { ac_try="$ac_link"-case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_link") 2>&5-  ac_status=$?-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; }; then :-  # If both `conftest.exe' and `conftest' are `present' (well, observable)-# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will-# work properly (i.e., refer to `conftest.exe'), while it won't with-# `rm'.-for ac_file in conftest.exe conftest conftest.*; do-  test -f "$ac_file" || continue-  case $ac_file in-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;-    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`-	  break;;-    * ) break;;-  esac-done-else-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error $? "cannot compute suffix of executables: cannot compile and link-See \`config.log' for more details" "$LINENO" 5; }-fi-rm -f conftest conftest$ac_cv_exeext-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5-$as_echo "$ac_cv_exeext" >&6; }--rm -f conftest.$ac_ext-EXEEXT=$ac_cv_exeext-ac_exeext=$EXEEXT-cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <stdio.h>-int-main ()-{-FILE *f = fopen ("conftest.out", "w");- return ferror (f) || fclose (f) != 0;--  ;-  return 0;-}-_ACEOF-ac_clean_files="$ac_clean_files conftest.out"-# Check that the compiler produces executables we can run.  If not, either-# the compiler is broken, or we cross compile.-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5-$as_echo_n "checking whether we are cross compiling... " >&6; }-if test "$cross_compiling" != yes; then-  { { ac_try="$ac_link"-case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_link") 2>&5-  ac_status=$?-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; }-  if { ac_try='./conftest$ac_cv_exeext'-  { { case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_try") 2>&5-  ac_status=$?-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; }; }; then-    cross_compiling=no-  else-    if test "$cross_compiling" = maybe; then-	cross_compiling=yes-    else-	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error $? "cannot run C compiled programs.-If you meant to cross compile, use \`--host'.-See \`config.log' for more details" "$LINENO" 5; }-    fi-  fi-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5-$as_echo "$cross_compiling" >&6; }--rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out-ac_clean_files=$ac_clean_files_save-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5-$as_echo_n "checking for suffix of object files... " >&6; }-if ${ac_cv_objext+:} false; then :-  $as_echo_n "(cached) " >&6-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */--int-main ()-{--  ;-  return 0;-}-_ACEOF-rm -f conftest.o conftest.obj-if { { ac_try="$ac_compile"-case "(($ac_try" in-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;-  *) ac_try_echo=$ac_try;;-esac-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""-$as_echo "$ac_try_echo"; } >&5-  (eval "$ac_compile") 2>&5-  ac_status=$?-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5-  test $ac_status = 0; }; then :-  for ac_file in conftest.o conftest.obj conftest.*; do-  test -f "$ac_file" || continue;-  case $ac_file in-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;-    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`-       break;;-  esac-done-else-  $as_echo "$as_me: failed program was:" >&5-sed 's/^/| /' conftest.$ac_ext >&5--{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error $? "cannot compute suffix of object files: cannot compile-See \`config.log' for more details" "$LINENO" 5; }-fi-rm -f conftest.$ac_cv_objext conftest.$ac_ext-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5-$as_echo "$ac_cv_objext" >&6; }-OBJEXT=$ac_cv_objext-ac_objext=$OBJEXT-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5-$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }-if ${ac_cv_c_compiler_gnu+:} false; then :-  $as_echo_n "(cached) " >&6-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */--int-main ()-{-#ifndef __GNUC__-       choke me-#endif--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_compiler_gnu=yes-else-  ac_compiler_gnu=no-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-ac_cv_c_compiler_gnu=$ac_compiler_gnu--fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5-$as_echo "$ac_cv_c_compiler_gnu" >&6; }-if test $ac_compiler_gnu = yes; then-  GCC=yes-else-  GCC=-fi-ac_test_CFLAGS=${CFLAGS+set}-ac_save_CFLAGS=$CFLAGS-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5-$as_echo_n "checking whether $CC accepts -g... " >&6; }-if ${ac_cv_prog_cc_g+:} false; then :-  $as_echo_n "(cached) " >&6-else-  ac_save_c_werror_flag=$ac_c_werror_flag-   ac_c_werror_flag=yes-   ac_cv_prog_cc_g=no-   CFLAGS="-g"-   cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */--int-main ()-{--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_prog_cc_g=yes-else-  CFLAGS=""-      cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */--int-main ()-{--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :--else-  ac_c_werror_flag=$ac_save_c_werror_flag-	 CFLAGS="-g"-	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */--int-main ()-{--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_prog_cc_g=yes-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-   ac_c_werror_flag=$ac_save_c_werror_flag-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5-$as_echo "$ac_cv_prog_cc_g" >&6; }-if test "$ac_test_CFLAGS" = set; then-  CFLAGS=$ac_save_CFLAGS-elif test $ac_cv_prog_cc_g = yes; then-  if test "$GCC" = yes; then-    CFLAGS="-g -O2"-  else-    CFLAGS="-g"-  fi-else-  if test "$GCC" = yes; then-    CFLAGS="-O2"-  else-    CFLAGS=-  fi-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5-$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }-if ${ac_cv_prog_cc_c89+:} false; then :-  $as_echo_n "(cached) " >&6-else-  ac_cv_prog_cc_c89=no-ac_save_CC=$CC-cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <stdarg.h>-#include <stdio.h>-struct stat;-/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */-struct buf { int x; };-FILE * (*rcsopen) (struct buf *, struct stat *, int);-static char *e (p, i)-     char **p;-     int i;-{-  return p[i];-}-static char *f (char * (*g) (char **, int), char **p, ...)-{-  char *s;-  va_list v;-  va_start (v,p);-  s = g (p, va_arg (v,int));-  va_end (v);-  return s;-}--/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has-   function prototypes and stuff, but not '\xHH' hex character constants.-   These don't provoke an error unfortunately, instead are silently treated-   as 'x'.  The following induces an error, until -std is added to get-   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an-   array size at least.  It's necessary to write '\x00'==0 to get something-   that's true only with -std.  */-int osf4_cc_array ['\x00' == 0 ? 1 : -1];--/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters-   inside strings and character constants.  */-#define FOO(x) 'x'-int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];--int test (int i, double x);-struct s1 {int (*f) (int a);};-struct s2 {int (*f) (double a);};-int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);-int argc;-char **argv;-int-main ()-{-return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];-  ;-  return 0;-}-_ACEOF-for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \-	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"-do-  CC="$ac_save_CC $ac_arg"-  if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_prog_cc_c89=$ac_arg-fi-rm -f core conftest.err conftest.$ac_objext-  test "x$ac_cv_prog_cc_c89" != "xno" && break-done-rm -f conftest.$ac_ext-CC=$ac_save_CC--fi-# AC_CACHE_VAL-case "x$ac_cv_prog_cc_c89" in-  x)-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5-$as_echo "none needed" >&6; } ;;-  xno)-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5-$as_echo "unsupported" >&6; } ;;-  *)-    CC="$CC $ac_cv_prog_cc_c89"-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5-$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;-esac-if test "x$ac_cv_prog_cc_c89" != xno; then :--fi--ac_ext=c-ac_cpp='$CPP $CPPFLAGS'-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'-ac_compiler_gnu=$ac_cv_c_compiler_gnu---{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for WINDOWS platform" >&5-$as_echo_n "checking for WINDOWS platform... " >&6; }-case $host in-    *mingw32*|*mingw64*|*cygwin*|*msys*)-        WINDOWS=YES;;-    *)-        WINDOWS=NO;;-esac-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $WINDOWS" >&5-$as_echo "$WINDOWS" >&6; }--# do we have long longs?--ac_ext=c-ac_cpp='$CPP $CPPFLAGS'-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'-ac_compiler_gnu=$ac_cv_c_compiler_gnu-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5-$as_echo_n "checking how to run the C preprocessor... " >&6; }-# On Suns, sometimes $CPP names a directory.-if test -n "$CPP" && test -d "$CPP"; then-  CPP=-fi-if test -z "$CPP"; then-  if ${ac_cv_prog_CPP+:} false; then :-  $as_echo_n "(cached) " >&6-else-      # Double quotes because CPP needs to be expanded-    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"-    do-      ac_preproc_ok=false-for ac_c_preproc_warn_flag in '' yes-do-  # Use a header file that comes with gcc, so configuring glibc-  # with a fresh cross-compiler works.-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since-  # <limits.h> exists even on freestanding compilers.-  # On the NeXT, cc -E runs the code through the compiler's parser,-  # not just through cpp. "Syntax error" is here to catch this case.-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#ifdef __STDC__-# include <limits.h>-#else-# include <assert.h>-#endif-		     Syntax error-_ACEOF-if ac_fn_c_try_cpp "$LINENO"; then :--else-  # Broken: fails on valid input.-continue-fi-rm -f conftest.err conftest.i conftest.$ac_ext--  # OK, works on sane cases.  Now check whether nonexistent headers-  # can be detected and how.-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <ac_nonexistent.h>-_ACEOF-if ac_fn_c_try_cpp "$LINENO"; then :-  # Broken: success on invalid input.-continue-else-  # Passes both tests.-ac_preproc_ok=:-break-fi-rm -f conftest.err conftest.i conftest.$ac_ext--done-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.-rm -f conftest.i conftest.err conftest.$ac_ext-if $ac_preproc_ok; then :-  break-fi--    done-    ac_cv_prog_CPP=$CPP--fi-  CPP=$ac_cv_prog_CPP-else-  ac_cv_prog_CPP=$CPP-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5-$as_echo "$CPP" >&6; }-ac_preproc_ok=false-for ac_c_preproc_warn_flag in '' yes-do-  # Use a header file that comes with gcc, so configuring glibc-  # with a fresh cross-compiler works.-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since-  # <limits.h> exists even on freestanding compilers.-  # On the NeXT, cc -E runs the code through the compiler's parser,-  # not just through cpp. "Syntax error" is here to catch this case.-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#ifdef __STDC__-# include <limits.h>-#else-# include <assert.h>-#endif-		     Syntax error-_ACEOF-if ac_fn_c_try_cpp "$LINENO"; then :--else-  # Broken: fails on valid input.-continue-fi-rm -f conftest.err conftest.i conftest.$ac_ext--  # OK, works on sane cases.  Now check whether nonexistent headers-  # can be detected and how.-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <ac_nonexistent.h>-_ACEOF-if ac_fn_c_try_cpp "$LINENO"; then :-  # Broken: success on invalid input.-continue-else-  # Passes both tests.-ac_preproc_ok=:-break-fi-rm -f conftest.err conftest.i conftest.$ac_ext--done-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.-rm -f conftest.i conftest.err conftest.$ac_ext-if $ac_preproc_ok; then :--else-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error $? "C preprocessor \"$CPP\" fails sanity check-See \`config.log' for more details" "$LINENO" 5; }-fi--ac_ext=c-ac_cpp='$CPP $CPPFLAGS'-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'-ac_compiler_gnu=$ac_cv_c_compiler_gnu---{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5-$as_echo_n "checking for grep that handles long lines and -e... " >&6; }-if ${ac_cv_path_GREP+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if test -z "$GREP"; then-  ac_path_GREP_found=false-  # Loop through the user's path and test for each of PROGNAME-LIST-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    for ac_prog in grep ggrep; do-    for ac_exec_ext in '' $ac_executable_extensions; do-      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"-      as_fn_executable_p "$ac_path_GREP" || continue-# Check for GNU ac_path_GREP and select it if it is found.-  # Check for GNU $ac_path_GREP-case `"$ac_path_GREP" --version 2>&1` in-*GNU*)-  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;-*)-  ac_count=0-  $as_echo_n 0123456789 >"conftest.in"-  while :-  do-    cat "conftest.in" "conftest.in" >"conftest.tmp"-    mv "conftest.tmp" "conftest.in"-    cp "conftest.in" "conftest.nl"-    $as_echo 'GREP' >> "conftest.nl"-    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break-    as_fn_arith $ac_count + 1 && ac_count=$as_val-    if test $ac_count -gt ${ac_path_GREP_max-0}; then-      # Best one so far, save it but keep looking for a better one-      ac_cv_path_GREP="$ac_path_GREP"-      ac_path_GREP_max=$ac_count-    fi-    # 10*(2^10) chars as input seems more than enough-    test $ac_count -gt 10 && break-  done-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;-esac--      $ac_path_GREP_found && break 3-    done-  done-  done-IFS=$as_save_IFS-  if test -z "$ac_cv_path_GREP"; then-    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5-  fi-else-  ac_cv_path_GREP=$GREP-fi--fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5-$as_echo "$ac_cv_path_GREP" >&6; }- GREP="$ac_cv_path_GREP"---{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5-$as_echo_n "checking for egrep... " >&6; }-if ${ac_cv_path_EGREP+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1-   then ac_cv_path_EGREP="$GREP -E"-   else-     if test -z "$EGREP"; then-  ac_path_EGREP_found=false-  # Loop through the user's path and test for each of PROGNAME-LIST-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    for ac_prog in egrep; do-    for ac_exec_ext in '' $ac_executable_extensions; do-      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"-      as_fn_executable_p "$ac_path_EGREP" || continue-# Check for GNU ac_path_EGREP and select it if it is found.-  # Check for GNU $ac_path_EGREP-case `"$ac_path_EGREP" --version 2>&1` in-*GNU*)-  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;-*)-  ac_count=0-  $as_echo_n 0123456789 >"conftest.in"-  while :-  do-    cat "conftest.in" "conftest.in" >"conftest.tmp"-    mv "conftest.tmp" "conftest.in"-    cp "conftest.in" "conftest.nl"-    $as_echo 'EGREP' >> "conftest.nl"-    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break-    as_fn_arith $ac_count + 1 && ac_count=$as_val-    if test $ac_count -gt ${ac_path_EGREP_max-0}; then-      # Best one so far, save it but keep looking for a better one-      ac_cv_path_EGREP="$ac_path_EGREP"-      ac_path_EGREP_max=$ac_count-    fi-    # 10*(2^10) chars as input seems more than enough-    test $ac_count -gt 10 && break-  done-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;-esac--      $ac_path_EGREP_found && break 3-    done-  done-  done-IFS=$as_save_IFS-  if test -z "$ac_cv_path_EGREP"; then-    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5-  fi-else-  ac_cv_path_EGREP=$EGREP-fi--   fi-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5-$as_echo "$ac_cv_path_EGREP" >&6; }- EGREP="$ac_cv_path_EGREP"---{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5-$as_echo_n "checking for ANSI C header files... " >&6; }-if ${ac_cv_header_stdc+:} false; then :-  $as_echo_n "(cached) " >&6-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <stdlib.h>-#include <stdarg.h>-#include <string.h>-#include <float.h>--int-main ()-{--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_header_stdc=yes-else-  ac_cv_header_stdc=no-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext--if test $ac_cv_header_stdc = yes; then-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <string.h>--_ACEOF-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |-  $EGREP "memchr" >/dev/null 2>&1; then :--else-  ac_cv_header_stdc=no-fi-rm -f conftest*--fi--if test $ac_cv_header_stdc = yes; then-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <stdlib.h>--_ACEOF-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |-  $EGREP "free" >/dev/null 2>&1; then :--else-  ac_cv_header_stdc=no-fi-rm -f conftest*--fi--if test $ac_cv_header_stdc = yes; then-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.-  if test "$cross_compiling" = yes; then :-  :-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <ctype.h>-#include <stdlib.h>-#if ((' ' & 0x0FF) == 0x020)-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))-#else-# define ISLOWER(c) \-		   (('a' <= (c) && (c) <= 'i') \-		     || ('j' <= (c) && (c) <= 'r') \-		     || ('s' <= (c) && (c) <= 'z'))-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))-#endif--#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))-int-main ()-{-  int i;-  for (i = 0; i < 256; i++)-    if (XOR (islower (i), ISLOWER (i))-	|| toupper (i) != TOUPPER (i))-      return 2;-  return 0;-}-_ACEOF-if ac_fn_c_try_run "$LINENO"; then :--else-  ac_cv_header_stdc=no-fi-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \-  conftest.$ac_objext conftest.beam conftest.$ac_ext-fi--fi-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5-$as_echo "$ac_cv_header_stdc" >&6; }-if test $ac_cv_header_stdc = yes; then--$as_echo "#define STDC_HEADERS 1" >>confdefs.h--fi--# On IRIX 5.3, sys/types and inttypes.h are conflicting.-for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \-		  inttypes.h stdint.h unistd.h-do :-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`-ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default-"-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :-  cat >>confdefs.h <<_ACEOF-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1-_ACEOF--fi--done---ac_fn_c_check_type "$LINENO" "long long" "ac_cv_type_long_long" "$ac_includes_default"-if test "x$ac_cv_type_long_long" = xyes; then :--cat >>confdefs.h <<_ACEOF-#define HAVE_LONG_LONG 1-_ACEOF---fi---{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5-$as_echo_n "checking for ANSI C header files... " >&6; }-if ${ac_cv_header_stdc+:} false; then :-  $as_echo_n "(cached) " >&6-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <stdlib.h>-#include <stdarg.h>-#include <string.h>-#include <float.h>--int-main ()-{--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_header_stdc=yes-else-  ac_cv_header_stdc=no-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext--if test $ac_cv_header_stdc = yes; then-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <string.h>--_ACEOF-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |-  $EGREP "memchr" >/dev/null 2>&1; then :--else-  ac_cv_header_stdc=no-fi-rm -f conftest*--fi--if test $ac_cv_header_stdc = yes; then-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <stdlib.h>--_ACEOF-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |-  $EGREP "free" >/dev/null 2>&1; then :--else-  ac_cv_header_stdc=no-fi-rm -f conftest*--fi--if test $ac_cv_header_stdc = yes; then-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.-  if test "$cross_compiling" = yes; then :-  :-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <ctype.h>-#include <stdlib.h>-#if ((' ' & 0x0FF) == 0x020)-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))-#else-# define ISLOWER(c) \-		   (('a' <= (c) && (c) <= 'i') \-		     || ('j' <= (c) && (c) <= 'r') \-		     || ('s' <= (c) && (c) <= 'z'))-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))-#endif--#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))-int-main ()-{-  int i;-  for (i = 0; i < 256; i++)-    if (XOR (islower (i), ISLOWER (i))-	|| toupper (i) != TOUPPER (i))-      return 2;-  return 0;-}-_ACEOF-if ac_fn_c_try_run "$LINENO"; then :--else-  ac_cv_header_stdc=no-fi-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \-  conftest.$ac_objext conftest.beam conftest.$ac_ext-fi--fi-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5-$as_echo "$ac_cv_header_stdc" >&6; }-if test $ac_cv_header_stdc = yes; then--$as_echo "#define STDC_HEADERS 1" >>confdefs.h--fi---# check for specific header (.h) files that we are interested in-for ac_header in ctype.h errno.h fcntl.h inttypes.h limits.h signal.h sys/resource.h sys/select.h sys/stat.h sys/syscall.h sys/time.h sys/timeb.h sys/timers.h sys/times.h sys/types.h sys/utsname.h sys/wait.h termios.h time.h unistd.h utime.h windows.h winsock.h langinfo.h poll.h sys/epoll.h sys/event.h sys/eventfd.h-do :-  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`-ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :-  cat >>confdefs.h <<_ACEOF-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1-_ACEOF--fi--done---# Enable large file support. Do this before testing the types ino_t, off_t, and-# rlim_t, because it will affect the result of that test.-# Check whether --enable-largefile was given.-if test "${enable_largefile+set}" = set; then :-  enableval=$enable_largefile;-fi--if test "$enable_largefile" != no; then--  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for special C compiler options needed for large files" >&5-$as_echo_n "checking for special C compiler options needed for large files... " >&6; }-if ${ac_cv_sys_largefile_CC+:} false; then :-  $as_echo_n "(cached) " >&6-else-  ac_cv_sys_largefile_CC=no-     if test "$GCC" != yes; then-       ac_save_CC=$CC-       while :; do-	 # IRIX 6.2 and later do not support large files by default,-	 # so use the C compiler's -n32 option if that helps.-	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <sys/types.h>- /* Check that off_t can represent 2**63 - 1 correctly.-    We can't simply define LARGE_OFF_T to be 9223372036854775807,-    since some C++ compilers masquerading as C compilers-    incorrectly reject 9223372036854775807.  */-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721-		       && LARGE_OFF_T % 2147483647 == 1)-		      ? 1 : -1];-int-main ()-{--  ;-  return 0;-}-_ACEOF-	 if ac_fn_c_try_compile "$LINENO"; then :-  break-fi-rm -f core conftest.err conftest.$ac_objext-	 CC="$CC -n32"-	 if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_sys_largefile_CC=' -n32'; break-fi-rm -f core conftest.err conftest.$ac_objext-	 break-       done-       CC=$ac_save_CC-       rm -f conftest.$ac_ext-    fi-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_largefile_CC" >&5-$as_echo "$ac_cv_sys_largefile_CC" >&6; }-  if test "$ac_cv_sys_largefile_CC" != no; then-    CC=$CC$ac_cv_sys_largefile_CC-  fi--  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _FILE_OFFSET_BITS value needed for large files" >&5-$as_echo_n "checking for _FILE_OFFSET_BITS value needed for large files... " >&6; }-if ${ac_cv_sys_file_offset_bits+:} false; then :-  $as_echo_n "(cached) " >&6-else-  while :; do-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <sys/types.h>- /* Check that off_t can represent 2**63 - 1 correctly.-    We can't simply define LARGE_OFF_T to be 9223372036854775807,-    since some C++ compilers masquerading as C compilers-    incorrectly reject 9223372036854775807.  */-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721-		       && LARGE_OFF_T % 2147483647 == 1)-		      ? 1 : -1];-int-main ()-{--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_sys_file_offset_bits=no; break-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#define _FILE_OFFSET_BITS 64-#include <sys/types.h>- /* Check that off_t can represent 2**63 - 1 correctly.-    We can't simply define LARGE_OFF_T to be 9223372036854775807,-    since some C++ compilers masquerading as C compilers-    incorrectly reject 9223372036854775807.  */-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721-		       && LARGE_OFF_T % 2147483647 == 1)-		      ? 1 : -1];-int-main ()-{--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_sys_file_offset_bits=64; break-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-  ac_cv_sys_file_offset_bits=unknown-  break-done-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_file_offset_bits" >&5-$as_echo "$ac_cv_sys_file_offset_bits" >&6; }-case $ac_cv_sys_file_offset_bits in #(-  no | unknown) ;;-  *)-cat >>confdefs.h <<_ACEOF-#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits-_ACEOF-;;-esac-rm -rf conftest*-  if test $ac_cv_sys_file_offset_bits = unknown; then-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _LARGE_FILES value needed for large files" >&5-$as_echo_n "checking for _LARGE_FILES value needed for large files... " >&6; }-if ${ac_cv_sys_large_files+:} false; then :-  $as_echo_n "(cached) " >&6-else-  while :; do-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <sys/types.h>- /* Check that off_t can represent 2**63 - 1 correctly.-    We can't simply define LARGE_OFF_T to be 9223372036854775807,-    since some C++ compilers masquerading as C compilers-    incorrectly reject 9223372036854775807.  */-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721-		       && LARGE_OFF_T % 2147483647 == 1)-		      ? 1 : -1];-int-main ()-{--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_sys_large_files=no; break-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#define _LARGE_FILES 1-#include <sys/types.h>- /* Check that off_t can represent 2**63 - 1 correctly.-    We can't simply define LARGE_OFF_T to be 9223372036854775807,-    since some C++ compilers masquerading as C compilers-    incorrectly reject 9223372036854775807.  */-#define LARGE_OFF_T ((((off_t) 1 << 31) << 31) - 1 + (((off_t) 1 << 31) << 31))-  int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721-		       && LARGE_OFF_T % 2147483647 == 1)-		      ? 1 : -1];-int-main ()-{--  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_compile "$LINENO"; then :-  ac_cv_sys_large_files=1; break-fi-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext-  ac_cv_sys_large_files=unknown-  break-done-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_large_files" >&5-$as_echo "$ac_cv_sys_large_files" >&6; }-case $ac_cv_sys_large_files in #(-  no | unknown) ;;-  *)-cat >>confdefs.h <<_ACEOF-#define _LARGE_FILES $ac_cv_sys_large_files-_ACEOF-;;-esac-rm -rf conftest*-  fi---fi---for ac_header in wctype.h-do :-  ac_fn_c_check_header_mongrel "$LINENO" "wctype.h" "ac_cv_header_wctype_h" "$ac_includes_default"-if test "x$ac_cv_header_wctype_h" = xyes; then :-  cat >>confdefs.h <<_ACEOF-#define HAVE_WCTYPE_H 1-_ACEOF- for ac_func in iswspace-do :-  ac_fn_c_check_func "$LINENO" "iswspace" "ac_cv_func_iswspace"-if test "x$ac_cv_func_iswspace" = xyes; then :-  cat >>confdefs.h <<_ACEOF-#define HAVE_ISWSPACE 1-_ACEOF--fi-done--fi--done---for ac_func in lstat-do :-  ac_fn_c_check_func "$LINENO" "lstat" "ac_cv_func_lstat"-if test "x$ac_cv_func_lstat" = xyes; then :-  cat >>confdefs.h <<_ACEOF-#define HAVE_LSTAT 1-_ACEOF--fi-done--{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for clock_gettime in -lrt" >&5-$as_echo_n "checking for clock_gettime in -lrt... " >&6; }-if ${ac_cv_lib_rt_clock_gettime+:} false; then :-  $as_echo_n "(cached) " >&6-else-  ac_check_lib_save_LIBS=$LIBS-LIBS="-lrt  $LIBS"-cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */--/* Override any GCC internal prototype to avoid an error.-   Use char because int might match the return type of a GCC-   builtin and then its argument prototype would still apply.  */-#ifdef __cplusplus-extern "C"-#endif-char clock_gettime ();-int-main ()-{-return clock_gettime ();-  ;-  return 0;-}-_ACEOF-if ac_fn_c_try_link "$LINENO"; then :-  ac_cv_lib_rt_clock_gettime=yes-else-  ac_cv_lib_rt_clock_gettime=no-fi-rm -f core conftest.err conftest.$ac_objext \-    conftest$ac_exeext conftest.$ac_ext-LIBS=$ac_check_lib_save_LIBS-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_rt_clock_gettime" >&5-$as_echo "$ac_cv_lib_rt_clock_gettime" >&6; }-if test "x$ac_cv_lib_rt_clock_gettime" = xyes; then :-  cat >>confdefs.h <<_ACEOF-#define HAVE_LIBRT 1-_ACEOF--  LIBS="-lrt $LIBS"--fi--for ac_func in clock_gettime-do :-  ac_fn_c_check_func "$LINENO" "clock_gettime" "ac_cv_func_clock_gettime"-if test "x$ac_cv_func_clock_gettime" = xyes; then :-  cat >>confdefs.h <<_ACEOF-#define HAVE_CLOCK_GETTIME 1-_ACEOF--fi-done--for ac_func in getclock getrusage times-do :-  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`-ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"-if eval test \"x\$"$as_ac_var"\" = x"yes"; then :-  cat >>confdefs.h <<_ACEOF-#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1-_ACEOF--fi-done--for ac_func in _chsize ftruncate-do :-  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`-ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"-if eval test \"x\$"$as_ac_var"\" = x"yes"; then :-  cat >>confdefs.h <<_ACEOF-#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1-_ACEOF--fi-done---for ac_func in epoll_ctl eventfd kevent kevent64 kqueue poll-do :-  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`-ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"-if eval test \"x\$"$as_ac_var"\" = x"yes"; then :-  cat >>confdefs.h <<_ACEOF-#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1-_ACEOF--fi-done---# event-related fun--if test "$ac_cv_header_sys_epoll_h" = yes -a "$ac_cv_func_epoll_ctl" = yes; then--$as_echo "#define HAVE_EPOLL 1" >>confdefs.h--fi--if test "$ac_cv_header_sys_event_h" = yes -a "$ac_cv_func_kqueue" = yes; then--$as_echo "#define HAVE_KQUEUE 1" >>confdefs.h---  # The cast to long int works around a bug in the HP C Compiler-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.-# This bug is HP SR number 8606223364.-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of kev.filter" >&5-$as_echo_n "checking size of kev.filter... " >&6; }-if ${ac_cv_sizeof_kev_filter+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (kev.filter))" "ac_cv_sizeof_kev_filter"        "#include <sys/event.h>-struct kevent kev;-"; then :--else-  if test "$ac_cv_type_kev_filter" = yes; then-     { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error 77 "cannot compute sizeof (kev.filter)-See \`config.log' for more details" "$LINENO" 5; }-   else-     ac_cv_sizeof_kev_filter=0-   fi-fi--fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_kev_filter" >&5-$as_echo "$ac_cv_sizeof_kev_filter" >&6; }----cat >>confdefs.h <<_ACEOF-#define SIZEOF_KEV_FILTER $ac_cv_sizeof_kev_filter-_ACEOF----  # The cast to long int works around a bug in the HP C Compiler-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.-# This bug is HP SR number 8606223364.-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of kev.flags" >&5-$as_echo_n "checking size of kev.flags... " >&6; }-if ${ac_cv_sizeof_kev_flags+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (kev.flags))" "ac_cv_sizeof_kev_flags"        "#include <sys/event.h>-struct kevent kev;-"; then :--else-  if test "$ac_cv_type_kev_flags" = yes; then-     { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error 77 "cannot compute sizeof (kev.flags)-See \`config.log' for more details" "$LINENO" 5; }-   else-     ac_cv_sizeof_kev_flags=0-   fi-fi--fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_kev_flags" >&5-$as_echo "$ac_cv_sizeof_kev_flags" >&6; }----cat >>confdefs.h <<_ACEOF-#define SIZEOF_KEV_FLAGS $ac_cv_sizeof_kev_flags-_ACEOF---fi--if test "$ac_cv_header_poll_h" = yes -a "$ac_cv_func_poll" = yes; then--$as_echo "#define HAVE_POLL 1" >>confdefs.h--fi--# unsetenv-for ac_func in unsetenv-do :-  ac_fn_c_check_func "$LINENO" "unsetenv" "ac_cv_func_unsetenv"-if test "x$ac_cv_func_unsetenv" = xyes; then :-  cat >>confdefs.h <<_ACEOF-#define HAVE_UNSETENV 1-_ACEOF--fi-done---###  POSIX.1003.1 unsetenv returns 0 or -1 (EINVAL), but older implementations-###  in common use return void.-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of unsetenv" >&5-$as_echo_n "checking return type of unsetenv... " >&6; }-if ${fptools_cv_func_unsetenv_return_type+:} false; then :-  $as_echo_n "(cached) " >&6-else-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <stdlib.h>--_ACEOF-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |-  $EGREP "void[      ]+unsetenv" >/dev/null 2>&1; then :-  fptools_cv_func_unsetenv_return_type=void-else-  fptools_cv_func_unsetenv_return_type=int-fi-rm -f conftest*--fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_func_unsetenv_return_type" >&5-$as_echo "$fptools_cv_func_unsetenv_return_type" >&6; }-case "$fptools_cv_func_unsetenv_return_type" in-  "void" )--$as_echo "#define UNSETENV_RETURNS_VOID 1" >>confdefs.h--  ;;-esac----# Check whether --with-iconv-includes was given.-if test "${with_iconv_includes+set}" = set; then :-  withval=$with_iconv_includes; ICONV_INCLUDE_DIRS=$withval; CPPFLAGS="-I$withval"-else-  ICONV_INCLUDE_DIRS=-fi----# Check whether --with-iconv-libraries was given.-if test "${with_iconv_libraries+set}" = set; then :-  withval=$with_iconv_libraries; ICONV_LIB_DIRS=$withval; LDFLAGS="-L$withval"-else-  ICONV_LIB_DIRS=-fi------# map standard C types and ISO types to Haskell types---------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for char" >&5-$as_echo_n "checking Haskell type for char... " >&6; }-    if ${fptools_cv_htype_char+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_char=yes-        if ac_fn_c_compute_int "$LINENO" "(char)0.2 - (char)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(char) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_char=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(char) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_char=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(char) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_char=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_char=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_char=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_char=LDouble-            else-                fptools_cv_htype_sup_char=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((char)(-1)) < ((char)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_char=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(char) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_char=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_char="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_char="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_char" = no-    then--        fptools_cv_htype_char=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_char" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_char" >&5-$as_echo "$fptools_cv_htype_char" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_CHAR $fptools_cv_htype_char-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for signed char" >&5-$as_echo_n "checking Haskell type for signed char... " >&6; }-    if ${fptools_cv_htype_signed_char+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_signed_char=yes-        if ac_fn_c_compute_int "$LINENO" "(signed char)0.2 - (signed char)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(signed char) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_signed_char=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(signed char) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_signed_char=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(signed char) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_signed_char=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_signed_char=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_signed_char=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_signed_char=LDouble-            else-                fptools_cv_htype_sup_signed_char=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((signed char)(-1)) < ((signed char)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_signed_char=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(signed char) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_signed_char=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_signed_char="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_signed_char="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_signed_char" = no-    then--        fptools_cv_htype_signed_char=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_signed_char" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_signed_char" >&5-$as_echo "$fptools_cv_htype_signed_char" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_SIGNED_CHAR $fptools_cv_htype_signed_char-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for unsigned char" >&5-$as_echo_n "checking Haskell type for unsigned char... " >&6; }-    if ${fptools_cv_htype_unsigned_char+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_unsigned_char=yes-        if ac_fn_c_compute_int "$LINENO" "(unsigned char)0.2 - (unsigned char)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned char) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_char=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned char) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_char=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned char) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_char=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_unsigned_char=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_char=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_char=LDouble-            else-                fptools_cv_htype_sup_unsigned_char=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((unsigned char)(-1)) < ((unsigned char)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_char=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned char) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_char=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_unsigned_char="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_unsigned_char="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_unsigned_char" = no-    then--        fptools_cv_htype_unsigned_char=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_unsigned_char" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_unsigned_char" >&5-$as_echo "$fptools_cv_htype_unsigned_char" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_UNSIGNED_CHAR $fptools_cv_htype_unsigned_char-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for short" >&5-$as_echo_n "checking Haskell type for short... " >&6; }-    if ${fptools_cv_htype_short+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_short=yes-        if ac_fn_c_compute_int "$LINENO" "(short)0.2 - (short)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(short) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_short=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(short) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_short=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(short) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_short=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_short=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_short=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_short=LDouble-            else-                fptools_cv_htype_sup_short=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((short)(-1)) < ((short)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_short=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(short) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_short=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_short="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_short="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_short" = no-    then--        fptools_cv_htype_short=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_short" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_short" >&5-$as_echo "$fptools_cv_htype_short" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_SHORT $fptools_cv_htype_short-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for unsigned short" >&5-$as_echo_n "checking Haskell type for unsigned short... " >&6; }-    if ${fptools_cv_htype_unsigned_short+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_unsigned_short=yes-        if ac_fn_c_compute_int "$LINENO" "(unsigned short)0.2 - (unsigned short)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned short) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_short=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned short) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_short=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned short) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_short=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_unsigned_short=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_short=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_short=LDouble-            else-                fptools_cv_htype_sup_unsigned_short=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((unsigned short)(-1)) < ((unsigned short)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_short=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned short) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_short=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_unsigned_short="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_unsigned_short="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_unsigned_short" = no-    then--        fptools_cv_htype_unsigned_short=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_unsigned_short" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_unsigned_short" >&5-$as_echo "$fptools_cv_htype_unsigned_short" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_UNSIGNED_SHORT $fptools_cv_htype_unsigned_short-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for int" >&5-$as_echo_n "checking Haskell type for int... " >&6; }-    if ${fptools_cv_htype_int+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_int=yes-        if ac_fn_c_compute_int "$LINENO" "(int)0.2 - (int)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(int) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_int=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(int) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_int=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(int) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_int=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_int=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_int=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_int=LDouble-            else-                fptools_cv_htype_sup_int=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((int)(-1)) < ((int)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_int=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(int) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_int=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_int="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_int="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_int" = no-    then--        fptools_cv_htype_int=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_int" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_int" >&5-$as_echo "$fptools_cv_htype_int" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_INT $fptools_cv_htype_int-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for unsigned int" >&5-$as_echo_n "checking Haskell type for unsigned int... " >&6; }-    if ${fptools_cv_htype_unsigned_int+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_unsigned_int=yes-        if ac_fn_c_compute_int "$LINENO" "(unsigned int)0.2 - (unsigned int)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned int) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_int=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned int) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_int=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned int) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_int=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_unsigned_int=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_int=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_int=LDouble-            else-                fptools_cv_htype_sup_unsigned_int=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((unsigned int)(-1)) < ((unsigned int)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_int=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned int) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_int=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_unsigned_int="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_unsigned_int="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_unsigned_int" = no-    then--        fptools_cv_htype_unsigned_int=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_unsigned_int" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_unsigned_int" >&5-$as_echo "$fptools_cv_htype_unsigned_int" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_UNSIGNED_INT $fptools_cv_htype_unsigned_int-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for long" >&5-$as_echo_n "checking Haskell type for long... " >&6; }-    if ${fptools_cv_htype_long+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_long=yes-        if ac_fn_c_compute_int "$LINENO" "(long)0.2 - (long)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(long) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(long) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(long) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_long=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_long=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_long=LDouble-            else-                fptools_cv_htype_sup_long=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((long)(-1)) < ((long)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(long) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_long="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_long="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_long" = no-    then--        fptools_cv_htype_long=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_long" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_long" >&5-$as_echo "$fptools_cv_htype_long" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_LONG $fptools_cv_htype_long-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for unsigned long" >&5-$as_echo_n "checking Haskell type for unsigned long... " >&6; }-    if ${fptools_cv_htype_unsigned_long+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_unsigned_long=yes-        if ac_fn_c_compute_int "$LINENO" "(unsigned long)0.2 - (unsigned long)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned long) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned long) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned long) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_unsigned_long=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_long=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_long=LDouble-            else-                fptools_cv_htype_sup_unsigned_long=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((unsigned long)(-1)) < ((unsigned long)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned long) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_unsigned_long="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_unsigned_long="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_unsigned_long" = no-    then--        fptools_cv_htype_unsigned_long=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_unsigned_long" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_unsigned_long" >&5-$as_echo "$fptools_cv_htype_unsigned_long" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_UNSIGNED_LONG $fptools_cv_htype_unsigned_long-_ACEOF--    fi---if test "$ac_cv_type_long_long" = yes; then---------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for long long" >&5-$as_echo_n "checking Haskell type for long long... " >&6; }-    if ${fptools_cv_htype_long_long+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_long_long=yes-        if ac_fn_c_compute_int "$LINENO" "(long long)0.2 - (long long)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(long long) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(long long) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(long long) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long_long=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_long_long=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_long_long=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_long_long=LDouble-            else-                fptools_cv_htype_sup_long_long=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((long long)(-1)) < ((long long)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(long long) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_long_long=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_long_long="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_long_long="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_long_long" = no-    then--        fptools_cv_htype_long_long=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_long_long" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_long_long" >&5-$as_echo "$fptools_cv_htype_long_long" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_LONG_LONG $fptools_cv_htype_long_long-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for unsigned long long" >&5-$as_echo_n "checking Haskell type for unsigned long long... " >&6; }-    if ${fptools_cv_htype_unsigned_long_long+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_unsigned_long_long=yes-        if ac_fn_c_compute_int "$LINENO" "(unsigned long long)0.2 - (unsigned long long)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned long long) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned long long) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned long long) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long_long=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_unsigned_long_long=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_long_long=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_unsigned_long_long=LDouble-            else-                fptools_cv_htype_sup_unsigned_long_long=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((unsigned long long)(-1)) < ((unsigned long long)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long_long=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(unsigned long long) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_unsigned_long_long=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_unsigned_long_long="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_unsigned_long_long="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_unsigned_long_long" = no-    then--        fptools_cv_htype_unsigned_long_long=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_unsigned_long_long" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_unsigned_long_long" >&5-$as_echo "$fptools_cv_htype_unsigned_long_long" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_UNSIGNED_LONG_LONG $fptools_cv_htype_unsigned_long_long-_ACEOF--    fi---fi---------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for float" >&5-$as_echo_n "checking Haskell type for float... " >&6; }-    if ${fptools_cv_htype_float+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_float=yes-        if ac_fn_c_compute_int "$LINENO" "(float)0.2 - (float)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(float) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_float=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(float) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_float=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(float) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_float=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_float=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_float=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_float=LDouble-            else-                fptools_cv_htype_sup_float=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((float)(-1)) < ((float)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_float=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(float) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_float=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_float="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_float="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_float" = no-    then--        fptools_cv_htype_float=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_float" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_float" >&5-$as_echo "$fptools_cv_htype_float" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_FLOAT $fptools_cv_htype_float-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for double" >&5-$as_echo_n "checking Haskell type for double... " >&6; }-    if ${fptools_cv_htype_double+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_double=yes-        if ac_fn_c_compute_int "$LINENO" "(double)0.2 - (double)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(double) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_double=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(double) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_double=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(double) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_double=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_double=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_double=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_double=LDouble-            else-                fptools_cv_htype_sup_double=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((double)(-1)) < ((double)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_double=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(double) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_double=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_double="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_double="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_double" = no-    then--        fptools_cv_htype_double=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_double" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_double" >&5-$as_echo "$fptools_cv_htype_double" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_DOUBLE $fptools_cv_htype_double-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for ptrdiff_t" >&5-$as_echo_n "checking Haskell type for ptrdiff_t... " >&6; }-    if ${fptools_cv_htype_ptrdiff_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_ptrdiff_t=yes-        if ac_fn_c_compute_int "$LINENO" "(ptrdiff_t)0.2 - (ptrdiff_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(ptrdiff_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ptrdiff_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(ptrdiff_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ptrdiff_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(ptrdiff_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ptrdiff_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_ptrdiff_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_ptrdiff_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_ptrdiff_t=LDouble-            else-                fptools_cv_htype_sup_ptrdiff_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((ptrdiff_t)(-1)) < ((ptrdiff_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ptrdiff_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(ptrdiff_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ptrdiff_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_ptrdiff_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_ptrdiff_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_ptrdiff_t" = no-    then--        fptools_cv_htype_ptrdiff_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_ptrdiff_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_ptrdiff_t" >&5-$as_echo "$fptools_cv_htype_ptrdiff_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_PTRDIFF_T $fptools_cv_htype_ptrdiff_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for size_t" >&5-$as_echo_n "checking Haskell type for size_t... " >&6; }-    if ${fptools_cv_htype_size_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_size_t=yes-        if ac_fn_c_compute_int "$LINENO" "(size_t)0.2 - (size_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(size_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_size_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(size_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_size_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(size_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_size_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_size_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_size_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_size_t=LDouble-            else-                fptools_cv_htype_sup_size_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((size_t)(-1)) < ((size_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_size_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(size_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_size_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_size_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_size_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_size_t" = no-    then--        fptools_cv_htype_size_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_size_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_size_t" >&5-$as_echo "$fptools_cv_htype_size_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_SIZE_T $fptools_cv_htype_size_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for wchar_t" >&5-$as_echo_n "checking Haskell type for wchar_t... " >&6; }-    if ${fptools_cv_htype_wchar_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_wchar_t=yes-        if ac_fn_c_compute_int "$LINENO" "(wchar_t)0.2 - (wchar_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(wchar_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_wchar_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(wchar_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_wchar_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(wchar_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_wchar_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_wchar_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_wchar_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_wchar_t=LDouble-            else-                fptools_cv_htype_sup_wchar_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((wchar_t)(-1)) < ((wchar_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_wchar_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(wchar_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_wchar_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_wchar_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_wchar_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_wchar_t" = no-    then--        fptools_cv_htype_wchar_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_wchar_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_wchar_t" >&5-$as_echo "$fptools_cv_htype_wchar_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_WCHAR_T $fptools_cv_htype_wchar_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for sig_atomic_t" >&5-$as_echo_n "checking Haskell type for sig_atomic_t... " >&6; }-    if ${fptools_cv_htype_sig_atomic_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_sig_atomic_t=yes-        if ac_fn_c_compute_int "$LINENO" "(sig_atomic_t)0.2 - (sig_atomic_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(sig_atomic_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_sig_atomic_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(sig_atomic_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_sig_atomic_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(sig_atomic_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_sig_atomic_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_sig_atomic_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_sig_atomic_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_sig_atomic_t=LDouble-            else-                fptools_cv_htype_sup_sig_atomic_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((sig_atomic_t)(-1)) < ((sig_atomic_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_sig_atomic_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(sig_atomic_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_sig_atomic_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_sig_atomic_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_sig_atomic_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_sig_atomic_t" = no-    then--        fptools_cv_htype_sig_atomic_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_sig_atomic_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_sig_atomic_t" >&5-$as_echo "$fptools_cv_htype_sig_atomic_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_SIG_ATOMIC_T $fptools_cv_htype_sig_atomic_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for clock_t" >&5-$as_echo_n "checking Haskell type for clock_t... " >&6; }-    if ${fptools_cv_htype_clock_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_clock_t=yes-        if ac_fn_c_compute_int "$LINENO" "(clock_t)0.2 - (clock_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(clock_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_clock_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(clock_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_clock_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(clock_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_clock_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_clock_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_clock_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_clock_t=LDouble-            else-                fptools_cv_htype_sup_clock_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((clock_t)(-1)) < ((clock_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_clock_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(clock_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_clock_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_clock_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_clock_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_clock_t" = no-    then--        fptools_cv_htype_clock_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_clock_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_clock_t" >&5-$as_echo "$fptools_cv_htype_clock_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_CLOCK_T $fptools_cv_htype_clock_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for time_t" >&5-$as_echo_n "checking Haskell type for time_t... " >&6; }-    if ${fptools_cv_htype_time_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_time_t=yes-        if ac_fn_c_compute_int "$LINENO" "(time_t)0.2 - (time_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(time_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_time_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(time_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_time_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(time_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_time_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_time_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_time_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_time_t=LDouble-            else-                fptools_cv_htype_sup_time_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((time_t)(-1)) < ((time_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_time_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(time_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_time_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_time_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_time_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_time_t" = no-    then--        fptools_cv_htype_time_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_time_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_time_t" >&5-$as_echo "$fptools_cv_htype_time_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_TIME_T $fptools_cv_htype_time_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for useconds_t" >&5-$as_echo_n "checking Haskell type for useconds_t... " >&6; }-    if ${fptools_cv_htype_useconds_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_useconds_t=yes-        if ac_fn_c_compute_int "$LINENO" "(useconds_t)0.2 - (useconds_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(useconds_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_useconds_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(useconds_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_useconds_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(useconds_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_useconds_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_useconds_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_useconds_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_useconds_t=LDouble-            else-                fptools_cv_htype_sup_useconds_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((useconds_t)(-1)) < ((useconds_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_useconds_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(useconds_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_useconds_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_useconds_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_useconds_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_useconds_t" = no-    then--        fptools_cv_htype_useconds_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_useconds_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_useconds_t" >&5-$as_echo "$fptools_cv_htype_useconds_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_USECONDS_T $fptools_cv_htype_useconds_t-_ACEOF--    fi----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for suseconds_t" >&5-$as_echo_n "checking Haskell type for suseconds_t... " >&6; }-    if ${fptools_cv_htype_suseconds_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_suseconds_t=yes-        if ac_fn_c_compute_int "$LINENO" "(suseconds_t)0.2 - (suseconds_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(suseconds_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_suseconds_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(suseconds_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_suseconds_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(suseconds_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_suseconds_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_suseconds_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_suseconds_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_suseconds_t=LDouble-            else-                fptools_cv_htype_sup_suseconds_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((suseconds_t)(-1)) < ((suseconds_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_suseconds_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(suseconds_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_suseconds_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_suseconds_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_suseconds_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_suseconds_t" = no-    then-        if test "$WINDOWS" = "YES"-                          then-                              fptools_cv_htype_suseconds_t=Int32-                              fptools_cv_htype_sup_suseconds_t=yes-                          else-                              as_fn_error $? "type not found" "$LINENO" 5-                          fi-    fi--            if test "$fptools_cv_htype_sup_suseconds_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_suseconds_t" >&5-$as_echo "$fptools_cv_htype_suseconds_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_SUSECONDS_T $fptools_cv_htype_suseconds_t-_ACEOF--    fi----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for dev_t" >&5-$as_echo_n "checking Haskell type for dev_t... " >&6; }-    if ${fptools_cv_htype_dev_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_dev_t=yes-        if ac_fn_c_compute_int "$LINENO" "(dev_t)0.2 - (dev_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(dev_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_dev_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(dev_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_dev_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(dev_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_dev_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_dev_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_dev_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_dev_t=LDouble-            else-                fptools_cv_htype_sup_dev_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((dev_t)(-1)) < ((dev_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_dev_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(dev_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_dev_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_dev_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_dev_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_dev_t" = no-    then--        fptools_cv_htype_dev_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_dev_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_dev_t" >&5-$as_echo "$fptools_cv_htype_dev_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_DEV_T $fptools_cv_htype_dev_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for ino_t" >&5-$as_echo_n "checking Haskell type for ino_t... " >&6; }-    if ${fptools_cv_htype_ino_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_ino_t=yes-        if ac_fn_c_compute_int "$LINENO" "(ino_t)0.2 - (ino_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(ino_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ino_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(ino_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ino_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(ino_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ino_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_ino_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_ino_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_ino_t=LDouble-            else-                fptools_cv_htype_sup_ino_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((ino_t)(-1)) < ((ino_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ino_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(ino_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ino_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_ino_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_ino_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_ino_t" = no-    then--        fptools_cv_htype_ino_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_ino_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_ino_t" >&5-$as_echo "$fptools_cv_htype_ino_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_INO_T $fptools_cv_htype_ino_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for mode_t" >&5-$as_echo_n "checking Haskell type for mode_t... " >&6; }-    if ${fptools_cv_htype_mode_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_mode_t=yes-        if ac_fn_c_compute_int "$LINENO" "(mode_t)0.2 - (mode_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(mode_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_mode_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(mode_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_mode_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(mode_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_mode_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_mode_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_mode_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_mode_t=LDouble-            else-                fptools_cv_htype_sup_mode_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((mode_t)(-1)) < ((mode_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_mode_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(mode_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_mode_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_mode_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_mode_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_mode_t" = no-    then--        fptools_cv_htype_mode_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_mode_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_mode_t" >&5-$as_echo "$fptools_cv_htype_mode_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_MODE_T $fptools_cv_htype_mode_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for off_t" >&5-$as_echo_n "checking Haskell type for off_t... " >&6; }-    if ${fptools_cv_htype_off_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_off_t=yes-        if ac_fn_c_compute_int "$LINENO" "(off_t)0.2 - (off_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(off_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_off_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(off_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_off_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(off_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_off_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_off_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_off_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_off_t=LDouble-            else-                fptools_cv_htype_sup_off_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((off_t)(-1)) < ((off_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_off_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(off_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_off_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_off_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_off_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_off_t" = no-    then--        fptools_cv_htype_off_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_off_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_off_t" >&5-$as_echo "$fptools_cv_htype_off_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_OFF_T $fptools_cv_htype_off_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for pid_t" >&5-$as_echo_n "checking Haskell type for pid_t... " >&6; }-    if ${fptools_cv_htype_pid_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_pid_t=yes-        if ac_fn_c_compute_int "$LINENO" "(pid_t)0.2 - (pid_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(pid_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_pid_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(pid_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_pid_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(pid_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_pid_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_pid_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_pid_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_pid_t=LDouble-            else-                fptools_cv_htype_sup_pid_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((pid_t)(-1)) < ((pid_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_pid_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(pid_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_pid_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_pid_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_pid_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_pid_t" = no-    then--        fptools_cv_htype_pid_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_pid_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_pid_t" >&5-$as_echo "$fptools_cv_htype_pid_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_PID_T $fptools_cv_htype_pid_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for gid_t" >&5-$as_echo_n "checking Haskell type for gid_t... " >&6; }-    if ${fptools_cv_htype_gid_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_gid_t=yes-        if ac_fn_c_compute_int "$LINENO" "(gid_t)0.2 - (gid_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(gid_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_gid_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(gid_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_gid_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(gid_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_gid_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_gid_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_gid_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_gid_t=LDouble-            else-                fptools_cv_htype_sup_gid_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((gid_t)(-1)) < ((gid_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_gid_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(gid_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_gid_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_gid_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_gid_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_gid_t" = no-    then--        fptools_cv_htype_gid_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_gid_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_gid_t" >&5-$as_echo "$fptools_cv_htype_gid_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_GID_T $fptools_cv_htype_gid_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for uid_t" >&5-$as_echo_n "checking Haskell type for uid_t... " >&6; }-    if ${fptools_cv_htype_uid_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_uid_t=yes-        if ac_fn_c_compute_int "$LINENO" "(uid_t)0.2 - (uid_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(uid_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uid_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(uid_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uid_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(uid_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uid_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_uid_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_uid_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_uid_t=LDouble-            else-                fptools_cv_htype_sup_uid_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((uid_t)(-1)) < ((uid_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uid_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(uid_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uid_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_uid_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_uid_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_uid_t" = no-    then--        fptools_cv_htype_uid_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_uid_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_uid_t" >&5-$as_echo "$fptools_cv_htype_uid_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_UID_T $fptools_cv_htype_uid_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for cc_t" >&5-$as_echo_n "checking Haskell type for cc_t... " >&6; }-    if ${fptools_cv_htype_cc_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_cc_t=yes-        if ac_fn_c_compute_int "$LINENO" "(cc_t)0.2 - (cc_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(cc_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_cc_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(cc_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_cc_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(cc_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_cc_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_cc_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_cc_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_cc_t=LDouble-            else-                fptools_cv_htype_sup_cc_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((cc_t)(-1)) < ((cc_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_cc_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(cc_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_cc_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_cc_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_cc_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_cc_t" = no-    then--        fptools_cv_htype_cc_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_cc_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_cc_t" >&5-$as_echo "$fptools_cv_htype_cc_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_CC_T $fptools_cv_htype_cc_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for speed_t" >&5-$as_echo_n "checking Haskell type for speed_t... " >&6; }-    if ${fptools_cv_htype_speed_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_speed_t=yes-        if ac_fn_c_compute_int "$LINENO" "(speed_t)0.2 - (speed_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(speed_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_speed_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(speed_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_speed_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(speed_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_speed_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_speed_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_speed_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_speed_t=LDouble-            else-                fptools_cv_htype_sup_speed_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((speed_t)(-1)) < ((speed_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_speed_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(speed_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_speed_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_speed_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_speed_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_speed_t" = no-    then--        fptools_cv_htype_speed_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_speed_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_speed_t" >&5-$as_echo "$fptools_cv_htype_speed_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_SPEED_T $fptools_cv_htype_speed_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for tcflag_t" >&5-$as_echo_n "checking Haskell type for tcflag_t... " >&6; }-    if ${fptools_cv_htype_tcflag_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_tcflag_t=yes-        if ac_fn_c_compute_int "$LINENO" "(tcflag_t)0.2 - (tcflag_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(tcflag_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_tcflag_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(tcflag_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_tcflag_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(tcflag_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_tcflag_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_tcflag_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_tcflag_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_tcflag_t=LDouble-            else-                fptools_cv_htype_sup_tcflag_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((tcflag_t)(-1)) < ((tcflag_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_tcflag_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(tcflag_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_tcflag_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_tcflag_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_tcflag_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_tcflag_t" = no-    then--        fptools_cv_htype_tcflag_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_tcflag_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_tcflag_t" >&5-$as_echo "$fptools_cv_htype_tcflag_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_TCFLAG_T $fptools_cv_htype_tcflag_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for nlink_t" >&5-$as_echo_n "checking Haskell type for nlink_t... " >&6; }-    if ${fptools_cv_htype_nlink_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_nlink_t=yes-        if ac_fn_c_compute_int "$LINENO" "(nlink_t)0.2 - (nlink_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(nlink_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_nlink_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(nlink_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_nlink_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(nlink_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_nlink_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_nlink_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_nlink_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_nlink_t=LDouble-            else-                fptools_cv_htype_sup_nlink_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((nlink_t)(-1)) < ((nlink_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_nlink_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(nlink_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_nlink_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_nlink_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_nlink_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_nlink_t" = no-    then--        fptools_cv_htype_nlink_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_nlink_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_nlink_t" >&5-$as_echo "$fptools_cv_htype_nlink_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_NLINK_T $fptools_cv_htype_nlink_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for ssize_t" >&5-$as_echo_n "checking Haskell type for ssize_t... " >&6; }-    if ${fptools_cv_htype_ssize_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_ssize_t=yes-        if ac_fn_c_compute_int "$LINENO" "(ssize_t)0.2 - (ssize_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(ssize_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ssize_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(ssize_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ssize_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(ssize_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ssize_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_ssize_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_ssize_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_ssize_t=LDouble-            else-                fptools_cv_htype_sup_ssize_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((ssize_t)(-1)) < ((ssize_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ssize_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(ssize_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_ssize_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_ssize_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_ssize_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_ssize_t" = no-    then--        fptools_cv_htype_ssize_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_ssize_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_ssize_t" >&5-$as_echo "$fptools_cv_htype_ssize_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_SSIZE_T $fptools_cv_htype_ssize_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for rlim_t" >&5-$as_echo_n "checking Haskell type for rlim_t... " >&6; }-    if ${fptools_cv_htype_rlim_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_rlim_t=yes-        if ac_fn_c_compute_int "$LINENO" "(rlim_t)0.2 - (rlim_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(rlim_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_rlim_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(rlim_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_rlim_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(rlim_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_rlim_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_rlim_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_rlim_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_rlim_t=LDouble-            else-                fptools_cv_htype_sup_rlim_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((rlim_t)(-1)) < ((rlim_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_rlim_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(rlim_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_rlim_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_rlim_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_rlim_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_rlim_t" = no-    then--        fptools_cv_htype_rlim_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_rlim_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_rlim_t" >&5-$as_echo "$fptools_cv_htype_rlim_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_RLIM_T $fptools_cv_htype_rlim_t-_ACEOF--    fi------------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for intptr_t" >&5-$as_echo_n "checking Haskell type for intptr_t... " >&6; }-    if ${fptools_cv_htype_intptr_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_intptr_t=yes-        if ac_fn_c_compute_int "$LINENO" "(intptr_t)0.2 - (intptr_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(intptr_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intptr_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(intptr_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intptr_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(intptr_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intptr_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_intptr_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_intptr_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_intptr_t=LDouble-            else-                fptools_cv_htype_sup_intptr_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((intptr_t)(-1)) < ((intptr_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intptr_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(intptr_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intptr_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_intptr_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_intptr_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_intptr_t" = no-    then--        fptools_cv_htype_intptr_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_intptr_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_intptr_t" >&5-$as_echo "$fptools_cv_htype_intptr_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_INTPTR_T $fptools_cv_htype_intptr_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for uintptr_t" >&5-$as_echo_n "checking Haskell type for uintptr_t... " >&6; }-    if ${fptools_cv_htype_uintptr_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_uintptr_t=yes-        if ac_fn_c_compute_int "$LINENO" "(uintptr_t)0.2 - (uintptr_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(uintptr_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintptr_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(uintptr_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintptr_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(uintptr_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintptr_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_uintptr_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_uintptr_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_uintptr_t=LDouble-            else-                fptools_cv_htype_sup_uintptr_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((uintptr_t)(-1)) < ((uintptr_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintptr_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(uintptr_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintptr_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_uintptr_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_uintptr_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_uintptr_t" = no-    then--        fptools_cv_htype_uintptr_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_uintptr_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_uintptr_t" >&5-$as_echo "$fptools_cv_htype_uintptr_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_UINTPTR_T $fptools_cv_htype_uintptr_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for intmax_t" >&5-$as_echo_n "checking Haskell type for intmax_t... " >&6; }-    if ${fptools_cv_htype_intmax_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_intmax_t=yes-        if ac_fn_c_compute_int "$LINENO" "(intmax_t)0.2 - (intmax_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(intmax_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intmax_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(intmax_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intmax_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(intmax_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intmax_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_intmax_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_intmax_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_intmax_t=LDouble-            else-                fptools_cv_htype_sup_intmax_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((intmax_t)(-1)) < ((intmax_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intmax_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(intmax_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_intmax_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_intmax_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_intmax_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_intmax_t" = no-    then--        fptools_cv_htype_intmax_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_intmax_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_intmax_t" >&5-$as_echo "$fptools_cv_htype_intmax_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_INTMAX_T $fptools_cv_htype_intmax_t-_ACEOF--    fi-----------    { $as_echo "$as_me:${as_lineno-$LINENO}: checking Haskell type for uintmax_t" >&5-$as_echo_n "checking Haskell type for uintmax_t... " >&6; }-    if ${fptools_cv_htype_uintmax_t+:} false; then :-  $as_echo_n "(cached) " >&6-else--        fptools_cv_htype_sup_uintmax_t=yes-        if ac_fn_c_compute_int "$LINENO" "(uintmax_t)0.2 - (uintmax_t)0.4 < 0 ? 0 : 1" "HTYPE_IS_INTEGRAL"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  HTYPE_IS_INTEGRAL=0-fi----        if test "$HTYPE_IS_INTEGRAL" -eq 0-        then-            if ac_fn_c_compute_int "$LINENO" "sizeof(uintmax_t) == sizeof(float)" "HTYPE_IS_FLOAT"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintmax_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(uintmax_t) == sizeof(double)" "HTYPE_IS_DOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintmax_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(uintmax_t) == sizeof(long double)" "HTYPE_IS_LDOUBLE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintmax_t=no-fi---            if test "$HTYPE_IS_FLOAT" -eq 1-            then-                fptools_cv_htype_uintmax_t=Float-            elif test "$HTYPE_IS_DOUBLE" -eq 1-            then-                fptools_cv_htype_uintmax_t=Double-            elif test "$HTYPE_IS_LDOUBLE" -eq 1-            then-                fptools_cv_htype_uintmax_t=LDouble-            else-                fptools_cv_htype_sup_uintmax_t=no-            fi-        else-            if ac_fn_c_compute_int "$LINENO" "((uintmax_t)(-1)) < ((uintmax_t)0)" "HTYPE_IS_SIGNED"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintmax_t=no-fi---            if ac_fn_c_compute_int "$LINENO" "sizeof(uintmax_t) * 8" "HTYPE_SIZE"        "-#include <stdio.h>-#include <stddef.h>--#if HAVE_SYS_TYPES_H-# include <sys/types.h>-#endif--#if HAVE_UNISTD_H-# include <unistd.h>-#endif--#if HAVE_SYS_STAT_H-# include <sys/stat.h>-#endif--#if HAVE_FCNTL_H-# include <fcntl.h>-#endif--#if HAVE_SIGNAL_H-# include <signal.h>-#endif--#if HAVE_TIME_H-# include <time.h>-#endif--#if HAVE_TERMIOS_H-# include <termios.h>-#endif--#if HAVE_STRING_H-# include <string.h>-#endif--#if HAVE_CTYPE_H-# include <ctype.h>-#endif--#if HAVE_INTTYPES_H-# include <inttypes.h>-#else-# if HAVE_STDINT_H-#  include <stdint.h>-# endif-#endif--#if HAVE_SYS_RESOURCE_H-# include <sys/resource.h>-#endif--#include <stdlib.h>-"; then :--else-  fptools_cv_htype_sup_uintmax_t=no-fi---            if test "$HTYPE_IS_SIGNED" -eq 0-            then-                fptools_cv_htype_uintmax_t="Word$HTYPE_SIZE"-            else-                fptools_cv_htype_uintmax_t="Int$HTYPE_SIZE"-            fi-        fi--fi--    if test "$fptools_cv_htype_sup_uintmax_t" = no-    then--        fptools_cv_htype_uintmax_t=NotReallyAType-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: not supported" >&5-$as_echo "not supported" >&6; }--    fi--            if test "$fptools_cv_htype_sup_uintmax_t" = yes; then-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fptools_cv_htype_uintmax_t" >&5-$as_echo "$fptools_cv_htype_uintmax_t" >&6; }--cat >>confdefs.h <<_ACEOF-#define HTYPE_UINTMAX_T $fptools_cv_htype_uintmax_t-_ACEOF--    fi----# test errno values-for fp_const_name in E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EADV EAFNOSUPPORT EAGAIN EALREADY EBADF EBADMSG EBADRPC EBUSY ECHILD ECOMM ECONNABORTED ECONNREFUSED ECONNRESET EDEADLK EDESTADDRREQ EDIRTY EDOM EDQUOT EEXIST EFAULT EFBIG EFTYPE EHOSTDOWN EHOSTUNREACH EIDRM EILSEQ EINPROGRESS EINTR EINVAL EIO EISCONN EISDIR ELOOP EMFILE EMLINK EMSGSIZE EMULTIHOP ENAMETOOLONG ENETDOWN ENETRESET ENETUNREACH ENFILE ENOBUFS ENODATA ENODEV ENOENT ENOEXEC ENOLCK ENOLINK ENOMEM ENOMSG ENONET ENOPROTOOPT ENOSPC ENOSR ENOSTR ENOSYS ENOTBLK ENOTCONN ENOTDIR ENOTEMPTY ENOTSOCK ENOTTY ENXIO EOPNOTSUPP EPERM EPFNOSUPPORT EPIPE EPROCLIM EPROCUNAVAIL EPROGMISMATCH EPROGUNAVAIL EPROTO EPROTONOSUPPORT EPROTOTYPE ERANGE EREMCHG EREMOTE EROFS ERPCMISMATCH ERREMOTE ESHUTDOWN ESOCKTNOSUPPORT ESPIPE ESRCH ESRMNT ESTALE ETIME ETIMEDOUT ETOOMANYREFS ETXTBSY EUSERS EWOULDBLOCK EXDEV ENOCIGAR ENOTSUP-do-as_fp_Cache=`$as_echo "fp_cv_const_$fp_const_name" | $as_tr_sh`-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking value of $fp_const_name" >&5-$as_echo_n "checking value of $fp_const_name... " >&6; }-if eval \${$as_fp_Cache+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if ac_fn_c_compute_int "$LINENO" "$fp_const_name" "fp_check_const_result"        "#include <stdio.h>-#include <errno.h>-"; then :--else-  fp_check_const_result='-1'-fi---eval "$as_fp_Cache=\$fp_check_const_result"-fi-eval ac_res=\$$as_fp_Cache-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5-$as_echo "$ac_res" >&6; }-cat >>confdefs.h <<_ACEOF-#define `$as_echo "CONST_$fp_const_name" | $as_tr_cpp` `eval 'as_val=${'$as_fp_Cache'};$as_echo "$as_val"'`-_ACEOF--done---# we need SIGINT in TopHandler.lhs-for fp_const_name in SIGINT-do-as_fp_Cache=`$as_echo "fp_cv_const_$fp_const_name" | $as_tr_sh`-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking value of $fp_const_name" >&5-$as_echo_n "checking value of $fp_const_name... " >&6; }-if eval \${$as_fp_Cache+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if ac_fn_c_compute_int "$LINENO" "$fp_const_name" "fp_check_const_result"        "-#if HAVE_SIGNAL_H-#include <signal.h>-#endif-"; then :--else-  fp_check_const_result='-1'-fi---eval "$as_fp_Cache=\$fp_check_const_result"-fi-eval ac_res=\$$as_fp_Cache-	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5-$as_echo "$ac_res" >&6; }-cat >>confdefs.h <<_ACEOF-#define `$as_echo "CONST_$fp_const_name" | $as_tr_cpp` `eval 'as_val=${'$as_fp_Cache'};$as_echo "$as_val"'`-_ACEOF--done---{ $as_echo "$as_me:${as_lineno-$LINENO}: checking value of O_BINARY" >&5-$as_echo_n "checking value of O_BINARY... " >&6; }-if ${fp_cv_const_O_BINARY+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if ac_fn_c_compute_int "$LINENO" "O_BINARY" "fp_check_const_result"        "#include <fcntl.h>-"; then :--else-  fp_check_const_result=0-fi---fp_cv_const_O_BINARY=$fp_check_const_result-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $fp_cv_const_O_BINARY" >&5-$as_echo "$fp_cv_const_O_BINARY" >&6; }-cat >>confdefs.h <<_ACEOF-#define CONST_O_BINARY $fp_cv_const_O_BINARY-_ACEOF---# We don't use iconv or libcharset on Windows, but if configure finds-# them then it can cause problems. So we don't even try looking if-# we are on Windows.-# See http://www.haskell.org/pipermail/cvs-ghc/2011-September/065980.html-if test "$WINDOWS" = "NO"-then--# We can't just use AC_SEARCH_LIBS for this, as on OpenBSD the iconv.h-# header needs to be included as iconv_open is #define'd to something-# else. We therefore use our own FP_SEARCH_LIBS_PROTO, which allows us-# to give prototype text.-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing iconv" >&5-$as_echo_n "checking for library containing iconv... " >&6; }-if ${ac_cv_search_iconv+:} false; then :-  $as_echo_n "(cached) " >&6-else-  ac_func_search_save_LIBS=$LIBS-cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */--#include <stddef.h>-#include <iconv.h>--int-main ()-{-iconv_t cd;-                      cd = iconv_open("", "");-                      iconv(cd,NULL,NULL,NULL,NULL);-                      iconv_close(cd);-  ;-  return 0;-}-_ACEOF-for ac_lib in '' iconv; do-  if test -z "$ac_lib"; then-    ac_res="none required"-  else-    ac_res=-l$ac_lib-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"-  fi-  if ac_fn_c_try_link "$LINENO"; then :-  ac_cv_search_iconv=$ac_res-fi-rm -f core conftest.err conftest.$ac_objext \-    conftest$ac_exeext-  if ${ac_cv_search_iconv+:} false; then :-  break-fi-done-if ${ac_cv_search_iconv+:} false; then :--else-  ac_cv_search_iconv=no-fi-rm conftest.$ac_ext-LIBS=$ac_func_search_save_LIBS-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_iconv" >&5-$as_echo "$ac_cv_search_iconv" >&6; }-ac_res=$ac_cv_search_iconv-if test "$ac_res" != no; then :-  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"-  EXTRA_LIBS="$EXTRA_LIBS $ac_lib"-else-  as_fn_error $? "iconv is required on non-Windows platforms" "$LINENO" 5-fi--# If possible, we use libcharset instead of nl_langinfo(CODESET) to-# determine the current locale's character encoding.-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing locale_charset" >&5-$as_echo_n "checking for library containing locale_charset... " >&6; }-if ${ac_cv_search_locale_charset+:} false; then :-  $as_echo_n "(cached) " >&6-else-  ac_func_search_save_LIBS=$LIBS-cat confdefs.h - <<_ACEOF >conftest.$ac_ext-/* end confdefs.h.  */-#include <libcharset.h>-int-main ()-{-const char* charset = locale_charset();-  ;-  return 0;-}-_ACEOF-for ac_lib in '' charset; do-  if test -z "$ac_lib"; then-    ac_res="none required"-  else-    ac_res=-l$ac_lib-    LIBS="-l$ac_lib  $ac_func_search_save_LIBS"-  fi-  if ac_fn_c_try_link "$LINENO"; then :-  ac_cv_search_locale_charset=$ac_res-fi-rm -f core conftest.err conftest.$ac_objext \-    conftest$ac_exeext-  if ${ac_cv_search_locale_charset+:} false; then :-  break-fi-done-if ${ac_cv_search_locale_charset+:} false; then :--else-  ac_cv_search_locale_charset=no-fi-rm conftest.$ac_ext-LIBS=$ac_func_search_save_LIBS-fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_locale_charset" >&5-$as_echo "$ac_cv_search_locale_charset" >&6; }-ac_res=$ac_cv_search_locale_charset-if test "$ac_res" != no; then :-  test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"--$as_echo "#define HAVE_LIBCHARSET 1" >>confdefs.h--     EXTRA_LIBS="$EXTRA_LIBS $ac_lib"-fi--fi--# Hack - md5.h needs HsFFI.h.  Is there a better way to do this?-CFLAGS="-I../../includes $CFLAGS"-# The cast to long int works around a bug in the HP C Compiler-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.-# This bug is HP SR number 8606223364.-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of struct MD5Context" >&5-$as_echo_n "checking size of struct MD5Context... " >&6; }-if ${ac_cv_sizeof_struct_MD5Context+:} false; then :-  $as_echo_n "(cached) " >&6-else-  if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (struct MD5Context))" "ac_cv_sizeof_struct_MD5Context"        "#include \"include/md5.h\"-"; then :--else-  if test "$ac_cv_type_struct_MD5Context" = yes; then-     { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}-as_fn_error 77 "cannot compute sizeof (struct MD5Context)-See \`config.log' for more details" "$LINENO" 5; }-   else-     ac_cv_sizeof_struct_MD5Context=0-   fi-fi--fi-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_struct_MD5Context" >&5-$as_echo "$ac_cv_sizeof_struct_MD5Context" >&6; }----cat >>confdefs.h <<_ACEOF-#define SIZEOF_STRUCT_MD5CONTEXT $ac_cv_sizeof_struct_MD5Context-_ACEOF-----ac_config_files="$ac_config_files base.buildinfo"---cat >confcache <<\_ACEOF-# This file is a shell script that caches the results of configure-# tests run on this system so they can be shared between configure-# scripts and configure runs, see configure's option --config-cache.-# It is not useful on other systems.  If it contains results you don't-# want to keep, you may remove or edit it.-#-# config.status only pays attention to the cache file if you give it-# the --recheck option to rerun configure.-#-# `ac_cv_env_foo' variables (set or unset) will be overridden when-# loading this file, other *unset* `ac_cv_foo' will be assigned the-# following values.--_ACEOF--# The following way of writing the cache mishandles newlines in values,-# but we know of no workaround that is simple, portable, and efficient.-# So, we kill variables containing newlines.-# Ultrix sh set writes to stderr and can't be redirected directly,-# and sets the high bit in the cache file unless we assign to the vars.-(-  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do-    eval ac_val=\$$ac_var-    case $ac_val in #(-    *${as_nl}*)-      case $ac_var in #(-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;-      esac-      case $ac_var in #(-      _ | IFS | as_nl) ;; #(-      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(-      *) { eval $ac_var=; unset $ac_var;} ;;-      esac ;;-    esac-  done--  (set) 2>&1 |-    case $as_nl`(ac_space=' '; set) 2>&1` in #(-    *${as_nl}ac_space=\ *)-      # `set' does not quote correctly, so add quotes: double-quote-      # substitution turns \\\\ into \\, and sed turns \\ into \.-      sed -n \-	"s/'/'\\\\''/g;-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"-      ;; #(-    *)-      # `set' quotes correctly as required by POSIX, so do not add quotes.-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"-      ;;-    esac |-    sort-) |-  sed '-     /^ac_cv_env_/b end-     t clear-     :clear-     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/-     t end-     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/-     :end' >>confcache-if diff "$cache_file" confcache >/dev/null 2>&1; then :; else-  if test -w "$cache_file"; then-    if test "x$cache_file" != "x/dev/null"; then-      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5-$as_echo "$as_me: updating cache $cache_file" >&6;}-      if test ! -f "$cache_file" || test -h "$cache_file"; then-	cat confcache >"$cache_file"-      else-        case $cache_file in #(-        */* | ?:*)-	  mv -f confcache "$cache_file"$$ &&-	  mv -f "$cache_file"$$ "$cache_file" ;; #(-        *)-	  mv -f confcache "$cache_file" ;;-	esac-      fi-    fi-  else-    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5-$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}-  fi-fi-rm -f confcache--test "x$prefix" = xNONE && prefix=$ac_default_prefix-# Let make expand exec_prefix.-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'--DEFS=-DHAVE_CONFIG_H--ac_libobjs=-ac_ltlibobjs=-U=-for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue-  # 1. Remove the extension, and $U if already installed.-  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'-  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`-  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR-  #    will be set to the directory where LIBOBJS objects are built.-  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"-  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'-done-LIBOBJS=$ac_libobjs--LTLIBOBJS=$ac_ltlibobjs----: "${CONFIG_STATUS=./config.status}"-ac_write_fail=0-ac_clean_files_save=$ac_clean_files-ac_clean_files="$ac_clean_files $CONFIG_STATUS"-{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5-$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}-as_write_fail=0-cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1-#! $SHELL-# Generated by $as_me.-# Run this file to recreate the current configuration.-# Compiler output produced by configure, useful for debugging-# configure, is in config.log if it exists.--debug=false-ac_cs_recheck=false-ac_cs_silent=false--SHELL=\${CONFIG_SHELL-$SHELL}-export SHELL-_ASEOF-cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1-## -------------------- ##-## M4sh Initialization. ##-## -------------------- ##--# Be more Bourne compatible-DUALCASE=1; export DUALCASE # for MKS sh-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :-  emulate sh-  NULLCMD=:-  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which-  # is contrary to our usage.  Disable this feature.-  alias -g '${1+"$@"}'='"$@"'-  setopt NO_GLOB_SUBST-else-  case `(set -o) 2>/dev/null` in #(-  *posix*) :-    set -o posix ;; #(-  *) :-     ;;-esac-fi---as_nl='-'-export as_nl-# Printing a long string crashes Solaris 7 /usr/bin/printf.-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo-# Prefer a ksh shell builtin over an external printf program on Solaris,-# but without wasting forks for bash or zsh.-if test -z "$BASH_VERSION$ZSH_VERSION" \-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then-  as_echo='print -r --'-  as_echo_n='print -rn --'-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then-  as_echo='printf %s\n'-  as_echo_n='printf %s'-else-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'-    as_echo_n='/usr/ucb/echo -n'-  else-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'-    as_echo_n_body='eval-      arg=$1;-      case $arg in #(-      *"$as_nl"*)-	expr "X$arg" : "X\\(.*\\)$as_nl";-	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;-      esac;-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"-    '-    export as_echo_n_body-    as_echo_n='sh -c $as_echo_n_body as_echo'-  fi-  export as_echo_body-  as_echo='sh -c $as_echo_body as_echo'-fi--# The user is always right.-if test "${PATH_SEPARATOR+set}" != set; then-  PATH_SEPARATOR=:-  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {-    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||-      PATH_SEPARATOR=';'-  }-fi---# IFS-# We need space, tab and new line, in precisely that order.  Quoting is-# there to prevent editors from complaining about space-tab.-# (If _AS_PATH_WALK were called with IFS unset, it would disable word-# splitting by setting IFS to empty value.)-IFS=" ""	$as_nl"--# Find who we are.  Look in the path if we contain no directory separator.-as_myself=-case $0 in #((-  *[\\/]* ) as_myself=$0 ;;-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR-for as_dir in $PATH-do-  IFS=$as_save_IFS-  test -z "$as_dir" && as_dir=.-    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break-  done-IFS=$as_save_IFS--     ;;-esac-# We did not find ourselves, most probably we were run as `sh COMMAND'-# in which case we are not to be found in the path.-if test "x$as_myself" = x; then-  as_myself=$0-fi-if test ! -f "$as_myself"; then-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2-  exit 1-fi--# Unset variables that we do not need and which cause bugs (e.g. in-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"-# suppresses any "Segmentation fault" message there.  '((' could-# trigger a bug in pdksh 5.2.14.-for as_var in BASH_ENV ENV MAIL MAILPATH-do eval test x\${$as_var+set} = xset \-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :-done-PS1='$ '-PS2='> '-PS4='+ '--# NLS nuisances.-LC_ALL=C-export LC_ALL-LANGUAGE=C-export LANGUAGE--# CDPATH.-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH---# as_fn_error STATUS ERROR [LINENO LOG_FD]-# -----------------------------------------# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the-# script with STATUS, using 1 if that was 0.-as_fn_error ()-{-  as_status=$1; test $as_status -eq 0 && as_status=1-  if test "$4"; then-    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4-  fi-  $as_echo "$as_me: error: $2" >&2-  as_fn_exit $as_status-} # as_fn_error---# as_fn_set_status STATUS-# ------------------------# Set $? to STATUS, without forking.-as_fn_set_status ()-{-  return $1-} # as_fn_set_status--# as_fn_exit STATUS-# ------------------# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.-as_fn_exit ()-{-  set +e-  as_fn_set_status $1-  exit $1-} # as_fn_exit--# as_fn_unset VAR-# ----------------# Portably unset VAR.-as_fn_unset ()-{-  { eval $1=; unset $1;}-}-as_unset=as_fn_unset-# as_fn_append VAR VALUE-# -----------------------# Append the text in VALUE to the end of the definition contained in VAR. Take-# advantage of any shell optimizations that allow amortized linear growth over-# repeated appends, instead of the typical quadratic growth present in naive-# implementations.-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :-  eval 'as_fn_append ()-  {-    eval $1+=\$2-  }'-else-  as_fn_append ()-  {-    eval $1=\$$1\$2-  }-fi # as_fn_append--# as_fn_arith ARG...-# -------------------# Perform arithmetic evaluation on the ARGs, and store the result in the-# global $as_val. Take advantage of shells that can avoid forks. The arguments-# must be portable across $(()) and expr.-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :-  eval 'as_fn_arith ()-  {-    as_val=$(( $* ))-  }'-else-  as_fn_arith ()-  {-    as_val=`expr "$@" || test $? -eq 1`-  }-fi # as_fn_arith---if expr a : '\(a\)' >/dev/null 2>&1 &&-   test "X`expr 00001 : '.*\(...\)'`" = X001; then-  as_expr=expr-else-  as_expr=false-fi--if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then-  as_basename=basename-else-  as_basename=false-fi--if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then-  as_dirname=dirname-else-  as_dirname=false-fi--as_me=`$as_basename -- "$0" ||-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \-	 X"$0" : 'X\(//\)$' \| \-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||-$as_echo X/"$0" |-    sed '/^.*\/\([^/][^/]*\)\/*$/{-	    s//\1/-	    q-	  }-	  /^X\/\(\/\/\)$/{-	    s//\1/-	    q-	  }-	  /^X\/\(\/\).*/{-	    s//\1/-	    q-	  }-	  s/.*/./; q'`--# Avoid depending upon Character Ranges.-as_cr_letters='abcdefghijklmnopqrstuvwxyz'-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'-as_cr_Letters=$as_cr_letters$as_cr_LETTERS-as_cr_digits='0123456789'-as_cr_alnum=$as_cr_Letters$as_cr_digits--ECHO_C= ECHO_N= ECHO_T=-case `echo -n x` in #(((((--n*)-  case `echo 'xy\c'` in-  *c*) ECHO_T='	';;	# ECHO_T is single tab character.-  xy)  ECHO_C='\c';;-  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null-       ECHO_T='	';;-  esac;;-*)-  ECHO_N='-n';;-esac--rm -f conf$$ conf$$.exe conf$$.file-if test -d conf$$.dir; then-  rm -f conf$$.dir/conf$$.file-else-  rm -f conf$$.dir-  mkdir conf$$.dir 2>/dev/null-fi-if (echo >conf$$.file) 2>/dev/null; then-  if ln -s conf$$.file conf$$ 2>/dev/null; then-    as_ln_s='ln -s'-    # ... but there are two gotchas:-    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.-    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.-    # In both cases, we have to default to `cp -pR'.-    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||-      as_ln_s='cp -pR'-  elif ln conf$$.file conf$$ 2>/dev/null; then-    as_ln_s=ln-  else-    as_ln_s='cp -pR'-  fi-else-  as_ln_s='cp -pR'-fi-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file-rmdir conf$$.dir 2>/dev/null---# as_fn_mkdir_p-# --------------# Create "$as_dir" as a directory, including parents if necessary.-as_fn_mkdir_p ()-{--  case $as_dir in #(-  -*) as_dir=./$as_dir;;-  esac-  test -d "$as_dir" || eval $as_mkdir_p || {-    as_dirs=-    while :; do-      case $as_dir in #(-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(-      *) as_qdir=$as_dir;;-      esac-      as_dirs="'$as_qdir' $as_dirs"-      as_dir=`$as_dirname -- "$as_dir" ||-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \-	 X"$as_dir" : 'X\(//\)[^/]' \| \-	 X"$as_dir" : 'X\(//\)$' \| \-	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||-$as_echo X"$as_dir" |-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{-	    s//\1/-	    q-	  }-	  /^X\(\/\/\)[^/].*/{-	    s//\1/-	    q-	  }-	  /^X\(\/\/\)$/{-	    s//\1/-	    q-	  }-	  /^X\(\/\).*/{-	    s//\1/-	    q-	  }-	  s/.*/./; q'`-      test -d "$as_dir" && break-    done-    test -z "$as_dirs" || eval "mkdir $as_dirs"-  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"---} # as_fn_mkdir_p-if mkdir -p . 2>/dev/null; then-  as_mkdir_p='mkdir -p "$as_dir"'-else-  test -d ./-p && rmdir ./-p-  as_mkdir_p=false-fi---# as_fn_executable_p FILE-# ------------------------# Test if FILE is an executable regular file.-as_fn_executable_p ()-{-  test -f "$1" && test -x "$1"-} # as_fn_executable_p-as_test_x='test -x'-as_executable_p=as_fn_executable_p--# Sed expression to map a string onto a valid CPP name.-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"--# Sed expression to map a string onto a valid variable name.-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"---exec 6>&1-## ----------------------------------- ##-## Main body of $CONFIG_STATUS script. ##-## ----------------------------------- ##-_ASEOF-test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1--cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1-# Save the log message, to keep $0 and so on meaningful, and to-# report actual input values of CONFIG_FILES etc. instead of their-# values after options handling.-ac_log="-This file was extended by Haskell base package $as_me 1.0, which was-generated by GNU Autoconf 2.69.  Invocation command line was--  CONFIG_FILES    = $CONFIG_FILES-  CONFIG_HEADERS  = $CONFIG_HEADERS-  CONFIG_LINKS    = $CONFIG_LINKS-  CONFIG_COMMANDS = $CONFIG_COMMANDS-  $ $0 $@--on `(hostname || uname -n) 2>/dev/null | sed 1q`-"--_ACEOF--case $ac_config_files in *"-"*) set x $ac_config_files; shift; ac_config_files=$*;;-esac--case $ac_config_headers in *"-"*) set x $ac_config_headers; shift; ac_config_headers=$*;;-esac---cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1-# Files that config.status was made for.-config_files="$ac_config_files"-config_headers="$ac_config_headers"--_ACEOF--cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1-ac_cs_usage="\-\`$as_me' instantiates files and other configuration actions-from templates according to the current configuration.  Unless the files-and actions are specified as TAGs, all are instantiated by default.--Usage: $0 [OPTION]... [TAG]...--  -h, --help       print this help, then exit-  -V, --version    print version number and configuration settings, then exit-      --config     print configuration, then exit-  -q, --quiet, --silent-                   do not print progress messages-  -d, --debug      don't remove temporary files-      --recheck    update $as_me by reconfiguring in the same conditions-      --file=FILE[:TEMPLATE]-                   instantiate the configuration file FILE-      --header=FILE[:TEMPLATE]-                   instantiate the configuration header FILE--Configuration files:-$config_files--Configuration headers:-$config_headers--Report bugs to <libraries@haskell.org>."--_ACEOF-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1-ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"-ac_cs_version="\\-Haskell base package config.status 1.0-configured by $0, generated by GNU Autoconf 2.69,-  with options \\"\$ac_cs_config\\"--Copyright (C) 2012 Free Software Foundation, Inc.-This config.status script is free software; the Free Software Foundation-gives unlimited permission to copy, distribute and modify it."--ac_pwd='$ac_pwd'-srcdir='$srcdir'-test -n "\$AWK" || AWK=awk-_ACEOF--cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1-# The default lists apply if the user does not specify any file.-ac_need_defaults=:-while test $# != 0-do-  case $1 in-  --*=?*)-    ac_option=`expr "X$1" : 'X\([^=]*\)='`-    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`-    ac_shift=:-    ;;-  --*=)-    ac_option=`expr "X$1" : 'X\([^=]*\)='`-    ac_optarg=-    ac_shift=:-    ;;-  *)-    ac_option=$1-    ac_optarg=$2-    ac_shift=shift-    ;;-  esac--  case $ac_option in-  # Handling of the options.-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)-    ac_cs_recheck=: ;;-  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )-    $as_echo "$ac_cs_version"; exit ;;-  --config | --confi | --conf | --con | --co | --c )-    $as_echo "$ac_cs_config"; exit ;;-  --debug | --debu | --deb | --de | --d | -d )-    debug=: ;;-  --file | --fil | --fi | --f )-    $ac_shift-    case $ac_optarg in-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;-    '') as_fn_error $? "missing file argument" ;;-    esac-    as_fn_append CONFIG_FILES " '$ac_optarg'"-    ac_need_defaults=false;;-  --header | --heade | --head | --hea )-    $ac_shift-    case $ac_optarg in-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;-    esac-    as_fn_append CONFIG_HEADERS " '$ac_optarg'"-    ac_need_defaults=false;;-  --he | --h)-    # Conflict between --help and --header-    as_fn_error $? "ambiguous option: \`$1'-Try \`$0 --help' for more information.";;-  --help | --hel | -h )-    $as_echo "$ac_cs_usage"; exit ;;-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \-  | -silent | --silent | --silen | --sile | --sil | --si | --s)-    ac_cs_silent=: ;;--  # This is an error.-  -*) as_fn_error $? "unrecognized option: \`$1'-Try \`$0 --help' for more information." ;;--  *) as_fn_append ac_config_targets " $1"-     ac_need_defaults=false ;;--  esac-  shift-done--ac_configure_extra_args=--if $ac_cs_silent; then-  exec 6>/dev/null-  ac_configure_extra_args="$ac_configure_extra_args --silent"-fi--_ACEOF-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1-if \$ac_cs_recheck; then-  set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion-  shift-  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6-  CONFIG_SHELL='$SHELL'-  export CONFIG_SHELL-  exec "\$@"-fi--_ACEOF-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1-exec 5>>config.log-{-  echo-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX-## Running $as_me. ##-_ASBOX-  $as_echo "$ac_log"-} >&5--_ACEOF-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1-_ACEOF--cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1--# Handling of arguments.-for ac_config_target in $ac_config_targets-do-  case $ac_config_target in-    "include/HsBaseConfig.h") CONFIG_HEADERS="$CONFIG_HEADERS include/HsBaseConfig.h" ;;-    "include/EventConfig.h") CONFIG_HEADERS="$CONFIG_HEADERS include/EventConfig.h" ;;-    "base.buildinfo") CONFIG_FILES="$CONFIG_FILES base.buildinfo" ;;--  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;-  esac-done---# If the user did not use the arguments to specify the items to instantiate,-# then the envvar interface is used.  Set only those that are not.-# We use the long form for the default assignment because of an extremely-# bizarre bug on SunOS 4.1.3.-if $ac_need_defaults; then-  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files-  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers-fi--# Have a temporary directory for convenience.  Make it in the build tree-# simply because there is no reason against having it here, and in addition,-# creating and moving files from /tmp can sometimes cause problems.-# Hook for its removal unless debugging.-# Note that there is a small window in which the directory will not be cleaned:-# after its creation but before its name has been assigned to `$tmp'.-$debug ||-{-  tmp= ac_tmp=-  trap 'exit_status=$?-  : "${ac_tmp:=$tmp}"-  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status-' 0-  trap 'as_fn_exit 1' 1 2 13 15-}-# Create a (secure) tmp directory for tmp files.--{-  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&-  test -d "$tmp"-}  ||-{-  tmp=./conf$$-$RANDOM-  (umask 077 && mkdir "$tmp")-} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5-ac_tmp=$tmp--# Set up the scripts for CONFIG_FILES section.-# No need to generate them if there are no CONFIG_FILES.-# This happens for instance with `./config.status config.h'.-if test -n "$CONFIG_FILES"; then---ac_cr=`echo X | tr X '\015'`-# On cygwin, bash can eat \r inside `` if the user requested igncr.-# But we know of no other shell where ac_cr would be empty at this-# point, so we can use a bashism as a fallback.-if test "x$ac_cr" = x; then-  eval ac_cr=\$\'\\r\'-fi-ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`-if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then-  ac_cs_awk_cr='\\r'-else-  ac_cs_awk_cr=$ac_cr-fi--echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&-_ACEOF---{-  echo "cat >conf$$subs.awk <<_ACEOF" &&-  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&-  echo "_ACEOF"-} >conf$$subs.sh ||-  as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5-ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`-ac_delim='%!_!# '-for ac_last_try in false false false false false :; do-  . ./conf$$subs.sh ||-    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5--  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`-  if test $ac_delim_n = $ac_delim_num; then-    break-  elif $ac_last_try; then-    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5-  else-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "-  fi-done-rm -f conf$$subs.sh--cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1-cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&-_ACEOF-sed -n '-h-s/^/S["/; s/!.*/"]=/-p-g-s/^[^!]*!//-:repl-t repl-s/'"$ac_delim"'$//-t delim-:nl-h-s/\(.\{148\}\)..*/\1/-t more1-s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/-p-n-b repl-:more1-s/["\\]/\\&/g; s/^/"/; s/$/"\\/-p-g-s/.\{148\}//-t nl-:delim-h-s/\(.\{148\}\)..*/\1/-t more2-s/["\\]/\\&/g; s/^/"/; s/$/"/-p-b-:more2-s/["\\]/\\&/g; s/^/"/; s/$/"\\/-p-g-s/.\{148\}//-t delim-' <conf$$subs.awk | sed '-/^[^""]/{-  N-  s/\n//-}-' >>$CONFIG_STATUS || ac_write_fail=1-rm -f conf$$subs.awk-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1-_ACAWK-cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&-  for (key in S) S_is_set[key] = 1-  FS = ""--}-{-  line = $ 0-  nfields = split(line, field, "@")-  substed = 0-  len = length(field[1])-  for (i = 2; i < nfields; i++) {-    key = field[i]-    keylen = length(key)-    if (S_is_set[key]) {-      value = S[key]-      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)-      len += length(value) + length(field[++i])-      substed = 1-    } else-      len += 1 + keylen-  }--  print line-}--_ACAWK-_ACEOF-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1-if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then-  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"-else-  cat-fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \-  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5-_ACEOF--# VPATH may cause trouble with some makes, so we remove sole $(srcdir),-# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and-# trailing colons and then remove the whole line if VPATH becomes empty-# (actually we leave an empty line to preserve line numbers).-if test "x$srcdir" = x.; then-  ac_vpsub='/^[	 ]*VPATH[	 ]*=[	 ]*/{-h-s///-s/^/:/-s/[	 ]*$/:/-s/:\$(srcdir):/:/g-s/:\${srcdir}:/:/g-s/:@srcdir@:/:/g-s/^:*//-s/:*$//-x-s/\(=[	 ]*\).*/\1/-G-s/\n//-s/^[^=]*=[	 ]*$//-}'-fi--cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1-fi # test -n "$CONFIG_FILES"--# Set up the scripts for CONFIG_HEADERS section.-# No need to generate them if there are no CONFIG_HEADERS.-# This happens for instance with `./config.status Makefile'.-if test -n "$CONFIG_HEADERS"; then-cat >"$ac_tmp/defines.awk" <<\_ACAWK ||-BEGIN {-_ACEOF--# Transform confdefs.h into an awk script `defines.awk', embedded as-# here-document in config.status, that substitutes the proper values into-# config.h.in to produce config.h.--# Create a delimiter string that does not exist in confdefs.h, to ease-# handling of long lines.-ac_delim='%!_!# '-for ac_last_try in false false :; do-  ac_tt=`sed -n "/$ac_delim/p" confdefs.h`-  if test -z "$ac_tt"; then-    break-  elif $ac_last_try; then-    as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5-  else-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "-  fi-done--# For the awk script, D is an array of macro values keyed by name,-# likewise P contains macro parameters if any.  Preserve backslash-# newline sequences.--ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*-sed -n '-s/.\{148\}/&'"$ac_delim"'/g-t rset-:rset-s/^[	 ]*#[	 ]*define[	 ][	 ]*/ /-t def-d-:def-s/\\$//-t bsnl-s/["\\]/\\&/g-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\-D["\1"]=" \3"/p-s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2"/p-d-:bsnl-s/["\\]/\\&/g-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\-D["\1"]=" \3\\\\\\n"\\/p-t cont-s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p-t cont-d-:cont-n-s/.\{148\}/&'"$ac_delim"'/g-t clear-:clear-s/\\$//-t bsnlc-s/["\\]/\\&/g; s/^/"/; s/$/"/p-d-:bsnlc-s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p-b cont-' <confdefs.h | sed '-s/'"$ac_delim"'/"\\\-"/g' >>$CONFIG_STATUS || ac_write_fail=1--cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1-  for (key in D) D_is_set[key] = 1-  FS = ""-}-/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ {-  line = \$ 0-  split(line, arg, " ")-  if (arg[1] == "#") {-    defundef = arg[2]-    mac1 = arg[3]-  } else {-    defundef = substr(arg[1], 2)-    mac1 = arg[2]-  }-  split(mac1, mac2, "(") #)-  macro = mac2[1]-  prefix = substr(line, 1, index(line, defundef) - 1)-  if (D_is_set[macro]) {-    # Preserve the white space surrounding the "#".-    print prefix "define", macro P[macro] D[macro]-    next-  } else {-    # Replace #undef with comments.  This is necessary, for example,-    # in the case of _POSIX_SOURCE, which is predefined and required-    # on some systems where configure will not decide to define it.-    if (defundef == "undef") {-      print "/*", prefix defundef, macro, "*/"-      next-    }-  }-}-{ print }-_ACAWK-_ACEOF-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1-  as_fn_error $? "could not setup config headers machinery" "$LINENO" 5-fi # test -n "$CONFIG_HEADERS"---eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    "-shift-for ac_tag-do-  case $ac_tag in-  :[FHLC]) ac_mode=$ac_tag; continue;;-  esac-  case $ac_mode$ac_tag in-  :[FHL]*:*);;-  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;-  :[FH]-) ac_tag=-:-;;-  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;-  esac-  ac_save_IFS=$IFS-  IFS=:-  set x $ac_tag-  IFS=$ac_save_IFS-  shift-  ac_file=$1-  shift--  case $ac_mode in-  :L) ac_source=$1;;-  :[FH])-    ac_file_inputs=-    for ac_f-    do-      case $ac_f in-      -) ac_f="$ac_tmp/stdin";;-      *) # Look for the file first in the build tree, then in the source tree-	 # (if the path is not absolute).  The absolute path cannot be DOS-style,-	 # because $ac_f cannot contain `:'.-	 test -f "$ac_f" ||-	   case $ac_f in-	   [\\/$]*) false;;-	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;-	   esac ||-	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;-      esac-      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac-      as_fn_append ac_file_inputs " '$ac_f'"-    done--    # Let's still pretend it is `configure' which instantiates (i.e., don't-    # use $as_me), people would be surprised to read:-    #    /* config.h.  Generated by config.status.  */-    configure_input='Generated from '`-	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'-	`' by configure.'-    if test x"$ac_file" != x-; then-      configure_input="$ac_file.  $configure_input"-      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5-$as_echo "$as_me: creating $ac_file" >&6;}-    fi-    # Neutralize special characters interpreted by sed in replacement strings.-    case $configure_input in #(-    *\&* | *\|* | *\\* )-       ac_sed_conf_input=`$as_echo "$configure_input" |-       sed 's/[\\\\&|]/\\\\&/g'`;; #(-    *) ac_sed_conf_input=$configure_input;;-    esac--    case $ac_tag in-    *:-:* | *:-) cat >"$ac_tmp/stdin" \-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;-    esac-    ;;-  esac--  ac_dir=`$as_dirname -- "$ac_file" ||-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \-	 X"$ac_file" : 'X\(//\)[^/]' \| \-	 X"$ac_file" : 'X\(//\)$' \| \-	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||-$as_echo X"$ac_file" |-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{-	    s//\1/-	    q-	  }-	  /^X\(\/\/\)[^/].*/{-	    s//\1/-	    q-	  }-	  /^X\(\/\/\)$/{-	    s//\1/-	    q-	  }-	  /^X\(\/\).*/{-	    s//\1/-	    q-	  }-	  s/.*/./; q'`-  as_dir="$ac_dir"; as_fn_mkdir_p-  ac_builddir=.--case "$ac_dir" in-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;-*)-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`-  # A ".." for each directory in $ac_dir_suffix.-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`-  case $ac_top_builddir_sub in-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;-  esac ;;-esac-ac_abs_top_builddir=$ac_pwd-ac_abs_builddir=$ac_pwd$ac_dir_suffix-# for backward compatibility:-ac_top_builddir=$ac_top_build_prefix--case $srcdir in-  .)  # We are building in place.-    ac_srcdir=.-    ac_top_srcdir=$ac_top_builddir_sub-    ac_abs_top_srcdir=$ac_pwd ;;-  [\\/]* | ?:[\\/]* )  # Absolute name.-    ac_srcdir=$srcdir$ac_dir_suffix;-    ac_top_srcdir=$srcdir-    ac_abs_top_srcdir=$srcdir ;;-  *) # Relative name.-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix-    ac_top_srcdir=$ac_top_build_prefix$srcdir-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;-esac-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix---  case $ac_mode in-  :F)-  #-  # CONFIG_FILE-  #--_ACEOF--cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1-# If the template does not know about datarootdir, expand it.-# FIXME: This hack should be removed a few years after 2.60.-ac_datarootdir_hack=; ac_datarootdir_seen=-ac_sed_dataroot='-/datarootdir/ {-  p-  q-}-/@datadir@/p-/@docdir@/p-/@infodir@/p-/@localedir@/p-/@mandir@/p'-case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in-*datarootdir*) ac_datarootdir_seen=yes;;-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5-$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}-_ACEOF-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1-  ac_datarootdir_hack='-  s&@datadir@&$datadir&g-  s&@docdir@&$docdir&g-  s&@infodir@&$infodir&g-  s&@localedir@&$localedir&g-  s&@mandir@&$mandir&g-  s&\\\${datarootdir}&$datarootdir&g' ;;-esac-_ACEOF--# Neutralize VPATH when `$srcdir' = `.'.-# Shell code in configure.ac might set extrasub.-# FIXME: do we really want to maintain this feature?-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1-ac_sed_extra="$ac_vpsub-$extrasub-_ACEOF-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1-:t-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b-s|@configure_input@|$ac_sed_conf_input|;t t-s&@top_builddir@&$ac_top_builddir_sub&;t t-s&@top_build_prefix@&$ac_top_build_prefix&;t t-s&@srcdir@&$ac_srcdir&;t t-s&@abs_srcdir@&$ac_abs_srcdir&;t t-s&@top_srcdir@&$ac_top_srcdir&;t t-s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t-s&@builddir@&$ac_builddir&;t t-s&@abs_builddir@&$ac_abs_builddir&;t t-s&@abs_top_builddir@&$ac_abs_top_builddir&;t t-$ac_datarootdir_hack-"-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \-  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5--test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&-  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&-  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \-      "$ac_tmp/out"`; test -z "$ac_out"; } &&-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'-which seems to be undefined.  Please make sure it is defined" >&5-$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'-which seems to be undefined.  Please make sure it is defined" >&2;}--  rm -f "$ac_tmp/stdin"-  case $ac_file in-  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;-  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;-  esac \-  || as_fn_error $? "could not create $ac_file" "$LINENO" 5- ;;-  :H)-  #-  # CONFIG_HEADER-  #-  if test x"$ac_file" != x-; then-    {-      $as_echo "/* $configure_input  */" \-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"-    } >"$ac_tmp/config.h" \-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5-    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then-      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5-$as_echo "$as_me: $ac_file is unchanged" >&6;}-    else-      rm -f "$ac_file"-      mv "$ac_tmp/config.h" "$ac_file" \-	|| as_fn_error $? "could not create $ac_file" "$LINENO" 5-    fi-  else-    $as_echo "/* $configure_input  */" \-      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \-      || as_fn_error $? "could not create -" "$LINENO" 5-  fi- ;;---  esac--done # for ac_tag---as_fn_exit 0-_ACEOF-ac_clean_files=$ac_clean_files_save--test $ac_write_fail = 0 ||-  as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5---# configure is writing to config.log, and then calls config.status.-# config.status does its own redirection, appending to config.log.-# Unfortunately, on DOS this fails, as config.log is still kept open-# by configure, so config.status won't be able to write to it; its-# output is simply discarded.  So we exec the FD to /dev/null,-# effectively closing config.log, so it can be properly (re)opened and-# appended to by config.status.  When coming back to configure, we-# need to make the FD available again.-if test "$no_create" != yes; then-  ac_cs_success=:-  ac_config_status_args=-  test "$silent" = yes &&-    ac_config_status_args="$ac_config_status_args --quiet"-  exec 5>/dev/null-  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false-  exec 5>>config.log-  # Use ||, not &&, to avoid exiting from the if with $? = 1, which-  # would make configure fail if this is the last instruction.-  $ac_cs_success || as_fn_exit 1-fi-if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5-$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}-fi-
− configure.ac
@@ -1,213 +0,0 @@-AC_INIT([Haskell base package], [1.0], [libraries@haskell.org], [base])--# Safety check: Ensure that we are in the correct source directory.-AC_CONFIG_SRCDIR([include/HsBase.h])--AC_CONFIG_HEADERS([include/HsBaseConfig.h include/EventConfig.h])--AC_CANONICAL_BUILD-AC_CANONICAL_HOST-AC_CANONICAL_TARGET--AC_ARG_WITH([cc],-            [C compiler],-            [CC=$withval])-AC_PROG_CC()--AC_MSG_CHECKING(for WINDOWS platform)-case $host in-    *mingw32*|*mingw64*|*cygwin*|*msys*)-        WINDOWS=YES;;-    *)-        WINDOWS=NO;;-esac-AC_MSG_RESULT($WINDOWS)--# do we have long longs?-AC_CHECK_TYPES([long long])--dnl ** check for full ANSI header (.h) files-AC_HEADER_STDC--# check for specific header (.h) files that we are interested in-AC_CHECK_HEADERS([ctype.h errno.h fcntl.h inttypes.h limits.h signal.h sys/resource.h sys/select.h sys/stat.h sys/syscall.h sys/time.h sys/timeb.h sys/timers.h sys/times.h sys/types.h sys/utsname.h sys/wait.h termios.h time.h unistd.h utime.h windows.h winsock.h langinfo.h poll.h sys/epoll.h sys/event.h sys/eventfd.h])--# Enable large file support. Do this before testing the types ino_t, off_t, and-# rlim_t, because it will affect the result of that test.-AC_SYS_LARGEFILE--dnl ** check for wide-char classifications-dnl FreeBSD has an emtpy wctype.h, so test one of the affected-dnl functions if it's really there.-AC_CHECK_HEADERS([wctype.h], [AC_CHECK_FUNCS(iswspace)])--AC_CHECK_FUNCS([lstat])-AC_CHECK_LIB([rt], [clock_gettime])-AC_CHECK_FUNCS([clock_gettime])-AC_CHECK_FUNCS([getclock getrusage times])-AC_CHECK_FUNCS([_chsize ftruncate])--AC_CHECK_FUNCS([epoll_ctl eventfd kevent kevent64 kqueue poll])--# event-related fun--if test "$ac_cv_header_sys_epoll_h" = yes -a "$ac_cv_func_epoll_ctl" = yes; then-  AC_DEFINE([HAVE_EPOLL], [1], [Define if you have epoll support.])-fi--if test "$ac_cv_header_sys_event_h" = yes -a "$ac_cv_func_kqueue" = yes; then-  AC_DEFINE([HAVE_KQUEUE], [1], [Define if you have kqueue support.])--  AC_CHECK_SIZEOF([kev.filter], [], [#include <sys/event.h>-struct kevent kev;])--  AC_CHECK_SIZEOF([kev.flags], [], [#include <sys/event.h>-struct kevent kev;])-fi--if test "$ac_cv_header_poll_h" = yes -a "$ac_cv_func_poll" = yes; then-  AC_DEFINE([HAVE_POLL], [1], [Define if you have poll support.])-fi--# unsetenv-AC_CHECK_FUNCS([unsetenv])--###  POSIX.1003.1 unsetenv returns 0 or -1 (EINVAL), but older implementations-###  in common use return void.-AC_CACHE_CHECK([return type of unsetenv], fptools_cv_func_unsetenv_return_type,-  [AC_EGREP_HEADER(changequote(<, >)<void[      ]+unsetenv>changequote([, ]),-                   stdlib.h,-                   [fptools_cv_func_unsetenv_return_type=void],-                   [fptools_cv_func_unsetenv_return_type=int])])-case "$fptools_cv_func_unsetenv_return_type" in-  "void" )-    AC_DEFINE([UNSETENV_RETURNS_VOID], [1], [Define if stdlib.h declares unsetenv to return void.])-  ;;-esac--dnl---------------------------------------------------------------------dnl * Deal with arguments telling us iconv is somewhere odd-dnl----------------------------------------------------------------------AC_ARG_WITH([iconv-includes],-  [AC_HELP_STRING([--with-iconv-includes],-    [directory containing iconv.h])],-    [ICONV_INCLUDE_DIRS=$withval; CPPFLAGS="-I$withval"],-    [ICONV_INCLUDE_DIRS=])--AC_ARG_WITH([iconv-libraries],-  [AC_HELP_STRING([--with-iconv-libraries],-    [directory containing iconv library])],-    [ICONV_LIB_DIRS=$withval; LDFLAGS="-L$withval"],-    [ICONV_LIB_DIRS=])--AC_SUBST(ICONV_INCLUDE_DIRS)-AC_SUBST(ICONV_LIB_DIRS)--# map standard C types and ISO types to Haskell types-FPTOOLS_CHECK_HTYPE(char)-FPTOOLS_CHECK_HTYPE(signed char)-FPTOOLS_CHECK_HTYPE(unsigned char)-FPTOOLS_CHECK_HTYPE(short)-FPTOOLS_CHECK_HTYPE(unsigned short)-FPTOOLS_CHECK_HTYPE(int)-FPTOOLS_CHECK_HTYPE(unsigned int)-FPTOOLS_CHECK_HTYPE(long)-FPTOOLS_CHECK_HTYPE(unsigned long)-if test "$ac_cv_type_long_long" = yes; then-FPTOOLS_CHECK_HTYPE(long long)-FPTOOLS_CHECK_HTYPE(unsigned long long)-fi-FPTOOLS_CHECK_HTYPE(float)-FPTOOLS_CHECK_HTYPE(double)-FPTOOLS_CHECK_HTYPE(ptrdiff_t)-FPTOOLS_CHECK_HTYPE(size_t)-FPTOOLS_CHECK_HTYPE(wchar_t)-FPTOOLS_CHECK_HTYPE(sig_atomic_t)-FPTOOLS_CHECK_HTYPE(clock_t)-FPTOOLS_CHECK_HTYPE(time_t)-FPTOOLS_CHECK_HTYPE(useconds_t)-FPTOOLS_CHECK_HTYPE_ELSE(suseconds_t,-                         [if test "$WINDOWS" = "YES"-                          then-                              AC_CV_NAME=Int32-                              AC_CV_NAME_supported=yes-                          else-                              AC_MSG_ERROR([type not found])-                          fi])-FPTOOLS_CHECK_HTYPE(dev_t)-FPTOOLS_CHECK_HTYPE(ino_t)-FPTOOLS_CHECK_HTYPE(mode_t)-FPTOOLS_CHECK_HTYPE(off_t)-FPTOOLS_CHECK_HTYPE(pid_t)-FPTOOLS_CHECK_HTYPE(gid_t)-FPTOOLS_CHECK_HTYPE(uid_t)-FPTOOLS_CHECK_HTYPE(cc_t)-FPTOOLS_CHECK_HTYPE(speed_t)-FPTOOLS_CHECK_HTYPE(tcflag_t)-FPTOOLS_CHECK_HTYPE(nlink_t)-FPTOOLS_CHECK_HTYPE(ssize_t)-FPTOOLS_CHECK_HTYPE(rlim_t)--FPTOOLS_CHECK_HTYPE(intptr_t)-FPTOOLS_CHECK_HTYPE(uintptr_t)-FPTOOLS_CHECK_HTYPE(intmax_t)-FPTOOLS_CHECK_HTYPE(uintmax_t)--# test errno values-FP_CHECK_CONSTS([E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EADV EAFNOSUPPORT EAGAIN EALREADY EBADF EBADMSG EBADRPC EBUSY ECHILD ECOMM ECONNABORTED ECONNREFUSED ECONNRESET EDEADLK EDESTADDRREQ EDIRTY EDOM EDQUOT EEXIST EFAULT EFBIG EFTYPE EHOSTDOWN EHOSTUNREACH EIDRM EILSEQ EINPROGRESS EINTR EINVAL EIO EISCONN EISDIR ELOOP EMFILE EMLINK EMSGSIZE EMULTIHOP ENAMETOOLONG ENETDOWN ENETRESET ENETUNREACH ENFILE ENOBUFS ENODATA ENODEV ENOENT ENOEXEC ENOLCK ENOLINK ENOMEM ENOMSG ENONET ENOPROTOOPT ENOSPC ENOSR ENOSTR ENOSYS ENOTBLK ENOTCONN ENOTDIR ENOTEMPTY ENOTSOCK ENOTTY ENXIO EOPNOTSUPP EPERM EPFNOSUPPORT EPIPE EPROCLIM EPROCUNAVAIL EPROGMISMATCH EPROGUNAVAIL EPROTO EPROTONOSUPPORT EPROTOTYPE ERANGE EREMCHG EREMOTE EROFS ERPCMISMATCH ERREMOTE ESHUTDOWN ESOCKTNOSUPPORT ESPIPE ESRCH ESRMNT ESTALE ETIME ETIMEDOUT ETOOMANYREFS ETXTBSY EUSERS EWOULDBLOCK EXDEV ENOCIGAR ENOTSUP], [#include <stdio.h>-#include <errno.h>])--# we need SIGINT in TopHandler.lhs-FP_CHECK_CONSTS([SIGINT], [-#if HAVE_SIGNAL_H-#include <signal.h>-#endif])--dnl ** can we open files in binary mode?-FP_CHECK_CONST([O_BINARY], [#include <fcntl.h>], [0])--# We don't use iconv or libcharset on Windows, but if configure finds-# them then it can cause problems. So we don't even try looking if-# we are on Windows.-# See http://www.haskell.org/pipermail/cvs-ghc/2011-September/065980.html-if test "$WINDOWS" = "NO"-then--# We can't just use AC_SEARCH_LIBS for this, as on OpenBSD the iconv.h-# header needs to be included as iconv_open is #define'd to something-# else. We therefore use our own FP_SEARCH_LIBS_PROTO, which allows us-# to give prototype text.-FP_SEARCH_LIBS_PROTO(iconv,-                     [-#include <stddef.h>-#include <iconv.h>-                      ],-                     [iconv_t cd;-                      cd = iconv_open("", "");-                      iconv(cd,NULL,NULL,NULL,NULL);-                      iconv_close(cd);],-                     iconv,-                     [EXTRA_LIBS="$EXTRA_LIBS $ac_lib"],-                     [AC_MSG_ERROR([iconv is required on non-Windows platforms])])--# If possible, we use libcharset instead of nl_langinfo(CODESET) to-# determine the current locale's character encoding.-FP_SEARCH_LIBS_PROTO(-    [locale_charset],-    [#include <libcharset.h>],-    [const char* charset = locale_charset();],-    [charset],-    [AC_DEFINE([HAVE_LIBCHARSET], [1], [Define to 1 if you have libcharset.])-     EXTRA_LIBS="$EXTRA_LIBS $ac_lib"])--fi--# Hack - md5.h needs HsFFI.h.  Is there a better way to do this?-CFLAGS="-I../../includes $CFLAGS"-AC_CHECK_SIZEOF([struct MD5Context], ,[#include "include/md5.h"])--AC_SUBST(EXTRA_LIBS)-AC_CONFIG_FILES([base.buildinfo])--AC_OUTPUT
− include/CTypes.h
@@ -1,54 +0,0 @@-{- ---------------------------------------------------------------------------// Dirty CPP hackery for CTypes/CTypesISO-//-// (c) The FFI task force, 2000-// ----------------------------------------------------------------------------}--#ifndef CTYPES__H-#define CTYPES__H--{--// As long as there is no automatic derivation of classes for newtypes we resort-// to extremely dirty cpp-hackery.   :-P   Some care has to be taken when the-// macros below are modified, otherwise the layout rule will bite you.--}----  // GHC can derive any class for a newtype, so we make use of that here...--#define ARITHMETIC_CLASSES  Eq,Ord,Num,Enum,Storable,Real,Typeable-#define INTEGRAL_CLASSES Bounded,Integral,Bits,FiniteBits-#define FLOATING_CLASSES Fractional,Floating,RealFrac,RealFloat--#define ARITHMETIC_TYPE(T,B) \-newtype T = T B deriving (ARITHMETIC_CLASSES); \-INSTANCE_READ(T,B); \-INSTANCE_SHOW(T,B);--#define INTEGRAL_TYPE(T,B) \-newtype T = T B deriving (ARITHMETIC_CLASSES, INTEGRAL_CLASSES); \-INSTANCE_READ(T,B); \-INSTANCE_SHOW(T,B);--#define INTEGRAL_TYPE_WITH_CTYPE(T,THE_CTYPE,B) \-newtype {-# CTYPE "THE_CTYPE" #-} T = T B deriving (ARITHMETIC_CLASSES, INTEGRAL_CLASSES); \-INSTANCE_READ(T,B); \-INSTANCE_SHOW(T,B);--#define FLOATING_TYPE(T,B) \-newtype T = T B deriving (ARITHMETIC_CLASSES, FLOATING_CLASSES); \-INSTANCE_READ(T,B); \-INSTANCE_SHOW(T,B);--#define INSTANCE_READ(T,B) \-instance Read T where { \-   readsPrec            = unsafeCoerce# (readsPrec :: Int -> ReadS B); \-   readList             = unsafeCoerce# (readList  :: ReadS [B]); }--#define INSTANCE_SHOW(T,B) \-instance Show T where { \-   showsPrec            = unsafeCoerce# (showsPrec :: Int -> B -> ShowS); \-   show                 = unsafeCoerce# (show :: B -> String); \-   showList             = unsafeCoerce# (showList :: [B] -> ShowS); }--#endif
− include/EventConfig.h.in
@@ -1,91 +0,0 @@-/* include/EventConfig.h.in.  Generated from configure.ac by autoheader.  */--/* Define if you have epoll support. */-#undef HAVE_EPOLL--/* Define to 1 if you have the `epoll_create1' function. */-#undef HAVE_EPOLL_CREATE1--/* Define to 1 if you have the `epoll_ctl' function. */-#undef HAVE_EPOLL_CTL--/* Define to 1 if you have the `eventfd' function. */-#undef HAVE_EVENTFD--/* Define to 1 if you have the <inttypes.h> header file. */-#undef HAVE_INTTYPES_H--/* Define to 1 if you have the `kevent' function. */-#undef HAVE_KEVENT--/* Define to 1 if you have the `kevent64' function. */-#undef HAVE_KEVENT64--/* Define if you have kqueue support. */-#undef HAVE_KQUEUE--/* Define to 1 if you have the <memory.h> header file. */-#undef HAVE_MEMORY_H--/* Define if you have poll support. */-#undef HAVE_POLL--/* Define to 1 if you have the <poll.h> header file. */-#undef HAVE_POLL_H--/* Define to 1 if you have the <signal.h> header file. */-#undef HAVE_SIGNAL_H--/* Define to 1 if you have the <stdint.h> header file. */-#undef HAVE_STDINT_H--/* Define to 1 if you have the <stdlib.h> header file. */-#undef HAVE_STDLIB_H--/* Define to 1 if you have the <strings.h> header file. */-#undef HAVE_STRINGS_H--/* Define to 1 if you have the <string.h> header file. */-#undef HAVE_STRING_H--/* Define to 1 if you have the <sys/epoll.h> header file. */-#undef HAVE_SYS_EPOLL_H--/* Define to 1 if you have the <sys/eventfd.h> header file. */-#undef HAVE_SYS_EVENTFD_H--/* Define to 1 if you have the <sys/event.h> header file. */-#undef HAVE_SYS_EVENT_H--/* Define to 1 if you have the <sys/stat.h> header file. */-#undef HAVE_SYS_STAT_H--/* Define to 1 if you have the <sys/types.h> header file. */-#undef HAVE_SYS_TYPES_H--/* Define to 1 if you have the <unistd.h> header file. */-#undef HAVE_UNISTD_H--/* Define to the address where bug reports for this package should be sent. */-#undef PACKAGE_BUGREPORT--/* Define to the full name of this package. */-#undef PACKAGE_NAME--/* Define to the full name and version of this package. */-#undef PACKAGE_STRING--/* Define to the one symbol short name of this package. */-#undef PACKAGE_TARNAME--/* Define to the version of this package. */-#undef PACKAGE_VERSION--/* Define to 1 if you have the ANSI C header files. */-#undef STDC_HEADERS--/* The size of `kev.filter', as computed by sizeof. */-#undef SIZEOF_KEV_FILTER--/* The size of `kev.flags', as computed by sizeof. */-#undef SIZEOF_KEV_FLAGS
− include/HsBase.h
@@ -1,559 +0,0 @@-/* ------------------------------------------------------------------------------ *- * (c) The University of Glasgow 2001-2004- *- * Definitions for package `base' which are visible in Haskell land.- *- * ---------------------------------------------------------------------------*/--#ifndef __HSBASE_H__-#define __HSBASE_H__--#include "HsBaseConfig.h"--/* ultra-evil... */-#undef PACKAGE_BUGREPORT-#undef PACKAGE_NAME-#undef PACKAGE_STRING-#undef PACKAGE_TARNAME-#undef PACKAGE_VERSION--/* Needed to get the macro version of errno on some OSs (eg. Solaris).-   We must do this, because these libs are only compiled once, but-   must work in both single-threaded and multi-threaded programs. */-#define _REENTRANT 1--#include "HsFFI.h"--#include <stdio.h>-#include <stdlib.h>-#include <math.h>--#if HAVE_SYS_TYPES_H-#include <sys/types.h>-#endif-#if HAVE_UNISTD_H-#include <unistd.h>-#endif-#if HAVE_SYS_STAT_H-#include <sys/stat.h>-#endif-#if HAVE_FCNTL_H-# include <fcntl.h>-#endif-#if HAVE_TERMIOS_H-#include <termios.h>-#endif-#if HAVE_SIGNAL_H-#include <signal.h>-/* Ultra-ugly: OpenBSD uses broken macros for sigemptyset and sigfillset (missing casts) */-#if __OpenBSD__-#undef sigemptyset-#undef sigfillset-#endif-#endif-#if HAVE_ERRNO_H-#include <errno.h>-#endif-#if HAVE_STRING_H-#include <string.h>-#endif-#if HAVE_UTIME_H-#include <utime.h>-#endif-#if HAVE_SYS_UTSNAME_H-#include <sys/utsname.h>-#endif-#if HAVE_GETTIMEOFDAY-#  if HAVE_SYS_TIME_H-#   include <sys/time.h>-#  endif-#elif HAVE_GETCLOCK-# if HAVE_SYS_TIMERS_H-#  define POSIX_4D9 1-#  include <sys/timers.h>-# endif-#endif-#if HAVE_TIME_H-#include <time.h>-#endif-#if HAVE_SYS_TIMEB_H && !defined(__FreeBSD__)-#include <sys/timeb.h>-#endif-#if HAVE_WINDOWS_H-#include <windows.h>-#endif-#if HAVE_SYS_TIMES_H-#include <sys/times.h>-#endif-#if HAVE_WINSOCK_H && defined(__MINGW32__)-#include <winsock.h>-#endif-#if HAVE_LIMITS_H-#include <limits.h>-#endif-#if HAVE_WCTYPE_H-#include <wctype.h>-#endif-#if HAVE_INTTYPES_H-# include <inttypes.h>-#elif HAVE_STDINT_H-# include <stdint.h>-#endif-#if HAVE_CLOCK_GETTIME-# ifdef _POSIX_MONOTONIC_CLOCK-#  define CLOCK_ID CLOCK_MONOTONIC-# else-#  define CLOCK_ID CLOCK_REALTIME-# endif-#elif defined(darwin_HOST_OS)-# include <mach/mach.h>-# include <mach/mach_time.h>-#endif--#if !defined(__MINGW32__) && !defined(irix_HOST_OS)-# if HAVE_SYS_RESOURCE_H-#  include <sys/resource.h>-# endif-#endif--#if !HAVE_GETRUSAGE && HAVE_SYS_SYSCALL_H-# include <sys/syscall.h>-# if defined(SYS_GETRUSAGE)	/* hpux_HOST_OS */-#  define getrusage(a, b)  syscall(SYS_GETRUSAGE, a, b)-#  define HAVE_GETRUSAGE 1-# endif-#endif--/* For System */-#if HAVE_SYS_WAIT_H-#include <sys/wait.h>-#endif-#if HAVE_VFORK_H-#include <vfork.h>-#endif-#include "WCsubst.h"--#if defined(__MINGW32__)-/* in Win32Utils.c */-extern void maperrno (void);-extern int maperrno_func(DWORD dwErrorCode);-extern HsWord64 getMonotonicUSec(void);-#endif--#if defined(__MINGW32__)-#include <io.h>-#include <fcntl.h>-#include <shlobj.h>-#include <share.h>-#endif--#if HAVE_SYS_SELECT_H-#include <sys/select.h>-#endif--/* in inputReady.c */-extern int fdReady(int fd, int write, int msecs, int isSock);--/* ------------------------------------------------------------------------------   INLINE functions.--   These functions are given as inlines here for when compiling via C,-   but we also generate static versions into the cbits library for-   when compiling to native code.-   -------------------------------------------------------------------------- */--#ifndef INLINE-# if defined(_MSC_VER)-#  define INLINE extern __inline-# else-#  define INLINE static inline-# endif-#endif--INLINE int __hscore_get_errno(void) { return errno; }-INLINE void __hscore_set_errno(int e) { errno = e; }--INLINE HsInt-__hscore_bufsiz(void)-{-  return BUFSIZ;-}--INLINE int-__hscore_o_binary(void)-{-#if defined(_MSC_VER)-  return O_BINARY;-#else-  return CONST_O_BINARY;-#endif-}--INLINE int-__hscore_o_rdonly(void)-{-#ifdef O_RDONLY-  return O_RDONLY;-#else-  return 0;-#endif-}--INLINE int-__hscore_o_wronly( void )-{-#ifdef O_WRONLY-  return O_WRONLY;-#else-  return 0;-#endif-}--INLINE int-__hscore_o_rdwr( void )-{-#ifdef O_RDWR-  return O_RDWR;-#else-  return 0;-#endif-}--INLINE int-__hscore_o_append( void )-{-#ifdef O_APPEND-  return O_APPEND;-#else-  return 0;-#endif-}--INLINE int-__hscore_o_creat( void )-{-#ifdef O_CREAT-  return O_CREAT;-#else-  return 0;-#endif-}--INLINE int-__hscore_o_excl( void )-{-#ifdef O_EXCL-  return O_EXCL;-#else-  return 0;-#endif-}--INLINE int-__hscore_o_trunc( void )-{-#ifdef O_TRUNC-  return O_TRUNC;-#else-  return 0;-#endif-}--INLINE int-__hscore_o_noctty( void )-{-#ifdef O_NOCTTY-  return O_NOCTTY;-#else-  return 0;-#endif-}--INLINE int-__hscore_o_nonblock( void )-{-#ifdef O_NONBLOCK-  return O_NONBLOCK;-#else-  return 0;-#endif-}--INLINE int-__hscore_ftruncate( int fd, off_t where )-{-#if defined(HAVE_FTRUNCATE)-  return ftruncate(fd,where);-#elif defined(HAVE__CHSIZE)-  return _chsize(fd,where);-#else-// ToDo: we should use _chsize_s() on Windows which allows a 64-bit-// offset, but it doesn't seem to be available from mingw at this time -// --SDM (01/2008)-#error at least ftruncate or _chsize functions are required to build-#endif-}--INLINE int-__hscore_setmode( int fd, HsBool toBin )-{-#if defined(_MSC_VER) || defined(__MINGW32__) || defined(_WIN32)-  return setmode(fd,(toBin == HS_BOOL_TRUE) ? _O_BINARY : _O_TEXT);-#else-  return 0;-#endif-}--#if defined(__MINGW32__)-// We want the versions of stat/fstat/lseek that use 64-bit offsets,-// and you have to ask for those explicitly.  Unfortunately there-// doesn't seem to be a 64-bit version of truncate/ftruncate, so while-// hFileSize and hSeek will work with large files, hSetFileSize will not.-typedef struct _stati64 struct_stat;-typedef off64_t stsize_t;-#else-typedef struct stat struct_stat;-typedef off_t stsize_t;-#endif--INLINE HsInt-__hscore_sizeof_stat( void )-{-  return sizeof(struct_stat);-}--INLINE time_t __hscore_st_mtime ( struct_stat* st ) { return st->st_mtime; }-INLINE stsize_t __hscore_st_size  ( struct_stat* st ) { return st->st_size; }-#if !defined(_MSC_VER)-INLINE mode_t __hscore_st_mode  ( struct_stat* st ) { return st->st_mode; }-INLINE dev_t  __hscore_st_dev  ( struct_stat* st ) { return st->st_dev; }-INLINE ino_t  __hscore_st_ino  ( struct_stat* st ) { return st->st_ino; }-#endif--#if defined(__MINGW32__)-INLINE int __hscore_stat(wchar_t *file, struct_stat *buf) {-	return _wstati64(file,buf);-}--INLINE int __hscore_fstat(int fd, struct_stat *buf) {-	return _fstati64(fd,buf);-}-INLINE int __hscore_lstat(wchar_t *fname, struct_stat *buf )-{-	return _wstati64(fname,buf);-}-#else-INLINE int __hscore_stat(char *file, struct_stat *buf) {-	return stat(file,buf);-}--INLINE int __hscore_fstat(int fd, struct_stat *buf) {-	return fstat(fd,buf);-}--INLINE int __hscore_lstat( const char *fname, struct stat *buf )-{-#if HAVE_LSTAT-  return lstat(fname, buf);-#else-  return stat(fname, buf);-#endif-}-#endif--#if HAVE_TERMIOS_H-INLINE tcflag_t __hscore_lflag( struct termios* ts ) { return ts->c_lflag; }--INLINE void-__hscore_poke_lflag( struct termios* ts, tcflag_t t ) { ts->c_lflag = t; }--INLINE unsigned char*-__hscore_ptr_c_cc( struct termios* ts )-{ return (unsigned char*) &ts->c_cc; }--INLINE HsInt-__hscore_sizeof_termios( void )-{-#ifndef __MINGW32__-  return sizeof(struct termios);-#else-  return 0;-#endif-}-#endif--#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(_WIN32)-INLINE HsInt-__hscore_sizeof_sigset_t( void )-{-  return sizeof(sigset_t);-}-#endif--INLINE int-__hscore_echo( void )-{-#ifdef ECHO-  return ECHO;-#else-  return 0;-#endif--}--INLINE int-__hscore_tcsanow( void )-{-#ifdef TCSANOW-  return TCSANOW;-#else-  return 0;-#endif--}--INLINE int-__hscore_icanon( void )-{-#ifdef ICANON-  return ICANON;-#else-  return 0;-#endif-}--INLINE int __hscore_vmin( void )-{-#ifdef VMIN-  return VMIN;-#else-  return 0;-#endif-}--INLINE int __hscore_vtime( void )-{-#ifdef VTIME-  return VTIME;-#else-  return 0;-#endif-}--INLINE int __hscore_sigttou( void )-{-#ifdef SIGTTOU-  return SIGTTOU;-#else-  return 0;-#endif-}--INLINE int __hscore_sig_block( void )-{-#ifdef SIG_BLOCK-  return SIG_BLOCK;-#else-  return 0;-#endif-}--INLINE int __hscore_sig_setmask( void )-{-#ifdef SIG_SETMASK-  return SIG_SETMASK;-#else-  return 0;-#endif-}--#ifndef __MINGW32__-INLINE size_t __hscore_sizeof_siginfo_t (void)-{-    return sizeof(siginfo_t);-}-#endif--INLINE int-__hscore_f_getfl( void )-{-#ifdef F_GETFL-  return F_GETFL;-#else-  return 0;-#endif-}--INLINE int-__hscore_f_setfl( void )-{-#ifdef F_SETFL-  return F_SETFL;-#else-  return 0;-#endif-}--INLINE int-__hscore_f_setfd( void )-{-#ifdef F_SETFD-  return F_SETFD;-#else-  return 0;-#endif-}--INLINE long-__hscore_fd_cloexec( void )-{-#ifdef FD_CLOEXEC-  return FD_CLOEXEC;-#else-  return 0;-#endif-}--// defined in rts/RtsStartup.c.-extern void* __hscore_get_saved_termios(int fd);-extern void __hscore_set_saved_termios(int fd, void* ts);--#ifdef __MINGW32__-INLINE int __hscore_open(wchar_t *file, int how, mode_t mode) {-	if ((how & O_WRONLY) || (how & O_RDWR) || (how & O_APPEND))-	  return _wsopen(file,how | _O_NOINHERIT,_SH_DENYNO,mode);-          // _O_NOINHERIT: see #2650-	else-	  return _wsopen(file,how | _O_NOINHERIT,_SH_DENYNO,mode);-          // _O_NOINHERIT: see #2650-}-#else-INLINE int __hscore_open(char *file, int how, mode_t mode) {-	return open(file,how,mode);-}-#endif--#if darwin_HOST_OS-// You should not access _environ directly on Darwin in a bundle/shared library.-// See #2458 and http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man7/environ.7.html-#include <crt_externs.h>-INLINE char **__hscore_environ(void) { return *(_NSGetEnviron()); }-#else-/* ToDo: write a feature test that doesn't assume 'environ' to- *    be in scope at link-time. */-extern char** environ;-INLINE char **__hscore_environ(void) { return environ; }-#endif--/* lossless conversions between pointers and integral types */-INLINE void *    __hscore_from_uintptr(uintptr_t n) { return (void *)n; }-INLINE void *    __hscore_from_intptr (intptr_t n)  { return (void *)n; }-INLINE uintptr_t __hscore_to_uintptr  (void *p)     { return (uintptr_t)p; }-INLINE intptr_t  __hscore_to_intptr   (void *p)     { return (intptr_t)p; }--void errorBelch2(const char*s, char *t);-void debugBelch2(const char*s, char *t);--#endif /* __HSBASE_H__ */-
− include/HsBaseConfig.h.in
@@ -1,624 +0,0 @@-/* include/HsBaseConfig.h.in.  Generated from configure.ac by autoheader.  */--/* The value of E2BIG. */-#undef CONST_E2BIG--/* The value of EACCES. */-#undef CONST_EACCES--/* The value of EADDRINUSE. */-#undef CONST_EADDRINUSE--/* The value of EADDRNOTAVAIL. */-#undef CONST_EADDRNOTAVAIL--/* The value of EADV. */-#undef CONST_EADV--/* The value of EAFNOSUPPORT. */-#undef CONST_EAFNOSUPPORT--/* The value of EAGAIN. */-#undef CONST_EAGAIN--/* The value of EALREADY. */-#undef CONST_EALREADY--/* The value of EBADF. */-#undef CONST_EBADF--/* The value of EBADMSG. */-#undef CONST_EBADMSG--/* The value of EBADRPC. */-#undef CONST_EBADRPC--/* The value of EBUSY. */-#undef CONST_EBUSY--/* The value of ECHILD. */-#undef CONST_ECHILD--/* The value of ECOMM. */-#undef CONST_ECOMM--/* The value of ECONNABORTED. */-#undef CONST_ECONNABORTED--/* The value of ECONNREFUSED. */-#undef CONST_ECONNREFUSED--/* The value of ECONNRESET. */-#undef CONST_ECONNRESET--/* The value of EDEADLK. */-#undef CONST_EDEADLK--/* The value of EDESTADDRREQ. */-#undef CONST_EDESTADDRREQ--/* The value of EDIRTY. */-#undef CONST_EDIRTY--/* The value of EDOM. */-#undef CONST_EDOM--/* The value of EDQUOT. */-#undef CONST_EDQUOT--/* The value of EEXIST. */-#undef CONST_EEXIST--/* The value of EFAULT. */-#undef CONST_EFAULT--/* The value of EFBIG. */-#undef CONST_EFBIG--/* The value of EFTYPE. */-#undef CONST_EFTYPE--/* The value of EHOSTDOWN. */-#undef CONST_EHOSTDOWN--/* The value of EHOSTUNREACH. */-#undef CONST_EHOSTUNREACH--/* The value of EIDRM. */-#undef CONST_EIDRM--/* The value of EILSEQ. */-#undef CONST_EILSEQ--/* The value of EINPROGRESS. */-#undef CONST_EINPROGRESS--/* The value of EINTR. */-#undef CONST_EINTR--/* The value of EINVAL. */-#undef CONST_EINVAL--/* The value of EIO. */-#undef CONST_EIO--/* The value of EISCONN. */-#undef CONST_EISCONN--/* The value of EISDIR. */-#undef CONST_EISDIR--/* The value of ELOOP. */-#undef CONST_ELOOP--/* The value of EMFILE. */-#undef CONST_EMFILE--/* The value of EMLINK. */-#undef CONST_EMLINK--/* The value of EMSGSIZE. */-#undef CONST_EMSGSIZE--/* The value of EMULTIHOP. */-#undef CONST_EMULTIHOP--/* The value of ENAMETOOLONG. */-#undef CONST_ENAMETOOLONG--/* The value of ENETDOWN. */-#undef CONST_ENETDOWN--/* The value of ENETRESET. */-#undef CONST_ENETRESET--/* The value of ENETUNREACH. */-#undef CONST_ENETUNREACH--/* The value of ENFILE. */-#undef CONST_ENFILE--/* The value of ENOBUFS. */-#undef CONST_ENOBUFS--/* The value of ENOCIGAR. */-#undef CONST_ENOCIGAR--/* The value of ENODATA. */-#undef CONST_ENODATA--/* The value of ENODEV. */-#undef CONST_ENODEV--/* The value of ENOENT. */-#undef CONST_ENOENT--/* The value of ENOEXEC. */-#undef CONST_ENOEXEC--/* The value of ENOLCK. */-#undef CONST_ENOLCK--/* The value of ENOLINK. */-#undef CONST_ENOLINK--/* The value of ENOMEM. */-#undef CONST_ENOMEM--/* The value of ENOMSG. */-#undef CONST_ENOMSG--/* The value of ENONET. */-#undef CONST_ENONET--/* The value of ENOPROTOOPT. */-#undef CONST_ENOPROTOOPT--/* The value of ENOSPC. */-#undef CONST_ENOSPC--/* The value of ENOSR. */-#undef CONST_ENOSR--/* The value of ENOSTR. */-#undef CONST_ENOSTR--/* The value of ENOSYS. */-#undef CONST_ENOSYS--/* The value of ENOTBLK. */-#undef CONST_ENOTBLK--/* The value of ENOTCONN. */-#undef CONST_ENOTCONN--/* The value of ENOTDIR. */-#undef CONST_ENOTDIR--/* The value of ENOTEMPTY. */-#undef CONST_ENOTEMPTY--/* The value of ENOTSOCK. */-#undef CONST_ENOTSOCK--/* The value of ENOTSUP. */-#undef CONST_ENOTSUP--/* The value of ENOTTY. */-#undef CONST_ENOTTY--/* The value of ENXIO. */-#undef CONST_ENXIO--/* The value of EOPNOTSUPP. */-#undef CONST_EOPNOTSUPP--/* The value of EPERM. */-#undef CONST_EPERM--/* The value of EPFNOSUPPORT. */-#undef CONST_EPFNOSUPPORT--/* The value of EPIPE. */-#undef CONST_EPIPE--/* The value of EPROCLIM. */-#undef CONST_EPROCLIM--/* The value of EPROCUNAVAIL. */-#undef CONST_EPROCUNAVAIL--/* The value of EPROGMISMATCH. */-#undef CONST_EPROGMISMATCH--/* The value of EPROGUNAVAIL. */-#undef CONST_EPROGUNAVAIL--/* The value of EPROTO. */-#undef CONST_EPROTO--/* The value of EPROTONOSUPPORT. */-#undef CONST_EPROTONOSUPPORT--/* The value of EPROTOTYPE. */-#undef CONST_EPROTOTYPE--/* The value of ERANGE. */-#undef CONST_ERANGE--/* The value of EREMCHG. */-#undef CONST_EREMCHG--/* The value of EREMOTE. */-#undef CONST_EREMOTE--/* The value of EROFS. */-#undef CONST_EROFS--/* The value of ERPCMISMATCH. */-#undef CONST_ERPCMISMATCH--/* The value of ERREMOTE. */-#undef CONST_ERREMOTE--/* The value of ESHUTDOWN. */-#undef CONST_ESHUTDOWN--/* The value of ESOCKTNOSUPPORT. */-#undef CONST_ESOCKTNOSUPPORT--/* The value of ESPIPE. */-#undef CONST_ESPIPE--/* The value of ESRCH. */-#undef CONST_ESRCH--/* The value of ESRMNT. */-#undef CONST_ESRMNT--/* The value of ESTALE. */-#undef CONST_ESTALE--/* The value of ETIME. */-#undef CONST_ETIME--/* The value of ETIMEDOUT. */-#undef CONST_ETIMEDOUT--/* The value of ETOOMANYREFS. */-#undef CONST_ETOOMANYREFS--/* The value of ETXTBSY. */-#undef CONST_ETXTBSY--/* The value of EUSERS. */-#undef CONST_EUSERS--/* The value of EWOULDBLOCK. */-#undef CONST_EWOULDBLOCK--/* The value of EXDEV. */-#undef CONST_EXDEV--/* The value of O_BINARY. */-#undef CONST_O_BINARY--/* The value of SIGINT. */-#undef CONST_SIGINT--/* Define to 1 if you have the `clock_gettime' function. */-#undef HAVE_CLOCK_GETTIME--/* Define to 1 if you have the <ctype.h> header file. */-#undef HAVE_CTYPE_H--/* Define if you have epoll support. */-#undef HAVE_EPOLL--/* Define to 1 if you have the `epoll_ctl' function. */-#undef HAVE_EPOLL_CTL--/* Define to 1 if you have the <errno.h> header file. */-#undef HAVE_ERRNO_H--/* Define to 1 if you have the `eventfd' function. */-#undef HAVE_EVENTFD--/* Define to 1 if you have the <fcntl.h> header file. */-#undef HAVE_FCNTL_H--/* Define to 1 if you have the `ftruncate' function. */-#undef HAVE_FTRUNCATE--/* Define to 1 if you have the `getclock' function. */-#undef HAVE_GETCLOCK--/* Define to 1 if you have the `getrusage' function. */-#undef HAVE_GETRUSAGE--/* Define to 1 if you have the <inttypes.h> header file. */-#undef HAVE_INTTYPES_H--/* Define to 1 if you have the `iswspace' function. */-#undef HAVE_ISWSPACE--/* Define to 1 if you have the `kevent' function. */-#undef HAVE_KEVENT--/* Define to 1 if you have the `kevent64' function. */-#undef HAVE_KEVENT64--/* Define if you have kqueue support. */-#undef HAVE_KQUEUE--/* Define to 1 if you have the <langinfo.h> header file. */-#undef HAVE_LANGINFO_H--/* Define to 1 if you have libcharset. */-#undef HAVE_LIBCHARSET--/* Define to 1 if you have the `rt' library (-lrt). */-#undef HAVE_LIBRT--/* Define to 1 if you have the <limits.h> header file. */-#undef HAVE_LIMITS_H--/* Define to 1 if the system has the type `long long'. */-#undef HAVE_LONG_LONG--/* Define to 1 if you have the `lstat' function. */-#undef HAVE_LSTAT--/* Define to 1 if you have the <memory.h> header file. */-#undef HAVE_MEMORY_H--/* Define if you have poll support. */-#undef HAVE_POLL--/* Define to 1 if you have the <poll.h> header file. */-#undef HAVE_POLL_H--/* Define to 1 if you have the <signal.h> header file. */-#undef HAVE_SIGNAL_H--/* Define to 1 if you have the <stdint.h> header file. */-#undef HAVE_STDINT_H--/* Define to 1 if you have the <stdlib.h> header file. */-#undef HAVE_STDLIB_H--/* Define to 1 if you have the <strings.h> header file. */-#undef HAVE_STRINGS_H--/* Define to 1 if you have the <string.h> header file. */-#undef HAVE_STRING_H--/* Define to 1 if you have the <sys/epoll.h> header file. */-#undef HAVE_SYS_EPOLL_H--/* Define to 1 if you have the <sys/eventfd.h> header file. */-#undef HAVE_SYS_EVENTFD_H--/* Define to 1 if you have the <sys/event.h> header file. */-#undef HAVE_SYS_EVENT_H--/* Define to 1 if you have the <sys/resource.h> header file. */-#undef HAVE_SYS_RESOURCE_H--/* Define to 1 if you have the <sys/select.h> header file. */-#undef HAVE_SYS_SELECT_H--/* Define to 1 if you have the <sys/stat.h> header file. */-#undef HAVE_SYS_STAT_H--/* Define to 1 if you have the <sys/syscall.h> header file. */-#undef HAVE_SYS_SYSCALL_H--/* Define to 1 if you have the <sys/timeb.h> header file. */-#undef HAVE_SYS_TIMEB_H--/* Define to 1 if you have the <sys/timers.h> header file. */-#undef HAVE_SYS_TIMERS_H--/* Define to 1 if you have the <sys/times.h> header file. */-#undef HAVE_SYS_TIMES_H--/* Define to 1 if you have the <sys/time.h> header file. */-#undef HAVE_SYS_TIME_H--/* Define to 1 if you have the <sys/types.h> header file. */-#undef HAVE_SYS_TYPES_H--/* Define to 1 if you have the <sys/utsname.h> header file. */-#undef HAVE_SYS_UTSNAME_H--/* Define to 1 if you have the <sys/wait.h> header file. */-#undef HAVE_SYS_WAIT_H--/* Define to 1 if you have the <termios.h> header file. */-#undef HAVE_TERMIOS_H--/* Define to 1 if you have the `times' function. */-#undef HAVE_TIMES--/* Define to 1 if you have the <time.h> header file. */-#undef HAVE_TIME_H--/* Define to 1 if you have the <unistd.h> header file. */-#undef HAVE_UNISTD_H--/* Define to 1 if you have the `unsetenv' function. */-#undef HAVE_UNSETENV--/* Define to 1 if you have the <utime.h> header file. */-#undef HAVE_UTIME_H--/* Define to 1 if you have the <wctype.h> header file. */-#undef HAVE_WCTYPE_H--/* Define to 1 if you have the <windows.h> header file. */-#undef HAVE_WINDOWS_H--/* Define to 1 if you have the <winsock.h> header file. */-#undef HAVE_WINSOCK_H--/* Define to 1 if you have the `_chsize' function. */-#undef HAVE__CHSIZE--/* Define to Haskell type for cc_t */-#undef HTYPE_CC_T--/* Define to Haskell type for char */-#undef HTYPE_CHAR--/* Define to Haskell type for clock_t */-#undef HTYPE_CLOCK_T--/* Define to Haskell type for dev_t */-#undef HTYPE_DEV_T--/* Define to Haskell type for double */-#undef HTYPE_DOUBLE--/* Define to Haskell type for float */-#undef HTYPE_FLOAT--/* Define to Haskell type for gid_t */-#undef HTYPE_GID_T--/* Define to Haskell type for ino_t */-#undef HTYPE_INO_T--/* Define to Haskell type for int */-#undef HTYPE_INT--/* Define to Haskell type for intmax_t */-#undef HTYPE_INTMAX_T--/* Define to Haskell type for intptr_t */-#undef HTYPE_INTPTR_T--/* Define to Haskell type for long */-#undef HTYPE_LONG--/* Define to Haskell type for long long */-#undef HTYPE_LONG_LONG--/* Define to Haskell type for mode_t */-#undef HTYPE_MODE_T--/* Define to Haskell type for nlink_t */-#undef HTYPE_NLINK_T--/* Define to Haskell type for off_t */-#undef HTYPE_OFF_T--/* Define to Haskell type for pid_t */-#undef HTYPE_PID_T--/* Define to Haskell type for ptrdiff_t */-#undef HTYPE_PTRDIFF_T--/* Define to Haskell type for rlim_t */-#undef HTYPE_RLIM_T--/* Define to Haskell type for short */-#undef HTYPE_SHORT--/* Define to Haskell type for signed char */-#undef HTYPE_SIGNED_CHAR--/* Define to Haskell type for sig_atomic_t */-#undef HTYPE_SIG_ATOMIC_T--/* Define to Haskell type for size_t */-#undef HTYPE_SIZE_T--/* Define to Haskell type for speed_t */-#undef HTYPE_SPEED_T--/* Define to Haskell type for ssize_t */-#undef HTYPE_SSIZE_T--/* Define to Haskell type for suseconds_t */-#undef HTYPE_SUSECONDS_T--/* Define to Haskell type for tcflag_t */-#undef HTYPE_TCFLAG_T--/* Define to Haskell type for time_t */-#undef HTYPE_TIME_T--/* Define to Haskell type for uid_t */-#undef HTYPE_UID_T--/* Define to Haskell type for uintmax_t */-#undef HTYPE_UINTMAX_T--/* Define to Haskell type for uintptr_t */-#undef HTYPE_UINTPTR_T--/* Define to Haskell type for unsigned char */-#undef HTYPE_UNSIGNED_CHAR--/* Define to Haskell type for unsigned int */-#undef HTYPE_UNSIGNED_INT--/* Define to Haskell type for unsigned long */-#undef HTYPE_UNSIGNED_LONG--/* Define to Haskell type for unsigned long long */-#undef HTYPE_UNSIGNED_LONG_LONG--/* Define to Haskell type for unsigned short */-#undef HTYPE_UNSIGNED_SHORT--/* Define to Haskell type for useconds_t */-#undef HTYPE_USECONDS_T--/* Define to Haskell type for wchar_t */-#undef HTYPE_WCHAR_T--/* Define to the address where bug reports for this package should be sent. */-#undef PACKAGE_BUGREPORT--/* Define to the full name of this package. */-#undef PACKAGE_NAME--/* Define to the full name and version of this package. */-#undef PACKAGE_STRING--/* Define to the one symbol short name of this package. */-#undef PACKAGE_TARNAME--/* Define to the home page for this package. */-#undef PACKAGE_URL--/* Define to the version of this package. */-#undef PACKAGE_VERSION--/* The size of `kev.filter', as computed by sizeof. */-#undef SIZEOF_KEV_FILTER--/* The size of `kev.flags', as computed by sizeof. */-#undef SIZEOF_KEV_FLAGS--/* The size of `struct MD5Context', as computed by sizeof. */-#undef SIZEOF_STRUCT_MD5CONTEXT--/* Define to 1 if you have the ANSI C header files. */-#undef STDC_HEADERS--/* Define if stdlib.h declares unsetenv to return void. */-#undef UNSETENV_RETURNS_VOID--/* Enable large inode numbers on Mac OS X 10.5.  */-#ifndef _DARWIN_USE_64_BIT_INODE-# define _DARWIN_USE_64_BIT_INODE 1-#endif--/* Number of bits in a file offset, on hosts where this is settable. */-#undef _FILE_OFFSET_BITS--/* Define for large files, on AIX-style hosts. */-#undef _LARGE_FILES
− include/Typeable.h
@@ -1,31 +0,0 @@-{- ---------------------------------------------------------------------------// Macros to help make Typeable instances.-//-// INSTANCE_TYPEABLEn(tc,tcname,"tc") defines-//-//	instance Typeable/n/ tc-//	instance Typeable a => Typeable/n-1/ (tc a)-//	instance (Typeable a, Typeable b) => Typeable/n-2/ (tc a b)-//	...-//	instance (Typeable a1, ..., Typeable an) => Typeable (tc a1 ... an)-// ----------------------------------------------------------------------------}--#ifndef TYPEABLE_H-#define TYPEABLE_H--#warning <Typeable.h> is obsolete and will be removed in GHC 7.10----  // For GHC, we can use DeriveDataTypeable + StandaloneDeriving to---  // generate the instances.--#define INSTANCE_TYPEABLE0(tycon,tcname,str) deriving instance Typeable tycon-#define INSTANCE_TYPEABLE1(tycon,tcname,str) deriving instance Typeable tycon-#define INSTANCE_TYPEABLE2(tycon,tcname,str) deriving instance Typeable tycon-#define INSTANCE_TYPEABLE3(tycon,tcname,str) deriving instance Typeable tycon-#define INSTANCE_TYPEABLE4(tycon,tcname,str) deriving instance Typeable tycon-#define INSTANCE_TYPEABLE5(tycon,tcname,str) deriving instance Typeable tycon-#define INSTANCE_TYPEABLE6(tycon,tcname,str) deriving instance Typeable tycon-#define INSTANCE_TYPEABLE7(tycon,tcname,str) deriving instance Typeable tycon--#endif
− include/WCsubst.h
@@ -1,25 +0,0 @@-#ifndef WCSUBST_INCL--#define WCSUBST_INCL--#include "HsFFI.h"-#include <stdlib.h>--HsInt u_iswupper(HsInt wc);-HsInt u_iswdigit(HsInt wc);-HsInt u_iswalpha(HsInt wc);-HsInt u_iswcntrl(HsInt wc);-HsInt u_iswspace(HsInt wc);-HsInt u_iswprint(HsInt wc);-HsInt u_iswlower(HsInt wc);--HsInt u_iswalnum(HsInt wc);--HsInt u_towlower(HsInt wc);-HsInt u_towupper(HsInt wc);-HsInt u_towtitle(HsInt wc);--HsInt u_gencat(HsInt wc);--#endif-
− include/consUtils.h
@@ -1,13 +0,0 @@-/* - * (c) The University of Glasgow, 2000-2002- *- * Win32 Console API helpers.- */-#ifndef __CONSUTILS_H__-#define __CONSUTILS_H__-extern int is_console__(int fd);-extern int set_console_buffering__(int fd, int cooked);-extern int set_console_echo__(int fd, int on);-extern int get_console_echo__(int fd);-extern int flush_input_console__ (int fd);-#endif
− include/ieee-flpt.h
@@ -1,35 +0,0 @@-/* this file is #included into both C (.c and .hc) and Haskell files */--    /* IEEE format floating-point */-#define IEEE_FLOATING_POINT 1--   /* Radix of exponent representation */-#ifndef FLT_RADIX-# define FLT_RADIX 2-#endif--   /* Number of base-FLT_RADIX digits in the significand of a float */-#ifndef FLT_MANT_DIG-# define FLT_MANT_DIG 24-#endif-   /* Minimum int x such that FLT_RADIX**(x-1) is a normalised float */-#ifndef FLT_MIN_EXP-#  define FLT_MIN_EXP (-125)-#endif-   /* Maximum int x such that FLT_RADIX**(x-1) is a representable float */-#ifndef FLT_MAX_EXP-# define FLT_MAX_EXP 128-#endif--   /* Number of base-FLT_RADIX digits in the significand of a double */-#ifndef DBL_MANT_DIG-# define DBL_MANT_DIG 53-#endif-   /* Minimum int x such that FLT_RADIX**(x-1) is a normalised double */-#ifndef DBL_MIN_EXP-#  define DBL_MIN_EXP (-1021)-#endif-   /* Maximum int x such that FLT_RADIX**(x-1) is a representable double */-#ifndef DBL_MAX_EXP-# define DBL_MAX_EXP 1024-#endif
− include/md5.h
@@ -1,24 +0,0 @@-/* MD5 message digest */-#ifndef _MD5_H-#define _MD5_H--#include "HsFFI.h"--typedef HsWord32 word32;-typedef HsWord8  byte;--struct MD5Context {-	word32 buf[4];-	word32 bytes[2];-	word32 in[16];-};--void __hsbase_MD5Init(struct MD5Context *context);-void __hsbase_MD5Update(struct MD5Context *context, byte const *buf, int len);-void __hsbase_MD5Final(byte digest[16], struct MD5Context *context);-void __hsbase_MD5Transform(word32 buf[4], word32 const in[16]);--#endif /* _MD5_H */---
− install-sh
@@ -1,527 +0,0 @@-#!/bin/sh-# install - install a program, script, or datafile--scriptversion=2011-11-20.07; # UTC--# This originates from X11R5 (mit/util/scripts/install.sh), which was-# later released in X11R6 (xc/config/util/install.sh) with the-# following copyright and license.-#-# Copyright (C) 1994 X Consortium-#-# Permission is hereby granted, free of charge, to any person obtaining a copy-# of this software and associated documentation files (the "Software"), to-# deal in the Software without restriction, including without limitation the-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or-# sell copies of the Software, and to permit persons to whom the Software is-# furnished to do so, subject to the following conditions:-#-# The above copyright notice and this permission notice shall be included in-# all copies or substantial portions of the Software.-#-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE-# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN-# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC--# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.-#-# Except as contained in this notice, the name of the X Consortium shall not-# be used in advertising or otherwise to promote the sale, use or other deal--# ings in this Software without prior written authorization from the X Consor--# tium.-#-#-# FSF changes to this file are in the public domain.-#-# Calling this script install-sh is preferred over install.sh, to prevent-# 'make' implicit rules from creating a file called install from it-# when there is no Makefile.-#-# This script is compatible with the BSD install script, but was written-# from scratch.--nl='-'-IFS=" ""	$nl"--# set DOITPROG to echo to test this script--# Don't use :- since 4.3BSD and earlier shells don't like it.-doit=${DOITPROG-}-if test -z "$doit"; then-  doit_exec=exec-else-  doit_exec=$doit-fi--# Put in absolute file names if you don't have them in your path;-# or use environment vars.--chgrpprog=${CHGRPPROG-chgrp}-chmodprog=${CHMODPROG-chmod}-chownprog=${CHOWNPROG-chown}-cmpprog=${CMPPROG-cmp}-cpprog=${CPPROG-cp}-mkdirprog=${MKDIRPROG-mkdir}-mvprog=${MVPROG-mv}-rmprog=${RMPROG-rm}-stripprog=${STRIPPROG-strip}--posix_glob='?'-initialize_posix_glob='-  test "$posix_glob" != "?" || {-    if (set -f) 2>/dev/null; then-      posix_glob=-    else-      posix_glob=:-    fi-  }-'--posix_mkdir=--# Desired mode of installed file.-mode=0755--chgrpcmd=-chmodcmd=$chmodprog-chowncmd=-mvcmd=$mvprog-rmcmd="$rmprog -f"-stripcmd=--src=-dst=-dir_arg=-dst_arg=--copy_on_change=false-no_target_directory=--usage="\-Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE-   or: $0 [OPTION]... SRCFILES... DIRECTORY-   or: $0 [OPTION]... -t DIRECTORY SRCFILES...-   or: $0 [OPTION]... -d DIRECTORIES...--In the 1st form, copy SRCFILE to DSTFILE.-In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.-In the 4th, create DIRECTORIES.--Options:-     --help     display this help and exit.-     --version  display version info and exit.--  -c            (ignored)-  -C            install only if different (preserve the last data modification time)-  -d            create directories instead of installing files.-  -g GROUP      $chgrpprog installed files to GROUP.-  -m MODE       $chmodprog installed files to MODE.-  -o USER       $chownprog installed files to USER.-  -s            $stripprog installed files.-  -t DIRECTORY  install into DIRECTORY.-  -T            report an error if DSTFILE is a directory.--Environment variables override the default commands:-  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG-  RMPROG STRIPPROG-"--while test $# -ne 0; do-  case $1 in-    -c) ;;--    -C) copy_on_change=true;;--    -d) dir_arg=true;;--    -g) chgrpcmd="$chgrpprog $2"-	shift;;--    --help) echo "$usage"; exit $?;;--    -m) mode=$2-	case $mode in-	  *' '* | *'	'* | *'-'*	  | *'*'* | *'?'* | *'['*)-	    echo "$0: invalid mode: $mode" >&2-	    exit 1;;-	esac-	shift;;--    -o) chowncmd="$chownprog $2"-	shift;;--    -s) stripcmd=$stripprog;;--    -t) dst_arg=$2-	# Protect names problematic for 'test' and other utilities.-	case $dst_arg in-	  -* | [=\(\)!]) dst_arg=./$dst_arg;;-	esac-	shift;;--    -T) no_target_directory=true;;--    --version) echo "$0 $scriptversion"; exit $?;;--    --)	shift-	break;;--    -*)	echo "$0: invalid option: $1" >&2-	exit 1;;--    *)  break;;-  esac-  shift-done--if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then-  # When -d is used, all remaining arguments are directories to create.-  # When -t is used, the destination is already specified.-  # Otherwise, the last argument is the destination.  Remove it from $@.-  for arg-  do-    if test -n "$dst_arg"; then-      # $@ is not empty: it contains at least $arg.-      set fnord "$@" "$dst_arg"-      shift # fnord-    fi-    shift # arg-    dst_arg=$arg-    # Protect names problematic for 'test' and other utilities.-    case $dst_arg in-      -* | [=\(\)!]) dst_arg=./$dst_arg;;-    esac-  done-fi--if test $# -eq 0; then-  if test -z "$dir_arg"; then-    echo "$0: no input file specified." >&2-    exit 1-  fi-  # It's OK to call 'install-sh -d' without argument.-  # This can happen when creating conditional directories.-  exit 0-fi--if test -z "$dir_arg"; then-  do_exit='(exit $ret); exit $ret'-  trap "ret=129; $do_exit" 1-  trap "ret=130; $do_exit" 2-  trap "ret=141; $do_exit" 13-  trap "ret=143; $do_exit" 15--  # Set umask so as not to create temps with too-generous modes.-  # However, 'strip' requires both read and write access to temps.-  case $mode in-    # Optimize common cases.-    *644) cp_umask=133;;-    *755) cp_umask=22;;--    *[0-7])-      if test -z "$stripcmd"; then-	u_plus_rw=-      else-	u_plus_rw='% 200'-      fi-      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;-    *)-      if test -z "$stripcmd"; then-	u_plus_rw=-      else-	u_plus_rw=,u+rw-      fi-      cp_umask=$mode$u_plus_rw;;-  esac-fi--for src-do-  # Protect names problematic for 'test' and other utilities.-  case $src in-    -* | [=\(\)!]) src=./$src;;-  esac--  if test -n "$dir_arg"; then-    dst=$src-    dstdir=$dst-    test -d "$dstdir"-    dstdir_status=$?-  else--    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command-    # might cause directories to be created, which would be especially bad-    # if $src (and thus $dsttmp) contains '*'.-    if test ! -f "$src" && test ! -d "$src"; then-      echo "$0: $src does not exist." >&2-      exit 1-    fi--    if test -z "$dst_arg"; then-      echo "$0: no destination specified." >&2-      exit 1-    fi-    dst=$dst_arg--    # If destination is a directory, append the input filename; won't work-    # if double slashes aren't ignored.-    if test -d "$dst"; then-      if test -n "$no_target_directory"; then-	echo "$0: $dst_arg: Is a directory" >&2-	exit 1-      fi-      dstdir=$dst-      dst=$dstdir/`basename "$src"`-      dstdir_status=0-    else-      # Prefer dirname, but fall back on a substitute if dirname fails.-      dstdir=`-	(dirname "$dst") 2>/dev/null ||-	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \-	     X"$dst" : 'X\(//\)[^/]' \| \-	     X"$dst" : 'X\(//\)$' \| \-	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||-	echo X"$dst" |-	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{-		   s//\1/-		   q-		 }-		 /^X\(\/\/\)[^/].*/{-		   s//\1/-		   q-		 }-		 /^X\(\/\/\)$/{-		   s//\1/-		   q-		 }-		 /^X\(\/\).*/{-		   s//\1/-		   q-		 }-		 s/.*/./; q'-      `--      test -d "$dstdir"-      dstdir_status=$?-    fi-  fi--  obsolete_mkdir_used=false--  if test $dstdir_status != 0; then-    case $posix_mkdir in-      '')-	# Create intermediate dirs using mode 755 as modified by the umask.-	# This is like FreeBSD 'install' as of 1997-10-28.-	umask=`umask`-	case $stripcmd.$umask in-	  # Optimize common cases.-	  *[2367][2367]) mkdir_umask=$umask;;-	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;--	  *[0-7])-	    mkdir_umask=`expr $umask + 22 \-	      - $umask % 100 % 40 + $umask % 20 \-	      - $umask % 10 % 4 + $umask % 2-	    `;;-	  *) mkdir_umask=$umask,go-w;;-	esac--	# With -d, create the new directory with the user-specified mode.-	# Otherwise, rely on $mkdir_umask.-	if test -n "$dir_arg"; then-	  mkdir_mode=-m$mode-	else-	  mkdir_mode=-	fi--	posix_mkdir=false-	case $umask in-	  *[123567][0-7][0-7])-	    # POSIX mkdir -p sets u+wx bits regardless of umask, which-	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.-	    ;;-	  *)-	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$-	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0--	    if (umask $mkdir_umask &&-		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1-	    then-	      if test -z "$dir_arg" || {-		   # Check for POSIX incompatibilities with -m.-		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or-		   # other-writable bit of parent directory when it shouldn't.-		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.-		   ls_ld_tmpdir=`ls -ld "$tmpdir"`-		   case $ls_ld_tmpdir in-		     d????-?r-*) different_mode=700;;-		     d????-?--*) different_mode=755;;-		     *) false;;-		   esac &&-		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {-		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`-		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"-		   }-		 }-	      then posix_mkdir=:-	      fi-	      rmdir "$tmpdir/d" "$tmpdir"-	    else-	      # Remove any dirs left behind by ancient mkdir implementations.-	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null-	    fi-	    trap '' 0;;-	esac;;-    esac--    if-      $posix_mkdir && (-	umask $mkdir_umask &&-	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"-      )-    then :-    else--      # The umask is ridiculous, or mkdir does not conform to POSIX,-      # or it failed possibly due to a race condition.  Create the-      # directory the slow way, step by step, checking for races as we go.--      case $dstdir in-	/*) prefix='/';;-	[-=\(\)!]*) prefix='./';;-	*)  prefix='';;-      esac--      eval "$initialize_posix_glob"--      oIFS=$IFS-      IFS=/-      $posix_glob set -f-      set fnord $dstdir-      shift-      $posix_glob set +f-      IFS=$oIFS--      prefixes=--      for d-      do-	test X"$d" = X && continue--	prefix=$prefix$d-	if test -d "$prefix"; then-	  prefixes=-	else-	  if $posix_mkdir; then-	    (umask=$mkdir_umask &&-	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break-	    # Don't fail if two instances are running concurrently.-	    test -d "$prefix" || exit 1-	  else-	    case $prefix in-	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;-	      *) qprefix=$prefix;;-	    esac-	    prefixes="$prefixes '$qprefix'"-	  fi-	fi-	prefix=$prefix/-      done--      if test -n "$prefixes"; then-	# Don't fail if two instances are running concurrently.-	(umask $mkdir_umask &&-	 eval "\$doit_exec \$mkdirprog $prefixes") ||-	  test -d "$dstdir" || exit 1-	obsolete_mkdir_used=true-      fi-    fi-  fi--  if test -n "$dir_arg"; then-    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&-    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||-      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1-  else--    # Make a couple of temp file names in the proper directory.-    dsttmp=$dstdir/_inst.$$_-    rmtmp=$dstdir/_rm.$$_--    # Trap to clean up those temp files at exit.-    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0--    # Copy the file name to the temp name.-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&--    # and set any options; do chmod last to preserve setuid bits.-    #-    # If any of these fail, we abort the whole thing.  If we want to-    # ignore errors from any of these, just make sure not to ignore-    # errors from the above "$doit $cpprog $src $dsttmp" command.-    #-    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&-    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&-    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&--    # If -C, don't bother to copy if it wouldn't change the file.-    if $copy_on_change &&-       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&-       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&--       eval "$initialize_posix_glob" &&-       $posix_glob set -f &&-       set X $old && old=:$2:$4:$5:$6 &&-       set X $new && new=:$2:$4:$5:$6 &&-       $posix_glob set +f &&--       test "$old" = "$new" &&-       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1-    then-      rm -f "$dsttmp"-    else-      # Rename the file to the real destination.-      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||--      # The rename failed, perhaps because mv can't rename something else-      # to itself, or perhaps because mv is so ancient that it does not-      # support -f.-      {-	# Now remove or move aside any old file at destination location.-	# We try this two ways since rm can't unlink itself on some-	# systems and the destination file might be busy for other-	# reasons.  In this case, the final cleanup might fail but the new-	# file should still install successfully.-	{-	  test ! -f "$dst" ||-	  $doit $rmcmd -f "$dst" 2>/dev/null ||-	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&-	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }-	  } ||-	  { echo "$0: cannot unlink or rename $dst" >&2-	    (exit 1); exit 1-	  }-	} &&--	# Now rename the file to the real destination.-	$doit $mvcmd "$dsttmp" "$dst"-      }-    fi || exit 1--    trap '' 0-  fi-done--# Local variables:-# eval: (add-hook 'write-file-hooks 'time-stamp)-# time-stamp-start: "scriptversion="-# time-stamp-format: "%:y-%02m-%02d.%02H"-# time-stamp-time-zone: "UTC"-# time-stamp-end: "; # UTC"-# End:
+ src/Control/Applicative.hs view
@@ -0,0 +1,145 @@+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE NoImplicitPrelude #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE DeriveDataTypeable #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Applicative+-- Copyright   :  Conor McBride and Ross Paterson 2005+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- This module describes a structure intermediate between a functor and+-- a monad (technically, a strong lax monoidal functor).  Compared with+-- monads, this interface lacks the full power of the binding operation+-- '>>=', but+--+-- * it has more instances.+--+-- * it is sufficient for many uses, e.g. context-free parsing, or the+--   'Data.Traversable.Traversable' class.+--+-- * instances can perform analysis of computations before they are+--   executed, and thus produce shared optimizations.+--+-- This interface was introduced for parsers by Niklas R&#xF6;jemo, because+-- it admits more sharing than the monadic interface.  The names here are+-- mostly based on parsing work by Doaitse Swierstra.+--+-- For more details, see+-- <http://www.soi.city.ac.uk/~ross/papers/Applicative.html Applicative Programming with Effects>,+-- by Conor McBride and Ross Paterson.++module Control.Applicative (+    -- * Applicative functors+    Applicative(..),+    -- * Alternatives+    Alternative(..),+    -- * Instances+    Const(..), WrappedMonad(..), WrappedArrow(..), ZipList(..),+    -- * Utility functions+    (<$>), (<$), (<**>),+    liftA, liftA3,+    optional,+    asum,+    ) where++import GHC.Internal.Control.Category hiding ((.), id)+import GHC.Internal.Control.Arrow+import GHC.Internal.Data.Maybe+import GHC.Internal.Data.Tuple+import GHC.Internal.Data.Foldable (asum)+import GHC.Internal.Data.Functor ((<$>))+import GHC.Internal.Data.Functor.Const (Const(..))+import GHC.Internal.Data.Typeable (Typeable)+import GHC.Internal.Data.Data (Data)++import GHC.Internal.Base+import GHC.Internal.Functor.ZipList (ZipList(..))+import GHC.Generics++-- $setup+-- >>> import Prelude++newtype WrappedMonad m a = WrapMonad { unwrapMonad :: m a }+                         deriving ( Generic  -- ^ @since 4.7.0.0+                                  , Generic1 -- ^ @since 4.7.0.0+                                  , Monad    -- ^ @since 4.7.0.0+                                  )++-- | @since 2.01+instance Monad m => Functor (WrappedMonad m) where+    fmap f (WrapMonad v) = WrapMonad (liftM f v)++-- | @since 2.01+instance Monad m => Applicative (WrappedMonad m) where+    pure = WrapMonad . pure+    WrapMonad f <*> WrapMonad v = WrapMonad (f `ap` v)+    liftA2 f (WrapMonad x) (WrapMonad y) = WrapMonad (liftM2 f x y)++-- | @since 2.01+instance MonadPlus m => Alternative (WrappedMonad m) where+    empty = WrapMonad mzero+    WrapMonad u <|> WrapMonad v = WrapMonad (u `mplus` v)++-- | @since 4.14.0.0+deriving instance (Typeable (m :: Type -> Type), Typeable a, Data (m a))+         => Data (WrappedMonad m a)++newtype WrappedArrow a b c = WrapArrow { unwrapArrow :: a b c }+                           deriving ( Generic  -- ^ @since 4.7.0.0+                                    , Generic1 -- ^ @since 4.7.0.0+                                    )++-- | @since 2.01+instance Arrow a => Functor (WrappedArrow a b) where+    fmap f (WrapArrow a) = WrapArrow (a >>> arr f)++-- | @since 2.01+instance Arrow a => Applicative (WrappedArrow a b) where+    pure x = WrapArrow (arr (const x))+    liftA2 f (WrapArrow u) (WrapArrow v) =+      WrapArrow (u &&& v >>> arr (uncurry f))++-- | @since 2.01+instance (ArrowZero a, ArrowPlus a) => Alternative (WrappedArrow a b) where+    empty = WrapArrow zeroArrow+    WrapArrow u <|> WrapArrow v = WrapArrow (u <+> v)++-- | @since 4.14.0.0+deriving instance (Typeable (a :: Type -> Type -> Type), Typeable b, Typeable c,+                   Data (a b c))+         => Data (WrappedArrow a b c)++-- extra functions++-- | One or none.+--+-- It is useful for modelling any computation that is allowed to fail.+--+-- ==== __Examples__+--+-- Using the 'Alternative' instance of "Control.Monad.Except", the following functions:+--+-- >>> import Control.Monad.Except+--+-- >>> canFail = throwError "it failed" :: Except String Int+-- >>> final = return 42                :: Except String Int+--+-- Can be combined by allowing the first function to fail:+--+-- >>> runExcept $ canFail *> final+-- Left "it failed"+--+-- >>> runExcept $ optional canFail *> final+-- Right 42++optional :: Alternative f => f a -> f (Maybe a)+optional v = Just <$> v <|> pure Nothing
+ src/Control/Arrow.hs view
@@ -0,0 +1,52 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Control.Arrow+-- Copyright   :  (c) Ross Paterson 2002+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Basic arrow definitions, based on+--+--  * /Generalising Monads to Arrows/, by John Hughes,+--    /Science of Computer Programming/ 37, pp67-111, May 2000.+--+-- plus a couple of definitions ('returnA' and 'loop') from+--+--  * /A New Notation for Arrows/, by Ross Paterson, in /ICFP 2001/,+--    Firenze, Italy, pp229-240.+--+-- These papers and more information on arrows can be found at+-- <http://www.haskell.org/arrows/>.++module Control.Arrow+    (-- *  Arrows+     Arrow(..),+     Kleisli(..),+     -- **  Derived combinators+     returnA,+     (^>>),+     (>>^),+     (>>>),+     (<<<),+     -- **  Right-to-left variants+     (<<^),+     (^<<),+     -- *  Monoid operations+     ArrowZero(..),+     ArrowPlus(..),+     -- *  Conditionals+     ArrowChoice(..),+     -- *  Arrow application+     ArrowApply(..),+     ArrowMonad(..),+     leftApp,+     -- *  Feedback+     ArrowLoop(..)+     ) where++import GHC.Internal.Control.Arrow
+ src/Control/Category.hs view
@@ -0,0 +1,36 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  Control.Category+-- Copyright   :  (c) Ashley Yakeley 2007+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  ashley@semantic.org+-- Stability   :  stable+-- Portability :  portable+--++module Control.Category+  ( -- * Class+    Category(..)++    -- * Combinators+  , (<<<)+  , (>>>)++  -- $namingConflicts+  ) where++import GHC.Internal.Control.Category++-- $namingConflicts+--+-- == A note on naming conflicts+--+-- The methods from 'Category' conflict with 'Prelude.id' and 'Prelude..' from the+-- prelude; you will likely want to either import this module qualified, or hide the+-- prelude functions:+--+-- @+-- import "Prelude" hiding (id, (.))+-- @
+ src/Control/Concurrent.hs view
@@ -0,0 +1,534 @@+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE CPP+           , MagicHash+           , UnboxedTuples+           , ScopedTypeVariables+           , RankNTypes+  #-}+{-# OPTIONS_GHC -Wno-deprecations #-}+-- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN+-- and Control.Concurrent.SampleVar imports.++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Concurrent+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (concurrency)+--+-- A common interface to a collection of useful concurrency+-- abstractions.+--+-----------------------------------------------------------------------------++module Control.Concurrent (+        -- * Concurrent Haskell++        -- $conc_intro++        -- * Basic concurrency operations++        ThreadId,+        myThreadId,++        forkIO,+        forkFinally,+        forkIOWithUnmask,+        killThread,+        throwTo,++        -- ** Threads with affinity+        forkOn,+        forkOnWithUnmask,+        getNumCapabilities,+        setNumCapabilities,+        threadCapability,++        -- * Scheduling++        -- $conc_scheduling+        yield,++        -- ** Blocking++        -- $blocking++        -- ** Waiting+        threadDelay,+        threadWaitRead,+        threadWaitWrite,+        threadWaitReadSTM,+        threadWaitWriteSTM,++        -- * Communication abstractions++        module GHC.Internal.Control.Concurrent.MVar,+        module Control.Concurrent.Chan,+        module Control.Concurrent.QSem,+        module Control.Concurrent.QSemN,++        -- * Bound Threads+        -- $boundthreads+        rtsSupportsBoundThreads,+        forkOS,+        forkOSWithUnmask,+        isCurrentThreadBound,+        runInBoundThread,+        runInUnboundThread,++        -- * Weak references to ThreadIds+        mkWeakThreadId,++        -- * GHC's implementation of concurrency++        -- |This section describes features specific to GHC's+        -- implementation of Concurrent Haskell.++        -- ** Haskell threads and Operating System threads++        -- $osthreads++        -- ** Terminating the program++        -- $termination++        -- ** Pre-emption++        -- $preemption++        -- ** Deadlock++        -- $deadlock++    ) where++import Prelude+import GHC.Internal.Control.Exception.Base as Exception++import GHC.Internal.Conc.Bound+import GHC.Conc hiding (threadWaitRead, threadWaitWrite,+                        threadWaitReadSTM, threadWaitWriteSTM)++import GHC.Internal.System.Posix.Types ( Fd )++#if defined(mingw32_HOST_OS)+import GHC.Internal.Foreign.C.Error+import GHC.Internal.Foreign.C.Types+import GHC.Internal.System.IO+import GHC.Internal.Data.Functor ( void )+import GHC.Internal.Int ( Int64 )+#else+import qualified GHC.Internal.Conc.IO as Conc+#endif++import GHC.Internal.Control.Concurrent.MVar+import Control.Concurrent.Chan+import Control.Concurrent.QSem+import Control.Concurrent.QSemN++{- $conc_intro++The concurrency extension for Haskell is described in the paper+/Concurrent Haskell/+<http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.++Concurrency is \"lightweight\", which means that both thread creation+and context switching overheads are extremely low.  Scheduling of+Haskell threads is done internally in the Haskell runtime system, and+doesn't make use of any operating system-supplied thread packages.++However, if you want to interact with a foreign library that expects your+program to use the operating system-supplied thread package, you can do so+by using 'forkOS' instead of 'forkIO'.++Haskell threads can communicate via 'MVar's, a kind of synchronised+mutable variable (see "Control.Concurrent.MVar").  Several common+concurrency abstractions can be built from 'MVar's, and these are+provided by the "Control.Concurrent" module.+In GHC, threads may also communicate via exceptions.+-}++{- $conc_scheduling++    Scheduling may be either pre-emptive or co-operative,+    depending on the implementation of Concurrent Haskell (see below+    for information related to specific compilers).  In a co-operative+    system, context switches only occur when you use one of the+    primitives defined in this module.  This means that programs such+    as:+++>   main = forkIO (write 'a') >> write 'b'+>     where write c = putChar c >> write c++    will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,+    instead of some random interleaving of @a@s and @b@s.  In+    practice, cooperative multitasking is sufficient for writing+    simple graphical user interfaces.+-}++{- $blocking+Different Haskell implementations have different characteristics with+regard to which operations block /all/ threads.++Using GHC without the @-threaded@ option, all foreign calls will block+all other Haskell threads in the system, although I\/O operations will+not.  With the @-threaded@ option, only foreign calls with the @unsafe@+attribute will block all other threads.++-}++-- | Fork a thread and call the supplied function when the thread is about+-- to terminate, with an exception or a returned value.  The function is+-- called with asynchronous exceptions masked.+--+-- > forkFinally action and_then =+-- >   mask $ \restore ->+-- >     forkIO $ try (restore action) >>= and_then+--+-- This function is useful for informing the parent when a child+-- terminates, for example.+--+-- @since 4.6.0.0+forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId+forkFinally action and_then =+  mask $ \restore ->+    forkIO $ try (restore action) >>= and_then++-- ---------------------------------------------------------------------------+-- Bound Threads++{- $boundthreads+   #boundthreads#++Support for multiple operating system threads and bound threads as described+below is currently only available in the GHC runtime system if you use the+/-threaded/ option when linking.++Other Haskell systems do not currently support multiple operating system threads.++A bound thread is a haskell thread that is /bound/ to an operating system+thread. While the bound thread is still scheduled by the Haskell run-time+system, the operating system thread takes care of all the foreign calls made+by the bound thread.++To a foreign library, the bound thread will look exactly like an ordinary+operating system thread created using OS functions like @pthread_create@+or @CreateThread@.++Bound threads can be created using the 'forkOS' function below. All foreign+exported functions are run in a bound thread (bound to the OS thread that+called the function). Also, the @main@ action of every Haskell program is+run in a bound thread.++Why do we need this? Because if a foreign library is called from a thread+created using 'forkIO', it won't have access to any /thread-local state/ -+state variables that have specific values for each OS thread+(see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some+libraries (OpenGL, for example) will not work from a thread created using+'forkIO'. They work fine in threads created using 'forkOS' or when called+from @main@ or from a @foreign export@.++In terms of performance, 'forkOS' (aka bound) threads are much more+expensive than 'forkIO' (aka unbound) threads, because a 'forkOS'+thread is tied to a particular OS thread, whereas a 'forkIO' thread+can be run by any OS thread.  Context-switching between a 'forkOS'+thread and a 'forkIO' thread is many times more expensive than between+two 'forkIO' threads.++Note in particular that the main program thread (the thread running+@Main.main@) is always a bound thread, so for good concurrency+performance you should ensure that the main thread is not doing+repeated communication with other threads in the system.  Typically+this means forking subthreads to do the work using 'forkIO', and+waiting for the results in the main thread.++-}++-- ---------------------------------------------------------------------------+-- threadWaitRead/threadWaitWrite++-- | Block the current thread until data is available to read on the+-- given file descriptor (GHC only).+--+-- This will throw an 'IOError' if the file descriptor was closed+-- while this thread was blocked.  To safely close a file descriptor+-- that has been used with 'threadWaitRead', use+-- 'GHC.Conc.closeFdWith'.+threadWaitRead :: Fd -> IO ()+threadWaitRead fd+#if defined(mingw32_HOST_OS)+  -- we have no IO manager implementing threadWaitRead on Windows.+  -- fdReady does the right thing, but we have to call it in a+  -- separate thread, otherwise threadWaitRead won't be interruptible,+  -- and this only works with -threaded.+  | threaded  = withThread "threadWaitRead worker" (waitFd fd False)+  | otherwise = case fd of+                  0 -> do _ <- hWaitForInput stdin (-1)+                          return ()+                        -- hWaitForInput does work properly, but we can only+                        -- do this for stdin since we know its FD.+                  _ -> errorWithoutStackTrace "threadWaitRead requires -threaded on Windows, or use GHC.System.IO.hWaitForInput"+#else+  = Conc.threadWaitRead fd+#endif++-- | Block the current thread until data can be written to the+-- given file descriptor (GHC only).+--+-- This will throw an 'IOError' if the file descriptor was closed+-- while this thread was blocked.  To safely close a file descriptor+-- that has been used with 'threadWaitWrite', use+-- 'GHC.Conc.closeFdWith'.+threadWaitWrite :: Fd -> IO ()+threadWaitWrite fd+#if defined(mingw32_HOST_OS)+  | threaded  = withThread "threadWaitWrite worker" (waitFd fd True)+  | otherwise = errorWithoutStackTrace "threadWaitWrite requires -threaded on Windows"+#else+  = Conc.threadWaitWrite fd+#endif++-- | Returns an STM action that can be used to wait for data+-- to read from a file descriptor. The second returned value+-- is an IO action that can be used to deregister interest+-- in the file descriptor.+--+-- @since 4.7.0.0+threadWaitReadSTM :: Fd -> IO (STM (), IO ())+threadWaitReadSTM fd+#if defined(mingw32_HOST_OS)+  | threaded = do v <- newTVarIO Nothing+                  mask_ $ void $ forkIO $ do+                    tid <- myThreadId+                    labelThread tid "threadWaitReadSTM worker"+                    result <- try (waitFd fd False)+                    atomically (writeTVar v $ Just result)+                  let waitAction = do result <- readTVar v+                                      case result of+                                        Nothing         -> retry+                                        Just (Right ()) -> return ()+                                        Just (Left e)   -> throwSTM (e :: IOException)+                  let killAction = return ()+                  return (waitAction, killAction)+  | otherwise = errorWithoutStackTrace "threadWaitReadSTM requires -threaded on Windows"+#else+  = Conc.threadWaitReadSTM fd+#endif++-- | Returns an STM action that can be used to wait until data+-- can be written to a file descriptor. The second returned value+-- is an IO action that can be used to deregister interest+-- in the file descriptor.+--+-- @since 4.7.0.0+threadWaitWriteSTM :: Fd -> IO (STM (), IO ())+threadWaitWriteSTM fd+#if defined(mingw32_HOST_OS)+  | threaded = do v <- newTVarIO Nothing+                  mask_ $ void $ forkIO $ do+                    tid <- myThreadId+                    labelThread tid "threadWaitWriteSTM worker"+                    result <- try (waitFd fd True)+                    atomically (writeTVar v $ Just result)+                  let waitAction = do result <- readTVar v+                                      case result of+                                        Nothing         -> retry+                                        Just (Right ()) -> return ()+                                        Just (Left e)   -> throwSTM (e :: IOException)+                  let killAction = return ()+                  return (waitAction, killAction)+  | otherwise = errorWithoutStackTrace "threadWaitWriteSTM requires -threaded on Windows"+#else+  = Conc.threadWaitWriteSTM fd+#endif++#if defined(mingw32_HOST_OS)+foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool++withThread :: String -> IO a -> IO a+withThread label io = do+  m <- newEmptyMVar+  _ <- mask_ $ forkIO $ do+    tid <- myThreadId+    labelThread tid label+    result <- try io+    putMVar m result+  x <- takeMVar m+  case x of+    Right a -> return a+    Left e  -> throwIO (e :: IOException)++waitFd :: Fd -> Bool -> IO ()+waitFd fd write = do+   throwErrnoIfMinus1_ "fdReady" $+        fdReady (fromIntegral fd) (if write then 1 else 0) (-1) 0++foreign import ccall safe "fdReady"+  fdReady :: CInt -> CBool -> Int64 -> CBool -> IO CInt+#endif++-- ---------------------------------------------------------------------------+-- More docs++{- $osthreads++      #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and+      are managed entirely by the GHC runtime.  Typically Haskell+      threads are an order of magnitude or two more efficient (in+      terms of both time and space) than operating system threads.++      The downside of having lightweight threads is that only one can+      run at a time, so if one thread blocks in a foreign call, for+      example, the other threads cannot continue.  The GHC runtime+      works around this by making use of full OS threads where+      necessary.  When the program is built with the @-threaded@+      option (to link against the multithreaded version of the+      runtime), a thread making a @safe@ foreign call will not block+      the other threads in the system; another OS thread will take+      over running Haskell threads until the original call returns.+      The runtime maintains a pool of these /worker/ threads so that+      multiple Haskell threads can be involved in external calls+      simultaneously.++      The "System.IO" module manages multiplexing in its own way.  On+      Windows systems it uses @safe@ foreign calls to ensure that+      threads doing I\/O operations don't block the whole runtime,+      whereas on Unix systems all the currently blocked I\/O requests+      are managed by a single thread (the /IO manager thread/) using+      a mechanism such as @epoll@ or @kqueue@, depending on what is+      provided by the host operating system.++      The runtime will run a Haskell thread using any of the available+      worker OS threads.  If you need control over which particular OS+      thread is used to run a given Haskell thread, perhaps because+      you need to call a foreign library that uses OS-thread-local+      state, then you need bound threads (see "Control.Concurrent#boundthreads").++      If you don't use the @-threaded@ option, then the runtime does+      not make use of multiple OS threads.  Foreign calls will block+      all other running Haskell threads until the call returns.  The+      "System.IO" module still does multiplexing, so there can be multiple+      threads doing I\/O, and this is handled internally by the runtime using+      @select@.+-}++{- $termination++      In a standalone GHC program, only the main thread is+      required to terminate in order for the process to terminate.+      Thus all other forked threads will simply terminate at the same+      time as the main thread (the terminology for this kind of+      behaviour is \"daemonic threads\").++      If you want the program to wait for child threads to+      finish before exiting, you need to program this yourself.  A+      simple mechanism is to have each child thread write to an+      'MVar' when it completes, and have the main+      thread wait on all the 'MVar's before+      exiting:++>   myForkIO :: IO () -> IO (MVar ())+>   myForkIO io = do+>     mvar <- newEmptyMVar+>     forkFinally io (\_ -> putMVar mvar ())+>     return mvar++      Note that we use 'forkFinally' to make sure that the+      'MVar' is written to even if the thread dies or+      is killed for some reason.++      A better method is to keep a global list of all child+      threads which we should wait for at the end of the program:++>    children :: MVar [MVar ()]+>    children = unsafePerformIO (newMVar [])+>+>    waitForChildren :: IO ()+>    waitForChildren = do+>      cs <- takeMVar children+>      case cs of+>        []   -> return ()+>        m:ms -> do+>           putMVar children ms+>           takeMVar m+>           waitForChildren+>+>    forkChild :: IO () -> IO ThreadId+>    forkChild io = do+>        mvar <- newEmptyMVar+>        childs <- takeMVar children+>        putMVar children (mvar:childs)+>        forkFinally io (\_ -> putMVar mvar ())+>+>     main =+>       later waitForChildren $+>       ...++      The main thread principle also applies to calls to Haskell from+      outside, using @foreign export@.  When the @foreign export@ed+      function is invoked, it starts a new main thread, and it returns+      when this main thread terminates.  If the call causes new+      threads to be forked, they may remain in the system after the+      @foreign export@ed function has returned.+-}++{- $preemption++      GHC implements pre-emptive multitasking: the execution of+      threads are interleaved in a random fashion.  More specifically,+      a thread may be pre-empted whenever it allocates some memory,+      which unfortunately means that tight loops which do no+      allocation tend to lock out other threads (this only seems to+      happen with pathological benchmark-style code, however).++      The rescheduling timer runs on a 20ms granularity by+      default, but this may be altered using the+      @-i\<n\>@ RTS option.  After a rescheduling+      \"tick\" the running thread is pre-empted as soon as+      possible.++      One final note: the+      @aaaa@ @bbbb@ example may not+      work too well on GHC (see Scheduling, above), due+      to the locking on a 'System.IO.Handle'.  Only one thread+      may hold the lock on a 'System.IO.Handle' at any one+      time, so if a reschedule happens while a thread is holding the+      lock, the other thread won't be able to run.  The upshot is that+      the switch from @aaaa@ to+      @bbbbb@ happens infrequently.  It can be+      improved by lowering the reschedule tick period.  We also have a+      patch that causes a reschedule whenever a thread waiting on a+      lock is woken up, but haven't found it to be useful for anything+      other than this example :-)+-}++{- $deadlock++GHC attempts to detect when threads are deadlocked using the garbage+collector.  A thread that is not reachable (cannot be found by+following pointers from live objects) must be deadlocked, and in this+case the thread is sent an exception.  The exception is either+'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM',+'NonTermination', or 'Deadlock', depending on the way in which the+thread is deadlocked.++Note that this feature is intended for debugging, and should not be+relied on for the correct operation of your program.  There is no+guarantee that the garbage collector will be accurate enough to detect+your deadlock, and no guarantee that the garbage collector will run in+a timely enough manner.  Basically, the same caveats as for finalizers+apply to deadlock detection.++There is a subtle interaction between deadlock detection and+finalizers (as created by 'GHC.Foreign.Concurrent.newForeignPtr' or the+functions in "System.Mem.Weak"): if a thread is blocked waiting for a+finalizer to run, then the thread will be considered deadlocked and+sent an exception.  So preferably don't do this, but if you have no+alternative then it is possible to prevent the thread from being+considered deadlocked by making a 'StablePtr' pointing to it.  Don't+forget to release the 'StablePtr' later with 'freeStablePtr'.+-}
+ src/Control/Concurrent/Chan.hs view
@@ -0,0 +1,143 @@+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE CPP #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Concurrent.Chan+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (concurrency)+--+-- Unbounded channels.+--+-- The channels are implemented with 'Control.Concurrent.MVar's and therefore inherit all the+-- caveats that apply to @MVar@s (possibility of races, deadlocks etc). The+-- @stm@ (software transactional memory) library has a more robust implementation+-- of channels called @TChan@s.+--+-----------------------------------------------------------------------------++module Control.Concurrent.Chan+  (+          -- * The 'Chan' type+        Chan,                   -- abstract++          -- * Operations+        newChan,+        writeChan,+        readChan,+        dupChan,++          -- * Stream interface+        getChanContents,+        writeList2Chan,+   ) where++import Prelude+import System.IO.Unsafe         ( unsafeInterleaveIO )+import GHC.Internal.Control.Concurrent.MVar+import GHC.Internal.Control.Exception (mask_)++#define _UPK_(x) {-# UNPACK #-} !(x)++-- A channel is represented by two @MVar@s keeping track of the two ends+-- of the channel contents, i.e., the read- and write ends. Empty @MVar@s+-- are used to handle consumers trying to read from an empty channel.++-- |'Chan' is an abstract type representing an unbounded FIFO channel.+data Chan a+ = Chan _UPK_(MVar (Stream a))+        _UPK_(MVar (Stream a)) -- Invariant: the Stream a is always an empty MVar+   deriving Eq -- ^ @since 4.4.0.0++type Stream a = MVar (ChItem a)++data ChItem a = ChItem a _UPK_(Stream a)+  -- benchmarks show that unboxing the MVar here is worthwhile, because+  -- although it leads to higher allocation, the channel data takes up+  -- less space and is therefore quicker to GC.++-- See the Concurrent Haskell paper for a diagram explaining+-- how the different channel operations proceed.++-- @newChan@ sets up the read and write end of a channel by initialising+-- these two @MVar@s with an empty @MVar@.++-- |Build and return a new instance of 'Chan'.+newChan :: IO (Chan a)+newChan = do+   hole  <- newEmptyMVar+   readVar  <- newMVar hole+   writeVar <- newMVar hole+   return (Chan readVar writeVar)++-- To put an element on a channel, a new hole at the write end is created.+-- What was previously the empty @MVar@ at the back of the channel is then+-- filled in with a new stream element holding the entered value and the+-- new hole.++-- |Write a value to a 'Chan'.+writeChan :: Chan a -> a -> IO ()+writeChan (Chan _ writeVar) val = do+  new_hole <- newEmptyMVar+  mask_ $ do+    old_hole <- takeMVar writeVar+    putMVar old_hole (ChItem val new_hole)+    putMVar writeVar new_hole++-- The reason we don't simply do this:+--+--    modifyMVar_ writeVar $ \old_hole -> do+--      putMVar old_hole (ChItem val new_hole)+--      return new_hole+--+-- is because if an asynchronous exception is received after the 'putMVar'+-- completes and before modifyMVar_ installs the new value, it will set the+-- Chan's write end to a filled hole.++-- |Read the next value from the 'Chan'. Blocks when the channel is empty. Since+-- the read end of a channel is an 'MVar', this operation inherits fairness+-- guarantees of 'MVar's (e.g. threads blocked in this operation are woken up in+-- FIFO order).+--+-- Throws 'Control.Exception.BlockedIndefinitelyOnMVar' when the channel is+-- empty and no other thread holds a reference to the channel.+readChan :: Chan a -> IO a+readChan (Chan readVar _) =+  modifyMVar readVar $ \read_end -> do+    (ChItem val new_read_end) <- readMVar read_end+        -- Use readMVar here, not takeMVar,+        -- else dupChan doesn't work+    return (new_read_end, val)++-- |Duplicate a 'Chan': the duplicate channel begins empty, but data written to+-- either channel from then on will be available from both. Hence this creates+-- a kind of broadcast channel, where data written by anyone is seen by+-- everyone else.+--+-- (Note that a duplicated channel is not equal to its original.+-- So: @fmap (c /=) $ dupChan c@ returns @True@ for all @c@.)+dupChan :: Chan a -> IO (Chan a)+dupChan (Chan _ writeVar) = do+   hole       <- readMVar writeVar+   newReadVar <- newMVar hole+   return (Chan newReadVar writeVar)++-- Operators for interfacing with functional streams.++-- |Return a lazy list representing the contents of the supplied+-- 'Chan', much like 'GHC.Internal.System.IO.hGetContents'.+getChanContents :: Chan a -> IO [a]+getChanContents ch+  = unsafeInterleaveIO (do+        x  <- readChan ch+        xs <- getChanContents ch+        return (x:xs)+    )++-- |Write an entire list of items to a 'Chan'.+writeList2Chan :: Chan a -> [a] -> IO ()+writeList2Chan ch ls = sequence_ (map (writeChan ch) ls)
+ src/Control/Concurrent/MVar.hs view
@@ -0,0 +1,149 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Control.Concurrent.MVar+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (concurrency)+--+-- An @'MVar' t@ is a mutable location that is either empty or contains a+-- value of type @t@.  It has two fundamental operations: 'putMVar'+-- which fills an 'MVar' if it is empty and blocks otherwise, and+-- 'takeMVar' which empties an 'MVar' if it is full and blocks+-- otherwise.  They can be used in multiple different ways:+--+--   1. As synchronized mutable variables,+--+--   2. As channels, with 'takeMVar' and 'putMVar' as receive and send, and+--+--   3. As a binary semaphore @'MVar' ()@, with 'takeMVar' and 'putMVar' as+--      wait and signal.+--+-- They were introduced in the paper+-- ["Concurrent Haskell"](https://www.microsoft.com/en-us/research/wp-content/uploads/1996/01/concurrent-haskell.pdf)+-- by Simon Peyton Jones, Andrew Gordon and Sigbjorn Finne, though+-- some details of their implementation have since then changed (in+-- particular, a put on a full 'MVar' used to error, but now merely+-- blocks.)+--+-- === Applicability+--+-- 'MVar's offer more flexibility than 'Data.IORef.IORef's, but less flexibility+-- than 'GHC.Conc.STM'.  They are appropriate for building synchronization+-- primitives and performing simple inter-thread communication; however+-- they are very simple and susceptible to race conditions, deadlocks or+-- uncaught exceptions.  Do not use them if you need to perform larger+-- atomic operations such as reading from multiple variables: use 'GHC.Conc.STM'+-- instead.+--+-- In particular, the "bigger" functions in this module ('swapMVar',+-- 'withMVar', 'modifyMVar_' and 'modifyMVar') are simply+-- the composition of a 'takeMVar' followed by a 'putMVar' with+-- exception safety.+-- These have atomicity guarantees only if all other threads+-- perform a 'takeMVar' before a 'putMVar' as well;  otherwise, they may+-- block.+--+-- === Fairness+--+-- No thread can be blocked indefinitely on an 'MVar' unless another+-- thread holds that 'MVar' indefinitely.  One usual implementation of+-- this fairness guarantee is that threads blocked on an 'MVar' are+-- served in a first-in-first-out fashion (this is what GHC does),+-- but this is not guaranteed in the semantics.+--+-- === Gotchas+--+-- Like many other Haskell data structures, 'MVar's are lazy.  This+-- means that if you place an expensive unevaluated thunk inside an+-- 'MVar', it will be evaluated by the thread that consumes it, not the+-- thread that produced it.  Be sure to 'evaluate' values to be placed+-- in an 'MVar' to the appropriate normal form, or utilize a strict+-- @MVar@ provided by the [strict-concurrency](https://hackage.haskell.org/package/strict-concurrency) package.+--+-- === Ordering+--+-- 'MVar' operations are always observed to take place in the order+-- they are written in the program, regardless of the memory model of+-- the underlying machine.  This is in contrast to 'Data.IORef.IORef' operations+-- which may appear out-of-order to another thread in some cases.+--+-- === Example+--+-- Consider the following concurrent data structure, a skip channel.+-- This is a channel for an intermittent source of high bandwidth+-- information (for example, mouse movement events.)  Writing to the+-- channel never blocks, and reading from the channel only returns the+-- most recent value, or blocks if there are no new values.  Multiple+-- readers are supported with a @dupSkipChan@ operation.+--+-- A skip channel is a pair of 'MVar's. The first 'MVar' contains the+-- current value, and a list of semaphores that need to be notified+-- when it changes. The second 'MVar' is a semaphore for this particular+-- reader: it is full if there is a value in the channel that this+-- reader has not read yet, and empty otherwise.+--+-- @+-- data SkipChan a = SkipChan (MVar (a, [MVar ()])) (MVar ())+--+-- newSkipChan :: IO (SkipChan a)+-- newSkipChan = do+--     sem <- newEmptyMVar+--     main <- newMVar (undefined, [sem])+--     return (SkipChan main sem)+--+-- putSkipChan :: SkipChan a -> a -> IO ()+-- putSkipChan (SkipChan main _) v = do+--     (_, sems) <- takeMVar main+--     putMVar main (v, [])+--     mapM_ (\\sem -> putMVar sem ()) sems+--+-- getSkipChan :: SkipChan a -> IO a+-- getSkipChan (SkipChan main sem) = do+--     takeMVar sem+--     (v, sems) <- takeMVar main+--     putMVar main (v, sem : sems)+--     return v+--+-- dupSkipChan :: SkipChan a -> IO (SkipChan a)+-- dupSkipChan (SkipChan main _) = do+--     sem <- newEmptyMVar+--     (v, sems) <- takeMVar main+--     putMVar main (v, sem : sems)+--     return (SkipChan main sem)+-- @+--+-- This example was adapted from the original Concurrent Haskell paper.+-- For more examples of 'MVar's being used to build higher-level+-- synchronization primitives, see 'Control.Concurrent.Chan' and+-- 'Control.Concurrent.QSem'.+--++module Control.Concurrent.MVar+    (-- *  @MVar@s+     MVar,+     newEmptyMVar,+     newMVar,+     takeMVar,+     putMVar,+     readMVar,+     swapMVar,+     tryTakeMVar,+     tryPutMVar,+     isEmptyMVar,+     withMVar,+     withMVarMasked,+     modifyMVar_,+     modifyMVar,+     modifyMVarMasked_,+     modifyMVarMasked,+     tryReadMVar,+     mkWeakMVar,+     addMVarFinalizer+     ) where++import GHC.Internal.Control.Concurrent.MVar
+ src/Control/Concurrent/QSem.hs view
@@ -0,0 +1,130 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE BangPatterns #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Concurrent.QSem+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (concurrency)+--+-- Simple quantity semaphores.+--+-----------------------------------------------------------------------------++module Control.Concurrent.QSem+        ( -- * Simple Quantity Semaphores+          QSem,         -- abstract+          newQSem,      -- :: Int  -> IO QSem+          waitQSem,     -- :: QSem -> IO ()+          signalQSem    -- :: QSem -> IO ()+        ) where++import Prelude+import GHC.Internal.Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar, tryTakeMVar+                          , putMVar, newMVar, tryPutMVar)+import GHC.Internal.Control.Exception+import GHC.Internal.Data.Maybe++-- | 'QSem' is a quantity semaphore in which the resource is acquired+-- and released in units of one. It provides guaranteed FIFO ordering+-- for satisfying blocked `waitQSem` calls.+--+-- The pattern+--+-- > bracket_ waitQSem signalQSem (...)+--+-- is safe; it never loses a unit of the resource.+--+newtype QSem = QSem (MVar (Int, [MVar ()], [MVar ()]))++-- The semaphore state (i, xs, ys):+--+--   i is the current resource value+--+--   (xs,ys) is the queue of blocked threads, where the queue is+--           given by xs ++ reverse ys.  We can enqueue new blocked threads+--           by consing onto ys, and dequeue by removing from the head of xs.+--+-- A blocked thread is represented by an empty (MVar ()).  To unblock+-- the thread, we put () into the MVar.+--+-- A thread can dequeue itself by also putting () into the MVar, which+-- it must do if it receives an exception while blocked in waitQSem.+-- This means that when unblocking a thread in signalQSem we must+-- first check whether the MVar is already full; the MVar lock on the+-- semaphore itself resolves race conditions between signalQSem and a+-- thread attempting to dequeue itself.++-- |Build a new 'QSem' with a supplied initial quantity.+--  The initial quantity must be at least 0.+newQSem :: Int -> IO QSem+newQSem initial+  | initial < 0 = fail "newQSem: Initial quantity must be non-negative"+  | otherwise   = do+      sem <- newMVar (initial, [], [])+      return (QSem sem)++-- |Wait for a unit to become available.+waitQSem :: QSem -> IO ()+waitQSem (QSem m) =+  mask_ $ do+    (i,b1,b2) <- takeMVar m+    if i == 0+       then do+         b <- newEmptyMVar+         putMVar m (i, b1, b:b2)+         wait b+       else do+         let !z = i-1+         putMVar m (z, b1, b2)+         return ()+  where+    wait b = takeMVar b `onException`+                (uninterruptibleMask_ $ do -- Note [signal uninterruptible]+                   (i,b1,b2) <- takeMVar m+                   r <- tryTakeMVar b+                   r' <- if isJust r+                            then signal (i,b1,b2)+                            else do putMVar b (); return (i,b1,b2)+                   putMVar m r')++-- |Signal that a unit of the 'QSem' is available.+signalQSem :: QSem -> IO ()+signalQSem (QSem m) =+  uninterruptibleMask_ $ do -- Note [signal uninterruptible]+    r <- takeMVar m+    r' <- signal r+    putMVar m r'++-- Note [signal uninterruptible]+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+--   If we have+--+--      bracket waitQSem signalQSem (...)+--+--   and an exception arrives at the signalQSem, then we must not lose+--   the resource.  The signalQSem is masked by bracket, but taking+--   the MVar might block, and so it would be interruptible.  Hence we+--   need an uninterruptibleMask here.+--+--   This isn't ideal: during high contention, some threads won't be+--   interruptible.  The QSemSTM implementation has better behaviour+--   here, but it performs much worse than this one in some+--   benchmarks.++signal :: (Int,[MVar ()],[MVar ()]) -> IO (Int,[MVar ()],[MVar ()])+signal (i,a1,a2) =+ if i == 0+   then loop a1 a2+   else let !z = i+1 in return (z, a1, a2)+ where+   loop [] [] = return (1, [], [])+   loop [] b2 = loop (reverse b2) []+   loop (b:bs) b2 = do+     r <- tryPutMVar b ()+     if r then return (0, bs, b2)+          else loop bs b2
+ src/Control/Concurrent/QSemN.hs view
@@ -0,0 +1,132 @@+{-# LANGUAGE Trustworthy #-}+{-# OPTIONS_GHC -funbox-strict-fields #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Concurrent.QSemN+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (concurrency)+--+-- Quantity semaphores in which each thread may wait for an arbitrary+-- \"amount\".+--+-----------------------------------------------------------------------------++module Control.Concurrent.QSemN+        (  -- * General Quantity Semaphores+          QSemN,        -- abstract+          newQSemN,     -- :: Int   -> IO QSemN+          waitQSemN,    -- :: QSemN -> Int -> IO ()+          signalQSemN   -- :: QSemN -> Int -> IO ()+      ) where++import Prelude+import GHC.Internal.Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar+                          , tryPutMVar, isEmptyMVar)+import GHC.Internal.Control.Exception+import GHC.Internal.Control.Monad (when)+import GHC.Internal.Data.IORef (IORef, newIORef, atomicModifyIORef)+import System.IO.Unsafe (unsafePerformIO)++-- | 'QSemN' is a quantity semaphore in which the resource is acquired+-- and released in arbitrary amounts. It provides guaranteed FIFO ordering+-- for satisfying blocked `waitQSemN` calls.+--+-- The pattern+--+-- > bracket_ (waitQSemN n) (signalQSemN n) (...)+--+-- is safe; it never loses any of the resource.+--+data QSemN = QSemN !(IORef (Int, [(Int, MVar ())], [(Int, MVar ())]))++-- The semaphore state (i, xs, ys):+--+--   i is the current resource value+--+--   (xs,ys) is the queue of blocked threads, where the queue is+--           given by xs ++ reverse ys.  We can enqueue new blocked threads+--           by consing onto ys, and dequeue by removing from the head of xs.+--+-- A blocked thread is represented by an empty (MVar ()).  To unblock+-- the thread, we put () into the MVar.+--+-- A thread can dequeue itself by also putting () into the MVar, which+-- it must do if it receives an exception while blocked in waitQSemN.+-- This means that when unblocking a thread in signalQSemN we must+-- first check whether the MVar is already full.++-- |Build a new 'QSemN' with a supplied initial quantity.+--  The initial quantity must be at least 0.+newQSemN :: Int -> IO QSemN+newQSemN initial+  | initial < 0 = fail "newQSemN: Initial quantity must be non-negative"+  | otherwise   = do+      sem <- newIORef (initial, [], [])+      return (QSemN sem)++-- An unboxed version of Maybe (MVar a)+data MaybeMV a = JustMV !(MVar a) | NothingMV++-- |Wait for the specified quantity to become available.+waitQSemN :: QSemN -> Int -> IO ()+-- We need to mask here. Once we've enqueued our MVar, we need+-- to be sure to wait for it. Otherwise, we could lose our+-- allocated resource.+waitQSemN qs@(QSemN m) sz = mask_ $ do+    -- unsafePerformIO and not unsafeDupablePerformIO. We must+    -- be sure to wait on the same MVar that gets enqueued.+  mmvar <- atomicModifyIORef m $ \ (i,b1,b2) -> unsafePerformIO $ do+    let z = i-sz+    if z < 0+      then do+        b <- newEmptyMVar+        return ((i, b1, (sz,b):b2), JustMV b)+      else return ((z, b1, b2), NothingMV)++  -- Note: this case match actually allocates the MVar if necessary.+  case mmvar of+    NothingMV -> return ()+    JustMV b -> wait b+  where+    wait :: MVar () -> IO ()+    wait b =+      takeMVar b `onException` do+        already_filled <- not <$> tryPutMVar b ()+        when already_filled $ signalQSemN qs sz++-- |Signal that a given quantity is now available from the 'QSemN'.+signalQSemN :: QSemN -> Int -> IO ()+-- We don't need to mask here because we should *already* be masked+-- here (e.g., by bracket). Indeed, if we're not already masked,+-- it's too late to do so.+--+-- What if the unsafePerformIO thunk is forced in another thread,+-- and receives an asynchronous exception? That shouldn't be a+-- problem: when we force it ourselves, presumably masked, we+-- will resume its execution.+signalQSemN (QSemN m) sz0 = do+    -- unsafePerformIO and not unsafeDupablePerformIO. We must not+    -- wake up more threads than we're supposed to.+  unit <- atomicModifyIORef m $ \(i,a1,a2) ->+            unsafePerformIO (loop (sz0 + i) a1 a2)++  -- Forcing this will actually wake the necessary threads.+  evaluate unit+ where+   loop 0  bs b2 = return ((0,  bs, b2), ())+   loop sz [] [] = return ((sz, [], []), ())+   loop sz [] b2 = loop sz (reverse b2) []+   loop sz ((j,b):bs) b2+     | j > sz = do+       r <- isEmptyMVar b+       if r then return ((sz, (j,b):bs, b2), ())+            else loop sz bs b2+     | otherwise = do+       r <- tryPutMVar b ()+       if r then loop (sz-j) bs b2+            else loop sz bs b2
+ src/Control/Exception.hs view
@@ -0,0 +1,332 @@+{-# LANGUAGE Trustworthy #-}++-- |+--+-- Module      :  Control.Exception+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (extended exceptions)+--+-- This module provides support for raising and catching both built-in+-- and user-defined exceptions.+--+-- In addition to exceptions thrown by 'IO' operations, exceptions may+-- be thrown by pure code (imprecise exceptions) or by external events+-- (asynchronous exceptions), but may only be caught in the 'IO' monad.+-- For more details, see:+--+--  * /A semantics for imprecise exceptions/, by Simon Peyton Jones,+--    Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,+--    in /PLDI'99/.+--+--  * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton+--    Jones, Andy Moran and John Reppy, in /PLDI'01/.+--+--  * /An Extensible Dynamically-Typed Hierarchy of Exceptions/,+--    by Simon Marlow, in /Haskell '06/.+--++module Control.Exception+    (-- * The 'SomeException' type+     SomeException(..),+     -- ** The 'Exception' class+     Exception(..),+     addExceptionContext,+     someExceptionContext,+     annotateIO,+     NoBacktrace(..),+     ExceptionWithContext(..),+     WhileHandling(..),++     -- * Concrete exception types+     IOException,+     ArithException(..),+     ArrayException(..),+     AssertionFailed(..),+     NoMethodError(..),+     PatternMatchFail(..),+     RecConError(..),+     RecSelError(..),+     RecUpdError(..),+     ErrorCall(..),+     TypeError(..),+     -- ** Asynchronous exceptions+     SomeAsyncException(..),+     AsyncException(..),+     asyncExceptionToException,+     asyncExceptionFromException,+     NonTermination(..),+     NestedAtomically(..),+     BlockedIndefinitelyOnMVar(..),+     BlockedIndefinitelyOnSTM(..),+     AllocationLimitExceeded(..),+     CompactionFailed(..),+     Deadlock(..),+     -- *  Throwing exceptions+     throw,+     throwIO,+     rethrowIO,+     ioError,+     throwTo,+     -- *  Catching Exceptions+     -- $catching+     -- **  Catching all exceptions+     -- $catchall+     -- **  The @catch@ functions+     catch,+     catchNoPropagate,+     catches,+     Handler(..),+     catchJust,+     -- **  The @handle@ functions+     handle,+     handleJust,+     -- **  The @try@ functions+     try,+     tryWithContext,+     tryJust,+     -- **  The @evaluate@ function+     evaluate,+     -- **  The @mapException@ function+     mapException,+     -- *  Asynchronous Exceptions+     -- $async+     -- **  Asynchronous exception control+     -- | The following functions allow a thread to control delivery of+     -- asynchronous exceptions during a critical region.+     mask,+     mask_,+     uninterruptibleMask,+     uninterruptibleMask_,+     MaskingState(..),+     getMaskingState,+     interruptible,+     allowInterrupt,+     -- ***  Applying @mask@ to an exception handler+     -- $block_handler+     -- ***  Interruptible operations+     -- $interruptible+     -- *  Assertions+     assert,+     -- *  Utilities+     bracket,+     bracket_,+     bracketOnError,+     finally,+     onException,+     -- ** Printing+     displayExceptionWithInfo++     ) where++import GHC.Internal.Control.Exception+import GHC.Internal.Exception.Type++{- $catching++There are several functions for catching and examining+exceptions; all of them may only be used from within the+'IO' monad.++Here's a rule of thumb for deciding which catch-style function to+use:++ * If you want to do some cleanup in the event that an exception+   is raised, use 'finally', 'bracket' or 'onException'.++ * To recover after an exception and do something else, the best+   choice is to use one of the 'try' family.++ * ... unless you are recovering from an asynchronous exception, in which+   case use 'catch' or 'catchJust'.++The difference between using 'try' and 'catch' for recovery is that in+'catch' the handler is inside an implicit 'mask' (see \"Asynchronous+Exceptions\") which is important when catching asynchronous+exceptions, but when catching other kinds of exception it is+unnecessary.  Furthermore it is possible to accidentally stay inside+the implicit 'mask' by tail-calling rather than returning from the+handler, which is why we recommend using 'try' rather than 'catch' for+ordinary exception recovery.++A typical use of 'tryJust' for recovery looks like this:++>  do r <- tryJust (guard . isDoesNotExistError) $ getEnv "HOME"+>     case r of+>       Left  e    -> ...+>       Right home -> ...++-}++{- $async++ #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to+external influences, and can be raised at any point during execution.+'StackOverflow' and 'HeapOverflow' are two examples of+system-generated asynchronous exceptions.++The primary source of asynchronous exceptions, however, is+'throwTo':++>  throwTo :: ThreadId -> Exception -> IO ()++'throwTo' (also 'Control.Concurrent.killThread') allows one+running thread to raise an arbitrary exception in another thread.  The+exception is therefore asynchronous with respect to the target thread,+which could be doing anything at the time it receives the exception.+Great care should be taken with asynchronous exceptions; it is all too+easy to introduce race conditions by the over zealous use of+'throwTo'.+-}++{- $block_handler+There\'s an implied 'mask' around every exception handler in a call+to one of the 'catch' family of functions.  This is because that is+what you want most of the time - it eliminates a common race condition+in starting an exception handler, because there may be no exception+handler on the stack to handle another exception if one arrives+immediately.  If asynchronous exceptions are masked on entering the+handler, though, we have time to install a new exception handler+before being interrupted.  If this weren\'t the default, one would have+to write something like++>      mask $ \restore ->+>           catch (restore (...))+>                 (\e -> handler)++If you need to unmask asynchronous exceptions again in the exception+handler, @restore@ can be used there too.++Note that 'try' and friends /do not/ have a similar default, because+there is no exception handler in this case.  Don't use 'try' for+recovering from an asynchronous exception.+-}++{- $interruptible++ #interruptible#+Some operations are /interruptible/, which means that they can receive+asynchronous exceptions even in the scope of a 'mask'.  Any function+which may itself block is defined as interruptible; this includes+'Control.Concurrent.MVar.takeMVar'+(but not 'Control.Concurrent.MVar.tryTakeMVar'),+and most operations which perform+some I\/O with the outside world.  The reason for having+interruptible operations is so that we can write things like++>      mask $ \restore -> do+>         a <- takeMVar m+>         catch (restore (...))+>               (\e -> ...)++if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,+then this particular+combination could lead to deadlock, because the thread itself would be+blocked in a state where it can\'t receive any asynchronous exceptions.+With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be+safe in the knowledge that the thread can receive exceptions right up+until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.+Similar arguments apply for other interruptible operations like+'System.IO.openFile'.++It is useful to think of 'mask' not as a way to completely prevent+asynchronous exceptions, but as a way to switch from asynchronous mode+to polling mode.  The main difficulty with asynchronous+exceptions is that they normally can occur anywhere, but within a+'mask' an asynchronous exception is only raised by operations that are+interruptible (or call other interruptible operations).  In many cases+these operations may themselves raise exceptions, such as I\/O errors,+so the caller will usually be prepared to handle exceptions arising from the+operation anyway.  To perform an explicit poll for asynchronous exceptions+inside 'mask', use 'allowInterrupt'.++Sometimes it is too onerous to handle exceptions in the middle of a+critical piece of stateful code.  There are three ways to handle this+kind of situation:++ * Use STM.  Since a transaction is always either completely executed+   or not at all, transactions are a good way to maintain invariants+   over state in the presence of asynchronous (and indeed synchronous)+   exceptions.++ * Use 'mask', and avoid interruptible operations.  In order to do+   this, we have to know which operations are interruptible.  It is+   impossible to know for any given library function whether it might+   invoke an interruptible operation internally; so instead we give a+   list of guaranteed-not-to-be-interruptible operations below.++ * Use 'uninterruptibleMask'.  This is generally not recommended,+   unless you can guarantee that any interruptible operations invoked+   during the scope of 'uninterruptibleMask' can only ever block for+   a short time.  Otherwise, 'uninterruptibleMask' is a good way to+   make your program deadlock and be unresponsive to user interrupts.++The following operations are guaranteed not to be interruptible:++ * operations on 'Data.IORef.IORef' from "Data.IORef"++ * STM transactions that do not use 'Conc.retry'++ * everything from the @Foreign@ modules++ * everything from "Control.Exception" except for 'throwTo'++ * 'Control.Concurrent.MVar.tryTakeMVar', 'Control.Concurrent.MVar.tryPutMVar',+   'Control.Concurrent.MVar.isEmptyMVar'++ * 'Control.Concurrent.MVar.takeMVar' if the 'Control.Concurrent.MVar.MVar' is+   definitely full, and conversely 'Control.Concurrent.MVar.putMVar' if the+   'Control.Concurrent.MVar.MVar' is definitely empty++ * 'Control.Concurrent.MVar.newEmptyMVar', 'Control.Concurrent.MVar.newMVar'++ * 'Control.Concurrent.forkIO', 'Control.Concurrent.myThreadId'++-}++{- $catchall++It is possible to catch all exceptions, by using the type 'SomeException':++> catch f (\e -> ... (e :: SomeException) ...)++HOWEVER, this is normally not what you want to do!++For example, suppose you want to read a file, but if it doesn't exist+then continue as if it contained \"\".  You might be tempted to just+catch all exceptions and return \"\" in the handler. However, this has+all sorts of undesirable consequences.  For example, if the user+presses control-C at just the right moment then the 'UserInterrupt'+exception will be caught, and the program will continue running under+the belief that the file contains \"\".  Similarly, if another thread+tries to kill the thread reading the file then the 'ThreadKilled'+exception will be ignored.++Instead, you should only catch exactly the exceptions that you really+want. In this case, this would likely be more specific than even+\"any IO exception\"; a permissions error would likely also want to be+handled differently. Instead, you would probably want something like:++> e <- tryJust (guard . isDoesNotExistError) (readFile f)+> let str = either (const "") id e++There are occasions when you really do need to catch any sort of+exception. However, in most cases this is just so you can do some+cleaning up; you aren't actually interested in the exception itself.+For example, if you open a file then you want to close it again,+whether processing the file executes normally or throws an exception.+However, in these cases you can use functions like 'bracket', 'finally'+and 'onException', which never actually pass you the exception, but+just call the cleanup functions at the appropriate points.++But sometimes you really do need to catch any exception, and actually+see what the exception is. One example is at the very top-level of a+program, you may wish to catch any exception, print it to a logfile or+the screen, and then exit gracefully. For these cases, you can use+'catch' (or one of the other exception-catching functions) with the+'SomeException' type.+-}+
+ src/Control/Exception/Annotation.hs view
@@ -0,0 +1,18 @@+-- |+-- Module      :  Control.Exception.Annotation+-- Copyright   :  (c) The University of Glasgow, 1998-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  cvs-ghc@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Exception annotations.+--+module Control.Exception.Annotation+    ( SomeExceptionAnnotation(..)+    , ExceptionAnnotation(..)+    ) where++import GHC.Internal.Exception.Context+
+ src/Control/Exception/Backtrace.hs view
@@ -0,0 +1,59 @@+-- |+-- Module      :  Control.Exception.Backtrace+-- Copyright   :  (c) The University of Glasgow 1994-2023+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- This module provides the 'Backtrace'\ s type, which provides a+-- common representation for backtrace information which can be, e.g., attached+-- to exceptions (via the 'Control.Exception.Context.ExceptionContext' facility).+-- These backtraces preserve useful context about the execution state of the program+-- using a variety of means; we call these means *backtrace mechanisms*.+--+-- We currently support four backtrace mechanisms:+--+--  - 'CostCentreBacktrace' captures the current cost-centre stack+--    using 'GHC.Stack.CCS.getCurrentCCS'.+--  - 'HasCallStackBacktrace' captures the 'HasCallStack' 'CallStack'.+--  - 'ExecutionBacktrace' captures the execution stack, unwound and resolved+--    to symbols via DWARF debug information.+--  - 'IPEBacktrace' captures the execution stack, resolved to names via info-table+--    provenance information.+--+-- Each of these are useful in different situations. While 'CostCentreBacktrace's are+-- readily mapped back to the source program, they require that the program be instrumented+-- with cost-centres, incurring runtime cost. Similarly, 'HasCallStackBacktrace's require that+-- the program be manually annotated with 'HasCallStack' constraints.+--+-- By contrast, 'IPEBacktrace's incur no runtime instrumentation but require that (at least+-- some subset of) the program be built with GHC\'s @-finfo-table-map@ flag. Moreover, because+-- info-table provenance information is derived after optimisation, it may be harder to relate+-- back to the structure of the source program.+--+-- 'ExecutionBacktrace's are similar to 'IPEBacktrace's but use DWARF stack unwinding+-- and symbol resolution; this allows for useful backtraces even in the presence+-- of foreign calls, both into and out of Haskell. However, for robust stack unwinding+-- the entirety of the program (and its dependencies, both Haskell and native) must+-- be compiled with debugging information (e.g. using GHC\'s @-g@ flag).+++-- Note [Backtrace mechanisms]+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~+-- See module docstring above.+++module Control.Exception.Backtrace+    ( -- * Backtrace mechanisms+      BacktraceMechanism(..)+    , getBacktraceMechanismState+    , setBacktraceMechanismState+      -- * Collecting backtraces+    , Backtraces+    , displayBacktraces+    , collectBacktraces+    ) where++import GHC.Internal.Exception.Backtrace
+ src/Control/Exception/Base.hs view
@@ -0,0 +1,93 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Control.Exception.Base+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (extended exceptions)+--+-- Extensible exceptions, except for multiple handlers.+--++module Control.Exception.Base+    (-- *  The Exception type+     SomeException(..),+     Exception(..),+     IOException,+     ArithException(..),+     ArrayException(..),+     AssertionFailed(..),+     SomeAsyncException(..),+     AsyncException(..),+     asyncExceptionToException,+     asyncExceptionFromException,+     NonTermination(..),+     NestedAtomically(..),+     BlockedIndefinitelyOnMVar(..),+     FixIOException(..),+     BlockedIndefinitelyOnSTM(..),+     AllocationLimitExceeded(..),+     CompactionFailed(..),+     Deadlock(..),+     NoMethodError(..),+     PatternMatchFail(..),+     RecConError(..),+     RecSelError(..),+     RecUpdError(..),+     ErrorCall(..),+     TypeError(..),+     NoMatchingContinuationPrompt(..),+     -- *  Throwing exceptions+     throwIO,+     throw,+     ioError,+     throwTo,+     -- *  Catching Exceptions+     -- **  The @catch@ functions+     catch,+     catchJust,+     -- **  The @handle@ functions+     handle,+     handleJust,+     -- **  The @try@ functions+     try,+     tryJust,+     onException,+     -- **  The @evaluate@ function+     evaluate,+     -- **  The @mapException@ function+     mapException,+     -- *  Asynchronous Exceptions+     -- **  Asynchronous exception control+     mask,+     mask_,+     uninterruptibleMask,+     uninterruptibleMask_,+     MaskingState(..),+     getMaskingState,+     -- *  Assertions+     assert,+     -- *  Utilities+     bracket,+     bracket_,+     bracketOnError,+     finally,+     -- *  Calls for GHC runtime+     recSelError,+     recConError,+     impossibleError,+     impossibleConstraintError,+     nonExhaustiveGuardsError,+     patError,+     noMethodBindingError,+     typeError,+     nonTermination,+     nestedAtomically,+     noMatchingContinuationPrompt+     ) where++import GHC.Internal.Control.Exception.Base
+ src/Control/Exception/Context.hs view
@@ -0,0 +1,22 @@+-- |+-- Module      :  Control.Exception.Context+-- Copyright   :  (c) The University of Glasgow, 1998-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  cvs-ghc@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Exception context and annotations.+--+module Control.Exception.Context+    ( ExceptionContext(..)+    , emptyExceptionContext+    , addExceptionAnnotation+      -- * Destructuring+    , getExceptionAnnotations+    , getAllExceptionAnnotations+    , displayExceptionContext+    ) where++import GHC.Internal.Exception.Context
+ src/Control/Monad.hs view
@@ -0,0 +1,89 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Control.Monad+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- The 'Functor', 'Monad' and 'MonadPlus' classes,+-- with some useful operations on monads.++module Control.Monad+    (-- *  Functor and monad classes+     Functor(..),+     Monad((>>=), (>>), return),+     MonadFail(fail),+     MonadPlus(mzero, mplus),+     -- *  Functions+     -- **  Naming conventions+     -- $naming+     -- **  Basic @Monad@ functions+     mapM,+     mapM_,+     forM,+     forM_,+     sequence,+     sequence_,+     (=<<),+     (>=>),+     (<=<),+     forever,+     void,+     -- **  Generalisations of list functions+     join,+     msum,+     mfilter,+     filterM,+     mapAndUnzipM,+     zipWithM,+     zipWithM_,+     foldM,+     foldM_,+     replicateM,+     replicateM_,+     -- **  Conditional execution of monadic expressions+     guard,+     when,+     unless,+     -- **  Monadic lifting operators+     liftM,+     liftM2,+     liftM3,+     liftM4,+     liftM5,+     ap,+     -- **  Strict monadic functions+     (<$!>)+     ) where++import GHC.Internal.Control.Monad++{- $naming++The functions in this module use the following naming conventions:++* A postfix \'@M@\' always stands for a function in the Kleisli category:+  The monad type constructor @m@ is added to function results+  (modulo currying) and nowhere else.  So, for example,++> filter  ::              (a ->   Bool) -> [a] ->   [a]+> filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]++* A postfix \'@_@\' changes the result type from @(m a)@ to @(m ())@.+  Thus, for example:++> sequence  :: Monad m => [m a] -> m [a]+> sequence_ :: Monad m => [m a] -> m ()++* A prefix \'@m@\' generalizes an existing function to a monadic form.+  Thus, for example:++> filter  ::                (a -> Bool) -> [a] -> [a]+> mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a++-}
+ src/Control/Monad/Fail.hs view
@@ -0,0 +1,43 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Control.Monad.Fail+-- Copyright   :  (C) 2015 David Luposchainsky,+--                (C) 2015 Herbert Valerio Riedel+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Transitional module providing the 'MonadFail' class and primitive+-- instances.+--+-- This module can be imported for defining forward compatible+-- 'MonadFail' instances:+--+-- @+-- import qualified Control.Monad.Fail as Fail+--+-- instance Monad Foo where+--   (>>=) = {- ...bind impl... -}+--+--   -- Provide legacy 'fail' implementation for when+--   -- new-style MonadFail desugaring is not enabled.+--   fail = Fail.fail+--+-- instance Fail.MonadFail Foo where+--   fail = {- ...fail implementation... -}+-- @+--+-- See <https://gitlab.haskell.org/haskell/prime/-/wikis/libraries/proposals/monad-fail>+-- for more details.+--+-- @since 4.9.0.0+--++module Control.Monad.Fail+    (MonadFail(fail)) where++import GHC.Internal.Control.Monad.Fail
+ src/Control/Monad/Fix.hs view
@@ -0,0 +1,121 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Control.Monad.Fix+-- Copyright   :  (c) Andy Gill 2001,+--                (c) Oregon Graduate Institute of Science and Technology, 2002+-- License     :  BSD-style (see the file libraries/base/LICENSE)+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Monadic fixpoints, used for desugaring of @{-# LANGUAGE RecursiveDo #-}@.+--+-- Consider the generalized version of so-called @repmin@+-- (/replace with minimum/) problem:+-- accumulate elements of a container into a 'Monoid'+-- and modify each element using the final accumulator.+--+-- @+-- repmin+--   :: (Functor t, Foldable t, Monoid b)+--   => (a -> b) -> (a -> b -> c) -> t a -> t c+-- repmin f g as = fmap (\`g\` foldMap f as) as+-- @+--+-- The naive implementation as above makes two traversals. Can we do better+-- and achieve the goal in a single pass? It's seemingly impossible, because we would+-- have to know the future,+-- but lazy evaluation comes to the rescue:+--+-- @+-- import Data.Traversable (mapAccumR)+--+-- repmin+--   :: (Traversable t, Monoid b)+--   => (a -> b) -> (a -> b -> c) -> t a -> t c+-- repmin f g as =+--   let (b, cs) = mapAccumR (\\acc a -> (f a <> acc, g a b)) mempty as in cs+-- @+--+-- How can we check that @repmin@ indeed traverses only once?+-- Let's run it on an infinite input:+--+-- >>> import Data.Monoid (All(..))+-- >>> take 3 $ repmin All (const id) ([True, True, False] ++ undefined)+-- [All {getAll = False},All {getAll = False},All {getAll = False}]+--+-- So far so good, but can we generalise @g@ to return a monadic value @a -> b -> m c@?+-- The following does not work, complaining that @b@ is not in scope:+--+-- @+-- import Data.Traversable (mapAccumM)+--+-- repminM+--   :: (Traversable t, Monoid b, Monad m)+--   => (a -> b) -> (a -> b -> m c) -> t a -> m (t c)+-- repminM f g as = do+--   (b, cs) \<- mapAccumM (\\acc a -> (f a <> acc,) \<$\> g a b) mempty as+--   pure cs+-- @+--+-- To solve the riddle, let's rewrite @repmin@ via 'fix':+--+-- @+-- repmin+--   :: (Traversable t, Monoid b)+--   => (a -> b) -> (a -> b -> c) -> t a -> t c+-- repmin f g as = snd $ fix $+--   \\(b, cs) -> mapAccumR (\\acc a -> (f a <> acc, g a b)) mempty as+-- @+--+-- Now we can replace 'fix' with 'mfix' to obtain the solution:+--+-- @+-- repminM+--   :: (Traversable t, Monoid b, MonadFix m)+--   => (a -> b) -> (a -> b -> m c) -> t a -> m (t c)+-- repminM f g as = fmap snd $ mfix $+--   \\(~(b, cs)) -> mapAccumM (\\acc a -> (f a <> acc,) \<$\> g a b) mempty as+-- @+--+-- For example,+--+-- >>> import Data.Monoid (Sum(..))+-- >>> repminM Sum (\a b -> print a >> pure (a + getSum b)) [3, 5, 2]+-- 3+-- 5+-- 2+-- [13,15,12]+--+-- Incredibly, GHC is capable to do this transformation automatically,+-- when @{-# LANGUAGE RecursiveDo #-}@ is enabled. Namely, the following+-- implementation of @repminM@ works (note @mdo@ instead of @do@):+--+-- @+-- {-# LANGUAGE RecursiveDo #-}+--+-- repminM+--   :: (Traversable t, Monoid b, MonadFix m)+--   => (a -> b) -> (a -> b -> m c) -> t a -> m (t c)+-- repminM f g as = mdo+--   (b, cs) \<- mapAccumM (\\acc a -> (f a <> acc,) \<$\> g a b) mempty as+--   pure cs+-- @+--+-- Further reading:+--+-- * GHC User’s Guide, The recursive do-notation.+-- * Haskell Wiki, <https://wiki.haskell.org/MonadFix MonadFix>.+-- * Levent Erkök, <https://leventerkok.github.io/papers/erkok-thesis.pdf Value recursion in monadic computations>, Oregon Graduate Institute, 2002.+-- * Levent Erkök, John Launchbury, <https://leventerkok.github.io/papers/recdo.pdf A recursive do for Haskell>, Haskell '02, 29-37, 2002.+-- * Richard S. Bird, <https://doi.org/10.1007/BF00264249 Using circular programs to eliminate multiple traversals of data>, Acta Informatica 21, 239-250, 1984.+-- * Jasper Van der Jeugt, <https://jaspervdj.be/posts/2023-07-22-lazy-layout.html Lazy layout>, 2023.++module Control.Monad.Fix+    (MonadFix(mfix),+     fix+     ) where++import GHC.Internal.Control.Monad.Fix
+ src/Control/Monad/IO/Class.hs view
@@ -0,0 +1,21 @@+{-# LANGUAGE Trustworthy #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Monad.IO.Class+-- Copyright   :  (c) Andy Gill 2001,+--                (c) Oregon Graduate Institute of Science and Technology, 2001+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  R.Paterson@city.ac.uk+-- Stability   :  stable+-- Portability :  portable+--+-- Class of monads based on @IO@.+-----------------------------------------------------------------------------++module Control.Monad.IO.Class+  ( MonadIO(..) )+  where++import GHC.Internal.Control.Monad.IO.Class
+ src/Control/Monad/Instances.hs view
@@ -0,0 +1,24 @@+{-# LANGUAGE Trustworthy #-}++-- |+--+-- Module      :  Control.Monad.Instances+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- /This module is DEPRECATED and will be removed in the future!/+--+-- 'Functor' and 'Monad' instances for @(->) r@ and+-- 'Functor' instances for @(,) a@ and @'Either' a@.++module Control.Monad.Instances+    {-# DEPRECATED "This module now contains no instances and will be removed in the future" #-} -- deprecated in 7.8+    ( Functor(..),+      Monad(..)+    ) where++import GHC.Internal.Base (Functor(..), Monad(..))
+ src/Control/Monad/ST.hs view
@@ -0,0 +1,31 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Control.Monad.ST+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (requires universal quantification for runST)+--+-- This module provides support for /strict/ state threads, as+-- described in the PLDI \'94 paper by John Launchbury and Simon Peyton+-- Jones /Lazy Functional State Threads/.+--+-- References (variables) that can be used within the @ST@ monad are+-- provided by "Data.STRef", and arrays are provided by+-- [Data.Array.ST](https://hackage.haskell.org/package/array/docs/Data-Array-ST.html).++module Control.Monad.ST+    (-- *  The 'ST' Monad+     ST,+     runST,+     fixST,+     -- *  Converting 'ST' to 'IO'+     RealWorld,+     stToIO+     ) where++import GHC.Internal.Control.Monad.ST
+ src/Control/Monad/ST/Lazy.hs view
@@ -0,0 +1,31 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Control.Monad.ST.Lazy+-- 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.+--++module Control.Monad.ST.Lazy+    (-- *  The 'ST' monad+     ST,+     runST,+     fixST,+     -- *  Converting between strict and lazy 'ST'+     strictToLazyST,+     lazyToStrictST,+     -- *  Converting 'ST' To 'IO'+     RealWorld,+     stToIO+     ) where++import GHC.Internal.Control.Monad.ST.Lazy
+ src/Control/Monad/ST/Lazy/Safe.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE Trustworthy #-}++-- |+--+-- Module      :  Control.Monad.ST.Lazy.Safe+-- 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 'ST' operations until+-- a value depending on them is required.+--+-- Safe API only.+--++module Control.Monad.ST.Lazy.Safe+    {-# DEPRECATED "Safe is now the default, please use GHC.Internal.Control.Monad.ST.Lazy instead" #-}+    (-- *  The 'ST' monad+     ST,+     runST,+     fixST,+     -- *  Converting between strict and lazy 'ST'+     strictToLazyST,+     lazyToStrictST,+     -- *  Converting 'ST' To 'IO'+     RealWorld,+     stToIO+     ) where++import GHC.Internal.Control.Monad.ST.Lazy.Imp
+ src/Control/Monad/ST/Lazy/Unsafe.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE Unsafe #-}++-- |+--+-- Module      :  Control.Monad.ST.Lazy.Unsafe+-- 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 'ST' operations until+-- a value depending on them is required.+--+-- Unsafe API.+--++module Control.Monad.ST.Lazy.Unsafe+    (-- *  Unsafe operations+     unsafeInterleaveST,+     unsafeIOToST+     ) where++import GHC.Internal.Control.Monad.ST.Lazy.Imp
+ src/Control/Monad/ST/Safe.hs view
@@ -0,0 +1,31 @@+{-# LANGUAGE Trustworthy #-}++-- |+--+-- Module      :  Control.Monad.ST.Safe+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (requires universal quantification for runST)+--+-- This module provides support for /strict/ state threads, as+-- described in the PLDI \'94 paper by John Launchbury and Simon Peyton+-- Jones /Lazy Functional State Threads/.+--+-- Safe API Only.+--++module Control.Monad.ST.Safe+    {-# DEPRECATED "Safe is now the default, please use GHC.Internal.Control.Monad.ST instead" #-}+    (-- *  The 'ST' Monad+     ST,+     runST,+     fixST,+     -- *  Converting 'ST' to 'IO'+     RealWorld,+     stToIO+     ) where++import GHC.Internal.Control.Monad.ST.Imp
+ src/Control/Monad/ST/Strict.hs view
@@ -0,0 +1,19 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Control.Monad.ST.Strict+-- 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)+--+-- The strict ST monad (re-export of "Control.Monad.ST")+--++module Control.Monad.ST.Strict+    (module GHC.Internal.Control.Monad.ST) where++import GHC.Internal.Control.Monad.ST
+ src/Control/Monad/ST/Unsafe.hs view
@@ -0,0 +1,28 @@+{-# LANGUAGE Unsafe #-}++-- |+--+-- Module      :  Control.Monad.ST.Unsafe+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (requires universal quantification for runST)+--+-- This module provides support for /strict/ state threads, as+-- described in the PLDI \'94 paper by John Launchbury and Simon Peyton+-- Jones /Lazy Functional State Threads/.+--+-- Unsafe API.+--++module Control.Monad.ST.Unsafe+    (-- *  Unsafe operations+     unsafeInterleaveST,+     unsafeDupableInterleaveST,+     unsafeIOToST,+     unsafeSTToIO+     ) where++import GHC.Internal.Control.Monad.ST.Imp
+ src/Control/Monad/Zip.hs view
@@ -0,0 +1,21 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE TypeOperators #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Control.Monad.Zip+-- Copyright   :  (c) Nils Schweinsberg 2011,+--                (c) George Giorgidze 2011+--                (c) University Tuebingen 2011+-- License     :  BSD-style (see the file libraries/base/LICENSE)+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Monadic zipping (used for monad comprehensions)+--+-----------------------------------------------------------------------------++module Control.Monad.Zip ( MonadZip(..) ) where++import GHC.Internal.Control.Monad.Zip(MonadZip(..))
+ src/Data/Array/Byte.hs view
@@ -0,0 +1,388 @@+-- |+-- Module      : Data.Array.Byte+-- Copyright   : (c) Roman Leshchinskiy 2009-2012+-- License     : BSD-style+--+-- Maintainer  : libraries@haskell.org+-- Portability : non-portable+--+-- Derived from @primitive@ package.++{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE MagicHash #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE UnboxedTuples #-}+{-# LANGUAGE TemplateHaskellQuotes #-}++module Data.Array.Byte (+  ByteArray(..),+  MutableByteArray(..),+) where++import GHC.Internal.Data.Bits ((.&.), unsafeShiftR)+import GHC.Internal.Data.Data (mkNoRepType, Data(..))+import GHC.Internal.Data.Typeable (Typeable)+import qualified GHC.Internal.Data.Foldable as F+import GHC.Internal.Data.Maybe (fromMaybe)+import Data.Semigroup+import GHC.Internal.Exts+import GHC.Num.Integer (Integer(..))+import GHC.Internal.Show (intToDigit)+import GHC.Internal.ST (ST(..), runST)+import GHC.Internal.Word (Word8(..))+import GHC.Internal.TH.Syntax+import GHC.Internal.TH.Lift+import GHC.Internal.ForeignPtr+import Prelude++-- | Lifted wrapper for 'ByteArray#'.+--+-- Since 'ByteArray#' is an unlifted type and not a member of kind 'Data.Kind.Type',+-- things like @[ByteArray#]@ or @IO ByteArray#@ are ill-typed. To work around this+-- inconvenience this module provides a standard lifted wrapper, inhabiting 'Data.Kind.Type'.+-- Clients are expected to use 'ByteArray' in higher-level APIs,+-- but wrap and unwrap 'ByteArray' internally as they please+-- and use functions from "GHC.Exts".+--+-- The memory representation of a 'ByteArray' is:+--+-- > ╭─────────────┬───╮  ╭────────┬──────┬─────────╮+-- > │ Constructor │ * ┼─►│ Header │ Size │ Payload │+-- > ╰─────────────┴───╯  ╰────────┴──────┴─────────╯+--+-- And its overhead is the following:+--+-- * 'ByteArray' constructor: 1 word+-- * Pointer to 'ByteArray#': 1 word+-- * 'ByteArray#' Header: 1 word+-- * 'ByteArray#' Size: 1 word+--+-- Where a word is the unit of heap allocation,+-- measuring 8 bytes on 64-bit systems, and 4 bytes on 32-bit systems.+--+-- @since 4.17.0.0+data ByteArray = ByteArray ByteArray#++-- | Lifted wrapper for 'MutableByteArray#'.+--+-- Since 'MutableByteArray#' is an unlifted type and not a member of kind 'Data.Kind.Type',+-- things like @[MutableByteArray#]@ or @IO MutableByteArray#@ are ill-typed. To work around this+-- inconvenience this module provides a standard lifted wrapper, inhabiting 'Data.Kind.Type'.+-- Clients are expected to use 'MutableByteArray' in higher-level APIs,+-- but wrap and unwrap 'MutableByteArray' internally as they please+-- and use functions from "GHC.Exts".+--+-- @since 4.17.0.0+data MutableByteArray s = MutableByteArray (MutableByteArray# s)++-- | Create a new mutable byte array of the specified size in bytes.+--+-- /Note:/ this function does not check if the input is non-negative.+newByteArray :: Int -> ST s (MutableByteArray s)+{-# INLINE newByteArray #-}+newByteArray (I# n#) =+  ST (\s# -> case newByteArray# n# s# of+    (# s'#, arr# #) -> (# s'#, MutableByteArray arr# #))++-- | Convert a mutable byte array to an immutable one without copying. The+-- array should not be modified after the conversion.+unsafeFreezeByteArray :: MutableByteArray s -> ST s ByteArray+{-# INLINE unsafeFreezeByteArray #-}+unsafeFreezeByteArray (MutableByteArray arr#) =+  ST (\s# -> case unsafeFreezeByteArray# arr# s# of+    (# s'#, arr'# #) -> (# s'#, ByteArray arr'# #))++-- | Size of the byte array in bytes.+sizeofByteArray :: ByteArray -> Int+{-# INLINE sizeofByteArray #-}+sizeofByteArray (ByteArray arr#) = I# (sizeofByteArray# arr#)++-- | Read byte at specific index.+indexByteArray :: ByteArray -> Int -> Word8+{-# INLINE indexByteArray #-}+indexByteArray (ByteArray arr#) (I# i#) = W8# (indexWord8Array# arr# i#)++-- | Write byte at specific index.+writeByteArray :: MutableByteArray s -> Int -> Word8 -> ST s ()+{-# INLINE writeByteArray #-}+writeByteArray (MutableByteArray arr#) (I# i#) (W8# x#) =+  ST (\s# -> case writeWord8Array# arr# i# x# s# of+    s'# -> (# s'#, () #))++-- | Explode 'ByteArray' into a list of bytes.+byteArrayToList :: ByteArray -> [Word8]+{-# INLINE byteArrayToList #-}+byteArrayToList arr = go 0+  where+    go i+      | i < maxI  = indexByteArray arr i : go (i+1)+      | otherwise = []+    maxI = sizeofByteArray arr++-- | Create a 'ByteArray' from a list of a known length. If the length+--   of the list does not match the given length, this throws an exception.+byteArrayFromListN :: Int -> [Word8] -> ByteArray+byteArrayFromListN n ys+  | n >= 0 = runST $ do+    marr <- newByteArray n+    let go !ix [] = if ix == n+          then return ()+          else errorWithoutStackTrace $ "Data.Array.Byte.byteArrayFromListN: list length less than specified size"+        go !ix (x : xs) = if ix < n+          then do+            writeByteArray marr ix x+            go (ix + 1) xs+          else errorWithoutStackTrace $ "Data.Array.Byte.byteArrayFromListN: list length greater than specified size"+    go 0 ys+    unsafeFreezeByteArray marr+  | otherwise = errorWithoutStackTrace "Data.Array.Byte.ByteArrayFromListN: specified size is negative"++-- | Copy a slice of an immutable byte array to a mutable byte array.+--+-- /Note:/ this function does not do bounds or overlap checking.+unsafeCopyByteArray+  :: MutableByteArray s -- ^ destination array+  -> Int                -- ^ offset into destination array+  -> ByteArray          -- ^ source array+  -> Int                -- ^ offset into source array+  -> Int                -- ^ number of bytes to copy+  -> ST s ()+{-# INLINE unsafeCopyByteArray #-}+unsafeCopyByteArray (MutableByteArray dst#) (I# doff#) (ByteArray src#) (I# soff#) (I# sz#) =+  ST (\s# -> case copyByteArray# src# soff# dst# doff# sz# s# of+    s'# -> (# s'#, () #))++-- | Copy a slice from one mutable byte array to another+-- or to the same mutable byte array.+--+-- /Note:/ this function does not do bounds or overlap checking.+unsafeCopyMutableByteArray+  :: MutableByteArray s -- ^ destination array+  -> Int                -- ^ offset into destination array+  -> MutableByteArray s -- ^ source array+  -> Int                -- ^ offset into source array+  -> Int                -- ^ number of bytes to copy+  -> ST s ()+{-# INLINE unsafeCopyMutableByteArray #-}+unsafeCopyMutableByteArray (MutableByteArray dst#) (I# doff#) (MutableByteArray src#) (I# soff#) (I# sz#) =+  ST (\s# -> case copyMutableByteArrayNonOverlapping# src# soff# dst# doff# sz# s# of+    s'# -> (# s'#, () #))++-- | @since 4.17.0.0+instance Data ByteArray where+  toConstr _ = error "toConstr"+  gunfold _ _ = error "gunfold"+  dataTypeOf _ = mkNoRepType "Data.Array.Byte.ByteArray"++-- | @since 4.17.0.0+instance Typeable s => Data (MutableByteArray s) where+  toConstr _ = error "toConstr"+  gunfold _ _ = error "gunfold"+  dataTypeOf _ = mkNoRepType "Data.Array.Byte.MutableByteArray"++-- | @since 4.17.0.0+instance Show ByteArray where+  showsPrec _ ba =+      showString "[" . go 0+    where+      showW8 :: Word8 -> String -> String+      showW8 !w s =+          '0'+        : 'x'+        : intToDigit (fromIntegral (unsafeShiftR w 4))+        : intToDigit (fromIntegral (w .&. 0x0F))+        : s+      go i+        | i < sizeofByteArray ba = comma . showW8 (indexByteArray ba i :: Word8) . go (i+1)+        | otherwise              = showChar ']'+        where+          comma | i == 0    = id+                | otherwise = showString ", "++instance Lift ByteArray where+  liftTyped = unsafeCodeCoerce . lift+  lift (ByteArray b) =+    [| addrToByteArray $(lift len)+                       $(pure . LitE . BytesPrimL $ Bytes ptr 0 (fromIntegral len))+    |]+    where+      len# = sizeofByteArray# b+      len = I# len#+      pb :: ByteArray#+      !(ByteArray pb)+        | isTrue# (isByteArrayPinned# b) = ByteArray b+        | otherwise = runST $ ST $+          \s -> case newPinnedByteArray# len# s of+            (# s', mb #) -> case copyByteArray# b 0# mb 0# len# s' of+              s'' -> case unsafeFreezeByteArray# mb s'' of+                (# s''', ret #) -> (# s''', ByteArray ret #)+      ptr :: ForeignPtr Word8+      ptr = ForeignPtr (byteArrayContents# pb) (PlainPtr (unsafeCoerce# pb))++{-# NOINLINE addrToByteArray #-}+addrToByteArray :: Int -> Addr# -> ByteArray+addrToByteArray (I# len) addr = runST $ ST $+  \s -> case newByteArray# len s of+    (# s', mb #) -> case copyAddrToByteArray# addr mb 0# len s' of+      s'' -> case unsafeFreezeByteArray# mb s'' of+        (# s''', ret #) -> (# s''', ByteArray ret #)++-- | Compare prefixes of given length.+compareByteArraysFromBeginning :: ByteArray -> ByteArray -> Int -> Ordering+{-# INLINE compareByteArraysFromBeginning #-}+compareByteArraysFromBeginning (ByteArray ba1#) (ByteArray ba2#) (I# n#)+  = compare (I# (compareByteArrays# ba1# 0# ba2# 0# n#)) 0++-- | Do two byte arrays share the same pointer?+sameByteArray :: ByteArray# -> ByteArray# -> Bool+sameByteArray ba1 ba2 =+    case sameByteArray# ba1 ba2 of r -> isTrue# r++-- | @since 4.17.0.0+instance Eq ByteArray where+  ba1@(ByteArray ba1#) == ba2@(ByteArray ba2#)+    | sameByteArray ba1# ba2# = True+    | n1 /= n2 = False+    | otherwise = compareByteArraysFromBeginning ba1 ba2 n1 == EQ+    where+      n1 = sizeofByteArray ba1+      n2 = sizeofByteArray ba2++-- | @since 4.17.0.0+instance Eq (MutableByteArray s) where+  (==) (MutableByteArray arr#) (MutableByteArray brr#)+    = isTrue# (sameMutableByteArray# arr# brr#)++-- | Non-lexicographic ordering. This compares the lengths of+-- the byte arrays first and uses a lexicographic ordering if+-- the lengths are equal. Subject to change between major versions.+--+-- @since 4.17.0.0+instance Ord ByteArray where+  ba1@(ByteArray ba1#) `compare` ba2@(ByteArray ba2#)+    | sameByteArray ba1# ba2# = EQ+    | n1 /= n2 = n1 `compare` n2+    | otherwise = compareByteArraysFromBeginning ba1 ba2 n1+    where+      n1 = sizeofByteArray ba1+      n2 = sizeofByteArray ba2+-- The primop compareByteArrays# (invoked from 'compareByteArraysFromBeginning')+-- performs a check for pointer equality as well. However, it+-- is included here because it is likely better to check for pointer equality+-- before checking for length equality. Getting the length requires deferencing+-- the pointers, which could cause accesses to memory that is not in the cache.+-- By contrast, a pointer equality check is always extremely cheap.++-- | Append two byte arrays.+appendByteArray :: ByteArray -> ByteArray -> ByteArray+appendByteArray ba1 ba2 = runST $ do+  let n1 = sizeofByteArray ba1+      n2 = sizeofByteArray ba2+      totSz = fromMaybe (sizeOverflowError "appendByteArray")+                        (checkedIntAdd n1 n2)+  marr <- newByteArray totSz+  unsafeCopyByteArray marr 0  ba1 0 n1+  unsafeCopyByteArray marr n1 ba2 0 n2+  unsafeFreezeByteArray marr++-- | Concatenate a list of 'ByteArray's.+concatByteArray :: [ByteArray] -> ByteArray+concatByteArray arrs = runST $ do+  let addLen acc arr = fromMaybe (sizeOverflowError "concatByteArray")+                                 (checkedIntAdd acc (sizeofByteArray arr))+      totLen = F.foldl' addLen 0 arrs+  marr <- newByteArray totLen+  pasteByteArrays marr 0 arrs+  unsafeFreezeByteArray marr++-- | Dump immutable 'ByteArray's into a mutable one, starting from a given offset.+pasteByteArrays :: MutableByteArray s -> Int -> [ByteArray] -> ST s ()+pasteByteArrays !_ !_ [] = return ()+pasteByteArrays !marr !ix (x : xs) = do+  unsafeCopyByteArray marr ix x 0 (sizeofByteArray x)+  pasteByteArrays marr (ix + sizeofByteArray x) xs++-- | An array of zero length.+emptyByteArray :: ByteArray+emptyByteArray = runST (newByteArray 0 >>= unsafeFreezeByteArray)++-- | Concatenates a given number of copies of an input ByteArray.+stimesPolymorphic :: Integral t => t -> ByteArray -> ByteArray+{-# INLINABLE stimesPolymorphic #-}+stimesPolymorphic nRaw !arr = case toInteger nRaw of+  IS nInt#+    | isTrue# (nInt# >#  0#) -> stimesPositiveInt (I# nInt#) arr+    | isTrue# (nInt# >=# 0#) -> emptyByteArray+      -- This check is redundant for unsigned types like Word.+      -- Using >=# intead of ==# may make it easier for GHC to notice that.+    | otherwise -> stimesNegativeErr+  IP _+    | sizeofByteArray arr == 0 -> emptyByteArray+    | otherwise -> stimesOverflowErr+  IN _ -> stimesNegativeErr++stimesNegativeErr :: ByteArray+stimesNegativeErr =+  errorWithoutStackTrace "stimes @ByteArray: negative multiplier"++stimesOverflowErr :: a+stimesOverflowErr = sizeOverflowError "stimes"++stimesPositiveInt :: Int -> ByteArray -> ByteArray+{-# NOINLINE stimesPositiveInt #-}+-- NOINLINE to prevent its duplication in specialisations of stimesPolymorphic+stimesPositiveInt n arr = runST $ do+  let inpSz = sizeofByteArray arr+      tarSz = fromMaybe stimesOverflowErr (checkedIntMultiply n inpSz)+  marr <- newByteArray tarSz+  unsafeCopyByteArray marr 0 arr 0 inpSz+  let+    halfTarSz = (tarSz - 1) `div` 2+    go copied+      | copied <= halfTarSz = do+          unsafeCopyMutableByteArray marr copied marr 0 copied+          go (copied + copied)+      | otherwise = unsafeCopyMutableByteArray marr copied marr 0 (tarSz - copied)+  go inpSz+  unsafeFreezeByteArray marr++-- | @since 4.17.0.0+instance Semigroup ByteArray where+  (<>) = appendByteArray+  sconcat = mconcat . F.toList+  {-# INLINE stimes #-}+  stimes = stimesPolymorphic++-- | @since 4.17.0.0+instance Monoid ByteArray where+  mempty = emptyByteArray+  mconcat = concatByteArray++-- | @since 4.17.0.0+instance IsList ByteArray where+  type Item ByteArray = Word8++  toList = byteArrayToList+  fromList xs = byteArrayFromListN (length xs) xs+  fromListN = byteArrayFromListN+++sizeOverflowError :: String -> a+sizeOverflowError fun+  = errorWithoutStackTrace $ "Data.Array.Byte." ++ fun ++ ": size overflow"+++-- TODO: Export these from a better home.++-- | Adds two @Int@s, returning @Nothing@ if this results in an overflow+checkedIntAdd :: Int -> Int -> Maybe Int+checkedIntAdd (I# x#) (I# y#) = case addIntC# x# y# of+  (# res, 0# #) -> Just (I# res)+  _ -> Nothing++-- | Multiplies two @Int@s, returning @Nothing@ if this results in an overflow+checkedIntMultiply :: Int -> Int -> Maybe Int+checkedIntMultiply (I# x#) (I# y#) = case timesInt2# x# y# of+  (# 0#, _hi, lo #) -> Just (I# lo)+  _ -> Nothing
+ src/Data/Bifoldable.hs view
@@ -0,0 +1,1054 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE ScopedTypeVariables #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Bifoldable+-- Copyright   :  (C) 2011-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- @since 4.10.0.0+----------------------------------------------------------------------------+module Data.Bifoldable+  ( Bifoldable(..)+  , bifoldr'+  , bifoldr1+  , bifoldrM+  , bifoldl'+  , bifoldl1+  , bifoldlM+  , bitraverse_+  , bifor_+  , bimapM_+  , biforM_+  , bimsum+  , bisequenceA_+  , bisequence_+  , biasum+  , biList+  , binull+  , bilength+  , bielem+  , bimaximum+  , biminimum+  , bisum+  , biproduct+  , biconcat+  , biconcatMap+  , biand+  , bior+  , biany+  , biall+  , bimaximumBy+  , biminimumBy+  , binotElem+  , bifind+  ) where++import Control.Applicative+import GHC.Internal.Data.Functor.Utils (Max(..), Min(..), (#.))+import GHC.Internal.Data.Maybe (fromMaybe)+import GHC.Internal.Data.Monoid+import GHC.Generics (K1(..))+import Prelude++-- $setup+-- >>> import Prelude+-- >>> import Data.Char+-- >>> import GHC.Internal.Data.Monoid (Product (..), Sum (..))+-- >>> data BiList a b = BiList [a] [b]+-- >>> instance Bifoldable BiList where bifoldr f g z (BiList as bs) = foldr f (foldr g z bs) as++-- | 'Bifoldable' identifies foldable structures with two different varieties+-- of elements (as opposed to 'Foldable', which has one variety of element).+-- Common examples are 'Either' and @(,)@:+--+-- > instance Bifoldable Either where+-- >   bifoldMap f _ (Left  a) = f a+-- >   bifoldMap _ g (Right b) = g b+-- >+-- > instance Bifoldable (,) where+-- >   bifoldr f g z (a, b) = f a (g b z)+--+-- Some examples below also use the following BiList to showcase empty+-- Bifoldable behaviors when relevant ('Either' and '(,)' containing always exactly+-- resp. 1 and 2 elements):+--+-- > data BiList a b = BiList [a] [b]+-- >+-- > instance Bifoldable BiList where+-- >   bifoldr f g z (BiList as bs) = foldr f (foldr g z bs) as+--+-- A minimal 'Bifoldable' definition consists of either 'bifoldMap' or+-- 'bifoldr'. When defining more than this minimal set, one should ensure+-- that the following identities hold:+--+-- @+-- 'bifold' ≡ 'bifoldMap' 'id' 'id'+-- 'bifoldMap' f g ≡ 'bifoldr' ('mappend' . f) ('mappend' . g) 'mempty'+-- 'bifoldr' f g z t ≡ 'appEndo' ('bifoldMap' (Endo . f) (Endo . g) t) z+-- @+--+-- If the type is also an instance of 'Foldable', then+-- it must satisfy (up to laziness):+--+-- @+-- 'bifoldl' 'const' ≡ 'foldl'+-- 'bifoldr' ('flip' 'const') ≡ 'foldr'+-- 'bifoldMap' ('const' 'mempty') ≡ 'foldMap'+-- @+--+-- If the type is also a 'Data.Bifunctor.Bifunctor' instance, it should satisfy:+--+-- @+-- 'bifoldMap' f g ≡ 'bifold' . 'Data.Bifunctor.bimap' f g+-- @+--+-- which implies that+--+-- @+-- 'bifoldMap' f g . 'Data.Bifunctor.bimap' h i ≡ 'bifoldMap' (f . h) (g . i)+-- @+--+-- @since 4.10.0.0+class Bifoldable p where+  {-# MINIMAL bifoldr | bifoldMap #-}++  -- | Combines the elements of a structure using a monoid.+  --+  -- @'bifold' ≡ 'bifoldMap' 'id' 'id'@+  --+  -- ==== __Examples__+  --+  -- Basic usage:+  --+  -- >>> bifold (Right [1, 2, 3])+  -- [1,2,3]+  --+  -- >>> bifold (Left [5, 6])+  -- [5,6]+  --+  -- >>> bifold ([1, 2, 3], [4, 5])+  -- [1,2,3,4,5]+  --+  -- >>> bifold (Product 6, Product 7)+  -- Product {getProduct = 42}+  --+  -- >>> bifold (Sum 6, Sum 7)+  -- Sum {getSum = 13}+  --+  -- @since 4.10.0.0+  bifold :: Monoid m => p m m -> m+  bifold = bifoldMap id id++  -- | Combines the elements of a structure, given ways of mapping them to a+  -- common monoid.+  --+  -- @'bifoldMap' f g ≡ 'bifoldr' ('mappend' . f) ('mappend' . g) 'mempty'@+  --+  -- ==== __Examples__+  --+  -- Basic usage:+  --+  -- >>> bifoldMap (take 3) (fmap digitToInt) ([1..], "89")+  -- [1,2,3,8,9]+  --+  -- >>> bifoldMap (take 3) (fmap digitToInt) (Left [1..])+  -- [1,2,3]+  --+  -- >>> bifoldMap (take 3) (fmap digitToInt) (Right "89")+  -- [8,9]+  --+  -- @since 4.10.0.0+  bifoldMap :: Monoid m => (a -> m) -> (b -> m) -> p a b -> m+  bifoldMap f g = bifoldr (mappend . f) (mappend . g) mempty++  -- | Combines the elements of a structure in a right associative manner.+  -- Given a hypothetical function @toEitherList :: p a b -> [Either a b]@+  -- yielding a list of all elements of a structure in order, the following+  -- would hold:+  --+  -- @'bifoldr' f g z ≡ 'foldr' ('either' f g) z . toEitherList@+  --+  -- ==== __Examples__+  --+  -- Basic usage:+  --+  -- @+  -- > bifoldr (+) (*) 3 (5, 7)+  -- 26 -- 5 + (7 * 3)+  --+  -- > bifoldr (+) (*) 3 (7, 5)+  -- 22 -- 7 + (5 * 3)+  --+  -- > bifoldr (+) (*) 3 (Right 5)+  -- 15 -- 5 * 3+  --+  -- > bifoldr (+) (*) 3 (Left 5)+  -- 8 -- 5 + 3+  -- @+  --+  -- @since 4.10.0.0+  bifoldr :: (a -> c -> c) -> (b -> c -> c) -> c -> p a b -> c+  bifoldr f g z t = appEndo (bifoldMap (Endo #. f) (Endo #. g) t) z++  -- | Combines the elements of a structure in a left associative manner. Given+  -- a hypothetical function @toEitherList :: p a b -> [Either a b]@ yielding a+  -- list of all elements of a structure in order, the following would hold:+  --+  -- @'bifoldl' f g z+  --     ≡ 'foldl' (\acc -> 'either' (f acc) (g acc)) z . toEitherList@+  --+  -- Note that if you want an efficient left-fold, you probably want to use+  -- 'bifoldl'' instead of 'bifoldl'. The reason is that the latter does not+  -- force the "inner" results, resulting in a thunk chain which then must be+  -- evaluated from the outside-in.+  --+  -- ==== __Examples__+  --+  -- Basic usage:+  --+  -- @+  -- > bifoldl (+) (*) 3 (5, 7)+  -- 56 -- (5 + 3) * 7+  --+  -- > bifoldl (+) (*) 3 (7, 5)+  -- 50 -- (7 + 3) * 5+  --+  -- > bifoldl (+) (*) 3 (Right 5)+  -- 15 -- 5 * 3+  --+  -- > bifoldl (+) (*) 3 (Left 5)+  -- 8 -- 5 + 3+  -- @+  --+  -- @since 4.10.0.0+  bifoldl :: (c -> a -> c) -> (c -> b -> c) -> c -> p a b -> c+  bifoldl f g z t = appEndo (getDual (bifoldMap (Dual . Endo . flip f)+                                                (Dual . Endo . flip g) t)) z++-- | Class laws for tuples hold only up to laziness. The+-- Bifoldable methods are lazier than their Foldable counterparts.+-- For example the law @'bifoldr' ('flip' 'const') ≡ 'foldr'@ does+-- not hold for tuples if laziness is exploited:+--+-- >>> bifoldr (flip const) (:) [] (undefined :: (Int, Word)) `seq` ()+-- ()+-- >>> foldr (:) [] (errorWithoutStackTrace "error!" :: (Int, Word)) `seq` ()+-- *** Exception: error!+--+-- @since 4.10.0.0+instance Bifoldable (,) where+  bifoldMap f g ~(a, b) = f a `mappend` g b++-- | @since 4.10.0.0+instance Bifoldable Const where+  bifoldMap f _ (Const a) = f a++-- | @since 4.10.0.0+instance Bifoldable (K1 i) where+  bifoldMap f _ (K1 c) = f c++-- | @since 4.10.0.0+instance Bifoldable ((,,) x) where+  bifoldMap f g ~(_,a,b) = f a `mappend` g b++-- | @since 4.10.0.0+instance Bifoldable ((,,,) x y) where+  bifoldMap f g ~(_,_,a,b) = f a `mappend` g b++-- | @since 4.10.0.0+instance Bifoldable ((,,,,) x y z) where+  bifoldMap f g ~(_,_,_,a,b) = f a `mappend` g b++-- | @since 4.10.0.0+instance Bifoldable ((,,,,,) x y z w) where+  bifoldMap f g ~(_,_,_,_,a,b) = f a `mappend` g b++-- | @since 4.10.0.0+instance Bifoldable ((,,,,,,) x y z w v) where+  bifoldMap f g ~(_,_,_,_,_,a,b) = f a `mappend` g b++-- | @since 4.10.0.0+instance Bifoldable Either where+  bifoldMap f _ (Left a) = f a+  bifoldMap _ g (Right b) = g b++-- | As 'bifoldr', but strict in the result of the reduction functions at each+-- step.+--+-- @since 4.10.0.0+bifoldr' :: Bifoldable t => (a -> c -> c) -> (b -> c -> c) -> c -> t a b -> c+bifoldr' f g z0 xs = bifoldl f' g' id xs z0 where+  f' k x z = k $! f x z+  g' k x z = k $! g x z++-- | A variant of 'bifoldr' that has no base case,+-- and thus may only be applied to non-empty structures.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bifoldr1 (+) (5, 7)+-- 12+--+-- >>> bifoldr1 (+) (Right 7)+-- 7+--+-- >>> bifoldr1 (+) (Left 5)+-- 5+--+-- @+-- > bifoldr1 (+) (BiList [1, 2] [3, 4])+-- 10 -- 1 + (2 + (3 + 4))+-- @+--+-- >>> bifoldr1 (+) (BiList [1, 2] [])+-- 3+--+-- On empty structures, this function throws an exception:+--+-- >>> bifoldr1 (+) (BiList [] [])+-- *** Exception: bifoldr1: empty structure+-- ...+--+-- @since 4.10.0.0+bifoldr1 :: Bifoldable t => (a -> a -> a) -> t a a -> a+bifoldr1 f xs = fromMaybe (error "bifoldr1: empty structure")+                  (bifoldr mbf mbf Nothing xs)+  where+    mbf x m = Just (case m of+                      Nothing -> x+                      Just y  -> f x y)++-- | Right associative monadic bifold over a structure.+--+-- @since 4.10.0.0+bifoldrM :: (Bifoldable t, Monad m)+         => (a -> c -> m c) -> (b -> c -> m c) -> c -> t a b -> m c+bifoldrM f g z0 xs = bifoldl f' g' return xs z0 where+  f' k x z = f x z >>= k+  g' k x z = g x z >>= k++-- | As 'bifoldl', but strict in the result of the reduction functions at each+-- step.+--+-- This ensures that each step of the bifold is forced to weak head normal form+-- before being applied, avoiding the collection of thunks that would otherwise+-- occur. This is often what you want to strictly reduce a finite structure to+-- a single, monolithic result (e.g., 'bilength').+--+-- @since 4.10.0.0+bifoldl':: Bifoldable t => (a -> b -> a) -> (a -> c -> a) -> a -> t b c -> a+bifoldl' f g z0 xs = bifoldr f' g' id xs z0 where+  f' x k z = k $! f z x+  g' x k z = k $! g z x++-- | A variant of 'bifoldl' that has no base case,+-- and thus may only be applied to non-empty structures.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bifoldl1 (+) (5, 7)+-- 12+--+-- >>> bifoldl1 (+) (Right 7)+-- 7+--+-- >>> bifoldl1 (+) (Left 5)+-- 5+--+-- @+-- > bifoldl1 (+) (BiList [1, 2] [3, 4])+-- 10 -- ((1 + 2) + 3) + 4+-- @+--+-- >>> bifoldl1 (+) (BiList [1, 2] [])+-- 3+--+-- On empty structures, this function throws an exception:+--+-- >>> bifoldl1 (+) (BiList [] [])+-- *** Exception: bifoldl1: empty structure+-- ...+--+-- @since 4.10.0.0+bifoldl1 :: Bifoldable t => (a -> a -> a) -> t a a -> a+bifoldl1 f xs = fromMaybe (error "bifoldl1: empty structure")+                  (bifoldl mbf mbf Nothing xs)+  where+    mbf m y = Just (case m of+                      Nothing -> y+                      Just x  -> f x y)++-- | Left associative monadic bifold over a structure.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 ("Hello", True)+-- "Hello"+-- "True"+-- 42+--+-- >>> bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Right True)+-- "True"+-- 42+--+-- >>> bifoldlM (\a b -> print b >> pure a) (\a c -> print (show c) >> pure a) 42 (Left "Hello")+-- "Hello"+-- 42+--+-- @since 4.10.0.0+bifoldlM :: (Bifoldable t, Monad m)+         => (a -> b -> m a) -> (a -> c -> m a) -> a -> t b c -> m a+bifoldlM f g z0 xs = bifoldr f' g' return xs z0 where+  f' x k z = f z x >>= k+  g' x k z = g z x >>= k++-- | Map each element of a structure using one of two actions, evaluate these+-- actions from left to right, and ignore the results. For a version that+-- doesn't ignore the results, see 'Data.Bitraversable.bitraverse'.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bitraverse_ print (print . show) ("Hello", True)+-- "Hello"+-- "True"+--+-- >>> bitraverse_ print (print . show) (Right True)+-- "True"+--+-- >>> bitraverse_ print (print . show) (Left "Hello")+-- "Hello"+--+-- @since 4.10.0.0+bitraverse_ :: (Bifoldable t, Applicative f)+            => (a -> f c) -> (b -> f d) -> t a b -> f ()+bitraverse_ f g = bifoldr ((*>) . f) ((*>) . g) (pure ())++-- | As 'bitraverse_', but with the structure as the primary argument. For a+-- version that doesn't ignore the results, see 'Data.Bitraversable.bifor'.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bifor_ ("Hello", True) print (print . show)+-- "Hello"+-- "True"+--+-- >>> bifor_ (Right True) print (print . show)+-- "True"+--+-- >>> bifor_ (Left "Hello") print (print . show)+-- "Hello"+--+-- @since 4.10.0.0+bifor_ :: (Bifoldable t, Applicative f)+       => t a b -> (a -> f c) -> (b -> f d) -> f ()+bifor_ t f g = bitraverse_ f g t++-- | Alias for 'bitraverse_'.+--+-- @since 4.10.0.0+bimapM_ :: (Bifoldable t, Applicative f)+        => (a -> f c) -> (b -> f d) -> t a b -> f ()+bimapM_ = bitraverse_++-- | Alias for 'bifor_'.+--+-- @since 4.10.0.0+biforM_ :: (Bifoldable t, Applicative f)+        => t a b ->  (a -> f c) -> (b -> f d) -> f ()+biforM_ = bifor_++-- | Alias for 'bisequence_'.+--+-- @since 4.10.0.0+bisequenceA_ :: (Bifoldable t, Applicative f) => t (f a) (f b) -> f ()+bisequenceA_ = bisequence_++-- | Evaluate each action in the structure from left to right, and ignore the+-- results. For a version that doesn't ignore the results, see+-- 'Data.Bitraversable.bisequence'.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bisequence_ (print "Hello", print "World")+-- "Hello"+-- "World"+--+-- >>> bisequence_ (Left (print "Hello"))+-- "Hello"+--+-- >>> bisequence_ (Right (print "World"))+-- "World"+--+-- @since 4.10.0.0+bisequence_ :: (Bifoldable t, Applicative f) => t (f a) (f b) -> f ()+bisequence_ = bifoldr (*>) (*>) (pure ())++-- | The sum of a collection of actions, generalizing 'biconcat'.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biasum (Nothing, Nothing)+-- Nothing+--+-- >>> biasum (Nothing, Just 42)+-- Just 42+--+-- >>> biasum (Just 18, Nothing)+-- Just 18+--+-- >>> biasum (Just 18, Just 42)+-- Just 18+--+-- @since 4.10.0.0+biasum :: (Bifoldable t, Alternative f) => t (f a) (f a) -> f a+biasum = bifoldr (<|>) (<|>) empty++-- | Alias for 'biasum'.+--+-- @since 4.10.0.0+bimsum :: (Bifoldable t, Alternative f) => t (f a) (f a) -> f a+bimsum = biasum++-- | Collects the list of elements of a structure, from left to right.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biList (18, 42)+-- [18,42]+--+-- >>> biList (Left 18)+-- [18]+--+-- @since 4.10.0.0+biList :: Bifoldable t => t a a -> [a]+biList = bifoldr (:) (:) []++-- | Test whether the structure is empty.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> binull (18, 42)+-- False+--+-- >>> binull (Right 42)+-- False+--+-- >>> binull (BiList [] [])+-- True+--+-- @since 4.10.0.0+binull :: Bifoldable t => t a b -> Bool+binull = bifoldr (\_ _ -> False) (\_ _ -> False) True++-- | Returns the size/length of a finite structure as an 'Int'.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bilength (True, 42)+-- 2+--+-- >>> bilength (Right 42)+-- 1+--+-- >>> bilength (BiList [1,2,3] [4,5])+-- 5+--+-- >>> bilength (BiList [] [])+-- 0+--+-- On infinite structures, this function hangs:+--+-- @+-- > bilength (BiList [1..] [])+-- * Hangs forever *+-- @+--+-- @since 4.10.0.0+bilength :: Bifoldable t => t a b -> Int+bilength = bifoldl' (\c _ -> c+1) (\c _ -> c+1) 0++-- | Does the element occur in the structure?+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bielem 42 (17, 42)+-- True+--+-- >>> bielem 42 (17, 43)+-- False+--+-- >>> bielem 42 (Left 42)+-- True+--+-- >>> bielem 42 (Right 13)+-- False+--+-- >>> bielem 42 (BiList [1..5] [1..100])+-- True+--+-- >>> bielem 42 (BiList [1..5] [1..41])+-- False+--+-- @since 4.10.0.0+bielem :: (Bifoldable t, Eq a) => a -> t a a -> Bool+bielem x = biany (== x) (== x)++-- | Reduces a structure of lists to the concatenation of those lists.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biconcat ([1, 2, 3], [4, 5])+-- [1,2,3,4,5]+--+-- >>> biconcat (Left [1, 2, 3])+-- [1,2,3]+--+-- >>> biconcat (BiList [[1, 2, 3, 4, 5], [6, 7, 8]] [[9]])+-- [1,2,3,4,5,6,7,8,9]+--+-- @since 4.10.0.0+biconcat :: Bifoldable t => t [a] [a] -> [a]+biconcat = bifold++-- | The largest element of a non-empty structure. This function is equivalent+-- to @'bifoldr1' 'max'@, and its behavior on structures with multiple largest+-- elements depends on the relevant implementation of 'max'. For the default+-- implementation of 'max' (@max x y = if x <= y then y else x@), structure+-- order is used as a tie-breaker: if there are multiple largest elements, the+-- rightmost of them is chosen (this is equivalent to @'bimaximumBy'+-- 'compare'@).+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bimaximum (42, 17)+-- 42+--+-- >>> bimaximum (Right 42)+-- 42+--+-- >>> bimaximum (BiList [13, 29, 4] [18, 1, 7])+-- 29+--+-- >>> bimaximum (BiList [13, 29, 4] [])+-- 29+--+-- On empty structures, this function throws an exception:+--+-- >>> bimaximum (BiList [] [])+-- *** Exception: bimaximum: empty structure+-- ...+--+-- @since 4.10.0.0+bimaximum :: forall t a. (Bifoldable t, Ord a) => t a a -> a+bimaximum = fromMaybe (error "bimaximum: empty structure") .+    getMax . bifoldMap mj mj+  where mj = Max #. (Just :: a -> Maybe a)++-- | The least element of a non-empty structure. This function is equivalent to+-- @'bifoldr1' 'min'@, and its behavior on structures with multiple least+-- elements depends on the relevant implementation of 'min'. For the default+-- implementation of 'min' (@min x y = if x <= y then x else y@), structure+-- order is used as a tie-breaker: if there are multiple least elements, the+-- leftmost of them is chosen (this is equivalent to @'biminimumBy'+-- 'compare'@).+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biminimum (42, 17)+-- 17+--+-- >>> biminimum (Right 42)+-- 42+--+-- >>> biminimum (BiList [13, 29, 4] [18, 1, 7])+-- 1+--+-- >>> biminimum (BiList [13, 29, 4] [])+-- 4+--+-- On empty structures, this function throws an exception:+--+-- >>> biminimum (BiList [] [])+-- *** Exception: biminimum: empty structure+-- ...+--+-- @since 4.10.0.0+biminimum :: forall t a. (Bifoldable t, Ord a) => t a a -> a+biminimum = fromMaybe (error "biminimum: empty structure") .+    getMin . bifoldMap mj mj+  where mj = Min #. (Just :: a -> Maybe a)++-- | The 'bisum' function computes the sum of the numbers of a structure.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bisum (42, 17)+-- 59+--+-- >>> bisum (Right 42)+-- 42+--+-- >>> bisum (BiList [13, 29, 4] [18, 1, 7])+-- 72+--+-- >>> bisum (BiList [13, 29, 4] [])+-- 46+--+-- >>> bisum (BiList [] [])+-- 0+--+-- @since 4.10.0.0+bisum :: (Bifoldable t, Num a) => t a a -> a+bisum = getSum #. bifoldMap Sum Sum++-- | The 'biproduct' function computes the product of the numbers of a+-- structure.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biproduct (42, 17)+-- 714+--+-- >>> biproduct (Right 42)+-- 42+--+-- >>> biproduct (BiList [13, 29, 4] [18, 1, 7])+-- 190008+--+-- >>> biproduct (BiList [13, 29, 4] [])+-- 1508+--+-- >>> biproduct (BiList [] [])+-- 1+--+-- @since 4.10.0.0+biproduct :: (Bifoldable t, Num a) => t a a -> a+biproduct = getProduct #. bifoldMap Product Product++-- | Given a means of mapping the elements of a structure to lists, computes the+-- concatenation of all such lists in order.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biconcatMap (take 3) (fmap digitToInt) ([1..], "89")+-- [1,2,3,8,9]+--+-- >>> biconcatMap (take 3) (fmap digitToInt) (Left [1..])+-- [1,2,3]+--+-- >>> biconcatMap (take 3) (fmap digitToInt) (Right "89")+-- [8,9]+--+-- @since 4.10.0.0+biconcatMap :: Bifoldable t => (a -> [c]) -> (b -> [c]) -> t a b -> [c]+biconcatMap = bifoldMap++-- | 'biand' returns the conjunction of a container of Bools.  For the+-- result to be 'True', the container must be finite; 'False', however,+-- results from a 'False' value finitely far from the left end.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biand (True, False)+-- False+--+-- >>> biand (True, True)+-- True+--+-- >>> biand (Left True)+-- True+--+-- Empty structures yield 'True':+--+-- >>> biand (BiList [] [])+-- True+--+-- A 'False' value finitely far from the left end yields 'False' (short circuit):+--+-- >>> biand (BiList [True, True, False, True] (repeat True))+-- False+--+-- A 'False' value infinitely far from the left end hangs:+--+-- @+-- > biand (BiList (repeat True) [False])+-- * Hangs forever *+-- @+--+-- An infinitely 'True' value hangs:+--+-- @+-- > biand (BiList (repeat True) [])+-- * Hangs forever *+-- @+--+-- @since 4.10.0.0+biand :: Bifoldable t => t Bool Bool -> Bool+biand = getAll #. bifoldMap All All++-- | 'bior' returns the disjunction of a container of Bools.  For the+-- result to be 'False', the container must be finite; 'True', however,+-- results from a 'True' value finitely far from the left end.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bior (True, False)+-- True+--+-- >>> bior (False, False)+-- False+--+-- >>> bior (Left True)+-- True+--+-- Empty structures yield 'False':+--+-- >>> bior (BiList [] [])+-- False+--+-- A 'True' value finitely far from the left end yields 'True' (short circuit):+--+-- >>> bior (BiList [False, False, True, False] (repeat False))+-- True+--+-- A 'True' value infinitely far from the left end hangs:+--+-- @+-- > bior (BiList (repeat False) [True])+-- * Hangs forever *+-- @+--+-- An infinitely 'False' value hangs:+--+-- @+-- > bior (BiList (repeat False) [])+-- * Hangs forever *+-- @+--+-- @since 4.10.0.0+bior :: Bifoldable t => t Bool Bool -> Bool+bior = getAny #. bifoldMap Any Any++-- | Determines whether any element of the structure satisfies its appropriate+-- predicate argument. Empty structures yield 'False'.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biany even isDigit (27, 't')+-- False+--+-- >>> biany even isDigit (27, '8')+-- True+--+-- >>> biany even isDigit (26, 't')+-- True+--+-- >>> biany even isDigit (Left 27)+-- False+--+-- >>> biany even isDigit (Left 26)+-- True+--+-- >>> biany even isDigit (BiList [27, 53] ['t', '8'])+-- True+--+-- Empty structures yield 'False':+--+-- >>> biany even isDigit (BiList [] [])+-- False+--+-- @since 4.10.0.0+biany :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool+biany p q = getAny #. bifoldMap (Any . p) (Any . q)++-- | Determines whether all elements of the structure satisfy their appropriate+-- predicate argument. Empty structures yield 'True'.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biall even isDigit (27, 't')+-- False+--+-- >>> biall even isDigit (26, '8')+-- True+--+-- >>> biall even isDigit (Left 27)+-- False+--+-- >>> biall even isDigit (Left 26)+-- True+--+-- >>> biall even isDigit (BiList [26, 52] ['3', '8'])+-- True+--+-- Empty structures yield 'True':+--+-- >>> biall even isDigit (BiList [] [])+-- True+--+-- @since 4.10.0.0+biall :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool+biall p q = getAll #. bifoldMap (All . p) (All . q)++-- | The largest element of a non-empty structure with respect to the+-- given comparison function. Structure order is used as a tie-breaker: if+-- there are multiple largest elements, the rightmost of them is chosen.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bimaximumBy compare (42, 17)+-- 42+--+-- >>> bimaximumBy compare (Left 17)+-- 17+--+-- >>> bimaximumBy compare (BiList [42, 17, 23] [-5, 18])+-- 42+--+-- On empty structures, this function throws an exception:+--+-- >>> bimaximumBy compare (BiList [] [])+-- *** Exception: bifoldr1: empty structure+-- ...+--+-- @since 4.10.0.0+bimaximumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a+bimaximumBy cmp = bifoldr1 max'+  where max' x y = case cmp x y of+                        GT -> x+                        _  -> y++-- | The least element of a non-empty structure with respect to the+-- given comparison function. Structure order is used as a tie-breaker: if+-- there are multiple least elements, the leftmost of them is chosen.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> biminimumBy compare (42, 17)+-- 17+--+-- >>> biminimumBy compare (Left 17)+-- 17+--+-- >>> biminimumBy compare (BiList [42, 17, 23] [-5, 18])+-- -5+--+-- On empty structures, this function throws an exception:+--+-- >>> biminimumBy compare (BiList [] [])+-- *** Exception: bifoldr1: empty structure+-- ...+--+-- @since 4.10.0.0+biminimumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a+biminimumBy cmp = bifoldr1 min'+  where min' x y = case cmp x y of+                        GT -> y+                        _  -> x++-- | 'binotElem' is the negation of 'bielem'.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> binotElem 42 (17, 42)+-- False+--+-- >>> binotElem 42 (17, 43)+-- True+--+-- >>> binotElem 42 (Left 42)+-- False+--+-- >>> binotElem 42 (Right 13)+-- True+--+-- >>> binotElem 42 (BiList [1..5] [1..100])+-- False+--+-- >>> binotElem 42 (BiList [1..5] [1..41])+-- True+--+-- @since 4.10.0.0+binotElem :: (Bifoldable t, Eq a) => a -> t a a-> Bool+binotElem x =  not . bielem x++-- | The 'bifind' function takes a predicate and a structure and returns+-- the leftmost element of the structure matching the predicate, or+-- 'Nothing' if there is no such element.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bifind even (27, 53)+-- Nothing+--+-- >>> bifind even (27, 52)+-- Just 52+--+-- >>> bifind even (26, 52)+-- Just 26+--+-- Empty structures always yield 'Nothing':+--+-- >>> bifind even (BiList [] [])+-- Nothing+--+-- @since 4.10.0.0+bifind :: Bifoldable t => (a -> Bool) -> t a a -> Maybe a+bifind p = getFirst . bifoldMap finder finder+  where finder x = First (if p x then Just x else Nothing)
+ src/Data/Bifoldable1.hs view
@@ -0,0 +1,49 @@+-- |+-- Copyright: Edward Kmett, Oleg Grenrus+-- License: BSD-3-Clause+--++{-# LANGUAGE NoImplicitPrelude #-}+{-# LANGUAGE Safe              #-}++module Data.Bifoldable1 where++import Control.Applicative (Const (..))+import Data.Bifoldable     (Bifoldable (..))+import Data.Semigroup      (Arg (..), Semigroup (..))+import Prelude             (Either (..), id)++class Bifoldable t => Bifoldable1 t where+     bifold1 :: Semigroup m => t m m -> m+     bifold1 = bifoldMap1 id id+     {-# INLINE bifold1 #-}++     bifoldMap1 :: Semigroup m => (a -> m) -> (b -> m) -> t a b -> m++instance Bifoldable1 Arg where+    bifoldMap1 f g (Arg a b) = f a <> g b++instance Bifoldable1 Either where+    bifoldMap1 f _ (Left a) = f a+    bifoldMap1 _ g (Right b) = g b+    {-# INLINE bifoldMap1 #-}++instance Bifoldable1 (,) where+    bifoldMap1 f g (a, b) = f a <> g b+    {-# INLINE bifoldMap1 #-}++instance Bifoldable1 ((,,) x) where+    bifoldMap1 f g (_,a,b) = f a <> g b+    {-# INLINE bifoldMap1 #-}++instance Bifoldable1 ((,,,) x y) where+    bifoldMap1 f g (_,_,a,b) = f a <> g b+    {-# INLINE bifoldMap1 #-}++instance Bifoldable1 ((,,,,) x y z) where+    bifoldMap1 f g (_,_,_,a,b) = f a <> g b+    {-# INLINE bifoldMap1 #-}++instance Bifoldable1 Const where+    bifoldMap1 f _ (Const a) = f a+    {-# INLINE bifoldMap1 #-}
+ src/Data/Bifunctor.hs view
@@ -0,0 +1,182 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE QuantifiedConstraints #-}+{-# LANGUAGE Safe #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Bifunctor+-- Copyright   :  (C) 2008-2014 Edward Kmett,+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- @since 4.8.0.0+----------------------------------------------------------------------------+module Data.Bifunctor+  ( Bifunctor(..)+  ) where++import Control.Applicative  ( Const(..) )+import GHC.Generics ( K1(..) )+import Prelude++-- $setup+-- >>> import Prelude+-- >>> import Data.Char (toUpper)++-- | A bifunctor is a type constructor that takes+-- two type arguments and is a functor in /both/ arguments. That+-- is, unlike with 'Functor', a type constructor such as 'Either'+-- does not need to be partially applied for a 'Bifunctor'+-- instance, and the methods in this class permit mapping+-- functions over the 'Left' value or the 'Right' value,+-- or both at the same time.+--+-- Formally, the class 'Bifunctor' represents a bifunctor+-- from @Hask@ -> @Hask@.+--+-- Intuitively it is a bifunctor where both the first and second+-- arguments are covariant.+--+-- The class definition of a 'Bifunctor' @p@ uses the+-- [QuantifiedConstraints](https://downloads.haskell.org/ghc/latest/docs/users_guide/exts/quantified_constraints.html)+-- language extension to quantify over the first type+-- argument @a@ in its context. The context requires that @p a@+-- must be a 'Functor' for all @a@. In other words a partially+-- applied 'Bifunctor' must be a 'Functor'. This makes 'Functor' a+-- superclass of 'Bifunctor' such that a function with a+-- 'Bifunctor' constraint may use 'fmap' in its implementation.+-- 'Functor' has been a quantified superclass of+-- 'Bifunctor' since base-4.18.0.0.+--+-- You can define a 'Bifunctor' by either defining 'bimap' or by+-- defining both 'first' and 'second'. The 'second' method must+-- agree with 'fmap':+--+-- @'second' ≡ 'fmap'@+--+-- From this it follows that:+--+-- @'second' 'id' ≡ 'id'@+--+-- If you supply 'bimap', you should ensure that:+--+-- @'bimap' 'id' 'id' ≡ 'id'@+--+-- If you supply 'first' and 'second', ensure:+--+-- @+-- 'first' 'id' ≡ 'id'+-- 'second' 'id' ≡ 'id'+-- @+--+-- If you supply both, you should also ensure:+--+-- @'bimap' f g ≡ 'first' f '.' 'second' g@+--+-- These ensure by parametricity:+--+-- @+-- 'bimap'  (f '.' g) (h '.' i) ≡ 'bimap' f h '.' 'bimap' g i+-- 'first'  (f '.' g) ≡ 'first'  f '.' 'first'  g+-- 'second' (f '.' g) ≡ 'second' f '.' 'second' g+-- @+--+-- @since 4.8.0.0+class (forall a. Functor (p a)) => Bifunctor p where+    {-# MINIMAL bimap | first, second #-}++    -- | Map over both arguments at the same time.+    --+    -- @'bimap' f g ≡ 'first' f '.' 'second' g@+    --+    -- ==== __Examples__+    -- >>> bimap toUpper (+1) ('j', 3)+    -- ('J',4)+    --+    -- >>> bimap toUpper (+1) (Left 'j')+    -- Left 'J'+    --+    -- >>> bimap toUpper (+1) (Right 3)+    -- Right 4+    bimap :: (a -> b) -> (c -> d) -> p a c -> p b d+    bimap f g = first f . second g+++    -- | Map covariantly over the first argument.+    --+    -- @'first' f ≡ 'bimap' f 'id'@+    --+    -- ==== __Examples__+    -- >>> first toUpper ('j', 3)+    -- ('J',3)+    --+    -- >>> first toUpper (Left 'j')+    -- Left 'J'+    first :: (a -> b) -> p a c -> p b c+    first f = bimap f id+++    -- | Map covariantly over the second argument.+    --+    -- @'second' ≡ 'bimap' 'id'@+    --+    -- ==== __Examples__+    -- >>> second (+1) ('j', 3)+    -- ('j',4)+    --+    -- >>> second (+1) (Right 3)+    -- Right 4+    second :: (b -> c) -> p a b -> p a c+    second = bimap id+++-- | Class laws for tuples hold only up to laziness. Both+-- 'first' 'id' and 'second' 'id' are lazier than 'id' (and 'fmap' 'id'):+--+-- >>> first id (undefined :: (Int, Word)) `seq` ()+-- ()+-- >>> second id (undefined :: (Int, Word)) `seq` ()+-- ()+-- >>> id (errorWithoutStackTrace "error!" :: (Int, Word)) `seq` ()+-- *** Exception: error!+--+-- @since 4.8.0.0+instance Bifunctor (,) where+    bimap f g ~(a, b) = (f a, g b)++-- | @since 4.8.0.0+instance Bifunctor ((,,) x1) where+    bimap f g ~(x1, a, b) = (x1, f a, g b)++-- | @since 4.8.0.0+instance Bifunctor ((,,,) x1 x2) where+    bimap f g ~(x1, x2, a, b) = (x1, x2, f a, g b)++-- | @since 4.8.0.0+instance Bifunctor ((,,,,) x1 x2 x3) where+    bimap f g ~(x1, x2, x3, a, b) = (x1, x2, x3, f a, g b)++-- | @since 4.8.0.0+instance Bifunctor ((,,,,,) x1 x2 x3 x4) where+    bimap f g ~(x1, x2, x3, x4, a, b) = (x1, x2, x3, x4, f a, g b)++-- | @since 4.8.0.0+instance Bifunctor ((,,,,,,) x1 x2 x3 x4 x5) where+    bimap f g ~(x1, x2, x3, x4, x5, a, b) = (x1, x2, x3, x4, x5, f a, g b)+++-- | @since 4.8.0.0+instance Bifunctor Either where+    bimap f _ (Left a) = Left (f a)+    bimap _ g (Right b) = Right (g b)++-- | @since 4.8.0.0+instance Bifunctor Const where+    bimap f _ (Const a) = Const (f a)++-- | @since 4.9.0.0+instance Bifunctor (K1 i) where+    bimap f _ (K1 c) = K1 (f c)
+ src/Data/Bitraversable.hs view
@@ -0,0 +1,377 @@+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE ScopedTypeVariables #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Bitraversable+-- Copyright   :  (C) 2011-2016 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- @since 4.10.0.0+----------------------------------------------------------------------------+module Data.Bitraversable+  ( Bitraversable(..)+  , bisequenceA+  , bisequence+  , bimapM+  , firstA+  , secondA+  , bifor+  , biforM+  , bimapAccumL+  , bimapAccumR+  , bimapDefault+  , bifoldMapDefault+  ) where++import Control.Applicative+import Data.Bifunctor+import Data.Bifoldable+import GHC.Internal.Data.Coerce+import GHC.Internal.Data.Functor.Identity (Identity(..))+import GHC.Internal.Data.Functor.Utils (StateL(..), StateR(..))+import GHC.Generics (K1(..))+import Prelude++-- $setup+-- >>> import Prelude+-- >>> import GHC.Internal.Data.Maybe+-- >>> import GHC.Internal.Data.List (find)++-- | 'Bitraversable' identifies bifunctorial data structures whose elements can+-- be traversed in order, performing 'Applicative' or 'Monad' actions at each+-- element, and collecting a result structure with the same shape.+--+-- As opposed to 'Traversable' data structures, which have one variety of+-- element on which an action can be performed, 'Bitraversable' data structures+-- have two such varieties of elements.+--+-- A definition of 'bitraverse' must satisfy the following laws:+--+-- [Naturality]+--   @'bitraverse' (t . f) (t . g) ≡ t . 'bitraverse' f g@+--   for every applicative transformation @t@+--+-- [Identity]+--   @'bitraverse' 'Identity' 'Identity' ≡ 'Identity'@+--+-- [Composition]+--   @'Data.Functor.Compose.Compose' .+--    'fmap' ('bitraverse' g1 g2) .+--    'bitraverse' f1 f2+--     ≡ 'bitraverse' ('Data.Functor.Compose.Compose' . 'fmap' g1 . f1)+--                  ('Data.Functor.Compose.Compose' . 'fmap' g2 . f2)@+--+-- where an /applicative transformation/ is a function+--+-- @t :: ('Applicative' f, 'Applicative' g) => f a -> g a@+--+-- preserving the 'Applicative' operations:+--+-- @+-- t ('pure' x) ≡ 'pure' x+-- t (f '<*>' x) ≡ t f '<*>' t x+-- @+--+-- and the identity functor 'Identity' and composition functors+-- 'Data.Functor.Compose.Compose' are from "Data.Functor.Identity" and+-- "Data.Functor.Compose".+--+-- Some simple examples are 'Either' and @(,)@:+--+-- > instance Bitraversable Either where+-- >   bitraverse f _ (Left x) = Left <$> f x+-- >   bitraverse _ g (Right y) = Right <$> g y+-- >+-- > instance Bitraversable (,) where+-- >   bitraverse f g (x, y) = (,) <$> f x <*> g y+--+-- 'Bitraversable' relates to its superclasses in the following ways:+--+-- @+-- 'bimap' f g ≡ 'runIdentity' . 'bitraverse' ('Identity' . f) ('Identity' . g)+-- 'bifoldMap' f g ≡ 'getConst' . 'bitraverse' ('Const' . f) ('Const' . g)+-- @+--+-- These are available as 'bimapDefault' and 'bifoldMapDefault' respectively.+--+-- If the type is also an instance of 'Traversable', then+-- it must satisfy (up to laziness):+--+-- @+-- 'traverse' ≡ 'bitraverse' 'pure'+-- @+--+-- @since 4.10.0.0+class (Bifunctor t, Bifoldable t) => Bitraversable t where+  -- | Evaluates the relevant functions at each element in the structure,+  -- running the action, and builds a new structure with the same shape, using+  -- the results produced from sequencing the actions.+  --+  -- @'bitraverse' f g ≡ 'bisequenceA' . 'bimap' f g@+  --+  -- For a version that ignores the results, see 'bitraverse_'.+  --+  -- ==== __Examples__+  --+  -- Basic usage:+  --+  -- >>> bitraverse listToMaybe (find odd) (Left [])+  -- Nothing+  --+  -- >>> bitraverse listToMaybe (find odd) (Left [1, 2, 3])+  -- Just (Left 1)+  --+  -- >>> bitraverse listToMaybe (find odd) (Right [4, 5])+  -- Just (Right 5)+  --+  -- >>> bitraverse listToMaybe (find odd) ([1, 2, 3], [4, 5])+  -- Just (1,5)+  --+  -- >>> bitraverse listToMaybe (find odd) ([], [4, 5])+  -- Nothing+  --+  -- @since 4.10.0.0+  bitraverse :: Applicative f => (a -> f c) -> (b -> f d) -> t a b -> f (t c d)++-- | Alias for 'bisequence'.+--+-- @since 4.10.0.0+bisequenceA :: (Bitraversable t, Applicative f) => t (f a) (f b) -> f (t a b)+bisequenceA = bisequence++-- | Alias for 'bitraverse'.+--+-- @since 4.10.0.0+bimapM :: (Bitraversable t, Applicative f)+       => (a -> f c) -> (b -> f d) -> t a b -> f (t c d)+bimapM = bitraverse++-- | Sequences all the actions in a structure, building a new structure with+-- the same shape using the results of the actions. For a version that ignores+-- the results, see 'bisequence_'.+--+-- @'bisequence' ≡ 'bitraverse' 'id' 'id'@+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bisequence (Just 4, Nothing)+-- Nothing+--+-- >>> bisequence (Just 4, Just 5)+-- Just (4,5)+--+-- >>> bisequence ([1, 2, 3], [4, 5])+-- [(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]+--+-- @since 4.10.0.0+bisequence :: (Bitraversable t, Applicative f) => t (f a) (f b) -> f (t a b)+bisequence = bitraverse id id++-- | Traverses only over the first argument.+--+-- @'firstA' f ≡ 'bitraverse' f 'pure'@++-- ==== __Examples__+--+-- Basic usage:+--+-- >>> firstA listToMaybe (Left [])+-- Nothing+--+-- >>> firstA listToMaybe (Left [1, 2, 3])+-- Just (Left 1)+--+-- >>> firstA listToMaybe (Right [4, 5])+-- Just (Right [4, 5])+--+-- >>> firstA listToMaybe ([1, 2, 3], [4, 5])+-- Just (1,[4, 5])+--+-- >>> firstA listToMaybe ([], [4, 5])+-- Nothing++-- @since 4.21.0.0+firstA :: Bitraversable t => Applicative f => (a -> f c) -> t a b -> f (t c b)+firstA f = bitraverse f pure++-- | Traverses only over the second argument.+--+-- @'secondA' f ≡ 'bitraverse' 'pure' f@+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> secondA (find odd) (Left [])+-- Just (Left [])+--+-- >>> secondA (find odd) (Left [1, 2, 3])+-- Just (Left [1,2,3])+--+-- >>> secondA (find odd) (Right [4, 5])+-- Just (Right 5)+--+-- >>> secondA (find odd) ([1, 2, 3], [4, 5])+-- Just ([1,2,3],5)+--+-- >>> secondA (find odd) ([1,2,3], [4])+-- Nothing+--+-- @since 4.21.0.0+secondA :: Bitraversable t => Applicative f => (b -> f c) -> t a b -> f (t a c)+secondA f = bitraverse pure f++-- | Class laws for tuples hold only up to laziness. The+-- Bitraversable methods are lazier than their Traversable counterparts.+-- For example the law @'bitraverse' 'pure' ≡ 'traverse'@ does+-- not hold for tuples if laziness is exploited:+--+-- >>> (bitraverse pure pure undefined :: IO (Int, Word)) `seq` ()+-- ()+-- >>> (traverse pure (errorWithoutStackTrace "error!") :: IO (Int, Word)) `seq` ()+-- *** Exception: error!+--+-- @since 4.10.0.0+instance Bitraversable (,) where+  bitraverse f g ~(a, b) = liftA2 (,) (f a) (g b)++-- | @since 4.10.0.0+instance Bitraversable ((,,) x) where+  bitraverse f g ~(x, a, b) = liftA2 ((,,) x) (f a) (g b)++-- | @since 4.10.0.0+instance Bitraversable ((,,,) x y) where+  bitraverse f g ~(x, y, a, b) = liftA2 ((,,,) x y) (f a) (g b)++-- | @since 4.10.0.0+instance Bitraversable ((,,,,) x y z) where+  bitraverse f g ~(x, y, z, a, b) = liftA2 ((,,,,) x y z) (f a) (g b)++-- | @since 4.10.0.0+instance Bitraversable ((,,,,,) x y z w) where+  bitraverse f g ~(x, y, z, w, a, b) = liftA2 ((,,,,,) x y z w) (f a) (g b)++-- | @since 4.10.0.0+instance Bitraversable ((,,,,,,) x y z w v) where+  bitraverse f g ~(x, y, z, w, v, a, b) =+    liftA2 ((,,,,,,) x y z w v) (f a) (g b)++-- | @since 4.10.0.0+instance Bitraversable Either where+  bitraverse f _ (Left a) = Left <$> f a+  bitraverse _ g (Right b) = Right <$> g b++-- | @since 4.10.0.0+instance Bitraversable Const where+  bitraverse f _ (Const a) = Const <$> f a++-- | @since 4.10.0.0+instance Bitraversable (K1 i) where+  bitraverse f _ (K1 c) = K1 <$> f c++-- | 'bifor' is 'bitraverse' with the structure as the first argument. For a+-- version that ignores the results, see 'bifor_'.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bifor (Left []) listToMaybe (find even)+-- Nothing+--+-- >>> bifor (Left [1, 2, 3]) listToMaybe (find even)+-- Just (Left 1)+--+-- >>> bifor (Right [4, 5]) listToMaybe (find even)+-- Just (Right 4)+--+-- >>> bifor ([1, 2, 3], [4, 5]) listToMaybe (find even)+-- Just (1,4)+--+-- >>> bifor ([], [4, 5]) listToMaybe (find even)+-- Nothing+--+-- @since 4.10.0.0+bifor :: (Bitraversable t, Applicative f)+      => t a b -> (a -> f c) -> (b -> f d) -> f (t c d)+bifor t f g = bitraverse f g t++-- | Alias for 'bifor'.+--+-- @since 4.10.0.0+biforM :: (Bitraversable t, Applicative f)+       => t a b -> (a -> f c) -> (b -> f d) -> f (t c d)+biforM = bifor++-- | The 'bimapAccumL' function behaves like a combination of 'bimap' and+-- 'bifoldl'; it traverses a structure from left to right, threading a state+-- of type @a@ and using the given actions to compute new elements for the+-- structure.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bimapAccumL (\acc bool -> (acc + 1, show bool)) (\acc string -> (acc * 2, reverse string)) 3 (True, "foo")+-- (8,("True","oof"))+--+-- @since 4.10.0.0+bimapAccumL :: Bitraversable t => (a -> b -> (a, c)) -> (a -> d -> (a, e))+            -> a -> t b d -> (a, t c e)+bimapAccumL f g s t+  = runStateL (bitraverse (StateL . flip f) (StateL . flip g) t) s++-- | The 'bimapAccumR' function behaves like a combination of 'bimap' and+-- 'bifoldr'; it traverses a structure from right to left, threading a state+-- of type @a@ and using the given actions to compute new elements for the+-- structure.+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> bimapAccumR (\acc bool -> (acc + 1, show bool)) (\acc string -> (acc * 2, reverse string)) 3 (True, "foo")+-- (7,("True","oof"))+--+-- @since 4.10.0.0+bimapAccumR :: Bitraversable t => (a -> b -> (a, c)) -> (a -> d -> (a, e))+            -> a -> t b d -> (a, t c e)+bimapAccumR f g s t+  = runStateR (bitraverse (StateR . flip f) (StateR . flip g) t) s++-- | A default definition of 'bimap' in terms of the 'Bitraversable'+-- operations.+--+-- @'bimapDefault' f g ≡+--     'runIdentity' . 'bitraverse' ('Identity' . f) ('Identity' . g)@+--+-- @since 4.10.0.0+bimapDefault :: forall t a b c d . Bitraversable t+             => (a -> b) -> (c -> d) -> t a c -> t b d+-- See Note [Function coercion] in Data.Functor.Utils.+bimapDefault = coerce+  (bitraverse :: (a -> Identity b)+              -> (c -> Identity d) -> t a c -> Identity (t b d))+{-# INLINE bimapDefault #-}++-- | A default definition of 'bifoldMap' in terms of the 'Bitraversable'+-- operations.+--+-- @'bifoldMapDefault' f g ≡+--    'getConst' . 'bitraverse' ('Const' . f) ('Const' . g)@+--+-- @since 4.10.0.0+bifoldMapDefault :: forall t m a b . (Bitraversable t, Monoid m)+                 => (a -> m) -> (b -> m) -> t a b -> m+-- See Note [Function coercion] in Data.Functor.Utils.+bifoldMapDefault = coerce+  (bitraverse :: (a -> Const m ())+              -> (b -> Const m ()) -> t a b -> Const m (t () ()))+{-# INLINE bifoldMapDefault #-}
+ src/Data/Bits.hs view
@@ -0,0 +1,42 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Bits+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- This module defines bitwise operations for signed and unsigned+-- integers.  Instances of the class 'Bits' for the 'Int' and+-- 'Integer' types are available from this module, and instances for+-- explicitly sized integral types are available from the+-- "Data.Int" and "Data.Word" modules.+--++module Data.Bits+    (-- *  Type classes+     Bits((.&.), (.|.), xor, complement, shift, rotate, zeroBits, bit, setBit, clearBit, complementBit, testBit, bitSizeMaybe, bitSize, isSigned, shiftL, shiftR, unsafeShiftL, unsafeShiftR, rotateL, rotateR, popCount),+     FiniteBits(finiteBitSize, countLeadingZeros, countTrailingZeros),+     -- *  Extra functions+     bitDefault,+     testBitDefault,+     popCountDefault,+     toIntegralSized,+     oneBits,+     (.^.),+     (.>>.),+     (.<<.),+     (!>>.),+     (!<<.),+     -- *  Newtypes+     And(..),+     Ior(..),+     Xor(..),+     Iff(..)+     ) where++import GHC.Internal.Data.Bits
+ src/Data/Bool.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Bool+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The 'Bool' type and related functions.+--++module Data.Bool+    (-- *  Booleans+     Bool(..),+     -- **  Operations+     (&&),+     (||),+     not,+     otherwise,+     bool+     ) where++import GHC.Internal.Data.Bool
+ src/Data/Bounded.hs view
@@ -0,0 +1,25 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE NoImplicitPrelude #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Bounded+-- Copyright   :  (c) The University of Glasgow, 1992-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  cvs-ghc@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (GHC extensions)+--+-- The 'Bounded' class.+--+-- @since 4.21.0.0+--+-----------------------------------------------------------------------------++module Data.Bounded+    ( Bounded(..)+    ) where++import GHC.Enum+
+ src/Data/Char.hs view
@@ -0,0 +1,292 @@+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE NoImplicitPrelude #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Char+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The Char type and associated operations.+--+-----------------------------------------------------------------------------++module Data.Char+    (+      Char++    -- * Character classification+    -- | Unicode characters are divided into letters, numbers, marks,+    -- punctuation, symbols, separators (including spaces) and others+    -- (including control characters).+    , isControl, isSpace+    , isLower, isLowerCase, isUpper, isUpperCase, isAlpha, isAlphaNum, isPrint+    , isDigit, isOctDigit, isHexDigit+    , isLetter, isMark, isNumber, isPunctuation, isSymbol, isSeparator++    -- ** Subranges+    , isAscii, isLatin1+    , isAsciiUpper, isAsciiLower++    -- ** Unicode general categories+    , GeneralCategory(..), generalCategory++    -- * Case conversion+    , toUpper, toLower, toTitle++    -- * Single digit characters+    , digitToInt+    , intToDigit++    -- * Numeric representations+    , ord+    , chr++    -- * String representations+    , showLitChar+    , lexLitChar+    , readLitChar+    ) where++import GHC.Internal.Base+import GHC.Internal.Char+import GHC.Internal.Real (fromIntegral)+import GHC.Internal.Show+import GHC.Internal.Read (readLitChar, lexLitChar)+import GHC.Internal.Unicode+import GHC.Internal.Num++-- $setup+-- Allow the use of Prelude in doctests.+-- >>> import Prelude++-- | Convert a single digit 'Char' to the corresponding 'Int'.  This+-- function fails unless its argument satisfies 'isHexDigit', but+-- recognises both upper- and lower-case hexadecimal digits (that+-- is, @\'0\'@..@\'9\'@, @\'a\'@..@\'f\'@, @\'A\'@..@\'F\'@).+--+-- ==== __Examples__+--+-- Characters @\'0\'@ through @\'9\'@ are converted properly to+-- @0..9@:+--+-- >>> map digitToInt ['0'..'9']+-- [0,1,2,3,4,5,6,7,8,9]+--+-- Both upper- and lower-case @\'A\'@ through @\'F\'@ are converted+-- as well, to @10..15@.+--+-- >>> map digitToInt ['a'..'f']+-- [10,11,12,13,14,15]+-- >>> map digitToInt ['A'..'F']+-- [10,11,12,13,14,15]+--+-- Anything else throws an exception:+--+-- >>> digitToInt 'G'+-- *** Exception: Char.digitToInt: not a digit 'G'+-- >>> digitToInt '♥'+-- *** Exception: Char.digitToInt: not a digit '\9829'+--+digitToInt :: Char -> Int+digitToInt c+  | (fromIntegral dec::Word) <= 9 = dec+  | (fromIntegral hexl::Word) <= 5 = hexl + 10+  | (fromIntegral hexu::Word) <= 5 = hexu + 10+  | otherwise = errorWithoutStackTrace ("Char.digitToInt: not a digit " ++ show c) -- sigh+  where+    dec = ord c - ord '0'+    hexl = ord c - ord 'a'+    hexu = ord c - ord 'A'++-- derived character classifiers++-- | Selects alphabetic Unicode characters (lower-case, upper-case and+-- title-case letters, plus letters of caseless scripts and+-- modifiers letters). This function is equivalent to+-- 'Data.Char.isAlpha'.+--+-- This function returns 'True' if its argument has one of the+-- following 'GeneralCategory's, or 'False' otherwise:+--+-- * 'UppercaseLetter'+-- * 'LowercaseLetter'+-- * 'TitlecaseLetter'+-- * 'ModifierLetter'+-- * 'OtherLetter'+--+-- These classes are defined in the+-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,+-- part of the Unicode standard. The same document defines what is+-- and is not a \"Letter\".+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> isLetter 'a'+-- True+-- >>> isLetter 'A'+-- True+-- >>> isLetter 'λ'+-- True+-- >>> isLetter '0'+-- False+-- >>> isLetter '%'+-- False+-- >>> isLetter '♥'+-- False+-- >>> isLetter '\31'+-- False+--+-- Ensure that 'isLetter' and 'isAlpha' are equivalent.+--+-- >>> let chars = [(chr 0)..]+-- >>> let letters = map isLetter chars+-- >>> let alphas = map isAlpha chars+-- >>> letters == alphas+-- True+--+isLetter :: Char -> Bool+isLetter c = case generalCategory c of+        UppercaseLetter         -> True+        LowercaseLetter         -> True+        TitlecaseLetter         -> True+        ModifierLetter          -> True+        OtherLetter             -> True+        _                       -> False++-- | Selects Unicode mark characters, for example accents and the+-- like, which combine with preceding characters.+--+-- This function returns 'True' if its argument has one of the+-- following 'GeneralCategory's, or 'False' otherwise:+--+-- * 'NonSpacingMark'+-- * 'SpacingCombiningMark'+-- * 'EnclosingMark'+--+-- These classes are defined in the+-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,+-- part of the Unicode standard. The same document defines what is+-- and is not a \"Mark\".+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> isMark 'a'+-- False+-- >>> isMark '0'+-- False+--+-- Combining marks such as accent characters usually need to follow+-- another character before they become printable:+--+-- >>> map isMark "ò"+-- [False,True]+--+-- Puns are not necessarily supported:+--+-- >>> isMark '✓'+-- False+--+isMark :: Char -> Bool+isMark c = case generalCategory c of+        NonSpacingMark          -> True+        SpacingCombiningMark    -> True+        EnclosingMark           -> True+        _                       -> False++-- | Selects Unicode numeric characters, including digits from various+-- scripts, Roman numerals, et cetera.+--+-- This function returns 'True' if its argument has one of the+-- following 'GeneralCategory's, or 'False' otherwise:+--+-- * 'DecimalNumber'+-- * 'LetterNumber'+-- * 'OtherNumber'+--+-- These classes are defined in the+-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,+-- part of the Unicode standard. The same document defines what is+-- and is not a \"Number\".+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> isNumber 'a'+-- False+-- >>> isNumber '%'+-- False+-- >>> isNumber '3'+-- True+--+-- ASCII @\'0\'@ through @\'9\'@ are all numbers:+--+-- >>> and $ map isNumber ['0'..'9']+-- True+--+-- Unicode Roman numerals are \"numbers\" as well:+--+-- >>> isNumber 'Ⅸ'+-- True+--+isNumber :: Char -> Bool+isNumber c = case generalCategory c of+        DecimalNumber           -> True+        LetterNumber            -> True+        OtherNumber             -> True+        _                       -> False++-- | Selects Unicode space and separator characters.+--+-- This function returns 'True' if its argument has one of the+-- following 'GeneralCategory's, or 'False' otherwise:+--+-- * 'Space'+-- * 'LineSeparator'+-- * 'ParagraphSeparator'+--+-- These classes are defined in the+-- <http://www.unicode.org/reports/tr44/tr44-14.html#GC_Values_Table Unicode Character Database>,+-- part of the Unicode standard. The same document defines what is+-- and is not a \"Separator\".+--+-- ==== __Examples__+--+-- Basic usage:+--+-- >>> isSeparator 'a'+-- False+-- >>> isSeparator '6'+-- False+-- >>> isSeparator ' '+-- True+--+-- Warning: newlines and tab characters are not considered+-- separators.+--+-- >>> isSeparator '\n'+-- False+-- >>> isSeparator '\t'+-- False+--+-- But some more exotic characters are (like HTML's @&nbsp;@):+--+-- >>> isSeparator '\160'+-- True+--+isSeparator :: Char -> Bool+isSeparator c = case generalCategory c of+        Space                   -> True+        LineSeparator           -> True+        ParagraphSeparator      -> True+        _                       -> False+
+ src/Data/Coerce.hs view
@@ -0,0 +1,24 @@+-- |+--+-- Module      :  Data.Coerce+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Safe coercions between data types.+--+-- More in-depth information can be found on the+-- <https://gitlab.haskell.org/ghc/ghc/wikis/roles Roles wiki page>+--+-- @since 4.7.0.0++module Data.Coerce+    (-- *  Safe coercions+     coerce,+     Coercible+     ) where++import GHC.Internal.Data.Coerce
+ src/Data/Complex.hs view
@@ -0,0 +1,387 @@+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DeriveTraversable #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Complex+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Complex numbers.+--+-----------------------------------------------------------------------------++module Data.Complex+        (+        -- * Rectangular form+          Complex((:+))++        , realPart+        , imagPart+        -- * Polar form+        , mkPolar+        , cis+        , polar+        , magnitude+        , phase+        -- * Conjugate+        , conjugate++        )  where++import Prelude hiding (Applicative(..))+import GHC.Internal.Base (Applicative (..))+import GHC.Generics (Generic, Generic1)+import GHC.Internal.Float (Floating(..))+import GHC.Internal.Data.Data (Data)+import Foreign (Storable, castPtr, peek, poke, pokeElemOff, peekElemOff, sizeOf,+                alignment)+import GHC.Internal.Control.Monad.Fix (MonadFix(..))+import Control.Monad.Zip (MonadZip(..))++infix  6  :+++-- $setup+-- >>> import Prelude++-- -----------------------------------------------------------------------------+-- The Complex type++-- | A data type representing complex numbers.+--+-- You can read about complex numbers [on wikipedia](https://en.wikipedia.org/wiki/Complex_number).+--+-- In haskell, complex numbers are represented as @a :+ b@ which can be thought of+-- as representing \(a + bi\). For a complex number @z@, @'abs' z@ is a number with the 'magnitude' of @z@,+-- but oriented in the positive real direction, whereas @'signum' z@+-- has the 'phase' of @z@, but unit 'magnitude'.+-- Apart from the loss of precision due to IEEE754 floating point numbers,+-- it holds that @z == 'abs' z * 'signum' z@.+--+-- Note that `Complex`'s instances inherit the deficiencies from the type+-- parameter's. For example, @Complex Float@'s 'Eq' instance has similar+-- problems to `Float`'s.+--+-- As can be seen in the examples, the 'Foldable'+-- and 'Traversable' instances traverse the real part first.+--+-- ==== __Examples__+--+-- >>> (5.0 :+ 2.5) + 6.5+-- 11.5 :+ 2.5+--+-- >>> abs (1.0 :+ 1.0) - sqrt 2.0+-- 0.0 :+ 0.0+--+-- >>> abs (signum (4.0 :+ 3.0))+-- 1.0 :+ 0.0+--+-- >>> foldr (:) [] (1 :+ 2)+-- [1,2]+--+-- >>> mapM print (1 :+ 2)+-- 1+-- 2+-- () :+ ()+data Complex a+  = !a :+ !a    -- ^ forms a complex number from its real and imaginary+                -- rectangular components.+        deriving ( Eq          -- ^ @since 2.01+                 , Show        -- ^ @since 2.01+                 , Read        -- ^ @since 2.01+                 , Data        -- ^ @since 2.01+                 , Generic     -- ^ @since 4.9.0.0+                 , Generic1    -- ^ @since 4.9.0.0+                 , Functor     -- ^ @since 4.9.0.0+                 , Foldable    -- ^ @since 4.9.0.0+                 , Traversable -- ^ @since 4.9.0.0+                 )+++-- -----------------------------------------------------------------------------+-- Functions over Complex++-- | Extracts the real part of a complex number.+--+-- ==== __Examples__+--+-- >>> realPart (5.0 :+ 3.0)+-- 5.0+--+-- >>> realPart ((5.0 :+ 3.0) * (2.0 :+ 3.0))+-- 1.0+realPart :: Complex a -> a+realPart (x :+ _) =  x++-- | Extracts the imaginary part of a complex number.+--+-- ==== __Examples__+--+-- >>> imagPart (5.0 :+ 3.0)+-- 3.0+--+-- >>> imagPart ((5.0 :+ 3.0) * (2.0 :+ 3.0))+-- 21.0+imagPart :: Complex a -> a+imagPart (_ :+ y) =  y++-- | The 'conjugate' of a complex number.+--+-- prop> conjugate (conjugate x) = x+--+-- ==== __Examples__+--+-- >>> conjugate (3.0 :+ 3.0)+-- 3.0 :+ (-3.0)+--+-- >>> conjugate ((3.0 :+ 3.0) * (2.0 :+ 2.0))+-- 0.0 :+ (-12.0)+{-# SPECIALISE conjugate :: Complex Double -> Complex Double #-}+conjugate        :: Num a => Complex a -> Complex a+conjugate (x:+y) =  x :+ (-y)++-- | Form a complex number from 'polar' components of 'magnitude' and 'phase'.+--+-- ==== __Examples__+--+-- >>> mkPolar 1 (pi / 4)+-- 0.7071067811865476 :+ 0.7071067811865475+--+-- >>> mkPolar 1 0+-- 1.0 :+ 0.0+{-# SPECIALISE mkPolar :: Double -> Double -> Complex Double #-}+mkPolar          :: Floating a => a -> a -> Complex a+mkPolar r theta  =  r * cos theta :+ r * sin theta++-- | @'cis' t@ is a complex value with 'magnitude' @1@+-- and 'phase' @t@ (modulo @2*'pi'@).+--+-- @+-- 'cis' = 'mkPolar' 1+-- @+--+-- ==== __Examples__+--+-- >>> cis 0+-- 1.0 :+ 0.0+--+-- The following examples are not perfectly zero due to [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)+--+-- >>> cis pi+-- (-1.0) :+ 1.2246467991473532e-16+--+-- >>> cis (4 * pi) - cis (2 * pi)+-- 0.0 :+ (-2.4492935982947064e-16)+{-# SPECIALISE cis :: Double -> Complex Double #-}+cis              :: Floating a => a -> Complex a+cis theta        =  cos theta :+ sin theta++-- | The function 'polar' takes a complex number and+-- returns a ('magnitude', 'phase') pair in canonical form:+-- the 'magnitude' is non-negative, and the 'phase' in the range @(-'pi', 'pi']@;+-- if the 'magnitude' is zero, then so is the 'phase'.+--+-- @'polar' z = ('magnitude' z, 'phase' z)@+--+-- ==== __Examples__+--+-- >>> polar (1.0 :+ 1.0)+-- (1.4142135623730951,0.7853981633974483)+--+-- >>> polar ((-1.0) :+ 0.0)+-- (1.0,3.141592653589793)+--+-- >>> polar (0.0 :+ 0.0)+-- (0.0,0.0)+{-# SPECIALISE polar :: Complex Double -> (Double,Double) #-}+polar            :: (RealFloat a) => Complex a -> (a,a)+polar z          =  (magnitude z, phase z)++-- | The non-negative 'magnitude' of a complex number.+--+-- ==== __Examples__+--+-- >>> magnitude (1.0 :+ 1.0)+-- 1.4142135623730951+--+-- >>> magnitude (1.0 + 0.0)+-- 1.0+--+-- >>> magnitude (0.0 :+ (-5.0))+-- 5.0+{-# SPECIALISE magnitude :: Complex Double -> Double #-}+magnitude :: (RealFloat a) => Complex a -> a+magnitude (x:+y) =  scaleFloat k+                     (sqrt (sqr (scaleFloat mk x) + sqr (scaleFloat mk y)))+                    where k  = max (exponent x) (exponent y)+                          mk = - k+                          sqr z = z * z++-- | The 'phase' of a complex number, in the range @(-'pi', 'pi']@.+-- If the 'magnitude' is zero, then so is the 'phase'.+--+-- ==== __Examples__+--+-- >>> phase (0.5 :+ 0.5) / pi+-- 0.25+--+-- >>> phase (0 :+ 4) / pi+-- 0.5+{-# SPECIALISE phase :: Complex Double -> Double #-}+phase :: (RealFloat a) => Complex a -> a+phase (0 :+ 0)   = 0            -- SLPJ July 97 from John Peterson+phase (x:+y)     = atan2 y x+++-- -----------------------------------------------------------------------------+-- Instances of Complex++-- | @since 2.01+instance  (RealFloat a) => Num (Complex a)  where+    {-# SPECIALISE instance Num (Complex Float) #-}+    {-# SPECIALISE instance Num (Complex Double) #-}+    (x:+y) + (x':+y')   =  (x+x') :+ (y+y')+    (x:+y) - (x':+y')   =  (x-x') :+ (y-y')+    (x:+y) * (x':+y')   =  (x*x'-y*y') :+ (x*y'+y*x')+    negate (x:+y)       =  negate x :+ negate y+    abs z               =  magnitude z :+ 0+    signum (0:+0)       =  0+    signum z@(x:+y)     =  x/r :+ y/r  where r = magnitude z+    fromInteger n       =  fromInteger n :+ 0++-- | @since 2.01+instance  (RealFloat a) => Fractional (Complex a)  where+    {-# SPECIALISE instance Fractional (Complex Float) #-}+    {-# SPECIALISE instance Fractional (Complex Double) #-}+    (x:+y) / (x':+y')   =  (x*x''+y*y'') / d :+ (y*x''-x*y'') / d+                           where x'' = scaleFloat k x'+                                 y'' = scaleFloat k y'+                                 k   = - max (exponent x') (exponent y')+                                 d   = x'*x'' + y'*y''++    fromRational a      =  fromRational a :+ 0++-- | @since 2.01+instance  (RealFloat a) => Floating (Complex a) where+    {-# SPECIALISE instance Floating (Complex Float) #-}+    {-# SPECIALISE instance Floating (Complex Double) #-}+    pi             =  pi :+ 0+    exp (x:+y)     =  expx * cos y :+ expx * sin y+                      where expx = exp x+    log z          =  log (magnitude z) :+ phase z++    x ** y = case (x,y) of+      (_ , (0:+0))  -> 1 :+ 0+      ((0:+0), (exp_re:+_)) -> case compare exp_re 0 of+                 GT -> 0 :+ 0+                 LT -> inf :+ 0+                 EQ -> nan :+ nan+      ((re:+im), (exp_re:+_))+        | (isInfinite re || isInfinite im) -> case compare exp_re 0 of+                 GT -> inf :+ 0+                 LT -> 0 :+ 0+                 EQ -> nan :+ nan+        | otherwise -> exp (log x * y)+      where+        inf = 1/0+        nan = 0/0++    sqrt (0:+0)    =  0+    sqrt z@(x:+y)  =  u :+ (if y < 0 then -v else v)+                      where (u,v) = if x < 0 then (v',u') else (u',v')+                            v'    = abs y / (u'*2)+                            u'    = sqrt ((magnitude z + abs x) / 2)++    sin (x:+y)     =  sin x * cosh y :+ cos x * sinh y+    cos (x:+y)     =  cos x * cosh y :+ (- sin x * sinh y)+    tan (x:+y)     =  (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))+                      where sinx  = sin x+                            cosx  = cos x+                            sinhy = sinh y+                            coshy = cosh y++    sinh (x:+y)    =  cos y * sinh x :+ sin  y * cosh x+    cosh (x:+y)    =  cos y * cosh x :+ sin y * sinh x+    tanh (x:+y)    =  (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)+                      where siny  = sin y+                            cosy  = cos y+                            sinhx = sinh x+                            coshx = cosh x++    asin z@(x:+y)  =  y':+(-x')+                      where  (x':+y') = log (((-y):+x) + sqrt (1 - z*z))+    acos z         =  y'':+(-x'')+                      where (x'':+y'') = log (z + ((-y'):+x'))+                            (x':+y')   = sqrt (1 - z*z)+    atan z@(x:+y)  =  y':+(-x')+                      where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))++    asinh z        =  log (z + sqrt (1+z*z))+    -- Take care to allow (-1)::Complex, fixing #8532+    acosh z        =  log (z + (sqrt $ z+1) * (sqrt $ z-1))+    atanh z        =  0.5 * log ((1.0+z) / (1.0-z))++    log1p x@(a :+ b)+      | abs a < 0.5 && abs b < 0.5+      , u <- 2*a + a*a + b*b = log1p (u/(1 + sqrt(u+1))) :+ atan2 (1 + a) b+      | otherwise = log (1 + x)+    {-# INLINE log1p #-}++    expm1 x@(a :+ b)+      | a*a + b*b < 1+      , u <- expm1 a+      , v <- sin (b/2)+      , w <- -2*v*v = (u*w + u + w) :+ (u+1)*sin b+      | otherwise = exp x - 1+    {-# INLINE expm1 #-}++-- | @since 4.8.0.0+instance Storable a => Storable (Complex a) where+    sizeOf a       = 2 * sizeOf (realPart a)+    alignment a    = alignment (realPart a)+    peek p           = do+                        q <- return $ castPtr p+                        r <- peek q+                        i <- peekElemOff q 1+                        return (r :+ i)+    poke p (r :+ i)  = do+                        q <-return $  (castPtr p)+                        poke q r+                        pokeElemOff q 1 i++-- | @since 4.9.0.0+instance Applicative Complex where+  pure a = a :+ a+  f :+ g <*> a :+ b = f a :+ g b+  liftA2 f (x :+ y) (a :+ b) = f x a :+ f y b++-- | @since 4.9.0.0+instance Monad Complex where+  a :+ b >>= f = realPart (f a) :+ imagPart (f b)++-- | @since 4.15.0.0+instance MonadZip Complex where+  mzipWith = liftA2++-- | @since 4.15.0.0+instance MonadFix Complex where+  mfix f = (let a :+ _ = f a in a) :+ (let _ :+ a = f a in a)++-- -----------------------------------------------------------------------------+-- Rules on Complex++{-# RULES++"realToFrac/a->Complex Double"+  realToFrac = \x -> realToFrac x :+ (0 :: Double)++"realToFrac/a->Complex Float"+  realToFrac = \x -> realToFrac x :+ (0 :: Float)++  #-}
+ src/Data/Data.hs view
@@ -0,0 +1,101 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  Data.Data+-- Copyright   :  (c) The University of Glasgow, CWI 2001--2004+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (local universal quantification)+--+-- This module provides the 'Data' class with its primitives for+-- generic programming, along with instances for many datatypes. It+-- corresponds to a merge between the previous "Data.Generics.Basics"+-- and almost all of "Data.Generics.Instances". The instances that are+-- not present in this module were moved to the+-- @Data.Generics.Instances@ module in the @syb@ package.+--+-- \"Scrap your boilerplate\" --- Generic programming in Haskell.  See+-- <https://wiki.haskell.org/Research_papers/Generics#Scrap_your_boilerplate.21>.+--++module Data.Data (++        -- * Module Data.Typeable re-exported for convenience+        module Data.Typeable,++        -- * The Data class for processing constructor applications+        Data(+                gfoldl,+                gunfold,+                toConstr,+                dataTypeOf,+                dataCast1,      -- mediate types and unary type constructors+                dataCast2,      -- mediate types and binary type constructors+                -- Generic maps defined in terms of gfoldl+                gmapT,+                gmapQ,+                gmapQl,+                gmapQr,+                gmapQi,+                gmapM,+                gmapMp,+                gmapMo+            ),++        -- * Datatype representations+        DataType,       -- abstract+        -- ** Constructors+        mkDataType,+        mkIntType,+        mkFloatType,+        mkCharType,+        mkNoRepType,+        -- ** Observers+        dataTypeName,+        DataRep(..),+        dataTypeRep,+        -- ** Convenience functions+        repConstr,+        isAlgType,+        dataTypeConstrs,+        indexConstr,+        maxConstrIndex,+        isNorepType,++        -- * Data constructor representations+        Constr,         -- abstract+        ConIndex,       -- alias for Int, start at 1+        Fixity(..),+        -- ** Constructors+        mkConstr,+        mkConstrTag,+        mkIntegralConstr,+        mkRealConstr,+        mkCharConstr,+        -- ** Observers+        constrType,+        ConstrRep(..),+        constrRep,+        constrFields,+        constrFixity,+        -- ** Convenience function: algebraic data types+        constrIndex,+        -- ** From strings to constructors and vice versa: all data types+        showConstr,+        readConstr,++        -- * Convenience functions: take type constructors apart+        tyconUQname,+        tyconModule,++        -- * Generic operations defined in terms of 'gunfold'+        fromConstr,+        fromConstrB,+        fromConstrM++  ) where++import GHC.Internal.Data.Data+import Data.Typeable
+ src/Data/Dynamic.hs view
@@ -0,0 +1,36 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Dynamic+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The Dynamic interface provides basic support for dynamic types.+--+-- Operations for injecting values of arbitrary type into+-- a dynamically typed value, Dynamic, are provided, together+-- with operations for converting dynamic values into a concrete+-- (monomorphic) type.+--++module Data.Dynamic+    (-- *  The @Dynamic@ type+     Dynamic(..),+     -- *  Converting to and from @Dynamic@+     toDyn,+     fromDyn,+     fromDynamic,+     -- *  Applying functions of dynamic type+     dynApply,+     dynApp,+     dynTypeRep,+     -- *  Convenience re-exports+     Typeable+     ) where++import GHC.Internal.Data.Dynamic
+ src/Data/Either.hs view
@@ -0,0 +1,28 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Either+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The Either type, and associated operations.+--++module Data.Either+    (Either(..),+     either,+     lefts,+     rights,+     isLeft,+     isRight,+     fromLeft,+     fromRight,+     partitionEithers+     ) where++import GHC.Internal.Data.Either
+ src/Data/Enum.hs view
@@ -0,0 +1,54 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE NoImplicitPrelude #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Enum+-- Copyright   :  (c) The University of Glasgow, 1992-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (GHC extensions)+--+-- The 'Enum' class.+--+-- @since 4.20.0.0+--+-----------------------------------------------------------------------------++module Data.Enum+    ( Enum(..)+    , {-# DEPRECATED "Bounded should be imported from Data.Bounded" #-}+      Bounded(..)+    , enumerate+    ) where++import GHC.Internal.Enum++-- | Returns a list of all values of an enum type+--+-- 'enumerate' is often used to list all values of a custom enum data structure, such as a custom Color enum below:+--+-- @+-- data Color = Yellow | Red | Blue+--     deriving (Enum, Bounded, Show)+--+-- allColors :: [Color]+-- allColors = enumerate+-- -- Result: [Yellow, Red, Blue]+-- @+--+-- Note that you need to derive the 'Bounded' type class as well, only 'Enum' is not enough.+-- 'Enum' allows for sequential enumeration, while 'Bounded' provides the 'minBound' and 'maxBound' values.+--+-- 'enumerate' is commonly used together with the TypeApplications syntax. Here is an example of using 'enumerate' to retrieve all values of the 'Ordering' type:+--+-- >> enumerate @Ordering+-- [LT, EQ, GT]+--+-- The '@' symbol here is provided by the TypeApplications language extension.+--+-- @since base-4.22.0.0+enumerate :: (Enum a, Bounded a) => [a]+enumerate = [minBound .. maxBound]
+ src/Data/Eq.hs view
@@ -0,0 +1,20 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Eq+-- Copyright   :  (c) The University of Glasgow 2005+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Equality+--++module Data.Eq+    (Eq(..)+     ) where++import GHC.Internal.Data.Eq
+ src/Data/Fixed.hs view
@@ -0,0 +1,458 @@+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE TemplateHaskellQuotes #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Fixed+-- Copyright   :  (c) Ashley Yakeley 2005, 2006, 2009+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  Ashley Yakeley <ashley@semantic.org>+-- Stability   :  stable+-- Portability :  portable+--+-- This module defines a 'Fixed' type for working with fixed-point arithmetic.+-- Fixed-point arithmetic represents fractional numbers with a fixed number of+-- digits for their fractional part. This is different to the behaviour of the floating-point+-- number types 'Float' and 'Double', because the number of digits of the+-- fractional part of 'Float' and 'Double' numbers depends on the size of the number.+-- Fixed point arithmetic is frequently used in financial mathematics, where they+-- are used for representing decimal currencies.+--+-- The type 'Fixed' is used for fixed-point fractional numbers, which are internally+-- represented as an 'Integer'. The type 'Fixed' takes one parameter, which should implement+-- the typeclass 'HasResolution', to specify the number of digits of the fractional part.+-- This module provides instances of the `HasResolution` typeclass for arbitrary typelevel+-- natural numbers, and for some canonical important fixed-point representations.+--+-- This module also contains generalisations of 'div', 'mod', and 'divMod' to+-- work with any 'Real' instance.+--+-- Automatic conversion between different 'Fixed' can be performed through+-- 'realToFrac', bear in mind that converting to a fixed with a smaller+-- resolution will truncate the number, losing information.+--+-- >>> realToFrac (0.123456 :: Pico) :: Milli+-- 0.123+--+-----------------------------------------------------------------------------++module Data.Fixed+(   -- * The Fixed Type+    Fixed(..), HasResolution(..),+    showFixed,+    -- * Resolution \/ Scaling Factors+    -- | The resolution or scaling factor determines the number of digits in the fractional part.+    --+    -- +------------+----------------------+--------------------------+--------------------------++    -- | Resolution | Scaling Factor       | Synonym for \"Fixed EX\" | show (12345 :: Fixed EX) |+    -- +============+======================+==========================+==========================++    -- | E0         | 1\/1                 | Uni                      | 12345.0                  |+    -- +------------+----------------------+--------------------------+--------------------------++    -- | E1         | 1\/10                | Deci                     | 1234.5                   |+    -- +------------+----------------------+--------------------------+--------------------------++    -- | E2         | 1\/100               | Centi                    | 123.45                   |+    -- +------------+----------------------+--------------------------+--------------------------++    -- | E3         | 1\/1 000             | Milli                    | 12.345                   |+    -- +------------+----------------------+--------------------------+--------------------------++    -- | E6         | 1\/1 000 000         | Micro                    | 0.012345                 |+    -- +------------+----------------------+--------------------------+--------------------------++    -- | E9         | 1\/1 000 000 000     | Nano                     | 0.000012345              |+    -- +------------+----------------------+--------------------------+--------------------------++    -- | E12        | 1\/1 000 000 000 000 | Pico                     | 0.000000012345           |+    -- +------------+----------------------+--------------------------+--------------------------++    --++    -- ** 1\/1+    E0,Uni,+    -- ** 1\/10+    E1,Deci,+    -- ** 1\/100+    E2,Centi,+    -- ** 1\/1 000+    E3,Milli,+    -- ** 1\/1 000 000+    E6,Micro,+    -- ** 1\/1 000 000 000+    E9,Nano,+    -- ** 1\/1 000 000 000 000+    E12,Pico,+    -- * Generalized Functions on Real's+    div',+    mod',+    divMod'+) where++import GHC.Internal.Data.Data+import GHC.Internal.TypeLits (KnownNat, natVal)+import GHC.Internal.Read+import GHC.Internal.Text.ParserCombinators.ReadPrec+import GHC.Internal.Text.Read.Lex+import qualified GHC.Internal.TH.Syntax as TH+import qualified GHC.Internal.TH.Lift as TH+import Data.Typeable+import Prelude++-- $setup+-- >>> import Prelude++default () -- avoid any defaulting shenanigans++-- | Generalisation of 'div' to any instance of 'Real'+div' :: (Real a,Integral b) => a -> a -> b+div' n d = floor ((toRational n) / (toRational d))++-- | Generalisation of 'divMod' to any instance of 'Real'+divMod' :: (Real a,Integral b) => a -> a -> (b,a)+divMod' n d = (f,n - (fromIntegral f) * d) where+    f = div' n d++-- | Generalisation of 'mod' to any instance of 'Real'+mod' :: (Real a) => a -> a -> a+mod' n d = n - (fromInteger f) * d where+    f = div' n d++-- | The type of fixed-point fractional numbers.+--   The type parameter specifies the number of digits of the fractional part and should be an instance of the 'HasResolution' typeclass.+--+-- === __Examples__+--+-- @+--  MkFixed 12345 :: Fixed E3+-- @+newtype Fixed (a :: k) = MkFixed Integer+        deriving ( Eq  -- ^ @since 2.01+                 , Ord -- ^ @since 2.01+                 )++-- We do this because the automatically derived Data instance requires (Data a) context.+-- Our manual instance has the more general (Typeable a) context.+tyFixed :: DataType+tyFixed = mkDataType "Data.Fixed.Fixed" [conMkFixed]++conMkFixed :: Constr+conMkFixed = mkConstr tyFixed "MkFixed" [] Prefix++-- | @since 4.1.0.0+instance (Typeable k,Typeable a) => Data (Fixed (a :: k)) where+    gfoldl k z (MkFixed a) = k (z MkFixed) a+    gunfold k z _ = k (z MkFixed)+    dataTypeOf _ = tyFixed+    toConstr _ = conMkFixed++-- |+-- @since template-haskell-2.19.0.0+-- @since base-4.21.0.0+instance TH.Lift (Fixed a) where+  liftTyped x = TH.unsafeCodeCoerce (TH.lift x)+  lift (MkFixed x) = [| MkFixed x |]++-- | Types which can be used as a resolution argument to the 'Fixed' type constructor must implement the 'HasResolution'  typeclass.+class HasResolution (a :: k) where+    -- | Provide the resolution for a fixed-point fractional number.+    resolution :: p a -> Integer++-- | For example, @Fixed 1000@ will give you a 'Fixed' with a resolution of 1000.+instance KnownNat n => HasResolution n where+    resolution _ = natVal (Proxy :: Proxy n)++withType :: (Proxy a -> f a) -> f a+withType foo = foo Proxy++withResolution :: (HasResolution a) => (Integer -> f a) -> f a+withResolution foo = withType (foo . resolution)++-- | @since 2.01+--+-- Recall that, for numeric types, 'succ' and 'pred' typically add and subtract+-- @1@, respectively. This is not true in the case of 'Fixed', whose successor+-- and predecessor functions intuitively return the "next" and "previous" values+-- in the enumeration. The results of these functions thus depend on the+-- resolution of the 'Fixed' value. For example, when enumerating values of+-- resolution @10^-3@ of @type Milli = Fixed E3@,+--+-- >>> succ (0.000 :: Milli)+-- 0.001+--+-- and likewise+--+-- >>> pred (0.000 :: Milli)+-- -0.001+--+-- In other words, 'succ' and 'pred' increment and decrement a fixed-precision+-- value by the least amount such that the value's resolution is unchanged.+-- For example, @10^-12@ is the smallest (positive) amount that can be added to+-- a value of @type Pico = Fixed E12@ without changing its resolution, and so+--+-- >>> succ (0.000000000000 :: Pico)+-- 0.000000000001+--+-- and similarly+--+-- >>> pred (0.000000000000 :: Pico)+-- -0.000000000001+--+--+-- This is worth bearing in mind when defining 'Fixed' arithmetic sequences. In+-- particular, you may be forgiven for thinking the sequence+--+-- @+--   [1..10] :: [Pico]+-- @+--+--+-- evaluates to @[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] :: [Pico]@.+--+-- However, this is not true. On the contrary, similarly to the above+-- implementations of 'succ' and 'pred', @enumFromTo :: Pico -> Pico -> [Pico]@+-- has a "step size" of @10^-12@. Hence, the list @[1..10] :: [Pico]@ has+-- the form+--+-- @+--   [1.000000000000, 1.00000000001, 1.00000000002, ..., 10.000000000000]+-- @+--+--+-- and contains @9 * 10^12 + 1@ values.+instance Enum (Fixed a) where+    succ (MkFixed a) = MkFixed (succ a)+    pred (MkFixed a) = MkFixed (pred a)+    toEnum = MkFixed . toEnum+    fromEnum (MkFixed a) = fromEnum a+    enumFrom (MkFixed a) = fmap MkFixed (enumFrom a)+    enumFromThen (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromThen a b)+    enumFromTo (MkFixed a) (MkFixed b) = fmap MkFixed (enumFromTo a b)+    enumFromThenTo (MkFixed a) (MkFixed b) (MkFixed c) = fmap MkFixed (enumFromThenTo a b c)++-- | @since 2.01+--+-- Multiplication is not associative or distributive:+--+-- >>> (0.2 * 0.6 :: Deci) * 0.9 == 0.2 * (0.6 * 0.9)+-- False+--+-- >>> (0.1 + 0.1 :: Deci) * 0.5 == 0.1 * 0.5 + 0.1 * 0.5+-- False+instance (HasResolution a) => Num (Fixed a) where+    (MkFixed a) + (MkFixed b) = MkFixed (a + b)+    (MkFixed a) - (MkFixed b) = MkFixed (a - b)+    fa@(MkFixed a) * (MkFixed b) = MkFixed (div (a * b) (resolution fa))+    negate (MkFixed a) = MkFixed (negate a)+    abs (MkFixed a) = MkFixed (abs a)+    signum (MkFixed a) = fromInteger (signum a)+    fromInteger i = withResolution (\res -> MkFixed (i * res))++-- | @since 2.01+instance (HasResolution a) => Real (Fixed a) where+    toRational fa@(MkFixed a) = (toRational a) / (toRational (resolution fa))++-- | @since 2.01+instance (HasResolution a) => Fractional (Fixed a) where+    fa@(MkFixed a) / (MkFixed b) = MkFixed (div (a * (resolution fa)) b)+    recip fa@(MkFixed a) = MkFixed (div (res * res) a) where+        res = resolution fa+    fromRational r = withResolution (\res -> MkFixed (floor (r * (toRational res))))++-- | @since 2.01+instance (HasResolution a) => RealFrac (Fixed a) where+    properFraction a = (i,a - (fromIntegral i)) where+        i = truncate a+    truncate f = truncate (toRational f)+    round f = round (toRational f)+    ceiling f = ceiling (toRational f)+    floor f = floor (toRational f)++chopZeros :: Integer -> String+chopZeros 0 = ""+chopZeros a | mod a 10 == 0 = chopZeros (div a 10)+chopZeros a = show a++-- only works for positive a+showIntegerZeros :: Bool -> Int -> Integer -> String+showIntegerZeros True _ 0 = ""+showIntegerZeros chopTrailingZeros digits a = replicate (digits - length s) '0' ++ s' where+    s = show a+    s' = if chopTrailingZeros then chopZeros a else s++withDot :: String -> String+withDot "" = ""+withDot s = '.':s++-- | First arg is whether to chop off trailing zeros+--+-- === __Examples__+--+-- >>> showFixed True  (MkFixed 10000 :: Fixed E3)+-- "10"+--+-- >>> showFixed False (MkFixed 10000 :: Fixed E3)+-- "10.000"+--+showFixed :: (HasResolution a) => Bool -> Fixed a -> String+showFixed chopTrailingZeros fa@(MkFixed a) | a < 0 = "-" ++ (showFixed chopTrailingZeros (asTypeOf (MkFixed (negate a)) fa))+showFixed chopTrailingZeros fa@(MkFixed a) = (show i) ++ (withDot (showIntegerZeros chopTrailingZeros digits fracNum)) where+    res = resolution fa+    (i,d) = divMod a res+    -- enough digits to be unambiguous+    digits = ceiling (logBase 10 (fromInteger res) :: Double)+    maxnum = 10 ^ digits+    -- read floors, so show must ceil for `read . show = id` to hold. See #9240+    fracNum = divCeil (d * maxnum) res+    divCeil x y = (x + y - 1) `div` y++-- | @since 2.01+instance (HasResolution a) => Show (Fixed a) where+    showsPrec p n = showParen (p > 6 && n < 0) $ showString $ showFixed False n++-- | @since 4.3.0.0+instance (HasResolution a) => Read (Fixed a) where+    readPrec     = readNumber convertFixed+    readListPrec = readListPrecDefault+    readList     = readListDefault++convertFixed :: forall a . HasResolution a => Lexeme -> ReadPrec (Fixed a)+convertFixed (Number n)+ | Just (i, f) <- numberToFixed e n =+    return (fromInteger i + (fromInteger f / (10 ^ e)))+    where r = resolution (Proxy :: Proxy a)+          -- round 'e' up to help make the 'read . show == id' property+          -- possible also for cases where 'resolution' is not a+          -- power-of-10, such as e.g. when 'resolution = 128'+          e = ceiling (logBase 10 (fromInteger r) :: Double)+convertFixed _ = pfail++-- | Resolution of 1, this works the same as Integer.+data E0++-- | @since 4.1.0.0+instance HasResolution E0 where+    resolution _ = 1++-- | Resolution of 1, this works the same as Integer.+--+-- === __Examples__+--+-- >>> show (MkFixed 12345 :: Fixed E0)+-- "12345.0"+--+-- >>> show (MkFixed 12345 :: Uni)+-- "12345.0"+--+type Uni = Fixed E0++-- | Resolution of 10^-1 = .1+data E1++-- | @since 4.1.0.0+instance HasResolution E1 where+    resolution _ = 10++-- | Resolution of 10^-1 = .1+--+-- === __Examples__+--+-- >>> show (MkFixed 12345 :: Fixed E1)+-- "1234.5"+--+-- >>> show (MkFixed 12345 :: Deci)+-- "1234.5"+--+type Deci = Fixed E1++-- | Resolution of 10^-2 = .01, useful for many monetary currencies+data E2++-- | @since 4.1.0.0+instance HasResolution E2 where+    resolution _ = 100++-- | Resolution of 10^-2 = .01, useful for many monetary currencies+--+-- === __Examples__+--+-- >>> show (MkFixed 12345 :: Fixed E2)+-- "123.45"+--+-- >>> show (MkFixed 12345 :: Centi)+-- "123.45"+--+type Centi = Fixed E2++-- | Resolution of 10^-3 = .001+data E3++-- | @since 4.1.0.0+instance HasResolution E3 where+    resolution _ = 1000++-- | Resolution of 10^-3 = .001+--+-- === __Examples__+--+-- >>> show (MkFixed 12345 :: Fixed E3)+-- "12.345"+--+-- >>> show (MkFixed 12345 :: Milli)+-- "12.345"+--+type Milli = Fixed E3++-- | Resolution of 10^-6 = .000001+data E6++-- | @since 2.01+instance HasResolution E6 where+    resolution _ = 1000000++-- | Resolution of 10^-6 = .000001+--+-- === __Examples__+--+-- >>> show (MkFixed 12345 :: Fixed E6)+-- "0.012345"+--+-- >>> show (MkFixed 12345 :: Micro)+-- "0.012345"+--+type Micro = Fixed E6++-- | Resolution of 10^-9 = .000000001+data E9++-- | @since 4.1.0.0+instance HasResolution E9 where+    resolution _ = 1000000000++-- | Resolution of 10^-9 = .000000001+--+-- === __Examples__+--+-- >>> show (MkFixed 12345 :: Fixed E9)+-- "0.000012345"+--+-- >>> show (MkFixed 12345 :: Nano)+-- "0.000012345"+--+type Nano = Fixed E9++-- | Resolution of 10^-12 = .000000000001+data E12++-- | @since 2.01+instance HasResolution E12 where+    resolution _ = 1000000000000++-- | Resolution of 10^-12 = .000000000001+--+-- === __Examples__+--+-- >>> show (MkFixed 12345 :: Fixed E12)+-- "0.000000012345"+--+-- >>> show (MkFixed 12345 :: Pico)+-- "0.000000012345"+--+type Pico = Fixed E12
+ src/Data/Foldable.hs view
@@ -0,0 +1,1119 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  Data.Foldable+-- Copyright   :  Ross Paterson 2005+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Class of data structures that can be folded to a summary value.+--++module Data.Foldable (+    Foldable(..),+    -- * Special biased folds+    foldrM,+    foldlM,+    -- * Folding actions+    -- ** Applicative actions+    traverse_,+    for_,+    sequenceA_,+    asum,+    -- ** Monadic actions+    mapM_,+    forM_,+    sequence_,+    msum,+    -- * Specialized folds+    concat,+    concatMap,+    and,+    or,+    any,+    all,+    maximumBy,+    minimumBy,+    -- * Searches+    notElem,+    find++    -- * Overview+    -- $overview++    -- ** Expectation of efficient left-to-right iteration+    -- $chirality++    -- ** Recursive and corecursive reduction+    -- $reduction++    -- *** Strict recursive folds+    -- $strict++    -- **** List of strict functions+    -- $strictlist++    -- *** Lazy corecursive folds+    -- $lazy++    -- **** List of lazy functions+    -- $lazylist++    -- *** Short-circuit folds+    -- $shortcircuit++    -- **** List of short-circuit functions+    -- $shortlist++    -- *** Hybrid folds+    -- $hybrid++    -- ** Generative Recursion+    -- $generative++    -- ** Avoiding multi-pass folds+    -- $multipass++    -- * Defining instances+    -- $instances++    -- *** Being strict by being lazy+    -- $strictlazy++    -- * Laws+    -- $laws++    -- * Notes+    -- $notes++    -- ** Generally linear-time `elem`+    -- $linear++    -- * See also+    -- $also+    ) where++import GHC.Internal.Data.Foldable++-- $setup+-- >>> import Prelude+-- >>> import qualified Data.List as List++-- $overview+--+-- #overview#+-- The Foldable class generalises some common "Data.List" functions to+-- structures that can be reduced to a summary value one element at a time.+--+-- == Left and right folds+--+-- #leftright#+-- The contribution of each element to the final result is combined with an+-- accumulator via a suitable /operator/.  The operator may be explicitly+-- provided by the caller as with `foldr` or may be implicit as in `length`.+-- In the case of `foldMap`, the caller provides a function mapping each+-- element into a suitable 'Monoid', which makes it possible to merge the+-- per-element contributions via that monoid's `mappend` function.+--+-- A key distinction is between left-associative and right-associative+-- folds:+--+-- * In left-associative folds the accumulator is a partial fold over the+--   elements that __precede__ the current element, and is passed to the+--   operator as its first (left) argument.  The outermost application of the+--   operator merges the contribution of the last element of the structure with+--   the contributions of all its predecessors.+--+-- * In right-associative folds the accumulator is a partial fold over the+--   elements that __follow__ the current element, and is passed to the+--   operator as its second (right) argument.  The outermost application of+--   the operator merges the contribution of the first element of the structure+--   with the contributions of all its successors.+--+-- These two types of folds are typified by the left-associative strict+-- 'foldl'' and the right-associative lazy `foldr`.+--+-- @+-- 'foldl'' :: Foldable t => (b -> a -> b) -> b -> t a -> b+-- `foldr`  :: Foldable t => (a -> b -> b) -> b -> t a -> b+-- @+--+-- Example usage:+--+-- >>> foldl' (+) 0 [1..100]+-- 5050+-- >>> foldr (&&) True (List.repeat False)+-- False+--+-- The first argument of both is an explicit /operator/ that merges the+-- contribution of an element of the structure with a partial fold over,+-- respectively, either the preceding or following elements of the structure.+--+-- The second argument of both is an initial accumulator value @z@ of type+-- @b@.  This is the result of the fold when the structure is empty.+-- When the structure is non-empty, this is the accumulator value merged with+-- the first element in left-associative folds, or with the last element in+-- right-associative folds.+--+-- The third and final argument is a @Foldable@ structure containing elements+-- @(a, b, c, &#x2026;)@.+--+-- * __'foldl''__ takes an operator argument of the form:+--+--     @+--     f :: b -- accumulated fold of the initial elements+--       -> a -- current element+--       -> b -- updated fold, inclusive of current element+--     @+--+--     If the structure's last element is @y@, the result of the fold is:+--+--     @+--     g y . &#x2026; . g c . g b . g a $ z+--       where g element !acc = f acc element+--     @+--+--     Since 'foldl'' is strict in the accumulator, this is always+--     a [strict](#strict) reduction with no opportunity for early return or+--     intermediate results.  The structure must be finite, since no result is+--     returned until the last element is processed.  The advantage of+--     strictness is space efficiency: the final result can be computed without+--     storing a potentially deep stack of lazy intermediate results.+--+-- * __`foldr`__ takes an operator argument of the form:+--+--     @+--     f :: a -- current element+--       -> b -- accumulated fold of the remaining elements+--       -> b -- updated fold, inclusive of current element+--     @+--+--     the result of the fold is:+--+--     @f a . f b . f c . &#x2026; $ z@+--+--     If each call of @f@ on the current element @e@, (referenced as @(f e)@+--     below) returns a structure in which its second argument is captured in a+--     lazily-evaluated component, then the fold of the remaining elements is+--     available to the caller of `foldr` as a pending computation (thunk) that+--     is computed only when that component is evaluated.+--+--     Alternatively, if any of the @(f e)@ ignore their second argument, the+--     fold stops there, with the remaining elements unused.  As a result,+--     `foldr` is well suited to define both [corecursive](#corec)+--     and [short-circuit](#short) reductions.+--+--     When the operator is always strict in its second argument, 'foldl'' is+--     generally a better choice than `foldr`.  When `foldr` is called with a+--     strict operator, evaluation cannot begin until the last element is+--     reached, by which point a deep stack of pending function applications+--     may have been built up in memory.+--++-- $chirality+--+-- #chirality#+-- Foldable structures are generally expected to be efficiently iterable from+-- left to right. Right-to-left iteration may be substantially more costly, or+-- even impossible (as with, for example, infinite lists).  The text in the+-- sections that follow that suggests performance differences between+-- left-associative and right-associative folds assumes /left-handed/+-- structures in which left-to-right iteration is cheaper than right-to-left+-- iteration.+--+-- In finite structures for which right-to-left sequencing no less efficient+-- than left-to-right sequencing, there is no inherent performance distinction+-- between left-associative and right-associative folds.  If the structure's+-- @Foldable@ instance takes advantage of this symmetry to also make strict+-- right folds space-efficient and lazy left folds corecursive, one need only+-- take care to choose either a strict or lazy method for the task at hand.+--+-- Foldable instances for symmetric structures should strive to provide equally+-- performant left-associative and right-associative interfaces. The main+-- limitations are:+--+-- * The lazy 'fold', 'foldMap' and 'toList' methods have no right-associative+--   counterparts.+-- * The strict 'foldMap'' method has no left-associative counterpart.+--+-- Thus, for some foldable structures 'foldr'' is just as efficient as 'foldl''+-- for strict reduction, and 'foldl' may be just as appropriate for corecursive+-- folds as 'foldr'.+--+-- Finally, in some less common structures (e.g. /snoc/ lists) right to left+-- iterations are cheaper than left to right.  Such structures are poor+-- candidates for a @Foldable@ instance, and are perhaps best handled via their+-- type-specific interfaces.  If nevertheless a @Foldable@ instance is+-- provided, the material in the sections that follow applies to these also, by+-- replacing each method with one with the opposite associativity (when+-- available) and switching the order of arguments in the fold's /operator/.+--+-- You may need to pay careful attention to strictness of the fold's /operator/+-- when its strictness is different between its first and second argument.+-- For example, while @('+')@ is expected to be commutative and strict in both+-- arguments, the list concatenation operator @('++')@ is not commutative and+-- is only strict in the initial constructor of its first argument.  The fold:+--+-- > myconcat xs = foldr (\a b -> a ++ b) [] xs+--+-- is substantially cheaper (linear in the length of the consumed portion of+-- the final list, thus e.g. constant time/space for just the first element)+-- than:+--+-- > revconcat xs = foldr (\a b -> b ++ a) [] xs+--+-- In which the total cost scales up with both the number of lists combined and+-- the number of elements ultimately consumed.  A more efficient way to combine+-- lists in reverse order, is to use:+--+-- > revconcat = foldr (++) [] . reverse++--------------++-- $reduction+--+-- As observed in the [above description](#leftright) of left and right folds,+-- there are three general ways in which a structure can be reduced to a+-- summary value:+--+-- * __Recursive__ reduction, which is strict in all the elements of the+--   structure.  This produces a single final result only after processing the+--   entire input structure, and so the input must be finite.+--+-- * __Corecursion__, which yields intermediate results as it encounters+--   additional input elements.  Lazy processing of the remaining elements+--   makes the intermediate results available even before the rest of the+--   input is processed.  The input may be unbounded, and the caller can+--   stop processing intermediate results early.+--+-- * __Short-circuit__ reduction, which examines some initial sequence of the+--   input elements, but stops once a termination condition is met, returning a+--   final result based only on the elements considered up to that point.  The+--   remaining elements are not considered.  The input should generally be+--   finite, because the termination condition might otherwise never be met.+--+-- Whether a fold is recursive, corecursive or short-circuiting can depend on+-- both the method chosen to perform the fold and on the operator passed to+-- that method (which may be implicit, as with the `mappend` method of a monoid+-- instance).+--+-- There are also hybrid cases, where the method and/or operator are not well+-- suited to the task at hand, resulting in a fold that fails to yield+-- incremental results until the entire input is processed, or fails to+-- strictly evaluate results as it goes, deferring all the work to the+-- evaluation of a large final thunk.  Such cases should be avoided, either by+-- selecting a more appropriate @Foldable@ method, or by tailoring the operator+-- to the chosen method.+--+-- The distinction between these types of folds is critical, both in deciding+-- which @Foldable@ method to use to perform the reduction efficiently, and in+-- writing @Foldable@ instances for new structures.  Below is a more detailed+-- overview of each type.++--------------++-- $strict+-- #strict#+--+-- Common examples of strict recursive reduction are the various /aggregate/+-- functions, like 'sum', 'product', 'length', as well as more complex+-- summaries such as frequency counts.  These functions return only a single+-- value after processing the entire input structure.  In such cases, lazy+-- processing of the tail of the input structure is generally not only+-- unnecessary, but also inefficient.  Thus, these and similar folds should be+-- implemented in terms of strict left-associative @Foldable@ methods (typically+-- 'foldl'') to perform an efficient reduction in constant space.+--+-- Conversely, an implementation of @Foldable@ for a new structure should+-- ensure that 'foldl'' actually performs a strict left-associative reduction.+--+-- The 'foldMap'' method is a special case of 'foldl'', in which the initial+-- accumulator is `mempty` and the operator is @mappend . f@, where @f@ maps+-- each input element into the 'Monoid' in question.  Therefore, 'foldMap'' is+-- an appropriate choice under essentially the same conditions as 'foldl'', and+-- its implementation for a given @Foldable@ structure should also be a strict+-- left-associative reduction.+--+-- While the examples below are not necessarily the most optimal definitions of+-- the intended functions, they are all cases in which 'foldMap'' is far more+-- appropriate (as well as more efficient) than the lazy `foldMap`.+--+-- > length  = getSum     . foldMap' (const (Sum 1))+-- > sum     = getSum     . foldMap' Sum+-- > product = getProduct . foldMap' Product+--+-- [ The actual default definitions employ coercions to optimise out+--   'getSum' and 'getProduct'. ]++--------------++-- $strictlist+--+-- The full list of strict recursive functions in this module is:+--+-- * Provided the operator is strict in its left argument:+--+--     @'foldl'' :: Foldable t => (b -> a -> b) -> b -> t a -> b@+--+-- * Provided `mappend` is strict in its left argument:+--+--     @'foldMap'' :: (Foldable t, Monoid m) => (a -> m) -> t a -> m@+--+-- * Provided the instance is correctly defined:+--+--     @+--     `length`    :: Foldable t => t a -> Int+--     `sum`       :: (Foldable t, Num a) => t a -> a+--     `product`   :: (Foldable t, Num a) => t a -> a+--     `maximum`   :: (Foldable t, Ord a) => t a -> a+--     `minimum`   :: (Foldable t, Ord a) => t a -> a+--     `maximumBy` :: Foldable t => (a -> a -> Ordering) -> t a -> a+--     `minimumBy` :: Foldable t => (a -> a -> Ordering) -> t a -> a+--     @++--------------++-- $lazy+--+-- #corec#+-- Common examples of lazy corecursive reduction are functions that map and+-- flatten a structure to a lazy stream of result values, i.e.  an iterator+-- over the transformed input elements.  In such cases, it is important to+-- choose a @Foldable@ method that is lazy in the tail of the structure, such+-- as `foldr` (or `foldMap`, if the result @Monoid@ has a lazy `mappend` as+-- with e.g. ByteString Builders).+--+-- Conversely, an implementation of `foldr` for a structure that can+-- accommodate a large (and possibly unbounded) number of elements is expected+-- to be lazy in the tail of the input, allowing operators that are lazy in the+-- accumulator to yield intermediate results incrementally.  Such folds are+-- right-associative, with the tail of the stream returned as a lazily+-- evaluated component of the result (an element of a tuple or some other+-- non-strict constructor, e.g. the @(:)@ constructor for lists).+--+-- The @toList@ function below lazily transforms a @Foldable@ structure to a+-- List.  Note that this transformation may be lossy, e.g.  for a keyed+-- container (@Map@, @HashMap@, &#x2026;) the output stream holds only the+-- values, not the keys.  Lossless transformations to\/from lists of @(key,+-- value)@ pairs are typically available in the modules for the specific+-- container types.+--+-- > toList = foldr (:) []+--+-- A more complex example is concatenation of a list of lists expressed as a+-- nested right fold (bypassing @('++')@).  We can check that the definition is+-- indeed lazy by folding an infinite list of lists, and taking an initial+-- segment.+--+-- >>> myconcat = foldr (\x z -> foldr (:) z x) []+-- >>> List.take 15 $ myconcat $ List.map (\i -> [0..i]) [0..]+-- [0,0,1,0,1,2,0,1,2,3,0,1,2,3,4]+--+-- Of course in this case another way to achieve the same result is via a+-- list comprehension:+--+-- > myconcat xss = [x | xs <- xss, x <- xs]++--------------++-- $lazylist+--+-- The full list of lazy corecursive functions in this module is:+--+-- * Provided the reduction function is lazy in its second argument,+--   (otherwise best to use a strict recursive reduction):+--+--     @+--     `foldr`  :: Foldable t => (a -> b -> b) -> b -> t a -> b+--     `foldr1` :: Foldable t => (a -> a -> a) -> t a -> a+--     @+--+-- * Provided the 'Monoid' `mappend` is lazy in its second argument+--   (otherwise best to use a strict recursive reduction):+--+--     @+--     `fold`    :: Foldable t => Monoid m => t m -> m+--     `foldMap` :: Foldable t => Monoid m => (a -> m) -> t a -> m+--     @+--+-- * Provided the instance is correctly defined:+--+--     @+--     `toList`    :: Foldable t => t a -> [a]+--     `concat`    :: Foldable t => t [a] -> [a]+--     `concatMap` :: Foldable t => (a -> [b]) -> t a -> [b]+--     @++--------------++-- $shortcircuit+--+-- #short#+-- Examples of short-circuit reduction include various boolean predicates that+-- test whether some or all the elements of a structure satisfy a given+-- condition.  Because these don't necessarily consume the entire list, they+-- typically employ `foldr` with an operator that is conditionally strict in+-- its second argument.  Once the termination condition is met the second+-- argument (tail of the input structure) is ignored.  No result is returned+-- until that happens.+--+-- The key distinguishing feature of these folds is /conditional/ strictness+-- in the second argument, it is sometimes evaluated and sometimes not.+--+-- The simplest (degenerate case) of these is 'null', which determines whether+-- a structure is empty or not.  This only needs to look at the first element,+-- and only to the extent of whether it exists or not, and not its value.  In+-- this case termination is guaranteed, and infinite input structures are fine.+-- Its default definition is of course in terms of the lazy 'foldr':+--+-- > null = foldr (\_ _ -> False) True+--+-- A more general example is `any`, which applies a predicate to each input+-- element in turn until it finds the first one for which the predicate is+-- true, at which point it returns success.  If, in an infinite input stream+-- the predicate is false for all the elements, `any` will not terminate,+-- but since it runs in constant space, it typically won't run out of memory,+-- it'll just loop forever.++--------------++-- $shortlist+--+-- The full list of short-circuit folds in this module is:+--+-- * Boolean predicate folds.+--   These functions examine elements strictly until a condition is met,+--   but then return a result ignoring the rest (lazy in the tail).  These+--   may loop forever given an unbounded input where no elements satisfy the+--   termination condition.+--+--     @+--     `null`    :: Foldable t => t a -> Bool+--     `elem`    :: Foldable t => Eq a => a -> t a -> Bool+--     `notElem` :: (Foldable t, Eq a) => a -> t a -> Bool+--     `and`     :: Foldable t => t Bool -> Bool+--     `or`      :: Foldable t => t Bool -> Bool+--     `find`    :: Foldable t => (a -> Bool) -> t a -> Maybe a+--     `any`     :: Foldable t => (a -> Bool) -> t a -> Bool+--     `all`     :: Foldable t => (a -> Bool) -> t a -> Bool+--     @+--+-- * Many instances of @('<|>')@ (e.g. the 'Maybe' instance) are conditionally+--   lazy, and use or don't use their second argument depending on the value+--   of the first.  These are used with the folds below, which terminate as+--   early as possible, but otherwise generally keep going.  Some instances+--   (e.g. for List) are always strict, but the result is lazy in the tail+--   of the output, so that `asum` for a list of lists is in fact corecursive.+--   These folds are defined in terms of `foldr`.+--+--     @+--     `asum` :: (Foldable t, Alternative f) => t (f a) -> f a+--     `msum` :: (Foldable t, MonadPlus m) => t (m a) -> m a+--     @+--+-- * Likewise, the @('*>')@ operator in some `Applicative` functors, and @('>>')@+--   in some monads are conditionally lazy and can /short-circuit/ a chain of+--   computations.  The below folds will terminate as early as possible, but+--   even infinite loops can be productive here, when evaluated solely for+--   their stream of IO side-effects.  See "Data.Traversable#effectful"+--   for discussion of related functions.+--+--     @+--     `traverse_`  :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f ()+--     `for_`       :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f ()+--     `sequenceA_` :: (Foldable t, Applicative f) => t (f a) -> f ()+--     `mapM_`      :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()+--     `forM_`      :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()+--     `sequence_`  :: (Foldable t, Monad m) => t (m a) -> m ()+--     @+--+-- * Finally, there's one more special case, `foldlM`:+--+--     @`foldlM` :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b@+--+--     The sequencing of monadic effects proceeds from left to right.  If at+--     some step the bind operator @('>>=')@ short-circuits (as with, e.g.,+--     'mzero' with a 'MonadPlus', or an exception with a 'MonadThrow', etc.),+--     then the evaluated effects will be from an initial portion of the+--     element sequence.+--+--     > :set -XBangPatterns+--     > import Control.Monad+--     > import Control.Monad.Trans.Class+--     > import Control.Monad.Trans.Maybe+--     > import Data.Foldable+--     > let f !_ e = when (e > 3) mzero >> lift (print e)+--     > runMaybeT $ foldlM f () [0..]+--     0+--     1+--     2+--     3+--     Nothing+--+--     Contrast this with `foldrM`, which sequences monadic effects from right+--     to left, and therefore diverges when folding an unbounded input+--     structure without ever having the opportunity to short-circuit.+--+--     > let f e _ = when (e > 3) mzero >> lift (print e)+--     > runMaybeT $ foldrM f () [0..]+--     ...hangs...+--+--     When the structure is finite `foldrM` performs the monadic effects from+--     right to left, possibly short-circuiting after processing a tail portion+--     of the element sequence.+--+--     > let f e _ = when (e < 3) mzero >> lift (print e)+--     > runMaybeT $ foldrM f () [0..5]+--     5+--     4+--     3+--     Nothing++--------------++-- $hybrid+--+-- The below folds, are neither strict reductions that produce a final answer+-- in constant space, nor lazy corecursions, and so have limited applicability.+-- They do have specialised uses, but are best avoided when in doubt.+--+-- @+-- 'foldr'' :: Foldable t => (a -> b -> b) -> b -> t a -> b+-- 'foldl'  :: Foldable t => (b -> a -> b) -> b -> t a -> b+-- 'foldl1' :: Foldable t => (a -> a -> a) -> t a -> a+-- 'foldrM' :: (Foldable t, Monad m) => (a -> b -> m b) -> b -> t a -> m b+-- @+--+-- The lazy left-folds (used corecursively) and 'foldrM' (used to sequence+-- actions right-to-left) can be performant in structures whose @Foldable@+-- instances take advantage of efficient right-to-left iteration to compute+-- lazy left folds outside-in from the rightmost element.+--+-- The strict 'foldr'' is the least likely to be useful, structures that+-- support efficient sequencing /only/ right-to-left are not common.++--------------++-- $instances+--+-- #instances#+-- For many structures reasonably efficient @Foldable@ instances can be derived+-- automatically, by enabling the @DeriveFoldable@ GHC extension.  When this+-- works, it is generally not necessary to define a custom instance by hand.+-- Though in some cases one may be able to get slightly faster hand-tuned code,+-- care is required to avoid producing slower code, or code that is not+-- sufficiently lazy, strict or /lawful/.+--+-- The hand-crafted instances can get away with only defining one of 'foldr' or+-- 'foldMap'.  All the other methods have default definitions in terms of one+-- of these.  The default definitions have the expected strictness and the+-- expected asymptotic runtime and space costs, modulo small constant factors.+-- If you choose to hand-tune, benchmarking is advised to see whether you're+-- doing better than the default derived implementations, plus careful tests to+-- ensure that the custom methods are correct.+--+-- Below we construct a @Foldable@ instance for a data type representing a+-- (finite) binary tree with depth-first traversal.+--+-- >>> data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)+--+-- a suitable instance would be:+--+-- >>> :{+-- instance Foldable Tree where+--    foldr f z Empty = z+--    foldr f z (Leaf x) = f x z+--    foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l+-- :}+--+-- The 'Node' case is a right fold of the left subtree whose initial+-- value is a right fold of the rest of the tree.+--+-- For example, when @f@ is @(':')@, all three cases return an immediate value,+-- respectively @z@ or a /cons cell/ holding @x@ or @l@, with the remainder the+-- structure, if any, encapsulated in a lazy thunk.  This meets the expected+-- efficient [corecursive](#corec) behaviour of 'foldr'.+--+-- Alternatively, one could define @foldMap@:+--+-- > instance Foldable Tree where+-- >    foldMap f Empty = mempty+-- >    foldMap f (Leaf x) = f x+-- >    foldMap f (Node l k r) = foldMap f l <> f k <> foldMap f r+--+-- And indeed some efficiency may be gained by directly defining both,+-- avoiding some indirection in the default definitions that express+-- one in terms of the other.  If you implement just one, likely 'foldr'+-- is the better choice.+--+-- A binary tree typically (when balanced, or randomly biased) provides equally+-- efficient access to its left and right subtrees.  This makes it possible to+-- define a `foldl` optimised for [corecursive](#corec) folds with operators+-- that are lazy in their first (left) argument.+--+-- > instance Foldable Tree where+-- >    foldr f z Empty = z+-- >    foldr f z (Leaf x) = f x z+-- >    foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l+-- >    --+-- >    foldMap f Empty = mempty+-- >    foldMap f (Leaf x) = f x+-- >    foldMap f (Node l k r) = foldMap f l <> f k <> foldMap f r+-- >    --+-- >    foldl f z Empty = z+-- >    foldl f z (Leaf x) = f z x+-- >    foldl f z (Node l k r) = foldl f (f (foldl f z l) k) r+--+-- Now left-to-right and right-to-left iteration over the structure+-- elements are equally efficient (note the mirror-order output when+-- using `foldl`):+--+-- >>> foldr (\e acc -> e : acc) [] (Node (Leaf 1) 2 (Leaf 3))+-- [1,2,3]+-- >>> foldl (\acc e -> e : acc) [] (Node (Leaf 1) 2 (Leaf 3))+-- [3,2,1]+--+-- We can carry this further, and define more non-default methods...+--+-- The structure definition actually admits trees that are unbounded on either+-- or both sides.  The only fold that can plausibly terminate for a tree+-- unbounded on both left and right is `null`, when defined as shown below.+-- The default definition in terms of `foldr` diverges if the tree is unbounded+-- on the left.  Here we define a variant that avoids travelling down the tree+-- to find the leftmost element and just examines the root node.+--+-- >    null Empty = True+-- >    null _     = False+--+-- This is a sound choice also for finite trees.+--+-- In practice, unbounded trees are quite uncommon, and can barely be said to+-- be @Foldable@.  They would typically employ breadth first traversal, and+-- would support only corecursive and short-circuit folds (diverge under strict+-- reduction).+--+-- Returning to simpler instances, defined just in terms of `foldr`, it is+-- somewhat surprising that a fairly efficient /default/ implementation of the+-- strict 'foldl'' is defined in terms of lazy `foldr` when only the latter is+-- explicitly provided by the instance.  It may be instructive to take a look+-- at how this works.++--------------++-- $strictlazy+--+-- #strictlazy#+--+-- Sometimes, it is useful for the result of applying 'foldr' to be a+-- /function/.  This is done by mapping the structure elements to functions+-- with the same argument and result types.  The per-element functions are then+-- composed to give the final result.+--+-- For example, we can /flip/ the strict left fold 'foldl'' by writing:+--+-- > foldl' f z xs = flippedFoldl' f xs z+--+-- with the function 'flippedFoldl'' defined as below, with 'seq' used to+-- ensure the strictness in the accumulator:+--+-- > flippedFoldl' f [] z = z+-- > flippedFoldl' f (x : xs) z = z `seq` flippedFoldl' f xs (f z x)+--+-- Rewriting to use lambdas, this is:+--+-- > flippedFoldl' f [] = \ b -> b+-- > flippedFoldl' f (x : xs) = \ b -> b `seq` r (f b x)+-- >     where r = flippedFoldl' f xs+--+-- The above has the form of a right fold, enabling a rewrite to:+--+-- > flippedFoldl' f = \ xs -> foldr f' id xs+-- >     where f' x r = \ b -> b `seq` r (f b x)+--+-- We can now unflip this to get 'foldl'':+--+-- > foldl' f z = \ xs -> foldr f' id xs z+-- >           -- \ xs -> flippedFoldl' f xs z+-- >   where f' x r = \ b -> b `seq` r (f b x)+--+-- The function __@foldr f' id xs@__ applied to @z@ is built corecursively, and+-- its terms are applied to an eagerly evaluated accumulator before further+-- terms are applied to the result.  As required, this runs in constant space,+-- and can be optimised to an efficient loop.+--+-- (The actual definition of 'foldl'' labels the lambdas in the definition of+-- __@f'@__ above as /oneShot/, which enables further optimisations).++--------------++-- $generative+--+-- #generative#+-- So far, we have not discussed /generative recursion/.  Unlike recursive+-- reduction or corecursion, instead of processing a sequence of elements+-- already in memory, generative recursion involves producing a possibly+-- unbounded sequence of values from an initial seed value.  The canonical+-- example of this is 'Data.List.unfoldr' for Lists, with variants available+-- for Vectors and various other structures.+--+-- A key issue with lists, when used generatively as /iterators/, rather than as+-- poor-man's containers (see [[1\]](#uselistsnot)), is that such iterators+-- tend to consume memory when used more than once.  A single traversal of a+-- list-as-iterator will run in constant space, but as soon as the list is+-- retained for reuse, its entire element sequence is stored in memory, and the+-- second traversal reads the copy, rather than regenerates the elements.  It+-- is sometimes better to recompute the elements rather than memoise the list.+--+-- Memoisation happens because the built-in Haskell list __@[]@__ is+-- represented as __data__, either empty or a /cons-cell/ holding the first+-- element and the tail of the list.  The @Foldable@ class enables a variant+-- representation of iterators as /functions/, which take an operator and a+-- starting accumulator and output a summary result.+--+-- The [@fmlist@](https://hackage.haskell.org/package/fmlist) package takes+-- this approach, by representing a list via its `foldMap` action.+--+-- Below we implement an analogous data structure using a representation+-- based on `foldr`.  This is an example of /Church encoding/+-- (named after Alonzo Church, inventor of the lambda calculus).+--+-- > {-# LANGUAGE RankNTypes #-}+-- > newtype FRList a = FR { unFR :: forall b. (a -> b -> b) -> b -> b }+--+-- The __@unFR@__ field of this type is essentially its `foldr` method+-- with the list as its first rather than last argument.  Thus we+-- immediately get a @Foldable@ instance (and a 'toList' function+-- mapping an __@FRList@__ to a regular list).+--+-- > instance Foldable FRList where+-- >     foldr f z l = unFR l f z+-- >     -- With older versions of @base@, also define sum, product, ...+-- >     -- to ensure use of the strict 'foldl''.+-- >     -- sum = foldl' (+) 0+-- >     -- ...+--+-- We can convert a regular list to an __@FRList@__ with:+--+-- > fromList :: [a] -> FRList a+-- > fromList as = FRList $ \ f z -> foldr f z as+--+-- However, reuse of an __@FRList@__ obtained in this way will typically+-- memoise the underlying element sequence.  Instead, we can define+-- __@FRList@__ terms directly:+--+-- > -- | Immediately return the initial accumulator+-- > nil :: FRList a+-- > nil = FRList $ \ _ z -> z+-- > {-# INLINE nil #-}+--+-- > -- | Fold the tail to use as an accumulator with the new initial element+-- > cons :: a -> FRList a -> FRList a+-- > cons a l = FRList $ \ f z -> f a (unFR l f z)+-- > {-# INLINE cons #-}+--+-- More crucially, we can also directly define the key building block for+-- generative recursion:+--+-- > -- | Generative recursion, dual to `foldr`.+-- > unfoldr :: (s -> Maybe (a, s)) -> s -> FRList a+-- > unfoldr g s0 = FR generate+-- >   where generate f z = loop s0+-- >           where loop s | Just (a, t) <- g s = f a (loop t)+-- >                        | otherwise = z+-- > {-# INLINE unfoldr #-}+--+-- Which can, for example, be specialised to number ranges:+--+-- > -- | Generate a range of consecutive integral values.+-- > range :: (Ord a, Integral a) => a -> a -> FRList a+-- > range lo hi =+-- >     unfoldr (\s -> if s > hi then Nothing else Just (s, s+1)) lo+-- > {-# INLINE range #-}+--+-- The program below, when compiled with optimisation:+--+-- > main :: IO ()+-- > main = do+-- >     let r :: FRList Int+-- >         r = range 1 10000000+-- >      in print (sum r, length r)+--+-- produces the expected output with no noticeable garbage-collection, despite+-- reuse of the __@FRList@__ term __@r@__.+--+-- > (50000005000000,10000000)+-- >     52,120 bytes allocated in the heap+-- >      3,320 bytes copied during GC+-- >     44,376 bytes maximum residency (1 sample(s))+-- >     25,256 bytes maximum slop+-- >          3 MiB total memory in use (0 MB lost due to fragmentation)+--+-- The Weak Head Normal Form of an __@FRList@__ is a lambda abstraction not a+-- data value, and reuse does not lead to memoisation.  Reuse of the iterator+-- above is somewhat contrived, when computing multiple folds over a common+-- list, you should generally traverse a  list only [once](#multipass).  The+-- goal is to demonstrate that the separate computations of the 'sum' and+-- 'length' run efficiently in constant space, despite reuse.  This would not+-- be the case with the list @[1..10000000]@.+--+-- This is, however, an artificially simple reduction.  More typically, there+-- are likely to be some allocations in the inner loop, but the temporary+-- storage used will be garbage-collected as needed, and overall memory+-- utilisation will remain modest and will not scale with the size of the list.+--+-- If we go back to built-in lists (i.e. __@[]@__), but avoid reuse by+-- performing reduction in a single pass, as below:+--+-- > data PairS a b = P !a !b -- We define a strict pair datatype+-- >+-- > main :: IO ()+-- > main = do+-- >     let l :: [Int]+-- >         l = [1..10000000]+-- >      in print $ average l+-- >   where+-- >     sumlen :: PairS Int Int -> Int -> PairS Int Int+-- >     sumlen (P s l) a = P (s + a) (l + 1)+-- >+-- >     average is =+-- >         let (P s l) = foldl' sumlen (P 0 0) is+-- >          in (fromIntegral s :: Double) / fromIntegral l+--+-- the result is again obtained in constant space:+--+-- > 5000000.5+-- >          102,176 bytes allocated in the heap+-- >            3,320 bytes copied during GC+-- >           44,376 bytes maximum residency (1 sample(s))+-- >           25,256 bytes maximum slop+-- >                3 MiB total memory in use (0 MB lost due to fragmentation)+--+-- (and, in fact, faster than with __@FRList@__ by a small factor).+--+-- The __@[]@__ list structure works as an efficient iterator when used+-- just once.  When space-leaks via list reuse are not a concern, and/or+-- memoisation is actually desirable, the regular list implementation is+-- likely to be faster.  This is not a suggestion to replace all your uses of+-- __@[]@__ with a generative alternative.+--+-- The __@FRList@__ type could be further extended with instances of 'Functor',+-- 'Applicative', 'Monad', 'Alternative', etc., and could then provide a+-- fully-featured list type, optimised for reuse without space-leaks.  If,+-- however, all that's required is space-efficient, re-use friendly iteration,+-- less is perhaps more, and just @Foldable@ may be sufficient.++--------------++-- $multipass+--+-- #multipass#+-- In applications where you want to compute a composite function of a+-- structure, which requires more than one aggregate as an input, it is+-- generally best to compute all the aggregates in a single pass, rather+-- than to traverse the same structure repeatedly.+--+-- The [@foldl@](http://hackage.haskell.org/package/foldl) package implements a+-- robust general framework for dealing with this situation.  If you choose to+-- to do it yourself, with a bit of care, the simplest cases are not difficult+-- to handle directly.  You just need to accumulate the individual aggregates+-- as __strict__ components of a single data type, and then apply a final+-- transformation to it to extract the composite result.  For example,+-- computing an average requires computing both the 'sum' and the 'length' of a+-- (non-empty) structure and dividing the sum by the length:+--+-- > import Data.Foldable (foldl')+-- >+-- > data PairS a b = P !a !b -- We define a strict pair datatype+-- >+-- > -- | Compute sum and length in a single pass, then reduce to the average.+-- > average :: (Foldable f, Fractional a) => f a -> a+-- > average xs =+-- >     let sumlen (P s l) a = P (s + a) (l + 1 :: Int)+-- >         (P s l) = foldl' sumlen (P 0 0) xs+-- >      in s / fromIntegral l+--+-- The above example is somewhat contrived, some structures keep track of their+-- length internally, and can return it in /O(1)/ time, so this particular+-- recipe for averages is not always the most efficient.  In general, composite+-- aggregate functions of large structures benefit from single-pass reduction.+-- This is especially the case when reuse of a list and memoisation of its+-- elements is thereby avoided.++--------------++-- $laws+-- #laws#+--+-- The type constructor 'Endo' from "Data.Monoid", associates with each type+-- __@b@__ the __@newtype@__-encapsulated type of functions mapping __@b@__ to+-- itself.  Functions from a type to itself are called /endomorphisms/, hence+-- the name /Endo/.  The type __@Endo b@__ is a 'Monoid' under function+-- composition:+--+-- > newtype Endo b = Endo { appEndo :: b -> b }+-- > instance Semigroup Endo b where+-- >     Endo f <> Endo g = Endo (f . g)+-- > instance Monoid Endo b where+-- >     mempty = Endo id+--+-- For every 'Monoid' m, we also have a 'Dual' monoid __@Dual m@__ which+-- combines elements in the opposite order:+--+-- > newtype Dual m = Dual { getDual :: m }+-- > instance Semigroup m => Semigroup Dual m where+-- >     Dual a <> Dual b = Dual (b <> a)+-- > instance Monoid m => Monoid Dual m where+-- >     mempty = Dual mempty+--+-- With the above preliminaries out of the way, 'Foldable' instances are+-- expected to satisfy the following laws:+--+-- The 'foldr' method must be equivalent in value and strictness to replacing+-- each element __@a@__ of a 'Foldable' structure with __@Endo (f a)@__,+-- composing these via 'foldMap' and applying the result to the base case+-- __@z@__:+--+-- > foldr f z t = appEndo (foldMap (Endo . f) t ) z+--+-- Likewise, the 'foldl' method must be equivalent in value and strictness+-- to composing the functions __@flip f a@__ in reverse order and applying+-- the result to the base case:+--+-- > foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z+--+-- When the elements of the structure are taken from a 'Monoid', the+-- definition of 'fold' must agree with __@foldMap id@__:+--+-- > fold = foldMap id+--+-- The 'length' method must agree with a 'foldMap' mapping each element to+-- __@Sum 1@__ (The 'Sum' type abstracts numbers as a monoid under addition).+--+-- > length = getSum . foldMap (Sum . const 1)+--+-- @sum@, @product@, @maximum@, and @minimum@ should all be essentially+-- equivalent to @foldMap@ forms, such as+--+-- > sum     = getSum     . foldMap' Sum+-- > product = getProduct . foldMap' Product+--+-- but are generally more efficient when defined more directly as:+--+-- > sum = foldl' (+) 0+-- > product = foldl' (*) 1+--+-- If the 'Foldable' structure has a 'Functor' instance, then for every+-- function __@f@__ mapping the elements into a 'Monoid', it should satisfy:+--+-- > foldMap f = fold . fmap f+--+-- which implies that+--+-- > foldMap f . fmap g = foldMap (f . g)+--++--------------++-- $notes+--+-- #notes#+-- Since 'Foldable' does not have 'Functor' as a superclass, it is possible to+-- define 'Foldable' instances for structures that constrain their element+-- types.  Therefore, __@Set@__ can be 'Foldable', even though sets keep their+-- elements in ascending order.  This requires the elements to be comparable,+-- which precludes defining a 'Functor' instance for @Set@.+--+-- The 'Foldable' class makes it possible to use idioms familiar from the @List@+-- type with container structures that are better suited to the task at hand.+-- This supports use of more appropriate 'Foldable' data types, such as @Seq@,+-- @Set@, @NonEmpty@, etc., without requiring new idioms (see+-- [[1\]](#uselistsnot) for when not to use lists).+--+-- The more general methods of the 'Foldable' class are now exported by the+-- "Prelude" in place of the original List-specific methods (see the+-- [FTP Proposal](https://wiki.haskell.org/Foldable_Traversable_In_Prelude)).+-- The List-specific variants are for now still available in "GHC.OldList", but+-- that module is intended only as a transitional aid, and may be removed in+-- the future.+--+-- Surprises can arise from the @Foldable@ instance of the 2-tuple @(a,)@ which+-- now behaves as a 1-element @Foldable@ container in its second slot.  In+-- contexts where a specific monomorphic type is expected, and you want to be+-- able to rely on type errors to guide refactoring, it may make sense to+-- define and use less-polymorphic variants of some of the @Foldable@ methods.+--+-- Below are two examples showing a definition of a reusable less-polymorphic+-- 'sum' and a one-off in-line specialisation of 'length':+--+-- > {-# LANGUAGE TypeApplications #-}+-- >+-- > mySum :: Num a => [a] -> a+-- > mySum = sum+-- >+-- > type SlowVector a = [a]+-- > slowLength :: SlowVector -> Int+-- > slowLength v = length @[] v+--+-- In both cases, if the data type to which the function is applied changes+-- to something other than a list, the call-site will no longer compile until+-- appropriate changes are made.++-- $linear+--+-- It is perhaps worth noting that since the __`elem`__ function in the+-- 'Foldable' class carries only an __`Eq`__ constraint on the element type,+-- search for the presence or absence of an element in the structure generally+-- takes /O(n)/ time, even for ordered structures like __@Set@__ that are+-- potentially capable of performing the search faster.  (The @member@ function+-- of the @Set@ module carries an `Ord` constraint, and can perform the search+-- in /O(log n)/ time).+--+-- An alternative to Foldable's __`elem`__ method is required in order to+-- abstract potentially faster than linear search over general container+-- structures.  This can be achieved by defining an additional type class (e.g.+-- @HasMember@ below).  Instances of such a type class (that are also+-- `Foldable') can employ the `elem` linear search as a last resort, when+-- faster search is not supported.+--+-- > {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}+-- >+-- > import qualified Data.Set as Set+-- >+-- > class Eq a => HasMember t a where+-- >     member :: a -> t a -> Bool+-- >+-- > instance Eq a => HasMember [] a where+-- >     member = elem+-- > [...]+-- > instance Ord a => HasMember Set.Set a where+-- >     member = Set.member+--+-- The above suggests that 'elem' may be a misfit in the 'Foldable' class.+-- Alternative design ideas are solicited on GHC's bug tracker via issue+-- [\#20421](https://gitlab.haskell.org/ghc/ghc/-/issues/20421).+--+-- Note that some structure-specific optimisations may of course be possible+-- directly in the corresponding @Foldable@ instance, e.g. with @Set@ the size+-- of the set is known in advance, without iterating to count the elements, and+-- its `length` instance takes advantage of this to return the size directly.++--------------++-- $also+--+--  * [1] #uselistsnot# \"When You Should Use Lists in Haskell (Mostly, You Should Not)\",+--    by Johannes Waldmann,+--    in arxiv.org, Programming Languages (cs.PL), at+--    <https://arxiv.org/abs/1808.08329>.+--+--  * [2] \"The Essence of the Iterator Pattern\",+--    by Jeremy Gibbons and Bruno Oliveira,+--    in /Mathematically-Structured Functional Programming/, 2006, online at+--    <http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/#iterator>.+--+--  * [3] \"A tutorial on the universality and expressiveness of fold\",+--    by Graham Hutton, J\. Functional Programming 9 (4): 355–372, July 1999,+--    online at <http://www.cs.nott.ac.uk/~pszgmh/fold.pdf>.
+ src/Data/Foldable1.hs view
@@ -0,0 +1,620 @@+-- |+-- Copyright: Edward Kmett, Oleg Grenrus+-- License: BSD-3-Clause+--+-- A class of non-empty data structures that can be folded to a summary value.+--+-- @since 4.18.0.0++{-# LANGUAGE FlexibleInstances          #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE NoImplicitPrelude          #-}+{-# LANGUAGE PolyKinds                  #-}+{-# LANGUAGE ScopedTypeVariables        #-}+{-# LANGUAGE StandaloneDeriving         #-}+{-# LANGUAGE Trustworthy                #-}+{-# LANGUAGE TypeOperators              #-}++module Data.Foldable1 (+    Foldable1(..),+    foldr1, foldr1',+    foldl1, foldl1',+    intercalate1,+    foldrM1,+    foldlM1,+    foldrMapM1,+    foldlMapM1,+    maximumBy,+    minimumBy,+    ) where++import GHC.Internal.Data.Foldable      (Foldable, foldlM, foldr)+import GHC.Internal.Data.List          (foldl, foldl')+import Data.List.NonEmpty (NonEmpty (..))+import Data.Semigroup+       (Dual (..), First (..), Last (..), Max (..), Min (..), Product (..),+       Semigroup (..), Sum (..))+import GHC.Tuple (Solo (..))+import Prelude+       (Maybe (..), Monad (..), Ord, Ordering (..), id, seq, ($!), ($), (.),+       (=<<), flip, const, error)++import qualified Data.List.NonEmpty as NE++import Data.Complex (Complex (..))+import GHC.Generics+       (M1 (..), Par1 (..), Rec1 (..), V1, (:*:) (..), (:+:) (..), (:.:) (..))++import GHC.Internal.Data.Ord (Down (..))++import qualified GHC.Internal.Data.Monoid as Mon++-- Instances+import Data.Functor.Compose          (Compose (..))+import GHC.Internal.Data.Functor.Identity         (Identity (..))++import qualified Data.Functor.Product as Functor+import qualified Data.Functor.Sum     as Functor++-- coerce+import GHC.Internal.Data.Coerce (Coercible, coerce)++-- $setup+-- >>> import Prelude hiding (foldr1, foldl1, head, last, minimum, maximum)+-- >>> import Data.List.NonEmpty (NonEmpty(..))+-- >>> import Data.Monoid (Sum(..))+-- >>> import Data.Functor.Identity++-------------------------------------------------------------------------------+-- Foldable1 type class+-------------------------------------------------------------------------------++-- | Non-empty data structures that can be folded.+--+-- @since 4.18.0.0+class Foldable t => Foldable1 t where+    {-# MINIMAL foldMap1 | foldrMap1 #-}++    -- At some point during design it was possible to define this class using+    -- only 'toNonEmpty'. But it seems a bad idea in general.+    --+    -- So currently we require either foldMap1 or foldrMap1+    --+    -- * foldMap1 defined using foldrMap1+    -- * foldrMap1 defined using foldMap1+    --+    -- One can always define an instance using the following pattern:+    --+    --     toNonEmpty = ...+    --     foldMap f     = foldMap f     . toNonEmpty+    --     foldrMap1 f g = foldrMap1 f g . toNonEmpty++    -- | Given a structure with elements whose type is a 'Semigroup', combine+    -- them via the semigroup's @('<>')@ operator. This fold is+    -- right-associative and lazy in the accumulator. When you need a strict+    -- left-associative fold, use 'foldMap1'' instead, with 'id' as the map.+    --+    -- @since 4.18.0.0+    fold1 :: Semigroup m => t m -> m+    fold1 = foldMap1 id++    -- | Map each element of the structure to a semigroup, and combine the+    -- results with @('<>')@. This fold is right-associative and lazy in the+    -- accumulator. For strict left-associative folds consider 'foldMap1''+    -- instead.+    --+    -- >>> foldMap1 (:[]) (1 :| [2, 3, 4])+    -- [1,2,3,4]+    --+    -- @since 4.18.0.0+    foldMap1 :: Semigroup m => (a -> m) -> t a -> m+    foldMap1 f = foldrMap1 f (\a m -> f a <> m)++    -- | A left-associative variant of 'foldMap1' that is strict in the+    -- accumulator. Use this for strict reduction when partial results are+    -- merged via @('<>')@.+    --+    -- >>> foldMap1' Sum (1 :| [2, 3, 4])+    -- Sum {getSum = 10}+    --+    -- @since 4.18.0.0+    foldMap1' :: Semigroup m => (a -> m) -> t a -> m+    foldMap1' f = foldlMap1' f (\m a -> m <> f a)++    -- | 'NonEmpty' list of elements of a structure, from left to right.+    --+    -- >>> toNonEmpty (Identity 2)+    -- 2 :| []+    --+    -- @since 4.18.0.0+    toNonEmpty :: t a -> NonEmpty a+    toNonEmpty = runNonEmptyDList . foldMap1 singleton++    -- | The largest element of a non-empty structure. This function is+    -- equivalent to @'foldr1' 'Data.Ord.max'@, and its behavior on structures+    -- with multiple largest elements depends on the relevant implementation of+    -- 'Data.Ord.max'. For the default implementation of 'Data.Ord.max' (@max x+    -- y = if x <= y then y else x@), structure order is used as a tie-breaker:+    -- if there are multiple largest elements, the rightmost of them is chosen+    -- (this is equivalent to @'maximumBy' 'Data.Ord.compare'@).+    --+    -- >>> maximum (32 :| [64, 8, 128, 16])+    -- 128+    --+    -- @since 4.18.0.0+    maximum :: Ord a => t a -> a+    maximum = getMax #. foldMap1' Max++    -- | The least element of a non-empty structure. This function is+    -- equivalent to @'foldr1' 'Data.Ord.min'@, and its behavior on structures+    -- with multiple largest elements depends on the relevant implementation of+    -- 'Data.Ord.min'. For the default implementation of 'Data.Ord.min' (@min x+    -- y = if x <= y then x else y@), structure order is used as a tie-breaker:+    -- if there are multiple least elements, the leftmost of them is chosen+    -- (this is equivalent to @'minimumBy' 'Data.Ord.compare'@).+    --+    -- >>> minimum (32 :| [64, 8, 128, 16])+    -- 8+    --+    -- @since 4.18.0.0+    minimum :: Ord a => t a -> a+    minimum = getMin #. foldMap1' Min++    -- | The first element of a non-empty structure.+    --+    -- >>> head (1 :| [2, 3, 4])+    -- 1+    --+    -- @since 4.18.0.0+    head :: t a -> a+    head = getFirst #. foldMap1 First++    -- | The last element of a non-empty structure.+    --+    -- >>> last (1 :| [2, 3, 4])+    -- 4+    --+    -- @since 4.18.0.0+    last :: t a -> a+    last = getLast #. foldMap1 Last++    -- | Right-associative fold of a structure, lazy in the accumulator.+    --+    -- In case of 'NonEmpty' lists, 'foldrMap1', when given a function @f@, a+    -- binary operator @g@, and a list, reduces the list using @g@ from right to+    -- left applying @f@ to the rightmost element:+    --+    -- > foldrMap1 f g (x1 :| [x2, ..., xn1, xn]) == x1 `g` (x2 `g` ... (xn1 `g` (f xn))...)+    --+    -- Note that since the head of the resulting expression is produced by+    -- an application of @g@ to the first element of the list, if @g@ is lazy+    -- in its right argument, 'foldrMap1' can produce a terminating expression+    -- from an unbounded list.+    --+    -- For a general 'Foldable1' structure this should be semantically identical+    -- to:+    --+    -- @foldrMap1 f g = foldrMap1 f g . 'toNonEmpty'@+    --+    -- @since 4.18.0.0+    foldrMap1 :: (a -> b) -> (a -> b -> b) -> t a -> b+    foldrMap1 f g xs =+        appFromMaybe (foldMap1 (FromMaybe #. h) xs) Nothing+      where+        h a Nothing  = f a+        h a (Just b) = g a b++    -- | Left-associative fold of a structure but with strict application of the+    -- operator.+    --+    -- This ensures that each step of the fold is forced to Weak Head Normal+    -- Form before being applied, avoiding the collection of thunks that would+    -- otherwise occur. This is often what you want to strictly reduce a+    -- finite structure to a single strict result.+    --+    -- For a general 'Foldable1' structure this should be semantically identical+    -- to:+    --+    -- @foldlMap1' f z = foldlMap1' f z . 'toNonEmpty'@+    --+    -- @since 4.18.0.0+    foldlMap1' :: (a -> b) -> (b -> a -> b) -> t a -> b+    foldlMap1' f g xs =+        foldrMap1 f' g' xs SNothing+      where+        -- f' :: a -> SMaybe b -> b+        f' a SNothing  = f a+        f' a (SJust b) = g b a++        -- g' :: a -> (SMaybe b -> b) -> SMaybe b -> b+        g' a x SNothing  = x $! SJust (f a)+        g' a x (SJust b) = x $! SJust (g b a)++    -- | Left-associative fold of a structure, lazy in the accumulator.  This is+    -- rarely what you want, but can work well for structures with efficient+    -- right-to-left sequencing and an operator that is lazy in its left+    -- argument.+    --+    -- In case of 'NonEmpty' lists, 'foldlMap1', when given a function @f@, a+    -- binary operator @g@, and a list, reduces the list using @g@ from left to+    -- right applying @f@ to the leftmost element:+    --+    -- > foldlMap1 f g (x1 :| [x2, ..., xn]) == (...(((f x1) `g` x2) `g`...) `g` xn+    --+    -- Note that to produce the outermost application of the operator the entire+    -- input list must be traversed. This means that 'foldlMap1' will diverge if+    -- given an infinite list.+    --+    -- If you want an efficient strict left-fold, you probably want to use+    -- 'foldlMap1''  instead of 'foldlMap1'. The reason for this is that the+    -- latter does not force the /inner/ results (e.g. @(f x1) \`g\` x2@ in the+    -- above example) before applying them to the operator (e.g. to+    -- @(\`g\` x3)@). This results in a thunk chain \(O(n)\) elements long,+    -- which then must be evaluated from the outside-in.+    --+    -- For a general 'Foldable1' structure this should be semantically identical+    -- to:+    --+    -- @foldlMap1 f g = foldlMap1 f g . 'toNonEmpty'@+    --+    -- @since 4.18.0.0+    foldlMap1 :: (a -> b) -> (b -> a -> b) -> t a -> b+    foldlMap1 f g xs =+        appFromMaybe (getDual (foldMap1 ((Dual . FromMaybe) #. h) xs)) Nothing+      where+        h a Nothing  = f a+        h a (Just b) = g b a++    -- | 'foldrMap1'' is a variant of 'foldrMap1' that performs strict reduction+    -- from right to left, i.e. starting with the right-most element. The input+    -- structure /must/ be finite, otherwise 'foldrMap1'' runs out of space+    -- (/diverges/).+    --+    -- If you want a strict right fold in constant space, you need a structure+    -- that supports faster than \(O(n)\) access to the right-most element.+    --+    -- This method does not run in constant space for structures such as+    -- 'NonEmpty' lists that don't support efficient right-to-left iteration and+    -- so require \(O(n)\) space to perform right-to-left reduction. Use of this+    -- method with such a structure is a hint that the chosen structure may be a+    -- poor fit for the task at hand. If the order in which the elements are+    -- combined is not important, use 'foldlMap1'' instead.+    --+    -- @since 4.18.0.0+    foldrMap1' :: (a -> b) -> (a -> b -> b) -> t a -> b+    foldrMap1' f g xs =+        foldlMap1 f' g' xs SNothing+      where+        f' a SNothing  = f a+        f' a (SJust b) = g a b++        g' bb a SNothing  = bb $! SJust (f a)+        g' bb a (SJust b) = bb $! SJust (g a b)++-------------------------------------------------------------------------------+-- Combinators+-------------------------------------------------------------------------------++-- | A variant of 'foldrMap1' where the rightmost element maps to itself.+--+-- @since 4.18.0.0+foldr1 :: Foldable1 t => (a -> a -> a) -> t a -> a+foldr1 = foldrMap1 id+{-# INLINE foldr1 #-}++-- | A variant of 'foldrMap1'' where the rightmost element maps to itself.+--+-- @since 4.18.0.0+foldr1' :: Foldable1 t => (a -> a -> a) -> t a -> a+foldr1' = foldrMap1' id+{-# INLINE foldr1' #-}++-- | A variant of 'foldlMap1' where the leftmost element maps to itself.+--+-- @since 4.18.0.0+foldl1 :: Foldable1 t => (a -> a -> a) -> t a -> a+foldl1 = foldlMap1 id+{-# INLINE foldl1 #-}++-- | A variant of 'foldlMap1'' where the leftmost element maps to itself.+--+-- @since 4.18.0.0+foldl1' :: Foldable1 t => (a -> a -> a) -> t a -> a+foldl1' = foldlMap1' id+{-# INLINE foldl1' #-}++-- | Insert an @m@ between each pair of @t m@.+--+-- >>> intercalate1 ", " $ "hello" :| ["how", "are", "you"]+-- "hello, how, are, you"+--+-- >>> intercalate1 ", " $ "hello" :| []+-- "hello"+--+-- >>> intercalate1 mempty $ "I" :| ["Am", "Fine", "You?"]+-- "IAmFineYou?"+--+-- @since 4.18.0.0+intercalate1 :: (Foldable1 t, Semigroup m) => m -> t m -> m+intercalate1 = flip intercalateMap1 id++intercalateMap1 :: (Foldable1 t, Semigroup m) => m -> (a -> m) -> t a -> m+intercalateMap1 j f = flip joinee j . foldMap1 (JoinWith . const . f)++-- | Monadic fold over the elements of a non-empty structure,+-- associating to the right, i.e. from right to left.+--+-- @since 4.18.0.0+foldrM1 :: (Foldable1 t, Monad m) => (a -> a -> m a) -> t a -> m a+foldrM1 = foldrMapM1 return++-- | Map variant of 'foldrM1'.+--+-- @since 4.18.0.0+foldrMapM1 :: (Foldable1 t, Monad m) => (a -> m b) -> (a -> b -> m b) -> t a -> m b+foldrMapM1 g f = go . toNonEmpty+  where+    go (e:|es) =+      case es of+        []   -> g e+        x:xs -> f e =<< go (x:|xs)++-- | Monadic fold over the elements of a non-empty structure,+-- associating to the left, i.e. from left to right.+--+-- @since 4.18.0.0+foldlM1 :: (Foldable1 t, Monad m) => (a -> a -> m a) -> t a -> m a+foldlM1 = foldlMapM1 return++-- | Map variant of 'foldlM1'.+--+-- @since 4.18.0.0+foldlMapM1 :: (Foldable1 t, Monad m) => (a -> m b) -> (b -> a -> m b) -> t a -> m b+foldlMapM1 g f t = g x >>= \y -> foldlM f y xs+  where x:|xs = toNonEmpty t++-- | The largest element of a non-empty structure with respect to the+-- given comparison function. Structure order is used as a tie-breaker: if+-- there are multiple largest elements, the rightmost of them is chosen.+--+-- @since 4.18.0.0+maximumBy :: Foldable1 t => (a -> a -> Ordering) -> t a -> a+maximumBy cmp = foldl1' max'+  where max' x y = case cmp x y of+                        GT -> x+                        _  -> y++-- | The least element of a non-empty structure with respect to the+-- given comparison function. Structure order is used as a tie-breaker: if+-- there are multiple least elements, the leftmost of them is chosen.+--+-- @since 4.18.0.0+minimumBy :: Foldable1 t => (a -> a -> Ordering) -> t a -> a+minimumBy cmp = foldl1' min'+  where min' x y = case cmp x y of+                        GT -> y+                        _  -> x++-------------------------------------------------------------------------------+-- Auxiliary types+-------------------------------------------------------------------------------++-- | Used for default toNonEmpty implementation.+newtype NonEmptyDList a = NEDL { unNEDL :: [a] -> NonEmpty a }++instance Semigroup (NonEmptyDList a) where+  xs <> ys = NEDL (unNEDL xs . NE.toList . unNEDL ys)+  {-# INLINE (<>) #-}++-- | Create dlist with a single element+singleton :: a -> NonEmptyDList a+singleton = NEDL #. (:|)++-- | Convert a dlist to a non-empty list+runNonEmptyDList :: NonEmptyDList a -> NonEmpty a+runNonEmptyDList = ($ []) . unNEDL+{-# INLINE runNonEmptyDList #-}++-- | Used for foldrMap1 and foldlMap1 definitions+newtype FromMaybe b = FromMaybe { appFromMaybe :: Maybe b -> b }++instance Semigroup (FromMaybe b) where+    FromMaybe f <> FromMaybe g = FromMaybe (f . Just . g)++-- | Strict maybe, used to implement default foldlMap1' etc.+data SMaybe a = SNothing | SJust !a++-- | Used to implement intercalate1/Map+newtype JoinWith a = JoinWith {joinee :: (a -> a)}++instance Semigroup a => Semigroup (JoinWith a) where+  JoinWith a <> JoinWith b = JoinWith $ \j -> a j <> j <> b j++-------------------------------------------------------------------------------+-- Instances for misc base types+-------------------------------------------------------------------------------++-- | @since 4.18.0.0+instance Foldable1 NonEmpty where+    foldMap1 f (x :| xs) = go (f x) xs where+        go y [] = y+        go y (z : zs) = y <> go (f z) zs++    foldMap1' f (x :| xs) = foldl' (\m y -> m <> f y) (f x) xs++    toNonEmpty = id++    foldrMap1 g f (x :| xs) = go x xs where+        go y [] = g y+        go y (z : zs) = f y (go z zs)++    foldlMap1  g f (x :| xs) = foldl f (g x) xs+    foldlMap1' g f (x :| xs) = let gx = g x in gx `seq` foldl' f gx xs++    head = NE.head+    last = NE.last++-- | @since 4.18.0.0+instance Foldable1 Down where+    foldMap1 = coerce++-- | @since 4.18.0.0+instance Foldable1 Complex where+    foldMap1 f (x :+ y) = f x <> f y++    toNonEmpty (x :+ y) = x :| y : []++-------------------------------------------------------------------------------+-- Instances for tuples+-------------------------------------------------------------------------------++-- 3+ tuples are not Foldable/Traversable++-- | @since 4.18.0.0+instance Foldable1 Solo where+    foldMap1 f (MkSolo y) = f y+    toNonEmpty (MkSolo x) = x :| []+    minimum (MkSolo x) = x+    maximum (MkSolo x) = x+    head (MkSolo x) = x+    last (MkSolo x) = x++-- | @since 4.18.0.0+instance Foldable1 ((,) a) where+    foldMap1 f (_, y) = f y+    toNonEmpty (_, x) = x :| []+    minimum (_, x) = x+    maximum (_, x) = x+    head (_, x) = x+    last (_, x) = x++-------------------------------------------------------------------------------+-- Monoid / Semigroup instances+-------------------------------------------------------------------------------++-- | @since 4.18.0.0+instance Foldable1 Dual where+    foldMap1 = coerce++-- | @since 4.18.0.0+instance Foldable1 Sum where+    foldMap1 = coerce++-- | @since 4.18.0.0+instance Foldable1 Product where+    foldMap1 = coerce++-- | @since 4.18.0.0+instance Foldable1 Min where+    foldMap1 = coerce++-- | @since 4.18.0.0+instance Foldable1 Max where+    foldMap1 = coerce++-- | @since 4.18.0.0+instance Foldable1 First where+    foldMap1 = coerce++-- | @since 4.18.0.0+instance Foldable1 Last where+    foldMap1 = coerce++-- | @since 4.18.0.0+deriving instance (Foldable1 f) => Foldable1 (Mon.Alt f)++-- | @since 4.18.0.0+deriving instance (Foldable1 f) => Foldable1 (Mon.Ap f)++-------------------------------------------------------------------------------+-- GHC.Generics instances+-------------------------------------------------------------------------------++-- | @since 4.18.0.0+instance Foldable1 V1 where+    foldMap1 _ x = x `seq` error "foldMap1 @V1"++-- | @since 4.18.0.0+instance Foldable1 Par1 where+    foldMap1 = coerce++-- | @since 4.18.0.0+deriving instance Foldable1 f => Foldable1 (Rec1 f)++-- | @since 4.18.0.0+deriving instance Foldable1 f => Foldable1 (M1 i c f)++-- | @since 4.18.0.0+instance (Foldable1 f, Foldable1 g) => Foldable1 (f :+: g) where+    foldMap1 f (L1 x) = foldMap1 f x+    foldMap1 f (R1 y) = foldMap1 f y++-- | @since 4.18.0.0+instance (Foldable1 f, Foldable1 g) => Foldable1 (f :*: g) where+    foldMap1 f (x :*: y) = foldMap1 f x <> foldMap1 f y++-- | @since 4.18.0.0+instance (Foldable1 f, Foldable1 g) => Foldable1 (f :.: g) where+    foldMap1 f = foldMap1 (foldMap1 f) . unComp1++-------------------------------------------------------------------------------+-- Extra instances+-------------------------------------------------------------------------------++-- | @since 4.18.0.0+instance Foldable1 Identity where+    foldMap1      = coerce++    foldrMap1  g _ = coerce g+    foldrMap1' g _ = coerce g+    foldlMap1  g _ = coerce g+    foldlMap1' g _ = coerce g++    toNonEmpty (Identity x) = x :| []++    last    = coerce+    head    = coerce+    minimum = coerce+    maximum = coerce++-- | It would be enough for either half of a product to be 'Foldable1'.+-- Other could be 'Foldable'.+instance (Foldable1 f, Foldable1 g) => Foldable1 (Functor.Product f g) where+    foldMap1 f (Functor.Pair x y)    = foldMap1 f x <> foldMap1 f y+    foldrMap1 g f (Functor.Pair x y) = foldr f (foldrMap1 g f y) x++    head (Functor.Pair x _) = head x+    last (Functor.Pair _ y) = last y++-- | @since 4.18.0.0+instance (Foldable1 f, Foldable1 g) => Foldable1 (Functor.Sum f g) where+    foldMap1 f (Functor.InL x) = foldMap1 f x+    foldMap1 f (Functor.InR y) = foldMap1 f y++    foldrMap1 g f (Functor.InL x) = foldrMap1 g f x+    foldrMap1 g f (Functor.InR y) = foldrMap1 g f y++    toNonEmpty (Functor.InL x) = toNonEmpty x+    toNonEmpty (Functor.InR y) = toNonEmpty y++    head (Functor.InL x) = head x+    head (Functor.InR y) = head y+    last (Functor.InL x) = last x+    last (Functor.InR y) = last y++    minimum (Functor.InL x) = minimum x+    minimum (Functor.InR y) = minimum y+    maximum (Functor.InL x) = maximum x+    maximum (Functor.InR y) = maximum y++-- | @since 4.18.0.0+instance (Foldable1 f, Foldable1 g) => Foldable1 (Compose f g) where+    foldMap1 f = foldMap1 (foldMap1 f) . getCompose++    foldrMap1 f g = foldrMap1 (foldrMap1 f g) (\xs x -> foldr g x xs) . getCompose++    head = head . head . getCompose+    last = last . last . getCompose++(#.) :: Coercible b c => (b -> c) -> (a -> b) -> a -> c+(#.) _f = coerce
+ src/Data/Function.hs view
@@ -0,0 +1,31 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Function+-- Copyright   :  Nils Anders Danielsson 2006+--             ,  Alexander Berntsen     2014+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Simple combinators working solely on and with functions.+--++module Data.Function+    (-- *  "Prelude" re-exports+     id,+     const,+     (.),+     flip,+     ($),+     -- *  Other combinators+     (&),+     fix,+     on,+     applyWhen+     ) where++import GHC.Internal.Data.Function
+ src/Data/Functor.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Functor+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+--+-- A type @f@ is a Functor if it provides a function 'fmap' which, given any types @a@ and @b@,+-- lets you apply any function of type @(a -> b)@ to turn an @f a@ into an @f b@, preserving the+-- structure of @f@.+module Data.Functor+    (Functor(..),+     ($>),+     (<$>),+     (<&>),+     unzip,+     void+     ) where++import GHC.Internal.Data.Functor
+ src/Data/Functor/Classes.hs view
@@ -0,0 +1,1446 @@+{-# LANGUAGE FlexibleContexts     #-}+{-# LANGUAGE FlexibleInstances    #-}+{-# LANGUAGE DefaultSignatures    #-}+{-# LANGUAGE InstanceSigs         #-}+{-# LANGUAGE Safe                 #-}+{-# LANGUAGE TypeOperators        #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE QuantifiedConstraints #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Functor.Classes+-- Copyright   :  (c) Ross Paterson 2013+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Liftings of the Prelude classes 'Eq', 'Ord', 'Read' and 'Show' to+-- unary and binary type constructors.+--+-- These classes are needed to express the constraints on arguments of+-- transformers in portable Haskell.  Thus for a new transformer @T@,+-- one might write instances like+--+-- > instance (Eq1 f) => Eq1 (T f) where ...+-- > instance (Ord1 f) => Ord1 (T f) where ...+-- > instance (Read1 f) => Read1 (T f) where ...+-- > instance (Show1 f) => Show1 (T f) where ...+--+-- If these instances can be defined, defining instances of the base+-- classes is mechanical:+--+-- > instance (Eq1 f, Eq a) => Eq (T f a) where (==) = eq1+-- > instance (Ord1 f, Ord a) => Ord (T f a) where compare = compare1+-- > instance (Read1 f, Read a) => Read (T f a) where+-- >   readPrec     = readPrec1+-- >   readListPrec = readListPrecDefault+-- > instance (Show1 f, Show a) => Show (T f a) where showsPrec = showsPrec1+--+-- @since 4.9.0.0+-----------------------------------------------------------------------------++module Data.Functor.Classes (+    -- * Liftings of Prelude classes+    -- ** For unary constructors+    Eq1(..), eq1,+    Ord1(..), compare1,+    Read1(..), readsPrec1, readPrec1,+    liftReadListDefault, liftReadListPrecDefault,+    Show1(..), showsPrec1,+    -- ** For binary constructors+    Eq2(..), eq2,+    Ord2(..), compare2,+    Read2(..), readsPrec2, readPrec2,+    liftReadList2Default, liftReadListPrec2Default,+    Show2(..), showsPrec2,+    -- * Helper functions+    -- $example+    readsData, readData,+    readsUnaryWith, readUnaryWith,+    readsBinaryWith, readBinaryWith,+    showsUnaryWith,+    showsBinaryWith,+    -- ** Obsolete helpers+    readsUnary,+    readsUnary1,+    readsBinary1,+    showsUnary,+    showsUnary1,+    showsBinary1,+  ) where++import Control.Applicative (Alternative((<|>)), Const(Const))++import GHC.Internal.Data.Functor.Identity (Identity(Identity))+import GHC.Internal.Data.Proxy (Proxy(Proxy))+import Data.List.NonEmpty (NonEmpty(..))+import GHC.Internal.Data.Ord (Down(Down))+import Data.Complex (Complex((:+)))++import GHC.Generics (Generic1(..), Generically1(..), V1, U1(..), Par1(..), Rec1(..), K1(..), M1(..) , (:+:)(..), (:*:)(..), (:.:)(..), URec(..), UAddr, UChar, UDouble, UFloat, UInt, UWord)+import GHC.Tuple (Solo (..))+import GHC.Internal.Read (expectP, list, paren, readField)+import GHC.Internal.Show (appPrec)++import GHC.Internal.Text.ParserCombinators.ReadPrec (ReadPrec, readPrec_to_S, readS_to_Prec, pfail)+import GHC.Internal.Text.Read (Read(..), parens, prec, step, reset)+import GHC.Internal.Text.Read.Lex (Lexeme(..))+import GHC.Internal.Text.Show (showListWith)+import Prelude++-- $setup+-- >>> import Prelude+-- >>> import Data.Complex (Complex (..))+-- >>> import GHC.Internal.Text.ParserCombinators.ReadPrec++-- | Lifting of the 'Eq' class to unary type constructors.+--+-- Any instance should be subject to the following law that canonicity+-- is preserved:+--+-- @liftEq (==)@ = @(==)@+--+-- This class therefore represents the generalization of 'Eq' by+-- decomposing its main method into a canonical lifting on a canonical+-- inner method, so that the lifting can be reused for other arguments+-- than the canonical one.+--+-- @since 4.9.0.0+class (forall a. Eq a => Eq (f a)) => Eq1 f where+    -- | Lift an equality test through the type constructor.+    --+    -- The function will usually be applied to an equality function,+    -- but the more general type ensures that the implementation uses+    -- it to compare elements of the first container with elements of+    -- the second.+    --+    -- @since 4.9.0.0+    liftEq :: (a -> b -> Bool) -> f a -> f b -> Bool+    default liftEq+        :: (f ~ f' c, Eq2 f', Eq c)+        => (a -> b -> Bool) -> f a -> f b -> Bool+    liftEq = liftEq2 (==)++-- | Lift the standard @('==')@ function through the type constructor.+--+-- @since 4.9.0.0+eq1 :: (Eq1 f, Eq a) => f a -> f a -> Bool+eq1 = liftEq (==)++-- | Lifting of the 'Ord' class to unary type constructors.+--+-- Any instance should be subject to the following law that canonicity+-- is preserved:+--+-- @liftCompare compare@ = 'compare'+--+-- This class therefore represents the generalization of 'Ord' by+-- decomposing its main method into a canonical lifting on a canonical+-- inner method, so that the lifting can be reused for other arguments+-- than the canonical one.+--+-- @since 4.9.0.0+class (Eq1 f, forall a. Ord a => Ord (f a)) => Ord1 f where+    -- | Lift a 'compare' function through the type constructor.+    --+    -- The function will usually be applied to a comparison function,+    -- but the more general type ensures that the implementation uses+    -- it to compare elements of the first container with elements of+    -- the second.+    --+    -- @since 4.9.0.0+    liftCompare :: (a -> b -> Ordering) -> f a -> f b -> Ordering+    default liftCompare+        :: (f ~ f' c, Ord2 f', Ord c)+        => (a -> b -> Ordering) -> f a -> f b -> Ordering+    liftCompare = liftCompare2 compare++-- | Lift the standard 'compare' function through the type constructor.+--+-- @since 4.9.0.0+compare1 :: (Ord1 f, Ord a) => f a -> f a -> Ordering+compare1 = liftCompare compare++-- | Lifting of the 'Read' class to unary type constructors.+--+-- Any instance should be subject to the following laws that canonicity+-- is preserved:+--+-- @liftReadsPrec readsPrec readList@ = 'readsPrec'+--+-- @liftReadList readsPrec readList@ = 'readList'+--+-- @liftReadPrec readPrec readListPrec@ = 'readPrec'+--+-- @liftReadListPrec readPrec readListPrec@ = 'readListPrec'+--+-- This class therefore represents the generalization of 'Read' by+-- decomposing it's methods into a canonical lifting on a canonical+-- inner method, so that the lifting can be reused for other arguments+-- than the canonical one.+--+-- Both 'liftReadsPrec' and 'liftReadPrec' exist to match the interface+-- provided in the 'Read' type class, but it is recommended to implement+-- 'Read1' instances using 'liftReadPrec' as opposed to 'liftReadsPrec', since+-- the former is more efficient than the latter. For example:+--+-- @+-- instance 'Read1' T where+--   'liftReadPrec'     = ...+--   'liftReadListPrec' = 'liftReadListPrecDefault'+-- @+--+-- For more information, refer to the documentation for the 'Read' class.+--+-- @since 4.9.0.0+class (forall a. Read a => Read (f a)) => Read1 f where+    {-# MINIMAL liftReadsPrec | liftReadPrec #-}++    -- | 'readsPrec' function for an application of the type constructor+    -- based on 'readsPrec' and 'readList' functions for the argument type.+    --+    -- @since 4.9.0.0+    liftReadsPrec :: (Int -> ReadS a) -> ReadS [a] -> Int -> ReadS (f a)+    liftReadsPrec rp rl = readPrec_to_S $+        liftReadPrec (readS_to_Prec rp) (readS_to_Prec (const rl))++    -- | 'readList' function for an application of the type constructor+    -- based on 'readsPrec' and 'readList' functions for the argument type.+    -- The default implementation using standard list syntax is correct+    -- for most types.+    --+    -- @since 4.9.0.0+    liftReadList :: (Int -> ReadS a) -> ReadS [a] -> ReadS [f a]+    liftReadList rp rl = readPrec_to_S+        (list $ liftReadPrec (readS_to_Prec rp) (readS_to_Prec (const rl))) 0++    -- | 'readPrec' function for an application of the type constructor+    -- based on 'readPrec' and 'readListPrec' functions for the argument type.+    --+    -- @since 4.10.0.0+    liftReadPrec :: ReadPrec a -> ReadPrec [a] -> ReadPrec (f a)+    liftReadPrec rp rl = readS_to_Prec $+        liftReadsPrec (readPrec_to_S rp) (readPrec_to_S rl 0)++    -- | 'readListPrec' function for an application of the type constructor+    -- based on 'readPrec' and 'readListPrec' functions for the argument type.+    --+    -- The default definition uses 'liftReadList'. Instances that define+    -- 'liftReadPrec' should also define 'liftReadListPrec' as+    -- 'liftReadListPrecDefault'.+    --+    -- @since 4.10.0.0+    liftReadListPrec :: ReadPrec a -> ReadPrec [a] -> ReadPrec [f a]+    liftReadListPrec rp rl = readS_to_Prec $ \_ ->+        liftReadList (readPrec_to_S rp) (readPrec_to_S rl 0)++-- | Lift the standard 'readsPrec' and 'readList' functions through the+-- type constructor.+--+-- @since 4.9.0.0+readsPrec1 :: (Read1 f, Read a) => Int -> ReadS (f a)+readsPrec1 = liftReadsPrec readsPrec readList++-- | Lift the standard 'readPrec' and 'readListPrec' functions through the+-- type constructor.+--+-- @since 4.10.0.0+readPrec1 :: (Read1 f, Read a) => ReadPrec (f a)+readPrec1 = liftReadPrec readPrec readListPrec++-- | A possible replacement definition for the 'liftReadList' method.+-- This is only needed for 'Read1' instances where 'liftReadListPrec' isn't+-- defined as 'liftReadListPrecDefault'.+--+-- @since 4.10.0.0+liftReadListDefault :: Read1 f => (Int -> ReadS a) -> ReadS [a] -> ReadS [f a]+liftReadListDefault rp rl = readPrec_to_S+    (liftReadListPrec (readS_to_Prec rp) (readS_to_Prec (const rl))) 0++-- | A possible replacement definition for the 'liftReadListPrec' method,+-- defined using 'liftReadPrec'.+--+-- @since 4.10.0.0+liftReadListPrecDefault :: Read1 f => ReadPrec a -> ReadPrec [a]+                        -> ReadPrec [f a]+liftReadListPrecDefault rp rl = list (liftReadPrec rp rl)++-- | Lifting of the 'Show' class to unary type constructors.+--+-- Any instance should be subject to the following laws that canonicity+-- is preserved:+--+-- @liftShowsPrec showsPrec showList@ = 'showsPrec'+--+-- @liftShowList showsPrec showList@ = 'showList'+--+-- This class therefore represents the generalization of 'Show' by+-- decomposing it's methods into a canonical lifting on a canonical+-- inner method, so that the lifting can be reused for other arguments+-- than the canonical one.+--+-- @since 4.9.0.0+class (forall a. Show a => Show (f a)) => Show1 f where+    -- | 'showsPrec' function for an application of the type constructor+    -- based on 'showsPrec' and 'showList' functions for the argument type.+    --+    -- @since 4.9.0.0+    liftShowsPrec :: (Int -> a -> ShowS) -> ([a] -> ShowS) ->+        Int -> f a -> ShowS+    default liftShowsPrec+        :: (f ~ f' b, Show2 f', Show b)+        => (Int -> a -> ShowS) -> ([a] -> ShowS) -> Int -> f a -> ShowS+    liftShowsPrec = liftShowsPrec2 showsPrec showList++    -- | 'showList' function for an application of the type constructor+    -- based on 'showsPrec' and 'showList' functions for the argument type.+    -- The default implementation using standard list syntax is correct+    -- for most types.+    --+    -- @since 4.9.0.0+    liftShowList :: (Int -> a -> ShowS) -> ([a] -> ShowS) ->+        [f a] -> ShowS+    liftShowList sp sl = showListWith (liftShowsPrec sp sl 0)++-- | Lift the standard 'showsPrec' and 'showList' functions through the+-- type constructor.+--+-- @since 4.9.0.0+showsPrec1 :: (Show1 f, Show a) => Int -> f a -> ShowS+showsPrec1 = liftShowsPrec showsPrec showList++-- | Lifting of the 'Eq' class to binary type constructors.+--+-- @since 4.9.0.0+class (forall a. Eq a => Eq1 (f a)) => Eq2 f where+    -- | Lift equality tests through the type constructor.+    --+    -- The function will usually be applied to equality functions,+    -- but the more general type ensures that the implementation uses+    -- them to compare elements of the first container with elements of+    -- the second.+    --+    -- @since 4.9.0.0+    liftEq2 :: (a -> b -> Bool) -> (c -> d -> Bool) -> f a c -> f b d -> Bool++-- | Lift the standard @('==')@ function through the type constructor.+--+-- @since 4.9.0.0+eq2 :: (Eq2 f, Eq a, Eq b) => f a b -> f a b -> Bool+eq2 = liftEq2 (==) (==)++-- | Lifting of the 'Ord' class to binary type constructors.+--+-- @since 4.9.0.0+class (Eq2 f, forall a. Ord a => Ord1 (f a)) => Ord2 f where+    -- | Lift 'compare' functions through the type constructor.+    --+    -- The function will usually be applied to comparison functions,+    -- but the more general type ensures that the implementation uses+    -- them to compare elements of the first container with elements of+    -- the second.+    --+    -- @since 4.9.0.0+    liftCompare2 :: (a -> b -> Ordering) -> (c -> d -> Ordering) ->+        f a c -> f b d -> Ordering++-- | Lift the standard 'compare' function through the type constructor.+--+-- @since 4.9.0.0+compare2 :: (Ord2 f, Ord a, Ord b) => f a b -> f a b -> Ordering+compare2 = liftCompare2 compare compare++-- | Lifting of the 'Read' class to binary type constructors.+--+-- Both 'liftReadsPrec2' and 'liftReadPrec2' exist to match the interface+-- provided in the 'Read' type class, but it is recommended to implement+-- 'Read2' instances using 'liftReadPrec2' as opposed to 'liftReadsPrec2',+-- since the former is more efficient than the latter. For example:+--+-- @+-- instance 'Read2' T where+--   'liftReadPrec2'     = ...+--   'liftReadListPrec2' = 'liftReadListPrec2Default'+-- @+--+-- For more information, refer to the documentation for the 'Read' class.+--+-- @since 4.9.0.0+class (forall a. Read a => Read1 (f a)) => Read2 f where+    {-# MINIMAL liftReadsPrec2 | liftReadPrec2 #-}++    -- | 'readsPrec' function for an application of the type constructor+    -- based on 'readsPrec' and 'readList' functions for the argument types.+    --+    -- @since 4.9.0.0+    liftReadsPrec2 :: (Int -> ReadS a) -> ReadS [a] ->+        (Int -> ReadS b) -> ReadS [b] -> Int -> ReadS (f a b)+    liftReadsPrec2 rp1 rl1 rp2 rl2 = readPrec_to_S $+        liftReadPrec2 (readS_to_Prec rp1) (readS_to_Prec (const rl1))+                      (readS_to_Prec rp2) (readS_to_Prec (const rl2))++    -- | 'readList' function for an application of the type constructor+    -- based on 'readsPrec' and 'readList' functions for the argument types.+    -- The default implementation using standard list syntax is correct+    -- for most types.+    --+    -- @since 4.9.0.0+    liftReadList2 :: (Int -> ReadS a) -> ReadS [a] ->+        (Int -> ReadS b) -> ReadS [b] -> ReadS [f a b]+    liftReadList2 rp1 rl1 rp2 rl2 = readPrec_to_S+       (list $ liftReadPrec2 (readS_to_Prec rp1) (readS_to_Prec (const rl1))+                             (readS_to_Prec rp2) (readS_to_Prec (const rl2))) 0++    -- | 'readPrec' function for an application of the type constructor+    -- based on 'readPrec' and 'readListPrec' functions for the argument types.+    --+    -- @since 4.10.0.0+    liftReadPrec2 :: ReadPrec a -> ReadPrec [a] ->+        ReadPrec b -> ReadPrec [b] -> ReadPrec (f a b)+    liftReadPrec2 rp1 rl1 rp2 rl2 = readS_to_Prec $+        liftReadsPrec2 (readPrec_to_S rp1) (readPrec_to_S rl1 0)+                       (readPrec_to_S rp2) (readPrec_to_S rl2 0)++    -- | 'readListPrec' function for an application of the type constructor+    -- based on 'readPrec' and 'readListPrec' functions for the argument types.+    --+    -- The default definition uses 'liftReadList2'. Instances that define+    -- 'liftReadPrec2' should also define 'liftReadListPrec2' as+    -- 'liftReadListPrec2Default'.+    --+    -- @since 4.10.0.0+    liftReadListPrec2 :: ReadPrec a -> ReadPrec [a] ->+        ReadPrec b -> ReadPrec [b] -> ReadPrec [f a b]+    liftReadListPrec2 rp1 rl1 rp2 rl2 = readS_to_Prec $ \_ ->+        liftReadList2 (readPrec_to_S rp1) (readPrec_to_S rl1 0)+                      (readPrec_to_S rp2) (readPrec_to_S rl2 0)++-- | Lift the standard 'readsPrec' function through the type constructor.+--+-- @since 4.9.0.0+readsPrec2 :: (Read2 f, Read a, Read b) => Int -> ReadS (f a b)+readsPrec2 = liftReadsPrec2 readsPrec readList readsPrec readList++-- | Lift the standard 'readPrec' function through the type constructor.+--+-- @since 4.10.0.0+readPrec2 :: (Read2 f, Read a, Read b) => ReadPrec (f a b)+readPrec2 = liftReadPrec2 readPrec readListPrec readPrec readListPrec++-- | A possible replacement definition for the 'liftReadList2' method.+-- This is only needed for 'Read2' instances where 'liftReadListPrec2' isn't+-- defined as 'liftReadListPrec2Default'.+--+-- @since 4.10.0.0+liftReadList2Default :: Read2 f => (Int -> ReadS a) -> ReadS [a] ->+    (Int -> ReadS b) -> ReadS [b] ->ReadS [f a b]+liftReadList2Default rp1 rl1 rp2 rl2 = readPrec_to_S+    (liftReadListPrec2 (readS_to_Prec rp1) (readS_to_Prec (const rl1))+                       (readS_to_Prec rp2) (readS_to_Prec (const rl2))) 0++-- | A possible replacement definition for the 'liftReadListPrec2' method,+-- defined using 'liftReadPrec2'.+--+-- @since 4.10.0.0+liftReadListPrec2Default :: Read2 f => ReadPrec a -> ReadPrec [a] ->+    ReadPrec b -> ReadPrec [b] -> ReadPrec [f a b]+liftReadListPrec2Default rp1 rl1 rp2 rl2 = list (liftReadPrec2 rp1 rl1 rp2 rl2)++-- | Lifting of the 'Show' class to binary type constructors.+--+-- @since 4.9.0.0+class (forall a. Show a => Show1 (f a)) => Show2 f where+    -- | 'showsPrec' function for an application of the type constructor+    -- based on 'showsPrec' and 'showList' functions for the argument types.+    --+    -- @since 4.9.0.0+    liftShowsPrec2 :: (Int -> a -> ShowS) -> ([a] -> ShowS) ->+        (Int -> b -> ShowS) -> ([b] -> ShowS) -> Int -> f a b -> ShowS++    -- | 'showList' function for an application of the type constructor+    -- based on 'showsPrec' and 'showList' functions for the argument types.+    -- The default implementation using standard list syntax is correct+    -- for most types.+    --+    -- @since 4.9.0.0+    liftShowList2 :: (Int -> a -> ShowS) -> ([a] -> ShowS) ->+        (Int -> b -> ShowS) -> ([b] -> ShowS) -> [f a b] -> ShowS+    liftShowList2 sp1 sl1 sp2 sl2 =+        showListWith (liftShowsPrec2 sp1 sl1 sp2 sl2 0)++-- | Lift the standard 'showsPrec' function through the type constructor.+--+-- @since 4.9.0.0+showsPrec2 :: (Show2 f, Show a, Show b) => Int -> f a b -> ShowS+showsPrec2 = liftShowsPrec2 showsPrec showList showsPrec showList++-- Instances for Prelude type constructors++-- | @since 4.9.0.0+instance Eq1 Maybe where+    liftEq _ Nothing Nothing = True+    liftEq _ Nothing (Just _) = False+    liftEq _ (Just _) Nothing = False+    liftEq eq (Just x) (Just y) = eq x y++-- | @since 4.9.0.0+instance Ord1 Maybe where+    liftCompare _ Nothing Nothing = EQ+    liftCompare _ Nothing (Just _) = LT+    liftCompare _ (Just _) Nothing = GT+    liftCompare comp (Just x) (Just y) = comp x y++-- | @since 4.9.0.0+instance Read1 Maybe where+    liftReadPrec rp _ =+        parens (expectP (Ident "Nothing") *> pure Nothing)+        <|>+        readData (readUnaryWith rp "Just" Just)++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.9.0.0+instance Show1 Maybe where+    liftShowsPrec _ _ _ Nothing = showString "Nothing"+    liftShowsPrec sp _ d (Just x) = showsUnaryWith sp "Just" d x++-- | @since 4.9.0.0+instance Eq1 [] where+    liftEq _ [] [] = True+    liftEq _ [] (_:_) = False+    liftEq _ (_:_) [] = False+    liftEq eq (x:xs) (y:ys) = eq x y && liftEq eq xs ys++-- | @since 4.9.0.0+instance Ord1 [] where+    liftCompare _ [] [] = EQ+    liftCompare _ [] (_:_) = LT+    liftCompare _ (_:_) [] = GT+    liftCompare comp (x:xs) (y:ys) = comp x y `mappend` liftCompare comp xs ys++-- | @since 4.9.0.0+instance Read1 [] where+    liftReadPrec _ rl = rl+    liftReadListPrec  = liftReadListPrecDefault+    liftReadList      = liftReadListDefault++-- | @since 4.9.0.0+instance Show1 [] where+    liftShowsPrec _ sl _ = sl++-- | @since 4.10.0.0+instance Eq1 NonEmpty where+  liftEq eq (a :| as) (b :| bs) = eq a b && liftEq eq as bs++-- | @since 4.10.0.0+instance Ord1 NonEmpty where+  liftCompare cmp (a :| as) (b :| bs) = cmp a b `mappend` liftCompare cmp as bs++-- | @since 4.10.0.0+instance Read1 NonEmpty where+  liftReadsPrec rdP rdL p s = readParen (p > 5) (\s' -> do+    (a, s'') <- rdP 6 s'+    (":|", s''') <- lex s''+    (as, s'''') <- rdL s'''+    return (a :| as, s'''')) s++-- | @since 4.10.0.0+instance Show1 NonEmpty where+  liftShowsPrec shwP shwL p (a :| as) = showParen (p > 5) $+    shwP 6 a . showString " :| " . shwL as+++-- | @since 4.9.0.0+instance Eq2 (,) where+    liftEq2 e1 e2 (x1, y1) (x2, y2) = e1 x1 x2 && e2 y1 y2++-- | @since 4.9.0.0+instance Ord2 (,) where+    liftCompare2 comp1 comp2 (x1, y1) (x2, y2) =+        comp1 x1 x2 `mappend` comp2 y1 y2++-- | @since 4.9.0.0+instance Read2 (,) where+    liftReadPrec2 rp1 _ rp2 _ = parens $ paren $ do+        x <- rp1+        expectP (Punc ",")+        y <- rp2+        return (x,y)++    liftReadListPrec2 = liftReadListPrec2Default+    liftReadList2     = liftReadList2Default++-- | @since 4.9.0.0+instance Show2 (,) where+    liftShowsPrec2 sp1 _ sp2 _ _ (x, y) =+        showChar '(' . sp1 0 x . showChar ',' . sp2 0 y . showChar ')'++-- | @since 4.15+instance Eq1 Solo where+  liftEq eq (MkSolo a) (MkSolo b) = a `eq` b++-- | @since 4.9.0.0+instance (Eq a) => Eq1 ((,) a) where+    liftEq = liftEq2 (==)++-- | @since 4.15+instance Ord1 Solo where+  liftCompare cmp (MkSolo a) (MkSolo b) = cmp a b++-- | @since 4.9.0.0+instance (Ord a) => Ord1 ((,) a) where+    liftCompare = liftCompare2 compare++-- | @since 4.15+instance Read1 Solo where+    liftReadPrec rp _ = readData (readUnaryWith rp "MkSolo" MkSolo)++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.9.0.0+instance (Read a) => Read1 ((,) a) where+    liftReadPrec = liftReadPrec2 readPrec readListPrec++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.15+instance Show1 Solo where+    liftShowsPrec sp _ d (MkSolo x) = showsUnaryWith sp "MkSolo" d x++-- | @since 4.9.0.0+instance (Show a) => Show1 ((,) a) where+    liftShowsPrec = liftShowsPrec2 showsPrec showList+++-- | @since 4.16.0.0+--+-- >>> eq2 ('x', True, "str") ('x', True, "str")+-- True+--+instance Eq a => Eq2 ((,,) a) where+    liftEq2 e1 e2 (u1, x1, y1) (v1, x2, y2) =+        u1 == v1 &&+        e1 x1 x2 && e2 y1 y2++-- | @since 4.16.0.0+--+-- >>> compare2 ('x', True, "aaa") ('x', True, "zzz")+-- LT+instance Ord a => Ord2 ((,,) a) where+    liftCompare2 comp1 comp2 (u1, x1, y1) (v1, x2, y2) =+        compare u1 v1 `mappend`+        comp1 x1 x2 `mappend` comp2 y1 y2++-- | @since 4.16.0.0+--+-- >>> readPrec_to_S readPrec2 0 "('x', True, 2)" :: [((Char, Bool, Int), String)]+-- [(('x',True,2),"")]+--+instance Read a => Read2 ((,,) a) where+    liftReadPrec2 rp1 _ rp2 _ = parens $ paren $ do+        x1 <- readPrec+        expectP (Punc ",")+        y1 <- rp1+        expectP (Punc ",")+        y2 <- rp2+        return (x1,y1,y2)++    liftReadListPrec2 = liftReadListPrec2Default+    liftReadList2     = liftReadList2Default++-- | @since 4.16.0.0+--+-- >>> showsPrec2 0 ('x', True, 2 :: Int) ""+-- "('x',True,2)"+--+instance Show a => Show2 ((,,) a) where+    liftShowsPrec2 sp1 _ sp2 _ _ (x1,y1,y2)+        = showChar '(' . showsPrec 0 x1+        . showChar ',' . sp1 0 y1+        . showChar ',' . sp2 0 y2+        . showChar ')'++-- | @since 4.16.0.0+instance (Eq a, Eq b) => Eq1 ((,,) a b) where+    liftEq = liftEq2 (==)++-- | @since 4.16.0.0+instance (Ord a, Ord b) => Ord1 ((,,) a b) where+    liftCompare = liftCompare2 compare++-- | @since 4.16.0.0+instance (Read a, Read b) => Read1 ((,,) a b) where+    liftReadPrec = liftReadPrec2 readPrec readListPrec++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.16.0.0+instance (Show a, Show b) => Show1 ((,,) a b) where+    liftShowsPrec = liftShowsPrec2 showsPrec showList+++-- | @since 4.16.0.0+--+-- >>> eq2 ('x', True, "str", 2) ('x', True, "str", 2 :: Int)+-- True+--+instance (Eq a, Eq b) => Eq2 ((,,,) a b) where+    liftEq2 e1 e2 (u1, u2, x1, y1) (v1, v2, x2, y2) =+        u1 == v1 &&+        u2 == v2 &&+        e1 x1 x2 && e2 y1 y2++-- | @since 4.16.0.0+--+-- >>> compare2 ('x', True, "str", 2) ('x', True, "str", 3 :: Int)+-- LT+--+instance (Ord a, Ord b) => Ord2 ((,,,) a b) where+    liftCompare2 comp1 comp2 (u1, u2, x1, y1) (v1, v2, x2, y2) =+        compare u1 v1 `mappend`+        compare u2 v2 `mappend`+        comp1 x1 x2 `mappend` comp2 y1 y2++-- | @since 4.16.0.0+--+-- >>> readPrec_to_S readPrec2 0 "('x', True, 2, 4.5)" :: [((Char, Bool, Int, Double), String)]+-- [(('x',True,2,4.5),"")]+--+instance (Read a, Read b) => Read2 ((,,,) a b) where+    liftReadPrec2 rp1 _ rp2 _ = parens $ paren $ do+        x1 <- readPrec+        expectP (Punc ",")+        x2 <- readPrec+        expectP (Punc ",")+        y1 <- rp1+        expectP (Punc ",")+        y2 <- rp2+        return (x1,x2,y1,y2)++    liftReadListPrec2 = liftReadListPrec2Default+    liftReadList2     = liftReadList2Default++-- | @since 4.16.0.0+--+-- >>> showsPrec2 0 ('x', True, 2 :: Int, 4.5 :: Double) ""+-- "('x',True,2,4.5)"+--+instance (Show a, Show b) => Show2 ((,,,) a b) where+    liftShowsPrec2 sp1 _ sp2 _ _ (x1,x2,y1,y2)+        = showChar '(' . showsPrec 0 x1+        . showChar ',' . showsPrec 0 x2+        . showChar ',' . sp1 0 y1+        . showChar ',' . sp2 0 y2+        . showChar ')'++-- | @since 4.16.0.0+instance (Eq a, Eq b, Eq c) => Eq1 ((,,,) a b c) where+    liftEq = liftEq2 (==)++-- | @since 4.16.0.0+instance (Ord a, Ord b, Ord c) => Ord1 ((,,,) a b c) where+    liftCompare = liftCompare2 compare++-- | @since 4.16.0.0+instance (Read a, Read b, Read c) => Read1 ((,,,) a b c) where+    liftReadPrec = liftReadPrec2 readPrec readListPrec++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.16.0.0+instance (Show a, Show b, Show c) => Show1 ((,,,) a b c) where+    liftShowsPrec = liftShowsPrec2 showsPrec showList++-- | @since 4.17.0.0+instance (Generic1 f, Eq1 (Rep1 f)) => Eq1 (Generically1 f) where+  liftEq :: (a1 -> a2 -> Bool) -> (Generically1 f a1 -> Generically1 f a2 -> Bool)+  liftEq (===) (Generically1 as1) (Generically1 as2) = liftEq (===) (from1 as1) (from1 as2)++-- | @since 4.17.0.0+instance (Generic1 f, Ord1 (Rep1 f)) => Ord1 (Generically1 f) where+  liftCompare :: (a1 -> a2 -> Ordering) -> (Generically1 f a1 -> Generically1 f a2 -> Ordering)+  liftCompare cmp (Generically1 as1) (Generically1 as2) = liftCompare cmp (from1 as1) (from1 as2)++-- | @since 4.9.0.0+instance Eq2 Either where+    liftEq2 e1 _ (Left x) (Left y) = e1 x y+    liftEq2 _ _ (Left _) (Right _) = False+    liftEq2 _ _ (Right _) (Left _) = False+    liftEq2 _ e2 (Right x) (Right y) = e2 x y++-- | @since 4.9.0.0+instance Ord2 Either where+    liftCompare2 comp1 _ (Left x) (Left y) = comp1 x y+    liftCompare2 _ _ (Left _) (Right _) = LT+    liftCompare2 _ _ (Right _) (Left _) = GT+    liftCompare2 _ comp2 (Right x) (Right y) = comp2 x y++-- | @since 4.9.0.0+instance Read2 Either where+    liftReadPrec2 rp1 _ rp2 _ = readData $+         readUnaryWith rp1 "Left" Left <|>+         readUnaryWith rp2 "Right" Right++    liftReadListPrec2 = liftReadListPrec2Default+    liftReadList2     = liftReadList2Default++-- | @since 4.9.0.0+instance Show2 Either where+    liftShowsPrec2 sp1 _ _ _ d (Left x) = showsUnaryWith sp1 "Left" d x+    liftShowsPrec2 _ _ sp2 _ d (Right x) = showsUnaryWith sp2 "Right" d x++-- | @since 4.9.0.0+instance (Eq a) => Eq1 (Either a) where+    liftEq = liftEq2 (==)++-- | @since 4.9.0.0+instance (Ord a) => Ord1 (Either a) where+    liftCompare = liftCompare2 compare++-- | @since 4.9.0.0+instance (Read a) => Read1 (Either a) where+    liftReadPrec = liftReadPrec2 readPrec readListPrec++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.9.0.0+instance (Show a) => Show1 (Either a) where+    liftShowsPrec = liftShowsPrec2 showsPrec showList++-- Instances for other functors defined in the base package++-- | @since 4.9.0.0+instance Eq1 Identity where+    liftEq eq (Identity x) (Identity y) = eq x y++-- | @since 4.9.0.0+instance Ord1 Identity where+    liftCompare comp (Identity x) (Identity y) = comp x y++-- | @since 4.9.0.0+instance Read1 Identity where+    liftReadPrec rp _ = readData $+         readUnaryWith rp "Identity" Identity++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.9.0.0+instance Show1 Identity where+    liftShowsPrec sp _ d (Identity x) = showsUnaryWith sp "Identity" d x++-- | @since 4.9.0.0+instance Eq2 Const where+    liftEq2 eq _ (Const x) (Const y) = eq x y++-- | @since 4.9.0.0+instance Ord2 Const where+    liftCompare2 comp _ (Const x) (Const y) = comp x y++-- | @since 4.9.0.0+instance Read2 Const where+    liftReadPrec2 rp _ _ _ = readData $+         readUnaryWith rp "Const" Const++    liftReadListPrec2 = liftReadListPrec2Default+    liftReadList2     = liftReadList2Default++-- | @since 4.9.0.0+instance Show2 Const where+    liftShowsPrec2 sp _ _ _ d (Const x) = showsUnaryWith sp "Const" d x++-- | @since 4.9.0.0+instance (Eq a) => Eq1 (Const a) where+    liftEq = liftEq2 (==)+-- | @since 4.9.0.0+instance (Ord a) => Ord1 (Const a) where+    liftCompare = liftCompare2 compare+-- | @since 4.9.0.0+instance (Read a) => Read1 (Const a) where+    liftReadPrec = liftReadPrec2 readPrec readListPrec++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault+-- | @since 4.9.0.0+instance (Show a) => Show1 (Const a) where+    liftShowsPrec = liftShowsPrec2 showsPrec showList++-- Proxy unfortunately imports this module, hence these instances are placed+-- here,+-- | @since 4.9.0.0+instance Eq1 Proxy where+  liftEq _ _ _ = True++-- | @since 4.9.0.0+instance Ord1 Proxy where+  liftCompare _ _ _ = EQ++-- | @since 4.9.0.0+instance Show1 Proxy where+  liftShowsPrec _ _ _ _ = showString "Proxy"++-- | @since 4.9.0.0+instance Read1 Proxy where+  liftReadPrec _ _ = parens (expectP (Ident "Proxy") *> pure Proxy)++  liftReadListPrec = liftReadListPrecDefault+  liftReadList     = liftReadListDefault++-- | @since 4.12.0.0+instance Eq1 Down where+    liftEq eq (Down x) (Down y) = eq x y++-- | @since 4.12.0.0+instance Ord1 Down where+    liftCompare comp (Down x) (Down y) = case comp x y of+        LT -> GT+        EQ -> EQ+        GT -> LT++-- | @since 4.12.0.0+instance Read1 Down where+    liftReadsPrec rp _ = readsData $+         readsUnaryWith rp "Down" Down++-- | @since 4.12.0.0+instance Show1 Down where+    liftShowsPrec sp _ d (Down x) = showsUnaryWith sp "Down" d x++-- | @since 4.16.0.0+--+-- >>> eq1 (1 :+ 2) (1 :+ 2)+-- True+--+-- >>> eq1 (1 :+ 2) (1 :+ 3)+-- False+--+instance Eq1 Complex where+    liftEq eq (x :+ y) (u :+ v) = eq x u && eq y v++-- | @since 4.16.0.0+--+-- >>> readPrec_to_S readPrec1 0 "(2 % 3) :+ (3 % 4)" :: [(Complex Rational, String)]+-- [(2 % 3 :+ 3 % 4,"")]+--+instance Read1 Complex where+    liftReadPrec rp _  = parens $ prec complexPrec $ do+        x <- step rp+        expectP (Symbol ":+")+        y <- step rp+        return (x :+ y)+      where+        complexPrec = 6++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.16.0.0+--+-- >>> showsPrec1 0 (2 :+ 3) ""+-- "2 :+ 3"+--+instance Show1 Complex where+    liftShowsPrec sp _ d (x :+ y) = showParen (d > complexPrec) $+        sp (complexPrec+1) x . showString " :+ " . sp (complexPrec+1) y+      where+        complexPrec = 6++-- Building blocks++-- | @'readsData' p d@ is a parser for datatypes where each alternative+-- begins with a data constructor.  It parses the constructor and+-- passes it to @p@.  Parsers for various constructors can be constructed+-- with 'readsUnary', 'readsUnary1' and 'readsBinary1', and combined with+-- @mappend@ from the @Monoid@ class.+--+-- @since 4.9.0.0+readsData :: (String -> ReadS a) -> Int -> ReadS a+readsData reader d =+    readParen (d > 10) $ \ r -> [res | (kw,s) <- lex r, res <- reader kw s]++-- | @'readData' p@ is a parser for datatypes where each alternative+-- begins with a data constructor.  It parses the constructor and+-- passes it to @p@.  Parsers for various constructors can be constructed+-- with 'readUnaryWith' and 'readBinaryWith', and combined with+-- '(<|>)' from the 'Alternative' class.+--+-- @since 4.10.0.0+readData :: ReadPrec a -> ReadPrec a+readData reader = parens $ prec 10 reader++-- | @'readsUnaryWith' rp n c n'@ matches the name of a unary data constructor+-- and then parses its argument using @rp@.+--+-- @since 4.9.0.0+readsUnaryWith :: (Int -> ReadS a) -> String -> (a -> t) -> String -> ReadS t+readsUnaryWith rp name cons kw s =+    [(cons x,t) | kw == name, (x,t) <- rp 11 s]++-- | @'readUnaryWith' rp n c'@ matches the name of a unary data constructor+-- and then parses its argument using @rp@.+--+-- @since 4.10.0.0+readUnaryWith :: ReadPrec a -> String -> (a -> t) -> ReadPrec t+readUnaryWith rp name cons = do+    expectP $ Ident name+    x <- step rp+    return $ cons x++-- | @'readsBinaryWith' rp1 rp2 n c n'@ matches the name of a binary+-- data constructor and then parses its arguments using @rp1@ and @rp2@+-- respectively.+--+-- @since 4.9.0.0+readsBinaryWith :: (Int -> ReadS a) -> (Int -> ReadS b) ->+    String -> (a -> b -> t) -> String -> ReadS t+readsBinaryWith rp1 rp2 name cons kw s =+    [(cons x y,u) | kw == name, (x,t) <- rp1 11 s, (y,u) <- rp2 11 t]++-- | @'readBinaryWith' rp1 rp2 n c'@ matches the name of a binary+-- data constructor and then parses its arguments using @rp1@ and @rp2@+-- respectively.+--+-- @since 4.10.0.0+readBinaryWith :: ReadPrec a -> ReadPrec b ->+    String -> (a -> b -> t) -> ReadPrec t+readBinaryWith rp1 rp2 name cons = do+    expectP $ Ident name+    x <- step rp1+    y <- step rp2+    return $ cons x y++-- | @'showsUnaryWith' sp n d x@ produces the string representation of a+-- unary data constructor with name @n@ and argument @x@, in precedence+-- context @d@.+--+-- @since 4.9.0.0+showsUnaryWith :: (Int -> a -> ShowS) -> String -> Int -> a -> ShowS+showsUnaryWith sp name d x = showParen (d > 10) $+    showString name . showChar ' ' . sp 11 x++-- | @'showsBinaryWith' sp1 sp2 n d x y@ produces the string+-- representation of a binary data constructor with name @n@ and arguments+-- @x@ and @y@, in precedence context @d@.+--+-- @since 4.9.0.0+showsBinaryWith :: (Int -> a -> ShowS) -> (Int -> b -> ShowS) ->+    String -> Int -> a -> b -> ShowS+showsBinaryWith sp1 sp2 name d x y = showParen (d > 10) $+    showString name . showChar ' ' . sp1 11 x . showChar ' ' . sp2 11 y++-- Obsolete building blocks++-- | @'readsUnary' n c n'@ matches the name of a unary data constructor+-- and then parses its argument using 'readsPrec'.+--+-- @since 4.9.0.0+{-# DEPRECATED readsUnary "Use 'readsUnaryWith' to define 'liftReadsPrec'" #-}+readsUnary :: (Read a) => String -> (a -> t) -> String -> ReadS t+readsUnary name cons kw s =+    [(cons x,t) | kw == name, (x,t) <- readsPrec 11 s]++-- | @'readsUnary1' n c n'@ matches the name of a unary data constructor+-- and then parses its argument using 'readsPrec1'.+--+-- @since 4.9.0.0+{-# DEPRECATED readsUnary1 "Use 'readsUnaryWith' to define 'liftReadsPrec'" #-}+readsUnary1 :: (Read1 f, Read a) => String -> (f a -> t) -> String -> ReadS t+readsUnary1 name cons kw s =+    [(cons x,t) | kw == name, (x,t) <- readsPrec1 11 s]++-- | @'readsBinary1' n c n'@ matches the name of a binary data constructor+-- and then parses its arguments using 'readsPrec1'.+--+-- @since 4.9.0.0+{-# DEPRECATED readsBinary1+      "Use 'readsBinaryWith' to define 'liftReadsPrec'" #-}+readsBinary1 :: (Read1 f, Read1 g, Read a) =>+    String -> (f a -> g a -> t) -> String -> ReadS t+readsBinary1 name cons kw s =+    [(cons x y,u) | kw == name,+        (x,t) <- readsPrec1 11 s, (y,u) <- readsPrec1 11 t]++-- | @'showsUnary' n d x@ produces the string representation of a unary data+-- constructor with name @n@ and argument @x@, in precedence context @d@.+--+-- @since 4.9.0.0+{-# DEPRECATED showsUnary "Use 'showsUnaryWith' to define 'liftShowsPrec'" #-}+showsUnary :: (Show a) => String -> Int -> a -> ShowS+showsUnary name d x = showParen (d > 10) $+    showString name . showChar ' ' . showsPrec 11 x++-- | @'showsUnary1' n d x@ produces the string representation of a unary data+-- constructor with name @n@ and argument @x@, in precedence context @d@.+--+-- @since 4.9.0.0+{-# DEPRECATED showsUnary1 "Use 'showsUnaryWith' to define 'liftShowsPrec'" #-}+showsUnary1 :: (Show1 f, Show a) => String -> Int -> f a -> ShowS+showsUnary1 name d x = showParen (d > 10) $+    showString name . showChar ' ' . showsPrec1 11 x++-- | @'showsBinary1' n d x y@ produces the string representation of a binary+-- data constructor with name @n@ and arguments @x@ and @y@, in precedence+-- context @d@.+--+-- @since 4.9.0.0+{-# DEPRECATED showsBinary1+      "Use 'showsBinaryWith' to define 'liftShowsPrec'" #-}+showsBinary1 :: (Show1 f, Show1 g, Show a) =>+    String -> Int -> f a -> g a -> ShowS+showsBinary1 name d x y = showParen (d > 10) $+    showString name . showChar ' ' . showsPrec1 11 x .+        showChar ' ' . showsPrec1 11 y++{- $example+These functions can be used to assemble 'Read' and 'Show' instances for+new algebraic types.  For example, given the definition++> data T f a = Zero a | One (f a) | Two a (f a)++a standard 'Read1' instance may be defined as++> instance (Read1 f) => Read1 (T f) where+>     liftReadPrec rp rl = readData $+>         readUnaryWith rp "Zero" Zero <|>+>         readUnaryWith (liftReadPrec rp rl) "One" One <|>+>         readBinaryWith rp (liftReadPrec rp rl) "Two" Two+>     liftReadListPrec = liftReadListPrecDefault++and the corresponding 'Show1' instance as++> instance (Show1 f) => Show1 (T f) where+>     liftShowsPrec sp _ d (Zero x) =+>         showsUnaryWith sp "Zero" d x+>     liftShowsPrec sp sl d (One x) =+>         showsUnaryWith (liftShowsPrec sp sl) "One" d x+>     liftShowsPrec sp sl d (Two x y) =+>         showsBinaryWith sp (liftShowsPrec sp sl) "Two" d x y++-}++-- | @since base-4.21.0.0+instance Eq1 V1 where+  liftEq _ = \_ _ -> True++-- | @since base-4.21.0.0+instance Ord1 V1 where+  liftCompare _ = \_ _ -> EQ++-- | @since base-4.21.0.0+instance Show1 V1 where+  liftShowsPrec _ _ _ = \_ -> showString "V1"++-- | @since base-4.21.0.0+instance Read1 V1 where+  liftReadsPrec _ _ = readPrec_to_S pfail+  liftReadListPrec  = liftReadListPrecDefault+  liftReadList      = liftReadListDefault++-- | @since base-4.21.0.0+instance Eq1 U1 where+  liftEq _ = \_ _ -> True++-- | @since base-4.21.0.0+instance Ord1 U1 where+  liftCompare _ = \_ _ -> EQ++-- | @since base-4.21.0.0+instance Show1 U1 where+  liftShowsPrec _ _ _ = \U1 -> showString "U1"++-- | @since base-4.21.0.0+instance Read1 U1 where+  liftReadPrec _ _ =+    parens (expectP (Ident "U1") *> pure U1)++  liftReadListPrec  = liftReadListPrecDefault+  liftReadList      = liftReadListDefault++-- | @since base-4.21.0.0+instance Eq1 Par1 where+  liftEq eq = \(Par1 a) (Par1 a') -> eq a a'++-- | @since base-4.21.0.0+instance Ord1 Par1 where+  liftCompare cmp = \(Par1 a) (Par1 a') -> cmp a a'++-- | @since base-4.21.0.0+instance Show1 Par1 where+  liftShowsPrec sp _ d = \(Par1 { unPar1 = a }) ->+    showsSingleFieldRecordWith sp "Par1" "unPar1" d a++-- | @since base-4.21.0.0+instance Read1 Par1 where+  liftReadPrec rp _ =+    readsSingleFieldRecordWith rp "Par1" "unPar1" Par1++  liftReadListPrec  = liftReadListPrecDefault+  liftReadList      = liftReadListDefault++-- | @since base-4.21.0.0+instance Eq1 f => Eq1 (Rec1 f) where+  liftEq eq = \(Rec1 a) (Rec1 a') -> liftEq eq a a'++-- | @since base-4.21.0.0+instance Ord1 f => Ord1 (Rec1 f) where+  liftCompare cmp = \(Rec1 a) (Rec1 a') -> liftCompare cmp a a'++-- | @since base-4.21.0.0+instance Show1 f => Show1 (Rec1 f) where+  liftShowsPrec sp sl d = \(Rec1 { unRec1 = a }) ->+    showsSingleFieldRecordWith (liftShowsPrec sp sl) "Rec1" "unRec1" d a++-- | @since base-4.21.0.0+instance Read1 f => Read1 (Rec1 f) where+  liftReadPrec rp rl =+    readsSingleFieldRecordWith (liftReadPrec rp rl) "Rec1" "unRec1" Rec1++  liftReadListPrec   = liftReadListPrecDefault+  liftReadList       = liftReadListDefault++-- | @since base-4.21.0.0+instance Eq c => Eq1 (K1 i c) where+  liftEq _ = \(K1 a) (K1 a') -> a == a'++-- | @since base-4.21.0.0+instance Ord c => Ord1 (K1 i c) where+  liftCompare _ = \(K1 a) (K1 a') -> compare a a'++-- | @since base-4.21.0.0+instance Show c => Show1 (K1 i c) where+  liftShowsPrec _ _ d = \(K1 { unK1 = a }) ->+    showsSingleFieldRecordWith showsPrec "K1" "unK1" d a++-- | @since base-4.21.0.0+instance Read c => Read1 (K1 i c) where+  liftReadPrec _ _ = readData $+    readsSingleFieldRecordWith readPrec "K1" "unK1" K1++  liftReadListPrec  = liftReadListPrecDefault+  liftReadList      = liftReadListDefault++-- | @since base-4.21.0.0+instance Eq1 f => Eq1 (M1 i c f) where+  liftEq eq = \(M1 a) (M1 a') -> liftEq eq a a'++-- | @since base-4.21.0.0+instance Ord1 f => Ord1 (M1 i c f) where+  liftCompare cmp = \(M1 a) (M1 a') -> liftCompare cmp a a'++-- | @since base-4.21.0.0+instance Show1 f => Show1 (M1 i c f) where+  liftShowsPrec sp sl d = \(M1 { unM1 = a }) ->+    showsSingleFieldRecordWith (liftShowsPrec sp sl) "M1" "unM1" d a++-- | @since base-4.21.0.0+instance Read1 f => Read1 (M1 i c f) where+  liftReadPrec rp rl = readData $+    readsSingleFieldRecordWith (liftReadPrec rp rl) "M1" "unM1" M1++  liftReadListPrec  = liftReadListPrecDefault+  liftReadList      = liftReadListDefault++-- | @since base-4.21.0.0+instance (Eq1 f, Eq1 g) => Eq1 (f :+: g) where+  liftEq eq = \lhs rhs -> case (lhs, rhs) of+    (L1 a, L1 a') -> liftEq eq a a'+    (R1 b, R1 b') -> liftEq eq b b'+    _           -> False++-- | @since base-4.21.0.0+instance (Ord1 f, Ord1 g) => Ord1 (f :+: g) where+  liftCompare cmp = \lhs rhs -> case (lhs, rhs) of+    (L1 _, R1 _)  -> LT+    (R1 _, L1 _)  -> GT+    (L1 a, L1 a') -> liftCompare cmp a a'+    (R1 b, R1 b') -> liftCompare cmp b b'++-- | @since base-4.21.0.0+instance (Show1 f, Show1 g) => Show1 (f :+: g) where+  liftShowsPrec sp sl d = \x -> case x of+    L1 a -> showsUnaryWith (liftShowsPrec sp sl) "L1" d a+    R1 b -> showsUnaryWith (liftShowsPrec sp sl) "R1" d b++-- | @since base-4.21.0.0+instance (Read1 f, Read1 g) => Read1 (f :+: g) where+  liftReadPrec rp rl = readData $+    readUnaryWith (liftReadPrec rp rl) "L1" L1 <|>+    readUnaryWith (liftReadPrec rp rl) "R1" R1++  liftReadListPrec  = liftReadListPrecDefault+  liftReadList      = liftReadListDefault++-- | @since base-4.21.0.0+instance (Eq1 f, Eq1 g) => Eq1 (f :*: g) where+  liftEq eq = \(f :*: g) (f' :*: g') -> liftEq eq f f' && liftEq eq g g'++-- | @since base-4.21.0.0+instance (Ord1 f, Ord1 g) => Ord1 (f :*: g) where+  liftCompare cmp = \(f :*: g) (f' :*: g') -> liftCompare cmp f f' <> liftCompare cmp g g'++-- | @since base-4.21.0.0+instance (Show1 f, Show1 g) => Show1 (f :*: g) where+  liftShowsPrec sp sl d = \(a :*: b) ->+    showsBinaryOpWith+      (liftShowsPrec sp sl)+      (liftShowsPrec sp sl)+      7+      ":*:"+      d+      a+      b++-- | @since base-4.21.0.0+instance (Read1 f, Read1 g) => Read1 (f :*: g) where+  liftReadPrec rp rl = parens $ prec 6 $+    readBinaryOpWith (liftReadPrec rp rl) (liftReadPrec rp rl) ":*:" (:*:)++  liftReadListPrec  = liftReadListPrecDefault+  liftReadList      = liftReadListDefault++-- | @since base-4.21.0.0+instance (Eq1 f, Eq1 g) => Eq1 (f :.: g) where+  liftEq eq = \(Comp1 a) (Comp1 a') -> liftEq (liftEq eq) a a'++-- | @since base-4.21.0.0+instance (Ord1 f, Ord1 g) => Ord1 (f :.: g) where+  liftCompare cmp = \(Comp1 a) (Comp1 a') -> liftCompare (liftCompare cmp) a a'++-- | @since base-4.21.0.0+instance (Show1 f, Show1 g) => Show1 (f :.: g) where+  liftShowsPrec sp sl d = \(Comp1 { unComp1 = a }) ->+    showsSingleFieldRecordWith+      (liftShowsPrec (liftShowsPrec sp sl) (liftShowList sp sl))+      "Comp1"+      "unComp1"+      d+      a++-- | @since base-4.21.0.0+instance (Read1 f, Read1 g) => Read1 (f :.: g) where+  liftReadPrec rp rl = readData $+    readsSingleFieldRecordWith+      (liftReadPrec (liftReadPrec rp rl) (liftReadListPrec rp rl))+      "Comp1"+      "unComp1"+      Comp1++  liftReadListPrec  = liftReadListPrecDefault+  liftReadList      = liftReadListDefault++-- | @since base-4.21.0.0+instance Eq1 UAddr where+  -- NB cannot use eqAddr# because its module isn't safe+  liftEq _ = \(UAddr a) (UAddr b) -> UAddr a == UAddr b++-- | @since base-4.21.0.0+instance Ord1 UAddr where+  liftCompare _ = \(UAddr a) (UAddr b) -> compare (UAddr a) (UAddr b)++-- | @since base-4.21.0.0+instance Show1 UAddr where+  liftShowsPrec _ _ = showsPrec++-- NB no Read1 for URec (Ptr ()) because there's no Read for Ptr.++-- | @since base-4.21.0.0+instance Eq1 UChar where+  liftEq _ = \(UChar a) (UChar b) -> UChar a == UChar b++-- | @since base-4.21.0.0+instance Ord1 UChar where+  liftCompare _ = \(UChar a) (UChar b) -> compare (UChar a) (UChar b)++-- | @since base-4.21.0.0+instance Show1 UChar where+  liftShowsPrec _ _ = showsPrec++-- | @since base-4.21.0.0+instance Eq1 UDouble where+  liftEq _ = \(UDouble a) (UDouble b) -> UDouble a == UDouble b++-- | @since base-4.21.0.0+instance Ord1 UDouble where+  liftCompare _ = \(UDouble a) (UDouble b) -> compare (UDouble a) (UDouble b)++-- | @since base-4.21.0.0+instance Show1 UDouble where+  liftShowsPrec _ _ = showsPrec++-- | @since base-4.21.0.0+instance Eq1 UFloat where+  liftEq _ = \(UFloat a) (UFloat b) -> UFloat a == UFloat b++-- | @since base-4.21.0.0+instance Ord1 UFloat where+  liftCompare _ = \(UFloat a) (UFloat b) -> compare (UFloat a) (UFloat b)++-- | @since base-4.21.0.0+instance Show1 UFloat where+  liftShowsPrec _ _ = showsPrec++-- | @since base-4.21.0.0+instance Eq1 UInt where+  liftEq _ = \(UInt a) (UInt b) -> UInt a == UInt b++-- | @since base-4.21.0.0+instance Ord1 UInt where+  liftCompare _ = \(UInt a) (UInt b) -> compare (UInt a) (UInt b)++-- | @since base-4.21.0.0+instance Show1 UInt where+  liftShowsPrec _ _ = showsPrec++-- | @since base-4.21.0.0+instance Eq1 UWord where+  liftEq _ = \(UWord a) (UWord b) -> UWord a == UWord b++-- | @since base-4.21.0.0+instance Ord1 UWord where+  liftCompare _ = \(UWord a) (UWord b) -> compare (UWord a) (UWord b)++-- | @since base-4.21.0.0+instance Show1 UWord where+  liftShowsPrec _ _ = showsPrec++showsSingleFieldRecordWith :: (Int -> a -> ShowS) -> String -> String -> Int -> a -> ShowS+showsSingleFieldRecordWith sp name field d x =+  showParen (d > appPrec) $+    showString name . showString " {" . showString field . showString " = " . sp 0 x . showChar '}'++readsSingleFieldRecordWith :: ReadPrec a -> String -> String -> (a -> t) -> ReadPrec t+readsSingleFieldRecordWith rp name field cons = parens $ prec 11 $ do+  expectP $ Ident name+  expectP $ Punc "{"+  x <- readField field $ reset rp+  expectP $ Punc "}"+  pure $ cons x++showsBinaryOpWith+  :: (Int -> a -> ShowS)+  -> (Int -> b -> ShowS)+  -> Int+  -> String+  -> Int+  -> a+  -> b+  -> ShowS+showsBinaryOpWith sp1 sp2 opPrec name d x y = showParen (d >= opPrec) $+  sp1 opPrec x . showChar ' ' . showString name . showChar ' ' . sp2 opPrec y++readBinaryOpWith+  :: ReadPrec a+  -> ReadPrec b+  -> String+  -> (a -> b -> t)+  -> ReadPrec t+readBinaryOpWith rp1 rp2 name cons =+  cons <$> step rp1 <* expectP (Symbol name) <*> step rp2
+ src/Data/Functor/Compose.hs view
@@ -0,0 +1,196 @@+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE StandaloneDeriving #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Functor.Compose+-- Copyright   :  (c) Ross Paterson 2010+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Composition of functors.+--+-- @since 4.9.0.0+-----------------------------------------------------------------------------++module Data.Functor.Compose (+    Compose(..),+  ) where++import Data.Functor.Classes++import Control.Applicative+import GHC.Internal.Data.Coerce (coerce)+import GHC.Internal.Data.Data (Data)+import GHC.Internal.Data.Foldable (Foldable(..))+import GHC.Internal.Data.Monoid (Sum(..), All(..), Any(..), Product(..))+import GHC.Internal.Data.Type.Equality (TestEquality(..), (:~:)(..))+import GHC.Generics (Generic, Generic1)+import GHC.Internal.Text.Read (Read(..), ReadPrec, readListDefault, readListPrecDefault)+import Prelude++infixr 9 `Compose`++-- $setup+-- >>> import Prelude++-- | Right-to-left composition of functors.+-- The composition of applicative functors is always applicative,+-- but the composition of monads is not always a monad.+--+-- ==== __Examples__+--+-- >>> fmap (subtract 1) (Compose (Just [1, 2, 3]))+-- Compose (Just [0,1,2])+--+-- >>> Compose (Just [1, 2, 3]) <> Compose Nothing+-- Compose (Just [1,2,3])+--+-- >>> Compose (Just [(++ "World"), (++ "Haskell")]) <*> Compose (Just ["Hello, "])+-- Compose (Just ["Hello, World","Hello, Haskell"])+newtype Compose f g a = Compose { getCompose :: f (g a) }+  deriving ( Data     -- ^ @since 4.9.0.0+           , Generic  -- ^ @since 4.9.0.0+           , Generic1 -- ^ @since 4.9.0.0+           , Semigroup -- ^ @since 4.16.0.0+           , Monoid    -- ^ @since 4.16.0.0+           )++-- Instances of Prelude classes++-- | @since 4.18.0.0+deriving instance Eq (f (g a)) => Eq (Compose f g a)+-- | @since 4.18.0.0+deriving instance Ord (f (g a)) => Ord (Compose f g a)+-- | @since 4.18.0.0+instance Read (f (g a)) => Read (Compose f g a) where+    readPrec = liftReadPrecCompose readPrec++    readListPrec = readListPrecDefault+    readList     = readListDefault+-- | @since 4.18.0.0+instance Show (f (g a)) => Show (Compose f g a) where+    showsPrec = liftShowsPrecCompose showsPrec++-- Instances of lifted Prelude classes++-- | @since 4.9.0.0+instance (Eq1 f, Eq1 g) => Eq1 (Compose f g) where+    liftEq eq (Compose x) (Compose y) = liftEq (liftEq eq) x y++-- | @since 4.9.0.0+instance (Ord1 f, Ord1 g) => Ord1 (Compose f g) where+    liftCompare comp (Compose x) (Compose y) =+        liftCompare (liftCompare comp) x y++-- | @since 4.9.0.0+instance (Read1 f, Read1 g) => Read1 (Compose f g) where+    liftReadPrec rp rl =+        liftReadPrecCompose (liftReadPrec rp' rl')+      where+        rp' = liftReadPrec     rp rl+        rl' = liftReadListPrec rp rl++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.9.0.0+instance (Show1 f, Show1 g) => Show1 (Compose f g) where+    liftShowsPrec sp sl =+        liftShowsPrecCompose (liftShowsPrec sp' sl')+      where+        sp' = liftShowsPrec sp sl+        sl' = liftShowList sp sl++-- The workhorse for Compose's Read and Read1 instances.+liftReadPrecCompose :: ReadPrec (f (g a)) -> ReadPrec (Compose f g a)+liftReadPrecCompose rp = readData $ readUnaryWith rp "Compose" Compose++-- The workhorse for Compose's Show and Show1 instances.+liftShowsPrecCompose :: (Int -> f (g a) -> ShowS) -> Int -> Compose f g a -> ShowS+liftShowsPrecCompose sp d (Compose x) = showsUnaryWith sp "Compose" d x++-- Functor instances++-- | @since 4.9.0.0+instance (Functor f, Functor g) => Functor (Compose f g) where+    fmap f (Compose x) = Compose (fmap (fmap f) x)+    a <$ (Compose x) = Compose (fmap (a <$) x)++-- | @since 4.9.0.0+instance (Foldable f, Foldable g) => Foldable (Compose f g) where+    fold (Compose t) = foldMap fold t+    foldMap f (Compose t) = foldMap (foldMap f) t+    foldMap' f (Compose t) = foldMap' (foldMap' f) t+    foldr f b (Compose fga) = foldr (\ga acc -> foldr f acc ga) b fga+    foldr' f b (Compose fga) = foldr' (\ga acc -> foldr' f acc ga) b fga+    foldl f b (Compose fga) = foldl (\acc ga -> foldl f acc ga) b fga+    foldl' f b (Compose fga) = foldl' (\acc ga -> foldl' f acc ga) b fga++    null (Compose t) = null t || getAll (foldMap (All . null) t)+    length (Compose t) = getSum (foldMap' (Sum . length) t)+    elem x (Compose t) = getAny (foldMap (Any . elem x) t)++    minimum (Compose fga) = minimum $ map minimum $ filter (not . null) $ toList fga+    maximum (Compose fga) = maximum $ map maximum $ filter (not . null) $ toList fga++    sum (Compose t) = getSum (foldMap' (Sum . sum) t)+    product (Compose t) = getProduct (foldMap' (Product . product) t)++-- | @since 4.9.0.0+instance (Traversable f, Traversable g) => Traversable (Compose f g) where+    traverse f (Compose t) = Compose <$> traverse (traverse f) t++-- | @since 4.9.0.0+instance (Applicative f, Applicative g) => Applicative (Compose f g) where+    pure x = Compose (pure (pure x))+    Compose f <*> Compose x = Compose (liftA2 (<*>) f x)+    liftA2 f (Compose x) (Compose y) =+      Compose (liftA2 (liftA2 f) x y)++-- | @since 4.9.0.0+instance (Alternative f, Applicative g) => Alternative (Compose f g) where+    empty = Compose empty+    (<|>) = coerce ((<|>) :: f (g a) -> f (g a) -> f (g a))+      :: forall a . Compose f g a -> Compose f g a -> Compose f g a+    some = coerce (fmap sequenceA . some :: f (g a) -> f (g [a]))+      :: forall a . Compose f g a -> Compose f g [a]+    many = coerce (fmap sequenceA . many :: f (g a) -> f (g [a]))+      :: forall a . Compose f g a -> Compose f g [a]++-- | The deduction (via generativity) that if @g x :~: g y@ then @x :~: y@.+--+-- @since 4.14.0.0+instance (TestEquality f) => TestEquality (Compose f g) where+  testEquality (Compose x) (Compose y) =+    case testEquality x y of -- :: Maybe (g x :~: g y)+      Just Refl -> Just Refl -- :: Maybe (x :~: y)+      Nothing   -> Nothing++-- | @since 4.19.0.0+deriving instance Enum (f (g a)) => Enum (Compose f g a)+-- | @since 4.19.0.0+deriving instance Bounded (f (g a)) => Bounded (Compose f g a)+-- | @since 4.19.0.0+deriving instance Num (f (g a)) => Num (Compose f g a)+-- | @since 4.19.0.0+deriving instance Real (f (g a)) => Real (Compose f g a)+-- | @since 4.19.0.0+deriving instance Integral (f (g a)) => Integral (Compose f g a)+-- | @since 4.20.0.0+deriving instance Fractional (f (g a)) => Fractional (Compose f g a)+-- | @since 4.20.0.0+deriving instance RealFrac (f (g a)) => RealFrac (Compose f g a)+-- | @since 4.20.0.0+deriving instance Floating (f (g a)) => Floating (Compose f g a)+-- | @since 4.20.0.0+deriving instance RealFloat (f (g a)) => RealFloat (Compose f g a)
+ src/Data/Functor/Const.hs view
@@ -0,0 +1,17 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Functor.Const+-- Copyright   :  Conor McBride and Ross Paterson 2005+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable++module Data.Functor.Const+    (Const(..)+     ) where++import GHC.Internal.Data.Functor.Const
+ src/Data/Functor/Contravariant.hs view
@@ -0,0 +1,378 @@+{-# LANGUAGE DerivingVia #-}+{-# LANGUAGE EmptyCase #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE InstanceSigs #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE TypeOperators #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Functor.Contravariant+-- Copyright   :  (C) 2007-2015 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- 'Contravariant' functors, sometimes referred to colloquially as @Cofunctor@,+-- even though the dual of a 'Functor' is just a 'Functor'. As with 'Functor'+-- the definition of 'Contravariant' for a given ADT is unambiguous.+--+-- @since 4.12.0.0+----------------------------------------------------------------------------++module Data.Functor.Contravariant (+  -- * Contravariant Functors+    Contravariant(..)+  , phantom++  -- * Operators+  , (>$<), (>$$<), ($<)++  -- * Predicates+  , Predicate(..)++  -- * Comparisons+  , Comparison(..)+  , defaultComparison++  -- * Equivalence Relations+  , Equivalence(..)+  , defaultEquivalence+  , comparisonEquivalence++  -- * Dual arrows+  , Op(..)+  ) where++import Control.Applicative+import GHC.Internal.Control.Category+import GHC.Internal.Data.Function (on)++import Data.Functor.Product+import Data.Functor.Sum+import Data.Functor.Compose++import GHC.Internal.Data.Monoid (Alt(..), All(..))+import GHC.Internal.Data.Proxy+import GHC.Generics++import Prelude hiding ((.), id)++-- | The class of contravariant functors.+--+-- Whereas in Haskell, one can think of a 'Functor' as containing or producing+-- values, a contravariant functor is a functor that can be thought of as+-- /consuming/ values.+--+-- As an example, consider the type of predicate functions  @a -> Bool@. One+-- such predicate might be @negative x = x < 0@, which+-- classifies integers as to whether they are negative. However, given this+-- predicate, we can re-use it in other situations, providing we have a way to+-- map values /to/ integers. For instance, we can use the @negative@ predicate+-- on a person's bank balance to work out if they are currently overdrawn:+--+-- @+-- newtype Predicate a = Predicate { getPredicate :: a -> Bool }+--+-- instance Contravariant Predicate where+--   contramap :: (a' -> a) -> (Predicate a -> Predicate a')+--   contramap f (Predicate p) = Predicate (p . f)+--                                          |   `- First, map the input...+--                                          `----- then apply the predicate.+--+-- overdrawn :: Predicate Person+-- overdrawn = contramap personBankBalance negative+-- @+--+-- Any instance should be subject to the following laws:+--+-- [Identity]    @'contramap' 'id'      = 'id'@+-- [Composition] @'contramap' (g . f) = 'contramap' f . 'contramap' g@+--+-- Note, that the second law follows from the free theorem of the type of+-- 'contramap' and the first law, so you need only check that the former+-- condition holds.++class Contravariant f where+  contramap :: (a' -> a) -> (f a -> f a')++  -- | Replace all locations in the output with the same value.+  -- The default definition is @'contramap' . 'const'@, but this may be+  -- overridden with a more efficient version.+  (>$) :: b -> f b -> f a+  (>$) = contramap . const++-- | If @f@ is both 'Functor' and 'Contravariant' then by the time you factor+-- in the laws of each of those classes, it can't actually use its argument in+-- any meaningful capacity.+--+-- This method is surprisingly useful. Where both instances exist and are+-- lawful we have the following laws:+--+-- @+-- 'fmap'      f ≡ 'phantom'+-- 'contramap' f ≡ 'phantom'+-- @+phantom :: (Functor f, Contravariant f) => f a -> f b+phantom x = () <$ x $< ()++infixl 4 >$, $<, >$<, >$$<++-- | This is '>$' with its arguments flipped.+($<) :: Contravariant f => f b -> b -> f a+($<) = flip (>$)++-- | This is an infix alias for 'contramap'.+(>$<) :: Contravariant f => (a -> b) -> (f b -> f a)+(>$<) = contramap++-- | This is an infix version of 'contramap' with the arguments flipped.+(>$$<) :: Contravariant f => f b -> (a -> b) -> f a+(>$$<) = flip contramap++deriving newtype instance Contravariant f => Contravariant (Alt f)+deriving newtype instance Contravariant f => Contravariant (Rec1 f)+deriving newtype instance Contravariant f => Contravariant (M1 i c f)++instance Contravariant V1 where+  contramap :: (a' -> a) -> (V1 a -> V1 a')+  contramap _ x = case x of++instance Contravariant U1 where+  contramap :: (a' -> a) -> (U1 a -> U1 a')+  contramap _ _ = U1++instance Contravariant (K1 i c) where+  contramap :: (a' -> a) -> (K1 i c a -> K1 i c a')+  contramap _ (K1 c) = K1 c++instance (Contravariant f, Contravariant g) => Contravariant (f :*: g) where+  contramap :: (a' -> a) -> ((f :*: g) a -> (f :*: g) a')+  contramap f (xs :*: ys) = contramap f xs :*: contramap f ys++instance (Functor f, Contravariant g) => Contravariant (f :.: g) where+  contramap :: (a' -> a) -> ((f :.: g) a -> (f :.: g) a')+  contramap f (Comp1 fg) = Comp1 (fmap (contramap f) fg)++instance (Contravariant f, Contravariant g) => Contravariant (f :+: g) where+  contramap :: (a' -> a) -> ((f :+: g) a -> (f :+: g) a')+  contramap f (L1 xs) = L1 (contramap f xs)+  contramap f (R1 ys) = R1 (contramap f ys)++instance (Contravariant f, Contravariant g) => Contravariant (Sum f g) where+  contramap :: (a' -> a) -> (Sum f g a -> Sum f g a')+  contramap f (InL xs) = InL (contramap f xs)+  contramap f (InR ys) = InR (contramap f ys)++instance (Contravariant f, Contravariant g)+      => Contravariant (Product f g) where+  contramap :: (a' -> a) -> (Product f g a -> Product f g a')+  contramap f (Pair a b) = Pair (contramap f a) (contramap f b)++instance Contravariant (Const a) where+  contramap :: (b' -> b) -> (Const a b -> Const a b')+  contramap _ (Const a) = Const a++instance (Functor f, Contravariant g) => Contravariant (Compose f g) where+  contramap :: (a' -> a) -> (Compose f g a -> Compose f g a')+  contramap f (Compose fga) = Compose (fmap (contramap f) fga)++instance Contravariant Proxy where+  contramap :: (a' -> a) -> (Proxy a -> Proxy a')+  contramap _ _ = Proxy++newtype Predicate a = Predicate { getPredicate :: a -> Bool }+  deriving+    ( -- | @('<>')@ on predicates uses logical conjunction @('&&')@ on+      -- the results. Without newtypes this equals @'liftA2' (&&)@.+      --+      -- @+      -- (<>) :: Predicate a -> Predicate a -> Predicate a+      -- Predicate pred <> Predicate pred' = Predicate \a ->+      --   pred a && pred' a+      -- @+      Semigroup+    , -- | @'mempty'@ on predicates always returns @True@. Without+      -- newtypes this equals @'pure' True@.+      --+      -- @+      -- mempty :: Predicate a+      -- mempty = \_ -> True+      -- @+      Monoid+    )+  via a -> All++  deriving+    ( -- | A 'Predicate' is a 'Contravariant' 'Functor', because+      -- 'contramap' can apply its function argument to the input of+      -- the predicate.+      --+      -- Without newtypes @'contramap' f@ equals precomposing with @f@+      -- (= @(. f)@).+      --+      -- @+      -- contramap :: (a' -> a) -> (Predicate a -> Predicate a')+      -- contramap f (Predicate g) = Predicate (g . f)+      -- @+      Contravariant+    )+  via Op Bool++-- | Defines a total ordering on a type as per 'compare'.+--+-- This condition is not checked by the types. You must ensure that the+-- supplied values are valid total orderings yourself.+newtype Comparison a = Comparison { getComparison :: a -> a -> Ordering }+  deriving+  newtype+    ( -- | @('<>')@ on comparisons combines results with @('<>')+      -- \@Ordering@. Without newtypes this equals @'liftA2' ('liftA2'+      -- ('<>'))@.+      --+      -- @+      -- (<>) :: Comparison a -> Comparison a -> Comparison a+      -- Comparison cmp <> Comparison cmp' = Comparison \a a' ->+      --   cmp a a' <> cmp a a'+      -- @+      Semigroup+    , -- | @'mempty'@ on comparisons always returns @EQ@. Without+      -- newtypes this equals @'pure' ('pure' EQ)@.+      --+      -- @+      -- mempty :: Comparison a+      -- mempty = Comparison \_ _ -> EQ+      -- @+      Monoid+    )++-- | A 'Comparison' is a 'Contravariant' 'Functor', because 'contramap' can+-- apply its function argument to each input of the comparison function.+instance Contravariant Comparison where+  contramap :: (a' -> a) -> (Comparison a -> Comparison a')+  contramap f (Comparison g) = Comparison (on g f)++-- | Compare using 'compare'.+defaultComparison :: Ord a => Comparison a+defaultComparison = Comparison compare++-- | This data type represents an equivalence relation.+--+-- Equivalence relations are expected to satisfy three laws:+--+-- [Reflexivity]:  @'getEquivalence' f a a = True@+-- [Symmetry]:     @'getEquivalence' f a b = 'getEquivalence' f b a@+-- [Transitivity]:+--    If @'getEquivalence' f a b@ and @'getEquivalence' f b c@ are both 'True'+--    then so is @'getEquivalence' f a c@.+--+-- The types alone do not enforce these laws, so you'll have to check them+-- yourself.+newtype Equivalence a = Equivalence { getEquivalence :: a -> a -> Bool }+  deriving+    ( -- | @('<>')@ on equivalences uses logical conjunction @('&&')@+      -- on the results. Without newtypes this equals @'liftA2'+      -- ('liftA2' (&&))@.+      --+      -- @+      -- (<>) :: Equivalence a -> Equivalence a -> Equivalence a+      -- Equivalence equiv <> Equivalence equiv' = Equivalence \a b ->+      --   equiv a b && equiv' a b+      -- @+      Semigroup+    , -- | @'mempty'@ on equivalences always returns @True@. Without+      -- newtypes this equals @'pure' ('pure' True)@.+      --+      -- @+      -- mempty :: Equivalence a+      -- mempty = Equivalence \_ _ -> True+      -- @+      Monoid+    )+  via a -> a -> All++-- | Equivalence relations are 'Contravariant', because you can+-- apply the contramapped function to each input to the equivalence+-- relation.+instance Contravariant Equivalence where+  contramap :: (a' -> a) -> (Equivalence a -> Equivalence a')+  contramap f (Equivalence g) = Equivalence (on g f)++-- | Check for equivalence with '=='.+--+-- Note: The instances for 'Double' and 'Float' violate reflexivity for @NaN@.+defaultEquivalence :: Eq a => Equivalence a+defaultEquivalence = Equivalence (==)++comparisonEquivalence :: Comparison a -> Equivalence a+comparisonEquivalence (Comparison p) = Equivalence $ \a b -> p a b == EQ++-- | Dual function arrows.+newtype Op a b = Op { getOp :: b -> a }+  deriving+  newtype+    ( -- | @('<>') \@(Op a b)@ without newtypes is @('<>') \@(b->a)@ =+      -- @liftA2 ('<>')@. This lifts the 'Semigroup' operation+      -- @('<>')@ over the output of @a@.+      --+      -- @+      -- (<>) :: Op a b -> Op a b -> Op a b+      -- Op f <> Op g = Op \a -> f a <> g a+      -- @+      Semigroup+    , -- | @'mempty' \@(Op a b)@ without newtypes is @mempty \@(b->a)@+      -- = @\_ -> mempty@.+      --+      -- @+      -- mempty :: Op a b+      -- mempty = Op \_ -> mempty+      -- @+      Monoid+    )++instance Category Op where+  id :: Op a a+  id = Op id++  (.) :: Op b c -> Op a b -> Op a c+  Op f . Op g = Op (g . f)++instance Contravariant (Op a) where+  contramap :: (b' -> b) -> (Op a b -> Op a b')+  contramap f g = Op (getOp g . f)++instance Num a => Num (Op a b) where+  Op f + Op g = Op $ \a -> f a + g a+  Op f * Op g = Op $ \a -> f a * g a+  Op f - Op g = Op $ \a -> f a - g a+  abs (Op f) = Op $ abs . f+  signum (Op f) = Op $ signum . f+  fromInteger = Op . const . fromInteger++instance Fractional a => Fractional (Op a b) where+  Op f / Op g = Op $ \a -> f a / g a+  recip (Op f) = Op $ recip . f+  fromRational = Op . const . fromRational++instance Floating a => Floating (Op a b) where+  pi = Op $ const pi+  exp (Op f) = Op $ exp . f+  sqrt (Op f) = Op $ sqrt . f+  log (Op f) = Op $ log . f+  sin (Op f) = Op $ sin . f+  tan (Op f) = Op $ tan . f+  cos (Op f) = Op $ cos . f+  asin (Op f) = Op $ asin . f+  atan (Op f) = Op $ atan . f+  acos (Op f) = Op $ acos . f+  sinh (Op f) = Op $ sinh . f+  tanh (Op f) = Op $ tanh . f+  cosh (Op f) = Op $ cosh . f+  asinh (Op f) = Op $ asinh . f+  atanh (Op f) = Op $ atanh . f+  acosh (Op f) = Op $ acosh . f+  Op f ** Op g = Op $ \a -> f a ** g a+  logBase (Op f) (Op g) = Op $ \a -> logBase (f a) (g a)
+ src/Data/Functor/Identity.hs view
@@ -0,0 +1,32 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Functor.Identity+-- Copyright   :  (c) Andy Gill 2001,+--                (c) Oregon Graduate Institute of Science and Technology 2001+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  ross@soi.city.ac.uk+-- Stability   :  stable+-- Portability :  portable+--+-- The identity functor and monad.+--+-- This trivial type constructor serves two purposes:+--+-- * It can be used with functions parameterized by functor or monad classes.+--+-- * It can be used as a base monad to which a series of monad+--   transformers may be applied to construct a composite monad.+--   Most monad transformer modules include the special case of+--   applying the transformer to 'Identity'.  For example, @State s@+--   is an abbreviation for @StateT s 'Identity'@.+--+-- @since 4.8.0.0++module Data.Functor.Identity+    (Identity(..)+     ) where++import GHC.Internal.Data.Functor.Identity
+ src/Data/Functor/Product.hs view
@@ -0,0 +1,136 @@+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE Safe #-}+{-# LANGUAGE StandaloneDeriving #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Functor.Product+-- Copyright   :  (c) Ross Paterson 2010+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Products, lifted to functors.+--+-- @since 4.9.0.0+-----------------------------------------------------------------------------++module Data.Functor.Product (+    Product(..),+  ) where++import Control.Applicative+import GHC.Internal.Control.Monad (MonadPlus(..))+import GHC.Internal.Control.Monad.Fix (MonadFix(..))+import Control.Monad.Zip (MonadZip(mzipWith))+import GHC.Internal.Data.Data (Data)+import Data.Functor.Classes+import GHC.Generics (Generic, Generic1)+import Prelude++-- $setup+-- >>> import Prelude++-- | Lifted product of functors.+--+-- ==== __Examples__+--+-- >>> fmap (+1) (Pair [1, 2, 3] (Just 0))+-- Pair [2,3,4] (Just 1)+--+-- >>> Pair "Hello, " (Left 'x') <> Pair "World" (Right 'y')+-- Pair "Hello, World" (Right 'y')+data Product f g a = Pair (f a) (g a)+  deriving ( Data     -- ^ @since 4.9.0.0+           , Generic  -- ^ @since 4.9.0.0+           , Generic1 -- ^ @since 4.9.0.0+           )++-- | @since 4.18.0.0+deriving instance (Eq (f a), Eq (g a)) => Eq (Product f g a)+-- | @since 4.18.0.0+deriving instance (Ord (f a), Ord (g a)) => Ord (Product f g a)+-- | @since 4.18.0.0+deriving instance (Read (f a), Read (g a)) => Read (Product f g a)+-- | @since 4.18.0.0+deriving instance (Show (f a), Show (g a)) => Show (Product f g a)++-- | @since 4.9.0.0+instance (Eq1 f, Eq1 g) => Eq1 (Product f g) where+    liftEq eq (Pair x1 y1) (Pair x2 y2) = liftEq eq x1 x2 && liftEq eq y1 y2++-- | @since 4.9.0.0+instance (Ord1 f, Ord1 g) => Ord1 (Product f g) where+    liftCompare comp (Pair x1 y1) (Pair x2 y2) =+        liftCompare comp x1 x2 `mappend` liftCompare comp y1 y2++-- | @since 4.9.0.0+instance (Read1 f, Read1 g) => Read1 (Product f g) where+    liftReadPrec rp rl = readData $+        readBinaryWith (liftReadPrec rp rl) (liftReadPrec rp rl) "Pair" Pair++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.9.0.0+instance (Show1 f, Show1 g) => Show1 (Product f g) where+    liftShowsPrec sp sl d (Pair x y) =+        showsBinaryWith (liftShowsPrec sp sl) (liftShowsPrec sp sl) "Pair" d x y++-- | @since 4.9.0.0+instance (Functor f, Functor g) => Functor (Product f g) where+    fmap f (Pair x y) = Pair (fmap f x) (fmap f y)+    a <$ (Pair x y) = Pair (a <$ x) (a <$ y)++-- | @since 4.9.0.0+instance (Foldable f, Foldable g) => Foldable (Product f g) where+    foldMap f (Pair x y) = foldMap f x `mappend` foldMap f y++-- | @since 4.9.0.0+instance (Traversable f, Traversable g) => Traversable (Product f g) where+    traverse f (Pair x y) = liftA2 Pair (traverse f x) (traverse f y)++-- | @since 4.9.0.0+instance (Applicative f, Applicative g) => Applicative (Product f g) where+    pure x = Pair (pure x) (pure x)+    Pair f g <*> Pair x y = Pair (f <*> x) (g <*> y)+    liftA2 f (Pair a b) (Pair x y) = Pair (liftA2 f a x) (liftA2 f b y)++-- | @since 4.9.0.0+instance (Alternative f, Alternative g) => Alternative (Product f g) where+    empty = Pair empty empty+    Pair x1 y1 <|> Pair x2 y2 = Pair (x1 <|> x2) (y1 <|> y2)++-- | @since 4.9.0.0+instance (Monad f, Monad g) => Monad (Product f g) where+    Pair m n >>= f = Pair (m >>= fstP . f) (n >>= sndP . f)+      where+        fstP (Pair a _) = a+        sndP (Pair _ b) = b++-- | @since 4.9.0.0+instance (MonadPlus f, MonadPlus g) => MonadPlus (Product f g) where+    mzero = Pair mzero mzero+    Pair x1 y1 `mplus` Pair x2 y2 = Pair (x1 `mplus` x2) (y1 `mplus` y2)++-- | @since 4.9.0.0+instance (MonadFix f, MonadFix g) => MonadFix (Product f g) where+    mfix f = Pair (mfix (fstP . f)) (mfix (sndP . f))+      where+        fstP (Pair a _) = a+        sndP (Pair _ b) = b++-- | @since 4.9.0.0+instance (MonadZip f, MonadZip g) => MonadZip (Product f g) where+    mzipWith f (Pair x1 y1) (Pair x2 y2) = Pair (mzipWith f x1 x2) (mzipWith f y1 y2)++-- | @since 4.16.0.0+instance (Semigroup (f a), Semigroup (g a)) => Semigroup (Product f g a) where+    Pair x1 y1 <> Pair x2 y2 = Pair (x1 <> x2) (y1 <> y2)++-- | @since 4.16.0.0+instance (Monoid (f a), Monoid (g a)) => Monoid (Product f g a) where+    mempty = Pair mempty mempty
+ src/Data/Functor/Sum.hs view
@@ -0,0 +1,104 @@+{-# LANGUAGE DeriveDataTypeable #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE Safe #-}+{-# LANGUAGE StandaloneDeriving #-}+-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Functor.Sum+-- Copyright   :  (c) Ross Paterson 2014+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Sums, lifted to functors.+--+-- @since 4.9.0.0+-----------------------------------------------------------------------------++module Data.Functor.Sum (+    Sum(..),+  ) where++import Control.Applicative ((<|>))+import GHC.Internal.Data.Data (Data)+import Data.Functor.Classes+import GHC.Generics (Generic, Generic1)+import Prelude++-- $setup+-- >>> import Prelude++-- | Lifted sum of functors.+--+-- ==== __Examples__+--+-- >>> fmap (+1) (InL (Just 1))  :: Sum Maybe [] Int+-- InL (Just 2)+--+-- >>> fmap (+1) (InR [1, 2, 3]) :: Sum Maybe [] Int+-- InR [2,3,4]+data Sum f g a = InL (f a) | InR (g a)+  deriving ( Data     -- ^ @since 4.9.0.0+           , Generic  -- ^ @since 4.9.0.0+           , Generic1 -- ^ @since 4.9.0.0+           )++-- | @since 4.18.0.0+deriving instance (Eq (f a), Eq (g a)) => Eq (Sum f g a)+-- | @since 4.18.0.0+deriving instance (Ord (f a), Ord (g a)) => Ord (Sum f g a)+-- | @since 4.18.0.0+deriving instance (Read (f a), Read (g a)) => Read (Sum f g a)+-- | @since 4.18.0.0+deriving instance (Show (f a), Show (g a)) => Show (Sum f g a)++-- | @since 4.9.0.0+instance (Eq1 f, Eq1 g) => Eq1 (Sum f g) where+    liftEq eq (InL x1) (InL x2) = liftEq eq x1 x2+    liftEq _ (InL _) (InR _) = False+    liftEq _ (InR _) (InL _) = False+    liftEq eq (InR y1) (InR y2) = liftEq eq y1 y2++-- | @since 4.9.0.0+instance (Ord1 f, Ord1 g) => Ord1 (Sum f g) where+    liftCompare comp (InL x1) (InL x2) = liftCompare comp x1 x2+    liftCompare _ (InL _) (InR _) = LT+    liftCompare _ (InR _) (InL _) = GT+    liftCompare comp (InR y1) (InR y2) = liftCompare comp y1 y2++-- | @since 4.9.0.0+instance (Read1 f, Read1 g) => Read1 (Sum f g) where+    liftReadPrec rp rl = readData $+        readUnaryWith (liftReadPrec rp rl) "InL" InL <|>+        readUnaryWith (liftReadPrec rp rl) "InR" InR++    liftReadListPrec = liftReadListPrecDefault+    liftReadList     = liftReadListDefault++-- | @since 4.9.0.0+instance (Show1 f, Show1 g) => Show1 (Sum f g) where+    liftShowsPrec sp sl d (InL x) =+        showsUnaryWith (liftShowsPrec sp sl) "InL" d x+    liftShowsPrec sp sl d (InR y) =+        showsUnaryWith (liftShowsPrec sp sl) "InR" d y++-- | @since 4.9.0.0+instance (Functor f, Functor g) => Functor (Sum f g) where+    fmap f (InL x) = InL (fmap f x)+    fmap f (InR y) = InR (fmap f y)++    a <$ (InL x) = InL (a <$ x)+    a <$ (InR y) = InR (a <$ y)++-- | @since 4.9.0.0+instance (Foldable f, Foldable g) => Foldable (Sum f g) where+    foldMap f (InL x) = foldMap f x+    foldMap f (InR y) = foldMap f y++-- | @since 4.9.0.0+instance (Traversable f, Traversable g) => Traversable (Sum f g) where+    traverse f (InL x) = InL <$> traverse f x+    traverse f (InR y) = InR <$> traverse f y
+ src/Data/IORef.hs view
@@ -0,0 +1,84 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.IORef+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Mutable references in the IO monad.+--++module Data.IORef+    (-- *  IORefs+     IORef,+     newIORef,+     readIORef,+     writeIORef,+     modifyIORef,+     modifyIORef',+     atomicModifyIORef,+     atomicModifyIORef',+     atomicWriteIORef,+     mkWeakIORef,+     -- **  Memory Model+     -- $memmodel+     ) where++import GHC.Internal.Data.IORef++{- $memmodel+  #memmodel#++  Most modern CPU achitectures (e.g. x86/64, ARM) have a memory model which allows+  threads to reorder reads with earlier writes to different locations,+  e.g. see <https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html the x86/64 architecture manual>,+  8.2.3.4 Loads May Be Reordered with Earlier Stores to Different Locations.++  Because of that, in a concurrent program, 'IORef' operations may appear out-of-order+  to another thread. In the following example:++  > import GHC.Internal.Data.IORef+  > import GHC.Internal.Control.Monad (unless)+  > import Control.Concurrent (forkIO, threadDelay)+  >+  > maybePrint :: IORef Bool -> IORef Bool -> IO ()+  > maybePrint myRef yourRef = do+  >   writeIORef myRef True+  >   yourVal <- readIORef yourRef+  >   unless yourVal $ putStrLn "critical section"+  >+  > main :: IO ()+  > main = do+  >   r1 <- newIORef False+  >   r2 <- newIORef False+  >   forkIO $ maybePrint r1 r2+  >   forkIO $ maybePrint r2 r1+  >   threadDelay 1000000++  it is possible that the string @"critical section"@ is printed+  twice, even though there is no interleaving of the operations of the+  two threads that allows that outcome.  The memory model of x86/64+  allows 'readIORef' to happen before the earlier 'writeIORef'.++  The ARM memory order model is typically even weaker than x86/64, allowing+  any reordering of reads and writes as long as they are independent+  from the point of view of the current thread.++  The implementation is required to ensure that reordering of memory+  operations cannot cause type-correct code to go wrong.  In+  particular, when inspecting the value read from an 'IORef', the+  memory writes that created that value must have occurred from the+  point of view of the current thread.++  'atomicWriteIORef', 'atomicModifyIORef' and 'atomicModifyIORef'' act+  as a barrier to reordering. Multiple calls to these functions+  occur in strict program order, never taking place ahead of any+  earlier (in program order) 'IORef' operations, or after any later+  'IORef' operations.++-}
+ src/Data/Int.hs view
@@ -0,0 +1,52 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Int+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Signed integer types+--++module Data.Int+    (-- *  Signed integer types+     Int,+     Int8,+     Int16,+     Int32,+     Int64,+     -- *  Notes+     -- $notes+     ) where++import GHC.Internal.Int++{- $notes++* All arithmetic is performed modulo 2^n, where @n@ is the number of+  bits in the type.++* For coercing between any two integer types, use 'Prelude.fromIntegral',+  which is specialized for all the common cases so should be fast+  enough.  Coercing word types (see "Data.Word") to and from integer+  types preserves representation, not sign.++* The rules that hold for 'Prelude.Enum' instances over a+  bounded type such as 'Int' (see the section of the+  Haskell report dealing with arithmetic sequences) also hold for the+  'Prelude.Enum' instances over the various+  'Int' types defined here.++* Right and left shifts by amounts greater than or equal to the width+  of the type result in either zero or -1, depending on the sign of+  the value being shifted.  This is contrary to the behaviour in C,+  which is undefined; a common interpretation is to truncate the shift+  count to the width of the type, for example @1 \<\< 32+  == 1@ in some C implementations.+-}+
+ src/Data/Ix.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Ix+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The 'Ix' class is used to map a contiguous subrange of values in+-- type onto integers.  It is used primarily for array indexing+-- (see the array package).  'Ix' uses row-major order.+--++module Data.Ix+    (-- *  The 'Ix' class+     Ix(range, index, inRange, rangeSize),+     -- *  Deriving Instances of 'Ix'+     -- |  Derived instance declarations for the class 'Ix' are only possible+     -- for enumerations (i.e. datatypes having only nullary constructors)+     -- and single-constructor datatypes, including arbitrarily large tuples,+     -- whose constituent types are instances of 'Ix'.+     --+     -- * For an enumeration, the nullary constructors are assumed to be+     -- numbered left-to-right with the indices being 0 to n-1 inclusive. This+     -- is the same numbering defined by the 'Enum' class. For example, given+     -- the datatype:+     --+     -- >        data Colour = Red | Orange | Yellow | Green | Blue | Indigo | Violet+     --+     -- we would have:+     --+     -- >        range   (Yellow,Blue)        ==  [Yellow,Green,Blue]+     -- >        index   (Yellow,Blue) Green  ==  1+     -- >        inRange (Yellow,Blue) Red    ==  False+     --+     -- * For single-constructor datatypes, the derived instance declarations+     -- are as shown for tuples in chapter 19, section 2 of the Haskell 2010 report:+     -- <https://www.haskell.org/onlinereport/haskell2010/haskellch19.html>.+     ) where++import GHC.Internal.Data.Ix
+ src/Data/Kind.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE Trustworthy #-}++-- |+--+-- Module      :  Data.Kind+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  not portable+--+-- Basic kinds+--+-- @since 4.9.0.0++module Data.Kind+    (Type,+     Constraint,+     FUN+     ) where++import GHC.Prim (FUN)+import GHC.Types (Type, Constraint)
+ src/Data/List.hs view
@@ -0,0 +1,284 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.List+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Operations on lists.+--++module Data.List+    (List,+     -- *  Basic functions+     (++),+     head,+     last,+     tail,+     init,+     uncons,+     unsnoc,+     singleton,+     null,+     length,+     compareLength,+     -- *  List transformations+     map,+     reverse,+     intersperse,+     intercalate,+     transpose,+     subsequences,+     permutations,+     -- *  Reducing lists (folds)+     foldl,+     foldl',+     foldl1,+     foldl1',+     foldr,+     foldr1,+     -- **  Special folds+     concat,+     concatMap,+     and,+     or,+     any,+     all,+     sum,+     product,+     maximum,+     minimum,+     -- *  Building lists+     -- **  Scans+     scanl,+     scanl',+     scanl1,+     scanr,+     scanr1,+     -- **  Accumulating maps+     mapAccumL,+     mapAccumR,+     -- **  Infinite lists+     iterate,+     iterate',+     repeat,+     replicate,+     cycle,+     -- **  Unfolding+     unfoldr,+     -- *  Sublists+     -- **  Extracting sublists+     take,+     drop,+     splitAt,+     takeWhile,+     dropWhile,+     dropWhileEnd,+     span,+     break,+     stripPrefix,+     group,+     inits,+     inits1,+     tails,+     tails1,+     -- **  Predicates+     isPrefixOf,+     isSuffixOf,+     isInfixOf,+     isSubsequenceOf,+     -- *  Searching lists+     -- **  Searching by equality+     elem,+     notElem,+     lookup,+     -- **  Searching with a predicate+     find,+     filter,+     partition,+     -- *  Indexing lists+     -- |  These functions treat a list @xs@ as an indexed collection,+     -- with indices ranging from 0 to @'length' xs - 1@.+     (!?),+     (!!),+     elemIndex,+     elemIndices,+     findIndex,+     findIndices,+     -- *  Zipping and unzipping lists+     zip,+     zip3,+     zip4,+     zip5,+     zip6,+     zip7,+     zipWith,+     zipWith3,+     zipWith4,+     zipWith5,+     zipWith6,+     zipWith7,+     unzip,+     unzip3,+     unzip4,+     unzip5,+     unzip6,+     unzip7,+     -- *  Special lists+     -- **  Functions on strings+     lines,+     words,+     unlines,+     unwords,+     -- **  \"Set\" operations+     nub,+     delete,+     (\\),+     union,+     intersect,+     -- **  Ordered lists+     sort,+     sortOn,+     insert,+     -- *  Generalized functions+     -- **  The \"@By@\" operations+     -- |  By convention, overloaded functions have a non-overloaded+     -- counterpart whose name is suffixed with \`@By@\'.+     --+     -- It is often convenient to use these functions together with+     -- 'Data.Function.on', for instance @'sortBy' ('Prelude.compare'+     -- ``Data.Function.on`` 'Prelude.fst')@.++     -- ***  User-supplied equality (replacing an @Eq@ context)+     -- |  The predicate is assumed to define an equivalence.+     nubBy,+     deleteBy,+     deleteFirstsBy,+     unionBy,+     intersectBy,+     groupBy,+     -- ***  User-supplied comparison (replacing an @Ord@ context)+     -- |  The function is assumed to define a total ordering.+     sortBy,+     insertBy,+     maximumBy,+     minimumBy,+     -- **  The \"@generic@\" operations+     -- |  The prefix \`@generic@\' indicates an overloaded function that+     -- is a generalized version of a "Prelude" function.+     genericLength,+     genericTake,+     genericDrop,+     genericSplitAt,+     genericIndex,+     genericReplicate+     ) where++import GHC.Internal.Data.Bool (otherwise)+import GHC.Internal.Data.List+import GHC.Internal.Data.List.NonEmpty (NonEmpty(..))+import GHC.Internal.Data.Ord (Ordering(..), (<), (>))+import GHC.Internal.Int (Int)+import GHC.Internal.Num ((-))+import GHC.List (build)++inits1, tails1 :: [a] -> [NonEmpty a]++-- | The 'inits1' function returns all non-empty initial segments of the+-- argument, shortest first.+--+-- @since 4.21.0.0+--+-- ==== __Laziness__+--+-- Note that 'inits1' has the following strictness property:+-- @inits1 (xs ++ _|_) = inits1 xs ++ _|_@+--+-- In particular,+-- @inits1 _|_ = _|_@+--+-- ==== __Examples__+--+-- >>> inits1 "abc"+-- ['a' :| "",'a' :| "b",'a' :| "bc"]+--+-- >>> inits1 []+-- []+--+-- inits1 is productive on infinite lists:+--+-- >>> take 3 $ inits1 [1..]+-- [1 :| [],1 :| [2],1 :| [2,3]]+inits1 [] = []+inits1 (x : xs) = map (x :|) (inits xs)++-- | \(\mathcal{O}(n)\). The 'tails1' function returns all non-empty final+-- segments of the argument, longest first.+--+-- @since 4.21.0.0+--+-- ==== __Laziness__+--+-- Note that 'tails1' has the following strictness property:+-- @tails1 _|_ = _|_@+--+-- >>> tails1 undefined+-- *** Exception: Prelude.undefined+--+-- >>> drop 1 (tails1 [undefined, 1, 2])+-- [1 :| [2],2 :| []]+--+-- ==== __Examples__+--+-- >>> tails1 "abc"+-- ['a' :| "bc",'b' :| "c",'c' :| ""]+--+-- >>> tails1 [1, 2, 3]+-- [1 :| [2,3],2 :| [3],3 :| []]+--+-- >>> tails1 []+-- []+{-# INLINABLE tails1 #-}+tails1 lst = build (\c n ->+  let tails1Go [] = n+      tails1Go (x : xs) = (x :| xs) `c` tails1Go xs+  in tails1Go lst)++-- | Use 'compareLength' @xs@ @n@ as a safer and faster alternative+-- to 'compare' ('length' @xs@) @n@. Similarly, it's better+-- to write @compareLength xs 10 == LT@ instead of @length xs < 10@.+--+-- While 'length' would force and traverse+-- the entire spine of @xs@ (which could even diverge if @xs@ is infinite),+-- 'compareLength' traverses at most @n@ elements to determine its result.+--+-- >>> compareLength [] 0+-- EQ+-- >>> compareLength [] 1+-- LT+-- >>> compareLength ['a'] 1+-- EQ+-- >>> compareLength ['a', 'b'] 1+-- GT+-- >>> compareLength [0..] 100+-- GT+-- >>> compareLength undefined (-1)+-- GT+-- >>> compareLength ('a' : undefined) 0+-- GT+--+-- @since 4.21.0.0+--+compareLength :: [a] -> Int -> Ordering+compareLength xs n+  | n < 0 = GT+  | otherwise = foldr+    (\_ f m -> if m > 0 then f (m - 1) else GT)+    (\m -> if m > 0 then LT else EQ)+    xs+    n
+ src/Data/List/NonEmpty.hs view
@@ -0,0 +1,616 @@+{-# LANGUAGE Trustworthy #-} -- can't use Safe due to IsList instance+{-# LANGUAGE TypeFamilies #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.List.NonEmpty+-- Copyright   :  (C) 2011-2015 Edward Kmett,+--                (C) 2010 Tony Morris, Oliver Taylor, Eelis van der Weegen+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- A 'NonEmpty' list is one which always has at least one element, but+-- is otherwise identical to the traditional list type in complexity+-- and in terms of API. You will almost certainly want to import this+-- module @qualified@.+--+-- @since 4.9.0.0+----------------------------------------------------------------------------++-- Function implementations in this module adhere to the following principle:+--+-- For every NonEmpty function that is different from a corresponding+-- List function only in the presence of NonEmpty in its type, both+-- the List and NonEmpty functions should have the same strictness+-- properties. Same applies to the class instances.++module Data.List.NonEmpty (+   -- * The type of non-empty streams+     NonEmpty(..)++   -- * Non-empty stream transformations+   , map         -- :: (a -> b) -> NonEmpty a -> NonEmpty b+   , intersperse -- :: a -> NonEmpty a -> NonEmpty a+   , scanl       -- :: Foldable f => (b -> a -> b) -> b -> f a -> NonEmpty b+   , scanr       -- :: Foldable f => (a -> b -> b) -> b -> f a -> NonEmpty b+   , scanl1      -- :: (a -> a -> a) -> NonEmpty a -> NonEmpty a+   , scanr1      -- :: (a -> a -> a) -> NonEmpty a -> NonEmpty a+   , transpose   -- :: NonEmpty (NonEmpty a) -> NonEmpty (NonEmpty a)+   , sortBy      -- :: (a -> a -> Ordering) -> NonEmpty a -> NonEmpty a+   , sortWith      -- :: Ord o => (a -> o) -> NonEmpty a -> NonEmpty a+   -- * Basic functions+   , length      -- :: NonEmpty a -> Int+   , compareLength -- :: NonEmpty a -> Int -> Ordering+   , head        -- :: NonEmpty a -> a+   , tail        -- :: NonEmpty a -> [a]+   , last        -- :: NonEmpty a -> a+   , init        -- :: NonEmpty a -> [a]+   , singleton   -- :: a -> NonEmpty a+   , (<|), cons  -- :: a -> NonEmpty a -> NonEmpty a+   , uncons      -- :: NonEmpty a -> (a, Maybe (NonEmpty a))+   , unfoldr     -- :: (a -> (b, Maybe a)) -> a -> NonEmpty b+   , sort        -- :: Ord a => NonEmpty a -> NonEmpty a+   , sortOn      -- :: Ord b => (a -> b) -> NonEmpty a -> NonEmpty a+   , reverse     -- :: NonEmpty a -> NonEmpty a+   , inits       -- :: Foldable f => f a -> NonEmpty [a]+   , inits1      -- :: NonEmpty a -> NonEmpty (NonEmpty a)+   , tails       -- :: Foldable f => f a -> NonEmpty [a]+   , tails1      -- :: NonEmpty a -> NonEmpty (NonEmpty a)+   , append      -- :: NonEmpty a -> NonEmpty a -> NonEmpty a+   , appendList  -- :: NonEmpty a -> [a] -> NonEmpty a+   , prependList -- :: [a] -> NonEmpty a -> NonEmpty a+   -- * Building streams+   , iterate     -- :: (a -> a) -> a -> NonEmpty a+   , repeat      -- :: a -> NonEmpty a+   , cycle       -- :: NonEmpty a -> NonEmpty a+   , unfold      -- :: (a -> (b, Maybe a)) -> a -> NonEmpty b+   , insert      -- :: (Foldable f, Ord a) => a -> f a -> NonEmpty a+   , some1       -- :: Alternative f => f a -> f (NonEmpty a)+   -- * Extracting sublists+   , take        -- :: Int -> NonEmpty a -> [a]+   , drop        -- :: Int -> NonEmpty a -> [a]+   , splitAt     -- :: Int -> NonEmpty a -> ([a], [a])+   , takeWhile   -- :: (a -> Bool) -> NonEmpty a -> [a]+   , dropWhile   -- :: (a -> Bool) -> NonEmpty a -> [a]+   , span        -- :: (a -> Bool) -> NonEmpty a -> ([a], [a])+   , break       -- :: (a -> Bool) -> NonEmpty a -> ([a], [a])+   , filter      -- :: (a -> Bool) -> NonEmpty a -> [a]+   , partition   -- :: (a -> Bool) -> NonEmpty a -> ([a],[a])+   , group       -- :: (Foldable f, Eq a) => f a -> [NonEmpty a]+   , groupBy     -- :: Foldable f => (a -> a -> Bool) -> f a -> [NonEmpty a]+   , groupWith     -- :: (Foldable f, Eq b) => (a -> b) -> f a -> [NonEmpty a]+   , groupAllWith  -- :: Ord b => (a -> b) -> [a] -> [NonEmpty a]+   , group1      -- :: Eq a => NonEmpty a -> NonEmpty (NonEmpty a)+   , groupBy1    -- :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty (NonEmpty a)+   , groupWith1     -- :: Eq b => (a -> b) -> NonEmpty a -> NonEmpty (NonEmpty a)+   , groupAllWith1  -- :: Ord b => (a -> b) -> NonEmpty a -> NonEmpty (NonEmpty a)+   , permutations   -- :: [a] -> NonEmpty [a]+   , permutations1  -- :: NonEmpty a -> NonEmpty (NonEmpty a)+   -- * Sublist predicates+   , isPrefixOf  -- :: Eq a => [a] -> NonEmpty a -> Bool+   -- * \"Set\" operations+   , nub         -- :: Eq a => NonEmpty a -> NonEmpty a+   , nubBy       -- :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty a+   -- * Indexing streams+   , (!!)        -- :: NonEmpty a -> Int -> a+   -- * Zipping and unzipping streams+   , zip         -- :: NonEmpty a -> NonEmpty b -> NonEmpty (a,b)+   , zipWith     -- :: (a -> b -> c) -> NonEmpty a -> NonEmpty b -> NonEmpty c+   , unzip       -- :: Functor f => f (a,b) -> (f a, f b)+   -- * Converting to and from a list+   , fromList    -- :: [a] -> NonEmpty a+   , toList      -- :: NonEmpty a -> [a]+   , nonEmpty    -- :: [a] -> Maybe (NonEmpty a)+   , xor         -- :: NonEmpty Bool -> Bool+   ) where+++import           Prelude             hiding (break, cycle, drop, dropWhile,+                                      filter, foldl, foldr, head, init, iterate,+                                      last, length, map, repeat, reverse,+                                      scanl, scanl1, scanr, scanr1, span,+                                      splitAt, tail, take, takeWhile,+                                      unzip, zip, zipWith, (!!), Applicative(..))+import qualified Prelude++import           Control.Applicative (Applicative (..), Alternative (many))+import qualified Data.List                        as List+import           GHC.Internal.Data.Foldable       hiding (length, toList)+import qualified GHC.Internal.Data.Foldable       as Foldable+import           GHC.Internal.Data.Function       (on)+import           GHC.Internal.Data.Ord            (comparing)+import           GHC.Internal.Stack.Types     (HasCallStack)+import           GHC.Internal.Data.List.NonEmpty (NonEmpty (..), map, zip, zipWith)++infixr 5 <|++-- $setup+-- >>> import Prelude+-- >>> import qualified Data.List as List+-- >>> import Data.Ord (comparing)++-- | Number of elements in 'NonEmpty' list.+length :: NonEmpty a -> Int+length (_ :| xs) = 1 + Prelude.length xs++-- | Use 'compareLength' @xs@ @n@ as a safer and faster alternative+-- to 'compare' ('length' @xs@) @n@. Similarly, it's better+-- to write @compareLength xs 10 == LT@ instead of @length xs < 10@.+--+-- While 'length' would force and traverse+-- the entire spine of @xs@ (which could even diverge if @xs@ is infinite),+-- 'compareLength' traverses at most @n@ elements to determine its result.+--+-- >>> compareLength ('a' :| []) 1+-- EQ+-- >>> compareLength ('a' :| ['b']) 3+-- LT+-- >>> compareLength (0 :| [1..]) 100+-- GT+-- >>> compareLength undefined 0+-- GT+-- >>> compareLength ('a' :| 'b' : undefined) 1+-- GT+--+-- @since 4.21.0.0+--+compareLength :: NonEmpty a -> Int -> Ordering+compareLength xs n+  | n < 1 = GT+  | otherwise = foldr+    (\_ f m -> if m > 0 then f (m - 1) else GT)+    (\m -> if m > 0 then LT else EQ)+    xs+    n++-- | Compute n-ary logic exclusive OR operation on 'NonEmpty' list.+xor :: NonEmpty Bool -> Bool+xor (x :| xs)   = foldr xor' x xs+  where xor' True y  = not y+        xor' False y = y++-- | 'unfold' produces a new stream by repeatedly applying the unfolding+-- function to the seed value to produce an element of type @b@ and a new+-- seed value.  When the unfolding function returns 'Nothing' instead of+-- a new seed value, the stream ends.+unfold :: (a -> (b, Maybe a)) -> a -> NonEmpty b+unfold f a = case f a of+  (b, Nothing) -> b :| []+  (b, Just c)  -> b <| unfold f c+{-# DEPRECATED unfold "Use unfoldr" #-}+-- Deprecated in 8.2.1, remove in 8.4++-- | 'nonEmpty' efficiently turns a normal list into a 'NonEmpty' stream,+-- producing 'Nothing' if the input is empty.+nonEmpty :: [a] -> Maybe (NonEmpty a)+nonEmpty []     = Nothing+nonEmpty (a:as) = Just (a :| as)++-- | 'uncons' produces the first element of the stream, and a stream of the+-- remaining elements, if any.+uncons :: NonEmpty a -> (a, Maybe (NonEmpty a))+uncons (a :| as) = (a, nonEmpty as)++-- | The 'unfoldr' function is analogous to "Data.List"'s+-- 'GHC.Internal.Data.List.unfoldr' operation.+unfoldr :: (a -> (b, Maybe a)) -> a -> NonEmpty b+unfoldr f a = case f a of+  (b, mc) -> b :| maybe [] go mc+ where+    go c = case f c of+      (d, me) -> d : maybe [] go me++-- | Extract the first element of the stream.+head :: NonEmpty a -> a+head (a :| _) = a++-- | Extract the possibly-empty tail of the stream.+tail :: NonEmpty a -> [a]+tail (_ :| as) = as++-- | Extract the last element of the stream.+last :: NonEmpty a -> a+last (a :| []) = a+last (_ :| (a : as)) = last (a :| as)++-- | Extract everything except the last element of the stream.+init :: NonEmpty a -> [a]+init (_ :| []) = []+init (a1 :| (a2 : as)) = a1 : init (a2 :| as)++-- | Construct a 'NonEmpty' list from a single element.+--+-- @since 4.15+singleton :: a -> NonEmpty a+singleton a = a :| []++-- | Prepend an element to the stream.+(<|) :: a -> NonEmpty a -> NonEmpty a+a <| bs = a :| toList bs++-- | Synonym for '<|'.+cons :: a -> NonEmpty a -> NonEmpty a+cons = (<|)++-- | Sort a stream.+sort :: Ord a => NonEmpty a -> NonEmpty a+sort = lift List.sort++-- | Sort a 'NonEmpty' on a user-supplied projection of its elements.+-- See 'List.sortOn' for more detailed information.+--+-- ==== __Examples__+--+-- >>> sortOn fst $ (2, "world") :| [(4, "!"), (1, "Hello")]+-- (1,"Hello") :| [(2,"world"),(4,"!")]+--+-- >>> sortOn List.length ("jim" :| ["creed", "pam", "michael", "dwight", "kevin"])+-- "jim" :| ["pam","creed","kevin","dwight","michael"]+--+-- ==== __Performance notes__+--+-- This function minimises the projections performed, by materialising+-- the projections in an intermediate list.+--+-- For trivial projections, you should prefer using 'sortBy' with+-- 'comparing', for example:+--+-- >>> sortBy (comparing fst) $ (3, 1) :| [(2, 2), (1, 3)]+-- (1,3) :| [(2,2),(3,1)]+--+-- Or, for the exact same API as 'sortOn', you can use `sortBy . comparing`:+--+-- >>> (sortBy . comparing) fst $ (3, 1) :| [(2, 2), (1, 3)]+-- (1,3) :| [(2,2),(3,1)]+--+-- 'sortWith' is an alias for `sortBy . comparing`.+--+-- @since 4.20.0.0+sortOn :: Ord b => (a -> b) -> NonEmpty a -> NonEmpty a+sortOn f = lift (List.sortOn f)++-- | Converts a normal list to a 'NonEmpty' stream.+--+-- Raises an error if given an empty list.+fromList :: HasCallStack => [a] -> NonEmpty a+fromList (a:as) = a :| as+fromList [] = error "NonEmpty.fromList: empty list"++-- | Convert a stream to a normal list efficiently.+toList :: NonEmpty a -> [a]+toList (a :| as) = a : as++-- | Lift list operations to work on a 'NonEmpty' stream.+--+-- /Beware/: If the provided function returns an empty list,+-- this will raise an error.+lift :: Foldable f => ([a] -> [b]) -> f a -> NonEmpty b+lift f = fromList . f . Foldable.toList++-- | The 'inits' function takes a stream @xs@ and returns all the+-- finite prefixes of @xs@, starting with the shortest. The result is+-- 'NonEmpty' because the result always contains the empty list as the first+-- element.+--+-- > inits [1,2,3] == [] :| [[1], [1,2], [1,2,3]]+-- > inits [1] == [] :| [[1]]+-- > inits [] == [] :| []+inits :: Foldable f => f a -> NonEmpty [a]+inits = fromList . List.inits . Foldable.toList++-- | The 'inits1' function takes a 'NonEmpty' stream @xs@ and returns all the+-- 'NonEmpty' finite prefixes of @xs@, starting with the shortest.+--+-- > inits1 (1 :| [2,3]) == (1 :| []) :| [1 :| [2], 1 :| [2,3]]+-- > inits1 (1 :| []) == (1 :| []) :| []+--+-- @since 4.18+inits1 :: NonEmpty a -> NonEmpty (NonEmpty a)+inits1 = fromList . List.inits1 . Foldable.toList++-- | The 'tails' function takes a stream @xs@ and returns all the+-- suffixes of @xs@, starting with the longest. The result is 'NonEmpty'+-- because the result always contains the empty list as the last element.+--+-- > tails [1,2,3] == [1,2,3] :| [[2,3], [3], []]+-- > tails [1] == [1] :| [[]]+-- > tails [] == [] :| []+tails   :: Foldable f => f a -> NonEmpty [a]+tails = fromList . List.tails . Foldable.toList++-- | The 'tails1' function takes a 'NonEmpty' stream @xs@ and returns all the+-- non-empty suffixes of @xs@, starting with the longest.+--+-- > tails1 (1 :| [2,3]) == (1 :| [2,3]) :| [2 :| [3], 3 :| []]+-- > tails1 (1 :| []) == (1 :| []) :| []+--+-- @since 4.18+tails1 :: NonEmpty a -> NonEmpty (NonEmpty a)+tails1 xs = xs :| List.tails1 (tail xs)++-- | @'insert' x xs@ inserts @x@ into the last position in @xs@ where it+-- is still less than or equal to the next element. In particular, if the+-- list is sorted beforehand, the result will also be sorted.+insert  :: (Foldable f, Ord a) => a -> f a -> NonEmpty a+insert a = fromList . List.insert a . Foldable.toList++-- | @'some1' x@ sequences @x@ one or more times.+some1 :: Alternative f => f a -> f (NonEmpty a)+some1 x = liftA2 (:|) x (many x)++-- | 'scanl' is similar to 'foldl', but returns a stream of successive+-- reduced values from the left:+--+-- > scanl f z [x1, x2, ...] == z :| [z `f` x1, (z `f` x1) `f` x2, ...]+--+-- Note that+--+-- > last (scanl f z xs) == foldl f z xs.+scanl   :: Foldable f => (b -> a -> b) -> b -> f a -> NonEmpty b+scanl f z = fromList . List.scanl f z . Foldable.toList++-- | 'scanr' is the right-to-left dual of 'scanl'.+-- Note that+--+-- > head (scanr f z xs) == foldr f z xs.+scanr   :: Foldable f => (a -> b -> b) -> b -> f a -> NonEmpty b+scanr f z = fromList . List.scanr f z . Foldable.toList++-- | 'scanl1' is a variant of 'scanl' that has no starting value argument:+--+-- > scanl1 f [x1, x2, ...] == x1 :| [x1 `f` x2, x1 `f` (x2 `f` x3), ...]+scanl1 :: (a -> a -> a) -> NonEmpty a -> NonEmpty a+scanl1 f (a :| as) = fromList (List.scanl f a as)++-- | 'scanr1' is a variant of 'scanr' that has no starting value argument.+scanr1 :: (a -> a -> a) -> NonEmpty a -> NonEmpty a+scanr1 f (a :| as) = fromList (List.scanr1 f (a:as))++-- | 'intersperse x xs' alternates elements of the list with copies of @x@.+--+-- > intersperse 0 (1 :| [2,3]) == 1 :| [0,2,0,3]+intersperse :: a -> NonEmpty a -> NonEmpty a+intersperse a (b :| bs) = b :| case bs of+    [] -> []+    _ -> a : List.intersperse a bs++-- | @'iterate' f x@ produces the infinite sequence+-- of repeated applications of @f@ to @x@.+--+-- > iterate f x = x :| [f x, f (f x), ..]+iterate :: (a -> a) -> a -> NonEmpty a+iterate f a = a :| List.iterate f (f a)++-- | @'cycle' xs@ returns the infinite repetition of @xs@:+--+-- > cycle (1 :| [2,3]) = 1 :| [2,3,1,2,3,...]+cycle :: NonEmpty a -> NonEmpty a+cycle = fromList . List.cycle . toList++-- | 'reverse' a finite NonEmpty stream.+reverse :: NonEmpty a -> NonEmpty a+reverse = lift List.reverse++-- | @'repeat' x@ returns a constant stream, where all elements are+-- equal to @x@.+repeat :: a -> NonEmpty a+repeat a = a :| List.repeat a++-- | @'take' n xs@ returns the first @n@ elements of @xs@.+take :: Int -> NonEmpty a -> [a]+take n = List.take n . toList++-- | @'drop' n xs@ drops the first @n@ elements off the front of+-- the sequence @xs@.+drop :: Int -> NonEmpty a -> [a]+drop n = List.drop n . toList++-- | @'splitAt' n xs@ returns a pair consisting of the prefix of @xs@+-- of length @n@ and the remaining stream immediately following this prefix.+--+-- > 'splitAt' n xs == ('take' n xs, 'drop' n xs)+-- > xs == ys ++ zs where (ys, zs) = 'splitAt' n xs+splitAt :: Int -> NonEmpty a -> ([a],[a])+splitAt n = List.splitAt n . toList++-- | @'takeWhile' p xs@ returns the longest prefix of the stream+-- @xs@ for which the predicate @p@ holds.+takeWhile :: (a -> Bool) -> NonEmpty a -> [a]+takeWhile p = List.takeWhile p . toList++-- | @'dropWhile' p xs@ returns the suffix remaining after+-- @'takeWhile' p xs@.+dropWhile :: (a -> Bool) -> NonEmpty a -> [a]+dropWhile p = List.dropWhile p . toList++-- | @'span' p xs@ returns the longest prefix of @xs@ that satisfies+-- @p@, together with the remainder of the stream.+--+-- > 'span' p xs == ('takeWhile' p xs, 'dropWhile' p xs)+-- > xs == ys ++ zs where (ys, zs) = 'span' p xs+span :: (a -> Bool) -> NonEmpty a -> ([a], [a])+span p = List.span p . toList++-- | The @'break' p@ function is equivalent to @'span' (not . p)@.+break :: (a -> Bool) -> NonEmpty a -> ([a], [a])+break p = span (not . p)++-- | @'filter' p xs@ removes any elements from @xs@ that do not satisfy @p@.+filter :: (a -> Bool) -> NonEmpty a -> [a]+filter p = List.filter p . toList++-- | The 'partition' function takes a predicate @p@ and a stream+-- @xs@, and returns a pair of lists. The first list corresponds to the+-- elements of @xs@ for which @p@ holds; the second corresponds to the+-- elements of @xs@ for which @p@ does not hold.+--+-- > 'partition' p xs = ('filter' p xs, 'filter' (not . p) xs)+partition :: (a -> Bool) -> NonEmpty a -> ([a], [a])+partition p = List.partition p . toList++-- | The 'group' function takes a stream and returns a list of+-- streams such that flattening the resulting list is equal to the+-- argument.  Moreover, each stream in the resulting list+-- contains only equal elements, and consecutive equal elements+-- of the input end up in the same stream of the output list.+-- For example, in list notation:+--+-- >>> group "Mississippi"+-- ['M' :| "",'i' :| "",'s' :| "s",'i' :| "",'s' :| "s",'i' :| "",'p' :| "p",'i' :| ""]+group :: (Foldable f, Eq a) => f a -> [NonEmpty a]+group = groupBy (==)++-- | 'groupBy' operates like 'group', but uses the provided equality+-- predicate instead of `==`.+groupBy :: Foldable f => (a -> a -> Bool) -> f a -> [NonEmpty a]+groupBy eq0 = go eq0 . Foldable.toList+  where+    go _  [] = []+    go eq (x : xs) = (x :| ys) : groupBy eq zs+      where (ys, zs) = List.span (eq x) xs++-- | 'groupWith' operates like 'group', but uses the provided projection when+-- comparing for equality+groupWith :: (Foldable f, Eq b) => (a -> b) -> f a -> [NonEmpty a]+groupWith f = groupBy ((==) `on` f)++-- | 'groupAllWith' operates like 'groupWith', but sorts the list+-- first so that each equivalence class has, at most, one list in the+-- output+groupAllWith :: (Ord b) => (a -> b) -> [a] -> [NonEmpty a]+groupAllWith f = groupWith f . List.sortBy (compare `on` f)++-- | 'group1' operates like 'group', but uses the knowledge that its+-- input is non-empty to produce guaranteed non-empty output.+group1 :: Eq a => NonEmpty a -> NonEmpty (NonEmpty a)+group1 = groupBy1 (==)++-- | 'groupBy1' is to 'group1' as 'groupBy' is to 'group'.+groupBy1 :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty (NonEmpty a)+groupBy1 eq (x :| xs) = (x :| ys) :| groupBy eq zs+  where (ys, zs) = List.span (eq x) xs++-- | 'groupWith1' is to 'group1' as 'groupWith' is to 'group'+groupWith1 :: (Eq b) => (a -> b) -> NonEmpty a -> NonEmpty (NonEmpty a)+groupWith1 f = groupBy1 ((==) `on` f)++-- | 'groupAllWith1' is to 'groupWith1' as 'groupAllWith' is to 'groupWith'+groupAllWith1 :: (Ord b) => (a -> b) -> NonEmpty a -> NonEmpty (NonEmpty a)+groupAllWith1 f = groupWith1 f . sortWith f++-- | The 'permutations' function returns the list of all permutations of the argument.+--+-- @since 4.20.0.0+permutations            :: [a] -> NonEmpty [a]+permutations xs0        =  xs0 :| perms xs0 []+  where+    perms []     _  = []+    perms (t:ts) is = foldr interleave (perms ts (t:is)) (permutations is)+      where interleave    xs     r = let (_,zs) = interleave' id xs r in zs+            interleave' _ []     r = (ts, r)+            interleave' f (y:ys) r = let (us,zs) = interleave' (f . (y:)) ys r+                                     in  (y:us, f (t:y:us) : zs)+-- The implementation of 'permutations' is adopted from 'GHC.Internal.Data.List.permutations',+-- see there for discussion and explanations.++-- | 'permutations1' operates like 'permutations', but uses the knowledge that its input is+-- non-empty to produce output where every element is non-empty.+--+-- > permutations1 = fmap fromList . permutations . toList+--+-- @since 4.20.0.0+permutations1 :: NonEmpty a -> NonEmpty (NonEmpty a)+permutations1 xs = fromList <$> permutations (toList xs)++-- | The 'isPrefixOf' function returns 'True' if the first argument is+-- a prefix of the second.+isPrefixOf :: Eq a => [a] -> NonEmpty a -> Bool+isPrefixOf [] _ = True+isPrefixOf (y:ys) (x :| xs) = (y == x) && List.isPrefixOf ys xs++-- | @xs !! n@ returns the element of the stream @xs@ at index+-- @n@. Note that the head of the stream has index 0.+--+-- /Beware/: a negative or out-of-bounds index will cause an error.+(!!) :: HasCallStack => NonEmpty a -> Int -> a+(!!) (x :| xs) n+  | n == 0 = x+  | n > 0  = xs List.!! (n - 1)+  | otherwise = error "NonEmpty.!! negative index"+infixl 9 !!++-- | The 'unzip' function is the inverse of the 'zip' function.+unzip :: NonEmpty (a, b) -> (NonEmpty a, NonEmpty b)+unzip ((a, b) :| asbs) = (a :| as, b :| bs)+  where+    (as, bs) = List.unzip asbs++-- | The 'nub' function removes duplicate elements from a list. In+-- particular, it keeps only the first occurrence of each element.+-- (The name 'nub' means \'essence\'.)+-- It is a special case of 'nubBy', which allows the programmer to+-- supply their own inequality test.+nub :: Eq a => NonEmpty a -> NonEmpty a+nub = nubBy (==)++-- | The 'nubBy' function behaves just like 'nub', except it uses a+-- user-supplied equality predicate instead of the overloaded '=='+-- function.+nubBy :: (a -> a -> Bool) -> NonEmpty a -> NonEmpty a+nubBy eq (a :| as) = a :| List.nubBy eq (List.filter (\b -> not (eq a b)) as)++-- | 'transpose' for 'NonEmpty', behaves the same as 'GHC.Internal.Data.List.transpose'+-- The rows/columns need not be the same length, in which case+-- > transpose . transpose /= id+transpose :: NonEmpty (NonEmpty a) -> NonEmpty (NonEmpty a)+transpose = fmap fromList+          . fromList . List.transpose . toList+          . fmap toList++-- | 'sortBy' for 'NonEmpty', behaves the same as 'GHC.Internal.Data.List.sortBy'+sortBy :: (a -> a -> Ordering) -> NonEmpty a -> NonEmpty a+sortBy f = lift (List.sortBy f)++-- | 'sortWith' for 'NonEmpty', behaves the same as:+--+-- > sortBy . comparing+sortWith :: Ord o => (a -> o) -> NonEmpty a -> NonEmpty a+sortWith = sortBy . comparing++-- | A monomorphic version of '<>' for 'NonEmpty'.+--+-- >>> append (1 :| []) (2 :| [3])+-- 1 :| [2,3]+--+-- @since 4.16+append :: NonEmpty a -> NonEmpty a -> NonEmpty a+append = (<>)++-- | Attach a list at the end of a 'NonEmpty'.+--+-- >>> appendList (1 :| [2,3]) []+-- 1 :| [2,3]+--+-- >>> appendList (1 :| [2,3]) [4,5]+-- 1 :| [2,3,4,5]+--+-- @since 4.16+appendList :: NonEmpty a -> [a] -> NonEmpty a+appendList (x :| xs) ys = x :| xs <> ys++-- | Attach a list at the beginning of a 'NonEmpty'.+--+-- >>> prependList [] (1 :| [2,3])+-- 1 :| [2,3]+--+-- >>> prependList [negate 1, 0] (1 :| [2, 3])+-- -1 :| [0,1,2,3]+--+-- @since 4.16+prependList :: [a] -> NonEmpty a -> NonEmpty a+prependList ls ne = case ls of+  [] -> ne+  (x : xs) -> x :| xs <> toList ne
+ src/Data/Maybe.hs view
@@ -0,0 +1,29 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Maybe+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The Maybe type, and associated operations.+--++module Data.Maybe+    (Maybe(Nothing, Just),+     maybe,+     isJust,+     isNothing,+     fromJust,+     fromMaybe,+     listToMaybe,+     maybeToList,+     catMaybes,+     mapMaybe+     ) where++import GHC.Internal.Data.Maybe
+ src/Data/Monoid.hs view
@@ -0,0 +1,77 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Monoid+-- Copyright   :  (c) Andy Gill 2001,+--                (c) Oregon Graduate Institute of Science and Technology, 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- A type @a@ is a 'Monoid' if it provides an associative function ('<>')+-- that lets you combine any two values of type @a@ into one, and a neutral+-- element (`mempty`) such that+--+-- > a <> mempty == mempty <> a == a+--+-- A 'Monoid' is a 'Semigroup' with the added requirement of a neutral element.+-- Thus any 'Monoid' is a 'Semigroup', but not the other way around.+--+-- ==== __Examples__+--+-- The 'Sum' monoid is defined by the numerical addition operator and `0` as neutral element:+--+-- >>> import Data.Int+-- >>> mempty :: Sum Int+-- Sum {getSum = 0}+-- >>> Sum 1 <> Sum 2 <> Sum 3 <> Sum 4 :: Sum Int+-- Sum {getSum = 10}+--+-- We can combine multiple values in a list into a single value using the `mconcat` function.+-- Note that we have to specify the type here since 'Int' is a monoid under several different+-- operations:+--+-- >>> mconcat [1,2,3,4] :: Sum Int+-- Sum {getSum = 10}+-- >>> mconcat [] :: Sum Int+-- Sum {getSum = 0}+--+-- Another valid monoid instance of 'Int' is 'Product' It is defined by multiplication+-- and `1` as neutral element:+--+-- >>> Product 1 <> Product 2 <> Product 3 <> Product 4 :: Product Int+-- Product {getProduct = 24}+-- >>> mconcat [1,2,3,4] :: Product Int+-- Product {getProduct = 24}+-- >>> mconcat [] :: Product Int+-- Product {getProduct = 1}+--+--++module Data.Monoid+    (-- *  'Monoid' typeclass+     Monoid(..),+     (<>),+     Dual(..),+     Endo(..),+     -- *  'Bool' wrappers+     All(..),+     Any(..),+     -- *  'Num' wrappers+     Sum(..),+     Product(..),+     -- *  'Maybe' wrappers+     -- $MaybeExamples+     First(..),+     Last(..),+     -- *  'Alternative' wrapper+     Alt(..),+     -- *  'Applicative' wrapper+     Ap(..)+     ) where++import GHC.Internal.Data.Monoid+
+ src/Data/Ord.hs view
@@ -0,0 +1,24 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Ord+-- Copyright   :  (c) The University of Glasgow 2005+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Orderings+--++module Data.Ord+    (Ord(..),+     Ordering(..),+     Down(..),+     comparing,+     clamp+     ) where++import GHC.Internal.Data.Ord
+ src/Data/Proxy.hs view
@@ -0,0 +1,22 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Proxy+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Definition of a Proxy type (poly-kinded in GHC)+--+-- @since 4.7.0.0++module Data.Proxy+    (Proxy(..),+     asProxyTypeOf,+     KProxy(..)+     ) where++import GHC.Internal.Data.Proxy
+ src/Data/Ratio.hs view
@@ -0,0 +1,79 @@+{-# LANGUAGE Safe #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Ratio+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Standard functions on rational numbers+--+-----------------------------------------------------------------------------++module Data.Ratio+    ( Ratio+    , Rational+    , (%)+    , numerator+    , denominator+    , approxRational++  ) where++import GHC.Internal.Real         -- The basic defns for Ratio+import Prelude++-- -----------------------------------------------------------------------------+-- approxRational++-- | 'approxRational', applied to two real fractional numbers @x@ and @epsilon@,+-- returns the simplest rational number within @epsilon@ of @x@.+-- A rational number @y@ is said to be /simpler/ than another @y'@ if+--+-- * @'abs' ('numerator' y) <= 'abs' ('numerator' y')@, and+--+-- * @'denominator' y <= 'denominator' y'@.+--+-- Any real interval contains a unique simplest rational;+-- in particular, note that @0\/1@ is the simplest rational of all.++-- Implementation details: Here, for simplicity, we assume a closed rational+-- interval.  If such an interval includes at least one whole number, then+-- the simplest rational is the absolutely least whole number.  Otherwise,+-- the bounds are of the form q%1 + r%d and q%1 + r'%d', where abs r < d+-- and abs r' < d', and the simplest rational is q%1 + the reciprocal of+-- the simplest rational between d'%r' and d%r.++approxRational :: (RealFrac a) => a -> a -> Rational+approxRational rat eps =+    -- We convert rat and eps to rational *before* subtracting/adding since+    -- otherwise we may overflow. This was the cause of #14425.+    simplest (toRational rat - toRational eps) (toRational rat + toRational eps)+  where+    simplest x y+      | y < x      =  simplest y x+      | x == y     =  xr+      | x > 0      =  simplest' n d n' d'+      | y < 0      =  - simplest' (-n') d' (-n) d+      | otherwise  =  0 :% 1+      where xr  = toRational x+            n   = numerator xr+            d   = denominator xr+            nd' = toRational y+            n'  = numerator nd'+            d'  = denominator nd'++    simplest' n d n' d'       -- assumes 0 < n%d < n'%d'+      | r == 0     =  q :% 1+      | q /= q'    =  (q+1) :% 1+      | otherwise  =  (q*n''+d'') :% n''+      where (q,r)      =  quotRem n d+            (q',r')    =  quotRem n' d'+            nd''       =  simplest' d' r' d r+            n''        =  numerator nd''+            d''        =  denominator nd''+
+ src/Data/STRef.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.STRef+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (uses Control.Monad.ST)+--+-- Mutable references in the (strict) ST monad.+--++module Data.STRef+    (-- *  STRefs+     STRef,+     newSTRef,+     readSTRef,+     writeSTRef,+     modifySTRef,+     modifySTRef'+     ) where++import GHC.Internal.Data.STRef
+ src/Data/STRef/Lazy.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE Safe #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.STRef.Lazy+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (uses Control.Monad.ST.Lazy)+--+-- Mutable references in the lazy ST monad.+--+-----------------------------------------------------------------------------++module Data.STRef.Lazy (+        -- * STRefs+        ST.STRef,       -- abstract+        newSTRef,+        readSTRef,+        writeSTRef,+        modifySTRef+ ) where++import Prelude+import GHC.Internal.Control.Monad.ST.Lazy+import qualified GHC.Internal.Data.STRef as ST++newSTRef    :: a -> ST s (ST.STRef s a)+readSTRef   :: ST.STRef s a -> ST s a+writeSTRef  :: ST.STRef s a -> a -> ST s ()+modifySTRef :: ST.STRef s a -> (a -> a) -> ST s ()++newSTRef        = strictToLazyST . ST.newSTRef+readSTRef       = strictToLazyST . ST.readSTRef+writeSTRef  r a = strictToLazyST (ST.writeSTRef r a)+modifySTRef r f = strictToLazyST (ST.modifySTRef r f)+
+ src/Data/STRef/Strict.hs view
@@ -0,0 +1,18 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.STRef.Strict+-- 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 (uses Control.Monad.ST.Strict)+--+-- Mutable references in the (strict) ST monad (re-export of "Data.STRef")+--++module Data.STRef.Strict (module Data.STRef) where++import Data.STRef
+ src/Data/Semigroup.hs view
@@ -0,0 +1,663 @@+{-# LANGUAGE NoImplicitPrelude          #-}+{-# LANGUAGE CPP                        #-}+{-# LANGUAGE DeriveDataTypeable         #-}+{-# LANGUAGE DeriveGeneric              #-}+{-# LANGUAGE FlexibleContexts           #-}+{-# LANGUAGE PolyKinds                  #-}+{-# LANGUAGE ScopedTypeVariables        #-}+{-# LANGUAGE Trustworthy                #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Data.Semigroup+-- Copyright   :  (C) 2011-2015 Edward Kmett+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- A type @a@ is a 'Semigroup' if it provides an associative function ('<>')+-- that lets you combine any two values of type @a@ into one. Where being+-- associative means that the following must always hold:+--+-- prop> (a <> b) <> c == a <> (b <> c)+--+-- ==== __Examples__+--+-- The 'Min' 'Semigroup' instance for 'Int' is defined to always pick the smaller+-- number:+--+-- >>> Min 1 <> Min 2 <> Min 3 <> Min 4 :: Min Int+-- Min {getMin = 1}+--+-- If we need to combine multiple values we can use the 'sconcat' function+-- to do so. We need to ensure however that we have at least one value to+-- operate on, since otherwise our result would be undefined. It is for this+-- reason that 'sconcat' uses "Data.List.NonEmpty.NonEmpty" - a list that+-- can never be empty:+--+-- >>> (1 :| [])+-- 1 :| []+--+-- -- equivalent to [1] but guaranteed to be non-empty.+--+-- >>> (1 :| [2, 3, 4])+-- 1 :| [2,3,4]+--+-- -- equivalent to [1,2,3,4] but guaranteed to be non-empty.+--+-- Equipped with this guaranteed to be non-empty data structure, we can combine+-- values using 'sconcat' and a 'Semigroup' of our choosing. We can try the 'Min'+-- and 'Max' instances of 'Int' which pick the smallest, or largest number+-- respectively:+--+-- >>> sconcat (1 :| [2, 3, 4]) :: Min Int+-- Min {getMin = 1}+--+-- >>> sconcat (1 :| [2, 3, 4]) :: Max Int+-- Max {getMax = 4}+--+-- String concatenation is another example of a 'Semigroup' instance:+--+-- >>> "foo" <> "bar"+-- "foobar"+--+-- A 'Semigroup' is a generalization of a 'Monoid'. Yet unlike the 'Semigroup', the 'Monoid'+-- requires the presence of a neutral element ('mempty') in addition to the associative+-- operator. The requirement for a neutral element prevents many types from being a full Monoid,+-- like "Data.List.NonEmpty.NonEmpty".+--+-- Note that the use of @(\<\>)@ in this module conflicts with an operator with the same+-- name that is being exported by "Data.Monoid". However, this package+-- re-exports (most of) the contents of Data.Monoid, so to use semigroups+-- and monoids in the same package just+--+-- > import Data.Semigroup+--+-- @since 4.9.0.0+----------------------------------------------------------------------------+module Data.Semigroup (+    Semigroup(..)+  , stimesMonoid+  , stimesIdempotent+  , stimesIdempotentMonoid+  , mtimesDefault+  -- * Semigroups+  , Min(..)+  , Max(..)+  , First(..)+  , Last(..)+  , WrappedMonoid(..)+  -- * Re-exported monoids+  , Dual(..)+  , Endo(..)+  , All(..)+  , Any(..)+  , Sum(..)+  , Product(..)+  -- * Difference lists of a semigroup+  , diff+  , cycle1+  -- * ArgMin, ArgMax+  , Arg(..)+  , ArgMin+  , ArgMax+  ) where++import           GHC.Internal.Base hiding (Any, NonEmpty(..))+import           GHC.Internal.Enum+import           GHC.Internal.Show+import           GHC.Internal.Read+import           GHC.Internal.Num+import           GHC.Internal.Real+import           GHC.Internal.Data.Functor ((<$>))+import           Data.Bifoldable+import           Data.Bifunctor+import           Data.Bitraversable+import           GHC.Internal.Data.Foldable+import           GHC.Internal.Data.NonEmpty (NonEmpty(..))+import           GHC.Internal.Data.Traversable+import           GHC.Internal.Data.Semigroup.Internal+import           GHC.Internal.Control.Monad.Fix+import           GHC.Internal.Data.Data+import           GHC.Generics+import qualified GHC.Internal.List as List++-- $setup+-- >>> import Prelude+-- >>> import Data.List.NonEmpty (NonEmpty (..))+-- >>> import GHC.Internal.Data.Semigroup.Internal++-- | A generalization of 'GHC.Internal.Data.List.cycle' to an arbitrary 'Semigroup'.+-- May fail to terminate for some values in some semigroups.+--+-- ==== __Examples__+--+-- >>> take 10 $ cycle1 [1, 2, 3]+-- [1,2,3,1,2,3,1,2,3,1]+--+-- >>> cycle1 (Right 1)+-- Right 1+--+-- >>> cycle1 (Left 1)+-- * Hangs forever *+cycle1 :: Semigroup m => m -> m+cycle1 xs = xs' where xs' = xs <> xs'++-- | This lets you use a difference list of a 'Semigroup' as a 'Monoid'.+--+-- ==== __Examples__+--+-- >>> let hello = diff "Hello, "+--+-- >>> appEndo hello "World!"+-- "Hello, World!"+--+-- >>> appEndo (hello <> mempty) "World!"+-- "Hello, World!"+--+-- >>> appEndo (mempty <> hello) "World!"+-- "Hello, World!"+--+-- >>> let world = diff "World"+-- >>> let excl = diff "!"+--+-- >>> appEndo (hello <> (world <> excl)) mempty+-- "Hello, World!"+--+-- >>> appEndo ((hello <> world) <> excl) mempty+-- "Hello, World!"+diff :: Semigroup m => m -> Endo m+diff = Endo . (<>)++-- | The 'Min' 'Monoid' and 'Semigroup' always choose the smaller element as+-- by the 'Ord' instance and 'min' of the contained type.+--+-- ==== __Examples__+--+-- >>> Min 42 <> Min 3+-- Min {getMin = 3}+--+-- >>> sconcat $ Min 1 :| [ Min n | n <- [2 .. 100]]+-- Min {getMin = 1}+newtype Min a = Min { getMin :: a }+  deriving ( Bounded  -- ^ @since 4.9.0.0+           , Eq       -- ^ @since 4.9.0.0+           , Ord      -- ^ @since 4.9.0.0+           , Show     -- ^ @since 4.9.0.0+           , Read     -- ^ @since 4.9.0.0+           , Data     -- ^ @since 4.9.0.0+           , Generic  -- ^ @since 4.9.0.0+           , Generic1 -- ^ @since 4.9.0.0+           )++-- | @since 4.9.0.0+instance Enum a => Enum (Min a) where+  succ (Min a) = Min (succ a)+  pred (Min a) = Min (pred a)+  toEnum = Min . toEnum+  fromEnum = fromEnum . getMin+  enumFrom (Min a) = Min `fmap` enumFrom a+  enumFromThen (Min a) (Min b) = Min `fmap` enumFromThen a b+  enumFromTo (Min a) (Min b) = Min `fmap` enumFromTo a b+  enumFromThenTo (Min a) (Min b) (Min c) = Min `fmap` enumFromThenTo a b c+++-- | @since 4.9.0.0+instance Ord a => Semigroup (Min a) where+  (<>) = coerce (min :: a -> a -> a)+  stimes = stimesIdempotent++-- | @since 4.9.0.0+instance (Ord a, Bounded a) => Monoid (Min a) where+  mempty = maxBound+  -- By default, we would get a lazy right fold. This forces the use of a strict+  -- left fold instead.+  mconcat = List.foldl' (<>) mempty+  {-# INLINE mconcat #-}++-- | @since 4.9.0.0+instance Functor Min where+  fmap f (Min x) = Min (f x)++-- | @since 4.9.0.0+instance Foldable Min where+  foldMap f (Min a) = f a++-- | @since 4.9.0.0+instance Traversable Min where+  traverse f (Min a) = Min `fmap` f a++-- | @since 4.9.0.0+instance Applicative Min where+  pure = Min+  a <* _ = a+  _ *> a = a+  (<*>) = coerce+  liftA2 = coerce++-- | @since 4.9.0.0+instance Monad Min where+  (>>) = (*>)+  Min a >>= f = f a++-- | @since 4.9.0.0+instance MonadFix Min where+  mfix f = fix (f . getMin)++-- | @since 4.9.0.0+instance Num a => Num (Min a) where+  (Min a) + (Min b) = Min (a + b)+  (Min a) * (Min b) = Min (a * b)+  (Min a) - (Min b) = Min (a - b)+  negate (Min a) = Min (negate a)+  abs    (Min a) = Min (abs a)+  signum (Min a) = Min (signum a)+  fromInteger    = Min . fromInteger++-- | The 'Max' 'Monoid' and 'Semigroup' always choose the bigger element as+-- by the 'Ord' instance and 'max' of the contained type.+--+-- ==== __Examples__+--+-- >>> Max 42 <> Max 3+-- Max {getMax = 42}+--+-- >>> sconcat $ Max 1 :| [ Max n | n <- [2 .. 100]]+-- Max {getMax = 100}+newtype Max a = Max { getMax :: a }+  deriving ( Bounded  -- ^ @since 4.9.0.0+           , Eq       -- ^ @since 4.9.0.0+           , Ord      -- ^ @since 4.9.0.0+           , Show     -- ^ @since 4.9.0.0+           , Read     -- ^ @since 4.9.0.0+           , Data     -- ^ @since 4.9.0.0+           , Generic  -- ^ @since 4.9.0.0+           , Generic1 -- ^ @since 4.9.0.0+           )++-- | @since 4.9.0.0+instance Enum a => Enum (Max a) where+  succ (Max a) = Max (succ a)+  pred (Max a) = Max (pred a)+  toEnum = Max . toEnum+  fromEnum = fromEnum . getMax+  enumFrom (Max a) = Max `fmap` enumFrom a+  enumFromThen (Max a) (Max b) = Max `fmap` enumFromThen a b+  enumFromTo (Max a) (Max b) = Max `fmap` enumFromTo a b+  enumFromThenTo (Max a) (Max b) (Max c) = Max `fmap` enumFromThenTo a b c++-- | @since 4.9.0.0+instance Ord a => Semigroup (Max a) where+  (<>) = coerce (max :: a -> a -> a)+  stimes = stimesIdempotent++-- | @since 4.9.0.0+instance (Ord a, Bounded a) => Monoid (Max a) where+  mempty = minBound+  -- By default, we would get a lazy right fold. This forces the use of a strict+  -- left fold instead.+  mconcat = List.foldl' (<>) mempty+  {-# INLINE mconcat #-}++-- | @since 4.9.0.0+instance Functor Max where+  fmap f (Max x) = Max (f x)++-- | @since 4.9.0.0+instance Foldable Max where+  foldMap f (Max a) = f a++-- | @since 4.9.0.0+instance Traversable Max where+  traverse f (Max a) = Max `fmap` f a++-- | @since 4.9.0.0+instance Applicative Max where+  pure = Max+  a <* _ = a+  _ *> a = a+  (<*>) = coerce+  liftA2 = coerce++-- | @since 4.9.0.0+instance Monad Max where+  (>>) = (*>)+  Max a >>= f = f a++-- | @since 4.9.0.0+instance MonadFix Max where+  mfix f = fix (f . getMax)++-- | @since 4.9.0.0+instance Num a => Num (Max a) where+  (Max a) + (Max b) = Max (a + b)+  (Max a) * (Max b) = Max (a * b)+  (Max a) - (Max b) = Max (a - b)+  negate (Max a) = Max (negate a)+  abs    (Max a) = Max (abs a)+  signum (Max a) = Max (signum a)+  fromInteger    = Max . fromInteger++-- | 'Arg' isn't itself a 'Semigroup' in its own right, but it can be+-- placed inside 'Min' and 'Max' to compute an arg min or arg max. In+-- the event of ties, the leftmost qualifying 'Arg' is chosen; contrast+-- with the behavior of 'minimum' and 'maximum' for many other types,+-- where ties are broken by considering elements to the left in the+-- structure to be less than elements to the right.+--+-- ==== __Examples__+--+-- >>> minimum [ Arg (x * x) x | x <- [-10 .. 10] ]+-- Arg 0 0+--+-- >>> maximum [ Arg (-0.2*x^2 + 1.5*x + 1) x | x <- [-10 .. 10] ]+-- Arg 3.8 4.0+--+-- >>> minimum [ Arg (-0.2*x^2 + 1.5*x + 1) x | x <- [-10 .. 10] ]+-- Arg (-34.0) (-10.0)+data Arg a b = Arg+  a+  -- ^ The argument used for comparisons in 'Eq' and 'Ord'.+  b+  -- ^ The "value" exposed via the 'Functor', 'Foldable' etc. instances.+  deriving+  ( Show     -- ^ @since 4.9.0.0+  , Read     -- ^ @since 4.9.0.0+  , Data     -- ^ @since 4.9.0.0+  , Generic  -- ^ @since 4.9.0.0+  , Generic1 -- ^ @since 4.9.0.0+  )++-- |+-- ==== __Examples__+--+-- >>> Min (Arg 0 ()) <> Min (Arg 1 ())+-- Min {getMin = Arg 0 ()}+--+-- >>> minimum [ Arg (length name) name | name <- ["violencia", "lea", "pixie"]]+-- Arg 3 "lea"+type ArgMin a b = Min (Arg a b)++-- |+-- ==== __Examples__+--+-- >>> Max (Arg 0 ()) <> Max (Arg 1 ())+-- Max {getMax = Arg 1 ()}+--+-- >>> maximum [ Arg (length name) name | name <- ["violencia", "lea", "pixie"]]+-- Arg 9 "violencia"+type ArgMax a b = Max (Arg a b)++-- | @since 4.9.0.0+instance Functor (Arg a) where+  fmap f (Arg x a) = Arg x (f a)++-- | @since 4.9.0.0+instance Foldable (Arg a) where+  foldMap f (Arg _ a) = f a++-- | @since 4.9.0.0+instance Traversable (Arg a) where+  traverse f (Arg x a) = Arg x `fmap` f a++-- |+-- Note that `Arg`'s 'Eq' instance does not satisfy extensionality:+--+-- >>> Arg 0 0 == Arg 0 1+-- True+-- >>> let f (Arg _ x) = x in f (Arg 0 0) == f (Arg 0 1)+-- False+--+-- @since 4.9.0.0+instance Eq a => Eq (Arg a b) where+  Arg a _ == Arg b _ = a == b++-- |+-- Note that `Arg`'s 'Ord' instance has 'min' and 'max' implementations that+-- differ from the tie-breaking conventions of the default implementation of+-- 'min' and 'max' in class 'Ord'; 'Arg' breaks ties by favoring the first+-- argument in both functions.+--+-- @since 4.9.0.0+instance Ord a => Ord (Arg a b) where+  Arg a _ `compare` Arg b _ = compare a b+  min x@(Arg a _) y@(Arg b _)+    | a <= b    = x+    | otherwise = y+  max x@(Arg a _) y@(Arg b _)+    | a >= b    = x+    | otherwise = y++-- | @since 4.9.0.0+instance Bifunctor Arg where+  bimap f g (Arg a b) = Arg (f a) (g b)++-- | @since 4.10.0.0+instance Bitraversable Arg where+  bitraverse f g (Arg a b) = Arg <$> f a <*> g b++-- | @since 4.10.0.0+instance Bifoldable Arg where+  bifoldMap f g (Arg a b) = f a <> g b++-- |+-- Beware that @Data.Semigroup.@'First' is different from+-- @Data.Monoid.@'Data.Monoid.First'. The former simply returns the first value,+-- so @Data.Semigroup.First Nothing <> x = Data.Semigroup.First Nothing@.+-- The latter returns the first non-'Nothing',+-- thus @Data.Monoid.First Nothing <> x = x@.+--+-- ==== __Examples__+--+-- >>> First 0 <> First 10+-- First {getFirst = 0}+--+-- >>> sconcat $ First 1 :| [ First n | n <- [2 ..] ]+-- First {getFirst = 1}+newtype First a = First { getFirst :: a }+  deriving ( Bounded  -- ^ @since 4.9.0.0+           , Eq       -- ^ @since 4.9.0.0+           , Ord      -- ^ @since 4.9.0.0+           , Show     -- ^ @since 4.9.0.0+           , Read     -- ^ @since 4.9.0.0+           , Data     -- ^ @since 4.9.0.0+           , Generic  -- ^ @since 4.9.0.0+           , Generic1 -- ^ @since 4.9.0.0+           )++-- | @since 4.9.0.0+instance Enum a => Enum (First a) where+  succ (First a) = First (succ a)+  pred (First a) = First (pred a)+  toEnum = First . toEnum+  fromEnum = fromEnum . getFirst+  enumFrom (First a) = First `fmap` enumFrom a+  enumFromThen (First a) (First b) = First `fmap` enumFromThen a b+  enumFromTo (First a) (First b) = First `fmap` enumFromTo a b+  enumFromThenTo (First a) (First b) (First c) = First `fmap` enumFromThenTo a b c++-- | @since 4.9.0.0+instance Semigroup (First a) where+  a <> _ = a+  stimes = stimesIdempotent+  sconcat (x :| _) = x++-- | @since 4.9.0.0+instance Functor First where+  fmap f (First x) = First (f x)++-- | @since 4.9.0.0+instance Foldable First where+  foldMap f (First a) = f a++-- | @since 4.9.0.0+instance Traversable First where+  traverse f (First a) = First `fmap` f a++-- | @since 4.9.0.0+instance Applicative First where+  pure x = First x+  a <* _ = a+  _ *> a = a+  (<*>) = coerce+  liftA2 = coerce++-- | @since 4.9.0.0+instance Monad First where+  (>>) = (*>)+  First a >>= f = f a++-- | @since 4.9.0.0+instance MonadFix First where+  mfix f = fix (f . getFirst)++-- |+-- Beware that @Data.Semigroup.@'Last' is different from+-- @Data.Monoid.@'Data.Monoid.Last'. The former simply returns the last value,+-- so @x <> Data.Semigroup.Last Nothing = Data.Semigroup.Last Nothing@.+-- The latter returns the last non-'Nothing',+-- thus @x <> Data.Monoid.Last Nothing = x@.+--+-- ==== __Examples__+--+-- >>> Last 0 <> Last 10+-- Last {getLast = 10}+--+-- >>> sconcat $ Last 1 :| [ Last n | n <- [2..]]+-- * Hangs forever *+newtype Last a = Last { getLast :: a }+  deriving ( Bounded  -- ^ @since 4.9.0.0+           , Eq       -- ^ @since 4.9.0.0+           , Ord      -- ^ @since 4.9.0.0+           , Show     -- ^ @since 4.9.0.0+           , Read     -- ^ @since 4.9.0.0+           , Data     -- ^ @since 4.9.0.0+           , Generic  -- ^ @since 4.9.0.0+           , Generic1 -- ^ @since 4.9.0.0+           )++-- | @since 4.9.0.0+instance Enum a => Enum (Last a) where+  succ (Last a) = Last (succ a)+  pred (Last a) = Last (pred a)+  toEnum = Last . toEnum+  fromEnum = fromEnum . getLast+  enumFrom (Last a) = Last `fmap` enumFrom a+  enumFromThen (Last a) (Last b) = Last `fmap` enumFromThen a b+  enumFromTo (Last a) (Last b) = Last `fmap` enumFromTo a b+  enumFromThenTo (Last a) (Last b) (Last c) = Last `fmap` enumFromThenTo a b c++-- | @since 4.9.0.0+instance Semigroup (Last a) where+  _ <> b = b+  stimes = stimesIdempotent++-- | @since 4.9.0.0+instance Functor Last where+  fmap f (Last x) = Last (f x)+  a <$ _ = Last a++-- | @since 4.9.0.0+instance Foldable Last where+  foldMap f (Last a) = f a++-- | @since 4.9.0.0+instance Traversable Last where+  traverse f (Last a) = Last `fmap` f a++-- | @since 4.9.0.0+instance Applicative Last where+  pure = Last+  a <* _ = a+  _ *> a = a+  (<*>) = coerce+  liftA2 = coerce++-- | @since 4.9.0.0+instance Monad Last where+  (>>) = (*>)+  Last a >>= f = f a++-- | @since 4.9.0.0+instance MonadFix Last where+  mfix f = fix (f . getLast)++-- | Provide a Semigroup for an arbitrary Monoid.+--+-- __NOTE__: This is not needed anymore since 'Semigroup' became a superclass of+-- 'Monoid' in /base-4.11/ and this newtype be deprecated at some point in the future.+newtype WrappedMonoid m = WrapMonoid { unwrapMonoid :: m }+  deriving ( Bounded  -- ^ @since 4.9.0.0+           , Eq       -- ^ @since 4.9.0.0+           , Ord      -- ^ @since 4.9.0.0+           , Show     -- ^ @since 4.9.0.0+           , Read     -- ^ @since 4.9.0.0+           , Data     -- ^ @since 4.9.0.0+           , Generic  -- ^ @since 4.9.0.0+           , Generic1 -- ^ @since 4.9.0.0+           )++-- | @since 4.9.0.0+instance Monoid m => Semigroup (WrappedMonoid m) where+  (<>) = coerce (mappend :: m -> m -> m)++-- | @since 4.9.0.0+instance Monoid m => Monoid (WrappedMonoid m) where+  mempty = WrapMonoid mempty+  -- This ensures that we use whatever mconcat is defined for the wrapped+  -- Monoid.+  mconcat = coerce (mconcat :: [m] -> m)++-- | @since 4.9.0.0+instance Enum a => Enum (WrappedMonoid a) where+  succ (WrapMonoid a) = WrapMonoid (succ a)+  pred (WrapMonoid a) = WrapMonoid (pred a)+  toEnum = WrapMonoid . toEnum+  fromEnum = fromEnum . unwrapMonoid+  enumFrom (WrapMonoid a) = WrapMonoid `fmap` enumFrom a+  enumFromThen (WrapMonoid a) (WrapMonoid b) = WrapMonoid `fmap` enumFromThen a b+  enumFromTo (WrapMonoid a) (WrapMonoid b) = WrapMonoid `fmap` enumFromTo a b+  enumFromThenTo (WrapMonoid a) (WrapMonoid b) (WrapMonoid c) =+      WrapMonoid `fmap` enumFromThenTo a b c++-- | Repeat a value @n@ times.+--+-- > mtimesDefault n a = a <> a <> ... <> a  -- using <> (n-1) times+--+-- In many cases, @'stimes' 0 a@ for a `Monoid` will produce `mempty`.+-- However, there are situations when it cannot do so. In particular,+-- the following situation is fairly common:+--+-- @+-- data T a = ...+--+-- class Constraint1 a+-- class Constraint1 a => Constraint2 a+-- @+--+-- @+-- instance Constraint1 a => 'Semigroup' (T a)+-- instance Constraint2 a => 'Monoid' (T a)+-- @+--+-- Since @Constraint1@ is insufficient to implement 'mempty',+-- 'stimes' for @T a@ cannot do so.+--+-- When working with such a type, or when working polymorphically with+-- 'Semigroup' instances, @mtimesDefault@ should be used when the+-- multiplier might be zero. It is implemented using 'stimes' when+-- the multiplier is nonzero and 'mempty' when it is zero.+--+-- ==== __Examples__+--+-- >>> mtimesDefault 0 "bark"+-- ""+--+-- >>> mtimesDefault 3 "meow"+-- "meowmeowmeow"+mtimesDefault :: (Integral b, Monoid a) => b -> a -> a+mtimesDefault n x+  | n == 0    = mempty+  | otherwise = stimes n x
+ src/Data/String.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.String+-- Copyright   :  (c) The University of Glasgow 2007+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The @String@ type and associated operations.+--++module Data.String+    (String,+     IsString(..),+     -- *  Functions on strings+     lines,+     words,+     unlines,+     unwords+     ) where++import GHC.Internal.Data.String
+ src/Data/Traversable.hs view
@@ -0,0 +1,1112 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  Data.Traversable+-- Copyright   :  Conor McBride and Ross Paterson 2005+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Class of data structures that can be traversed from left to right,+-- performing an action on each element.  Instances are expected to satisfy+-- the listed [laws](#laws).++module Data.Traversable (+    -- * The 'Traversable' class+    Traversable(..),+    -- * Utility functions+    for,+    forM,+    forAccumM,+    mapAccumL,+    mapAccumR,+    mapAccumM,+    -- * General definitions for superclass methods+    fmapDefault,+    foldMapDefault,++    -- * Overview+    -- $overview++    -- ** The 'traverse' and 'mapM' methods+    -- $traverse++    -- *** Their 'Foldable', just the effects, analogues.+    -- $effectful++    -- *** Result multiplicity+    -- $multiplicity++    -- ** The 'sequenceA' and 'sequence' methods+    -- $sequence++    -- *** Care with default method implementations+    -- $seqdefault++    -- *** Monadic short circuits+    -- $seqshort++    -- ** Example binary tree instance+    -- $tree_instance++    -- *** Pre-order and post-order tree traversal+    -- $tree_order++    -- ** Making construction intuitive+    --+    -- $construction++    -- * Advanced traversals+    -- $advanced++    -- *** Coercion+    -- $coercion++    -- ** Identity: the 'fmapDefault' function+    -- $identity++    -- ** State: the 'mapAccumL', 'mapAccumR' functions+    -- $stateful++    -- ** Const: the 'foldMapDefault' function+    -- $phantom++    -- ** ZipList: transposing lists of lists+    -- $ziplist++    -- * Laws+    --+    -- $laws++    -- * See also+    -- $also+    ) where++import GHC.Internal.Data.Traversable++-- $setup+-- >>> import Prelude+-- >>> import Data.Maybe+-- >>> import Data.Either+-- >>> import qualified Data.List as List+-- >>> :set -XExplicitForAll++-- $overview+--+-- #overview#+-- Traversable structures support element-wise sequencing of 'Applicative'+-- effects (thus also 'Monad' effects) to construct new structures of+-- __the same shape__ as the input.+--+-- To illustrate what is meant by /same shape/, if the input structure is+-- __@[a]@__, each output structure is a list __@[b]@__ of the same length as+-- the input.  If the input is a __@Tree a@__, each output __@Tree b@__ has the+-- same graph of intermediate nodes and leaves.  Similarly, if the input is a+-- 2-tuple __@(x, a)@__, each output is a 2-tuple __@(x, b)@__, and so forth.+--+-- It is in fact possible to decompose a traversable structure __@t a@__ into+-- its shape (a.k.a. /spine/) of type __@t ()@__ and its element list+-- __@[a]@__.  The original structure can be faithfully reconstructed from its+-- spine and element list.+--+-- The implementation of a @Traversable@ instance for a given structure follows+-- naturally from its type; see the [Construction](#construction) section for+-- details.+-- Instances must satisfy the laws listed in the [Laws section](#laws).+-- The diverse uses of @Traversable@ structures result from the many possible+-- choices of Applicative effects.+-- See the [Advanced Traversals](#advanced) section for some examples.+--+-- Every @Traversable@ structure is both a 'Functor' and 'Foldable' because it+-- is possible to implement the requisite instances in terms of 'traverse' by+-- using 'fmapDefault' for 'fmap' and 'foldMapDefault' for 'foldMap'.  Direct+-- fine-tuned implementations of these superclass methods can in some cases be+-- more efficient.++------------------++-- $traverse+-- For an 'Applicative' functor __@f@__ and a @Traversable@ functor __@t@__,+-- the type signatures of 'traverse' and 'fmap' are rather similar:+--+-- > fmap     :: (a -> f b) -> t a -> t (f b)+-- > traverse :: (a -> f b) -> t a -> f (t b)+--+-- The key difference is that 'fmap' produces a structure whose elements (of+-- type __@f b@__) are individual effects, while 'traverse' produces an+-- aggregate effect yielding structures of type __@t b@__.+--+-- For example, when __@f@__ is the __@IO@__ monad, and __@t@__ is __@List@__,+-- 'fmap' yields a list of IO actions, whereas 'traverse' constructs an IO+-- action that evaluates to a list of the return values of the individual+-- actions performed left-to-right.+--+-- > traverse :: (a -> IO b) -> [a] -> IO [b]+--+-- The 'mapM' function is a specialisation of 'traverse' to the case when+-- __@f@__ is a 'Monad'.  For monads, 'mapM' is more idiomatic than 'traverse'.+-- The two are otherwise generally identical (though 'mapM' may be specifically+-- optimised for monads, and could be more efficient than using the more+-- general 'traverse').+--+-- > traverse :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b)+-- > mapM     :: (Monad       m, Traversable t) => (a -> m b) -> t a -> m (t b)+--+-- When the traversable term is a simple variable or expression, and the+-- monadic action to run is a non-trivial do block, it can be more natural to+-- write the action last.  This idiom is supported by 'for', 'forM', and+-- 'forAccumM' which are the flipped versions of 'traverse', 'mapM', and+-- 'mapAccumM' respectively.++------------------++-- $multiplicity+--+-- #multiplicity#+-- When 'traverse' or 'mapM' is applied to an empty structure __@ts@__ (one for+-- which __@'null' ts@__ is 'True') the return value is __@pure ts@__+-- regardless of the provided function __@g :: a -> f b@__.  It is not possible+-- to apply the function when no values of type __@a@__ are available, but its+-- type determines the relevant instance of 'pure'.+--+-- prop> null ts ==> traverse g ts == pure ts+--+-- Otherwise, when __@ts@__ is non-empty and at least one value of type __@b@__+-- results from each __@f a@__, the structures __@t b@__ have /the same shape/+-- (list length, graph of tree nodes, ...) as the input structure __@t a@__,+-- but the slots previously occupied by elements of type __@a@__ now hold+-- elements of type __@b@__.+--+-- A single traversal may produce one, zero or many such structures.  The zero+-- case happens when one of the effects __@f a@__ sequenced as part of the+-- traversal yields no replacement values.  Otherwise, the many case happens+-- when one of sequenced effects yields multiple values.+--+-- The 'traverse' function does not perform selective filtering of slots in the+-- output structure as with e.g. 'Data.Maybe.mapMaybe'.+--+-- >>> let incOdd n = if odd n then Just $ n + 1 else Nothing+-- >>> mapMaybe incOdd [1, 2, 3]+-- [2,4]+-- >>> traverse incOdd [1, 3, 5]+-- Just [2,4,6]+-- >>> traverse incOdd [1, 2, 3]+-- Nothing+--+-- In the above examples, with 'Maybe' as the 'Applicative' __@f@__, we see+-- that the number of __@t b@__ structures produced by 'traverse' may differ+-- from one: it is zero when the result short-circuits to __@Nothing@__.  The+-- same can happen when __@f@__ is __@List@__ and the result is __@[]@__, or+-- __@f@__ is __@Either e@__ and the result is __@Left (x :: e)@__, or perhaps+-- the 'Control.Applicative.empty' value of some+-- 'Control.Applicative.Alternative' functor.+--+-- When __@f@__ is e.g. __@List@__, and the map __@g :: a -> [b]@__ returns+-- more than one value for some inputs __@a@__ (and at least one for all+-- __@a@__), the result of __@mapM g ts@__ will contain multiple structures of+-- the same shape as __@ts@__:+--+-- prop> List.length (mapM g ts) == List.product (fmap (List.length . g) ts)+--+-- For example:+--+-- >>> List.length $ mapM (\n -> [1..n]) [1..6]+-- 720+-- >>> List.product $ List.length . (\n -> [1..n]) <$> [1..6]+-- 720+--+-- In other words, a traversal with a function __@g :: a -> [b]@__, over an+-- input structure __@t a@__, yields a list __@[t b]@__, whose length is the+-- product of the lengths of the lists that @g@ returns for each element of the+-- input structure!  The individual elements __@a@__ of the structure are+-- replaced by each element of __@g a@__ in turn:+--+-- >>> mapM (\n -> [1..n]) $ Just 3+-- [Just 1,Just 2,Just 3]+-- >>> mapM (\n -> [1..n]) [1..3]+-- [[1,1,1],[1,1,2],[1,1,3],[1,2,1],[1,2,2],[1,2,3]]+--+-- If any element of the structure __@t a@__ is mapped by @g@ to an empty list,+-- then the entire aggregate result is empty, because no value is available to+-- fill one of the slots of the output structure:+--+-- >>> mapM (\n -> [1..n]) $ [0..6] -- [1..0] is empty+-- []++------------------++-- $effectful+-- #effectful#+--+-- The 'traverse' and 'mapM' methods have analogues in the "Data.Foldable"+-- module.  These are 'traverse_' and 'mapM_', and their flipped variants+-- 'for_' and 'forM_', respectively.  The result type is __@f ()@__, they don't+-- return an updated structure, and can be used to sequence effects over all+-- the elements of a @Traversable@ (any 'Foldable') structure just for their+-- side-effects.+--+-- If the @Traversable@ structure is empty, the result is __@pure ()@__.  When+-- effects short-circuit, the __@f ()@__ result may, for example, be 'Nothing'+-- if __@f@__ is 'Maybe', or __@'Left' e@__ when it is __@'Either' e@__.+--+-- It is perhaps worth noting that 'Maybe' is not only a potential+-- 'Applicative' functor for the return value of the first argument of+-- 'traverse', but is also itself a 'Traversable' structure with either zero or+-- one element.  A convenient idiom for conditionally executing an action just+-- for its effects on a 'Just' value, and doing nothing otherwise is:+--+-- > -- action :: Monad m => a -> m ()+-- > -- mvalue :: Maybe a+-- > mapM_ action mvalue -- :: m ()+--+-- which is more concise than:+--+-- > maybe (return ()) action mvalue+--+-- The 'mapM_' idiom works verbatim if the type of __@mvalue@__ is later+-- refactored from __@Maybe a@__ to __@Either e a@__ (assuming it remains OK to+-- silently do nothing in the 'Left' case).++------------------++-- $sequence+--+-- #sequence#+-- The 'sequenceA' and 'sequence' methods are useful when what you have is a+-- container of pending applicative or monadic effects, and you want to combine+-- them into a single effect that produces zero or more containers with the+-- computed values.+--+-- > sequenceA :: (Applicative f, Traversable t) => t (f a) -> f (t a)+-- > sequence  :: (Monad       m, Traversable t) => t (m a) -> m (t a)+-- > sequenceA = traverse id -- default definition+-- > sequence  = sequenceA   -- default definition+--+-- When the monad __@m@__ is 'System.IO.IO', applying 'sequence' to a list of+-- IO actions, performs each in turn, returning a list of the results:+--+-- > sequence [putStr "Hello ", putStrLn "World!"]+-- >     = (\a b -> [a,b]) <$> putStr "Hello " <*> putStrLn "World!"+-- >     = do u1 <- putStr "Hello "+-- >          u2 <- putStrLn "World!"+-- >          return [u1, u2]         -- In this case  [(), ()]+--+-- For 'sequenceA', the /non-deterministic/ behaviour of @List@ is most easily+-- seen in the case of a list of lists (of elements of some common fixed type).+-- The result is a cross-product of all the sublists:+--+-- >>> sequenceA [[0, 1, 2], [30, 40], [500]]+-- [[0,30,500],[0,40,500],[1,30,500],[1,40,500],[2,30,500],[2,40,500]]+--+-- Because the input list has three (sublist) elements, the result is a list of+-- triples (/same shape/).++------------------++-- $seqshort+--+-- #seqshort#+-- When the monad __@m@__ is 'Either' or 'Maybe' (more generally any+-- 'Control.Monad.MonadPlus'), the effect in question is to short-circuit the+-- result on encountering 'Left' or 'Nothing' (more generally+-- 'Control.Monad.mzero').+--+-- >>> sequence [Just 1,Just 2,Just 3]+-- Just [1,2,3]+-- >>> sequence [Just 1,Nothing,Just 3]+-- Nothing+-- >>> sequence [Right 1,Right 2,Right 3]+-- Right [1,2,3]+-- >>> sequence [Right 1,Left "sorry",Right 3]+-- Left "sorry"+--+-- The result of 'sequence' is all-or-nothing, either structures of exactly the+-- same shape as the input or none at all.  The 'sequence' function does not+-- perform selective filtering as with e.g. 'Data.Maybe.catMaybes' or+-- 'Data.Either.rights':+--+-- >>> catMaybes [Just 1,Nothing,Just 3]+-- [1,3]+-- >>> rights [Right 1,Left "sorry",Right 3]+-- [1,3]++------------------++-- $seqdefault+--+-- #seqdefault#+-- The 'traverse' method has a default implementation in terms of 'sequenceA':+--+-- > traverse g = sequenceA . fmap g+--+-- but relying on this default implementation is not recommended, it requires+-- that the structure is already independently a 'Functor'.  The definition of+-- 'sequenceA' in terms of __@traverse id@__ is much simpler than 'traverse'+-- expressed via a composition of 'sequenceA' and 'fmap'.  Instances should+-- generally implement 'traverse' explicitly.  It may in some cases also make+-- sense to implement a specialised 'mapM'.+--+-- Because 'fmapDefault' is defined in terms of 'traverse' (whose default+-- definition in terms of 'sequenceA' uses 'fmap'), you must not use+-- 'fmapDefault' to define the @Functor@ instance if the @Traversable@ instance+-- directly defines only 'sequenceA'.++------------------++-- $tree_instance+--+-- #tree#+-- The definition of a 'Traversable' instance for a binary tree is rather+-- similar to the corresponding instance of 'Functor', given the data type:+--+-- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)+--+-- a canonical @Functor@ instance would be+--+-- > instance Functor Tree where+-- >    fmap g Empty        = Empty+-- >    fmap g (Leaf x)     = Leaf (g x)+-- >    fmap g (Node l k r) = Node (fmap g l) (g k) (fmap g r)+--+-- a canonical @Traversable@ instance would be+--+-- > instance Traversable Tree where+-- >    traverse g Empty        = pure Empty+-- >    traverse g (Leaf x)     = Leaf <$> g x+-- >    traverse g (Node l k r) = Node <$> traverse g l <*> g k <*> traverse g r+--+-- This definition works for any __@g :: a -> f b@__, with __@f@__ an+-- Applicative functor, as the laws for @('<*>')@ imply the requisite+-- associativity.+--+-- We can add an explicit non-default 'mapM' if desired:+--+-- >    mapM g Empty        = return Empty+-- >    mapM g (Leaf x)     = Leaf <$> g x+-- >    mapM g (Node l k r) = do+-- >        ml <- mapM g l+-- >        mk <- g k+-- >        mr <- mapM g r+-- >        return $ Node ml mk mr+--+-- See [Construction](#construction) below for a more detailed exploration of+-- the general case, but as mentioned in [Overview](#overview) above, instance+-- definitions are typically rather simple, all the interesting behaviour is a+-- result of an interesting choice of 'Applicative' functor for a traversal.++-- $tree_order+--+-- It is perhaps worth noting that the traversal defined above gives an+-- /in-order/ sequencing of the elements.  If instead you want either+-- /pre-order/ (parent first, then child nodes) or post-order (child nodes+-- first, then parent) sequencing, you can define the instance accordingly:+--+-- > inOrderNode :: Tree a -> a -> Tree a -> Tree a+-- > inOrderNode l x r = Node l x r+-- >+-- > preOrderNode :: a -> Tree a -> Tree a -> Tree a+-- > preOrderNode x l r = Node l x r+-- >+-- > postOrderNode :: Tree a -> Tree a -> a -> Tree a+-- > postOrderNode l r x = Node l x r+-- >+-- > -- Traversable instance with in-order traversal+-- > instance Traversable Tree where+-- >     traverse g t = case t of+-- >         Empty      -> pure Empty+-- >         Leaf x     -> Leaf <$> g x+-- >         Node l x r -> inOrderNode <$> traverse g l <*> g x <*> traverse g r+-- >+-- > -- Traversable instance with pre-order traversal+-- > instance Traversable Tree where+-- >     traverse g t = case t of+-- >         Empty      -> pure Empty+-- >         Leaf x     -> Leaf <$> g x+-- >         Node l x r -> preOrderNode <$> g x <*> traverse g l <*> traverse g r+-- >+-- > -- Traversable instance with post-order traversal+-- > instance Traversable Tree where+-- >     traverse g t = case t of+-- >         Empty      -> pure Empty+-- >         Leaf x     -> Leaf <$> g x+-- >         Node l x r -> postOrderNode <$> traverse g l <*> traverse g r <*> g x+--+-- Since the same underlying Tree structure is used in all three cases, it is+-- possible to use @newtype@ wrappers to make all three available at the same+-- time!  The user need only wrap the root of the tree in the appropriate+-- @newtype@ for the desired traversal order.  Tne associated instance+-- definitions are shown below (see [coercion](#coercion) if unfamiliar with+-- the use of 'coerce' in the sample code):+--+-- > {-# LANGUAGE ScopedTypeVariables, TypeApplications #-}+-- >+-- > -- Default in-order traversal+-- >+-- > import Data.Coerce (coerce)+-- > import Data.Traversable+-- >+-- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)+-- > instance Functor  Tree where fmap    = fmapDefault+-- > instance Foldable Tree where foldMap = foldMapDefault+-- >+-- > instance Traversable Tree where+-- >     traverse _ Empty = pure Empty+-- >     traverse g (Leaf a) = Leaf <$> g a+-- >     traverse g (Node l a r) = Node <$> traverse g l <*> g a <*> traverse g r+-- >+-- > -- Optional pre-order traversal+-- >+-- > newtype PreOrderTree a = PreOrderTree (Tree a)+-- > instance Functor  PreOrderTree where fmap    = fmapDefault+-- > instance Foldable PreOrderTree where foldMap = foldMapDefault+-- >+-- > instance Traversable PreOrderTree where+-- >     traverse _ (PreOrderTree Empty)        = pure $ preOrderEmpty+-- >     traverse g (PreOrderTree (Leaf x))     = preOrderLeaf <$> g x+-- >     traverse g (PreOrderTree (Node l x r)) = preOrderNode+-- >         <$> g x+-- >         <*> traverse g (coerce l)+-- >         <*> traverse g (coerce r)+-- >+-- > preOrderEmpty :: forall a. PreOrderTree a+-- > preOrderEmpty = coerce (Empty @a)+-- > preOrderLeaf :: forall a. a -> PreOrderTree a+-- > preOrderLeaf = coerce (Leaf @a)+-- > preOrderNode :: a -> PreOrderTree a -> PreOrderTree a -> PreOrderTree a+-- > preOrderNode x l r = coerce (Node (coerce l) x (coerce r))+-- >+-- > -- Optional post-order traversal+-- >+-- > newtype PostOrderTree a = PostOrderTree (Tree a)+-- > instance Functor  PostOrderTree where fmap    = fmapDefault+-- > instance Foldable PostOrderTree where foldMap = foldMapDefault+-- >+-- > instance Traversable PostOrderTree where+-- >     traverse _ (PostOrderTree Empty)        = pure postOrderEmpty+-- >     traverse g (PostOrderTree (Leaf x))     = postOrderLeaf <$> g x+-- >     traverse g (PostOrderTree (Node l x r)) = postOrderNode+-- >         <$> traverse g (coerce l)+-- >         <*> traverse g (coerce r)+-- >         <*> g x+-- >+-- > postOrderEmpty :: forall a. PostOrderTree a+-- > postOrderEmpty = coerce (Empty @a)+-- > postOrderLeaf :: forall a. a -> PostOrderTree a+-- > postOrderLeaf = coerce (Leaf @a)+-- > postOrderNode :: PostOrderTree a -> PostOrderTree a -> a -> PostOrderTree a+-- > postOrderNode l r x = coerce (Node (coerce l) x (coerce r))+--+-- With the above, given a sample tree:+--+-- > inOrder :: Tree Int+-- > inOrder = Node (Node (Leaf 10) 3 (Leaf 20)) 5 (Leaf 42)+--+-- we have:+--+-- > import Data.Foldable (toList)+-- > print $ toList inOrder+-- > [10,3,20,5,42]+-- >+-- > print $ toList (coerce inOrder :: PreOrderTree Int)+-- > [5,3,10,20,42]+-- >+-- > print $ toList (coerce inOrder :: PostOrderTree Int)+-- > [10,20,3,42,5]+--+-- You would typically define instances for additional common type classes,+-- such as 'Eq', 'Ord', 'Show', etc.++------------------++-- $construction+--+-- #construction#+-- In order to be able to reason about how a given type of 'Applicative'+-- effects will be sequenced through a general 'Traversable' structure by its+-- 'traversable' and related methods, it is helpful to look more closely+-- at how a general 'traverse' method is implemented.  We'll look at how+-- general traversals are constructed primarily with a view to being able+-- to predict their behaviour as a user, even if you're not defining your+-- own 'Traversable' instances.+--+-- Traversable structures __@t a@__ are assembled incrementally from their+-- constituent parts, perhaps by prepending or appending individual elements of+-- type __@a@__, or, more generally, by recursively combining smaller composite+-- traversable building blocks that contain multiple such elements.+--+-- As in the [tree example](#tree) above, the components being combined are+-- typically pieced together by a suitable /constructor/, i.e. a function+-- taking two or more arguments that returns a composite value.+--+-- The 'traverse' method enriches simple incremental construction with+-- threading of 'Applicative' effects of some function __@g :: a -> f b@__.+--+-- The basic building blocks we'll use to model the construction of 'traverse'+-- are a hypothetical set of elementary functions, some of which may have+-- direct analogues in specific @Traversable@ structures.  For example, the+-- __@(':')@__ constructor is an analogue for lists of @prepend@ or the more+-- general @combine@.+--+-- > empty :: t a               -- build an empty container+-- > singleton :: a -> t a      -- build a one-element container+-- > prepend :: a -> t a -> t a -- extend by prepending a new initial element+-- > append  :: t a -> a -> t a -- extend by appending a new final element+-- > combine :: a1 -> a2 -> ... -> an -> t a -- combine multiple inputs+--+-- * An empty structure has no elements of type __@a@__, so there's nothing+--   to which __@g@__ can be applied, but since we need an output of type+--   __@f (t b)@__, we just use the 'pure' instance of __@f@__ to wrap an+--   empty of type __@t b@__:+--+--     > traverse _ (empty :: t a) = pure (empty :: t b)+--+--     With the List monad, /empty/ is __@[]@__, while with 'Maybe' it is+--     'Nothing'.  With __@Either e a@__ we have an /empty/ case for each+--     value of __@e@__:+--+--     > traverse _ (Left e :: Either e a) = pure $ (Left e :: Either e b)+--+-- * A singleton structure has just one element of type __@a@__, and+--   'traverse' can take that __@a@__, apply __@g :: a -> f b@__ getting an+--   __@f b@__, then __@fmap singleton@__ over that, getting an __@f (t b)@__+--   as required:+--+--     > traverse g (singleton a) = fmap singleton $ g a+--+--     Note that if __@f@__ is __@List@__ and __@g@__ returns multiple values+--     the result will be a list of multiple __@t b@__ singletons!+--+--     Since 'Maybe' and 'Either' are either empty or singletons, we have+--+--     > traverse _ Nothing = pure Nothing+--     > traverse g (Just a) = Just <$> g a+--+--     > traverse _ (Left e) = pure (Left e)+--     > traverse g (Right a) = Right <$> g a+--+--     For @List@, empty is __@[]@__ and @singleton@ is __@(:[])@__, so we have:+--+--     > traverse _ []  = pure []+--     > traverse g [a] = fmap (:[]) (g a)+--     >                = (:) <$> (g a) <*> traverse g []+--     >                = liftA2 (:) (g a) (traverse g [])+--+-- * When the structure is built by adding one more element via __@prepend@__+--   or __@append@__, traversal amounts to:+--+--     > traverse g (prepend a t0) = prepend <$> (g a) <*> traverse g t0+--     >                           = liftA2 prepend (g a) (traverse g t0)+--+--     > traverse g (append t0 a) = append <$> traverse g t0 <*> g a+--     >                          = liftA2 append (traverse g t0) (g a)+--+--     The origin of the combinatorial product when __@f@__ is @List@ should now+--     be apparent, when __@traverse g t0@__ has __@n@__ elements and __@g a@__+--     has __@m@__ elements, the /non-deterministic/ 'Applicative' instance of+--     @List@ will produce a result with __@m * n@__ elements.+--+-- * When combining larger building blocks, we again use __@('<*>')@__ to+--   combine the traversals of the components.  With bare elements __@a@__+--   mapped to __@f b@__ via __@g@__, and composite traversable+--   sub-structures transformed via __@traverse g@__:+--+--     > traverse g (combine a1 a2 ... an) =+--     >     combine <$> t1 <*> t2 <*> ... <*> tn+--     >   where+--     >      t1 = g a1          -- if a1 fills a slot of type @a@+--     >         = traverse g a1 -- if a1 is a traversable substructure+--     >      ... ditto for the remaining constructor arguments ...+--+-- The above definitions sequence the 'Applicative' effects of __@f@__ in the+-- expected order while producing results of the expected shape __@t@__.+--+-- For lists this becomes:+--+-- > traverse g [] = pure []+-- > traverse g (x:xs) = liftA2 (:) (g a) (traverse g xs)+--+-- The actual definition of 'traverse' for lists is an equivalent+-- right fold in order to facilitate list /fusion/.+--+-- > traverse g = foldr (\x r -> liftA2 (:) (g x) r) (pure [])++------------------++-- $advanced+--+-- #advanced#+-- In the sections below we'll examine some advanced choices of 'Applicative'+-- effects that give rise to very different transformations of @Traversable@+-- structures.+--+-- These examples cover the implementations of 'fmapDefault', 'foldMapDefault',+-- 'mapAccumL' and 'mapAccumR' functions illustrating the use of 'Identity',+-- 'Const' and stateful 'Applicative' effects.  The [ZipList](#ziplist) example+-- illustrates the use of a less-well known 'Applicative' instance for lists.+--+-- This is optional material, which is not essential to a basic understanding of+-- @Traversable@ structures.  If this is your first encounter with @Traversable@+-- structures, you can come back to these at a later date.++-- $coercion+--+-- #coercion#+-- Some of the examples make use of an advanced Haskell feature, namely+-- @newtype@ /coercion/.  This is done for two reasons:+--+-- * Use of 'coerce' makes it possible to avoid cluttering the code with+--   functions that wrap and unwrap /newtype/ terms, which at runtime are+--   indistinguishable from the underlying value.  Coercion is particularly+--   convenient when one would have to otherwise apply multiple newtype+--   constructors to function arguments, and then peel off multiple layers+--   of same from the function output.+--+-- * Use of 'coerce' can produce more efficient code, by reusing the original+--   value, rather than allocating space for a wrapped clone.+--+-- If you're not familiar with 'coerce', don't worry, it is just a shorthand+-- that, e.g., given:+--+-- > newtype Foo a = MkFoo { getFoo :: a }+-- > newtype Bar a = MkBar { getBar :: a }+-- > newtype Baz a = MkBaz { getBaz :: a }+-- > f :: Baz Int -> Bar (Foo String)+--+-- makes it possible to write:+--+-- > x :: Int -> String+-- > x = coerce f+--+-- instead of+--+-- > x = getFoo . getBar . f . MkBaz++------------------++-- $identity+--+-- #identity#+-- The simplest Applicative functor is 'Identity', which just wraps and unwraps+-- pure values and function application.  This allows us to define+-- 'fmapDefault':+--+-- > {-# LANGUAGE ScopedTypeVariables, TypeApplications #-}+-- > import Data.Coercible (coerce)+-- >+-- > fmapDefault :: forall t a b. Traversable t => (a -> b) -> t a -> t b+-- > fmapDefault = coerce (traverse @t @Identity @a @b)+--+-- The use of [coercion](#coercion) avoids the need to explicitly wrap and+-- unwrap terms via 'Identity' and 'runIdentity'.+--+-- As noted in [Overview](#overview), 'fmapDefault' can only be used to define+-- the requisite 'Functor' instance of a 'Traversable' structure when the+-- 'traverse' method is explicitly implemented.  An infinite loop would result+-- if in addition 'traverse' were defined in terms of 'sequenceA' and 'fmap'.++------------------++-- $stateful+--+-- #stateful#+-- Applicative functors that thread a changing state through a computation are+-- an interesting use-case for 'traverse'.  The 'mapAccumL' and 'mapAccumR'+-- functions in this module are each defined in terms of such traversals.+--+-- We first define a simplified (not a monad transformer) version of+-- 'Control.Monad.Trans.State.State' that threads a state __@s@__ through a+-- chain of computations left to right.  Its @('<*>')@ operator passes the+-- input state first to its left argument, and then the resulting state is+-- passed to its right argument, which returns the final state.+--+-- > newtype StateL s a = StateL { runStateL :: s -> (s, a) }+-- >+-- > instance Functor (StateL s) where+-- >     fmap f (StateL kx) = StateL $ \ s ->+-- >         let (s', x) = kx s in (s', f x)+-- >+-- > instance Applicative (StateL s) where+-- >     pure a = StateL $ \s -> (s, a)+-- >     (StateL kf) <*> (StateL kx) = StateL $ \ s ->+-- >         let { (s',  f) = kf s+-- >             ; (s'', x) = kx s' } in (s'', f x)+-- >     liftA2 f (StateL kx) (StateL ky) = StateL $ \ s ->+-- >         let { (s',  x) = kx s+-- >             ; (s'', y) = ky s' } in (s'', f x y)+--+-- With @StateL@, we can define 'mapAccumL' as follows:+--+-- > {-# LANGUAGE ScopedTypeVariables, TypeApplications #-}+-- > mapAccumL :: forall t s a b. Traversable t+-- >           => (s -> a -> (s, b)) -> s -> t a -> (s, t b)+-- > mapAccumL g s ts = coerce (traverse @t @(StateL s) @a @b) (flip g) ts s+--+-- The use of [coercion](#coercion) avoids the need to explicitly wrap and+-- unwrap __@newtype@__ terms.+--+-- The type of __@flip g@__ is coercible to __@a -> StateL b@__, which makes it+-- suitable for use with 'traverse'.  As part of the Applicative+-- [construction](#construction) of __@StateL (t b)@__ the state updates will+-- thread left-to-right along the sequence of elements of __@t a@__.+--+-- While 'mapAccumR' has a type signature identical to 'mapAccumL', it differs+-- in the expected order of evaluation of effects, which must take place+-- right-to-left.+--+-- For this we need a variant control structure @StateR@, which threads the+-- state right-to-left, by passing the input state to its right argument and+-- then using the resulting state as an input to its left argument:+--+-- > newtype StateR s a = StateR { runStateR :: s -> (s, a) }+-- >+-- > instance Functor (StateR s) where+-- >     fmap f (StateR kx) = StateR $ \s ->+-- >         let (s', x) = kx s in (s', f x)+-- >+-- > instance Applicative (StateR s) where+-- >     pure a = StateR $ \s -> (s, a)+-- >     (StateR kf) <*> (StateR kx) = StateR $ \ s ->+-- >         let { (s',  x) = kx s+-- >             ; (s'', f) = kf s' } in (s'', f x)+-- >     liftA2 f (StateR kx) (StateR ky) = StateR $ \ s ->+-- >         let { (s',  y) = ky s+-- >             ; (s'', x) = kx s' } in (s'', f x y)+--+-- With @StateR@, we can define 'mapAccumR' as follows:+--+-- > {-# LANGUAGE ScopedTypeVariables, TypeApplications #-}+-- > mapAccumR :: forall t s a b. Traversable t+-- >           => (s -> a -> (s, b)) -> s -> t a -> (s, t b)+-- > mapAccumR g s0 ts = coerce (traverse @t @(StateR s) @a @b) (flip g) ts s0+--+-- The use of [coercion](#coercion) avoids the need to explicitly wrap and+-- unwrap __@newtype@__ terms.+--+-- Various stateful traversals can be constructed from 'mapAccumL' and+-- 'mapAccumR' for suitable choices of @g@, or built directly along similar+-- lines.++------------------++-- $phantom+--+-- #phantom#+-- The 'Const' Functor enables applications of 'traverse' that summarise the+-- input structure to an output value without constructing any output values+-- of the same type or shape.+--+-- As noted [above](#overview), the @Foldable@ superclass constraint is+-- justified by the fact that it is possible to construct 'foldMap', 'foldr',+-- etc., from 'traverse'.  The technique used is useful in its own right, and+-- is explored below.+--+-- A key feature of folds is that they can reduce the input structure to a+-- summary value. Often neither the input structure nor a mutated clone is+-- needed once the fold is computed, and through list fusion the input may not+-- even have been memory resident in its entirety at the same time.+--+-- The 'traverse' method does not at first seem to be a suitable building block+-- for folds, because its return value __@f (t b)@__ appears to retain mutated+-- copies of the input structure.  But the presence of __@t b@__ in the type+-- signature need not mean that terms of type __@t b@__ are actually embedded+-- in __@f (t b)@__.  The simplest way to elide the excess terms is by basing+-- the Applicative functor used with 'traverse' on 'Const'.+--+-- Not only does __@Const a b@__ hold just an __@a@__ value, with the __@b@__+-- parameter merely a /phantom/ type, but when __@m@__ has a 'Monoid' instance,+-- __@Const m@__ is an 'Applicative' functor:+--+-- > import Data.Coerce (coerce)+-- > newtype Const a b = Const { getConst :: a } deriving (Eq, Ord, Show) -- etc.+-- > instance Functor (Const m) where fmap = const coerce+-- > instance Monoid m => Applicative (Const m) where+-- >    pure _   = Const mempty+-- >    (<*>)    = coerce (mappend :: m -> m -> m)+-- >    liftA2 _ = coerce (mappend :: m -> m -> m)+--+-- The use of [coercion](#coercion) avoids the need to explicitly wrap and+-- unwrap __@newtype@__ terms.+--+-- We can therefore define a specialisation of 'traverse':+--+-- > {-# LANGUAGE ScopedTypeVariables, TypeApplications #-}+-- > traverseC :: forall t a m. (Monoid m, Traversable t)+-- >           => (a -> Const m ()) -> t a -> Const m (t ())+-- > traverseC = traverse @t @(Const m) @a @()+--+-- For which the Applicative [construction](#construction) of 'traverse'+-- leads to:+--+-- prop> null ts ==> traverseC g ts = Const mempty+-- prop> traverseC g (prepend x xs) = Const (g x) <> traverseC g xs+--+-- In other words, this makes it possible to define:+--+-- > {-# LANGUAGE ScopedTypeVariables, TypeApplications #-}+-- > foldMapDefault :: forall t a m. (Monoid m, Traversable t) => (a -> m) -> t a -> m+-- > foldMapDefault = coerce (traverse @t @(Const m) @a @())+--+-- Which is sufficient to define a 'Foldable' superclass instance:+--+-- The use of [coercion](#coercion) avoids the need to explicitly wrap and+-- unwrap __@newtype@__ terms.+--+-- > instance Traversable t => Foldable t where foldMap = foldMapDefault+--+-- It may however be instructive to also directly define candidate default+-- implementations of 'foldr' and 'foldl'', which take a bit more machinery+-- to construct:+--+-- > {-# LANGUAGE ScopedTypeVariables, TypeApplications #-}+-- > import Data.Coerce (coerce)+-- > import Data.Functor.Const (Const(..))+-- > import Data.Semigroup (Dual(..), Endo(..))+-- > import GHC.Exts (oneShot)+-- >+-- > foldrDefault :: forall t a b. Traversable t+-- >              => (a -> b -> b) -> b -> t a -> b+-- > foldrDefault f z = \t ->+-- >     coerce (traverse @t @(Const (Endo b)) @a @()) f t z+-- >+-- > foldlDefault' :: forall t a b. Traversable t => (b -> a -> b) -> b -> t a -> b+-- > foldlDefault' f z = \t ->+-- >     coerce (traverse @t @(Const (Dual (Endo b))) @a @()) f' t z+-- >   where+-- >     f' :: a -> b -> b+-- >     f' a = oneShot $ \ b -> b `seq` f b a+--+-- In the above we're using the __@'Data.Monoid.Endo' b@__ 'Monoid' and its+-- 'Dual' to compose a sequence of __@b -> b@__ accumulator updates in either+-- left-to-right or right-to-left order.+--+-- The use of 'seq' in the definition of __@foldlDefault'@__ ensures strictness+-- in the accumulator.+--+-- The use of [coercion](#coercion) avoids the need to explicitly wrap and+-- unwrap __@newtype@__ terms.+--+-- The 'GHC.Exts.oneShot' function gives a hint to the compiler that aids in+-- correct optimisation of lambda terms that fire at most once (for each+-- element __@a@__) and so should not try to pre-compute and re-use+-- subexpressions that pay off only on repeated execution.  Otherwise, it is+-- just the identity function.++------------------++-- $ziplist+--+-- #ziplist#+-- As a warm-up for looking at the 'ZipList' 'Applicative' functor, we'll first+-- look at a simpler analogue.  First define a fixed width 2-element @Vec2@+-- type, whose 'Applicative' instance combines a pair of functions with a pair of+-- values by applying each function to the corresponding value slot:+--+-- > data Vec2 a = Vec2 a a+-- > instance Functor Vec2 where+-- >     fmap f (Vec2 a b) = Vec2 (f a) (f b)+-- > instance Applicative Vec2 where+-- >     pure x = Vec2 x x+-- >     liftA2 f (Vec2 a b) (Vec2 p q) = Vec2 (f a p) (f b q)+-- > instance Foldable Vec2 where+-- >     foldr f z (Vec2 a b) = f a (f b z)+-- >     foldMap f (Vec2 a b) = f a <> f b+-- > instance Traversable Vec2 where+-- >     traverse f (Vec2 a b) = Vec2 <$> f a <*> f b+--+-- Along with a similar definition for fixed width 3-element vectors:+--+-- > data Vec3 a = Vec3 a a a+-- > instance Functor Vec3 where+-- >     fmap f (Vec3 x y z) = Vec3 (f x) (f y) (f z)+-- > instance Applicative Vec3 where+-- >     pure x = Vec3 x x x+-- >     liftA2 f (Vec3 p q r) (Vec3 x y z) = Vec3 (f p x) (f q y) (f r z)+-- > instance Foldable Vec3 where+-- >     foldr f z (Vec3 a b c) = f a (f b (f c z))+-- >     foldMap f (Vec3 a b c) = f a <> f b <> f c+-- > instance Traversable Vec3 where+-- >     traverse f (Vec3 a b c) = Vec3 <$> f a <*> f b <*> f c+--+-- With the above definitions, @'sequenceA'@ (same as @'traverse' 'id'@) acts+-- as a /matrix transpose/ operation on @Vec2 (Vec3 Int)@ producing a+-- corresponding @Vec3 (Vec2 Int)@:+--+-- Let __@t = Vec2 (Vec3 1 2 3) (Vec3 4 5 6)@__ be our 'Traversable' structure,+-- and __@g = id :: Vec3 Int -> Vec3 Int@__ be the function used to traverse+-- __@t@__.  We then have:+--+-- > traverse g t = Vec2 <$> (Vec3 1 2 3) <*> (Vec3 4 5 6)+-- >              = Vec3 (Vec2 1 4) (Vec2 2 5) (Vec2 3 6)+--+-- This construction can be generalised from fixed width vectors to variable+-- length lists via 'Control.Applicative.ZipList'.  This gives a transpose+-- operation that works well for lists of equal length.  If some of the lists+-- are longer than others, they're truncated to the longest common length.+--+-- We've already looked at the standard 'Applicative' instance of @List@ for+-- which applying __@m@__ functions __@f1, f2, ..., fm@__ to __@n@__ input+-- values __@a1, a2, ..., an@__ produces __@m * n@__ outputs:+--+-- >>> :set -XTupleSections+-- >>> [("f1",), ("f2",), ("f3",)] <*> [1,2]+-- [("f1",1),("f1",2),("f2",1),("f2",2),("f3",1),("f3",2)]+--+-- There are however two more common ways to turn lists into 'Applicative'+-- control structures.  The first is via __@'Const' [a]@__, since lists are+-- monoids under concatenation, and we've already seen that __@'Const' m@__ is+-- an 'Applicative' functor when __@m@__ is a 'Monoid'.  The second, is based+-- on 'Data.List.zipWith', and is called 'Control.Applicative.ZipList':+--+-- > {-# LANGUAGE GeneralizedNewtypeDeriving #-}+-- > newtype ZipList a = ZipList { getZipList :: [a] }+-- >     deriving (Show, Eq, ..., Functor)+-- >+-- > instance Applicative ZipList where+-- >     liftA2 f (ZipList xs) (ZipList ys) = ZipList $ zipWith f xs ys+-- >     pure x = repeat x+--+-- The 'liftA2' definition is clear enough, instead of applying __@f@__ to each+-- pair __@(x, y)@__ drawn independently from the __@xs@__ and __@ys@__, only+-- corresponding pairs at each index in the two lists are used.+--+-- The definition of 'pure' may look surprising, but it is needed to ensure+-- that the instance is lawful:+--+-- prop> liftA2 f (pure x) ys == fmap (f x) ys+--+-- Since __@ys@__ can have any length, we need to provide an infinite supply+-- of __@x@__ values in __@pure x@__ in order to have a value to pair with+-- each element __@y@__.+--+-- When 'Control.Applicative.ZipList' is the 'Applicative' functor used in the+-- [construction](#construction) of a traversal, a ZipList holding a partially+-- built structure with __@m@__ elements is combined with a component holding+-- __@n@__ elements via 'zipWith', resulting in __@min m n@__ outputs!+--+-- Therefore 'traverse' with __@g :: a -> ZipList b@__ will produce a @ZipList@+-- of __@t b@__ structures whose element count is the minimum length of the+-- ZipLists __@g a@__ with __@a@__ ranging over the elements of __@t@__.  When+-- __@t@__ is empty, the length is infinite (as expected for a minimum of an+-- empty set).+--+-- If the structure __@t@__ holds values of type __@ZipList a@__, we can use+-- the identity function __@id :: ZipList a -> ZipList a@__ for the first+-- argument of 'traverse':+--+-- > traverse (id :: ZipList a -> ZipList a) :: t (ZipList a) -> ZipList (t a)+--+-- The number of elements in the output @ZipList@ will be the length of the+-- shortest @ZipList@ element of __@t@__.  Each output __@t a@__ will have the+-- /same shape/ as the input __@t (ZipList a)@__, i.e. will share its number of+-- elements.+--+-- If we think of the elements of __@t (ZipList a)@__ as its rows, and the+-- elements of each individual @ZipList@ as the columns of that row, we see+-- that our traversal implements a /transpose/ operation swapping the rows+-- and columns of __@t@__, after first truncating all the rows to the column+-- count of the shortest one.+--+-- Since in fact __@'traverse' id@__ is just 'sequenceA' the above boils down+-- to a rather concise definition of /transpose/, with [coercion](#coercion)+-- used to implicitly wrap and unwrap the @ZipList@ @newtype@ as needed, giving+-- a function that operates on a list of lists:+--+-- >>> :set -XScopedTypeVariables+-- >>> import Control.Applicative (ZipList(..))+-- >>> import Data.Coerce (coerce)+-- >>>+-- >>> :{+-- >>> let+-- >>>     transpose :: forall a. [[a]] -> [[a]]+-- >>>     transpose = coerce (sequenceA :: [ZipList a] -> ZipList [a])+-- >>> in transpose [[1,2,3],[4..],[7..]]+-- >>> :}+-- [[1,4,7],[2,5,8],[3,6,9]]+--+-- The use of [coercion](#coercion) avoids the need to explicitly wrap and+-- unwrap __@ZipList@__ terms.++------------------++-- $laws+--+-- #laws#+-- A definition of 'traverse' must satisfy the following laws:+--+-- [Naturality]+--   @t . 'traverse' f = 'traverse' (t . f)@+--   for every applicative transformation @t@+--+-- [Identity]+--   @'traverse' 'Identity' = 'Identity'@+--+-- [Composition]+--   @'traverse' ('Data.Functor.Compose.Compose' . 'fmap' g . f)+--     = 'Data.Functor.Compose.Compose' . 'fmap' ('traverse' g) . 'traverse' f@+--+-- A definition of 'sequenceA' must satisfy the following laws:+--+-- [Naturality]+--   @t . 'sequenceA' = 'sequenceA' . 'fmap' t@+--   for every applicative transformation @t@+--+-- [Identity]+--   @'sequenceA' . 'fmap' 'Identity' = 'Identity'@+--+-- [Composition]+--   @'sequenceA' . 'fmap' 'Data.Functor.Compose.Compose'+--     = 'Data.Functor.Compose.Compose' . 'fmap' 'sequenceA' . 'sequenceA'@+--+-- where an /applicative transformation/ is a function+--+-- @t :: (Applicative f, Applicative g) => f a -> g a@+--+-- preserving the 'Applicative' operations, i.e.+--+-- @+-- t ('pure' x) = 'pure' x+-- t (f '<*>' x) = t f '<*>' t x+-- @+--+-- and the identity functor 'Identity' and composition functors+-- 'Data.Functor.Compose.Compose' are from "Data.Functor.Identity" and+-- "Data.Functor.Compose".+--+-- A result of the naturality law is a purity law for 'traverse'+--+-- @'traverse' 'pure' = 'pure'@+--+-- The superclass instances should satisfy the following:+--+--  * In the 'Functor' instance, 'fmap' should be equivalent to traversal+--    with the identity applicative functor ('fmapDefault').+--+--  * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be+--    equivalent to traversal with a constant applicative functor+--    ('foldMapDefault').+--+-- Note: the 'Functor' superclass means that (in GHC) Traversable structures+-- cannot impose any constraints on the element type.  A Haskell implementation+-- that supports constrained functors could make it possible to define+-- constrained @Traversable@ structures.++------------------++-- $also+--+--  * \"The Essence of the Iterator Pattern\",+--    by Jeremy Gibbons and Bruno Oliveira,+--    in /Mathematically-Structured Functional Programming/, 2006, online at+--    <http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/#iterator>.+--+--  * \"Applicative Programming with Effects\",+--    by Conor McBride and Ross Paterson,+--    /Journal of Functional Programming/ 18:1 (2008) 1-13, online at+--    <http://www.soi.city.ac.uk/~ross/papers/Applicative.html>.+--+--  * \"An Investigation of the Laws of Traversals\",+--    by Mauro Jaskelioff and Ondrej Rypacek,+--    in /Mathematically-Structured Functional Programming/, 2012, online at+--    <http://arxiv.org/pdf/1202.2919>.
+ src/Data/Tuple.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Tuple+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Functions associated with the tuple data types.+--++module Data.Tuple+    (Solo(..),+     getSolo,+     fst,+     snd,+     curry,+     uncurry,+     swap+     ) where++import GHC.Internal.Data.Tuple
+ src/Data/Type/Bool.hs view
@@ -0,0 +1,25 @@+{-# LANGUAGE Safe #-}++{-# LANGUAGE ExplicitNamespaces #-}++-- |+--+-- Module      :  Data.Type.Bool+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  not portable+--+-- Basic operations on type-level Booleans.+--+-- @since 4.7.0.0++module Data.Type.Bool+    (If,+     type (&&),+     type (||),+     Not+     ) where++import GHC.Internal.Data.Type.Bool
+ src/Data/Type/Coercion.hs view
@@ -0,0 +1,24 @@+-- |+--+-- Module      :  Data.Type.Coercion+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  not portable+--+-- Definition of representational equality ('Coercion').+--+-- @since 4.7.0.0++module Data.Type.Coercion+    (Coercion(..),+     coerceWith,+     gcoerceWith,+     sym,+     trans,+     repr,+     TestCoercion(..)+     ) where++import GHC.Internal.Data.Type.Coercion
+ src/Data/Type/Equality.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE Safe #-}++{-# LANGUAGE ExplicitNamespaces #-}++-- |+--+-- Module      :  Data.Type.Equality+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  not portable+--+-- Definition of propositional equality @(':~:')@. Pattern-matching on a variable+-- of type @(a ':~:' b)@ produces a proof that @a '~' b@.+--+-- @since 4.7.0.0++module Data.Type.Equality+    (-- *  The equality types+     type (~),+     type (~~),+     (:~:)(..),+     (:~~:)(..),+     -- *  Working with equality+     sym,+     trans,+     castWith,+     gcastWith,+     apply,+     inner,+     outer,+     -- *  Inferring equality from other types+     TestEquality(..),+     -- *  Boolean type-level equality+     type (==)+     ) where++import GHC.Internal.Data.Type.Equality
+ src/Data/Type/Ord.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE Safe #-}++{-# LANGUAGE ExplicitNamespaces #-}++-- |+--+-- Module      :  Data.Type.Ord+-- License     :  BSD-style (see the LICENSE file in the distribution)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  not portable+--+-- Basic operations on type-level Orderings.+--+-- @since 4.16.0.0++module Data.Type.Ord+    (Compare,+     OrderingI(..),+     type (<=),+     type (<=?),+     type (>=),+     type (>=?),+     type (>),+     type (>?),+     type (<),+     type (<?),+     Max,+     Min,+     OrdCond+     ) where++import GHC.Internal.Data.Type.Ord
+ src/Data/Typeable.hs view
@@ -0,0 +1,88 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Typeable+-- Copyright   :  (c) The University of Glasgow, CWI 2001--2004+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The 'Typeable' class reifies types to some extent by associating type+-- representations to types. These type representations can be compared,+-- and one can in turn define a type-safe cast operation. To this end,+-- an unsafe cast is guarded by a test for type (representation)+-- equivalence. The module "Data.Dynamic" uses Typeable for an+-- implementation of dynamics. The module "Data.Data" uses Typeable+-- and type-safe cast (but not dynamics) to support the \"Scrap your+-- boilerplate\" style of generic programming.+--+-- == Compatibility Notes+--+-- Since GHC 8.2, GHC has supported type-indexed type representations.+-- "Data.Typeable" provides type representations which are qualified over this+-- index, providing an interface very similar to the "Typeable" notion seen in+-- previous releases. For the type-indexed interface, see "Type.Reflection".+--+-- Since GHC 7.10, all types automatically have 'Typeable' instances derived.+-- This is in contrast to previous releases where 'Typeable' had to be+-- explicitly derived using the @DeriveDataTypeable@ language extension.+--+-- Since GHC 7.8, 'Typeable' is poly-kinded. The changes required for this might+-- break some old programs involving 'Typeable'. More details on this, including+-- how to fix your code, can be found on the+-- <https://gitlab.haskell.org/ghc/ghc/wikis/ghc-kinds/poly-typeable PolyTypeable wiki page>+--++module Data.Typeable+    (-- *  The Typeable class+     Typeable,+     typeOf,+     typeRep,+     -- *  Propositional equality+     (:~:)(Refl),+     (:~~:)(HRefl),+     -- *  Type-safe cast+     cast,+     eqT,+     heqT,+     decT,+     hdecT,+     gcast,+     -- *  Generalized casts for higher-order kinds+     gcast1,+     gcast2,+     -- *  A canonical proxy type+     Proxy(..),+     -- *  Type representations+     TypeRep,+     rnfTypeRep,+     showsTypeRep,+     mkFunTy,+     -- *  Observing type representations+     funResultTy,+     splitTyConApp,+     typeRepArgs,+     typeRepTyCon,+     typeRepFingerprint,+     -- *  Type constructors+     TyCon,+     tyConPackage,+     tyConModule,+     tyConName,+     rnfTyCon,+     tyConFingerprint,+     -- *  For backwards compatibility+     typeOf1,+     typeOf2,+     typeOf3,+     typeOf4,+     typeOf5,+     typeOf6,+     typeOf7,+     trLiftedRep+     ) where++import GHC.Internal.Data.Typeable
+ src/Data/Unique.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Unique+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable+--+-- An abstract interface to a unique symbol generator.+--++module Data.Unique+    (-- *  Unique objects+     Unique,+     newUnique,+     hashUnique+     ) where++import GHC.Internal.Data.Unique
+ src/Data/Version.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  Data.Version+-- Copyright   :  (c) The University of Glasgow 2004+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (local universal quantification in ReadP)+--+-- A general API for representation and manipulation of versions.+--+-- Versioning schemes are many and varied, so the version+-- representation provided by this library is intended to be a+-- compromise between complete generality, where almost no common+-- functionality could reasonably be provided, and fixing a particular+-- versioning scheme, which would probably be too restrictive.+--+-- So the approach taken here is to provide a representation which+-- subsumes many of the versioning schemes commonly in use, and we+-- provide implementations of 'Eq', 'Ord' and conversion to\/from 'String'+-- which will be appropriate for some applications, but not all.+--++module Data.Version (+        -- * The @Version@ type+        Version(..),+        -- * A concrete representation of @Version@+        showVersion, parseVersion,+        -- * Constructor function+        makeVersion+      ) where++import GHC.Internal.Data.Version
+ src/Data/Void.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Copyright   :  (C) 2008-2014 Edward Kmett+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  Edward Kmett <ekmett@gmail.com>+-- Stability   :  provisional+-- Portability :  portable+--+-- A logically uninhabited data type, used to indicate that a given+-- term should not exist.+--+-- @since 4.8.0.0++module Data.Void+    (Void,+     absurd,+     vacuous+     ) where++import GHC.Internal.Data.Void
+ src/Data/Word.hs view
@@ -0,0 +1,62 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Data.Word+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Unsigned integer types.+--++module Data.Word+    (-- *  Unsigned integral types+     Word,+     Word8,+     Word16,+     Word32,+     Word64,+     -- *  byte swapping+     byteSwap16,+     byteSwap32,+     byteSwap64,+     -- *  bit reversal+     bitReverse8,+     bitReverse16,+     bitReverse32,+     bitReverse64,+     -- *  Notes+     -- $notes+     ) where++import GHC.Internal.Word++{- $notes++* All arithmetic is performed modulo 2^n, where n is the number of+  bits in the type.  One non-obvious consequence of this is that 'Prelude.negate'+  should /not/ raise an error on negative arguments.++* For coercing between any two integer types, use+  'Prelude.fromIntegral', which is specialized for all the+  common cases so should be fast enough.  Coercing word types to and+  from integer types preserves representation, not sign.++* An unbounded size unsigned integer type is available with+  'Numeric.Natural.Natural'.++* The rules that hold for 'Prelude.Enum' instances over a bounded type+  such as 'Prelude.Int' (see the section of the Haskell report dealing+  with arithmetic sequences) also hold for the 'Prelude.Enum' instances+  over the various 'Word' types defined here.++* Right and left shifts by amounts greater than or equal to the width+  of the type result in a zero result.  This is contrary to the+  behaviour in C, which is undefined; a common interpretation is to+  truncate the shift count to the width of the type, for example @1 \<\<+  32 == 1@ in some C implementations.+-}
+ src/Debug/Trace.hs view
@@ -0,0 +1,95 @@+-- |+--+-- Module      :  Debug.Trace+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Functions for tracing and monitoring execution.+--+-- These can be useful for investigating bugs or performance problems.+-- They should /not/ be used in production code.+--++module Debug.Trace+    (-- * Tracing+     -- $tracing+     trace,+     traceId,+     traceShow,+     traceShowId,+     traceWith,+     traceShowWith,+     traceStack,+     traceIO,+     traceM,+     traceShowM,+     putTraceMsg,++     -- * Eventlog tracing+     -- $eventlog_tracing+     traceEvent,+     traceEventWith,+     traceEventIO,+     flushEventLog,++     -- * Execution phase markers+     -- $markers+     traceMarker,+     traceMarkerIO,+     ) where++import GHC.Internal.Debug.Trace++-- $setup+-- >>> import Prelude++-- $tracing+--+-- The 'trace', 'traceShow' and 'traceIO' functions print messages to an output+-- stream. They are intended for \"printf debugging\", that is: tracing the flow+-- of execution and printing interesting values.+--+-- All these functions evaluate the message completely before printing+-- it; so if the message is not fully defined, none of it will be+-- printed.+--+-- The usual output stream is 'GHC.Internal.System.IO.stderr'. For Windows GUI applications+-- (that have no stderr) the output is directed to the Windows debug console.+-- Some implementations of these functions may decorate the string that\'s+-- output to indicate that you\'re tracing.++-- $eventlog_tracing+--+-- Eventlog tracing is a performance profiling system. These functions emit+-- extra events into the eventlog. In combination with eventlog profiling+-- tools these functions can be used for monitoring execution and+-- investigating performance problems.+--+-- Currently only GHC provides eventlog profiling, see the GHC user guide for+-- details on how to use it. These function exists for other Haskell+-- implementations but no events are emitted. Note that the string message is+-- always evaluated, whether or not profiling is available or enabled.++-- $markers+--+-- When looking at a profile for the execution of a program we often want to+-- be able to mark certain points or phases in the execution and see that+-- visually in the profile.+--+-- For example, a program might have several distinct phases with different+-- performance or resource behaviour in each phase. To properly interpret the+-- profile graph we really want to see when each phase starts and ends.+--+-- Markers let us do this: we can annotate the program to emit a marker at+-- an appropriate point during execution and then see that in a profile.+--+-- Currently this feature is only supported in GHC by the eventlog tracing+-- system, but in future it may also be supported by the heap profiling or+-- other profiling tools. These function exists for other Haskell+-- implementations but they have no effect. Note that the string message is+-- always evaluated, whether or not profiling is available or enabled.+
+ src/Foreign.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- A collection of data types, classes, and functions for interfacing+-- with another programming language.+--++module Foreign+        ( module Data.Bits+        , module Data.Int+        , module Data.Word+        , module Foreign.Ptr+        , module Foreign.ForeignPtr+        , module Foreign.StablePtr+        , module Foreign.Storable+        , module Foreign.Marshal+        ) where++import Data.Bits+import Data.Int+import Data.Word+import Foreign.Ptr+import Foreign.ForeignPtr+import Foreign.StablePtr+import Foreign.Storable+import Foreign.Marshal
+ src/Foreign/C.hs view
@@ -0,0 +1,24 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.C+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Bundles the C specific FFI library functionality+--++module Foreign.C+    (module Foreign.C.Types,+     module Foreign.C.String,+     module Foreign.C.Error+     ) where++import Foreign.C.Types+import Foreign.C.String+import Foreign.C.Error
+ src/Foreign/C/ConstPtr.hs view
@@ -0,0 +1,21 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.C.ConstPtr+-- Copyright   :  (c) GHC Developers+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- This module provides typed @const@ pointers to foreign data. It is part+-- of the Foreign Function Interface (FFI).+--++module Foreign.C.ConstPtr+    (ConstPtr(..)+     ) where++import GHC.Internal.Foreign.C.ConstPtr
+ src/Foreign/C/Error.hs view
@@ -0,0 +1,154 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.C.Error+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- C-specific Marshalling support: Handling of C \"errno\" error codes.+--++module Foreign.C.Error+    (-- *  Haskell representations of @errno@ values+     Errno(..),+     -- **  Common @errno@ symbols+     -- | Different operating systems and\/or C libraries often support+     -- different values of @errno@. This module defines the common values,+     -- but due to the open definition of 'Errno' users may add definitions+     -- which are not predefined.+     eOK,+     e2BIG,+     eACCES,+     eADDRINUSE,+     eADDRNOTAVAIL,+     eADV,+     eAFNOSUPPORT,+     eAGAIN,+     eALREADY,+     eBADF,+     eBADMSG,+     eBADRPC,+     eBUSY,+     eCHILD,+     eCOMM,+     eCONNABORTED,+     eCONNREFUSED,+     eCONNRESET,+     eDEADLK,+     eDESTADDRREQ,+     eDIRTY,+     eDOM,+     eDQUOT,+     eEXIST,+     eFAULT,+     eFBIG,+     eFTYPE,+     eHOSTDOWN,+     eHOSTUNREACH,+     eIDRM,+     eILSEQ,+     eINPROGRESS,+     eINTR,+     eINVAL,+     eIO,+     eISCONN,+     eISDIR,+     eLOOP,+     eMFILE,+     eMLINK,+     eMSGSIZE,+     eMULTIHOP,+     eNAMETOOLONG,+     eNETDOWN,+     eNETRESET,+     eNETUNREACH,+     eNFILE,+     eNOBUFS,+     eNODATA,+     eNODEV,+     eNOENT,+     eNOEXEC,+     eNOLCK,+     eNOLINK,+     eNOMEM,+     eNOMSG,+     eNONET,+     eNOPROTOOPT,+     eNOSPC,+     eNOSR,+     eNOSTR,+     eNOSYS,+     eNOTBLK,+     eNOTCONN,+     eNOTDIR,+     eNOTEMPTY,+     eNOTSOCK,+     eNOTSUP,+     eNOTTY,+     eNXIO,+     eOPNOTSUPP,+     ePERM,+     ePFNOSUPPORT,+     ePIPE,+     ePROCLIM,+     ePROCUNAVAIL,+     ePROGMISMATCH,+     ePROGUNAVAIL,+     ePROTO,+     ePROTONOSUPPORT,+     ePROTOTYPE,+     eRANGE,+     eREMCHG,+     eREMOTE,+     eROFS,+     eRPCMISMATCH,+     eRREMOTE,+     eSHUTDOWN,+     eSOCKTNOSUPPORT,+     eSPIPE,+     eSRCH,+     eSRMNT,+     eSTALE,+     eTIME,+     eTIMEDOUT,+     eTOOMANYREFS,+     eTXTBSY,+     eUSERS,+     eWOULDBLOCK,+     eXDEV,+     -- **  'Errno' functions+     isValidErrno,+     getErrno,+     resetErrno,+     errnoToIOError,+     throwErrno,+     -- **  Guards for IO operations that may fail+     throwErrnoIf,+     throwErrnoIf_,+     throwErrnoIfRetry,+     throwErrnoIfRetry_,+     throwErrnoIfMinus1,+     throwErrnoIfMinus1_,+     throwErrnoIfMinus1Retry,+     throwErrnoIfMinus1Retry_,+     throwErrnoIfNull,+     throwErrnoIfNullRetry,+     throwErrnoIfRetryMayBlock,+     throwErrnoIfRetryMayBlock_,+     throwErrnoIfMinus1RetryMayBlock,+     throwErrnoIfMinus1RetryMayBlock_,+     throwErrnoIfNullRetryMayBlock,+     throwErrnoPath,+     throwErrnoPathIf,+     throwErrnoPathIf_,+     throwErrnoPathIfNull,+     throwErrnoPathIfMinus1,+     throwErrnoPathIfMinus1_+     ) where++import GHC.Internal.Foreign.C.Error
+ src/Foreign/C/String.hs view
@@ -0,0 +1,95 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  Foreign.C.String+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Utilities for primitive marshalling of C strings.+--+-- The marshalling converts each Haskell character, representing a Unicode+-- code point, to one or more bytes in a manner that, by default, is+-- determined by the current locale.  As a consequence, no guarantees+-- can be made about the relative length of a Haskell string and its+-- corresponding C string, and therefore all the marshalling routines+-- include memory allocation.  The translation between Unicode and the+-- encoding of the current locale may be lossy.+--++module Foreign.C.String (+  -- * C strings++  CString,+  CStringLen,++  -- ** Using a locale-dependent encoding++  -- | These functions are different from their @CAString@ counterparts+  -- in that they will use an encoding determined by the current locale,+  -- rather than always assuming ASCII.++  -- conversion of C strings into Haskell strings+  --+  peekCString,+  peekCStringLen,++  -- conversion of Haskell strings into C strings+  --+  newCString,+  newCStringLen,++  -- conversion of Haskell strings into C strings using temporary storage+  --+  withCString,+  withCStringLen,++  charIsRepresentable,++  -- ** Using 8-bit characters++  -- | These variants of the above functions are for use with C libraries+  -- that are ignorant of Unicode.  These functions should be used with+  -- care, as a loss of information can occur.++  castCharToCChar,+  castCCharToChar,++  castCharToCUChar,+  castCUCharToChar,+  castCharToCSChar,+  castCSCharToChar,++  peekCAString,+  peekCAStringLen,+  newCAString,+  newCAStringLen,+  withCAString,+  withCAStringLen,++  -- * C wide strings++  -- | These variants of the above functions are for use with C libraries+  -- that encode Unicode using the C @wchar_t@ type in a system-dependent+  -- way.  The only encodings supported are+  --+  -- * UTF-32 (the C compiler defines @__STDC_ISO_10646__@), or+  --+  -- * UTF-16 (as used on Windows systems).++  CWString,+  CWStringLen,++  peekCWString,+  peekCWStringLen,+  newCWString,+  newCWStringLen,+  withCWString,+  withCWStringLen,++  ) where++import GHC.Internal.Foreign.C.String
+ src/Foreign/C/Types.hs view
@@ -0,0 +1,84 @@+-- |+--+-- Module      :  Foreign.C.Types+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Mapping of C types to corresponding Haskell types.+--++module Foreign.C.Types+    (-- *  Representations of C types+     -- $ctypes+     -- **  #platform# Platform differences+     -- |  This module contains platform specific information about types.+     -- __/As such, the types presented on this page reflect the/__+     -- __/platform on which the documentation was generated and may/__+     -- __/not coincide with the types on your platform./__+     -- **  Integral types+     -- |  These types are represented as @newtype@s of+     -- types in "Data.Int" and "Data.Word", and are instances of+     -- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',+     -- 'Prelude.Show', 'Prelude.Enum', 'Data.Typeable.Typeable',+     -- 'Storable', 'Prelude.Bounded', 'Prelude.Real', 'Prelude.Integral'+     -- and 'Bits'.+     CChar(..),+     CSChar(..),+     CUChar(..),+     CShort(..),+     CUShort(..),+     CInt(..),+     CUInt(..),+     CLong(..),+     CULong(..),+     CPtrdiff(..),+     CSize(..),+     CWchar(..),+     CSigAtomic(..),+     CLLong(..),+     CULLong(..),+     CBool(..),+     CIntPtr(..),+     CUIntPtr(..),+     CIntMax(..),+     CUIntMax(..),+     -- **  Numeric types+     -- |  These types are represented as @newtype@s of basic+     -- foreign types, and are instances of+     -- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',+     -- 'Prelude.Show', 'Prelude.Enum', 'Data.Typeable.Typeable' and+     -- 'Storable'.+     CClock(..),+     CTime(..),+     CUSeconds(..),+     CSUSeconds(..),+     -- |  To convert 'CTime' to 'Data.Time.UTCTime', use the following:+     --+     -- > \t -> posixSecondsToUTCTime (realToFrac t :: POSIXTime)++     -- **  Floating types+     -- |  These types are represented as @newtype@s of+     -- 'Prelude.Float' and 'Prelude.Double', and are instances of+     -- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',+     -- 'Prelude.Show', 'Prelude.Enum', 'Data.Typeable.Typeable', 'Storable',+     -- 'Prelude.Real', 'Prelude.Fractional', 'Prelude.Floating',+     -- 'Prelude.RealFrac' and 'Prelude.RealFloat'. That does mean+     -- that `CFloat`'s (respectively `CDouble`'s) instances of+     -- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num' and+     -- 'Prelude.Fractional' are as badly behaved as `Prelude.Float`'s+     -- (respectively `Prelude.Double`'s).+     CFloat(..),+     CDouble(..),+     -- XXX GHC doesn't support CLDouble yet+     -- , CLDouble(..)+     -- **  Other types+     CFile,+     CFpos,+     CJmpBuf+     ) where++import GHC.Internal.Foreign.C.Types
+ src/Foreign/Concurrent.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Concurrent+-- Copyright   :  (c) The University of Glasgow 2003+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  non-portable (requires concurrency)+--+-- FFI datatypes and operations that use or require concurrency (GHC only).+--++module Foreign.Concurrent+    (-- *  Concurrency-based 'ForeignPtr' operations+     -- |  These functions generalize their namesakes in the portable+     -- "Foreign.ForeignPtr" module by allowing arbitrary 'IO' actions+     -- as finalizers.  These finalizers necessarily run in a separate+     -- thread, cf. /Destructors, Finalizers and Synchronization/,+     -- by Hans Boehm, /POPL/, 2003.+     newForeignPtr,+     addForeignPtrFinalizer+     ) where++import GHC.Internal.Foreign.Concurrent
+ src/Foreign/ForeignPtr.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.ForeignPtr+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- The 'ForeignPtr' type and operations.  This module is part of the+-- Foreign Function Interface (FFI) and will usually be imported via+-- the "Foreign" module.+--+-- For non-portable support of Haskell finalizers, see the+-- "Foreign.Concurrent" module.+--++module Foreign.ForeignPtr+    (-- *  Finalised data pointers+     ForeignPtr,+     FinalizerPtr,+     FinalizerEnvPtr,+     -- **  Basic operations+     newForeignPtr,+     newForeignPtr_,+     addForeignPtrFinalizer,+     newForeignPtrEnv,+     addForeignPtrFinalizerEnv,+     withForeignPtr,+     finalizeForeignPtr,+     -- **  Low-level operations+     touchForeignPtr,+     castForeignPtr,+     plusForeignPtr,+     -- **  Allocating managed memory+     mallocForeignPtr,+     mallocForeignPtrBytes,+     mallocForeignPtrArray,+     mallocForeignPtrArray0+     ) where++import GHC.Internal.Foreign.ForeignPtr
+ src/Foreign/ForeignPtr/Safe.hs view
@@ -0,0 +1,44 @@+{-# LANGUAGE Trustworthy #-}++-- |+--+-- Module      :  Foreign.ForeignPtr.Safe+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- The 'ForeignPtr' type and operations.  This module is part of the+-- Foreign Function Interface (FFI) and will usually be imported via+-- the "Foreign" module.+--+-- Safe API Only.+--++module Foreign.ForeignPtr.Safe+    {-# DEPRECATED "Safe is now the default, please use GHC.Internal.Foreign.ForeignPtr instead" #-}+    (-- *  Finalised data pointers+     ForeignPtr,+     FinalizerPtr,+     FinalizerEnvPtr,+     -- **  Basic operations+     newForeignPtr,+     newForeignPtr_,+     addForeignPtrFinalizer,+     newForeignPtrEnv,+     addForeignPtrFinalizerEnv,+     withForeignPtr,+     finalizeForeignPtr,+     -- **  Low-level operations+     touchForeignPtr,+     castForeignPtr,+     -- **  Allocating managed memory+     mallocForeignPtr,+     mallocForeignPtrBytes,+     mallocForeignPtrArray,+     mallocForeignPtrArray0+     ) where++import GHC.Internal.Foreign.ForeignPtr.Imp
+ src/Foreign/ForeignPtr/Unsafe.hs view
@@ -0,0 +1,23 @@+-- |+--+-- Module      :  Foreign.ForeignPtr.Unsafe+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- The 'ForeignPtr' type and operations.  This module is part of the+-- Foreign Function Interface (FFI) and will usually be imported via+-- the "Foreign" module.+--+-- Unsafe API Only.+--++module Foreign.ForeignPtr.Unsafe+    (-- **  Unsafe low-level operations+     unsafeForeignPtrToPtr+     ) where++import GHC.Internal.Foreign.ForeignPtr.Unsafe
+ src/Foreign/Marshal.hs view
@@ -0,0 +1,30 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Marshal+-- Copyright   :  (c) The FFI task force 2003+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Marshalling support+--++module Foreign.Marshal+    (-- |  The module "Foreign.Marshal.Safe" re-exports the other modules in the+     -- @Foreign.Marshal@ hierarchy (except for @Foreign.Marshal.Unsafe@):+     module Foreign.Marshal.Alloc,+     module Foreign.Marshal.Array,+     module Foreign.Marshal.Error,+     module Foreign.Marshal.Pool,+     module Foreign.Marshal.Utils+     ) where++import Foreign.Marshal.Alloc+import Foreign.Marshal.Array+import Foreign.Marshal.Error+import Foreign.Marshal.Pool+import Foreign.Marshal.Utils
+ src/Foreign/Marshal/Alloc.hs view
@@ -0,0 +1,61 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Marshal.Alloc+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- The module "Foreign.Marshal.Alloc" provides operations to allocate and+-- deallocate blocks of raw memory (i.e., unstructured chunks of memory+-- outside of the area maintained by the Haskell storage manager).  These+-- memory blocks are commonly used to pass compound data structures to+-- foreign functions or to provide space in which compound result values+-- are obtained from foreign functions.+--+-- If any of the allocation functions fails, an exception is thrown.+-- In some cases, memory exhaustion may mean the process is terminated.+-- If 'free' or 'reallocBytes' is applied to a memory area+-- that has been allocated with 'alloca' or 'allocaBytes', the+-- behaviour is undefined.  Any further access to memory areas allocated with+-- 'alloca' or 'allocaBytes', after the computation that was passed to+-- the allocation function has terminated, leads to undefined behaviour.  Any+-- further access to the memory area referenced by a pointer passed to+-- 'realloc', 'reallocBytes', or 'free' entails undefined+-- behaviour.+--+-- All storage allocated by functions that allocate based on a /size in bytes/+-- must be sufficiently aligned for any of the basic foreign types+-- that fits into the newly allocated storage. All storage allocated by+-- functions that allocate based on a specific type must be sufficiently+-- aligned for that type. Array allocation routines need to obey the same+-- alignment constraints for each array element.+--+-- The underlying implementation is wrapping the @<stdlib.h>@+-- @malloc@, @realloc@, and @free@.+-- In other words it should be safe to allocate using C-@malloc@,+-- and free memory with 'free' from this module.+--++module Foreign.Marshal.Alloc+    (-- *  Memory allocation+     -- **  Local allocation+     alloca,+     allocaBytes,+     allocaBytesAligned,+     -- **  Dynamic allocation+     malloc,+     mallocBytes,+     calloc,+     callocBytes,+     realloc,+     reallocBytes,+     free,+     finalizerFree+     ) where++import GHC.Internal.Foreign.Marshal.Alloc
+ src/Foreign/Marshal/Array.hs view
@@ -0,0 +1,50 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Marshal.Array+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Marshalling support: routines allocating, storing, and retrieving Haskell+-- lists that are represented as arrays in the foreign language+--++module Foreign.Marshal.Array+    (-- *  Marshalling arrays+     -- **  Allocation+     mallocArray,+     mallocArray0,+     allocaArray,+     allocaArray0,+     reallocArray,+     reallocArray0,+     callocArray,+     callocArray0,+     -- **  Marshalling+     peekArray,+     peekArray0,+     pokeArray,+     pokeArray0,+     -- **  Combined allocation and marshalling+     newArray,+     newArray0,+     withArray,+     withArray0,+     withArrayLen,+     withArrayLen0,+     -- **  Copying+     -- |  (argument order: destination, source)+     copyArray,+     moveArray,+     -- **  Finding the length+     lengthArray0,+     -- **  Indexing+     advancePtr+     ) where++import GHC.Internal.Foreign.Marshal.Array
+ src/Foreign/Marshal/Error.hs view
@@ -0,0 +1,26 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Marshal.Error+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Routines for testing return values and raising a 'userError' exception+-- in case of values indicating an error state.+--++module Foreign.Marshal.Error+    (throwIf,+     throwIf_,+     throwIfNeg,+     throwIfNeg_,+     throwIfNull,+     void+     ) where++import GHC.Internal.Foreign.Marshal.Error
+ src/Foreign/Marshal/Pool.hs view
@@ -0,0 +1,42 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Marshal.Pool+-- Copyright   :  (c) Sven Panne 2002-2004+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  sven.panne@aedion.de+-- Stability   :  provisional+-- Portability :  portable+--+-- This module contains support for pooled memory management. Under this scheme,+-- (re-)allocations belong to a given pool, and everything in a pool is+-- deallocated when the pool itself is deallocated. This is useful when+-- 'Foreign.Marshal.Alloc.alloca' with its implicit allocation and deallocation+-- is not flexible enough, but explicit uses of 'Foreign.Marshal.Alloc.malloc'+-- and 'free' are too awkward.+--++module Foreign.Marshal.Pool+    (-- *  Pool management+     Pool,+     newPool,+     freePool,+     withPool,+     -- *  (Re-)Allocation within a pool+     pooledMalloc,+     pooledMallocBytes,+     pooledRealloc,+     pooledReallocBytes,+     pooledMallocArray,+     pooledMallocArray0,+     pooledReallocArray,+     pooledReallocArray0,+     -- *  Combined allocation and marshalling+     pooledNew,+     pooledNewArray,+     pooledNewArray0+     ) where++import GHC.Internal.Foreign.Marshal.Pool
+ src/Foreign/Marshal/Safe.hs view
@@ -0,0 +1,32 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Marshal.Safe+-- Copyright   :  (c) The FFI task force 2003+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Marshalling support+--+-- Safe API Only.+--++module Foreign.Marshal.Safe+    (-- |  The module "Foreign.Marshal.Safe" re-exports the other modules in the+     -- @Foreign.Marshal@ hierarchy:+     module Foreign.Marshal.Alloc,+     module Foreign.Marshal.Array,+     module Foreign.Marshal.Error,+     module Foreign.Marshal.Pool,+     module Foreign.Marshal.Utils+     ) where++import Foreign.Marshal.Alloc+import Foreign.Marshal.Array+import Foreign.Marshal.Error+import Foreign.Marshal.Pool+import Foreign.Marshal.Utils
+ src/Foreign/Marshal/Unsafe.hs view
@@ -0,0 +1,19 @@+-- |+--+-- Module      :  Foreign.Marshal.Unsafe+-- Copyright   :  (c) The FFI task force 2003+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Marshalling support. Unsafe API.+--++module Foreign.Marshal.Unsafe+    (-- *  Unsafe functions+     unsafeLocalState+     ) where++import GHC.Internal.Foreign.Marshal.Unsafe
+ src/Foreign/Marshal/Utils.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Marshal.Utils+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Utilities for primitive marshaling+--++module Foreign.Marshal.Utils+    (-- *  General marshalling utilities+     -- **  Combined allocation and marshalling+     with,+     new,+     -- **  Marshalling of Boolean values (non-zero corresponds to 'True')+     fromBool,+     toBool,+     -- **  Marshalling of Maybe values+     maybeNew,+     maybeWith,+     maybePeek,+     -- **  Marshalling lists of storable objects+     withMany,+     -- **  Haskellish interface to memcpy and memmove+     -- |  (argument order: destination, source)++     copyBytes,+     moveBytes,+     -- **  Filling up memory area with required values+     fillBytes+     ) where++import GHC.Internal.Foreign.Marshal.Utils
+ src/Foreign/Ptr.hs view
@@ -0,0 +1,42 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Ptr+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- This module provides typed pointers to foreign data.  It is part+-- of the Foreign Function Interface (FFI) and will normally be+-- imported via the "Foreign" module.+--++module Foreign.Ptr+    (-- *  Data pointers+     Ptr,+     nullPtr,+     castPtr,+     plusPtr,+     alignPtr,+     minusPtr,+     -- *  Function pointers+     FunPtr,+     nullFunPtr,+     castFunPtr,+     castFunPtrToPtr,+     castPtrToFunPtr,+     freeHaskellFunPtr,+     -- *  Integral types with lossless conversion to and from pointers+     IntPtr(..),+     ptrToIntPtr,+     intPtrToPtr,+     WordPtr(..),+     ptrToWordPtr,+     wordPtrToPtr+     ) where++import GHC.Internal.Foreign.Ptr
+ src/Foreign/Safe.hs view
@@ -0,0 +1,38 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Safe+-- Copyright   :  (c) The FFI task force 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- A collection of data types, classes, and functions for interfacing+-- with another programming language.+--+-- Safe API Only.+--++module Foreign.Safe {-# DEPRECATED "Safe is now the default, please use Foreign instead" #-}+    (module Data.Bits,+     module Data.Int,+     module Data.Word,+     module Foreign.Ptr,+     module Foreign.ForeignPtr,+     module Foreign.StablePtr,+     module Foreign.Storable,+     module Foreign.Marshal+     ) where++import Data.Bits+import Data.Int+import Data.Word+import Foreign.Ptr+import Foreign.ForeignPtr+import Foreign.StablePtr+import Foreign.Storable+import Foreign.Marshal+
+ src/Foreign/StablePtr.hs view
@@ -0,0 +1,43 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.StablePtr+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- This module is part of the Foreign Function Interface (FFI) and will usually+-- be imported via the module "Foreign".+--++module Foreign.StablePtr+    (-- *  Stable references to Haskell values+     StablePtr,+     newStablePtr,+     deRefStablePtr,+     freeStablePtr,+     castStablePtrToPtr,+     castPtrToStablePtr,+     -- **  The C-side interface+     -- $cinterface+     ) where++import GHC.Internal.Foreign.StablePtr++-- $cinterface+--+-- The following definition is available to C programs inter-operating with+-- Haskell code when including the header @HsFFI.h@.+--+-- > typedef void *HsStablePtr;  /* C representation of a StablePtr */+--+-- Note that no assumptions may be made about the values representing stable+-- pointers.  In fact, they need not even be valid memory addresses.  The only+-- guarantee provided is that if they are passed back to Haskell land, the+-- function 'deRefStablePtr' will be able to reconstruct the+-- Haskell value referred to by the stable pointer.+
+ src/Foreign/Storable.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Foreign.Storable+-- Copyright   :  (c) The FFI task force 2001+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- The module "Foreign.Storable" provides most elementary support for+-- marshalling and is part of the language-independent portion of the+-- Foreign Function Interface (FFI), and will normally be imported via+-- the "Foreign" module.+--++module Foreign.Storable+    (Storable(sizeOf, alignment, peekElemOff, pokeElemOff, peekByteOff, pokeByteOff, peek, poke)+     ) where++import GHC.Internal.Foreign.Storable
+ src/GHC/Arr.hs view
@@ -0,0 +1,77 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Arr+-- Copyright   :  (c) The University of Glasgow, 1994-2000+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- GHC\'s array implementation.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.Arr+    (Ix(..),+     Array(..),+     STArray(..),+     arrEleBottom,+     array,+     listArray,+     (!),+     safeRangeSize,+     negRange,+     safeIndex,+     badSafeIndex,+     bounds,+     numElements,+     numElementsSTArray,+     indices,+     elems,+     assocs,+     accumArray,+     adjust,+     (//),+     accum,+     amap,+     ixmap,+     eqArray,+     cmpArray,+     cmpIntArray,+     newSTArray,+     boundsSTArray,+     readSTArray,+     writeSTArray,+     freezeSTArray,+     thawSTArray,+     foldlElems,+     foldlElems',+     foldl1Elems,+     foldrElems,+     foldrElems',+     foldr1Elems,+     -- *  Unsafe operations+     fill,+     done,+     unsafeArray,+     unsafeArray',+     lessSafeIndex,+     unsafeAt,+     unsafeReplace,+     unsafeAccumArray,+     unsafeAccumArray',+     unsafeAccum,+     unsafeReadSTArray,+     unsafeWriteSTArray,+     unsafeFreezeSTArray,+     unsafeThawSTArray+     ) where++import GHC.Internal.Arr
+ src/GHC/ArrayArray.hs view
@@ -0,0 +1,44 @@+{-# LANGUAGE Safe #-}++{-# LANGUAGE MagicHash #-}++-- |+--+-- Module      :  GHC.ArrayArray+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Legacy interface for arrays of arrays.+-- Deprecated, because the 'Array#' type can now store arrays directly.+-- Consider simply using 'Array#' instead of 'ArrayArray#'.+--+-- Use GHC.Exts instead of importing this module directly.+--++module GHC.ArrayArray+    (ArrayArray#(..),+     MutableArrayArray#(..),+     newArrayArray#,+     unsafeFreezeArrayArray#,+     sizeofArrayArray#,+     sizeofMutableArrayArray#,+     indexByteArrayArray#,+     indexArrayArrayArray#,+     readByteArrayArray#,+     readMutableByteArrayArray#,+     readArrayArrayArray#,+     readMutableArrayArrayArray#,+     writeByteArrayArray#,+     writeMutableByteArrayArray#,+     writeArrayArrayArray#,+     writeMutableArrayArrayArray#,+     copyArrayArray#,+     copyMutableArrayArray#,+     sameArrayArray#,+     sameMutableArrayArray#+     ) where++import GHC.Internal.ArrayArray
+ src/GHC/Base.hs view
@@ -0,0 +1,410 @@+{-# LANGUAGE MagicHash #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Base+-- Copyright   :  (c) The University of Glasgow, 1992-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Basic data types and classes.+--++-- N.B. This is a legacy module which we would at some point like to+-- deprecate and drop from `base`. In short, everything found here is+-- better imported from elsewhere. Until we have done so we prefer to+-- keep the export list as specific as possible (e.g. avoiding module+-- exports) to avoid changes in `ghc-internal` inadvertently+-- compromising the stability of this interface.++module GHC.Base+    ( module GHC.Types+    , module GHC.Prim+    , module GHC.Prim.Ext+    , module GHC.Prim.PtrEq+    , module GHC.Internal.Err+    , module GHC.Internal.Maybe++      -- * Equality and ordering+    , IP(..)+    , Eq(..)+    , Ord(..)+      -- ** Monomorphic equality operators+    , eqInt, neInt+    , eqWord, neWord+    , eqChar, neChar+    , eqFloat, eqDouble+    , gtInt, geInt, leInt, ltInt, compareInt, compareInt#+    , gtWord, geWord, leWord, ltWord, compareWord, compareWord#++      -- * C Strings+    , unpackCString#, unpackAppendCString#, unpackFoldrCString#+    , cstringLength#+    , unpackCStringUtf8#, unpackAppendCStringUtf8#, unpackFoldrCStringUtf8#+    , unpackNBytes#++      -- * Magic combinators+    , inline, noinline, lazy, oneShot, runRW#, seq#, DataToTag(..)+    , WithDict(withDict)++      -- * Functions over 'Bool'+    , (&&), (||), not++      -- Void+    , Void+    , absurd+    , vacuous++      -- * Semigroup/Monoid+    , Semigroup(..)+    , Monoid(..)++      -- * Functors+    , Functor(..)+    , Applicative(..)+    , (<**>)+    , liftA+    , liftA3+    , join+    , Monad(..)+    , (=<<)+    , when+    , sequence+    , mapM+    , liftM+    , liftM2+    , liftM3+    , liftM4+    , liftM5+    , ap+    , Alternative(..)+    , MonadPlus(..)++      -- Lists+    , NonEmpty(..)+    , foldr+    , build+    , augment+    , map+    , mapFB+    , (++)+    , String+    , unsafeChr+    , ord+    , eqString+    , minInt, maxInt++      -- * Miscellanea+    , otherwise+    , id+    , assert+    , breakpoint+    , breakpointCond+    , Opaque(..)+    , const+    , (.)+    , flip+    , ($)+    , ($!)+    , until+    , asTypeOf++      -- * IO+    , returnIO+    , bindIO+    , thenIO+    , failIO+    , unIO++      -- * Low-level integer utilities+    , getTag+    , quotInt+    , remInt+    , divInt+    , modInt+    , quotRemInt+    , divModInt+    , shift_mask+    , shiftL#+    , shiftRL#+    , iShiftL#+    , iShiftRA#+    , iShiftRL#+    , divInt#, divInt8#, divInt16#, divInt32#+    , modInt#, modInt8#, modInt16#, modInt32#+    , divModInt#, divModInt8#, divModInt16#, divModInt32#+    ) where++import GHC.Internal.Base hiding ( NonEmpty(..) )+import GHC.Internal.Data.NonEmpty ( NonEmpty(..) )+import GHC.Prim hiding+  (+  -- Hide dataToTag# ops because they are expected to break for+  -- GHC-internal reasons in the near future, and shouldn't+  -- be exposed from base+    dataToTagSmall#, dataToTagLarge#+  -- whereFrom# is similarly internal.+  , whereFrom#+  , isByteArrayWeaklyPinned#, isMutableByteArrayWeaklyPinned#+  -- Don't re-export vector FMA instructions+  , fmaddFloatX4#+  , fmsubFloatX4#+  , fnmaddFloatX4#+  , fnmsubFloatX4#+  , fmaddFloatX8#+  , fmsubFloatX8#+  , fnmaddFloatX8#+  , fnmsubFloatX8#+  , fmaddFloatX16#+  , fmsubFloatX16#+  , fnmaddFloatX16#+  , fnmsubFloatX16#+  , fmaddDoubleX2#+  , fmsubDoubleX2#+  , fnmaddDoubleX2#+  , fnmsubDoubleX2#+  , fmaddDoubleX4#+  , fmsubDoubleX4#+  , fnmaddDoubleX4#+  , fnmsubDoubleX4#+  , fmaddDoubleX8#+  , fmsubDoubleX8#+  , fnmaddDoubleX8#+  , fnmsubDoubleX8#+  -- Don't re-export SIMD shuffle primops+  , shuffleDoubleX2#+  , shuffleDoubleX4#+  , shuffleDoubleX8#+  , shuffleFloatX16#+  , shuffleFloatX4#+  , shuffleFloatX8#+  , shuffleInt16X16#+  , shuffleInt16X32#+  , shuffleInt16X8#+  , shuffleInt32X16#+  , shuffleInt32X4#+  , shuffleInt32X8#+  , shuffleInt64X2#+  , shuffleInt64X4#+  , shuffleInt64X8#+  , shuffleInt8X16#+  , shuffleInt8X32#+  , shuffleInt8X64#+  , shuffleWord16X16#+  , shuffleWord16X32#+  , shuffleWord16X8#+  , shuffleWord32X16#+  , shuffleWord32X4#+  , shuffleWord32X8#+  , shuffleWord64X2#+  , shuffleWord64X4#+  , shuffleWord64X8#+  , shuffleWord8X16#+  , shuffleWord8X32#+  , shuffleWord8X64#+  -- Don't re-export min/max primops+  , maxDouble#+  , maxDoubleX2#+  , maxDoubleX4#+  , maxDoubleX8#+  , maxFloat#+  , maxFloatX16#+  , maxFloatX4#+  , maxFloatX8#+  , maxInt16X16#+  , maxInt16X32#+  , maxInt16X8#+  , maxInt32X16#+  , maxInt32X4#+  , maxInt32X8#+  , maxInt64X2#+  , maxInt64X4#+  , maxInt64X8#+  , maxInt8X16#+  , maxInt8X32#+  , maxInt8X64#+  , maxWord16X16#+  , maxWord16X32#+  , maxWord16X8#+  , maxWord32X16#+  , maxWord32X4#+  , maxWord32X8#+  , maxWord64X2#+  , maxWord64X4#+  , maxWord64X8#+  , maxWord8X16#+  , maxWord8X32#+  , maxWord8X64#+  , minDouble#+  , minDoubleX2#+  , minDoubleX4#+  , minDoubleX8#+  , minFloat#+  , minFloatX16#+  , minFloatX4#+  , minFloatX8#+  , minInt16X16#+  , minInt16X32#+  , minInt16X8#+  , minInt32X16#+  , minInt32X4#+  , minInt32X8#+  , minInt64X2#+  , minInt64X4#+  , minInt64X8#+  , minInt8X16#+  , minInt8X32#+  , minInt8X64#+  , minWord16X16#+  , minWord16X32#+  , minWord16X8#+  , minWord32X16#+  , minWord32X4#+  , minWord32X8#+  , minWord64X2#+  , minWord64X4#+  , minWord64X8#+  , minWord8X16#+  , minWord8X32#+  , minWord8X64#+  )++import GHC.Prim.Ext+import GHC.Prim.PtrEq+import GHC.Internal.Err+import GHC.Internal.IO (seq#)+import GHC.Internal.Maybe+import GHC.Types hiding (+  Unit#,+  Solo#(..),+  Tuple0#,+  Tuple1#,+  Tuple2#,+  Tuple3#,+  Tuple4#,+  Tuple5#,+  Tuple6#,+  Tuple7#,+  Tuple8#,+  Tuple9#,+  Tuple10#,+  Tuple11#,+  Tuple12#,+  Tuple13#,+  Tuple14#,+  Tuple15#,+  Tuple16#,+  Tuple17#,+  Tuple18#,+  Tuple19#,+  Tuple20#,+  Tuple21#,+  Tuple22#,+  Tuple23#,+  Tuple24#,+  Tuple25#,+  Tuple26#,+  Tuple27#,+  Tuple28#,+  Tuple29#,+  Tuple30#,+  Tuple31#,+  Tuple32#,+  Tuple33#,+  Tuple34#,+  Tuple35#,+  Tuple36#,+  Tuple37#,+  Tuple38#,+  Tuple39#,+  Tuple40#,+  Tuple41#,+  Tuple42#,+  Tuple43#,+  Tuple44#,+  Tuple45#,+  Tuple46#,+  Tuple47#,+  Tuple48#,+  Tuple49#,+  Tuple50#,+  Tuple51#,+  Tuple52#,+  Tuple53#,+  Tuple54#,+  Tuple55#,+  Tuple56#,+  Tuple57#,+  Tuple58#,+  Tuple59#,+  Tuple60#,+  Tuple61#,+  Tuple62#,+  Tuple63#,+  Tuple64#,+  Sum2#,+  Sum3#,+  Sum4#,+  Sum5#,+  Sum6#,+  Sum7#,+  Sum8#,+  Sum9#,+  Sum10#,+  Sum11#,+  Sum12#,+  Sum13#,+  Sum14#,+  Sum15#,+  Sum16#,+  Sum17#,+  Sum18#,+  Sum19#,+  Sum20#,+  Sum21#,+  Sum22#,+  Sum23#,+  Sum24#,+  Sum25#,+  Sum26#,+  Sum27#,+  Sum28#,+  Sum29#,+  Sum30#,+  Sum31#,+  Sum32#,+  Sum33#,+  Sum34#,+  Sum35#,+  Sum36#,+  Sum37#,+  Sum38#,+  Sum39#,+  Sum40#,+  Sum41#,+  Sum42#,+  Sum43#,+  Sum44#,+  Sum45#,+  Sum46#,+  Sum47#,+  Sum48#,+  Sum49#,+  Sum50#,+  Sum51#,+  Sum52#,+  Sum53#,+  Sum54#,+  Sum55#,+  Sum56#,+  Sum57#,+  Sum58#,+  Sum59#,+  Sum60#,+  Sum61#,+  Sum62#,+  Sum63#,+  )
+ src/GHC/Bits.hs view
@@ -0,0 +1,30 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Bits+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- This module defines bitwise operations for signed and unsigned+-- integers.  Instances of the class 'Bits' for the 'Int' and+-- 'Integer' types are available from this module, and instances for+-- explicitly sized integral types are available from the+-- "Data.Int" and "Data.Word" modules.+--++module GHC.Bits+    (Bits((.&.), (.|.), xor, complement, shift, rotate, zeroBits, bit, setBit, clearBit, complementBit, testBit, bitSizeMaybe, bitSize, isSigned, shiftL, shiftR, unsafeShiftL, unsafeShiftR, rotateL, rotateR, popCount),+     FiniteBits(finiteBitSize, countLeadingZeros, countTrailingZeros),+     bitDefault,+     testBitDefault,+     popCountDefault,+     toIntegralSized+     ) where++import GHC.Internal.Bits
+ src/GHC/ByteOrder.hs view
@@ -0,0 +1,22 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.ByteOrder+-- Copyright   :  (c) The University of Glasgow, 1994-2000+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Target byte ordering.+--+-- @since 4.11.0.0++module GHC.ByteOrder+    (ByteOrder(..),+     targetByteOrder+     ) where++import GHC.Internal.ByteOrder
+ src/GHC/Char.hs view
@@ -0,0 +1,12 @@+{-# LANGUAGE Safe #-}++module GHC.Char+    (-- *  Utilities+     chr,+     -- *  Monomorphic equality operators+     -- |  See GHC.Classes#matching_overloaded_methods_in_rules+     eqChar,+     neChar+     ) where++import GHC.Internal.Char
+ src/GHC/Clock.hs view
@@ -0,0 +1,18 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  GHC.Clock+-- License     :  BSD-style (see the file LICENSE in this distribution)+--+-- Stability   :  internal+-- Portability :  portable+--+-- System monotonic time.+--++module GHC.Clock+    ( getMonotonicTime+    , getMonotonicTimeNSec+    ) where++import GHC.Internal.Clock
+ src/GHC/Conc.hs view
@@ -0,0 +1,125 @@+{-# LANGUAGE Unsafe #-}+{-# LANGUAGE CPP, NoImplicitPrelude #-}+{-# OPTIONS_GHC -Wno-missing-signatures #-}+{-# OPTIONS_HADDOCK not-home #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  GHC.Conc+-- Copyright   :  (c) The University of Glasgow, 1994-2023+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Basic concurrency stuff.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--+-----------------------------------------------------------------------------++-- No: #hide, because bits of this module are exposed by the stm package.+-- However, we don't want this module to be the home location for the+-- bits it exports, we'd rather have Control.Concurrent and the other+-- higher level modules be the home.  Hence: #not-home++module GHC.Conc+        ( ThreadId(..)++        -- * Forking and suchlike+        , forkIO+        , forkIOWithUnmask+        , forkOn+        , forkOnWithUnmask+        , numCapabilities+        , getNumCapabilities+        , setNumCapabilities+        , getNumProcessors+        , numSparks+        , childHandler+        , myThreadId+        , killThread+        , throwTo+        , par+        , pseq+        , runSparks+        , yield+        , labelThread+        , mkWeakThreadId+        , listThreads++        , ThreadStatus(..), BlockReason(..)+        , threadStatus+        , threadCapability++        , newStablePtrPrimMVar, PrimMVar++        -- * Waiting+        , threadDelay+        , registerDelay+        , threadWaitRead+        , threadWaitWrite+        , threadWaitReadSTM+        , threadWaitWriteSTM+        , closeFdWith++        -- * Allocation counter and limit+        , setAllocationCounter+        , getAllocationCounter+        , enableAllocationLimit+        , disableAllocationLimit++        -- * TVars+        , STM(..)+        , atomically+        , retry+        , orElse+        , throwSTM+        , catchSTM+        , TVar(..)+        , newTVar+        , newTVarIO+        , readTVar+        , readTVarIO+        , writeTVar+        , unsafeIOToSTM++        -- * Miscellaneous+        , withMVar+#if defined(mingw32_HOST_OS)+        , asyncRead+        , asyncWrite+        , asyncDoProc++        , asyncReadBA+        , asyncWriteBA+#endif++#if !defined(mingw32_HOST_OS)+        , Signal, HandlerFun, setHandler, runHandlers+#endif++        , ensureIOManagerIsRunning+        , ioManagerCapabilitiesChanged++#if defined(mingw32_HOST_OS)+        , ConsoleEvent(..)+        , win32ConsoleHandler+        , toWin32ConsoleEvent+#endif+        , setUncaughtExceptionHandler+        , getUncaughtExceptionHandler++        , reportError, reportStackOverflow, reportHeapOverflow+        ) where++import GHC.Internal.Conc.IO+import GHC.Internal.Conc.Sync++#if !defined(mingw32_HOST_OS)+import GHC.Internal.Conc.Signal+#endif
+ src/GHC/Conc/IO.hs view
@@ -0,0 +1,35 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Conc.IO+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Basic concurrency stuff.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.Conc.IO+    (ensureIOManagerIsRunning,+     ioManagerCapabilitiesChanged,+     interruptIOManager,+     -- *  Waiting+     threadDelay,+     registerDelay,+     threadWaitRead,+     threadWaitWrite,+     threadWaitReadSTM,+     threadWaitWriteSTM,+     closeFdWith+     ) where++import GHC.Internal.Conc.IO
+ src/GHC/Conc/POSIX.hs view
@@ -0,0 +1,42 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Conc.POSIX+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Windows I/O manager+--+-- This is the I/O manager based on posix FDs for windows.+-- When using the winio manager these functions may not+-- be used as they will behave in unexpected ways.+--+-- TODO: This manager is currently the default. But we will eventually+-- switch to use winio instead.+--++module GHC.Conc.POSIX+       ( ensureIOManagerIsRunning+       , interruptIOManager++       -- * Waiting+       , threadDelay+       , registerDelay++       -- * Miscellaneous+       , asyncRead+       , asyncWrite+       , asyncDoProc++       , asyncReadBA+       , asyncWriteBA++       , module GHC.Internal.Event.Windows.ConsoleEvent+       ) where++import GHC.Internal.Conc.POSIX+import GHC.Internal.Event.Windows.ConsoleEvent
+ src/GHC/Conc/POSIX/Const.hs view
@@ -0,0 +1,5 @@+module GHC.Conc.POSIX.Const+    ( io_MANAGER_WAKEUP, io_MANAGER_DIE+    ) where++import GHC.Internal.Conc.POSIX.Const
+ src/GHC/Conc/Signal.hs view
@@ -0,0 +1,11 @@+{-# LANGUAGE Safe #-}++module GHC.Conc.Signal+    (Signal,+     HandlerFun,+     setHandler,+     runHandlers,+     runHandlersPtr+     ) where++import GHC.Internal.Conc.Signal
+ src/GHC/Conc/Sync.hs view
@@ -0,0 +1,91 @@+{-# LANGUAGE MagicHash #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Conc.Sync+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Basic concurrency stuff.+--++module GHC.Conc.Sync+        (+        -- * Threads+          ThreadId(..)+        , fromThreadId+        , showThreadId+        , myThreadId+        , killThread+        , throwTo+        , yield+        , labelThread+        , labelThreadByteArray#+        , mkWeakThreadId+        -- ** Queries+        , listThreads+        , threadLabel+        , ThreadStatus(..), BlockReason(..)+        , threadStatus+        , threadCapability++        -- * Forking and suchlike+        , forkIO+        , forkIOWithUnmask+        , forkOn+        , forkOnWithUnmask++        -- * Capabilities+        , numCapabilities+        , getNumCapabilities+        , setNumCapabilities+        , getNumProcessors++        -- * Sparks+        , numSparks+        , childHandler+        , par+        , pseq+        , runSparks++        -- * PrimMVar+        , newStablePtrPrimMVar, PrimMVar++        -- * Allocation counter and quota+        , setAllocationCounter+        , getAllocationCounter+        , enableAllocationLimit+        , disableAllocationLimit++        -- * TVars+        , STM(..)+        , atomically+        , retry+        , orElse+        , throwSTM+        , catchSTM+        , TVar(..)+        , newTVar+        , newTVarIO+        , readTVar+        , readTVarIO+        , writeTVar+        , unsafeIOToSTM++        -- * Miscellaneous+        , withMVar+        , modifyMVar_++        , setUncaughtExceptionHandler+        , getUncaughtExceptionHandler++        , reportError, reportStackOverflow, reportHeapOverflow++        , sharedCAF+        ) where++import GHC.Internal.Conc.Sync
+ src/GHC/Conc/WinIO.hs view
@@ -0,0 +1,23 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Conc.WinIO+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Windows I/O Completion Port interface to the one defined in+-- GHC.Event.Windows.+--+-- This module is an indirection to keep things in the same structure as before+-- but also to keep the new code where the actual I/O manager is.  As such it+-- just re-exports "GHC.Event.Windows.Thread"+--++module GHC.Conc.WinIO+       ( module GHC.Internal.Event.Windows.Thread ) where++import GHC.Internal.Event.Windows.Thread
+ src/GHC/Conc/Windows.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Safe #-}++-- |+-- Module      :  GHC.Internal.Conc.Windows+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Windows I/O manager interfaces. Depending on which I/O Subsystem is used+-- requests will be routed to different places.+--+--+module GHC.Conc.Windows++#if defined(javascript_HOST_ARCH)+       () where++#else+       ( ensureIOManagerIsRunning+       , interruptIOManager++       -- * Waiting+       , threadDelay+       , registerDelay++       -- * Miscellaneous+       , asyncRead+       , asyncWrite+       , asyncDoProc++       , asyncReadBA+       , asyncWriteBA++       -- * Console event handler+       , module GHC.Internal.Event.Windows.ConsoleEvent+       ) where++import GHC.Internal.Conc.Windows+import GHC.Internal.Event.Windows.ConsoleEvent++#endif
+ src/GHC/ConsoleHandler.hs view
@@ -0,0 +1,36 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Safe #-}++-- |+-- Module      :  GHC.ConsoleHandler+-- Copyright   :  (c) The University of Glasgow+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- NB. the contents of this module are only available on Windows.+--+-- Installing Win32 console handlers.+--++#if !defined(mingw32_HOST_OS)++module GHC.ConsoleHandler () where++-- See W1 of Note [Tracking dependencies on primitives] in GHC.Internal.Base+import Prelude () -- for build ordering++#else++module GHC.ConsoleHandler+        ( Handler(..)+        , installHandler+        , ConsoleEvent(..)+        ) where++import GHC.Internal.ConsoleHandler++#endif+
+ src/GHC/Constants.hs view
@@ -0,0 +1,6 @@+-- TODO: Deprecate+module GHC.Constants where++-- See W1 of Note [Tracking dependencies on primitives] in GHC.Internal.Base+import GHC.Types () -- for build ordering+
+ src/GHC/Desugar.hs view
@@ -0,0 +1,33 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-----------------------------------------------------------------------------+-- |+--+-- Module      :  GHC.Desugar+-- Copyright   :  (c) The University of Glasgow, 2007+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  deprecated (<https://github.com/haskell/core-libraries-committee/issues/216>)+-- Portability :  non-portable (GHC extensions)+--+-- Support code for desugaring in GHC+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--+-----------------------------------------------------------------------------++#if __GLASGOW_HASKELL >= 914+#error "GHC.Desugar should be removed in GHC 9.14"+#endif++module GHC.Desugar+  {-# DEPRECATED ["GHC.Desugar is deprecated and will be removed in GHC 9.14.", "(>>>) should be imported from Control.Arrow.", "AnnotationWrapper is internal to GHC and should not be used externally."] #-}+  ((>>>), AnnotationWrapper(..), toAnnotationWrapper) where++import GHC.Internal.Desugar
+ src/GHC/Encoding/UTF8.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE MagicHash #-}++-- |+--+-- Module      :  GHC.Encoding.UTF8+-- Copyright   :  (c) The University of Glasgow, 1994-2023+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--+-- Simple UTF-8 codecs supporting non-streaming encoding/decoding.+-- For encoding where codepoints may be broken across buffers,+-- see "GHC.IO.Encoding.UTF8".+--+-- This is one of several UTF-8 implementations provided by GHC; see Note+-- [GHC's many UTF-8 implementations] in "GHC.Encoding.UTF8" for an+-- overview.+--++module GHC.Encoding.UTF8+    (-- *  Decoding single characters+     utf8DecodeCharAddr#,+     utf8DecodeCharPtr,+     utf8DecodeCharByteArray#,+     -- *  Decoding strings+     utf8DecodeByteArray#,+     utf8DecodeForeignPtr,+     -- *  Counting characters+     utf8CountCharsByteArray#,+     -- *  Comparison+     utf8CompareByteArray#,+     -- *  Encoding strings+     utf8EncodePtr,+     utf8EncodeByteArray#,+     utf8EncodedLength+     ) where++import GHC.Internal.Encoding.UTF8
+ src/GHC/Enum.hs view
@@ -0,0 +1,22 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Enum+-- Copyright   :  (c) The University of Glasgow, 1992-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- The 'Enum' and 'Bounded' classes.+--++module GHC.Enum(+        Bounded(..), Enum(..),+        boundedEnumFrom, boundedEnumFromThen,+        toEnumError, fromEnumError, succError, predError,+   ) where++import GHC.Internal.Enum
+ src/GHC/Environment.hs view
@@ -0,0 +1,7 @@+{-# LANGUAGE Safe #-}++module GHC.Environment+    (getFullArgs+     ) where++import GHC.Internal.Environment
+ src/GHC/Err.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Err+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- The "GHC.Err" module defines the code for the wired-in error functions,+-- which have a special type in the compiler (with \"open tyvars\").+--+-- We cannot define these functions in a module where they might be used+-- (e.g., "GHC.Base"), because the magical wired-in type will get confused+-- with what the typechecker figures out.+--++module GHC.Err( absentErr, error, errorWithoutStackTrace, undefined ) where++import GHC.Internal.Err
+ src/GHC/Event.hs view
@@ -0,0 +1,47 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Safe #-}++-- |+-- This module provides scalable event notification for file+-- descriptors and timeouts.+--+-- This module should be considered GHC internal.+--+-- ----------------------------------------------------------------------------++#if defined(javascript_HOST_ARCH)++module GHC.Event ( ) where++#else++module GHC.Event+    (-- *  Types+     EventManager,+     TimerManager,+     -- *  Creation+     getSystemEventManager,+     new,+     getSystemTimerManager,+     -- *  Registering interest in I/O events+     Event,+     evtRead,+     evtWrite,+     IOCallback,+     FdKey(keyFd),+     Lifetime(..),+     registerFd,+     unregisterFd,+     unregisterFd_,+     closeFd,+     -- *  Registering interest in timeout events+     TimeoutCallback,+     TimeoutKey,+     registerTimeout,+     updateTimeout,+     unregisterTimeout+     ) where++import GHC.Internal.Event++#endif
+ src/GHC/Event/TimeOut.hs view
@@ -0,0 +1,24 @@+-- |+-- Module      :  GHC.Event.TimeOut+-- Copyright   :  (c) Tamar Christina 2018+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable+--+-- Common Timer definitions shared between WinIO and RIO.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.++module GHC.Event.TimeOut+    ( TimeoutQueue+    , TimeoutCallback+    , TimeoutEdit+    , TimeoutKey(..)+    ) where++import GHC.Internal.Event.TimeOut
+ src/GHC/Event/Windows.hs view
@@ -0,0 +1,61 @@+-- |+-- Module      :  GHC.Event.Windows+-- Copyright   :  (c) Tamar Christina 2018+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable+--+-- WinIO Windows event manager.+--++module GHC.Event.Windows (+    -- * Manager+    Manager,+    getSystemManager,+    interruptSystemManager,+    wakeupIOManager,+    processRemoteCompletion,++    -- * Overlapped I/O+    associateHandle,+    associateHandle',+    withOverlapped,+    withOverlappedEx,+    StartCallback,+    StartIOCallback,+    CbResult(..),+    CompletionCallback,+    LPOVERLAPPED,++    -- * Timeouts+    TimeoutCallback,+    TimeoutKey,+    Seconds,+    registerTimeout,+    updateTimeout,+    unregisterTimeout,++    -- * Utilities+    withException,+    ioSuccess,+    ioFailed,+    ioFailedAny,+    getLastError,++    -- * I/O Result type+    IOResult(..),++    -- * I/O Event notifications+    HandleData (..), -- seal for release+    HandleKey (handleValue),+    registerHandle,+    unregisterHandle,++    -- * Console events+    module GHC.Internal.Event.Windows.ConsoleEvent+) where++import GHC.Internal.Event.Windows+import GHC.Internal.Event.Windows.ConsoleEvent
+ src/GHC/Event/Windows/Clock.hs view
@@ -0,0 +1,12 @@+module GHC.Event.Windows.Clock (+    Clock,+    Seconds,+    getTime,+    getClock,++    -- * Specific implementations+    queryPerformanceCounter,+    getTickCount64+) where++import GHC.Internal.Event.Windows.Clock
+ src/GHC/Event/Windows/ConsoleEvent.hs view
@@ -0,0 +1,21 @@+-- |+-- Module      :  GHC.Event.Windows.ConsoleEvent+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Windows I/O manager interfaces. Depending on which I/O Subsystem is used+-- requests will be routed to different places.+--++module GHC.Event.Windows.ConsoleEvent (+  ConsoleEvent (..),+  start_console_handler,+  toWin32ConsoleEvent,+  win32ConsoleHandler+) where++import GHC.Internal.Event.Windows.ConsoleEvent
+ src/GHC/Event/Windows/FFI.hs view
@@ -0,0 +1,59 @@+-- |+-- Module      :  GHC.Event.Windows.FFI+-- Copyright   :  (c) Tamar Christina 2019+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable+--+-- WinIO Windows API Foreign Function imports+--++module GHC.Event.Windows.FFI (+    -- * IOCP+    IOCP(..),+    CompletionKey,+    newIOCP,+    associateHandleWithIOCP,+    getQueuedCompletionStatusEx,+    postQueuedCompletionStatus,+    getOverlappedResult,++    -- * Completion Data+    CompletionData(..),+    CompletionCallback,+    withRequest,++    -- * Overlapped+    OVERLAPPED,+    LPOVERLAPPED,+    OVERLAPPED_ENTRY(..),+    LPOVERLAPPED_ENTRY,+    HASKELL_OVERLAPPED,+    LPHASKELL_OVERLAPPED,+    allocOverlapped,+    zeroOverlapped,+    pokeOffsetOverlapped,+    overlappedIOStatus,+    overlappedIONumBytes,++    -- * Cancel pending I/O+    cancelIoEx,+    cancelIoEx',++    -- * Monotonic time++    -- ** GetTickCount+    getTickCount64,++    -- ** QueryPerformanceCounter+    queryPerformanceCounter,+    queryPerformanceFrequency,++    -- ** Miscellaneous+    throwWinErr,+    setLastError+  ) where++import GHC.Internal.Event.Windows.FFI
+ src/GHC/Event/Windows/ManagedThreadPool.hs view
@@ -0,0 +1,23 @@+-- |+-- Module      :  GHC.Event.Windows.ManagedThreadPool+-- Copyright   :  (c) Tamar Christina 2019+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable+--+-- WinIO Windows Managed Thread pool API.  This thread pool scales dynamically+-- based on demand.+--+-------------------------------------------------------------------------------++module GHC.Event.Windows.ManagedThreadPool+  ( ThreadPool(..)+  , startThreadPool+  , notifyRunning+  , notifyWaiting+  , monitorThreadPool+  ) where++import GHC.Internal.Event.Windows.ManagedThreadPool
+ src/GHC/Event/Windows/Thread.hs view
@@ -0,0 +1,8 @@+module GHC.Event.Windows.Thread (+    ensureIOManagerIsRunning,+    interruptIOManager,+    threadDelay,+    registerDelay,+) where++import GHC.Internal.Event.Windows.Thread
+ src/GHC/Exception.hs view
@@ -0,0 +1,57 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE PatternSynonyms #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Exception+-- Copyright   :  (c) The University of Glasgow, 1998-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Exceptions and exception-handling functions.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.Exception+    ( -- * 'Exception' class+      Exception(..)++      -- * 'SomeException'+    , SomeException(..)++      -- * Throwing+    , throw++      -- * Concrete exceptions+      -- ** Arithmetic exceptions+    , ArithException(..)+    , divZeroException+    , overflowException+    , ratioZeroDenomException+    , underflowException+      -- ** 'ErrorCall'+    , ErrorCall(..)+    , errorCallException+    , errorCallWithCallStackException++      -- * Reexports+      -- Re-export CallStack and SrcLoc from GHC.Types+    , CallStack, fromCallSiteList, getCallStack, prettyCallStack+    , prettyCallStackLines+    , SrcLoc(..), prettySrcLoc+    ) where++import GHC.Internal.Exception++-- XXX: This is a temporary workaround to ensure correct build ordering+-- despite #24436 since `GHC.Internal.Stack` has a .hs-boot file which+-- `ghc -M` does not track correctly.+-- This dependency should be removed when #24436 is fixed.+import GHC.Internal.Stack ()
+ src/GHC/Exception/Type.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Exception.Type+-- Copyright   :  (c) The University of Glasgow, 1998-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  cvs-ghc@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Exceptions and exception-handling functions.+--++module GHC.Exception.Type+       ( Exception(..)    -- Class+       , SomeException(..), ArithException(..)+       , divZeroException, overflowException, ratioZeroDenomException+       , underflowException+       ) where++import GHC.Internal.Exception.Type
+ src/GHC/ExecutionStack.hs view
@@ -0,0 +1,38 @@+-- |+--+-- Module      :  GHC.ExecutionStack+-- Copyright   :  (c) The University of Glasgow 2013-2015+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- This is a module for efficient stack traces. This stack trace implementation+-- is considered low overhead. Basic usage looks like this:+--+-- @+-- import GHC.ExecutionStack+--+-- myFunction :: IO ()+-- myFunction = do+--      putStrLn =<< showStackTrace+-- @+--+-- Your GHC must have been built with @libdw@ support for this to work.+--+-- @+-- user@host:~$ ghc --info | grep libdw+--  ,("RTS expects libdw","YES")+-- @+--+-- @since 4.9.0.0++module GHC.ExecutionStack+    (Location(..),+     SrcLoc(..),+     getStackTrace,+     showStackTrace+     ) where++import GHC.Internal.ExecutionStack
+ src/GHC/Exts.hs view
@@ -0,0 +1,386 @@+{-# LANGUAGE MagicHash #-}++-- |+--+-- Module      :  GHC.Exts+-- Copyright   :  (c) The University of Glasgow 2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- GHC Extensions: this is the Approved Way to get at GHC-specific extensions.+--+-- Note: no other @base@ module should import this module.++-- See Note [Where do we export PrimOps] for details about how to expose primops+-- to users.++module GHC.Exts+    (-- **  Pointer types+     Ptr(..),+     FunPtr(..),+     -- **  Other primitive types+     module GHC.Types,+     -- **  Legacy interface for arrays of arrays+     module GHC.Internal.ArrayArray,+     -- *  Primitive operations+     module GHC.Prim,+     module GHC.Prim.Ext,+     -- **  Running 'RealWorld' state thread+     runRW#,+     -- **  Bit shift operations+     shiftL#,+     shiftRL#,+     iShiftL#,+     iShiftRA#,+     iShiftRL#,+     -- **  Pointer comparison operations+     reallyUnsafePtrEquality,+     unsafePtrEquality#,+     eqStableName#,+     sameArray#,+     sameMutableArray#,+     sameSmallArray#,+     sameSmallMutableArray#,+     sameByteArray#,+     sameMutableByteArray#,+     sameMVar#,+     sameMutVar#,+     sameTVar#,+     samePromptTag#,+     -- **  Compat wrapper+     atomicModifyMutVar#,+     -- **  Resize functions+     -- |  Resizing arrays of boxed elements is currently handled in+     -- library space (rather than being a primop) since there is not+     -- an efficient way to grow arrays. However, resize operations+     -- may become primops in a future release of GHC.+     resizeSmallMutableArray#,+     -- **  Fusion+     build,+     augment,+     -- *  Overloaded lists+     IsList(..),+     -- *  Transform comprehensions+     Down(..),+     groupWith,+     sortWith,+     the,+     -- *  Strings+     -- **  Overloaded string literals+     IsString(..),+     -- **  CString+     unpackCString#,+     unpackAppendCString#,+     unpackFoldrCString#,+     unpackCStringUtf8#,+     unpackNBytes#,+     cstringLength#,+     -- *  Debugging+     -- **  Breakpoints+     breakpoint,+     breakpointCond,+     -- **  Event logging+     traceEvent,+     -- **  The call stack+     currentCallStack,+     -- *  Ids with special behaviour+     inline,+     noinline,+     lazy,+     oneShot,+     considerAccessible,+     seq#,+     -- *  SpecConstr annotations+     SpecConstrAnnotation(..),+     SPEC(..),+     -- *  Coercions+     -- **  Safe coercions+     -- |  These are available from the /Trustworthy/ module "Data.Coerce" as well.+     --+     -- @since 4.7.0.0+     coerce,+     -- **  Very unsafe coercion+     unsafeCoerce#,+     -- **  Casting class dictionaries with single methods+     WithDict(..),+     -- *  Converting ADTs to constructor tags+     DataToTag(..),+     -- *  The maximum tuple size+     maxTupleSize+     ) where++import GHC.Internal.Exts+import GHC.Internal.ArrayArray+import GHC.Prim hiding+  ( coerce+  -- Hide dataToTag# ops because they are expected to break for+  -- GHC-internal reasons in the near future, and shouldn't+  -- be exposed from base (not even GHC.Exts)+  , dataToTagSmall#, dataToTagLarge#+  -- whereFrom# is similarly internal.+  , whereFrom#+  , isByteArrayWeaklyPinned#, isMutableByteArrayWeaklyPinned#++  -- Don't re-export vector FMA instructions+  , fmaddFloatX4#+  , fmsubFloatX4#+  , fnmaddFloatX4#+  , fnmsubFloatX4#+  , fmaddFloatX8#+  , fmsubFloatX8#+  , fnmaddFloatX8#+  , fnmsubFloatX8#+  , fmaddFloatX16#+  , fmsubFloatX16#+  , fnmaddFloatX16#+  , fnmsubFloatX16#+  , fmaddDoubleX2#+  , fmsubDoubleX2#+  , fnmaddDoubleX2#+  , fnmsubDoubleX2#+  , fmaddDoubleX4#+  , fmsubDoubleX4#+  , fnmaddDoubleX4#+  , fnmsubDoubleX4#+  , fmaddDoubleX8#+  , fmsubDoubleX8#+  , fnmaddDoubleX8#+  , fnmsubDoubleX8#+  -- Don't re-export SIMD shuffle primops+  , shuffleDoubleX2#+  , shuffleDoubleX4#+  , shuffleDoubleX8#+  , shuffleFloatX16#+  , shuffleFloatX4#+  , shuffleFloatX8#+  , shuffleInt16X16#+  , shuffleInt16X32#+  , shuffleInt16X8#+  , shuffleInt32X16#+  , shuffleInt32X4#+  , shuffleInt32X8#+  , shuffleInt64X2#+  , shuffleInt64X4#+  , shuffleInt64X8#+  , shuffleInt8X16#+  , shuffleInt8X32#+  , shuffleInt8X64#+  , shuffleWord16X16#+  , shuffleWord16X32#+  , shuffleWord16X8#+  , shuffleWord32X16#+  , shuffleWord32X4#+  , shuffleWord32X8#+  , shuffleWord64X2#+  , shuffleWord64X4#+  , shuffleWord64X8#+  , shuffleWord8X16#+  , shuffleWord8X32#+  , shuffleWord8X64#+  -- Don't re-export min/max primops+  , maxDouble#+  , maxDoubleX2#+  , maxDoubleX4#+  , maxDoubleX8#+  , maxFloat#+  , maxFloatX16#+  , maxFloatX4#+  , maxFloatX8#+  , maxInt16X16#+  , maxInt16X32#+  , maxInt16X8#+  , maxInt32X16#+  , maxInt32X4#+  , maxInt32X8#+  , maxInt64X2#+  , maxInt64X4#+  , maxInt64X8#+  , maxInt8X16#+  , maxInt8X32#+  , maxInt8X64#+  , maxWord16X16#+  , maxWord16X32#+  , maxWord16X8#+  , maxWord32X16#+  , maxWord32X4#+  , maxWord32X8#+  , maxWord64X2#+  , maxWord64X4#+  , maxWord64X8#+  , maxWord8X16#+  , maxWord8X32#+  , maxWord8X64#+  , minDouble#+  , minDoubleX2#+  , minDoubleX4#+  , minDoubleX8#+  , minFloat#+  , minFloatX16#+  , minFloatX4#+  , minFloatX8#+  , minInt16X16#+  , minInt16X32#+  , minInt16X8#+  , minInt32X16#+  , minInt32X4#+  , minInt32X8#+  , minInt64X2#+  , minInt64X4#+  , minInt64X8#+  , minInt8X16#+  , minInt8X32#+  , minInt8X64#+  , minWord16X16#+  , minWord16X32#+  , minWord16X8#+  , minWord32X16#+  , minWord32X4#+  , minWord32X8#+  , minWord64X2#+  , minWord64X4#+  , minWord64X8#+  , minWord8X16#+  , minWord8X32#+  , minWord8X64#+  )++import GHC.Prim.Ext++import GHC.Types hiding (+  IO,   -- Exported from "GHC.IO"+  Type, -- Exported from "Data.Kind"+  -- GHC's internal representation of 'TyCon's, for 'Typeable'+  Module, TrName, TyCon, TypeLitSort, KindRep, KindBndr,+  Unit#,+  Solo#(..),+  Tuple0#,+  Tuple1#,+  Tuple2#,+  Tuple3#,+  Tuple4#,+  Tuple5#,+  Tuple6#,+  Tuple7#,+  Tuple8#,+  Tuple9#,+  Tuple10#,+  Tuple11#,+  Tuple12#,+  Tuple13#,+  Tuple14#,+  Tuple15#,+  Tuple16#,+  Tuple17#,+  Tuple18#,+  Tuple19#,+  Tuple20#,+  Tuple21#,+  Tuple22#,+  Tuple23#,+  Tuple24#,+  Tuple25#,+  Tuple26#,+  Tuple27#,+  Tuple28#,+  Tuple29#,+  Tuple30#,+  Tuple31#,+  Tuple32#,+  Tuple33#,+  Tuple34#,+  Tuple35#,+  Tuple36#,+  Tuple37#,+  Tuple38#,+  Tuple39#,+  Tuple40#,+  Tuple41#,+  Tuple42#,+  Tuple43#,+  Tuple44#,+  Tuple45#,+  Tuple46#,+  Tuple47#,+  Tuple48#,+  Tuple49#,+  Tuple50#,+  Tuple51#,+  Tuple52#,+  Tuple53#,+  Tuple54#,+  Tuple55#,+  Tuple56#,+  Tuple57#,+  Tuple58#,+  Tuple59#,+  Tuple60#,+  Tuple61#,+  Tuple62#,+  Tuple63#,+  Tuple64#,+  Sum2#,+  Sum3#,+  Sum4#,+  Sum5#,+  Sum6#,+  Sum7#,+  Sum8#,+  Sum9#,+  Sum10#,+  Sum11#,+  Sum12#,+  Sum13#,+  Sum14#,+  Sum15#,+  Sum16#,+  Sum17#,+  Sum18#,+  Sum19#,+  Sum20#,+  Sum21#,+  Sum22#,+  Sum23#,+  Sum24#,+  Sum25#,+  Sum26#,+  Sum27#,+  Sum28#,+  Sum29#,+  Sum30#,+  Sum31#,+  Sum32#,+  Sum33#,+  Sum34#,+  Sum35#,+  Sum36#,+  Sum37#,+  Sum38#,+  Sum39#,+  Sum40#,+  Sum41#,+  Sum42#,+  Sum43#,+  Sum44#,+  Sum45#,+  Sum46#,+  Sum47#,+  Sum48#,+  Sum49#,+  Sum50#,+  Sum51#,+  Sum52#,+  Sum53#,+  Sum54#,+  Sum55#,+  Sum56#,+  Sum57#,+  Sum58#,+  Sum59#,+  Sum60#,+  Sum61#,+  Sum62#,+  Sum63#,+  )
+ src/GHC/Fingerprint.hs view
@@ -0,0 +1,11 @@+{-# LANGUAGE Safe #-}++module GHC.Fingerprint (+        Fingerprint(..), fingerprint0,+        fingerprintData,+        fingerprintString,+        fingerprintFingerprints,+        getFileHash+   ) where++import GHC.Internal.Fingerprint
+ src/GHC/Fingerprint/Type.hs view
@@ -0,0 +1,25 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.Fingerprint.Type+-- Copyright   :  (c) The University of Glasgow, 1994-2023+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Fingerprints for recompilation checking and ABI versioning, and+-- implementing fast comparison of Typeable.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.++module GHC.Fingerprint.Type+    (Fingerprint(..)+     ) where++import GHC.Internal.Fingerprint.Type
+ src/GHC/Float.hs view
@@ -0,0 +1,172 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE MagicHash #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Float+-- Copyright   :  (c) The University of Glasgow 1994-2002+--                Portions obtained from hbc (c) Lennart Augusstson+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The types 'Float' and 'Double', the classes 'Floating' and 'RealFloat' and+-- casting between Word32 and Float and Word64 and Double.+--++module GHC.Float+    (-- *  Classes+     Floating(..),+     RealFloat(..),+     -- *  'Float'+     Float(..),+     Float#,+     -- **  Conversion+     float2Int,+     int2Float,+     word2Float,+     integerToFloat#,+     naturalToFloat#,+     rationalToFloat,+     castWord32ToFloat,+     castFloatToWord32,+     castWord32ToFloat#,+     castFloatToWord32#,+     float2Double,+     -- **  Operations+     floorFloat,+     ceilingFloat,+     truncateFloat,+     roundFloat,+     properFractionFloat,+     -- **  Predicate+     isFloatDenormalized,+     isFloatFinite,+     isFloatInfinite,+     isFloatNaN,+     isFloatNegativeZero,+     -- **  Comparison+     gtFloat,+     geFloat,+     leFloat,+     ltFloat,+     -- **  Arithmetic+     plusFloat,+     minusFloat,+     timesFloat,+     divideFloat,+     negateFloat,+     expFloat,+     expm1Float,+     logFloat,+     log1pFloat,+     sqrtFloat,+     fabsFloat,+     sinFloat,+     cosFloat,+     tanFloat,+     asinFloat,+     acosFloat,+     atanFloat,+     sinhFloat,+     coshFloat,+     tanhFloat,+     asinhFloat,+     acoshFloat,+     atanhFloat,+     -- *  'Double'+     Double(..),+     Double#,+     -- **  Conversion+     double2Int,+     int2Double,+     word2Double,+     integerToDouble#,+     naturalToDouble#,+     rationalToDouble,+     castWord64ToDouble,+     castDoubleToWord64,+     castWord64ToDouble#,+     castDoubleToWord64#,+     double2Float,+     -- **  Operations+     floorDouble,+     ceilingDouble,+     truncateDouble,+     roundDouble,+     properFractionDouble,+     -- **  Predicate+     isDoubleDenormalized,+     isDoubleFinite,+     isDoubleInfinite,+     isDoubleNaN,+     isDoubleNegativeZero,+     -- **  Comparison+     gtDouble,+     geDouble,+     leDouble,+     ltDouble,+     -- **  Arithmetic+     plusDouble,+     minusDouble,+     timesDouble,+     divideDouble,+     negateDouble,+     expDouble,+     expm1Double,+     logDouble,+     log1pDouble,+     sqrtDouble,+     fabsDouble,+     sinDouble,+     cosDouble,+     tanDouble,+     asinDouble,+     acosDouble,+     atanDouble,+     sinhDouble,+     coshDouble,+     tanhDouble,+     asinhDouble,+     acoshDouble,+     atanhDouble,+     -- *  Formatting+     showFloat,+     FFFormat(..),+     formatRealFloat,+     formatRealFloatAlt,+     showSignedFloat,+     -- *  Operations+     log1mexpOrd,+     roundTo,+     floatToDigits,+     integerToBinaryFloat',+     fromRat,+     fromRat',+     roundingMode#,+     -- *  Monomorphic equality operators+     -- |  See GHC.Classes#matching_overloaded_methods_in_rules+     eqFloat,+     eqDouble,+     -- *  Internal+     -- |  These may vanish in a future release+     clamp,+     expt,+     expts,+     expts10,+     fromRat'',+     maxExpt,+     maxExpt10,+     minExpt,+     powerDouble,+     powerFloat,+     stgDoubleToWord64,+     stgFloatToWord32,+     stgWord64ToDouble,+     stgWord32ToFloat+     ) where++import GHC.Internal.Float
+ src/GHC/Float/ConversionUtils.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE MagicHash #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Float.ConversionUtils+-- Copyright   :  (c) Daniel Fischer 2010+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Utilities for conversion between Double/Float and Rational+--++module GHC.Float.ConversionUtils+    (elimZerosInteger,+     elimZerosInt#+     ) where++import GHC.Internal.Float.ConversionUtils
+ src/GHC/Float/RealFracMethods.hs view
@@ -0,0 +1,58 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Float.RealFracMethods+-- Copyright   :  (c) Daniel Fischer 2010+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Methods for the RealFrac instances for 'Float' and 'Double',+-- with specialised versions for 'Int'.+--+-- Moved to their own module to not bloat "GHC.Float" further.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.Float.RealFracMethods+    (-- *  Double methods+     -- **  Integer results+     properFractionDoubleInteger,+     truncateDoubleInteger,+     floorDoubleInteger,+     ceilingDoubleInteger,+     roundDoubleInteger,+     -- **  Int results+     properFractionDoubleInt,+     floorDoubleInt,+     ceilingDoubleInt,+     roundDoubleInt,+     -- *  Double/Int conversions, wrapped primops+     double2Int,+     int2Double,+     -- *  Float methods+     -- **  Integer results+     properFractionFloatInteger,+     truncateFloatInteger,+     floorFloatInteger,+     ceilingFloatInteger,+     roundFloatInteger,+     -- **  Int results+     properFractionFloatInt,+     floorFloatInt,+     ceilingFloatInt,+     roundFloatInt,+     -- *  Float/Int conversions, wrapped primops+     float2Int,+     int2Float+     ) where++import GHC.Internal.Float.RealFracMethods
+ src/GHC/Foreign.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.Foreign+-- Copyright   :  (c) The University of Glasgow, 2008-2011+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Foreign marshalling support for CStrings with configurable encodings+--++module GHC.Foreign+    (-- *  C strings with a configurable encoding+     CString,+     CStringLen,+     -- *  Conversion of C strings into Haskell strings+     peekCString,+     peekCStringLen,+     -- *  Conversion of Haskell strings into C strings+     newCString,+     newCStringLen,+     newCStringLen0,+     -- *  Conversion of Haskell strings into C strings using temporary storage+     withCString,+     withCStringLen,+     withCStringLen0,+     withCStringsLen,+     charIsRepresentable+     ) where++import GHC.Internal.Foreign.C.String.Encoding
+ src/GHC/ForeignPtr.hs view
@@ -0,0 +1,93 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.ForeignPtr+-- Copyright   :  (c) The University of Glasgow, 1992-2003+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- GHC's implementation of the 'ForeignPtr' data type.+--++module GHC.ForeignPtr+  (+        -- * Types+        ForeignPtr(..),+        ForeignPtrContents(..),+        Finalizers(..),+        FinalizerPtr,+        FinalizerEnvPtr,+        -- * Create+        newForeignPtr_,+        mallocForeignPtr,+        mallocPlainForeignPtr,+        mallocForeignPtrBytes,+        mallocPlainForeignPtrBytes,+        mallocForeignPtrAlignedBytes,+        mallocPlainForeignPtrAlignedBytes,+        newConcForeignPtr,+        -- * Add Finalizers+        addForeignPtrFinalizer,+        addForeignPtrFinalizerEnv,+        addForeignPtrConcFinalizer,+        -- * Conversion+        unsafeForeignPtrToPtr,+        castForeignPtr,+        plusForeignPtr,+        -- * Control over lifetype+        withForeignPtr,+        unsafeWithForeignPtr,+        touchForeignPtr,+        -- * Finalization+        finalizeForeignPtr+        -- * Commentary+        -- $commentary+  ) where++import GHC.Internal.ForeignPtr++{- $commentary++This is a high-level overview of how 'ForeignPtr' works.+The implementation of 'ForeignPtr' must accomplish several goals:++1. Invoke a finalizer once a foreign pointer becomes unreachable.+2. Support augmentation of finalizers, i.e. 'addForeignPtrFinalizer'.+   As a motivating example, suppose that the payload of a foreign+   pointer is C struct @bar@ that has an optionally NULL pointer field+   @foo@ to an unmanaged heap object. Initially, @foo@ is NULL, and+   later the program uses @malloc@, initializes the object, and assigns+   @foo@ the address returned by @malloc@. When the foreign pointer+   becomes unreachable, it is now necessary to first @free@ the object+   pointed to by @foo@ and then invoke whatever finalizer was associated+   with @bar@. That is, finalizers must be invoked in the opposite order+   they are added.+3. Allow users to invoke a finalizer promptly if they know that the+   foreign pointer is unreachable, i.e. 'finalizeForeignPtr'.++How can these goals be accomplished? Goal 1 suggests that weak references+and finalizers (via 'Weak#' and 'mkWeak#') are necessary. But how should+they be used and what should their key be?  Certainly not 'ForeignPtr' or+'ForeignPtrContents'. See the warning in "GHC.Weak" about weak pointers with+lifted (non-primitive) keys. The two finalizer-supporting data constructors of+'ForeignPtr' have an @'IORef' 'Finalizers'@ (backed by 'MutVar#') field.+This gets used in two different ways depending on the kind of finalizer:++* 'HaskellFinalizers': The first @addForeignPtrConcFinalizer_@ call uses+  'mkWeak#' to attach the finalizer @foreignPtrFinalizer@ to the 'MutVar#'.+  The resulting 'Weak#' is discarded (see @addForeignPtrConcFinalizer_@).+  Subsequent calls to @addForeignPtrConcFinalizer_@ (goal 2) just add+  finalizers onto the list in the 'HaskellFinalizers' data constructor.+* 'CFinalizers': The first 'addForeignPtrFinalizer' call uses+  'mkWeakNoFinalizer#' to create a 'Weak#'. The 'Weak#' is preserved in the+  'CFinalizers' data constructor. Both the first call and subsequent+  calls (goal 2) use 'addCFinalizerToWeak#' to attach finalizers to the+  'Weak#' itself. Also, see Note [MallocPtr finalizers] for discussion of+  the key and value of this 'Weak#'.++In either case, the runtime invokes the appropriate finalizers when the+'ForeignPtr' becomes unreachable.+-}
+ src/GHC/GHCi.hs view
@@ -0,0 +1,29 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.GHCi+-- Copyright   :  (c) The University of Glasgow 2012+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The GHCi Monad lifting interface.+--+-- EXPERIMENTAL! DON'T USE.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.GHCi+    {-# WARNING "This is an unstable interface." #-}+    (GHCiSandboxIO(..),+     NoIO()+     ) where++import GHC.Internal.GHCi
+ src/GHC/GHCi/Helpers.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.GHCi.Helpers+-- Copyright   :  (c) The GHC Developers+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Various helpers used by the GHCi shell.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.GHCi.Helpers+    (disableBuffering,+     flushAll,+     evalWrapper+     ) where++import GHC.Internal.GHCi.Helpers
+ src/GHC/Generics.hs view
@@ -0,0 +1,694 @@+{-# LANGUAGE Safe #-}++{-# LANGUAGE ExplicitNamespaces #-}++-- |+-- Module      :  GHC.Generics+-- Copyright   :  (c) Universiteit Utrecht 2010-2011, University of Oxford 2012-2014+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- @since 4.6.0.0+--+-- If you're using @GHC.Generics@, you should consider using the+-- <http://hackage.haskell.org/package/generic-deriving> package, which+-- contains many useful generic functions.++module GHC.Generics  (+-- * Introduction+--+-- |+--+-- Datatype-generic functions are based on the idea of converting values of+-- a datatype @T@ into corresponding values of a (nearly) isomorphic type @'Rep' T@.+-- The type @'Rep' T@ is+-- built from a limited set of type constructors, all provided by this module. A+-- datatype-generic function is then an overloaded function with instances+-- for most of these type constructors, together with a wrapper that performs+-- the mapping between @T@ and @'Rep' T@. By using this technique, we merely need+-- a few generic instances in order to implement functionality that works for any+-- representable type.+--+-- Representable types are collected in the 'Generic' class, which defines the+-- associated type 'Rep' as well as conversion functions 'from' and 'to'.+-- Typically, you will not define 'Generic' instances by hand, but have the compiler+-- derive them for you.++-- ** Representing datatypes+--+-- |+--+-- The key to defining your own datatype-generic functions is to understand how to+-- represent datatypes using the given set of type constructors.+--+-- Let us look at an example first:+--+-- @+-- data Tree a = Leaf a | Node (Tree a) (Tree a)+--   deriving 'Generic'+-- @+--+-- The above declaration (which requires the language pragma @DeriveGeneric@)+-- causes the following representation to be generated:+--+-- @+-- instance 'Generic' (Tree a) where+--   type 'Rep' (Tree a) =+--     'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)+--       ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False)+--          ('S1' ('MetaSel 'Nothing+--                          'NoSourceUnpackedness+--                          'NoSourceStrictness+--                          'DecidedLazy)+--                 ('Rec0' a))+--        ':+:'+--        'C1' ('MetaCons \"Node\" 'PrefixI 'False)+--          ('S1' ('MetaSel 'Nothing+--                          'NoSourceUnpackedness+--                          'NoSourceStrictness+--                          'DecidedLazy)+--                ('Rec0' (Tree a))+--           ':*:'+--           'S1' ('MetaSel 'Nothing+--                          'NoSourceUnpackedness+--                          'NoSourceStrictness+--                          'DecidedLazy)+--                ('Rec0' (Tree a))))+--   ...+-- @+--+-- /Hint:/ You can obtain information about the code being generated from GHC by passing+-- the @-ddump-deriv@ flag. In GHCi, you can expand a type family such as 'Rep' using+-- the @:kind!@ command.+--+-- This is a lot of information! However, most of it is actually merely meta-information+-- that makes names of datatypes and constructors and more available on the type level.+--+-- Here is a reduced representation for @Tree@ with nearly all meta-information removed,+-- for now keeping only the most essential aspects:+--+-- @+-- instance 'Generic' (Tree a) where+--   type 'Rep' (Tree a) =+--     'Rec0' a+--     ':+:'+--     ('Rec0' (Tree a) ':*:' 'Rec0' (Tree a))+-- @+--+-- The @Tree@ datatype has two constructors. The representation of individual constructors+-- is combined using the binary type constructor ':+:'.+--+-- The first constructor consists of a single field, which is the parameter @a@. This is+-- represented as @'Rec0' a@.+--+-- The second constructor consists of two fields. Each is a recursive field of type @Tree a@,+-- represented as @'Rec0' (Tree a)@. Representations of individual fields are combined using+-- the binary type constructor ':*:'.+--+-- Now let us explain the additional tags being used in the complete representation:+--+--    * The @'S1' ('MetaSel 'Nothing 'NoSourceUnpackedness 'NoSourceStrictness+--      'DecidedLazy)@ tag indicates several things. The @'Nothing@ indicates+--      that there is no record field selector associated with this field of+--      the constructor (if there were, it would have been marked @'Just+--      \"recordName\"@ instead). The other types contain meta-information on+--      the field's strictness:+--+--      * There is no @{\-\# UNPACK \#-\}@ or @{\-\# NOUNPACK \#-\}@ annotation+--        in the source, so it is tagged with @'NoSourceUnpackedness@.+--+--      * There is no strictness (@!@) or laziness (@~@) annotation in the+--        source, so it is tagged with @'NoSourceStrictness@.+--+--      * The compiler infers that the field is lazy, so it is tagged with+--        @'DecidedLazy@. Bear in mind that what the compiler decides may be+--        quite different from what is written in the source. See+--        'DecidedStrictness' for a more detailed explanation.+--+--      The @'MetaSel@ type is also an instance of the type class 'Selector',+--      which can be used to obtain information about the field at the value+--      level.+--+--    * The @'C1' ('MetaCons \"Leaf\" 'PrefixI 'False)@ and+--      @'C1' ('MetaCons \"Node\" 'PrefixI 'False)@ invocations indicate that the enclosed part is+--      the representation of the first and second constructor of datatype @Tree@, respectively.+--      Here, the meta-information regarding constructor names, fixity and whether+--      it has named fields or not is encoded at the type level. The @'MetaCons@+--      type is also an instance of the type class 'Constructor'. This type class can be used+--      to obtain information about the constructor at the value level.+--+--    * The @'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)@ tag+--      indicates that the enclosed part is the representation of the+--      datatype @Tree@. Again, the meta-information is encoded at the type level.+--      The @'MetaData@ type is an instance of class 'Datatype', which+--      can be used to obtain the name of a datatype, the module it has been+--      defined in, the package it is located under, and whether it has been+--      defined using @data@ or @newtype@ at the value level.++-- ** Derived and fundamental representation types+--+-- |+--+-- There are many datatype-generic functions that do not distinguish between positions that+-- are parameters or positions that are recursive calls. There are also many datatype-generic+-- functions that do not care about the names of datatypes and constructors at all. To keep+-- the number of cases to consider in generic functions in such a situation to a minimum,+-- it turns out that many of the type constructors introduced above are actually synonyms,+-- defining them to be variants of a smaller set of constructors.++-- *** Individual fields of constructors: 'K1'+--+-- |+--+-- The type constructor 'Rec0' is a variant of 'K1':+--+-- @+-- type 'Rec0' = 'K1' 'R'+-- @+--+-- Here, 'R' is a type-level proxy that does not have any associated values.+--+-- There used to be another variant of 'K1' (namely @Par0@), but it has since+-- been deprecated.++-- *** Meta information: 'M1'+--+-- |+--+-- The type constructors 'S1', 'C1' and 'D1' are all variants of 'M1':+--+-- @+-- type 'S1' = 'M1' 'S'+-- type 'C1' = 'M1' 'C'+-- type 'D1' = 'M1' 'D'+-- @+--+-- The types 'S', 'C' and 'D' are once again type-level proxies, just used to create+-- several variants of 'M1'.++-- *** Additional generic representation type constructors+--+-- |+--+-- Next to 'K1', 'M1', ':+:' and ':*:' there are a few more type constructors that occur+-- in the representations of other datatypes.++-- **** Empty datatypes: 'V1'+--+-- |+--+-- For empty datatypes, 'V1' is used as a representation. For example,+--+-- @+-- data Empty deriving 'Generic'+-- @+--+-- yields+--+-- @+-- instance 'Generic' Empty where+--   type 'Rep' Empty =+--     'D1' ('MetaData \"Empty\" \"Main\" \"package-name\" 'False) 'V1'+-- @++-- **** Constructors without fields: 'U1'+--+-- |+--+-- If a constructor has no arguments, then 'U1' is used as its representation. For example+-- the representation of 'Bool' is+--+-- @+-- instance 'Generic' Bool where+--   type 'Rep' Bool =+--     'D1' ('MetaData \"Bool\" \"Data.Bool\" \"package-name\" 'False)+--       ('C1' ('MetaCons \"False\" 'PrefixI 'False) 'U1' ':+:' 'C1' ('MetaCons \"True\" 'PrefixI 'False) 'U1')+-- @++-- *** Representation of types with many constructors or many fields+--+-- |+--+-- As ':+:' and ':*:' are just binary operators, one might ask what happens if the+-- datatype has more than two constructors, or a constructor with more than two+-- fields. The answer is simple: the operators are used several times, to combine+-- all the constructors and fields as needed. However, users /should not rely on+-- a specific nesting strategy/ for ':+:' and ':*:' being used. The compiler is+-- free to choose any nesting it prefers. (In practice, the current implementation+-- tries to produce a more-or-less balanced nesting, so that the traversal of+-- the structure of the datatype from the root to a particular component can be+-- performed in logarithmic rather than linear time.)++-- ** Defining datatype-generic functions+--+-- |+--+-- A datatype-generic function comprises two parts:+--+--    1. /Generic instances/ for the function, implementing it for most of the representation+--       type constructors introduced above.+--+--    2. A /wrapper/ that for any datatype that is in `Generic`, performs the conversion+--       between the original value and its `Rep`-based representation and then invokes the+--       generic instances.+--+-- As an example, let us look at a function @encode@ that produces a naive, but lossless+-- bit encoding of values of various datatypes. So we are aiming to define a function+--+-- @+-- encode :: 'Generic' a => a -> [Bool]+-- @+--+-- where we use 'Bool' as our datatype for bits.+--+-- For part 1, we define a class @Encode'@. Perhaps surprisingly, this class is parameterized+-- over a type constructor @f@ of kind @* -> *@. This is a technicality: all the representation+-- type constructors operate with kind @* -> *@ as base kind. But the type argument is never+-- being used. This may be changed at some point in the future. The class has a single method,+-- and we use the type we want our final function to have, but we replace the occurrences of+-- the generic type argument @a@ with @f p@ (where the @p@ is any argument; it will not be used).+--+-- > class Encode' f where+-- >   encode' :: f p -> [Bool]+--+-- With the goal in mind to make @encode@ work on @Tree@ and other datatypes, we now define+-- instances for the representation type constructors 'V1', 'U1', ':+:', ':*:', 'K1', and 'M1'.++-- *** Definition of the generic representation types+--+-- |+--+-- In order to be able to do this, we need to know the actual definitions of these types:+--+-- @+-- data    'V1'        p                       -- lifted version of Empty+-- data    'U1'        p = 'U1'                  -- lifted version of ()+-- data    (':+:') f g p = 'L1' (f p) | 'R1' (g p) -- lifted version of 'Either'+-- data    (':*:') f g p = (f p) ':*:' (g p)     -- lifted version of (,)+-- newtype 'K1'    i c p = 'K1' { 'unK1' :: c }    -- a container for a c+-- newtype 'M1'  i t f p = 'M1' { 'unM1' :: f p }  -- a wrapper+-- @+--+-- So, 'U1' is just the unit type, ':+:' is just a binary choice like 'Either',+-- ':*:' is a binary pair like the pair constructor @(,)@, and 'K1' is a value+-- of a specific type @c@, and 'M1' wraps a value of the generic type argument,+-- which in the lifted world is an @f p@ (where we do not care about @p@).++-- *** Generic instances+--+-- |+--+-- To deal with the 'V1' case, we use the following code (which requires the pragma @EmptyCase@):+--+-- @+-- instance Encode' 'V1' where+--   encode' x = case x of { }+-- @+--+-- There are no values of type @V1 p@ to pass, so it is impossible for this+-- function to be invoked. One can ask why it is useful to define an instance+-- for 'V1' at all in this case? Well, an empty type can be used as an argument+-- to a non-empty type, and you might still want to encode the resulting type.+-- As a somewhat contrived example, consider @[Empty]@, which is not an empty+-- type, but contains just the empty list. The 'V1' instance ensures that we+-- can call the generic function on such types.+--+-- There is exactly one value of type 'U1', so encoding it requires no+-- knowledge, and we can use zero bits:+--+-- @+-- instance Encode' 'U1' where+--   encode' 'U1' = []+-- @+--+-- In the case for ':+:', we produce 'False' or 'True' depending on whether+-- the constructor of the value provided is located on the left or on the right:+--+-- @+-- instance (Encode' f, Encode' g) => Encode' (f ':+:' g) where+--   encode' ('L1' x) = False : encode' x+--   encode' ('R1' x) = True  : encode' x+-- @+--+-- (Note that this encoding strategy may not be reliable across different+-- versions of GHC. Recall that the compiler is free to choose any nesting+-- of ':+:' it chooses, so if GHC chooses @(a ':+:' b) ':+:' c@, then the+-- encoding for @a@ would be @[False, False]@, @b@ would be @[False, True]@,+-- and @c@ would be @[True]@. However, if GHC chooses @a ':+:' (b ':+:' c)@,+-- then the encoding for @a@ would be @[False]@, @b@ would be @[True, False]@,+-- and @c@ would be @[True, True]@.)+--+-- In the case for ':*:', we append the encodings of the two subcomponents:+--+-- @+-- instance (Encode' f, Encode' g) => Encode' (f ':*:' g) where+--   encode' (x ':*:' y) = encode' x ++ encode' y+-- @+--+-- The case for 'K1' is rather interesting. Here, we call the final function+-- @encode@ that we yet have to define, recursively. We will use another type+-- class @Encode@ for that function:+--+-- @+-- instance (Encode c) => Encode' ('K1' i c) where+--   encode' ('K1' x) = encode x+-- @+--+-- Note how we can define a uniform instance for 'M1', because we completely+-- disregard all meta-information:+--+-- @+-- instance (Encode' f) => Encode' ('M1' i t f) where+--   encode' ('M1' x) = encode' x+-- @+--+-- Unlike in 'K1', the instance for 'M1' refers to @encode'@, not @encode@.++-- *** The wrapper and generic default+--+-- |+--+-- We now define class @Encode@ for the actual @encode@ function:+--+-- @+-- class Encode a where+--   encode :: a -> [Bool]+--   default encode :: (Generic a, Encode' (Rep a)) => a -> [Bool]+--   encode x = encode' ('from' x)+-- @+--+-- The incoming @x@ is converted using 'from', then we dispatch to the+-- generic instances using @encode'@. We use this as a default definition+-- for @encode@. We need the @default encode@ signature because ordinary+-- Haskell default methods must not introduce additional class constraints,+-- but our generic default does.+--+-- Defining a particular instance is now as simple as saying+--+-- @+-- instance (Encode a) => Encode (Tree a)+-- @+--+-- The generic default is being used. In the future, it will hopefully be+-- possible to use @deriving Encode@ as well, but GHC does not yet support+-- that syntax for this situation.+--+-- Having @Encode@ as a class has the advantage that we can define+-- non-generic special cases, which is particularly useful for abstract+-- datatypes that have no structural representation. For example, given+-- a suitable integer encoding function @encodeInt@, we can define+--+-- @+-- instance Encode Int where+--   encode = encodeInt+-- @++-- *** Omitting generic instances+--+-- |+--+-- It is not always required to provide instances for all the generic+-- representation types, but omitting instances restricts the set of+-- datatypes the functions will work for:+--+--    * If no ':+:' instance is given, the function may still work for+--      empty datatypes or datatypes that have a single constructor,+--      but will fail on datatypes with more than one constructor.+--+--    * If no ':*:' instance is given, the function may still work for+--      datatypes where each constructor has just zero or one field,+--      in particular for enumeration types.+--+--    * If no 'K1' instance is given, the function may still work for+--      enumeration types, where no constructor has any fields.+--+--    * If no 'V1' instance is given, the function may still work for+--      any datatype that is not empty.+--+--    * If no 'U1' instance is given, the function may still work for+--      any datatype where each constructor has at least one field.+--+-- An 'M1' instance is always required (but it can just ignore the+-- meta-information, as is the case for @encode@ above).+--+-- ** Generic constructor classes+--+-- |+--+-- Datatype-generic functions as defined above work for a large class+-- of datatypes, including parameterized datatypes. (We have used @Tree@+-- as our example above, which is of kind @* -> *@.) However, the+-- 'Generic' class ranges over types of kind @*@, and therefore, the+-- resulting generic functions (such as @encode@) must be parameterized+-- by a generic type argument of kind @*@.+--+-- What if we want to define generic classes that range over type+-- constructors (such as 'Data.Functor.Functor',+-- 'Data.Traversable.Traversable', or 'Data.Foldable.Foldable')?++-- *** The 'Generic1' class+--+-- |+--+-- Like 'Generic', there is a class 'Generic1' that defines a+-- representation 'Rep1' and conversion functions 'from1' and 'to1',+-- only that 'Generic1' ranges over types of kind @* -> *@. (More generally,+-- it can range over types of kind @k -> *@, for any kind @k@, if the+-- @PolyKinds@ extension is enabled. More on this later.)+-- The 'Generic1' class is also derivable.+--+-- The representation 'Rep1' is ever so slightly different from 'Rep'.+-- Let us look at @Tree@ as an example again:+--+-- @+-- data Tree a = Leaf a | Node (Tree a) (Tree a)+--   deriving 'Generic1'+-- @+--+-- The above declaration causes the following representation to be generated:+--+-- @+-- instance 'Generic1' Tree where+--   type 'Rep1' Tree =+--     'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)+--       ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False)+--          ('S1' ('MetaSel 'Nothing+--                          'NoSourceUnpackedness+--                          'NoSourceStrictness+--                          'DecidedLazy)+--                'Par1')+--        ':+:'+--        'C1' ('MetaCons \"Node\" 'PrefixI 'False)+--          ('S1' ('MetaSel 'Nothing+--                          'NoSourceUnpackedness+--                          'NoSourceStrictness+--                          'DecidedLazy)+--                ('Rec1' Tree)+--           ':*:'+--           'S1' ('MetaSel 'Nothing+--                          'NoSourceUnpackedness+--                          'NoSourceStrictness+--                          'DecidedLazy)+--                ('Rec1' Tree)))+--   ...+-- @+--+-- The representation reuses 'D1', 'C1', 'S1' (and thereby 'M1') as well+-- as ':+:' and ':*:' from 'Rep'. (This reusability is the reason that we+-- carry around the dummy type argument for kind-@*@-types, but there are+-- already enough different names involved without duplicating each of+-- these.)+--+-- What's different is that we now use 'Par1' to refer to the parameter+-- (and that parameter, which used to be @a@), is not mentioned explicitly+-- by name anywhere; and we use 'Rec1' to refer to a recursive use of @Tree a@.++-- *** Representation of @* -> *@ types+--+-- |+--+-- Unlike 'Rec0', the 'Par1' and 'Rec1' type constructors do not+-- map to 'K1'. They are defined directly, as follows:+--+-- @+-- newtype 'Par1'   p = 'Par1' { 'unPar1' ::   p } -- gives access to parameter p+-- newtype 'Rec1' f p = 'Rec1' { 'unRec1' :: f p } -- a wrapper+-- @+--+-- In 'Par1', the parameter @p@ is used for the first time, whereas 'Rec1' simply+-- wraps an application of @f@ to @p@.+--+-- Note that 'K1' (in the guise of 'Rec0') can still occur in a 'Rep1' representation,+-- namely when the datatype has a field that does not mention the parameter.+--+-- The declaration+--+-- @+-- data WithInt a = WithInt Int a+--   deriving 'Generic1'+-- @+--+-- yields+--+-- @+-- instance 'Generic1' WithInt where+--   type 'Rep1' WithInt =+--     'D1' ('MetaData \"WithInt\" \"Main\" \"package-name\" 'False)+--       ('C1' ('MetaCons \"WithInt\" 'PrefixI 'False)+--         ('S1' ('MetaSel 'Nothing+--                         'NoSourceUnpackedness+--                         'NoSourceStrictness+--                         'DecidedLazy)+--               ('Rec0' Int)+--          ':*:'+--          'S1' ('MetaSel 'Nothing+--                          'NoSourceUnpackedness+--                          'NoSourceStrictness+--                          'DecidedLazy)+--               'Par1'))+-- @+--+-- If the parameter @a@ appears underneath a composition of other type constructors,+-- then the representation involves composition, too:+--+-- @+-- data Rose a = Fork a [Rose a]+-- @+--+-- yields+--+-- @+-- instance 'Generic1' Rose where+--   type 'Rep1' Rose =+--     'D1' ('MetaData \"Rose\" \"Main\" \"package-name\" 'False)+--       ('C1' ('MetaCons \"Fork\" 'PrefixI 'False)+--         ('S1' ('MetaSel 'Nothing+--                         'NoSourceUnpackedness+--                         'NoSourceStrictness+--                         'DecidedLazy)+--               'Par1'+--          ':*:'+--          'S1' ('MetaSel 'Nothing+--                          'NoSourceUnpackedness+--                          'NoSourceStrictness+--                          'DecidedLazy)+--               ([] ':.:' 'Rec1' Rose)))+-- @+--+-- where+--+-- @+-- newtype (':.:') f g p = 'Comp1' { 'unComp1' :: f (g p) }+-- @++-- *** Representation of @k -> *@ types+--+-- |+--+-- The 'Generic1' class can be generalized to range over types of kind+-- @k -> *@, for any kind @k@. To do so, derive a 'Generic1' instance with the+-- @PolyKinds@ extension enabled. For example, the declaration+--+-- @+-- data Proxy (a :: k) = Proxy deriving 'Generic1'+-- @+--+-- yields a slightly different instance depending on whether @PolyKinds@ is+-- enabled. If compiled without @PolyKinds@, then @'Rep1' Proxy :: * -> *@, but+-- if compiled with @PolyKinds@, then @'Rep1' Proxy :: k -> *@.++-- *** Representation of unlifted types+--+-- |+--+-- If one were to attempt to derive a Generic instance for a datatype with an+-- unlifted argument (for example, 'Int#'), one might expect the occurrence of+-- the 'Int#' argument to be marked with @'Rec0' 'Int#'@. This won't work,+-- though, since 'Int#' is of an unlifted kind, and 'Rec0' expects a type of+-- kind @*@.+--+-- One solution would be to represent an occurrence of 'Int#' with 'Rec0 Int'+-- instead. With this approach, however, the programmer has no way of knowing+-- whether the 'Int' is actually an 'Int#' in disguise.+--+-- Instead of reusing 'Rec0', a separate data family 'URec' is used to mark+-- occurrences of common unlifted types:+--+-- @+-- data family URec a p+--+-- data instance 'URec' ('Ptr' ()) p = 'UAddr'   { 'uAddr#'   :: 'Addr#'   }+-- data instance 'URec' 'Char'     p = 'UChar'   { 'uChar#'   :: 'Char#'   }+-- data instance 'URec' 'Double'   p = 'UDouble' { 'uDouble#' :: 'Double#' }+-- data instance 'URec' 'Int'      p = 'UFloat'  { 'uFloat#'  :: 'Float#'  }+-- data instance 'URec' 'Float'    p = 'UInt'    { 'uInt#'    :: 'Int#'    }+-- data instance 'URec' 'Word'     p = 'UWord'   { 'uWord#'   :: 'Word#'   }+-- @+--+-- Several type synonyms are provided for convenience:+--+-- @+-- type 'UAddr'   = 'URec' ('Ptr' ())+-- type 'UChar'   = 'URec' 'Char'+-- type 'UDouble' = 'URec' 'Double'+-- type 'UFloat'  = 'URec' 'Float'+-- type 'UInt'    = 'URec' 'Int'+-- type 'UWord'   = 'URec' 'Word'+-- @+--+-- The declaration+--+-- @+-- data IntHash = IntHash Int#+--   deriving 'Generic'+-- @+--+-- yields+--+-- @+-- instance 'Generic' IntHash where+--   type 'Rep' IntHash =+--     'D1' ('MetaData \"IntHash\" \"Main\" \"package-name\" 'False)+--       ('C1' ('MetaCons \"IntHash\" 'PrefixI 'False)+--         ('S1' ('MetaSel 'Nothing+--                         'NoSourceUnpackedness+--                         'NoSourceStrictness+--                         'DecidedLazy)+--               'UInt'))+-- @+--+-- Currently, only the six unlifted types listed above are generated, but this+-- may be extended to encompass more unlifted types in the future.++  -- * Generic representation types+    V1, U1(..), Par1(..), Rec1(..), K1(..), M1(..)+  , (:+:)(..), (:*:)(..), (:.:)(..)++  -- ** Unboxed representation types+  , URec(..)+  , type UAddr, type UChar, type UDouble+  , type UFloat, type UInt, type UWord++  -- ** Synonyms for convenience+  , Rec0, R+  , D1, C1, S1, D, C, S++  -- * Meta-information+  , Datatype(..), Constructor(..), Selector(..)+  , Fixity(..), FixityI(..), Associativity(..), prec+  , SourceUnpackedness(..), SourceStrictness(..), DecidedStrictness(..)+  , Meta(..)++  -- * Generic type classes+  , Generic(..)+  , Generic1(..)++  -- * Generic wrapper+  , Generically(..)+  , Generically1(..)+  ) where++import GHC.Internal.Generics
+ src/GHC/IO.hs view
@@ -0,0 +1,39 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.IO+-- Copyright   :  (c) The University of Glasgow 1994-2023+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Definitions for the 'IO' monad and its friends.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.IO (+        IO(..), unIO, liftIO, mplusIO,+        unsafePerformIO, unsafeInterleaveIO,+        unsafeDupablePerformIO, unsafeDupableInterleaveIO,+        noDuplicate,++        -- To and from ST+        stToIO, ioToST, unsafeIOToST, unsafeSTToIO,++        FilePath,++        catch, catchException, catchAny, throwIO,+        mask, mask_, uninterruptibleMask, uninterruptibleMask_,+        MaskingState(..), getMaskingState,+        unsafeUnmask, interruptible,+        onException, bracket, finally, evaluate,+        mkUserError+    ) where++import GHC.Internal.IO
+ src/GHC/IO/Buffer.hs view
@@ -0,0 +1,66 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.Buffer+-- Copyright   :  (c) The University of Glasgow 2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Buffers used in the IO system+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.IO.Buffer+    (-- *  Buffers of any element+     Buffer(..),+     BufferState(..),+     CharBuffer,+     CharBufElem,+     -- **  Creation+     newByteBuffer,+     newCharBuffer,+     newBuffer,+     emptyBuffer,+     -- **  Insertion/removal+     bufferRemove,+     bufferAdd,+     slideContents,+     bufferAdjustL,+     bufferAddOffset,+     bufferAdjustOffset,+     -- **  Inspecting+     isEmptyBuffer,+     isFullBuffer,+     isFullCharBuffer,+     isWriteBuffer,+     bufferElems,+     bufferAvailable,+     bufferOffset,+     summaryBuffer,+     -- **  Operating on the raw buffer as a Ptr+     withBuffer,+     withRawBuffer,+     -- **  Assertions+     checkBuffer,+     -- *  Raw buffers+     RawBuffer,+     readWord8Buf,+     writeWord8Buf,+     RawCharBuffer,+     peekCharBuf,+     readCharBuf,+     writeCharBuf,+     readCharBufPtr,+     writeCharBufPtr,+     charSize+     ) where++import GHC.Internal.IO.Buffer
+ src/GHC/IO/BufferedIO.hs view
@@ -0,0 +1,24 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.BufferedIO+-- Copyright   :  (c) The University of Glasgow 2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Class of buffered IO devices+--++module GHC.IO.BufferedIO+    (BufferedIO(..),+     readBuf,+     readBufNonBlocking,+     writeBuf,+     writeBufNonBlocking+     ) where++import GHC.Internal.IO.BufferedIO
+ src/GHC/IO/Device.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  GHC.IO.Device+-- Copyright   :  (c) The University of Glasgow, 1994-2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Type classes for I/O providers.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.IO.Device (+        RawIO(..),+        IODevice(..),+        IODeviceType(..),+        SeekMode(..)+    ) where++import GHC.Internal.IO.Device
+ src/GHC/IO/Encoding.hs view
@@ -0,0 +1,50 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.Encoding+-- Copyright   :  (c) The University of Glasgow, 2008-2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Text codecs for I/O+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.IO.Encoding+    (BufferCodec(..),+     TextEncoding(..),+     TextEncoder,+     TextDecoder,+     CodingProgress(..),+     latin1,+     latin1_encode,+     latin1_decode,+     utf8,+     utf8_bom,+     utf16,+     utf16le,+     utf16be,+     utf32,+     utf32le,+     utf32be,+     initLocaleEncoding,+     getLocaleEncoding,+     getFileSystemEncoding,+     getForeignEncoding,+     setLocaleEncoding,+     setFileSystemEncoding,+     setForeignEncoding,+     char8,+     mkTextEncoding,+     argvEncoding+     ) where++import GHC.Internal.IO.Encoding
+ src/GHC/IO/Encoding/CodePage.hs view
@@ -0,0 +1,21 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Safe #-}++#if ! defined(mingw32_HOST_OS)++module GHC.IO.Encoding.CodePage ( ) where++-- See W1 of Note [Tracking dependencies on primitives] in GHC.Internal.Base+import Prelude () -- for build ordering++#else++module GHC.IO.Encoding.CodePage+  ( codePageEncoding, mkCodePageEncoding,+    localeEncoding, mkLocaleEncoding, CodePage,+    getCurrentCodePage+  ) where++import GHC.Internal.IO.Encoding.CodePage++#endif
+ src/GHC/IO/Encoding/CodePage/API.hs view
@@ -0,0 +1,7 @@+{-# LANGUAGE Safe #-}++module GHC.IO.Encoding.CodePage.API (+    mkCodePageEncoding+  ) where++import GHC.Internal.IO.Encoding.CodePage.API
+ src/GHC/IO/Encoding/CodePage/Table.hs view
@@ -0,0 +1,8 @@+{-# LANGUAGE Trustworthy #-}++module GHC.IO.Encoding.CodePage.Table+    ( module GHC.Internal.IO.Encoding.CodePage.Table+    ) where++import GHC.Internal.IO.Encoding.CodePage.Table+
+ src/GHC/IO/Encoding/Failure.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE MagicHash #-}++-- |+--+-- Module      :  GHC.IO.Encoding.Failure+-- Copyright   :  (c) The University of Glasgow, 2008-2011+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Types for specifying how text encoding/decoding fails+--++module GHC.IO.Encoding.Failure+    (CodingFailureMode(..),+     codingFailureModeSuffix,+     isSurrogate,+     recoverDecode,+     recoverEncode,+     recoverDecode#,+     recoverEncode#+     ) where++import GHC.Internal.IO.Encoding.Failure
+ src/GHC/IO/Encoding/Iconv.hs view
@@ -0,0 +1,30 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.IO.Encoding.Iconv+-- Copyright   :  (c) The University of Glasgow, 2008-2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- This module provides text encoding/decoding using iconv+--++module GHC.IO.Encoding.Iconv+#if !defined(mingw32_HOST_OS)+    (iconvEncoding,+     mkIconvEncoding,+     localeEncodingName+     ) where++import GHC.Internal.IO.Encoding.Iconv++#else+    ( ) where++#endif
+ src/GHC/IO/Encoding/Latin1.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.Encoding.Latin1+-- Copyright   :  (c) The University of Glasgow, 2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Single-byte encodings that map directly to Unicode code points.+--+-- Portions Copyright   : (c) Tom Harper 2008-2009,+--                        (c) Bryan O'Sullivan 2009,+--                        (c) Duncan Coutts 2009+--++module GHC.IO.Encoding.Latin1+    (latin1,+     mkLatin1,+     latin1_checked,+     mkLatin1_checked,+     ascii,+     mkAscii,+     latin1_decode,+     ascii_decode,+     latin1_encode,+     latin1_checked_encode,+     ascii_encode+     ) where++import GHC.Internal.IO.Encoding.Latin1
+ src/GHC/IO/Encoding/Types.hs view
@@ -0,0 +1,33 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE MagicHash #-}+{-# LANGUAGE PatternSynonyms #-}++-- |+--+-- Module      :  GHC.IO.Encoding.Types+-- Copyright   :  (c) The University of Glasgow, 2008-2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Types for text encoding/decoding+--++module GHC.IO.Encoding.Types+    (BufferCodec(..),+     TextEncoding(..),+     TextEncoder,+     TextDecoder,+     CodeBuffer,+     EncodeBuffer,+     DecodeBuffer,+     CodingProgress(..),+     DecodeBuffer#,+     EncodeBuffer#,+     DecodingBuffer#,+     EncodingBuffer#+     ) where++import GHC.Internal.IO.Encoding.Types
+ src/GHC/IO/Encoding/UTF16.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.Encoding.UTF16+-- Copyright   :  (c) The University of Glasgow, 2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- UTF-16 Codecs for the IO library+--+-- Portions Copyright   : (c) Tom Harper 2008-2009,+--                        (c) Bryan O'Sullivan 2009,+--                        (c) Duncan Coutts 2009+--++module GHC.IO.Encoding.UTF16+    (utf16,+     mkUTF16,+     utf16_decode,+     utf16_encode,+     utf16be,+     mkUTF16be,+     utf16be_decode,+     utf16be_encode,+     utf16le,+     mkUTF16le,+     utf16le_decode,+     utf16le_encode+     ) where++import GHC.Internal.IO.Encoding.UTF16
+ src/GHC/IO/Encoding/UTF32.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.Encoding.UTF32+-- Copyright   :  (c) The University of Glasgow, 2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- UTF-32 Codecs for the IO library+--+-- Portions Copyright   : (c) Tom Harper 2008-2009,+--                        (c) Bryan O'Sullivan 2009,+--                        (c) Duncan Coutts 2009+--++module GHC.IO.Encoding.UTF32+    (utf32,+     mkUTF32,+     utf32_decode,+     utf32_encode,+     utf32be,+     mkUTF32be,+     utf32be_decode,+     utf32be_encode,+     utf32le,+     mkUTF32le,+     utf32le_decode,+     utf32le_encode+     ) where++import GHC.Internal.IO.Encoding.UTF32
+ src/GHC/IO/Encoding/UTF8.hs view
@@ -0,0 +1,31 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.Encoding.UTF8+-- Copyright   :  (c) The University of Glasgow, 2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- UTF-8 Codec for the IO library+--+-- This is one of several UTF-8 implementations provided by GHC; see Note+-- [GHC's many UTF-8 implementations] in "GHC.Encoding.UTF8" for an+-- overview.+--+-- Portions Copyright   : (c) Tom Harper 2008-2009,+--                        (c) Bryan O'Sullivan 2009,+--                        (c) Duncan Coutts 2009+--++module GHC.IO.Encoding.UTF8+    (utf8,+     mkUTF8,+     utf8_bom,+     mkUTF8_bom+     ) where++import GHC.Internal.IO.Encoding.UTF8
+ src/GHC/IO/Exception.hs view
@@ -0,0 +1,50 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.IO.Exception+-- Copyright   :  (c) The University of Glasgow, 2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- IO-related Exception types and functions+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.IO.Exception (+  BlockedIndefinitelyOnMVar(..), blockedIndefinitelyOnMVar,+  BlockedIndefinitelyOnSTM(..), blockedIndefinitelyOnSTM,+  Deadlock(..),+  AllocationLimitExceeded(..), allocationLimitExceeded,+  AssertionFailed(..),+  CompactionFailed(..),+  cannotCompactFunction, cannotCompactPinned, cannotCompactMutable,++  SomeAsyncException(..),+  asyncExceptionToException, asyncExceptionFromException,+  AsyncException(..), stackOverflow, heapOverflow,++  ArrayException(..),+  ExitCode(..),+  FixIOException (..),++  ioException,+  ioError,+  IOError,+  IOException(..),+  IOErrorType(..),+  userError,+  assertError,+  unsupportedOperation,+  untangle,+ ) where++import GHC.Internal.IO.Exception+
+ src/GHC/IO/FD.hs view
@@ -0,0 +1,32 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.IO.FD+-- Copyright   :  (c) The University of Glasgow, 1994-2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Raw read/write operations on file descriptors+--++module GHC.IO.FD+    (FD(..),+     openFileWith,+     openFile,+     mkFD,+     release,+     setNonBlockingMode,+     readRawBufferPtr,+     readRawBufferPtrNoBlock,+     writeRawBufferPtr,+     stdin,+     stdout,+     stderr+     ) where++import GHC.Internal.IO.FD
+ src/GHC/IO/Handle.hs view
@@ -0,0 +1,76 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.Handle+-- Copyright   :  (c) The University of Glasgow, 1994-2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  non-portable+--+-- External API for GHC's Handle implementation+--++module GHC.IO.Handle+    (Handle,+     BufferMode(..),+     mkFileHandle,+     mkDuplexHandle,+     hFileSize,+     hSetFileSize,+     hIsEOF,+     isEOF,+     hLookAhead,+     hSetBuffering,+     hSetBinaryMode,+     hSetEncoding,+     hGetEncoding,+     hFlush,+     hFlushAll,+     hDuplicate,+     hDuplicateTo,+     hClose,+     hClose_help,+     LockMode(..),+     hLock,+     hTryLock,+     HandlePosition,+     HandlePosn(..),+     hGetPosn,+     hSetPosn,+     SeekMode(..),+     hSeek,+     hTell,+     hIsOpen,+     hIsClosed,+     hIsReadable,+     hIsWritable,+     hGetBuffering,+     hIsSeekable,+     hSetEcho,+     hGetEcho,+     hIsTerminalDevice,+     hSetNewlineMode,+     Newline(..),+     NewlineMode(..),+     nativeNewline,+     noNewlineTranslation,+     universalNewlineMode,+     nativeNewlineMode,+     hShow,+     hWaitForInput,+     hGetChar,+     hGetLine,+     hGetContents,+     hGetContents',+     hPutChar,+     hPutStr,+     hGetBuf,+     hGetBufNonBlocking,+     hPutBuf,+     hPutBufNonBlocking+     ) where++import GHC.Internal.IO.Handle
+ src/GHC/IO/Handle/FD.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.Handle.FD+-- Copyright   :  (c) The University of Glasgow, 1994-2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Handle operations implemented by file descriptors (FDs)+--+-- @since 4.2.0.0+--++module GHC.IO.Handle.FD+    (stdin,+     stdout,+     stderr,+     openFile,+     withFile,+     openBinaryFile,+     withBinaryFile,+     openFileBlocking,+     withFileBlocking,+     mkHandleFromFD,+     fdToHandle,+     fdToHandle',+     handleToFd+     ) where++import GHC.Internal.IO.Handle.FD
+ src/GHC/IO/Handle/Internals.hs view
@@ -0,0 +1,72 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.IO.Handle.Internals+-- Copyright   :  (c) The University of Glasgow, 1994-2001+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- This module defines the basic operations on I\/O \"handles\".  All+-- of the operations defined here are independent of the underlying+-- device.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.IO.Handle.Internals+    (withHandle,+     withHandle',+     withHandle_,+     withHandle__',+     withHandle_',+     withAllHandles__,+     wantWritableHandle,+     wantReadableHandle,+     wantReadableHandle_,+     wantSeekableHandle,+     mkHandle,+     mkFileHandle,+     mkFileHandleNoFinalizer,+     mkDuplexHandle,+     mkDuplexHandleNoFinalizer,+     addHandleFinalizer,+     openTextEncoding,+     closeTextCodecs,+     initBufferState,+     dEFAULT_CHAR_BUFFER_SIZE,+     flushBuffer,+     flushWriteBuffer,+     flushCharReadBuffer,+     flushCharBuffer,+     flushByteReadBuffer,+     flushByteWriteBuffer,+     readTextDevice,+     writeCharBuffer,+     readTextDeviceNonBlocking,+     decodeByteBuf,+     augmentIOError,+     ioe_closedHandle,+     ioe_semiclosedHandle,+     ioe_EOF,+     ioe_notReadable,+     ioe_notWritable,+     ioe_finalizedHandle,+     ioe_bufsiz,+     hClose_impl,+     hClose_help,+     hLookAhead_,+     HandleFinalizer,+     handleFinalizer,+     debugIO,+     traceIO+     ) where++import GHC.Internal.IO.Handle.Internals
+ src/GHC/IO/Handle/Lock.hs view
@@ -0,0 +1,9 @@+module GHC.IO.Handle.Lock+    (FileLockingNotSupported(..),+     LockMode(..),+     hLock,+     hTryLock,+     hUnlock+     ) where++import GHC.Internal.IO.Handle.Lock
+ src/GHC/IO/Handle/Text.hs view
@@ -0,0 +1,28 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.IO.Handle.Text+-- Copyright   :  (c) The University of Glasgow, 1992-2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- String I\/O functions+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.IO.Handle.Text (+        hWaitForInput, hGetChar, hGetLine, hGetContents, hPutChar, hPutStr,+        commitBuffer',       -- hack, see below+        hGetBuf, hGetBufSome, hGetBufNonBlocking, hPutBuf, hPutBufNonBlocking,+        memcpy, hPutStrLn, hGetContents',+    ) where++import GHC.Internal.IO.Handle.Text
+ src/GHC/IO/Handle/Types.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.IO.Handle.Types+-- Copyright   :  (c) The University of Glasgow, 1994-2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Basic types for the implementation of IO Handles.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.IO.Handle.Types (+      Handle(..), Handle__(..), showHandle,+      checkHandleInvariants,+      BufferList(..),+      HandleType(..),+      isReadableHandleType, isWritableHandleType, isReadWriteHandleType,+      isAppendHandleType,+      BufferMode(..),+      BufferCodec(..),+      NewlineMode(..), Newline(..), nativeNewline,+      universalNewlineMode, noNewlineTranslation, nativeNewlineMode+  ) where++import GHC.Internal.IO.Handle.Types
+ src/GHC/IO/Handle/Windows.hs view
@@ -0,0 +1,20 @@+-- |+-- Module      :  GHC.IO.Handle.Windows+-- Copyright   :  (c) The University of Glasgow, 2017+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Handle operations implemented by Windows native handles+--+-----------------------------------------------------------------------------++module GHC.IO.Handle.Windows (+  stdin, stdout, stderr,+  openFile, openBinaryFile, openFileBlocking,+  handleToHANDLE, mkHandleFromHANDLE+ ) where++import GHC.Internal.IO.Handle.Windows
+ src/GHC/IO/IOMode.hs view
@@ -0,0 +1,21 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.IO.IOMode+-- Copyright   :  (c) The University of Glasgow, 1994-2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- The IOMode type+--++module GHC.IO.IOMode+    (IOMode(..)+     ) where++import GHC.Internal.IO.IOMode
+ src/GHC/IO/StdHandles.hs view
@@ -0,0 +1,29 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.StdHandles+-- Copyright   :  (c) The University of Glasgow, 2017+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- This model abstracts away the platform specific handles that can be toggled+-- through the RTS.+--++module GHC.IO.StdHandles+    (stdin,+     stdout,+     stderr,+     openFile,+     openBinaryFile,+     openFileBlocking,+     withFile,+     withBinaryFile,+     withFileBlocking+     ) where++import GHC.Internal.IO.StdHandles
+ src/GHC/IO/SubSystem.hs view
@@ -0,0 +1,33 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IO.SubSystem+-- Copyright   :  (c) The University of Glasgow, 2017+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- The 'IoSubSystem' control interface.  These methods can be used to disambiguate+-- between the two operations.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.IO.SubSystem+    (withIoSubSystem,+     withIoSubSystem',+     whenIoSubSystem,+     ioSubSystem,+     IoSubSystem(..),+     conditional,+     (<!>),+     isWindowsNativeIO+     ) where++import GHC.Internal.IO.SubSystem
+ src/GHC/IO/Unsafe.hs view
@@ -0,0 +1,24 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.IO.Unsafe+-- Copyright   :  (c) The University of Glasgow 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Unsafe IO operations+--++module GHC.IO.Unsafe+    (unsafePerformIO,+     unsafeInterleaveIO,+     unsafeDupablePerformIO,+     unsafeDupableInterleaveIO,+     noDuplicate+     ) where++import GHC.Internal.IO.Unsafe
+ src/GHC/IO/Windows/Encoding.hs view
@@ -0,0 +1,25 @@+-- |+-- Module      :  System.Win32.Encoding+-- Copyright   :  2012 shelarcy+-- License     :  BSD-style+--+-- Maintainer  :  shelarcy@gmail.com+-- Stability   :  Provisional+-- Portability :  Non-portable (Win32 API)+--+-- Encode/Decode multibyte character using Win32 API.+--++module GHC.IO.Windows.Encoding+  ( encodeMultiByte+  , encodeMultiByteIO+  , encodeMultiByteRawIO+  , decodeMultiByte+  , decodeMultiByteIO+  , wideCharToMultiByte+  , multiByteToWideChar+  , withGhcInternalToUTF16+  , withUTF16ToGhcInternal+  ) where++import GHC.Internal.IO.Windows.Encoding
+ src/GHC/IO/Windows/Handle.hs view
@@ -0,0 +1,40 @@+-- |+-- Module      :  GHC.IO.Windows.Handle+-- Copyright   :  (c) The University of Glasgow, 2017+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Raw read/write operations on Windows Handles+--++module GHC.IO.Windows.Handle+ ( -- * Basic Types+   NativeHandle(),+   ConsoleHandle(),+   IoHandle(),+   HANDLE,+   Io(),++   -- * Utility functions+   convertHandle,+   toHANDLE,+   fromHANDLE,+   handleToMode,+   isAsynchronous,+   optimizeFileAccess,++   -- * Standard Handles+   stdin,+   stdout,+   stderr,++   -- * File utilities+   openFile,+   openFileAsTemp,+   release+ ) where++import GHC.Internal.IO.Windows.Handle
+ src/GHC/IO/Windows/Paths.hs view
@@ -0,0 +1,18 @@+-- |+-- Module      :  GHC.IO.Windows.Paths+-- Copyright   :  (c) The University of Glasgow, 2017+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Windows FilePath handling utility for GHC code.+--+-----------------------------------------------------------------------------++module GHC.IO.Windows.Paths+   ( getDevicePath+   ) where++import GHC.Internal.IO.Windows.Paths
+ src/GHC/IOArray.hs view
@@ -0,0 +1,26 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.IOArray+-- Copyright   :  (c) The University of Glasgow 2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The IOArray type+--++module GHC.IOArray+    (IOArray(..),+     newIOArray,+     unsafeReadIOArray,+     unsafeWriteIOArray,+     readIOArray,+     writeIOArray,+     boundsIOArray+     ) where++import GHC.Internal.IOArray
+ src/GHC/IORef.hs view
@@ -0,0 +1,30 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.IORef+-- Copyright   :  (c) The University of Glasgow 2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The IORef type+--++module GHC.IORef+    (IORef(..),+     newIORef,+     readIORef,+     writeIORef,+     atomicModifyIORef2Lazy,+     atomicModifyIORef2,+     atomicModifyIORefLazy_,+     atomicModifyIORef'_,+     atomicModifyIORefP,+     atomicSwapIORef,+     atomicModifyIORef'+     ) where++import GHC.Internal.IORef
+ src/GHC/InfoProv.hs view
@@ -0,0 +1,32 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  GHC.InfoProv+-- Copyright   :  (c) The University of Glasgow 2011+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Access to GHC's info-table provenance metadata.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--+-- @since 4.18.0.0+--++module GHC.InfoProv+    ( InfoProv(..)+    , ipLoc+    , ipeProv+    , whereFrom+      -- * Internals+    , InfoProvEnt+    , peekInfoProv+    ) where++import GHC.Internal.InfoProv
+ src/GHC/Int.hs view
@@ -0,0 +1,63 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE MagicHash #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Int+-- Copyright   :  (c) The University of Glasgow 1997-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The sized integral datatypes, 'Int8', 'Int16', 'Int32', and 'Int64'.+--++module GHC.Int+    (Int(..),+     Int8(..),+     Int16(..),+     Int32(..),+     Int64(..),+     uncheckedIShiftL64#,+     uncheckedIShiftRA64#,+     shiftRLInt8#,+     shiftRLInt16#,+     shiftRLInt32#,+     -- *  Equality operators+     -- |  See GHC.Classes#matching_overloaded_methods_in_rules+     eqInt,+     neInt,+     gtInt,+     geInt,+     ltInt,+     leInt,+     eqInt8,+     neInt8,+     gtInt8,+     geInt8,+     ltInt8,+     leInt8,+     eqInt16,+     neInt16,+     gtInt16,+     geInt16,+     ltInt16,+     leInt16,+     eqInt32,+     neInt32,+     gtInt32,+     geInt32,+     ltInt32,+     leInt32,+     eqInt64,+     neInt64,+     gtInt64,+     geInt64,+     ltInt64,+     leInt64+     ) where++import GHC.Internal.Int
+ src/GHC/Integer.hs view
@@ -0,0 +1,65 @@+{-# LANGUAGE MagicHash #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Compatibility module for pre-@ghc-bignum@ code.++module GHC.Integer+    (Integer,+     -- *  Construct 'Integer's+     smallInteger,+     wordToInteger,+     -- *  Conversion to other integral types+     integerToWord,+     integerToInt,+     -- *  Helpers for 'RealFloat' type-class operations+     encodeFloatInteger,+     encodeDoubleInteger,+     decodeDoubleInteger,+     -- *  Arithmetic operations+     plusInteger,+     minusInteger,+     timesInteger,+     negateInteger,+     absInteger,+     signumInteger,+     divModInteger,+     divInteger,+     modInteger,+     quotRemInteger,+     quotInteger,+     remInteger,+     -- *  Comparison predicates+     eqInteger,+     neqInteger,+     leInteger,+     gtInteger,+     ltInteger,+     geInteger,+     compareInteger,+     -- **  'Int#'-boolean valued versions of comparison predicates+     -- |  These operations return @0#@ and @1#@ instead of 'False' and+     -- 'True' respectively.  See+     -- <https://gitlab.haskell.org/ghc/ghc/wikis/prim-bool PrimBool wiki-page>+     -- for more details+     eqInteger#,+     neqInteger#,+     leInteger#,+     gtInteger#,+     ltInteger#,+     geInteger#,+     -- *  Bit-operations+     andInteger,+     orInteger,+     xorInteger,+     complementInteger,+     shiftLInteger,+     shiftRInteger,+     testBitInteger,+     popCountInteger,+     bitInteger,+     -- *  Hashing+     hashInteger+     ) where++import GHC.Internal.Integer
+ src/GHC/Integer/Logarithms.hs view
@@ -0,0 +1,12 @@+{-# LANGUAGE MagicHash #-}++-- |+-- Compatibility module for pre-@ghc-bignum@ code.++module GHC.Integer.Logarithms+    (wordLog2#,+     integerLog2#,+     integerLogBase#+     ) where++import GHC.Internal.Integer.Logarithms
+ src/GHC/IsList.hs view
@@ -0,0 +1,19 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.IsList+-- Copyright   :  (c) The University of Glasgow 2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- @since 4.17.0.0++module GHC.IsList+    (IsList(..)+     ) where++import GHC.Internal.IsList
+ src/GHC/Ix.hs view
@@ -0,0 +1,21 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Ix+-- Copyright   :  (c) The University of Glasgow, 1994-2000+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- GHC\'s Ix typeclass implementation.+--++module GHC.Ix+    (Ix(..),+     indexError+     ) where++import GHC.Internal.Ix
+ src/GHC/JS/Foreign/Callback.hs view
@@ -0,0 +1,22 @@+module GHC.JS.Foreign.Callback+    ( Callback+    , OnBlocked(..)+    , releaseCallback+      -- * asynchronous callbacks+    , asyncCallback+    , asyncCallback1+    , asyncCallback2+    , asyncCallback3+      -- * synchronous callbacks+    , syncCallback+    , syncCallback1+    , syncCallback2+    , syncCallback3+      -- * synchronous callbacks that return a value+    , syncCallback'+    , syncCallback1'+    , syncCallback2'+    , syncCallback3'+    ) where++import GHC.Internal.JS.Foreign.Callback
+ src/GHC/JS/Prim.hs view
@@ -0,0 +1,38 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE MagicHash #-}++module GHC.JS.Prim+    ( JSVal(..), JSVal#+    , JSException(..)+    , WouldBlockException(..)+#if defined(javascript_HOST_ARCH)+    , toIO+    , resolve+    , resolveIO+    , mkJSException+    , fromJSString+    , toJSString+    , toJSArray+    , fromJSArray+    , fromJSInt+    , toJSInt+    , isNull+    , isUndefined+    , jsNull+    , getProp+    , getProp'+    , getProp#+    , unsafeGetProp+    , unsafeGetProp'+    , unsafeGetProp#+    , unpackJSString#+    , unpackJSStringUtf8#+    , unsafeUnpackJSString#+    , unsafeUnpackJSStringUtf8#+    , unpackJSStringUtf8##+    , unsafeUnpackJSStringUtf8##+#endif+    ) where++import GHC.Internal.JS.Prim+
+ src/GHC/JS/Prim/Internal.hs view
@@ -0,0 +1,10 @@+module GHC.JS.Prim.Internal+    ( blockedIndefinitelyOnMVar+    , blockedIndefinitelyOnSTM+    , wouldBlock+    , ignoreException+    , setCurrentThreadResultException+    , setCurrentThreadResultValue+    ) where++import GHC.Internal.JS.Prim.Internal
+ src/GHC/JS/Prim/Internal/Build.hs view
@@ -0,0 +1,147 @@+{-# LANGUAGE CPP #-}++module GHC.JS.Prim.Internal.Build+  {-# DEPRECATED "Use ghc-internal:GHC.Internal.JS.Prim.Internal.Build instead" #-}+  -- deprecated for now. To be fully removed in GHC 9.16+  -- see https://github.com/haskell/core-libraries-committee/issues/329 and #23432+#if !defined(javascript_HOST_ARCH)+  () where+#else+  ( buildArrayI+  , buildArrayM+  , buildObjectI+  , buildObjectM+  , buildArrayI1+  , buildArrayI2+  , buildArrayI3+  , buildArrayI4+  , buildArrayI5+  , buildArrayI6+  , buildArrayI7+  , buildArrayI8+  , buildArrayI9+  , buildArrayI10+  , buildArrayI11+  , buildArrayI12+  , buildArrayI13+  , buildArrayI14+  , buildArrayI15+  , buildArrayI16+  , buildArrayI17+  , buildArrayI18+  , buildArrayI19+  , buildArrayI20+  , buildArrayI21+  , buildArrayI22+  , buildArrayI23+  , buildArrayI24+  , buildArrayI25+  , buildArrayI26+  , buildArrayI27+  , buildArrayI28+  , buildArrayI29+  , buildArrayI30+  , buildArrayI31+  , buildArrayI32+  , buildArrayM1+  , buildArrayM2+  , buildArrayM3+  , buildArrayM4+  , buildArrayM5+  , buildArrayM6+  , buildArrayM7+  , buildArrayM8+  , buildArrayM9+  , buildArrayM10+  , buildArrayM11+  , buildArrayM12+  , buildArrayM13+  , buildArrayM14+  , buildArrayM15+  , buildArrayM16+  , buildArrayM17+  , buildArrayM18+  , buildArrayM19+  , buildArrayM20+  , buildArrayM21+  , buildArrayM22+  , buildArrayM23+  , buildArrayM24+  , buildArrayM25+  , buildArrayM26+  , buildArrayM27+  , buildArrayM28+  , buildArrayM29+  , buildArrayM30+  , buildArrayM31+  , buildArrayM32+  , buildObjectI1+  , buildObjectI2+  , buildObjectI3+  , buildObjectI4+  , buildObjectI5+  , buildObjectI6+  , buildObjectI7+  , buildObjectI8+  , buildObjectI9+  , buildObjectI10+  , buildObjectI11+  , buildObjectI12+  , buildObjectI13+  , buildObjectI14+  , buildObjectI15+  , buildObjectI16+  , buildObjectI17+  , buildObjectI18+  , buildObjectI19+  , buildObjectI20+  , buildObjectI21+  , buildObjectI22+  , buildObjectI23+  , buildObjectI24+  , buildObjectI25+  , buildObjectI26+  , buildObjectI27+  , buildObjectI28+  , buildObjectI29+  , buildObjectI30+  , buildObjectI31+  , buildObjectI32+  , buildObjectM1+  , buildObjectM2+  , buildObjectM3+  , buildObjectM4+  , buildObjectM5+  , buildObjectM6+  , buildObjectM7+  , buildObjectM8+  , buildObjectM9+  , buildObjectM10+  , buildObjectM11+  , buildObjectM12+  , buildObjectM13+  , buildObjectM14+  , buildObjectM15+  , buildObjectM16+  , buildObjectM17+  , buildObjectM18+  , buildObjectM19+  , buildObjectM20+  , buildObjectM21+  , buildObjectM22+  , buildObjectM23+  , buildObjectM24+  , buildObjectM25+  , buildObjectM26+  , buildObjectM27+  , buildObjectM28+  , buildObjectM29+  , buildObjectM30+  , buildObjectM31+  , buildObjectM32+  ) where++import GHC.Internal.JS.Prim.Internal.Build++#endif+
+ src/GHC/List.hs view
@@ -0,0 +1,43 @@+{-# LANGUAGE Safe #-}+++-- |+--+-- Module      :  GHC.List+-- Copyright   :  (c) The University of Glasgow 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The List data type and its operations+--++module GHC.List (++   -- * The list data type+   List,++   -- * List-monomorphic Foldable methods and misc functions+   foldr, foldr', foldr1,+   foldl, foldl', foldl1,+   null, length, elem, notElem,+   maximum, minimum, sum, product, and, or, any, all,++   -- * Other functions+   foldl1', concat, concatMap,+   map, (++), filter, lookup,+   head, last, tail, init, uncons, unsnoc, (!?), (!!),+   scanl, scanl1, scanl', scanr, scanr1,+   iterate, iterate', repeat, replicate, cycle,+   take, drop, splitAt, takeWhile, dropWhile, span, break, reverse,+   zip, zip3, zipWith, zipWith3, unzip, unzip3,+   errorEmptyList,++   -- * GHC List fusion+   augment, build,++ ) where++import GHC.Internal.List
+ src/GHC/MVar.hs view
@@ -0,0 +1,31 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.MVar+-- Copyright   :  (c) The University of Glasgow 2008+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The MVar type+--++module GHC.MVar+    (-- *  MVars+     MVar(..),+     newMVar,+     newEmptyMVar,+     takeMVar,+     readMVar,+     putMVar,+     tryTakeMVar,+     tryPutMVar,+     tryReadMVar,+     isEmptyMVar,+     addMVarFinalizer+     ) where++import GHC.Internal.MVar
+ src/GHC/Maybe.hs view
@@ -0,0 +1,17 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Maybe+-- Copyright   :  (c) The University of Glasgow 1997-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The 'Maybe' type.++module GHC.Maybe+    (Maybe(..)) where++import GHC.Internal.Maybe
+ src/GHC/Natural.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE MagicHash #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Compatibility module for pre ghc-bignum code.++module GHC.Natural+    (Natural(NatS#, NatJ#),+     BigNat(..),+     mkNatural,+     isValidNatural,+     -- *  Arithmetic+     plusNatural,+     minusNatural,+     minusNaturalMaybe,+     timesNatural,+     negateNatural,+     signumNatural,+     quotRemNatural,+     quotNatural,+     remNatural,+     gcdNatural,+     lcmNatural,+     -- *  Bits+     andNatural,+     orNatural,+     xorNatural,+     bitNatural,+     testBitNatural,+     popCountNatural,+     shiftLNatural,+     shiftRNatural,+     -- *  Conversions+     naturalToInteger,+     naturalToWord,+     naturalToWordMaybe,+     wordToNatural,+     wordToNatural#,+     naturalFromInteger,+     -- *  Modular arithmetic+     powModNatural+     ) where++import GHC.Internal.Natural
+ src/GHC/Num.hs view
@@ -0,0 +1,26 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Num+-- Copyright   :  (c) The University of Glasgow 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The 'Num' class and the 'Integer' type.+--++module GHC.Num+   ( Num(..)+   , subtract+   , quotRemInteger+   , module GHC.Num.Integer+   , module GHC.Num.Natural+   )+where++import GHC.Internal.Num+import GHC.Num.Integer+import GHC.Num.Natural
+ src/GHC/Num/BigNat.hs view
@@ -0,0 +1,6 @@+module GHC.Num.BigNat+  ( module GHC.Internal.Bignum.BigNat+  )+where++import GHC.Internal.Bignum.BigNat
+ src/GHC/Num/Integer.hs view
@@ -0,0 +1,6 @@+module GHC.Num.Integer+  ( module GHC.Internal.Bignum.Integer+  )+where++import GHC.Internal.Bignum.Integer
+ src/GHC/Num/Natural.hs view
@@ -0,0 +1,6 @@+module GHC.Num.Natural+  ( module GHC.Internal.Bignum.Natural+  )+where++import GHC.Internal.Bignum.Natural
+ src/GHC/OldList.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.OldList+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- This legacy module provides access to the list-specialised operations+-- of "Data.List". This module may go away again in future GHC versions and+-- is provided as transitional tool to access some of the list-specialised+-- operations that had to be generalised due to the implementation of the+-- <https://wiki.haskell.org/Foldable_Traversable_In_Prelude Foldable/Traversable-in-Prelude Proposal (FTP)>.+--+-- If the operations needed are available in "GHC.List", it's+-- recommended to avoid importing this module and use "GHC.List"+-- instead for now.+--+-- @since 4.8.0.0++module GHC.OldList (module GHC.Internal.Data.OldList) where++import GHC.Internal.Data.OldList
+ src/GHC/OverloadedLabels.hs view
@@ -0,0 +1,32 @@+-- |+--+-- Module      :  GHC.OverloadedLabels+-- Copyright   :  (c) Adam Gundry 2015-2016+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- This module defines the 'IsLabel' class used by the+-- @OverloadedLabels@ extension.  See the+-- <https://gitlab.haskell.org/ghc/ghc/wikis/records/overloaded-record-fields/overloaded-labels wiki page>+-- for more details.+--+-- When @OverloadedLabels@ is enabled, if GHC sees an occurrence of+-- the overloaded label syntax @#foo@, it is replaced with+--+-- > fromLabel @"foo" :: alpha+--+-- plus a wanted constraint @IsLabel "foo" alpha@.+--+-- Note that if @RebindableSyntax@ is enabled, the desugaring of+-- overloaded label syntax will make use of whatever @fromLabel@ is in+-- scope.+--++module GHC.OverloadedLabels+    (IsLabel(..)+     ) where++import GHC.Internal.OverloadedLabels
+ src/GHC/Profiling.hs view
@@ -0,0 +1,16 @@+{-# LANGUAGE Safe #-}++-- |+-- @since 4.7.0.0++module GHC.Profiling+    (-- *  Cost Centre Profiling+     startProfTimer,+     stopProfTimer,+     -- *  Heap Profiling+     startHeapProfTimer,+     stopHeapProfTimer,+     requestHeapCensus+     ) where++import GHC.Internal.Profiling
+ src/GHC/Ptr.hs view
@@ -0,0 +1,24 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Ptr+-- Copyright   :  (c) The FFI Task Force, 2000-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The 'Ptr' and 'FunPtr' types and operations.+--++module GHC.Ptr (+        Ptr(..), FunPtr(..),+        nullPtr, castPtr, plusPtr, alignPtr, minusPtr,+        nullFunPtr, castFunPtr,++        -- * Unsafe functions+        castFunPtrToPtr, castPtrToFunPtr,+    ) where++import GHC.Internal.Ptr
+ src/GHC/RTS/Flags.hs view
@@ -0,0 +1,474 @@+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE DeriveGeneric #-}++-- |+-- Module      :  GHC.RTS.Flags+-- Copyright   :  (c) The University of Glasgow, 1994-2000+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- /The API of this module is unstable and is tightly coupled to GHC's internals./+-- If depend on it, make sure to use a tight upper bound, e.g., @base < 4.X@ rather+-- than @base < 5@, because the interface can change rapidly without much warning.+--+-- Descriptions of flags can be seen in+-- <https://www.haskell.org/ghc/docs/latest/html/users_guide/runtime_control.html GHC User's Guide>,+-- or by running RTS help message using @+RTS --help@.+--+-- @since 4.8.0.0+--+-- This module is a compatibility layer. It is meant to be temporary to allow for the eventual deprecation of these declarations as described in [CLC proposal #289](https://github.com/haskell/core-libraries-committee/issues/289). These declarations are now instead available from the @ghc-experimental@ package.++module GHC.RTS.Flags+  ( RtsTime+  , RTSFlags (..)+  , GiveGCStats (..)+  , GCFlags (..)+  , ConcFlags (..)+  , MiscFlags (..)+  , IoManagerFlag (..)+  , DebugFlags (..)+  , DoCostCentres (..)+  , CCFlags (..)+  , DoHeapProfile (..)+  , ProfFlags (..)+  , DoTrace (..)+  , TraceFlags (..)+  , TickyFlags (..)+  , ParFlags (..)+  , HpcFlags (..)+  , {-# DEPRECATED "import GHC.IO.SubSystem (IoSubSystem (..))" #-}+    IoSubSystem (..)+  , getRTSFlags+  , getGCFlags+  , getConcFlags+  , getMiscFlags+  , getDebugFlags+  , getCCFlags+  , getProfFlags+  , getTraceFlags+  , getTickyFlags+  , getParFlags+  , getHpcFlags+  ) where++import Prelude (Show,IO,Bool,Maybe,String,Int,Enum,FilePath,Double,Eq,(<$>))++import GHC.Generics (Generic)+import qualified GHC.Internal.RTS.Flags as Internal+import GHC.Internal.IO.SubSystem (IoSubSystem(..))++import Data.Word (Word32,Word64,Word)++-- | 'RtsTime' is defined as a @StgWord64@ in @stg/Types.h@+--+-- @since base-4.8.2.0+type RtsTime = Word64++-- | Should we produce a summary of the garbage collector statistics after the+-- program has exited?+--+-- @since base-4.8.2.0+data GiveGCStats+    = NoGCStats+    | CollectGCStats+    | OneLineGCStats+    | SummaryGCStats+    | VerboseGCStats+    deriving ( Show -- ^ @since base-4.8.0.0+             , Generic -- ^ @since base-4.15.0.0+             )++-- | Parameters of the garbage collector.+--+-- @since base-4.8.0.0+data GCFlags = GCFlags+    { statsFile             :: Maybe FilePath+    , giveStats             :: GiveGCStats+    , maxStkSize            :: Word32+    , initialStkSize        :: Word32+    , stkChunkSize          :: Word32+    , stkChunkBufferSize    :: Word32+    , maxHeapSize           :: Word32+    , minAllocAreaSize      :: Word32+    , largeAllocLim         :: Word32+    , nurseryChunkSize      :: Word32+    , minOldGenSize         :: Word32+    , heapSizeSuggestion    :: Word32+    , heapSizeSuggestionAuto :: Bool+    , oldGenFactor          :: Double+    , returnDecayFactor     :: Double+    , pcFreeHeap            :: Double+    , generations           :: Word32+    , squeezeUpdFrames      :: Bool+    , compact               :: Bool -- ^ True <=> "compact all the time"+    , compactThreshold      :: Double+    , sweep                 :: Bool+      -- ^ use "mostly mark-sweep" instead of copying for the oldest generation+    , ringBell              :: Bool+    , idleGCDelayTime       :: RtsTime+    , doIdleGC              :: Bool+    , heapBase              :: Word -- ^ address to ask the OS for memory+    , allocLimitGrace       :: Word+    , numa                  :: Bool+    , numaMask              :: Word+    } deriving ( Show -- ^ @since base-4.8.0.0+               , Generic -- ^ @since base-4.15.0.0+               )++-- | Parameters concerning context switching+--+-- @since base-4.8.0.0+data ConcFlags = ConcFlags+    { ctxtSwitchTime  :: RtsTime+    , ctxtSwitchTicks :: Int+    } deriving ( Show -- ^ @since base-4.8.0.0+               , Generic -- ^ @since base-4.15.0.0+               )++-- | Miscellaneous parameters+--+-- @since base-4.8.0.0+data MiscFlags = MiscFlags+    { tickInterval          :: RtsTime+    , installSignalHandlers :: Bool+    , installSEHHandlers    :: Bool+    , generateCrashDumpFile :: Bool+    , generateStackTrace    :: Bool+    , machineReadable       :: Bool+    , disableDelayedOsMemoryReturn :: Bool+    , internalCounters      :: Bool+    , linkerAlwaysPic       :: Bool+    , linkerMemBase         :: Word+      -- ^ address to ask the OS for memory for the linker, 0 ==> off+    , ioManager             :: IoManagerFlag+    , numIoWorkerThreads    :: Word32+    } deriving ( Show -- ^ @since base-4.8.0.0+               , Generic -- ^ @since base-4.15.0.0+               )++-- |+--+-- @since base-4.21.0.0+data IoManagerFlag =+       IoManagerFlagAuto+     | IoManagerFlagSelect        -- ^ Unix only, non-threaded RTS only+     | IoManagerFlagMIO           -- ^ cross-platform, threaded RTS only+     | IoManagerFlagWinIO         -- ^ Windows only+     | IoManagerFlagWin32Legacy   -- ^ Windows only, non-threaded RTS only+  deriving (Eq, Enum, Show)++-- | Flags to control debugging output & extra checking in various+-- subsystems.+--+-- @since base-4.8.0.0+data DebugFlags = DebugFlags+    { scheduler      :: Bool -- ^ @s@+    , interpreter    :: Bool -- ^ @i@+    , weak           :: Bool -- ^ @w@+    , gccafs         :: Bool -- ^ @G@+    , gc             :: Bool -- ^ @g@+    , nonmoving_gc   :: Bool -- ^ @n@+    , block_alloc    :: Bool -- ^ @b@+    , sanity         :: Bool -- ^ @S@+    , stable         :: Bool -- ^ @t@+    , prof           :: Bool -- ^ @p@+    , linker         :: Bool -- ^ @l@ the object linker+    , apply          :: Bool -- ^ @a@+    , stm            :: Bool -- ^ @m@+    , squeeze        :: Bool -- ^ @z@ stack squeezing & lazy blackholing+    , hpc            :: Bool -- ^ @c@ coverage+    , sparks         :: Bool -- ^ @r@+    } deriving ( Show -- ^ @since base-4.8.0.0+               , Generic -- ^ @since base-4.15.0.0+               )++-- | Should the RTS produce a cost-center summary?+--+-- @since base-4.8.2.0+data DoCostCentres+    = CostCentresNone+    | CostCentresSummary+    | CostCentresVerbose+    | CostCentresAll+    | CostCentresJSON+    deriving ( Show -- ^ @since base-4.8.0.0+             , Generic -- ^ @since base-4.15.0.0+             )++-- | Parameters pertaining to the cost-center profiler.+--+-- @since base-4.8.0.0+data CCFlags = CCFlags+    { doCostCentres :: DoCostCentres+    , profilerTicks :: Int+    , msecsPerTick  :: Int+    } deriving ( Show -- ^ @since base-4.8.0.0+               , Generic -- ^ @since base-4.15.0.0+               )++-- | What sort of heap profile are we collecting?+--+-- @since base-4.8.2.0+data DoHeapProfile+    = NoHeapProfiling+    | HeapByCCS+    | HeapByMod+    | HeapByDescr+    | HeapByType+    | HeapByRetainer+    | HeapByLDV+    | HeapByClosureType+    | HeapByInfoTable+    | HeapByEra -- ^ @since base-4.20.0.0+    deriving ( Show -- ^ @since base-4.8.0.0+             , Generic -- ^ @since base-4.15.0.0+             )++-- | Parameters of the cost-center profiler+--+-- @since base-4.8.0.0+data ProfFlags = ProfFlags+    { doHeapProfile            :: DoHeapProfile+    , heapProfileInterval      :: RtsTime -- ^ time between samples+    , heapProfileIntervalTicks :: Word    -- ^ ticks between samples (derived)+    , startHeapProfileAtStartup :: Bool+    , startTimeProfileAtStartup :: Bool   -- ^ @since base-4.20.0.0+    , showCCSOnException       :: Bool+    , automaticEraIncrement    :: Bool   -- ^ @since 4.20.0.0+    , maxRetainerSetSize       :: Word+    , ccsLength                :: Word+    , modSelector              :: Maybe String+    , descrSelector            :: Maybe String+    , typeSelector             :: Maybe String+    , ccSelector               :: Maybe String+    , ccsSelector              :: Maybe String+    , retainerSelector         :: Maybe String+    , bioSelector              :: Maybe String+    , eraSelector              :: Word -- ^ @since base-4.20.0.0+    } deriving ( Show -- ^ @since base-4.8.0.0+               , Generic -- ^ @since base-4.15.0.0+               )++-- | Is event tracing enabled?+--+-- @since base-4.8.2.0+data DoTrace+    = TraceNone      -- ^ no tracing+    | TraceEventLog  -- ^ send tracing events to the event log+    | TraceStderr    -- ^ send tracing events to @stderr@+    deriving ( Show -- ^ @since base-4.8.0.0+             , Generic -- ^ @since base-4.15.0.0+             )++-- | Parameters pertaining to event tracing+--+-- @since base-4.8.0.0+data TraceFlags = TraceFlags+    { tracing        :: DoTrace+    , timestamp      :: Bool -- ^ show timestamp in stderr output+    , traceScheduler :: Bool -- ^ trace scheduler events+    , traceGc        :: Bool -- ^ trace GC events+    , traceNonmovingGc+                     :: Bool -- ^ trace nonmoving GC heap census samples+    , sparksSampled  :: Bool -- ^ trace spark events by a sampled method+    , sparksFull     :: Bool -- ^ trace spark events 100% accurately+    , user           :: Bool -- ^ trace user events (emitted from Haskell code)+    } deriving ( Show -- ^ @since base-4.8.0.0+               , Generic -- ^ @since base-4.15.0.0+               )++-- | Parameters pertaining to ticky-ticky profiler+--+-- @since base-4.8.0.0+data TickyFlags = TickyFlags+    { showTickyStats :: Bool+    , tickyFile      :: Maybe FilePath+    } deriving ( Show -- ^ @since base-4.8.0.0+               , Generic -- ^ @since base-4.15.0.0+               )++-- | Parameters pertaining to parallelism+--+-- @since base-4.8.0.0+data ParFlags = ParFlags+    { nCapabilities             :: Word32+    , migrate                   :: Bool+    , maxLocalSparks            :: Word32+    , parGcEnabled              :: Bool+    , parGcGen                  :: Word32+    , parGcLoadBalancingEnabled :: Bool+    , parGcLoadBalancingGen     :: Word32+    , parGcNoSyncWithIdle       :: Word32+    , parGcThreads              :: Word32+    , setAffinity               :: Bool+    }+    deriving ( Show -- ^ @since base-4.8.0.0+             , Generic -- ^ @since base-4.15.0.0+             )++-- | Parameters pertaining to Haskell program coverage (HPC)+--+-- @since base-4.20.0.0+data HpcFlags = HpcFlags+    { readTixFile :: Bool+      -- ^ Controls whether a @<program>.tix@ file is read at+      -- the start of execution to initialize the RTS internal+      -- HPC datastructures.+    , writeTixFile :: Bool+      -- ^ Controls whether the @<program>.tix@ file should be+      -- written after the execution of the program.+    }+    deriving (Show -- ^ @since base-4.20.0.0+             , Generic -- ^ @since base-4.20.0.0+             )+-- | Parameters of the runtime system+--+-- @since base-4.8.0.0+data RTSFlags = RTSFlags+    { gcFlags         :: GCFlags+    , concurrentFlags :: ConcFlags+    , miscFlags       :: MiscFlags+    , debugFlags      :: DebugFlags+    , costCentreFlags :: CCFlags+    , profilingFlags  :: ProfFlags+    , traceFlags      :: TraceFlags+    , tickyFlags      :: TickyFlags+    , parFlags        :: ParFlags+    , hpcFlags        :: HpcFlags+    } deriving ( Show -- ^ @since base-4.8.0.0+               , Generic -- ^ @since base-4.15.0.0+               )++-------------------------------- compat ----------------------------------------++internal_to_base_RTSFlags :: Internal.RTSFlags -> RTSFlags+internal_to_base_RTSFlags Internal.RTSFlags{..} =+  RTSFlags{ gcFlags         = internal_to_base_GCFlags    gcFlags+          , concurrentFlags = internal_to_base_ConcFlags  concurrentFlags+          , miscFlags       = internal_to_base_MiscFlags  miscFlags+          , debugFlags      = internal_to_base_DebugFlags debugFlags+          , costCentreFlags = internal_to_base_CCFlags    costCentreFlags+          , profilingFlags  = internal_to_base_ProfFlags  profilingFlags+          , traceFlags      = internal_to_base_TraceFlags traceFlags+          , tickyFlags      = internal_to_base_TickyFlags tickyFlags+          , parFlags        = internal_to_base_ParFlags   parFlags+          , hpcFlags        = internal_to_base_HpcFlags   hpcFlags+          }++internal_to_base_GCFlags :: Internal.GCFlags -> GCFlags+internal_to_base_GCFlags i@Internal.GCFlags{..} =+  let give_stats = internal_to_base_giveStats (Internal.giveStats i)+  in GCFlags{ giveStats = give_stats, .. }+  where+    internal_to_base_giveStats :: Internal.GiveGCStats -> GiveGCStats+    internal_to_base_giveStats Internal.NoGCStats      = NoGCStats+    internal_to_base_giveStats Internal.CollectGCStats = CollectGCStats+    internal_to_base_giveStats Internal.OneLineGCStats = OneLineGCStats+    internal_to_base_giveStats Internal.SummaryGCStats = SummaryGCStats+    internal_to_base_giveStats Internal.VerboseGCStats = VerboseGCStats++internal_to_base_ParFlags :: Internal.ParFlags -> ParFlags+internal_to_base_ParFlags Internal.ParFlags{..} = ParFlags{..}++internal_to_base_HpcFlags :: Internal.HpcFlags -> HpcFlags+internal_to_base_HpcFlags Internal.HpcFlags{..} = HpcFlags{..}++internal_to_base_ConcFlags :: Internal.ConcFlags -> ConcFlags+internal_to_base_ConcFlags Internal.ConcFlags{..} = ConcFlags{..}++internal_to_base_MiscFlags :: Internal.MiscFlags -> MiscFlags+internal_to_base_MiscFlags i@Internal.MiscFlags{..} =+  let io_manager = internal_to_base_ioManager (Internal.ioManager i)+  in MiscFlags{ ioManager = io_manager, ..}+  where+    internal_to_base_ioManager :: Internal.IoManagerFlag -> IoManagerFlag+    internal_to_base_ioManager Internal.IoManagerFlagAuto        = IoManagerFlagAuto+    internal_to_base_ioManager Internal.IoManagerFlagSelect      = IoManagerFlagSelect+    internal_to_base_ioManager Internal.IoManagerFlagMIO         = IoManagerFlagMIO+    internal_to_base_ioManager Internal.IoManagerFlagWinIO       = IoManagerFlagWinIO+    internal_to_base_ioManager Internal.IoManagerFlagWin32Legacy = IoManagerFlagWin32Legacy++internal_to_base_DebugFlags :: Internal.DebugFlags -> DebugFlags+internal_to_base_DebugFlags Internal.DebugFlags{..} = DebugFlags{..}++internal_to_base_CCFlags :: Internal.CCFlags -> CCFlags+internal_to_base_CCFlags i@Internal.CCFlags{..} =+  let do_cost_centres = internal_to_base_costCentres (Internal.doCostCentres i)+  in CCFlags{ doCostCentres = do_cost_centres, ..}+  where+    internal_to_base_costCentres :: Internal.DoCostCentres -> DoCostCentres+    internal_to_base_costCentres Internal.CostCentresNone    = CostCentresNone+    internal_to_base_costCentres Internal.CostCentresSummary = CostCentresSummary+    internal_to_base_costCentres Internal.CostCentresVerbose = CostCentresVerbose+    internal_to_base_costCentres Internal.CostCentresAll     = CostCentresAll+    internal_to_base_costCentres Internal.CostCentresJSON    = CostCentresJSON++internal_to_base_ProfFlags :: Internal.ProfFlags -> ProfFlags+internal_to_base_ProfFlags i@Internal.ProfFlags{..} =+  let do_heap_profile = internal_to_base_doHeapProfile (Internal.doHeapProfile i)+  in ProfFlags{ doHeapProfile = do_heap_profile,..}+  where+    internal_to_base_doHeapProfile :: Internal.DoHeapProfile -> DoHeapProfile+    internal_to_base_doHeapProfile Internal.NoHeapProfiling   = NoHeapProfiling+    internal_to_base_doHeapProfile Internal.HeapByCCS         = HeapByCCS+    internal_to_base_doHeapProfile Internal.HeapByMod         = HeapByMod+    internal_to_base_doHeapProfile Internal.HeapByDescr       = HeapByDescr+    internal_to_base_doHeapProfile Internal.HeapByType        = HeapByType+    internal_to_base_doHeapProfile Internal.HeapByRetainer    = HeapByRetainer+    internal_to_base_doHeapProfile Internal.HeapByLDV         = HeapByLDV+    internal_to_base_doHeapProfile Internal.HeapByClosureType = HeapByClosureType+    internal_to_base_doHeapProfile Internal.HeapByInfoTable   = HeapByInfoTable+    internal_to_base_doHeapProfile Internal.HeapByEra         = HeapByEra++internal_to_base_TraceFlags :: Internal.TraceFlags -> TraceFlags+internal_to_base_TraceFlags i@Internal.TraceFlags{..} =+  let do_trace = internal_to_base_doTrace (Internal.tracing i)+  in TraceFlags{ tracing = do_trace,..}+  where+    internal_to_base_doTrace :: Internal.DoTrace -> DoTrace+    internal_to_base_doTrace Internal.TraceNone     = TraceNone+    internal_to_base_doTrace Internal.TraceEventLog = TraceEventLog+    internal_to_base_doTrace Internal.TraceStderr   = TraceStderr++internal_to_base_TickyFlags :: Internal.TickyFlags -> TickyFlags+internal_to_base_TickyFlags Internal.TickyFlags{..} = TickyFlags{..}++-------------------------------- shims -----------------------------------------++getRTSFlags :: IO RTSFlags+getRTSFlags = internal_to_base_RTSFlags <$> Internal.getRTSFlags++getGCFlags :: IO GCFlags+getGCFlags = internal_to_base_GCFlags <$> Internal.getGCFlags++getParFlags :: IO ParFlags+getParFlags = internal_to_base_ParFlags <$> Internal.getParFlags++getHpcFlags :: IO HpcFlags+getHpcFlags = internal_to_base_HpcFlags <$> Internal.getHpcFlags++getConcFlags :: IO ConcFlags+getConcFlags =  internal_to_base_ConcFlags <$> Internal.getConcFlags++{-# INLINEABLE getMiscFlags #-}+getMiscFlags :: IO MiscFlags+getMiscFlags = internal_to_base_MiscFlags <$> Internal.getMiscFlags++getDebugFlags :: IO DebugFlags+getDebugFlags = internal_to_base_DebugFlags <$> Internal.getDebugFlags++getCCFlags :: IO CCFlags+getCCFlags = internal_to_base_CCFlags <$> Internal.getCCFlags++getProfFlags :: IO ProfFlags+getProfFlags = internal_to_base_ProfFlags <$> Internal.getProfFlags++getTraceFlags :: IO TraceFlags+getTraceFlags = internal_to_base_TraceFlags <$> Internal.getTraceFlags++getTickyFlags :: IO TickyFlags+getTickyFlags = internal_to_base_TickyFlags <$> Internal.getTickyFlags
+ src/GHC/Read.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Read+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The 'Read' class and instances for basic data types.+--++module GHC.Read+  ( -- * Class+    Read(..)++  -- * ReadS type+  , ReadS++  -- * Haskell 2010 compatibility+  , lex+  , lexLitChar+  , readLitChar+  , lexDigits++  -- * Defining readers+  , lexP, expectP+  , paren+  , parens+  , list+  , choose+  , readListDefault, readListPrecDefault+  , readNumber+  , readField+  , readFieldHash+  , readSymField++  , readParen+  )+ where++import GHC.Internal.Read
+ src/GHC/Real.hs view
@@ -0,0 +1,84 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Real+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The types 'Ratio' and 'Rational', and the classes 'Real', 'Fractional',+-- 'Integral', and 'RealFrac'.+--++module GHC.Real+    ( -- * Classes+      Real(..)+    , Integral(..)+    , Fractional(..)+    , RealFrac(..)++      -- * Conversion+    , fromIntegral+    , realToFrac++      -- * Formatting+    , showSigned++      -- * Predicates+    , even+    , odd++      -- * Arithmetic+    , (^)+    , (^^)+    , gcd+    , lcm++      -- * 'Ratio'+    , Ratio(..)+    , Rational+    , infinity+    , notANumber++      -- * 'Enum' helpers+    , numericEnumFrom+    , numericEnumFromThen+    , numericEnumFromTo+    , numericEnumFromThenTo+    , integralEnumFrom+    , integralEnumFromThen+    , integralEnumFromTo+    , integralEnumFromThenTo++      -- ** Construction+    , (%)++      -- ** Projection+    , numerator+    , denominator++      -- ** Operations+    , reduce++      -- * Internal+    , ratioPrec+    , ratioPrec1+    , divZeroError+    , ratioZeroDenominatorError+    , overflowError+    , underflowError+    , mkRationalBase2+    , mkRationalBase10+    , FractionalExponentBase(..)+    , (^%^)+    , (^^%^^)+    , mkRationalWithExponentBase+    , powImpl+    , powImplAcc+    ) where++import GHC.Internal.Real
+ src/GHC/Records.hs view
@@ -0,0 +1,24 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.Records+-- Copyright   :  (c) Adam Gundry 2015-2016+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- This module defines the 'HasField' class used by the+-- @OverloadedRecordDot@ extension.  See the+-- [wiki page](https://gitlab.haskell.org/ghc/ghc/wikis/records/overloaded-record-fields)+-- for more details.+--+-- @since 4.10.0.0++module GHC.Records+    (HasField(..)+     ) where++import GHC.Internal.Records
+ src/GHC/ResponseFile.hs view
@@ -0,0 +1,22 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  GHC.ResponseFile+-- License     :  BSD-style (see the file LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  portable+--+-- GCC style response files.+--+-- @since 4.12.0.0++module GHC.ResponseFile (+    getArgsWithResponseFiles,+    unescapeArgs,+    escapeArgs,+    expandResponse+  ) where++import GHC.Internal.ResponseFile
+ src/GHC/ST.hs view
@@ -0,0 +1,27 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.ST+-- Copyright   :  (c) The University of Glasgow, 1992-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The 'ST' Monad.+--++module GHC.ST+    (ST(..),+     STret(..),+     STRep,+     runST,+     -- *  Unsafe functions+     liftST,+     unsafeInterleaveST,+     unsafeDupableInterleaveST+     ) where++import GHC.Internal.ST
+ src/GHC/STRef.hs view
@@ -0,0 +1,23 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.STRef+-- Copyright   :  (c) The University of Glasgow, 1994-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- References in the 'ST' monad.+--++module GHC.STRef+    (STRef(..),+     newSTRef,+     readSTRef,+     writeSTRef+     ) where++import GHC.Internal.STRef
+ src/GHC/Show.hs view
@@ -0,0 +1,31 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Show+-- Copyright   :  (c) The University of Glasgow, 1992-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- The 'Show' class, and related operations.+--++module GHC.Show+        (+        Show(..), ShowS,++        -- * Show support code+        shows, showChar, showString, showMultiLineString,+        showParen, showList__, showCommaSpace, showSpace,+        showLitChar, showLitString, protectEsc,+        intToDigit, showSignedInt,+        appPrec, appPrec1,++        -- * Character operations+        asciiTab,+  ) where++import GHC.Internal.Show
+ src/GHC/Stable.hs view
@@ -0,0 +1,24 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  GHC.Stable+-- Copyright   :  (c) The University of Glasgow, 1992-2004+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Stable pointers.+--++module GHC.Stable (+        StablePtr(..),+        newStablePtr,+        deRefStablePtr,+        freeStablePtr,+        castStablePtrToPtr,+        castPtrToStablePtr+    ) where++import GHC.Internal.Stable
+ src/GHC/StableName.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  System.Mem.StableName+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable+--+-- Stable names are a way of performing fast ( \(\mathcal{O}(1)\) ),+-- not-quite-exact comparison between objects.+--+-- Stable names solve the following problem: suppose you want to build+-- a hash table with Haskell objects as keys, but you want to use+-- pointer equality for comparison; maybe because the keys are large+-- and hashing would be slow, or perhaps because the keys are infinite+-- in size.  We can\'t build a hash table using the address of the+-- object as the key, because objects get moved around by the garbage+-- collector, meaning a re-hash would be necessary after every garbage+-- collection.+--++module GHC.StableName+    (-- *  Stable Names+     StableName(..),+     makeStableName,+     hashStableName,+     eqStableName+     ) where++import GHC.Internal.StableName
+ src/GHC/Stack.hs view
@@ -0,0 +1,52 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  GHC.Stack+-- Copyright   :  (c) The University of Glasgow 2011+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Access to GHC's call-stack simulation+--+-- @since 4.5.0.0++module GHC.Stack+    (errorWithStackTrace,+     -- *  Profiling call stacks+     currentCallStack,+     whoCreated,+     -- *  HasCallStack call stacks+     CallStack,+     HasCallStack,+     callStack,+     emptyCallStack,+     freezeCallStack,+     fromCallSiteList,+     getCallStack,+     popCallStack,+     prettyCallStack,+     pushCallStack,+     withFrozenCallStack,+     -- *  Source locations+     SrcLoc(..),+     prettySrcLoc,+     -- *  Internals+     CostCentreStack,+     CostCentre,+     getCurrentCCS,+     getCCSOf,+     clearCCS,+     ccsCC,+     ccsParent,+     ccLabel,+     ccModule,+     ccSrcSpan,+     ccsToStrings,+     renderStack+     ) where++import GHC.Internal.Stack
+ src/GHC/Stack/CCS.hs view
@@ -0,0 +1,36 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  GHC.Stack.CCS+-- Copyright   :  (c) The University of Glasgow 2011+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Access to GHC's call-stack simulation+--+-- @since 4.5.0.0++module GHC.Stack.CCS (+    -- * Call stacks+    currentCallStack,+    whoCreated,++    -- * Internals+    CostCentreStack,+    CostCentre,+    getCurrentCCS,+    getCCSOf,+    clearCCS,+    ccsCC,+    ccsParent,+    ccLabel,+    ccModule,+    ccSrcSpan,+    ccsToStrings,+    renderStack,+  ) where++import GHC.Internal.Stack.CCS
+ src/GHC/Stack/CloneStack.hs view
@@ -0,0 +1,20 @@+-- |+-- This module exposes an interface for capturing the state of a thread's+-- execution stack for diagnostics purposes: 'cloneMyStack',+-- 'cloneThreadStack'.+--+-- Such a "cloned" stack can be decoded with 'decode' to a stack trace, given+-- that the @-finfo-table-map@ is enabled.+--+-- @since 4.17.0.0++module GHC.Stack.CloneStack (+  StackSnapshot(..),+  StackEntry(..),+  cloneMyStack,+  cloneThreadStack,+  decode+  ) where++import GHC.Internal.Stack.CloneStack+import GHC.Internal.Stack.Decode
+ src/GHC/Stack/Types.hs view
@@ -0,0 +1,37 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Stack.Types+-- Copyright   :  (c) The University of Glasgow 2015+-- License     :  see libraries/ghc-prim/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Type definitions for implicit call-stacks.+-- Use "GHC.Stack" from the base package instead of importing this+-- module directly.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.Stack.Types+    (-- *  Implicit call stacks+     CallStack(..),+     HasCallStack,+     emptyCallStack,+     freezeCallStack,+     fromCallSiteList,+     getCallStack,+     pushCallStack,+     -- *  Source locations+     SrcLoc(..)+     ) where++import GHC.Internal.Stack.Types
+ src/GHC/StaticPtr.hs view
@@ -0,0 +1,44 @@+-- |+-- Module      :  GHC.StaticPtr+-- Copyright   :  (C) 2014 I/O Tweag+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Symbolic references to values.+--+-- References to values are usually implemented with memory addresses, and this+-- is practical when communicating values between the different pieces of a+-- single process.+--+-- When values are communicated across different processes running in possibly+-- different machines, though, addresses are no longer useful since each+-- process may use different addresses to store a given value.+--+-- To solve such concern, the references provided by this module offer a key+-- that can be used to locate the values on each process. Each process maintains+-- a global table of references which can be looked up with a given key. This+-- table is known as the Static Pointer Table. The reference can then be+-- dereferenced to obtain the value.+--+-- The various communicating processes need to agree on the keys used to refer+-- to the values in the Static Pointer Table, or lookups will fail. Only+-- processes launched from the same program binary are guaranteed to use the+-- same set of keys.+--++module GHC.StaticPtr+  ( StaticPtr+  , deRefStaticPtr+  , StaticKey+  , staticKey+  , unsafeLookupStaticPtr+  , StaticPtrInfo(..)+  , staticPtrInfo+  , staticPtrKeys+  , IsStatic(..)+  ) where++import GHC.Internal.StaticPtr
+ src/GHC/Stats.hs view
@@ -0,0 +1,205 @@+{-# LANGUAGE DeriveGeneric   #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE Safe            #-}++-- |+-- Module      :  RTS.Stats+-- Copyright   :  (c) The University of Glasgow, 1994-2000+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- This module provides access to internal garbage collection and+-- memory usage statistics.  These statistics are not available unless+-- a program is run with the @-T@ RTS flag.+--+-- /The API of this module is unstable and is tightly coupled to GHC's internals./+-- If depend on it, make sure to use a tight upper bound, e.g., @base < 4.X@ rather+-- than @base < 5@, because the interface can change rapidly without much warning.+--+-- @since 4.5.0.0+--+-- This module is a compatibility layer. It is meant to be temporary to allow+-- for the eventual deprecation of these declarations as described in [CLC+-- proposal+-- #289](https://github.com/haskell/core-libraries-committee/issues/289). These+-- declarations are now instead available from the @ghc-experimental@ package.++module GHC.Stats+    ( -- * Runtime statistics+      RTSStats(..), GCDetails(..), RtsTime+    , getRTSStats+    , getRTSStatsEnabled+    ) where+++import Prelude (Bool,IO,Read,Show,(<$>))++import qualified GHC.Internal.Stats as Internal+import GHC.Generics (Generic)+import Data.Word (Word64,Word32)+import Data.Int (Int64)++-- | Time values from the RTS, using a fixed resolution of nanoseconds.+type RtsTime = Int64++--+-- | Statistics about runtime activity since the start of the+-- program.  This is a mirror of the C @struct RTSStats@ in @RtsAPI.h@+--+-- @since base-4.10.0.0+--+data RTSStats = RTSStats {+  -- -----------------------------------+  -- Cumulative stats about memory use++    -- | Total number of GCs+    gcs :: Word32+    -- | Total number of major (oldest generation) GCs+  , major_gcs :: Word32+    -- | Total bytes allocated+  , allocated_bytes :: Word64+    -- | Maximum live data (including large objects + compact regions) in the+    -- heap. Updated after a major GC.+  , max_live_bytes :: Word64+    -- | Maximum live data in large objects+  , max_large_objects_bytes :: Word64+    -- | Maximum live data in compact regions+  , max_compact_bytes :: Word64+    -- | Maximum slop+  , max_slop_bytes :: Word64+    -- | Maximum memory in use by the RTS+  , max_mem_in_use_bytes :: Word64+    -- | Sum of live bytes across all major GCs.  Divided by major_gcs+    -- gives the average live data over the lifetime of the program.+  , cumulative_live_bytes :: Word64+    -- | Sum of copied_bytes across all GCs+  , copied_bytes :: Word64+    -- | Sum of copied_bytes across all parallel GCs+  , par_copied_bytes :: Word64+    -- | Sum of par_max_copied_bytes across all parallel GCs. Deprecated.+  , cumulative_par_max_copied_bytes :: Word64+    -- | Sum of par_balanced_copied bytes across all parallel GCs+  , cumulative_par_balanced_copied_bytes :: Word64++  -- -----------------------------------+  -- Cumulative stats about time use+  -- (we use signed values here because due to inaccuracies in timers+  -- the values can occasionally go slightly negative)++    -- | Total CPU time used by the init phase+    -- @since base-4.12.0.0+  , init_cpu_ns :: RtsTime+    -- | Total elapsed time used by the init phase+    -- @since base-4.12.0.0+  , init_elapsed_ns :: RtsTime+    -- | Total CPU time used by the mutator+  , mutator_cpu_ns :: RtsTime+    -- | Total elapsed time used by the mutator+  , mutator_elapsed_ns :: RtsTime+    -- | Total CPU time used by the GC+  , gc_cpu_ns :: RtsTime+    -- | Total elapsed time used by the GC+  , gc_elapsed_ns :: RtsTime+    -- | Total CPU time (at the previous GC)+  , cpu_ns :: RtsTime+    -- | Total elapsed time (at the previous GC)+  , elapsed_ns :: RtsTime++    -- | The total CPU time used during the post-mark pause phase of the+    -- concurrent nonmoving GC.+  , nonmoving_gc_sync_cpu_ns :: RtsTime+    -- | The total time elapsed during the post-mark pause phase of the+    -- concurrent nonmoving GC.+  , nonmoving_gc_sync_elapsed_ns :: RtsTime+    -- | The maximum elapsed length of any post-mark pause phase of the+    -- concurrent nonmoving GC.+  , nonmoving_gc_sync_max_elapsed_ns :: RtsTime+    -- | The total CPU time used by the nonmoving GC.+  , nonmoving_gc_cpu_ns :: RtsTime+    -- | The total time elapsed during which there is a nonmoving GC active.+  , nonmoving_gc_elapsed_ns :: RtsTime+    -- | The maximum time elapsed during any nonmoving GC cycle.+  , nonmoving_gc_max_elapsed_ns :: RtsTime++    -- | Details about the most recent GC+  , gc :: GCDetails+  } deriving ( Read -- ^ @since base-4.10.0.0+             , Show -- ^ @since base-4.10.0.0+             , Generic -- ^ @since base-4.15.0.0+             )++--+-- | Statistics about a single GC.  This is a mirror of the C @struct+--   GCDetails@ in @RtsAPI.h@, with the field prefixed with @gc_@ to+--   avoid collisions with 'RTSStats'.+--+data GCDetails = GCDetails {+    -- | The generation number of this GC+    gcdetails_gen :: Word32+    -- | Number of threads used in this GC+  , gcdetails_threads :: Word32+    -- | Number of bytes allocated since the previous GC+  , gcdetails_allocated_bytes :: Word64+    -- | Total amount of live data in the heap (includes large + compact data).+    -- Updated after every GC. Data in uncollected generations (in minor GCs)+    -- are considered live.+  , gcdetails_live_bytes :: Word64+    -- | Total amount of live data in large objects+  , gcdetails_large_objects_bytes :: Word64+    -- | Total amount of live data in compact regions+  , gcdetails_compact_bytes :: Word64+    -- | Total amount of slop (wasted memory)+  , gcdetails_slop_bytes :: Word64+    -- | Total amount of memory in use by the RTS+  , gcdetails_mem_in_use_bytes :: Word64+    -- | Total amount of data copied during this GC+  , gcdetails_copied_bytes :: Word64+    -- | In parallel GC, the max amount of data copied by any one thread.+    -- Deprecated.+  , gcdetails_par_max_copied_bytes :: Word64+    -- | In parallel GC, the amount of balanced data copied by all threads+  , gcdetails_par_balanced_copied_bytes :: Word64+    -- | The amount of memory lost due to block fragmentation in bytes.+    -- Block fragmentation is the difference between the amount of blocks retained by the RTS and the blocks that are in use.+    -- This occurs when megablocks are only sparsely used, eg, when data that cannot be moved retains a megablock.+    --+    -- @since base-4.18.0.0+  , gcdetails_block_fragmentation_bytes :: Word64+    -- | The time elapsed during synchronisation before GC+  , gcdetails_sync_elapsed_ns :: RtsTime+    -- | The CPU time used during GC itself+  , gcdetails_cpu_ns :: RtsTime+    -- | The time elapsed during GC itself+  , gcdetails_elapsed_ns :: RtsTime++    -- | The CPU time used during the post-mark pause phase of the concurrent+    -- nonmoving GC.+  , gcdetails_nonmoving_gc_sync_cpu_ns :: RtsTime+    -- | The time elapsed during the post-mark pause phase of the concurrent+    -- nonmoving GC.+  , gcdetails_nonmoving_gc_sync_elapsed_ns :: RtsTime+  } deriving ( Read -- ^ @since base-4.10.0.0+             , Show -- ^ @since base-4.10.0.0+             , Generic -- ^ @since base-4.15.0.0+             )++-------------------------------- compat ----------------------------------------++internal_to_base_RTSStats :: Internal.RTSStats -> RTSStats+internal_to_base_RTSStats i@Internal.RTSStats{..} =+  let gc_details = internal_to_base_GCDetails (Internal.gc i)+  in RTSStats{gc = gc_details,..}++internal_to_base_GCDetails :: Internal.GCDetails -> GCDetails+internal_to_base_GCDetails Internal.GCDetails{..} = GCDetails{..}++-------------------------------- shims -----------------------------------------++getRTSStats :: IO RTSStats+getRTSStats = internal_to_base_RTSStats <$> Internal.getRTSStats++getRTSStatsEnabled :: IO Bool+getRTSStatsEnabled = Internal.getRTSStatsEnabled
+ src/GHC/Storable.hs view
@@ -0,0 +1,52 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Storable+-- Copyright   :  (c) The FFI task force, 2000-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ffi@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Helper functions for "Foreign.Storable"+--++module GHC.Storable+    (readWideCharOffPtr,+     readIntOffPtr,+     readWordOffPtr,+     readPtrOffPtr,+     readFunPtrOffPtr,+     readFloatOffPtr,+     readDoubleOffPtr,+     readStablePtrOffPtr,+     readInt8OffPtr,+     readInt16OffPtr,+     readInt32OffPtr,+     readInt64OffPtr,+     readWord8OffPtr,+     readWord16OffPtr,+     readWord32OffPtr,+     readWord64OffPtr,+     writeWideCharOffPtr,+     writeIntOffPtr,+     writeWordOffPtr,+     writePtrOffPtr,+     writeFunPtrOffPtr,+     writeFloatOffPtr,+     writeDoubleOffPtr,+     writeStablePtrOffPtr,+     writeInt8OffPtr,+     writeInt16OffPtr,+     writeInt32OffPtr,+     writeInt64OffPtr,+     writeWord8OffPtr,+     writeWord16OffPtr,+     writeWord32OffPtr,+     writeWord64OffPtr+     ) where++import GHC.Internal.Storable
+ src/GHC/TopHandler.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.TopHandler+-- Copyright   :  (c) The University of Glasgow, 2001-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Support for catching exceptions raised during top-level computations+-- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports)+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--++module GHC.TopHandler+    (runMainIO,+     runIO,+     runIOFastExit,+     runNonIO,+     topHandler,+     topHandlerFastExit,+     reportStackOverflow,+     reportError,+     flushStdHandles+     ) where++import GHC.Internal.TopHandler
+ src/GHC/TypeError.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++{-|+This module exports:++  - The 'TypeError' type family, which is used to provide custom type+    errors. This is a type-level analogue to the term level error function.+  - The 'ErrorMessage' kind, used to define custom error messages.+  - The 'Unsatisfiable' constraint, a more principled variant of 'TypeError'+    which gives a more predictable way of reporting custom type errors.++@since 4.17.0.0+-}++module GHC.TypeError+  ( ErrorMessage (..)+  , TypeError+  , Assert+  , Unsatisfiable, unsatisfiable+  ) where++import GHC.Internal.TypeError
+ src/GHC/TypeLits.hs view
@@ -0,0 +1,95 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE ExplicitNamespaces #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE NoStarIsType #-}++-- |+--+-- GHC's @DataKinds@ language extension lifts data constructors, natural+-- numbers, and strings to the type level. This module provides the+-- primitives needed for working with type-level numbers (the 'Nat' kind),+-- strings (the 'Symbol' kind), and characters (the 'Char' kind). It also defines the 'TypeError' type+-- family, a feature that makes use of type-level strings to support user+-- defined type errors.+--+-- For now, this module is the API for working with type-level literals.+-- However, please note that it is a work in progress and is subject to change.+-- Once the design of the @DataKinds@ feature is more stable, this will be+-- considered only an internal GHC module, and the programmer interface for+-- working with type-level data will be defined in a separate library.+--+-- @since 4.6.0.0+--++module GHC.TypeLits+    (-- *  Kinds+     Natural,+     Nat,+     Symbol,+     -- *  Linking type and value level+     KnownNat(natSing),+     natVal,+     natVal',+     KnownSymbol(symbolSing),+     symbolVal,+     symbolVal',+     KnownChar(charSing),+     charVal,+     charVal',+     SomeNat(..),+     SomeSymbol(..),+     SomeChar(..),+     someNatVal,+     someSymbolVal,+     someCharVal,+     sameNat,+     sameSymbol,+     sameChar,+     decideNat,+     decideSymbol,+     decideChar,+     OrderingI(..),+     cmpNat,+     cmpSymbol,+     cmpChar,+     -- **  Singleton values+     SNat,+     SSymbol,+     SChar,+     pattern SNat,+     pattern SSymbol,+     pattern SChar,+     fromSNat,+     fromSSymbol,+     fromSChar,+     withSomeSNat,+     withSomeSSymbol,+     withSomeSChar,+     withKnownNat,+     withKnownSymbol,+     withKnownChar,+     -- *  Functions on type literals+     type (<=),+     type (<=?),+     type (+),+     type (*),+     type (^),+     type (-),+     type Div,+     type Mod,+     type Log2,+     AppendSymbol,+     CmpNat,+     CmpSymbol,+     CmpChar,+     ConsSymbol,+     UnconsSymbol,+     CharToNat,+     NatToChar,+     -- *  User-defined type errors+     TypeError,+     ErrorMessage(..)+     ) where++import GHC.Internal.TypeLits
+ src/GHC/TypeNats.hs view
@@ -0,0 +1,47 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE ExplicitNamespaces #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE NoStarIsType #-}++-- |+-- This module is an internal GHC module.  It declares the constants used+-- in the implementation of type-level natural numbers.  The programmer interface+-- for working with type-level naturals should be defined in a separate module.+--+-- @since 4.10.0.0+--++module GHC.TypeNats+    (-- *  Nat Kind+     Natural,+     Nat,+     -- *  Linking type and value level+     KnownNat(natSing),+     natVal,+     natVal',+     SomeNat(..),+     someNatVal,+     sameNat,+     decideNat,+     -- **  Singleton values+     SNat,+     pattern SNat,+     fromSNat,+     withSomeSNat,+     withKnownNat,+     -- *  Functions on type literals+     type (<=),+     type (<=?),+     type (+),+     type (*),+     type (^),+     type (-),+     CmpNat,+     cmpNat,+     Div,+     Mod,+     Log2+     ) where++import GHC.Internal.TypeNats
+ src/GHC/Unicode.hs view
@@ -0,0 +1,46 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Unicode+-- Copyright   :  (c) The University of Glasgow, 2003+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC extensions)+--+-- Implementations for the character predicates (isLower, isUpper, etc.)+-- and the conversions (toUpper, toLower).  The implementation uses+-- libunicode on Unix systems if that is available.+--++module GHC.Unicode+    (unicodeVersion,+     GeneralCategory(..),+     generalCategory,+     isAscii,+     isLatin1,+     isControl,+     isAsciiUpper,+     isAsciiLower,+     isPrint,+     isSpace,+     isUpper,+     isUpperCase,+     isLower,+     isLowerCase,+     isAlpha,+     isDigit,+     isOctDigit,+     isHexDigit,+     isAlphaNum,+     isPunctuation,+     isSymbol,+     toUpper,+     toLower,+     toTitle+     ) where++import GHC.Internal.Unicode
+ src/GHC/Weak.hs view
@@ -0,0 +1,31 @@+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Weak+-- Copyright   :  (c) The University of Glasgow, 1998-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Weak pointers.+--++module GHC.Weak+    (Weak(..),+     mkWeak,+     deRefWeak,+     finalize,+     -- *  Handling exceptions+     -- |  When an exception is thrown by a finalizer called by the+     -- garbage collector, GHC calls a global handler which can be set with+     -- 'setFinalizerExceptionHandler'. Note that any exceptions thrown by+     -- this handler will be ignored.+     setFinalizerExceptionHandler,+     getFinalizerExceptionHandler,+     printToHandleFinalizerExceptionHandler+     ) where++import GHC.Internal.Weak
+ src/GHC/Weak/Finalize.hs view
@@ -0,0 +1,38 @@+{-# LANGUAGE MagicHash #-}+module GHC.Weak.Finalize+    ( -- * Handling exceptions+      -- | When an exception is thrown by a finalizer called by the+      -- garbage collector, GHC calls a global handler which can be set with+      -- 'setFinalizerExceptionHandler'. Note that any exceptions thrown by+      -- this handler will be ignored.+      setFinalizerExceptionHandler+    , getFinalizerExceptionHandler+    , printToHandleFinalizerExceptionHandler+      -- * Internal+    , GHC.Weak.Finalize.runFinalizerBatch+    ) where++import GHC.Internal.Weak.Finalize++-- These imports can be removed once runFinalizerBatch is removed,+-- as can MagicHash above.+import GHC.Internal.Base (Int, Array#, IO, State#, RealWorld)+++{-# DEPRECATED runFinalizerBatch+    "This function is internal to GHC. It will not be exported in future." #-}+-- | Run a batch of finalizers from the garbage collector. Given an+-- array of finalizers and the length of the array, just call each one+-- in turn.+--+-- This is an internal detail of the GHC RTS weak pointer finaliser+-- mechanism. It should no longer be exported from base. There is no+-- good reason to use it. It will be removed in the next major version+-- of base (4.23.*).+--+-- See <https://github.com/haskell/core-libraries-committee/issues/342>+--+runFinalizerBatch :: Int+                  -> Array# (State# RealWorld -> State# RealWorld)+                  -> IO ()+runFinalizerBatch = GHC.Internal.Weak.Finalize.runFinalizerBatch
+ src/GHC/Windows.hs view
@@ -0,0 +1,82 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Safe #-}++-- |+-- Module      :  GHC.Windows+-- Copyright   :  (c) The University of Glasgow, 2009+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  internal+-- Portability :  non-portable+--+-- Windows functionality used by several modules.+--+-- ToDo: this just duplicates part of System.Win32.Types, which isn't+-- available yet.  We should move some Win32 functionality down here,+-- maybe as part of the grand reorganisation of the base package...+--++module GHC.Windows+#if defined(javascript_HOST_ARCH)+    ( ) where++#else+    (+        -- * Types+        BOOL,+        LPBOOL,+        BYTE,+        DWORD,+        DDWORD,+        UINT,+        ULONG,+        ErrCode,+        HANDLE,+        LPWSTR,+        LPTSTR,+        LPCTSTR,+        LPVOID,+        LPDWORD,+        LPSTR,+        LPCSTR,+        LPCWSTR,+        WORD,+        UCHAR,+        NTSTATUS,++        -- * Constants+        iNFINITE,+        iNVALID_HANDLE_VALUE,++        -- * System errors+        throwGetLastError,+        failWith,+        getLastError,+        getErrorMessage,+        errCodeToIOError,++        -- ** Guards for system calls that might fail+        failIf,+        failIf_,+        failIfNull,+        failIfZero,+        failIfFalse_,+        failUnlessSuccess,+        failUnlessSuccessOr,++        -- ** Mapping system errors to errno+        -- $errno+        c_maperrno,+        c_maperrno_func,++        -- * Misc+        ddwordToDwords,+        dwordsToDdword,+        nullHANDLE,+    ) where++#endif++import GHC.Internal.Windows+
+ src/GHC/Word.hs view
@@ -0,0 +1,71 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE MagicHash #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+--+-- Module      :  GHC.Word+-- Copyright   :  (c) The University of Glasgow, 1997-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (GHC Extensions)+--+-- Sized unsigned integral types: 'Word', 'Word8', 'Word16', 'Word32', and+-- 'Word64'.+--++module GHC.Word+    (Word(..),+     Word8(..),+     Word16(..),+     Word32(..),+     Word64(..),+     -- *  Shifts+     uncheckedShiftL64#,+     uncheckedShiftRL64#,+     -- *  Byte swapping+     byteSwap16,+     byteSwap32,+     byteSwap64,+     -- *  Bit reversal+     bitReverse8,+     bitReverse16,+     bitReverse32,+     bitReverse64,+     -- *  Equality operators+     -- |  See GHC.Classes#matching_overloaded_methods_in_rules+     eqWord,+     neWord,+     gtWord,+     geWord,+     ltWord,+     leWord,+     eqWord8,+     neWord8,+     gtWord8,+     geWord8,+     ltWord8,+     leWord8,+     eqWord16,+     neWord16,+     gtWord16,+     geWord16,+     ltWord16,+     leWord16,+     eqWord32,+     neWord32,+     gtWord32,+     geWord32,+     ltWord32,+     leWord32,+     eqWord64,+     neWord64,+     gtWord64,+     geWord64,+     ltWord64,+     leWord64+     ) where++import GHC.Internal.Word
+ src/Numeric.hs view
@@ -0,0 +1,50 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Numeric+-- Copyright   :  (c) The University of Glasgow 2002+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Odds and ends, mostly functions for reading and showing+-- 'RealFloat'-like kind of values.+--++module Numeric+    (-- *  Showing+     showSigned,+     showIntAtBase,+     showInt,+     showBin,+     showHex,+     showOct,+     showEFloat,+     showFFloat,+     showGFloat,+     showFFloatAlt,+     showGFloatAlt,+     showFloat,+     showHFloat,+     floatToDigits,+     -- *  Reading+     -- |  /NB:/ 'readInt' is the \'dual\' of 'showIntAtBase',+     -- and 'readDec' is the \`dual\' of 'showInt'.+     -- The inconsistent naming is a historical accident.+     readSigned,+     readInt,+     readBin,+     readDec,+     readOct,+     readHex,+     readFloat,+     lexDigits,+     -- *  Miscellaneous+     fromRat,+     Floating(..)+     ) where++import GHC.Internal.Numeric
+ src/Numeric/Natural.hs view
@@ -0,0 +1,23 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Numeric.Natural+-- Copyright   :  (C) 2014 Herbert Valerio Riedel,+--                (C) 2011 Edward Kmett+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- The arbitrary-precision 'Natural' number type.+--+-- @since 4.8.0.0++module Numeric.Natural+    (Natural,+     minusNaturalMaybe+     ) where++import GHC.Internal.Numeric.Natural
+ src/Prelude.hs view
@@ -0,0 +1,185 @@+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE NoImplicitPrelude #-}+{-# LANGUAGE ExplicitNamespaces #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Prelude+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The Prelude: a standard module. The Prelude is imported by default+-- into all Haskell modules unless either there is an explicit import+-- statement for it, or the NoImplicitPrelude extension is enabled.+--+-----------------------------------------------------------------------------++module Prelude (++    -- * Standard types, classes and related functions++    -- ** Basic data types+    Bool(False, True),+    (&&), (||), not, otherwise,++    Maybe(Nothing, Just),+    maybe,++    Either(Left, Right),+    either,++    Ordering(LT, EQ, GT),+    Char, String,++    -- *** Tuples+    fst, snd, curry, uncurry,++    -- ** Basic type classes+    Eq((==), (/=)),+    Ord(compare, (<), (<=), (>=), (>), max, min),+    Enum(succ, pred, toEnum, fromEnum, enumFrom, enumFromThen,+         enumFromTo, enumFromThenTo),+    Bounded(minBound, maxBound),++    -- ** Numbers++    -- *** Numeric types+    Int, Integer, Float, Double,+    Rational, Word,++    -- *** Numeric type classes+    Num((+), (-), (*), negate, abs, signum, fromInteger),+    Real(toRational),+    Integral(quot, rem, div, mod, quotRem, divMod, toInteger),+    Fractional((/), recip, fromRational),+    Floating(pi, exp, log, sqrt, (**), logBase, sin, cos, tan,+             asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh),+    RealFrac(properFraction, truncate, round, ceiling, floor),+    RealFloat(floatRadix, floatDigits, floatRange, decodeFloat,+              encodeFloat, exponent, significand, scaleFloat, isNaN,+              isInfinite, isDenormalized, isIEEE, isNegativeZero, atan2),++    -- *** Numeric functions+    subtract, even, odd, gcd, lcm, (^), (^^),+    fromIntegral, realToFrac,++    -- ** Semigroups and Monoids+    Semigroup((<>)),+    Monoid(mempty, mappend, mconcat),++    -- ** Monads and functors+    Functor(fmap, (<$)), (<$>),+    Applicative(pure, (<*>), (*>), (<*), liftA2),+    Monad((>>=), (>>), return),+    MonadFail(fail),+    mapM_, sequence_, (=<<),++    -- ** Folds and traversals+    Foldable(elem,      -- :: (Foldable t, Eq a) => a -> t a -> Bool+             -- fold,   -- :: Monoid m => t m -> m+             foldMap,   -- :: Monoid m => (a -> m) -> t a -> m+             foldr,     -- :: (a -> b -> b) -> b -> t a -> b+             -- foldr', -- :: (a -> b -> b) -> b -> t a -> b+             foldl,     -- :: (b -> a -> b) -> b -> t a -> b+             foldl', -- :: (b -> a -> b) -> b -> t a -> b+             foldr1,    -- :: (a -> a -> a) -> t a -> a+             foldl1,    -- :: (a -> a -> a) -> t a -> a+             maximum,   -- :: (Foldable t, Ord a) => t a -> a+             minimum,   -- :: (Foldable t, Ord a) => t a -> a+             product,   -- :: (Foldable t, Num a) => t a -> a+             sum),      -- :: Num a => t a -> a+             -- toList) -- :: Foldable t => t a -> [a]++    Traversable(traverse, sequenceA, mapM, sequence),++    -- ** Miscellaneous functions+    id, const, (.), flip, ($), until,+    asTypeOf, error, errorWithoutStackTrace, undefined,+    seq, ($!),++    -- * List operations+    List.map, (List.++), List.filter,+    List.head, List.last, List.tail, List.init, (List.!!),+    Foldable.null, Foldable.length,+    List.reverse,+    -- *** Special folds+    Foldable.and, Foldable.or, Foldable.any, Foldable.all,+    Foldable.concat, Foldable.concatMap,+    -- ** Building lists+    -- *** Scans+    List.scanl, List.scanl1, List.scanr, List.scanr1,+    -- *** Infinite lists+    List.iterate, List.repeat, List.replicate, List.cycle,+    -- ** Sublists+    List.take, List.drop,+    List.takeWhile, List.dropWhile,+    List.span, List.break,+    List.splitAt,+    -- ** Searching lists+    Foldable.notElem,+    List.lookup,+    -- ** Zipping and unzipping lists+    List.zip, List.zip3,+    List.zipWith, List.zipWith3,+    List.unzip, List.unzip3,+    -- ** Functions on strings+    List.lines, List.words, List.unlines, List.unwords,++    -- * Converting to and from @String@+    -- ** Converting to @String@+    ShowS,+    Show(showsPrec, showList, show),+    shows,+    showChar, showString, showParen,+    -- ** Converting from @String@+    ReadS,+    Read(readsPrec, readList),+    reads, readParen, read, lex,++    -- * Basic Input and output+    IO,+    -- ** Simple I\/O operations+    -- All I/O functions defined here are character oriented.  The+    -- treatment of the newline character will vary on different systems.+    -- For example, two characters of input, return and linefeed, may+    -- read as a single newline character.  These functions cannot be+    -- used portably for binary I/O.+    -- *** Output functions+    putChar,+    putStr, putStrLn, print,+    -- *** Input functions+    getChar,+    getLine, getContents, interact,+    -- *** Files+    FilePath,+    readFile, writeFile, appendFile, readIO, readLn,+    -- ** Exception handling in the I\/O monad+    IOError, ioError, userError,++    -- ** The equality types+    type (~)+  ) where++import GHC.Internal.Control.Monad+import GHC.Internal.System.IO+import GHC.Internal.System.IO.Error+import qualified GHC.Internal.Data.List as List+import GHC.Internal.Data.Either+import GHC.Internal.Data.Foldable    ( Foldable(..) )+import qualified GHC.Internal.Data.Foldable as Foldable+import GHC.Internal.Data.Functor     ( (<$>) )+import GHC.Internal.Data.Maybe+import GHC.Internal.Data.Traversable ( Traversable(..) )+import GHC.Internal.Data.Tuple++import GHC.Internal.Base hiding ( foldr, mapM, sequence )+import GHC.Internal.Text.Read+import GHC.Internal.Enum+import GHC.Internal.Num+import GHC.Internal.Real+import GHC.Internal.Float+import GHC.Internal.Show
+ src/System/CPUTime.hsc view
@@ -0,0 +1,71 @@+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE CPP, CApiFFI #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  System.CPUTime+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- The standard CPUTime library.+--+-----------------------------------------------------------------------------++#include "HsFFI.h"+#include "HsBaseConfig.h"++-- For various _POSIX_* #defines+#if defined(HAVE_UNISTD_H)+#include <unistd.h>+#endif++module System.CPUTime+    ( getCPUTime+    , cpuTimePrecision+    ) where++import Prelude+import System.IO.Unsafe (unsafePerformIO)++-- Here is where we decide which backend to use+#if defined(mingw32_HOST_OS)+import qualified System.CPUTime.Windows as I++#elif defined(javascript_HOST_ARCH)+import qualified System.CPUTime.Javascript as I++#elif _POSIX_TIMERS > 0 && defined(_POSIX_CPUTIME) && _POSIX_CPUTIME >= 0+import qualified System.CPUTime.Posix.ClockGetTime as I++#elif defined(HAVE_GETRUSAGE) && ! solaris2_HOST_OS+import qualified System.CPUTime.Posix.RUsage as I++-- @getrusage()@ is right royal pain to deal with when targeting multiple+-- versions of Solaris, since some versions supply it in libc (2.3 and 2.5),+-- while 2.4 has got it in libucb (I wouldn't be too surprised if it was back+-- again in libucb in 2.6..)+--+-- Avoid the problem by resorting to times() instead.+#elif defined(HAVE_TIMES)+import qualified System.CPUTime.Posix.Times as I++#else+import qualified System.CPUTime.Unsupported as I+#endif++-- | The 'cpuTimePrecision' constant is the smallest measurable difference+-- in CPU time that the implementation can record, and is given as an+-- integral number of picoseconds.+cpuTimePrecision :: Integer+cpuTimePrecision = unsafePerformIO I.getCpuTimePrecision+{-# NOINLINE cpuTimePrecision #-}++-- | Computation 'getCPUTime' returns the number of picoseconds CPU time+-- used by the current program.  The precision of this result is+-- implementation-dependent.+getCPUTime :: IO Integer+getCPUTime = I.getCPUTime
+ src/System/CPUTime/Javascript.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE JavaScriptFFI #-}++module System.CPUTime.Javascript+  ( getCPUTime+  , getCpuTimePrecision+  )+where++import qualified System.CPUTime.Unsupported as I+import Prelude++getCpuTimePrecision :: IO Integer+getCpuTimePrecision = toInteger <$> js_cpuTimePrecision++getCPUTime :: IO Integer+getCPUTime = do+  t <- js_getCPUTime+  if t == -1 then I.getCPUTime+             else pure (1000 * round t)++foreign import javascript unsafe+  "(() => { return h$cpuTimePrecision(); })"+  js_cpuTimePrecision :: IO Int++foreign import javascript unsafe+  "(() => { return h$getCPUTime(); })"+  js_getCPUTime :: IO Double
+ src/System/CPUTime/Posix/ClockGetTime.hsc view
@@ -0,0 +1,61 @@+{-# LANGUAGE CPP, CApiFFI, NumDecimals #-}++#include "HsFFI.h"+#include "HsBaseConfig.h"+#include <unistd.h>+#include <time.h>++module System.CPUTime.Posix.ClockGetTime+    ( getCPUTime+    , getCpuTimePrecision+    ) where++import Prelude++#if _POSIX_TIMERS > 0 && defined(_POSIX_CPUTIME) && _POSIX_CPUTIME >= 0++import Foreign+import Foreign.C+import System.CPUTime.Utils++getCPUTime :: IO Integer+getCPUTime = fmap snd $ withTimespec $ \ts ->+    throwErrnoIfMinus1_ "clock_gettime"+    $ clock_gettime cLOCK_PROCESS_CPUTIME_ID ts++getCpuTimePrecision :: IO Integer+getCpuTimePrecision = fmap snd $ withTimespec $ \ts ->+    throwErrnoIfMinus1_ "clock_getres"+    $ clock_getres cLOCK_PROCESS_CPUTIME_ID ts++data Timespec++-- | Perform the given action to fill in a @struct timespec@, returning the+-- result of the action and the value of the @timespec@ in picoseconds.+withTimespec :: (Ptr Timespec -> IO a) -> IO (a, Integer)+withTimespec action =+    allocaBytes (# const sizeof(struct timespec)) $ \p_ts -> do+        r <- action p_ts+        u_sec  <- (#peek struct timespec,tv_sec)  p_ts :: IO CTime+        u_nsec <- (#peek struct timespec,tv_nsec) p_ts :: IO CLong+        return (r, cTimeToInteger u_sec * 1e12 + fromIntegral u_nsec * 1e3)++foreign import capi unsafe "time.h clock_getres"  clock_getres  :: CUIntPtr -> Ptr Timespec -> IO CInt+foreign import capi unsafe "time.h clock_gettime" clock_gettime :: CUIntPtr -> Ptr Timespec -> IO CInt++#if HAVE_DECL_CLOCK_PROCESS_CPUTIME_ID+foreign import capi unsafe "time.h value CLOCK_PROCESS_CPUTIME_ID" cLOCK_PROCESS_CPUTIME_ID :: CUIntPtr+#else+foreign import capi unsafe "time.h value CLOCK_MONOTONIC" cLOCK_PROCESS_CPUTIME_ID :: CUIntPtr+#endif // HAVE_DECL_CLOCK_PROCESS_CPUTIME_ID++#else++-- This should never happen+getCPUTime :: IO Integer+getCPUTime = error "System.CPUTime.Posix.ClockGetTime: Unsupported"++getCpuTimePrecision :: IO Integer+getCpuTimePrecision = error "System.CPUTime.Posix.ClockGetTime: Unsupported"++#endif // _POSIX_CPUTIME
+ src/System/CPUTime/Posix/RUsage.hsc view
@@ -0,0 +1,55 @@+{-# LANGUAGE CPP, CApiFFI, NumDecimals #-}++#include "HsFFI.h"+#include "HsBaseConfig.h"++module System.CPUTime.Posix.RUsage+    ( getCPUTime+    , getCpuTimePrecision+    ) where++import Prelude+import Data.Ratio+import Foreign+import Foreign.C+import System.CPUTime.Utils++-- For struct rusage+#if HAVE_SYS_RESOURCE_H+#include <sys/resource.h>+#endif++#if HAVE_GETRUSAGE++getCPUTime :: IO Integer+getCPUTime = allocaBytes (#const sizeof(struct rusage)) $ \ p_rusage -> do+    throwErrnoIfMinus1_ "getrusage" $ getrusage (#const RUSAGE_SELF) p_rusage++    let ru_utime = (#ptr struct rusage, ru_utime) p_rusage+    let ru_stime = (#ptr struct rusage, ru_stime) p_rusage+    u_sec  <- (#peek struct timeval,tv_sec)  ru_utime :: IO CTime+    u_usec <- (#peek struct timeval,tv_usec) ru_utime :: IO CSUSeconds+    s_sec  <- (#peek struct timeval,tv_sec)  ru_stime :: IO CTime+    s_usec <- (#peek struct timeval,tv_usec) ru_stime :: IO CSUSeconds+    let usec = cTimeToInteger u_sec * 1e6 + csuSecondsToInteger u_usec ++               cTimeToInteger s_sec * 1e6 + csuSecondsToInteger s_usec+    return (usec * 1e6)++type CRUsage = ()+foreign import capi unsafe "HsBase.h getrusage" getrusage :: CInt -> Ptr CRUsage -> IO CInt++getCpuTimePrecision :: IO Integer+getCpuTimePrecision =+    return $ round ((1e12::Integer) % fromIntegral clk_tck)++foreign import ccall unsafe clk_tck :: CLong++#else++getCPUTime :: IO Integer+getCPUTime = fail "System.CPUTime.Posix.RUsage.getCPUTime"++getCpuTimePrecision :: IO Integer+getCpuTimePrecision = fail "System.CPUTime.Posix.RUsage.getCpuTimePrecision"++#endif
+ src/System/CPUTime/Posix/Times.hsc view
@@ -0,0 +1,52 @@+{-# LANGUAGE CPP, CApiFFI, NumDecimals #-}++#include "HsFFI.h"+#include "HsBaseConfig.h"++module System.CPUTime.Posix.Times+    ( getCPUTime+    , getCpuTimePrecision+    ) where++import Prelude+import Foreign+import Data.Ratio+import GHC.Internal.Foreign.C.Types+import System.CPUTime.Utils++-- for struct tms+#if HAVE_SYS_TIMES_H+#include <sys/times.h>+#endif++#if HAVE_TIMES++getCPUTime :: IO Integer+getCPUTime = allocaBytes (#const sizeof(struct tms)) $ \ p_tms -> do+    _ <- times p_tms+    u_ticks  <- (#peek struct tms,tms_utime) p_tms :: IO CClock+    s_ticks  <- (#peek struct tms,tms_stime) p_tms :: IO CClock+    return (( (cClockToInteger u_ticks + cClockToInteger s_ticks) * 1e12)+                        `div` fromIntegral clockTicks)++type CTms = ()+foreign import ccall unsafe times :: Ptr CTms -> IO CClock++getCpuTimePrecision :: IO Integer+getCpuTimePrecision =+    return $ round ((1e12::Integer) % clockTicks)++foreign import ccall unsafe clk_tck :: CLong++clockTicks :: Integer+clockTicks = fromIntegral clk_tck++#else++getCPUTime :: IO Integer+getCPUTime = fail "System.CPUTime.Posix.Times.getCPUTime"++getCpuTimePrecision :: IO Integer+getCpuTimePrecision = fail "System.CPUTime.Posix.Times.getCpuTimePrecision"++#endif
+ src/System/CPUTime/Unsupported.hs view
@@ -0,0 +1,21 @@+module System.CPUTime.Unsupported+    ( getCPUTime+    , getCpuTimePrecision+    ) where++import GHC.Internal.IO.Exception+import Prelude++getCPUTime :: IO Integer+getCPUTime =+    ioError (IOError Nothing UnsupportedOperation+                     "getCPUTime"+                     "can't get CPU time"+                     Nothing Nothing)++getCpuTimePrecision :: IO Integer+getCpuTimePrecision =+    ioError (IOError Nothing UnsupportedOperation+                     "cpuTimePrecision"+                     "can't get CPU time"+                     Nothing Nothing)
+ src/System/CPUTime/Utils.hs view
@@ -0,0 +1,21 @@+module System.CPUTime.Utils+    ( -- * Integer conversions+      -- | These types have no 'Integral' instances in the Haskell report+      -- so we must do this ourselves.+      cClockToInteger+    , cTimeToInteger+    , csuSecondsToInteger+    ) where++import GHC.Internal.Foreign.C.Types+import GHC.Num.Integer (Integer)+import GHC.Internal.Real (fromIntegral)++cClockToInteger :: CClock -> Integer+cClockToInteger (CClock n) = fromIntegral n++cTimeToInteger :: CTime -> Integer+cTimeToInteger (CTime n) = fromIntegral n++csuSecondsToInteger :: CSUSeconds -> Integer+csuSecondsToInteger (CSUSeconds n) = fromIntegral n
+ src/System/CPUTime/Windows.hsc view
@@ -0,0 +1,68 @@+{-# LANGUAGE CPP, CApiFFI, NondecreasingIndentation, NumDecimals #-}++#include "HsFFI.h"+#include "HsBaseConfig.h"++module System.CPUTime.Windows+    ( getCPUTime+    , getCpuTimePrecision+    ) where++import GHC.Internal.Foreign.Ptr+import GHC.Internal.Foreign.Marshal.Alloc+import GHC.Internal.Foreign.Marshal.Utils+import GHC.Internal.Foreign.Storable+import GHC.Internal.Foreign.C.Types+import GHC.Internal.Word+import Prelude++-- For FILETIME etc. on Windows+#if HAVE_WINDOWS_H+#include <windows.h>+#endif++getCPUTime :: IO Integer+getCPUTime = do+     -- NOTE: GetProcessTimes() is only supported on NT-based OSes.+     -- The counts reported by GetProcessTimes() are in 100-ns (10^-7) units.+    allocaBytes (#const sizeof(FILETIME)) $ \ p_creationTime -> do+    allocaBytes (#const sizeof(FILETIME)) $ \ p_exitTime -> do+    allocaBytes (#const sizeof(FILETIME)) $ \ p_kernelTime -> do+    allocaBytes (#const sizeof(FILETIME)) $ \ p_userTime -> do+    pid <- getCurrentProcess+    ok <- getProcessTimes pid p_creationTime p_exitTime p_kernelTime p_userTime+    if toBool ok then do+      ut <- ft2psecs p_userTime+      kt <- ft2psecs p_kernelTime+      return (ut + kt)+     else return 0+  where+        ft2psecs :: Ptr FILETIME -> IO Integer+        ft2psecs ft = do+          high <- (#peek FILETIME,dwHighDateTime) ft :: IO Word32+          low  <- (#peek FILETIME,dwLowDateTime)  ft :: IO Word32+            -- Convert 100-ns units to picosecs (10^-12)+            -- => multiply by 10^5.+          return (((fromIntegral high) * (2^(32::Int)) + (fromIntegral low)) * 100000)++    -- ToDo: pin down elapsed times to just the OS thread(s) that+    -- are evaluating/managing Haskell code.++-- While it's hard to get reliable numbers, the consensus is that Windows only provides+-- 16 millisecond resolution in GetProcessTimes (see Python PEP 0418)+getCpuTimePrecision :: IO Integer+getCpuTimePrecision = return 16e9++type FILETIME = ()+type HANDLE = ()++-- need proper Haskell names (initial lower-case character)+#if defined(i386_HOST_ARCH)+foreign import stdcall unsafe "GetCurrentProcess" getCurrentProcess :: IO (Ptr HANDLE)+foreign import stdcall unsafe "GetProcessTimes" getProcessTimes :: Ptr HANDLE -> Ptr FILETIME -> Ptr FILETIME -> Ptr FILETIME -> Ptr FILETIME -> IO CInt+#elif defined(x86_64_HOST_ARCH) || defined(aarch64_HOST_ARCH)+foreign import ccall unsafe "GetCurrentProcess" getCurrentProcess :: IO (Ptr HANDLE)+foreign import ccall unsafe "GetProcessTimes" getProcessTimes :: Ptr HANDLE -> Ptr FILETIME -> Ptr FILETIME -> Ptr FILETIME -> Ptr FILETIME -> IO CInt+#else+#error Unknown mingw32 arch+#endif
+ src/System/Console/GetOpt.hs view
@@ -0,0 +1,411 @@+{-# LANGUAGE Safe #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  System.Console.GetOpt+-- Copyright   :  (c) Sven Panne 2002-2005+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- This module provides facilities for parsing the command-line options+-- in a standalone program.  It is essentially a Haskell port of the GNU+-- @getopt@ library.+--+-----------------------------------------------------------------------------++{-+Sven Panne <Sven.Panne@informatik.uni-muenchen.de> Oct. 1996 (small+changes Dec. 1997)++Two rather obscure features are missing: The Bash 2.0 non-option hack+(if you don't already know it, you probably don't want to hear about+it...) and the recognition of long options with a single dash+(e.g. '-help' is recognised as '--help', as long as there is no short+option 'h').++Other differences between GNU's getopt and this implementation:++* To enforce a coherent description of options and arguments, there+  are explanation fields in the option/argument descriptor.++* Error messages are now more informative, but no longer POSIX+  compliant... :-(++And a final Haskell advertisement: The GNU C implementation uses well+over 1100 lines, we need only 195 here, including a 46 line example!+:-)+-}++module System.Console.GetOpt (+   -- * GetOpt+   getOpt, getOpt',+   usageInfo,+   ArgOrder(..),+   OptDescr(..),+   ArgDescr(..),++   -- * Examples++   -- |To hopefully illuminate the role of the different data structures,+   -- here are the command-line options for a (very simple) compiler,+   -- done in two different ways.+   -- The difference arises because the type of 'getOpt' is+   -- parameterized by the type of values derived from flags.++   -- ** Interpreting flags as concrete values+   -- $example1++   -- ** Interpreting flags as transformations of an options record+   -- $example2+) where++import Prelude+import GHC.Internal.Data.List ( isPrefixOf, find )++-- |What to do with options following non-options+data ArgOrder a+  = RequireOrder                -- ^ no option processing after first non-option+  | Permute                     -- ^ freely intersperse options and non-options+  | ReturnInOrder (String -> a) -- ^ wrap non-options into options++{-|+Each 'OptDescr' describes a single option.++The arguments to 'Option' are:++* list of short option characters++* list of long option strings (without \"--\")++* argument descriptor++* explanation of option for user+-}+data OptDescr a =              -- description of a single options:+   Option [Char]                --    list of short option characters+          [String]              --    list of long option strings (without "--")+          (ArgDescr a)          --    argument descriptor+          String                --    explanation of option for user++-- |Describes whether an option takes an argument or not, and if so+-- how the argument is injected into a value of type @a@.+data ArgDescr a+   = NoArg                   a         -- ^   no argument expected+   | ReqArg (String       -> a) String -- ^   option requires argument+   | OptArg (Maybe String -> a) String -- ^   optional argument++-- | @since 4.7.0.0+instance Functor ArgOrder where+    fmap _ RequireOrder      = RequireOrder+    fmap _ Permute           = Permute+    fmap f (ReturnInOrder g) = ReturnInOrder (f . g)++-- | @since 4.7.0.0+instance Functor OptDescr where+    fmap f (Option a b argDescr c) = Option a b (fmap f argDescr) c++-- | @since 4.7.0.0+instance Functor ArgDescr where+    fmap f (NoArg a)    = NoArg (f a)+    fmap f (ReqArg g s) = ReqArg (f . g) s+    fmap f (OptArg g s) = OptArg (f . g) s++data OptKind a                -- kind of cmd line arg (internal use only):+   = Opt       a                --    an option+   | UnreqOpt  String           --    an un-recognized option+   | NonOpt    String           --    a non-option+   | EndOfOpts                  --    end-of-options marker (i.e. "--")+   | OptErr    String           --    something went wrong...++-- | Return a string describing the usage of a command, derived from+-- the header (first argument) and the options described by the+-- second argument.+usageInfo :: String                    -- header+          -> [OptDescr a]              -- option descriptors+          -> String                    -- nicely formatted description of options+usageInfo header optDescr = unlines (header:table)+   where (ss,ls,ds)     = (unzip3 . concatMap fmtOpt) optDescr+         table          = zipWith3 paste (sameLen ss) (sameLen ls) ds+         paste x y z    = "  " ++ x ++ "  " ++ y ++ "  " ++ z+         sameLen xs     = flushLeft ((maximum . map length) xs) xs+         flushLeft n xs = [ take n (x ++ repeat ' ') | x <- xs ]++fmtOpt :: OptDescr a -> [(String,String,String)]+fmtOpt (Option sos los ad descr) =+   case lines descr of+     []     -> [(sosFmt,losFmt,"")]+     (d:ds) ->  (sosFmt,losFmt,d) : [ ("","",d') | d' <- ds ]+   where sepBy _  []     = ""+         sepBy _  [x]    = x+         sepBy ch (x:xs) = x ++ ch:' ':sepBy ch xs+         sosFmt = sepBy ',' (map (fmtShort ad) sos)+         losFmt = sepBy ',' (map (fmtLong  ad) los)++fmtShort :: ArgDescr a -> Char -> String+fmtShort (NoArg  _   ) so = "-" ++ [so]+fmtShort (ReqArg _ ad) so = "-" ++ [so] ++ " " ++ ad+fmtShort (OptArg _ ad) so = "-" ++ [so] ++ "[" ++ ad ++ "]"++fmtLong :: ArgDescr a -> String -> String+fmtLong (NoArg  _   ) lo = "--" ++ lo+fmtLong (ReqArg _ ad) lo = "--" ++ lo ++ "=" ++ ad+fmtLong (OptArg _ ad) lo = "--" ++ lo ++ "[=" ++ ad ++ "]"++{-|+Process the command-line, and return the list of values that matched+(and those that didn\'t). The arguments are:++* The order requirements (see 'ArgOrder')++* The option descriptions (see 'OptDescr')++* The actual command line arguments (presumably got from+  'GHC.Internal.System.Environment.getArgs').++'getOpt' returns a triple consisting of the option arguments, a list+of non-options, and a list of error messages.+-}+getOpt :: ArgOrder a                   -- non-option handling+       -> [OptDescr a]                 -- option descriptors+       -> [String]                     -- the command-line arguments+       -> ([a],[String],[String])      -- (options,non-options,error messages)+getOpt ordering optDescr args = (os,xs,es ++ map errUnrec us)+   where (os,xs,us,es) = getOpt' ordering optDescr args++{-|+This is almost the same as 'getOpt', but returns a quadruple+consisting of the option arguments, a list of non-options, a list of+unrecognized options, and a list of error messages.+-}+getOpt' :: ArgOrder a                         -- non-option handling+        -> [OptDescr a]                       -- option descriptors+        -> [String]                           -- the command-line arguments+        -> ([a],[String], [String] ,[String]) -- (options,non-options,unrecognized,error messages)+getOpt' _        _        []         =  ([],[],[],[])+getOpt' ordering optDescr (arg:args) = procNextOpt opt ordering+   where procNextOpt (Opt o)      _                 = (o:os,xs,us,es)+         procNextOpt (UnreqOpt u) _                 = (os,xs,u:us,es)+         procNextOpt (NonOpt x)   RequireOrder      = ([],x:rest,[],[])+         procNextOpt (NonOpt x)   Permute           = (os,x:xs,us,es)+         procNextOpt (NonOpt x)   (ReturnInOrder f) = (f x :os, xs,us,es)+         procNextOpt EndOfOpts    RequireOrder      = ([],rest,[],[])+         procNextOpt EndOfOpts    Permute           = ([],rest,[],[])+         procNextOpt EndOfOpts    (ReturnInOrder f) = (map f rest,[],[],[])+         procNextOpt (OptErr e)   _                 = (os,xs,us,e:es)++         (opt,rest) = getNext arg args optDescr+         (os,xs,us,es) = getOpt' ordering optDescr rest++-- take a look at the next cmd line arg and decide what to do with it+getNext :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])+getNext ('-':'-':[]) rest _        = (EndOfOpts,rest)+getNext ('-':'-':xs) rest optDescr = longOpt xs rest optDescr+getNext ('-': x :xs) rest optDescr = shortOpt x xs rest optDescr+getNext a            rest _        = (NonOpt a,rest)++-- handle long option+longOpt :: String -> [String] -> [OptDescr a] -> (OptKind a,[String])+longOpt ls rs optDescr = long ads arg rs+   where (opt,arg) = break (=='=') ls+         getWith p = [ o | o@(Option _ xs _ _) <- optDescr+                         , find (p opt) xs /= Nothing ]+         exact     = getWith (==)+         options   = if null exact then getWith isPrefixOf else exact+         ads       = [ ad | Option _ _ ad _ <- options ]+         optStr    = ("--"++opt)++         long (_:_:_)      _        rest     = (errAmbig options optStr,rest)+         long [NoArg  a  ] []       rest     = (Opt a,rest)+         long [NoArg  _  ] ('=':_)  rest     = (errNoArg optStr,rest)+         long [ReqArg _ d] []       []       = (errReq d optStr,[])+         long [ReqArg f _] []       (r:rest) = (Opt (f r),rest)+         long [ReqArg f _] ('=':xs) rest     = (Opt (f xs),rest)+         long [OptArg f _] []       rest     = (Opt (f Nothing),rest)+         long [OptArg f _] ('=':xs) rest     = (Opt (f (Just xs)),rest)+         long _            _        rest     = (UnreqOpt ("--"++ls),rest)++-- handle short option+shortOpt :: Char -> String -> [String] -> [OptDescr a] -> (OptKind a,[String])+shortOpt y ys rs optDescr = short ads ys rs+  where options = [ o  | o@(Option ss _ _ _) <- optDescr, s <- ss, y == s ]+        ads     = [ ad | Option _ _ ad _ <- options ]+        optStr  = '-':[y]++        short (_:_:_)        _  rest     = (errAmbig options optStr,rest)+        short (NoArg  a  :_) [] rest     = (Opt a,rest)+        short (NoArg  a  :_) xs rest     = (Opt a,('-':xs):rest)+        short (ReqArg _ d:_) [] []       = (errReq d optStr,[])+        short (ReqArg f _:_) [] (r:rest) = (Opt (f r),rest)+        short (ReqArg f _:_) xs rest     = (Opt (f xs),rest)+        short (OptArg f _:_) [] rest     = (Opt (f Nothing),rest)+        short (OptArg f _:_) xs rest     = (Opt (f (Just xs)),rest)+        short []             [] rest     = (UnreqOpt optStr,rest)+        short []             xs rest     = (UnreqOpt optStr,('-':xs):rest)++-- miscellaneous error formatting++errAmbig :: [OptDescr a] -> String -> OptKind a+errAmbig ods optStr = OptErr (usageInfo header ods)+   where header = "option `" ++ optStr ++ "' is ambiguous; could be one of:"++errReq :: String -> String -> OptKind a+errReq d optStr = OptErr ("option `" ++ optStr ++ "' requires an argument " ++ d ++ "\n")++errUnrec :: String -> String+errUnrec optStr = "unrecognized option `" ++ optStr ++ "'\n"++errNoArg :: String -> OptKind a+errNoArg optStr = OptErr ("option `" ++ optStr ++ "' doesn't allow an argument\n")++{-+-----------------------------------------------------------------------------------------+-- and here a small and hopefully enlightening example:++data Flag = Verbose | Version | Name String | Output String | Arg String   deriving Show++options :: [OptDescr Flag]+options =+   [Option ['v']     ["verbose"]           (NoArg Verbose)      "verbosely list files",+    Option ['V','?'] ["version","release"] (NoArg Version)      "show version info",+    Option ['o']     ["output"]            (OptArg out "FILE")  "use FILE for dump",+    Option ['n']     ["name"]              (ReqArg Name "USER") "only dump USER's files"]++out :: Maybe String -> Flag+out Nothing  = Output "stdout"+out (Just o) = Output o++test :: ArgOrder Flag -> [String] -> String+test order cmdline = case getOpt order options cmdline of+                        (o,n,[]  ) -> "options=" ++ show o ++ "  args=" ++ show n ++ "\n"+                        (_,_,errs) -> concat errs ++ usageInfo header options+   where header = "Usage: foobar [OPTION...] files..."++-- example runs:+-- putStr (test RequireOrder ["foo","-v"])+--    ==> options=[]  args=["foo", "-v"]+-- putStr (test Permute ["foo","-v"])+--    ==> options=[Verbose]  args=["foo"]+-- putStr (test (ReturnInOrder Arg) ["foo","-v"])+--    ==> options=[Arg "foo", Verbose]  args=[]+-- putStr (test Permute ["foo","--","-v"])+--    ==> options=[]  args=["foo", "-v"]+-- putStr (test Permute ["-?o","--name","bar","--na=baz"])+--    ==> options=[Version, Output "stdout", Name "bar", Name "baz"]  args=[]+-- putStr (test Permute ["--ver","foo"])+--    ==> option `--ver' is ambiguous; could be one of:+--          -v      --verbose             verbosely list files+--          -V, -?  --version, --release  show version info+--        Usage: foobar [OPTION...] files...+--          -v        --verbose             verbosely list files+--          -V, -?    --version, --release  show version info+--          -o[FILE]  --output[=FILE]       use FILE for dump+--          -n USER   --name=USER           only dump USER's files+-----------------------------------------------------------------------------------------+-}++{- $example1++A simple choice for the type associated with flags is to define a type+@Flag@ as an algebraic type representing the possible flags and their+arguments:++>    module Opts1 where+>+>    import System.Console.GetOpt+>    import GHC.Internal.Data.Maybe ( fromMaybe )+>+>    data Flag+>     = Verbose  | Version+>     | Input String | Output String | LibDir String+>       deriving Show+>+>    options :: [OptDescr Flag]+>    options =+>     [ Option ['v']     ["verbose"] (NoArg Verbose)       "chatty output on stderr"+>     , Option ['V','?'] ["version"] (NoArg Version)       "show version number"+>     , Option ['o']     ["output"]  (OptArg outp "FILE")  "output FILE"+>     , Option ['c']     []          (OptArg inp  "FILE")  "input FILE"+>     , Option ['L']     ["libdir"]  (ReqArg LibDir "DIR") "library directory"+>     ]+>+>    inp,outp :: Maybe String -> Flag+>    outp = Output . fromMaybe "stdout"+>    inp  = Input  . fromMaybe "stdin"+>+>    compilerOpts :: [String] -> IO ([Flag], [String])+>    compilerOpts argv =+>       case getOpt Permute options argv of+>          (o,n,[]  ) -> return (o,n)+>          (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))+>      where header = "Usage: ic [OPTION...] files..."++Then the rest of the program will use the constructed list of flags+to determine it\'s behaviour.++-}++{- $example2++A different approach is to group the option values in a record of type+@Options@, and have each flag yield a function of type+@Options -> Options@ transforming this record.++>    module Opts2 where+>+>    import System.Console.GetOpt+>    import GHC.Internal.Data.Maybe ( fromMaybe )+>+>    data Options = Options+>     { optVerbose     :: Bool+>     , optShowVersion :: Bool+>     , optOutput      :: Maybe FilePath+>     , optInput       :: Maybe FilePath+>     , optLibDirs     :: [FilePath]+>     } deriving Show+>+>    defaultOptions    = Options+>     { optVerbose     = False+>     , optShowVersion = False+>     , optOutput      = Nothing+>     , optInput       = Nothing+>     , optLibDirs     = []+>     }+>+>    options :: [OptDescr (Options -> Options)]+>    options =+>     [ Option ['v']     ["verbose"]+>         (NoArg (\ opts -> opts { optVerbose = True }))+>         "chatty output on stderr"+>     , Option ['V','?'] ["version"]+>         (NoArg (\ opts -> opts { optShowVersion = True }))+>         "show version number"+>     , Option ['o']     ["output"]+>         (OptArg ((\ f opts -> opts { optOutput = Just f }) . fromMaybe "output")+>                 "FILE")+>         "output FILE"+>     , Option ['c']     []+>         (OptArg ((\ f opts -> opts { optInput = Just f }) . fromMaybe "input")+>                 "FILE")+>         "input FILE"+>     , Option ['L']     ["libdir"]+>         (ReqArg (\ d opts -> opts { optLibDirs = optLibDirs opts ++ [d] }) "DIR")+>         "library directory"+>     ]+>+>    compilerOpts :: [String] -> IO (Options, [String])+>    compilerOpts argv =+>       case getOpt Permute options argv of+>          (o,n,[]  ) -> return (foldl (flip id) defaultOptions o, n)+>          (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))+>      where header = "Usage: ic [OPTION...] files..."++Similarly, each flag could yield a monadic function transforming a record,+of type @Options -> IO Options@ (or any other monad), allowing option+processing to perform actions of the chosen monad, e.g. printing help or+version messages, checking that file arguments exist, etc.++-}+
+ src/System/Environment.hs view
@@ -0,0 +1,30 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  System.Environment+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Miscellaneous information about the system environment.+--++module System.Environment+    (+      getArgs,+      getProgName,+      executablePath,+      getExecutablePath,+      getEnv,+      lookupEnv,+      setEnv,+      unsetEnv,+      withArgs,+      withProgName,+      getEnvironment,+  ) where++import GHC.Internal.System.Environment
+ src/System/Environment/Blank.hs view
@@ -0,0 +1,48 @@+{-# LANGUAGE Safe #-}++-- |+-- Module      :  System.Environment.Blank+-- Copyright   :  (c) Habib Alamin 2017+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- A setEnv implementation that allows blank environment variables. Mimics+-- the `System.Posix.Env` module from the @unix@ package, but with support+-- for Windows too.+--+-- The matrix of platforms that:+--+--   * support @putenv("FOO")@ to unset environment variables,+--   * support @putenv("FOO=")@ to unset environment variables or set them+--     to blank values,+--   * support @unsetenv@ to unset environment variables,+--   * support @setenv@ to set environment variables,+--   * etc.+--+-- is very complicated. Some platforms don't support unsetting of environment+-- variables at all.+--++module System.Environment.Blank+    (+      module System.Environment,+      getEnv,+      getEnvDefault,+      setEnv,+      unsetEnv,+  ) where++import System.Environment+    (+      getArgs,+      getProgName,+      getExecutablePath,+      withArgs,+      withProgName,+      getEnvironment+    )++import GHC.Internal.System.Environment.Blank
+ src/System/Exit.hs view
@@ -0,0 +1,24 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  System.Exit+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Exiting the program.+--++module System.Exit+    (ExitCode(ExitSuccess, ExitFailure),+     exitWith,+     exitFailure,+     exitSuccess,+     die+     ) where++import GHC.Internal.System.Exit
+ src/System/IO.hs view
@@ -0,0 +1,219 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  System.IO+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- The standard IO API.+--++module System.IO+    (-- * Examples+     -- $stdio_examples++     -- *  The IO monad+     IO,+     fixIO,+     -- *  Files and handles+     FilePath,+     Handle,+     -- |  GHC note: a 'Handle' will be automatically closed when the garbage+     -- collector detects that it has become unreferenced by the program.+     -- However, relying on this behaviour is not generally recommended:+     -- the garbage collector is unpredictable.  If possible, use+     -- an explicit 'hClose' to close 'Handle's when they are no longer+     -- required.  GHC does not currently attempt to free up file+     -- descriptors when they have run out, it is your responsibility to+     -- ensure that this doesn't happen.++     -- **  Standard handles+     -- |  Three handles are allocated during program initialisation,+     -- and are initially open.+     stdin,+     stdout,+     stderr,+     -- *  Opening and closing files+     -- **  Opening files+     withFile,+     openFile,+     IOMode(ReadMode, WriteMode, AppendMode, ReadWriteMode),+     -- **  Closing files+     hClose,+     -- **  Special cases+     -- |  These functions are also exported by the "Prelude".+     readFile,+     readFile',+     writeFile,+     appendFile,+     -- **  File locking+     -- $locking+     -- *  Operations on handles+     -- **  Determining and changing the size of a file+     hFileSize,+     hSetFileSize,+     -- **  Detecting the end of input+     hIsEOF,+     isEOF,+     -- **  Buffering operations+     BufferMode(NoBuffering, LineBuffering, BlockBuffering),+     hSetBuffering,+     hGetBuffering,+     hFlush,+     -- **  Repositioning handles+     hGetPosn,+     hSetPosn,+     HandlePosn,+     hSeek,+     SeekMode(AbsoluteSeek, RelativeSeek, SeekFromEnd),+     hTell,+     -- **  Handle properties+     hIsOpen,+     hIsClosed,+     hIsReadable,+     hIsWritable,+     hIsSeekable,+     -- **  Terminal operations (not portable: GHC only)+     hIsTerminalDevice,+     hSetEcho,+     hGetEcho,+     -- **  Showing handle state (not portable: GHC only)+     hShow,+     -- *  Text input and output+     -- **  Text input+     hWaitForInput,+     hReady,+     hGetChar,+     hGetLine,+     hLookAhead,+     hGetContents,+     hGetContents',+     -- **  Text output+     hPutChar,+     hPutStr,+     hPutStrLn,+     hPrint,+     -- **  Special cases for standard input and output+     -- |  These functions are also exported by the "Prelude".+     interact,+     putChar,+     putStr,+     putStrLn,+     print,+     getChar,+     getLine,+     getContents,+     getContents',+     readIO,+     readLn,+     -- *  Binary input and output+     withBinaryFile,+     openBinaryFile,+     hSetBinaryMode,+     hPutBuf,+     hGetBuf,+     hGetBufSome,+     hPutBufNonBlocking,+     hGetBufNonBlocking,+     -- *  Temporary files+     openTempFile,+     openBinaryTempFile,+     openTempFileWithDefaultPermissions,+     openBinaryTempFileWithDefaultPermissions,+     -- *  Unicode encoding\/decoding+     -- |  A text-mode 'Handle' has an associated 'TextEncoding', which+     -- is used to decode bytes into Unicode characters when reading,+     -- and encode Unicode characters into bytes when writing.+     --+     -- The default 'TextEncoding' is the same as the default encoding+     -- on your system, which is also available as 'localeEncoding'.+     -- (GHC note: on Windows, we currently do not support double-byte+     -- encodings; if the console\'s code page is unsupported, then+     -- 'localeEncoding' will be 'latin1'.)+     --+     -- Encoding and decoding errors are always detected and reported,+     -- except during lazy I/O ('hGetContents', 'getContents', and+     -- 'readFile'), where a decoding error merely results in+     -- termination of the character stream, as with other I/O errors.+     hSetEncoding,+     hGetEncoding,+     -- **  Unicode encodings+     TextEncoding,+     latin1,+     utf8,+     utf8_bom,+     utf16,+     utf16le,+     utf16be,+     utf32,+     utf32le,+     utf32be,+     localeEncoding,+     char8,+     mkTextEncoding,+     -- *  Newline conversion+     -- | In Haskell, a newline is always represented by the character+     -- @\'\\n\'@.  However, in files and external character streams, a+     -- newline may be represented by another character sequence, such+     -- as @\'\\r\\n\'@.+     --+     -- A text-mode 'Handle' has an associated 'NewlineMode' that+     -- specifies how to translate newline characters.  The+     -- 'NewlineMode' specifies the input and output translation+     -- separately, so that for instance you can translate @\'\\r\\n\'@+     -- to @\'\\n\'@ on input, but leave newlines as @\'\\n\'@ on output.+     --+     -- The default 'NewlineMode' for a 'Handle' is+     -- 'nativeNewlineMode', which does no translation on Unix systems,+     -- but translates @\'\\r\\n\'@ to @\'\\n\'@ and back on Windows.+     --+     -- Binary-mode 'Handle's do no newline translation at all.++     hSetNewlineMode,+     Newline(..),+     nativeNewline,+     NewlineMode(..),+     noNewlineTranslation,+     universalNewlineMode,+     nativeNewlineMode+     ) where++import GHC.Internal.System.IO++-- $locking+-- Implementations should enforce as far as possible, at least locally to the+-- Haskell process, multiple-reader single-writer locking on files.+-- That is, /there may either be many handles on the same file which manage input, or just one handle on the file which manages output/.  If any+-- open or semi-closed handle is managing a file for output, no new+-- handle can be allocated for that file.  If any open or semi-closed+-- handle is managing a file for input, new handles can only be allocated+-- if they do not manage output.  Whether two files are the same is+-- implementation-dependent, but they should normally be the same if they+-- have the same absolute path name and neither has been renamed, for+-- example.+--+-- /Warning/: the 'readFile' operation holds a semi-closed handle on+-- the file until the entire contents of the file have been consumed.+-- It follows that an attempt to write to a file (using 'writeFile', for+-- example) that was earlier opened by 'readFile' will usually result in+-- failure with 'GHC.Internal.System.IO.Error.isAlreadyInUseError'.++-- $stdio_examples+-- Note: Some of the examples in this module do not work "as is" in ghci.+-- This is because using 'stdin' in combination with lazy IO+-- does not work well in interactive mode.+--+-- Lines starting with @>@ indicate 'stdin' and @^D@ signales EOF.+--+-- ==== __Example__+--+-- ghci> foo+-- > input+-- output+-- > input^D+-- output
+ src/System/IO/Error.hs view
@@ -0,0 +1,71 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  System.IO.Error+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Standard IO Errors.+--++module System.IO.Error+    (-- *  I\/O errors+     IOError,+     userError,+     mkIOError,+     annotateIOError,+     -- **  Classifying I\/O errors+     isAlreadyExistsError,+     isDoesNotExistError,+     isAlreadyInUseError,+     isFullError,+     isEOFError,+     isIllegalOperation,+     isPermissionError,+     isUserError,+     isResourceVanishedError,+     -- **  Attributes of I\/O errors+     ioeGetErrorType,+     ioeGetLocation,+     ioeGetErrorString,+     ioeGetHandle,+     ioeGetFileName,+     ioeSetErrorType,+     ioeSetErrorString,+     ioeSetLocation,+     ioeSetHandle,+     ioeSetFileName,+     -- *  Types of I\/O error+     IOErrorType,+     alreadyExistsErrorType,+     doesNotExistErrorType,+     alreadyInUseErrorType,+     fullErrorType,+     eofErrorType,+     illegalOperationErrorType,+     permissionErrorType,+     userErrorType,+     resourceVanishedErrorType,+     -- **  'IOErrorType' predicates+     isAlreadyExistsErrorType,+     isDoesNotExistErrorType,+     isAlreadyInUseErrorType,+     isFullErrorType,+     isEOFErrorType,+     isIllegalOperationErrorType,+     isPermissionErrorType,+     isUserErrorType,+     isResourceVanishedErrorType,+     -- *  Throwing and catching I\/O errors+     ioError,+     catchIOError,+     tryIOError,+     modifyIOError+     ) where++import GHC.Internal.System.IO.Error
+ src/System/IO/Unsafe.hs view
@@ -0,0 +1,50 @@+{-# LANGUAGE Unsafe #-}+{-# LANGUAGE NoImplicitPrelude #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  System.IO.Unsafe+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- \"Unsafe\" IO operations.+--+-----------------------------------------------------------------------------++module System.IO.Unsafe (+   -- * Unsafe 'System.IO.IO' operations+   unsafePerformIO,+   unsafeDupablePerformIO,+   unsafeInterleaveIO,+   unsafeFixIO,+  ) where++import GHC.Internal.Base+import GHC.Internal.IO+import GHC.Internal.IORef+import GHC.Internal.Exception+import GHC.Internal.Control.Exception++-- | A slightly faster version of `GHC.Internal.System.IO.fixIO` that may not be+-- safe to use with multiple threads.  The unsafety arises when used+-- like this:+--+-- >  unsafeFixIO $ \r -> do+-- >     forkIO (print r)+-- >     return (...)+--+-- In this case, the child thread will receive a @NonTermination@+-- exception instead of waiting for the value of @r@ to be computed.+--+-- @since 4.5.0.0+unsafeFixIO :: (a -> IO a) -> IO a+unsafeFixIO k = do+  ref <- newIORef (throw NonTermination)+  ans <- unsafeDupableInterleaveIO (readIORef ref)+  result <- k ans+  writeIORef ref result+  return result
+ src/System/Info.hs view
@@ -0,0 +1,113 @@+{-# LANGUAGE CPP  #-}+{-# LANGUAGE Safe #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  System.Info+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  portable+--+-- Information about the characteristics of the host+-- system lucky enough to run your program.+--+-- For a comprehensive listing of supported platforms, please refer to+-- https://gitlab.haskell.org/ghc/ghc/-/wikis/platforms+-----------------------------------------------------------------------------++module System.Info+  ( os+  , arch+  , compilerName+  , compilerVersion+  , fullCompilerVersion+  ) where++import GHC.Internal.Data.Version (Version (..))+import Prelude++-- | The version of 'compilerName' with which the program was compiled+-- or is being interpreted.+--+-- ==== __Example__+-- > ghci> compilerVersion+-- > Version {versionBranch = [8,8], versionTags = []}+compilerVersion :: Version+compilerVersion = Version [major, minor] []+  where (major, minor) = compilerVersionRaw `divMod` 100++-- | The full version of 'compilerName' with which the program was compiled+-- or is being interpreted. It includes the major, minor, revision and an additional+-- identifier, generally in the form "<year><month><day>".+fullCompilerVersion :: Version+fullCompilerVersion = Version version []+  where+    version :: [Int]+    version = fmap read $ splitVersion __GLASGOW_HASKELL_FULL_VERSION__++splitVersion :: String -> [String]+splitVersion s =+  case dropWhile (== '.') s of+    "" -> []+    s' -> let (w, s'') = break (== '.') s'+           in w : splitVersion s''++#include "ghcplatform.h"++-- | The operating system on which the program is running.+-- Common values include:+--+--     * "darwin" — macOS+--     * "freebsd"+--     * "linux"+--     * "linux-android"+--     * "mingw32" — Windows+--     * "netbsd"+--     * "openbsd"+os :: String+os = HOST_OS++-- | The machine architecture on which the program is running.+-- Common values include:+--+--    * "aarch64"+--    * "alpha"+--    * "arm"+--    * "hppa"+--    * "hppa1_1"+--    * "i386"+--    * "ia64"+--    * "m68k"+--    * "mips"+--    * "mipseb"+--    * "mipsel"+--    * "nios2"+--    * "powerpc"+--    * "powerpc64"+--    * "powerpc64le"+--    * "riscv32"+--    * "riscv64"+--    * "loongarch32"+--    * "loongarch64"+--    * "rs6000"+--    * "s390"+--    * "s390x"+--    * "sh4"+--    * "sparc"+--    * "sparc64"+--    * "vax"+--    * "x86_64"+arch :: String+arch = HOST_ARCH++-- | The Haskell implementation with which the program was compiled+-- or is being interpreted.+-- On the GHC platform, the value is "ghc".+compilerName :: String+compilerName = "ghc"++compilerVersionRaw :: Int+compilerVersionRaw = __GLASGOW_HASKELL__
+ src/System/Mem.hs view
@@ -0,0 +1,29 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  System.Mem+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Memory-related system things.+--++module System.Mem+    (-- *  Garbage collection+     performGC,+     performMajorGC,+     performBlockingMajorGC,+     performMinorGC,+     -- *  Allocation counter and limits+     setAllocationCounter,+     getAllocationCounter,+     enableAllocationLimit,+     disableAllocationLimit+     ) where++import GHC.Internal.System.Mem
+ src/System/Mem/StableName.hs view
@@ -0,0 +1,41 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  System.Mem.StableName+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable+--+-- Stable names are a way of performing fast ( \(\mathcal{O}(1)\) ),+-- not-quite-exact comparison between objects.+--+-- Stable names solve the following problem: suppose you want to build+-- a hash table with Haskell objects as keys, but you want to use+-- pointer equality for comparison; maybe because the keys are large+-- and hashing would be slow, or perhaps because the keys are infinite+-- in size.  We can\'t build a hash table using the address of the+-- object as the key, because objects get moved around by the garbage+-- collector, meaning a re-hash would be necessary after every garbage+-- collection.+--+-- See [Stretching the storage manager: weak pointers and stable names in+-- Haskell](https://www.microsoft.com/en-us/research/publication/stretching-the-storage-manager-weak-pointers-and-stable-names-in-haskell/)+-- by Simon Peyton Jones, Simon Marlow and Conal Elliott for detailed discussion+-- of stable names. An implementation of a memo table with stable names+-- can be found in [@stable-memo@](https://hackage.haskell.org/package/stable-memo)+-- package.+--++module System.Mem.StableName+    (-- *  Stable Names+     StableName,+     makeStableName,+     hashStableName,+     eqStableName+     ) where++import GHC.Internal.System.Mem.StableName
+ src/System/Mem/Weak.hs view
@@ -0,0 +1,179 @@+{-# LANGUAGE Trustworthy #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  System.Mem.Weak+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable+--+-- In general terms, a weak pointer is a reference to an object that is+-- not followed by the garbage collector - that is, the existence of a+-- weak pointer to an object has no effect on the lifetime of that+-- object.  A weak pointer can be de-referenced to find out+-- whether the object it refers to is still alive or not, and if so+-- to return the object itself.+--+-- Weak pointers are particularly useful for caches and memo tables.+-- To build a memo table, you build a data structure+-- mapping from the function argument (the key) to its result (the+-- value).  When you apply the function to a new argument you first+-- check whether the key\/value pair is already in the memo table.+-- The key point is that the memo table itself should not keep the+-- key and value alive.  So the table should contain a weak pointer+-- to the key, not an ordinary pointer.  The pointer to the value must+-- not be weak, because the only reference to the value might indeed be+-- from the memo table.+--+-- So it looks as if the memo table will keep all its values+-- alive for ever.  One way to solve this is to purge the table+-- occasionally, by deleting entries whose keys have died.+--+-- The weak pointers in this module+-- support another approach, called /finalization/.+-- When the key referred to by a weak pointer dies, the storage manager+-- arranges to run a programmer-specified finalizer.  In the case of memo+-- tables, for example, the finalizer could remove the key\/value pair+-- from the memo table.+--+-- Another difficulty with the memo table is that the value of a+-- key\/value pair might itself contain a pointer to the key.+-- So the memo table keeps the value alive, which keeps the key alive,+-- even though there may be no other references to the key so both should+-- die.  The weak pointers in this module provide a slight+-- generalisation of the basic weak-pointer idea, in which each+-- weak pointer actually contains both a key and a value.+--+-- See [Stretching the storage manager: weak pointers and stable names in+-- Haskell](https://www.microsoft.com/en-us/research/publication/stretching-the-storage-manager-weak-pointers-and-stable-names-in-haskell/)+-- by Simon Peyton Jones, Simon Marlow and Conal Elliott for detailed discussion+-- of weak pointers. An implementation of a memo table with weak pointers+-- can be found in [@stable-memo@](https://hackage.haskell.org/package/stable-memo)+-- package.+--+-----------------------------------------------------------------------------++module System.Mem.Weak (+        -- * The @Weak@ type+        Weak,                   -- abstract++        -- * The general interface+        mkWeak,+        deRefWeak,+        finalize,++        -- * Specialised versions+        mkWeakPtr,+        addFinalizer,+        mkWeakPair,+        -- replaceFinaliser++        -- * Handling exceptions+        -- | When an exception is thrown by a finalizer called by the+        -- garbage collector, GHC calls a global handler which can be set with+        -- 'setFinalizerExceptionHandler'. Note that any exceptions thrown by+        -- this handler will be ignored.+        setFinalizerExceptionHandler,+        getFinalizerExceptionHandler,+        printToHandleFinalizerExceptionHandler,++        -- * A precise semantics++        -- $precise++        -- * Implementation notes++        -- $notes+   ) where++import Prelude+import GHC.Internal.Weak++-- | A specialised version of 'mkWeak', where the key and the value are+-- the same object:+--+-- > mkWeakPtr key finalizer = mkWeak key key finalizer+--+mkWeakPtr :: k -> Maybe (IO ()) -> IO (Weak k)+mkWeakPtr key finalizer = mkWeak key key finalizer++{-|+  A specialised version of 'mkWeakPtr', where the 'Weak' object+  returned is simply thrown away (however the finalizer will be+  remembered by the garbage collector, and will still be run+  when the key becomes unreachable).++  Note: adding a finalizer to a 'Foreign.ForeignPtr.ForeignPtr' using+  'addFinalizer' won't work; use the specialised version+  'GHC.Internal.Foreign.ForeignPtr.addForeignPtrFinalizer' instead.  For discussion+  see the 'Weak' type.+.+-}+addFinalizer :: key -> IO () -> IO ()+addFinalizer key finalizer = do+   _ <- mkWeakPtr key (Just finalizer) -- throw it away+   return ()++-- | A specialised version of 'mkWeak' where the value is actually a pair+-- of the key and value passed to 'mkWeakPair':+--+-- > mkWeakPair key val finalizer = mkWeak key (key,val) finalizer+--+-- The advantage of this is that the key can be retrieved by 'deRefWeak'+-- in addition to the value.+mkWeakPair :: k -> v -> Maybe (IO ()) -> IO (Weak (k,v))+mkWeakPair key val finalizer = mkWeak key (key,val) finalizer+++{- $precise++The above informal specification is fine for simple situations, but+matters can get complicated.  In particular, it needs to be clear+exactly when a key dies, so that any weak pointers that refer to it+can be finalized.  Suppose, for example, the value of one weak pointer+refers to the key of another...does that keep the key alive?++The behaviour is simply this:++ *  If a weak pointer (object) refers to an /unreachable/+    key, it may be finalized.++ *  Finalization means (a) arrange that subsequent calls+    to 'deRefWeak' return 'Nothing'; and (b) run the finalizer.++This behaviour depends on what it means for a key to be reachable.+Informally, something is reachable if it can be reached by following+ordinary pointers from the root set, but not following weak pointers.+We define reachability more precisely as follows.++A heap object is /reachable/ if:++ * It is a member of the /root set/.++ * It is directly pointed to by a reachable object, other than+   a weak pointer object.++ * It is a weak pointer object whose key is reachable.++ * It is the value or finalizer of a weak pointer object whose key is reachable.+-}++{- $notes++A finalizer is not always called after its weak pointer\'s object becomes+unreachable. If the object becomes unreachable right before the program exits,+then GC may not be performed. Finalizers run during GC, so finalizers associated+with the object do not run if GC does not happen.++Other than the above caveat, users can always expect that a finalizer will be+run after its weak pointer\'s object becomes unreachable.++If a finalizer throws an exception, the exception is silently caught without+notice. See the commit of issue+<https://gitlab.haskell.org/ghc/ghc/-/issues/13167 13167> for details. Writing a+finalizer that throws exceptions is discouraged.++-}
+ src/System/Posix/Internals.hs view
@@ -0,0 +1,30 @@+{-# LANGUAGE Safe #-}+{-# OPTIONS_HADDOCK not-home #-}++-- |+-- Module      :  System.Posix.Internals+-- Copyright   :  (c) The University of Glasgow, 1992-2002+-- License     :  see libraries/base/LICENSE+--+-- Maintainer  :  ghc-devs@haskell.org+-- Stability   :  internal+-- Portability :  non-portable (requires POSIX)+--+-- POSIX support layer for the standard libraries.+--+-- /The API of this module is unstable and not meant to be consumed by the general public./+-- If you absolutely must depend on it, make sure to use a tight upper+-- bound, e.g., @base < 4.X@ rather than @base < 5@, because the interface can+-- change rapidly without much warning.+--+-- This module is built on *every* platform, including Win32.+--+-- Non-POSIX compliant in order to support the following features:+--  * S_ISSOCK (no sockets in POSIX)+--++module System.Posix.Internals+  ( module GHC.Internal.System.Posix.Internals -- TODO: deprecate+  ) where++import GHC.Internal.System.Posix.Internals
+ src/System/Posix/Types.hs view
@@ -0,0 +1,25 @@+-- |+--+-- Module      :  System.Posix.Types+-- Copyright   :  (c) The University of Glasgow 2002+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  non-portable (requires POSIX)+--+-- POSIX data types: Haskell equivalents of the types defined by the+-- @\<sys\/types.h>@ C header on a POSIX system.+--++module System.Posix.Types+    (-- *  POSIX data types+     -- **  Platform differences+     -- |  This module contains platform specific information about types.+     -- __/As such the types presented on this page reflect the platform+     -- on which the documentation was generated and may not coincide with+     -- the types on your platform./__+     module GHC.Internal.System.Posix.Types+     ) where++import GHC.Internal.System.Posix.Types
+ src/System/Timeout.hs view
@@ -0,0 +1,148 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE Trustworthy #-}++-------------------------------------------------------------------------------+-- |+-- Module      :  System.Timeout+-- Copyright   :  (c) The University of Glasgow 2007+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable+--+-- Attach a timeout event to arbitrary 'IO' computations.+--+-------------------------------------------------------------------------------+-- TODO: Inspect is still suitable.+module System.Timeout ( Timeout, timeout ) where++#if !defined(mingw32_HOST_OS) && !defined(javascript_HOST_ARCH)+import GHC.Internal.Control.Monad+import GHC.Internal.Event           (getSystemTimerManager,+                            registerTimeout, unregisterTimeout)+#endif++import Control.Concurrent+import GHC.Internal.Control.Exception   (Exception(..), handleJust, bracket,+                            uninterruptibleMask_,+                            asyncExceptionToException,+                            asyncExceptionFromException)+import GHC.Internal.Data.Unique         (Unique, newUnique)+import GHC.Conc (labelThread)+import Prelude++-- $setup+-- >>> import Prelude+-- >>> import Control.Concurrent (threadDelay)++-- An internal type that is thrown as a dynamic exception to+-- interrupt the running IO computation when the timeout has+-- expired.++-- | An exception thrown to a thread by 'timeout' to interrupt a timed-out+-- computation.+--+-- @since 4.0+newtype Timeout = Timeout Unique deriving Eq++-- | @since 4.0+instance Show Timeout where+    show _ = "<<timeout>>"++-- Timeout is a child of SomeAsyncException+-- | @since 4.7.0.0+instance Exception Timeout where+  toException = asyncExceptionToException+  fromException = asyncExceptionFromException++-- |Wrap an 'IO' computation to time out and return @Nothing@ in case no result+-- is available within @n@ microseconds (@1\/10^6@ seconds). In case a result+-- is available before the timeout expires, @Just a@ is returned. A negative+-- timeout interval means \"wait indefinitely\". When specifying long timeouts,+-- be careful not to exceed @maxBound :: Int@, which on 32-bit machines is only+-- 2147483647 μs, less than 36 minutes.+-- Consider using @Control.Concurrent.Timeout.timeout@ from @unbounded-delays@ package.+--+-- >>> timeout 1000000 (threadDelay 1000 *> pure "finished on time")+-- Just "finished on time"+--+-- >>> timeout 10000 (threadDelay 100000 *> pure "finished on time")+-- Nothing+--+-- The design of this combinator was guided by the objective that @timeout n f@+-- should behave exactly the same as @f@ as long as @f@ doesn't time out. This+-- means that @f@ has the same 'myThreadId' it would have without the timeout+-- wrapper. Any exceptions @f@ might throw cancel the timeout and propagate+-- further up. It also possible for @f@ to receive exceptions thrown to it by+-- another thread.+--+-- A tricky implementation detail is the question of how to abort an @IO@+-- computation. This combinator relies on asynchronous exceptions internally+-- (namely throwing the computation the 'Timeout' exception).  The technique+-- works very well for computations executing inside of the Haskell runtime+-- system, but it doesn't work at all for non-Haskell code.  Foreign function+-- calls, for example, cannot be timed out with this combinator simply because+-- an arbitrary C function cannot receive asynchronous exceptions. When+-- @timeout@ is used to wrap an FFI call that blocks, no timeout event can be+-- delivered until the FFI call returns, which pretty much negates the purpose+-- of the combinator. In practice, however, this limitation is less severe than+-- it may sound. Standard I\/O functions like 'GHC.Internal.System.IO.hGetBuf',+-- 'GHC.Internal.System.IO.hPutBuf', Network.Socket.accept, or 'GHC.Internal.System.IO.hWaitForInput'+-- appear to be blocking, but they really don't because the runtime system uses+-- scheduling mechanisms like @select(2)@ to perform asynchronous I\/O, so it+-- is possible to interrupt standard socket I\/O or file I\/O using this+-- combinator.+---+-- Note that 'timeout' cancels the computation by throwing it the 'Timeout'+-- exception. Consequently blanket exception handlers (e.g. catching+-- 'SomeException') within the computation will break the timeout behavior.+timeout :: Int -> IO a -> IO (Maybe a)+timeout n f+    | n <  0    = fmap Just f+    | n == 0    = return Nothing+#if !defined(mingw32_HOST_OS) && !defined(javascript_HOST_ARCH)+    | rtsSupportsBoundThreads = do+        -- In the threaded RTS, we use the Timer Manager to delay the+        -- (fairly expensive) 'forkIO' call until the timeout has expired.+        --+        -- An additional thread is required for the actual delivery of+        -- the Timeout exception because killThread (or another throwTo)+        -- is the only way to reliably interrupt a throwTo in flight.+        pid <- myThreadId+        ex  <- fmap Timeout newUnique+        tm  <- getSystemTimerManager+        -- 'lock' synchronizes the timeout handler and the main thread:+        --  * the main thread can disable the handler by writing to 'lock';+        --  * the handler communicates the spawned thread's id through 'lock'.+        -- These two cases are mutually exclusive.+        lock <- newEmptyMVar+        let handleTimeout = do+                v <- isEmptyMVar lock+                when v $ void $ forkIOWithUnmask $ \unmask -> unmask $ do+                    tid <- myThreadId+                    labelThread tid "timeout worker"+                    v2 <- tryPutMVar lock tid+                    when v2 $ throwTo pid ex+            cleanupTimeout key = uninterruptibleMask_ $ do+                v <- tryPutMVar lock undefined+                if v then unregisterTimeout tm key+                     else takeMVar lock >>= killThread+        handleJust (\e -> if e == ex then Just () else Nothing)+                   (\_ -> return Nothing)+                   (bracket (registerTimeout tm n handleTimeout)+                            cleanupTimeout+                            (\_ -> fmap Just f))+#endif+    | otherwise = do+        pid <- myThreadId+        ex  <- fmap Timeout newUnique+        handleJust (\e -> if e == ex then Just () else Nothing)+                   (\_ -> return Nothing)+                   (bracket (forkIOWithUnmask $ \unmask -> do+                                 tid <- myThreadId+                                 labelThread tid "timeout worker"+                                 unmask $ threadDelay n >> throwTo pid ex)+                            (uninterruptibleMask_ . killThread)+                            (\_ -> fmap Just f))+        -- #7719 explains why we need uninterruptibleMask_ above.
+ src/Text/ParserCombinators/ReadP.hs view
@@ -0,0 +1,63 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Text.ParserCombinators.ReadP+-- Copyright   :  (c) The University of Glasgow 2002+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  non-portable (local universal quantification)+--+-- This is a module of parser combinators, originally written by Koen Claessen.+-- It parses all alternatives in parallel, so it never keeps hold of+-- the beginning of the input string, a common source of space leaks with+-- other parsers.  The @('+++')@ choice combinator is genuinely commutative;+-- it makes no difference which branch is \"shorter\".++module Text.ParserCombinators.ReadP+    (-- *  The 'ReadP' type+     ReadP,+     -- *  Primitive operations+     get,+     look,+     (+++),+     (<++),+     gather,+     -- *  Other operations+     pfail,+     eof,+     satisfy,+     char,+     string,+     munch,+     munch1,+     skipSpaces,+     choice,+     count,+     between,+     option,+     optional,+     many,+     many1,+     skipMany,+     skipMany1,+     sepBy,+     sepBy1,+     endBy,+     endBy1,+     chainr,+     chainl,+     chainl1,+     chainr1,+     manyTill,+     -- *  Running a parser+     ReadS,+     readP_to_S,+     readS_to_P,+     -- *  Properties+     -- $properties+     ) where++import GHC.Internal.Text.ParserCombinators.ReadP
+ src/Text/ParserCombinators/ReadPrec.hs view
@@ -0,0 +1,40 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Text.ParserCombinators.ReadPrec+-- Copyright   :  (c) The University of Glasgow 2002+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  non-portable (uses Text.ParserCombinators.ReadP)+--+-- This module defines parser combinators for precedence parsing.++module Text.ParserCombinators.ReadPrec+    (ReadPrec,+     -- *  Precedences+     Prec,+     minPrec,+     -- *  Precedence operations+     lift,+     prec,+     step,+     reset,+     -- *  Other operations+     -- |  All are based directly on their similarly-named 'ReadP' counterparts.+     get,+     look,+     (+++),+     (<++),+     pfail,+     choice,+     -- *  Converters+     readPrec_to_P,+     readP_to_Prec,+     readPrec_to_S,+     readS_to_Prec+     ) where++import GHC.Internal.Text.ParserCombinators.ReadPrec
+ src/Text/Printf.hs view
@@ -0,0 +1,919 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE TypeOperators #-}+{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}++-----------------------------------------------------------------------------+-- |+-- Module      :  Text.Printf+-- Copyright   :  (c) Lennart Augustsson and Bart Massey 2013+-- License     :  BSD-style (see the file LICENSE in this distribution)+--+-- Maintainer  :  Bart Massey <bart@cs.pdx.edu>+-- Stability   :  provisional+-- Portability :  portable+--+-- A C @printf(3)@-like formatter. This version has been+-- extended by Bart Massey as per the recommendations of+-- John Meacham and Simon Marlow+-- <http://comments.gmane.org/gmane.comp.lang.haskell.libraries/4726>+-- to support extensible formatting for new datatypes.  It+-- has also been extended to support almost all C+-- @printf(3)@ syntax.+-----------------------------------------------------------------------------++module Text.Printf(+-- * Printing Functions+   printf, hPrintf,+-- * Extending To New Types+--+-- | This 'printf' can be extended to format types+-- other than those provided for by default. This+-- is done by instantiating 'PrintfArg' and providing+-- a 'formatArg' for the type. It is possible to+-- provide a 'parseFormat' to process type-specific+-- modifiers, but the default instance is usually+-- the best choice.+--+-- For example:+--+-- > instance PrintfArg () where+-- >   formatArg x fmt | fmtChar (vFmt 'U' fmt) == 'U' =+-- >     formatString "()" (fmt { fmtChar = 's', fmtPrecision = Nothing })+-- >   formatArg _ fmt = errorBadFormat $ fmtChar fmt+-- >+-- > main :: IO ()+-- > main = printf "[%-3.1U]\n" ()+--+-- prints \"@[() ]@\". Note the use of 'formatString' to+-- take care of field formatting specifications in a convenient+-- way.+   PrintfArg(..),+   FieldFormatter,+   FieldFormat(..),+   FormatAdjustment(..), FormatSign(..),+   vFmt,+-- ** Handling Type-specific Modifiers+--+-- | In the unlikely case that modifier characters of+-- some kind are desirable for a user-provided type,+-- a 'ModifierParser' can be provided to process these+-- characters. The resulting modifiers will appear in+-- the 'FieldFormat' for use by the type-specific formatter.+   ModifierParser, FormatParse(..),+-- ** Standard Formatters+--+-- | These formatters for standard types are provided for+-- convenience in writing new type-specific formatters:+-- a common pattern is to throw to 'formatString' or+-- 'formatInteger' to do most of the format handling for+-- a new type.+   formatString, formatChar, formatInt,+   formatInteger, formatRealFloat,+-- ** Raising Errors+--+-- | These functions are used internally to raise various+-- errors, and are exported for use by new type-specific+-- formatters.+  errorBadFormat, errorShortFormat, errorMissingArgument,+  errorBadArgument,+  perror,+-- * Implementation Internals+-- | These types are needed for implementing processing+-- variable numbers of arguments to 'printf' and 'hPrintf'.+-- Their implementation is intentionally not visible from+-- this module. If you attempt to pass an argument of a type+-- which is not an instance of the appropriate class to+-- 'printf' or 'hPrintf', then the compiler will report it+-- as a missing instance of 'PrintfArg'.  (All 'PrintfArg'+-- instances are 'PrintfType' instances.)+  PrintfType, HPrintfType,+-- | This class is needed as a Haskell98 compatibility+-- workaround for the lack of FlexibleInstances.+  IsChar(..)+) where++import Prelude+import Data.Char+import GHC.Internal.Int+import GHC.Internal.Data.List (stripPrefix)+import GHC.Internal.Word+import GHC.Internal.Numeric+import GHC.Internal.Numeric.Natural+import GHC.Internal.System.IO++-- $setup+-- >>> import Prelude++-------------------++-- | Format a variable number of arguments with the C-style formatting string.+--+-- >>> printf "%s, %d, %.4f" "hello" 123 pi+-- hello, 123, 3.1416+--+-- The return value is either 'String' or @('IO' a)@ (which+-- should be @('IO' ())@, but Haskell's type system+-- makes this hard).+--+-- The format string consists of ordinary characters and+-- /conversion specifications/, which specify how to format+-- one of the arguments to 'printf' in the output string. A+-- format specification is introduced by the @%@ character;+-- this character can be self-escaped into the format string+-- using @%%@. A format specification ends with a+-- /format character/ that provides the primary information about+-- how to format the value. The rest of the conversion+-- specification is optional.  In order, one may have flag+-- characters, a width specifier, a precision specifier, and+-- type-specific modifier characters.+--+-- Unlike C @printf(3)@, the formatting of this 'printf'+-- is driven by the argument type; formatting is type specific. The+-- types formatted by 'printf' \"out of the box\" are:+--+--   * 'Integral' types, including 'Char'+--+--   * 'String'+--+--   * 'RealFloat' types+--+-- 'printf' is also extensible to support other types: see below.+--+-- A conversion specification begins with the+-- character @%@, followed by zero or more of the following flags:+--+-- > -      left adjust (default is right adjust)+-- > +      always use a sign (+ or -) for signed conversions+-- > space  leading space for positive numbers in signed conversions+-- > 0      pad with zeros rather than spaces+-- > #      use an \"alternate form\": see below+--+-- When both flags are given, @-@ overrides @0@ and @+@ overrides space.+-- A negative width specifier in a @*@ conversion is treated as+-- positive but implies the left adjust flag.+--+-- The \"alternate form\" for unsigned radix conversions is+-- as in C @printf(3)@:+--+-- > %o           prefix with a leading 0 if needed+-- > %x           prefix with a leading 0x if nonzero+-- > %X           prefix with a leading 0X if nonzero+-- > %b           prefix with a leading 0b if nonzero+-- > %[eEfFgG]    ensure that the number contains a decimal point+--+-- Any flags are followed optionally by a field width:+--+-- > num    field width+-- > *      as num, but taken from argument list+--+-- The field width is a minimum, not a maximum: it will be+-- expanded as needed to avoid mutilating a value.+--+-- Any field width is followed optionally by a precision:+--+-- > .num   precision+-- > .      same as .0+-- > .*     as num, but taken from argument list+--+-- Negative precision is taken as 0. The meaning of the+-- precision depends on the conversion type.+--+-- > Integral    minimum number of digits to show+-- > RealFloat   number of digits after the decimal point+-- > String      maximum number of characters+--+-- The precision for Integral types is accomplished by zero-padding.+-- If both precision and zero-pad are given for an Integral field,+-- the zero-pad is ignored.+--+-- Any precision is followed optionally for Integral types+-- by a width modifier; the only use of this modifier being+-- to set the implicit size of the operand for conversion of+-- a negative operand to unsigned:+--+-- > hh     Int8+-- > h      Int16+-- > l      Int32+-- > ll     Int64+-- > L      Int64+--+-- The specification ends with a format character:+--+-- > c      character               Integral+-- > d      decimal                 Integral+-- > o      octal                   Integral+-- > x      hexadecimal             Integral+-- > X      hexadecimal             Integral+-- > b      binary                  Integral+-- > u      unsigned decimal        Integral+-- > f      floating point          RealFloat+-- > F      floating point          RealFloat+-- > g      general format float    RealFloat+-- > G      general format float    RealFloat+-- > e      exponent format float   RealFloat+-- > E      exponent format float   RealFloat+-- > s      string                  String+-- > v      default format          any type+--+-- The \"%v\" specifier is provided for all built-in types,+-- and should be provided for user-defined type formatters+-- as well. It picks a \"best\" representation for the given+-- type. For the built-in types the \"%v\" specifier is+-- converted as follows:+--+-- > c      Char+-- > u      other unsigned Integral+-- > d      other signed Integral+-- > g      RealFloat+-- > s      String+--+-- Mismatch between the argument types and the format+-- string, as well as any other syntactic or semantic errors+-- in the format string, will cause an exception to be+-- thrown at runtime.+--+-- Note that the formatting for 'RealFloat' types is+-- currently a bit different from that of C @printf(3)@,+-- conforming instead to 'GHC.Internal.Numeric.showEFloat',+-- 'GHC.Internal.Numeric.showFFloat' and 'GHC.Internal.Numeric.showGFloat' (and their+-- alternate versions 'GHC.Internal.Numeric.showFFloatAlt' and+-- 'GHC.Internal.Numeric.showGFloatAlt'). This is hard to fix: the fixed+-- versions would format in a backward-incompatible way.+-- In any case the Haskell behavior is generally more+-- sensible than the C behavior.  A brief summary of some+-- key differences:+--+-- * Haskell 'printf' never uses the default \"6-digit\" precision+--   used by C printf.+--+-- * Haskell 'printf' treats the \"precision\" specifier as+--   indicating the number of digits after the decimal point.+--+-- * Haskell 'printf' prints the exponent of e-format+--   numbers without a gratuitous plus sign, and with the+--   minimum possible number of digits.+--+-- * Haskell 'printf' will place a zero after a decimal point when+--   possible.+printf :: (PrintfType r) => String -> r+printf fmts = spr fmts []++-- | Similar to 'printf', except that output is via the specified+-- 'Handle'.  The return type is restricted to @('IO' a)@.+hPrintf :: (HPrintfType r) => Handle -> String -> r+hPrintf hdl fmts = hspr hdl fmts []++-- |The 'PrintfType' class provides the variable argument magic for+-- 'printf'.  Its implementation is intentionally not visible from+-- this module. If you attempt to pass an argument of a type which+-- is not an instance of this class to 'printf' or 'hPrintf', then+-- the compiler will report it as a missing instance of 'PrintfArg'.+class PrintfType t where+    spr :: String -> [UPrintf] -> t++-- | The 'HPrintfType' class provides the variable argument magic for+-- 'hPrintf'.  Its implementation is intentionally not visible from+-- this module.+class HPrintfType t where+    hspr :: Handle -> String -> [UPrintf] -> t++{- not allowed in Haskell 2010+instance PrintfType String where+    spr fmt args = uprintf fmt (reverse args)+-}+-- | @since 2.01+instance (IsChar c) => PrintfType [c] where+    spr fmts args = map fromChar (uprintf fmts (reverse args))++-- Note that this should really be (IO ()), but GHC's+-- type system won't readily let us say that without+-- bringing the GADTs. So we go conditional for these defs.++-- | @since 4.7.0.0+instance (a ~ ()) => PrintfType (IO a) where+    spr fmts args =+        putStr $ map fromChar $ uprintf fmts $ reverse args++-- | @since 4.7.0.0+instance (a ~ ()) => HPrintfType (IO a) where+    hspr hdl fmts args =+        hPutStr hdl (uprintf fmts (reverse args))++-- | @since 2.01+instance (PrintfArg a, PrintfType r) => PrintfType (a -> r) where+    spr fmts args = \ a -> spr fmts+                             ((parseFormat a, formatArg a) : args)++-- | @since 2.01+instance (PrintfArg a, HPrintfType r) => HPrintfType (a -> r) where+    hspr hdl fmts args = \ a -> hspr hdl fmts+                                  ((parseFormat a, formatArg a) : args)++-- | Typeclass of 'printf'-formattable values. The 'formatArg' method+-- takes a value and a field format descriptor and either fails due+-- to a bad descriptor or produces a 'ShowS' as the result. The+-- default 'parseFormat' expects no modifiers: this is the normal+-- case. Minimal instance: 'formatArg'.+class PrintfArg a where+    -- | @since 4.7.0.0+    formatArg :: a -> FieldFormatter+    -- | @since 4.7.0.0+    parseFormat :: a -> ModifierParser+    parseFormat _ (c : cs) = FormatParse "" c cs+    parseFormat _ "" = errorShortFormat++-- | @since 2.01+instance PrintfArg Char where+    formatArg = formatChar+    parseFormat _ cf = parseIntFormat (undefined :: Int) cf++-- | @since 2.01+instance (IsChar c) => PrintfArg [c] where+    formatArg = formatString++-- | @since 2.01+instance PrintfArg Int where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Int8 where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Int16 where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Int32 where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Int64 where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Word where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Word8 where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Word16 where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Word32 where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Word64 where+    formatArg = formatInt+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Integer where+    formatArg = formatInteger+    parseFormat = parseIntFormat++-- | @since 4.8.0.0+instance PrintfArg Natural where+    formatArg = formatInteger . toInteger+    parseFormat = parseIntFormat++-- | @since 2.01+instance PrintfArg Float where+    formatArg = formatRealFloat++-- | @since 2.01+instance PrintfArg Double where+    formatArg = formatRealFloat++-- | This class, with only the one instance, is used as+-- a workaround for the fact that 'String', as a concrete+-- type, is not allowable as a typeclass instance. 'IsChar'+-- is exported for backward-compatibility.+class IsChar c where+    -- | @since 4.7.0.0+    toChar :: c -> Char+    -- | @since 4.7.0.0+    fromChar :: Char -> c++-- | @since 2.01+instance IsChar Char where+    toChar c = c+    fromChar c = c++-------------------++-- | Whether to left-adjust or zero-pad a field. These are+-- mutually exclusive, with 'LeftAdjust' taking precedence.+--+-- @since 4.7.0.0+data FormatAdjustment = LeftAdjust | ZeroPad++-- | How to handle the sign of a numeric field.  These are+-- mutually exclusive, with 'SignPlus' taking precedence.+--+-- @since 4.7.0.0+data FormatSign = SignPlus | SignSpace++-- | Description of field formatting for 'formatArg'. See UNIX @printf(3)@+-- for a description of how field formatting works.+--+-- @since 4.7.0.0+data FieldFormat = FieldFormat {+  fmtWidth :: Maybe Int,       -- ^ Total width of the field.+  fmtPrecision :: Maybe Int,   -- ^ Secondary field width specifier.+  fmtAdjust :: Maybe FormatAdjustment,  -- ^ Kind of filling or padding+                                        --   to be done.+  fmtSign :: Maybe FormatSign, -- ^ Whether to insist on a+                               -- plus sign for positive+                               -- numbers.+  fmtAlternate :: Bool,        -- ^ Indicates an "alternate+                               -- format".  See @printf(3)@+                               -- for the details, which+                               -- vary by argument spec.+  fmtModifiers :: String,      -- ^ Characters that appeared+                               -- immediately to the left of+                               -- 'fmtChar' in the format+                               -- and were accepted by the+                               -- type's 'parseFormat'.+                               -- Normally the empty string.+  fmtChar :: Char              -- ^ The format character+                               -- 'printf' was invoked+                               -- with. 'formatArg' should+                               -- fail unless this character+                               -- matches the type. It is+                               -- normal to handle many+                               -- different format+                               -- characters for a single+                               -- type.+  }++-- | The \"format parser\" walks over argument-type-specific+-- modifier characters to find the primary format character.+-- This is the type of its result.+--+-- @since 4.7.0.0+data FormatParse = FormatParse {+  fpModifiers :: String,   -- ^ Any modifiers found.+  fpChar :: Char,          -- ^ Primary format character.+  fpRest :: String         -- ^ Rest of the format string.+  }++-- Contains the "modifier letters" that can precede an+-- integer type.+intModifierMap :: [(String, Integer)]+intModifierMap = [+  ("hh", toInteger (minBound :: Int8)),+  ("h", toInteger (minBound :: Int16)),+  ("l", toInteger (minBound :: Int32)),+  ("ll", toInteger (minBound :: Int64)),+  ("L", toInteger (minBound :: Int64)) ]++parseIntFormat :: a -> String -> FormatParse+parseIntFormat _ s =+  case foldr matchPrefix Nothing intModifierMap of+    Just m -> m+    Nothing ->+      case s of+        c : cs -> FormatParse "" c cs+        "" -> errorShortFormat+  where+    matchPrefix (p, _) m@(Just (FormatParse p0 _ _))+      | length p0 >= length p = m+      | otherwise = case getFormat p of+          Nothing -> m+          Just fp -> Just fp+    matchPrefix (p, _) Nothing =+      getFormat p+    getFormat p =+      stripPrefix p s >>= fp+      where+        fp (c : cs) = Just $ FormatParse p c cs+        fp "" = errorShortFormat++-- | This is the type of a field formatter reified over its+-- argument.+--+-- @since 4.7.0.0+type FieldFormatter = FieldFormat -> ShowS++-- | Type of a function that will parse modifier characters+-- from the format string.+--+-- @since 4.7.0.0+type ModifierParser = String -> FormatParse++-- | Substitute a \'v\' format character with the given+-- default format character in the 'FieldFormat'. A+-- convenience for user-implemented types, which should+-- support \"%v\".+--+-- @since 4.7.0.0+vFmt :: Char -> FieldFormat -> FieldFormat+vFmt c ufmt@(FieldFormat {fmtChar = 'v'}) = ufmt {fmtChar = c}+vFmt _ ufmt = ufmt++-- | Formatter for 'Char' values.+--+-- @since 4.7.0.0+formatChar :: Char -> FieldFormatter+formatChar x ufmt =+  formatIntegral (Just 0) (toInteger $ ord x) $ vFmt 'c' ufmt++-- | Formatter for 'String' values.+--+-- @since 4.7.0.0+formatString :: IsChar a => [a] -> FieldFormatter+formatString x ufmt =+  case fmtChar $ vFmt 's' ufmt of+    's' -> map toChar . (adjust ufmt ("", ts) ++)+           where+             ts = map toChar $ trunc $ fmtPrecision ufmt+               where+                 trunc Nothing = x+                 trunc (Just n) = take n x+    c   -> errorBadFormat c++-- Possibly apply the int modifiers to get a new+-- int width for conversion.+fixupMods :: FieldFormat -> Maybe Integer -> Maybe Integer+fixupMods ufmt m =+  let mods = fmtModifiers ufmt in+  case mods of+    "" -> m+    _ -> case lookup mods intModifierMap of+      Just m0 -> Just m0+      Nothing -> perror "unknown format modifier"++-- | Formatter for 'Int' values.+--+-- @since 4.7.0.0+formatInt :: (Integral a, Bounded a) => a -> FieldFormatter+formatInt x ufmt =+  let lb = toInteger $ minBound `asTypeOf` x+      m = fixupMods ufmt (Just lb)+      ufmt' = case lb of+        0 -> vFmt 'u' ufmt+        _ -> ufmt+  in+  formatIntegral m (toInteger x) ufmt'++-- | Formatter for 'Integer' values.+--+-- @since 4.7.0.0+formatInteger :: Integer -> FieldFormatter+formatInteger x ufmt =+  let m = fixupMods ufmt Nothing in+  formatIntegral m x ufmt++-- All formatting for integral types is handled+-- consistently.  The only difference is between Integer and+-- bounded types; this difference is handled by the 'm'+-- argument containing the lower bound.+formatIntegral :: Maybe Integer -> Integer -> FieldFormatter+formatIntegral m x ufmt0 =+  let prec = fmtPrecision ufmt0 in+  case fmtChar ufmt of+    'd' -> (adjustSigned ufmt (fmti prec x) ++)+    'i' -> (adjustSigned ufmt (fmti prec x) ++)+    'x' -> (adjust ufmt (fmtu 16 (alt "0x" x) prec m x) ++)+    'X' -> (adjust ufmt (upcase $ fmtu 16 (alt "0X" x) prec m x) ++)+    'b' -> (adjust ufmt (fmtu 2 (alt "0b" x) prec m x) ++)+    'o' -> (adjust ufmt (fmtu 8 (alt "0" x) prec m x) ++)+    'u' -> (adjust ufmt (fmtu 10 Nothing prec m x) ++)+    'c' | x >= fromIntegral (ord (minBound :: Char)) &&+          x <= fromIntegral (ord (maxBound :: Char)) &&+          fmtPrecision ufmt == Nothing &&+          fmtModifiers ufmt == "" ->+            formatString [chr $ fromIntegral x] (ufmt { fmtChar = 's' })+    'c' -> perror "illegal char conversion"+    c   -> errorBadFormat c+  where+    ufmt = vFmt 'd' $ case ufmt0 of+      FieldFormat { fmtPrecision = Just _, fmtAdjust = Just ZeroPad } ->+        ufmt0 { fmtAdjust = Nothing }+      _ -> ufmt0+    alt _ 0 = Nothing+    alt p _ = case fmtAlternate ufmt of+      True -> Just p+      False -> Nothing+    upcase (s1, s2) = (s1, map toUpper s2)++-- | Formatter for 'RealFloat' values.+--+-- @since 4.7.0.0+formatRealFloat :: RealFloat a => a -> FieldFormatter+formatRealFloat x ufmt =+  let c = fmtChar $ vFmt 'g' ufmt+      prec = fmtPrecision ufmt+      alt = fmtAlternate ufmt+  in+   case c of+     'e' -> (adjustSigned ufmt (dfmt c prec alt x) ++)+     'E' -> (adjustSigned ufmt (dfmt c prec alt x) ++)+     'f' -> (adjustSigned ufmt (dfmt c prec alt x) ++)+     'F' -> (adjustSigned ufmt (dfmt c prec alt x) ++)+     'g' -> (adjustSigned ufmt (dfmt c prec alt x) ++)+     'G' -> (adjustSigned ufmt (dfmt c prec alt x) ++)+     _   -> errorBadFormat c++-- This is the type carried around for arguments in+-- the varargs code.+type UPrintf = (ModifierParser, FieldFormatter)++-- Given a format string and a list of formatting functions+-- (the actual argument value having already been baked into+-- each of these functions before delivery), return the+-- actual formatted text string.+uprintf :: String -> [UPrintf] -> String+uprintf s us = uprintfs s us ""++-- This function does the actual work, producing a ShowS+-- instead of a string, for future expansion and for+-- misguided efficiency.+uprintfs :: String -> [UPrintf] -> ShowS+uprintfs ""       []       = id+uprintfs ""       (_:_)    = errorShortFormat+uprintfs ('%':'%':cs) us   = ('%' :) . uprintfs cs us+uprintfs ('%':_)  []       = errorMissingArgument+uprintfs ('%':cs) us@(_:_) = fmt cs us+uprintfs (c:cs)   us       = (c :) . uprintfs cs us++-- Given a suffix of the format string starting just after+-- the percent sign, and the list of remaining unprocessed+-- arguments in the form described above, format the portion+-- of the output described by this field description, and+-- then continue with 'uprintfs'.+fmt :: String -> [UPrintf] -> ShowS+fmt cs0 us0 =+  case getSpecs False False Nothing False cs0 us0 of+    (_, _, []) -> errorMissingArgument+    (ufmt, cs, (_, u) : us) -> u ufmt . uprintfs cs us++-- Given field formatting information, and a tuple+-- consisting of a prefix (for example, a minus sign) that+-- is supposed to go before the argument value and a string+-- representing the value, return the properly padded and+-- formatted result.+adjust :: FieldFormat -> (String, String) -> String+adjust ufmt (pre, str) =+  let naturalWidth = length pre + length str+      zero = case fmtAdjust ufmt of+        Just ZeroPad -> True+        _ -> False+      left = case fmtAdjust ufmt of+        Just LeftAdjust -> True+        _ -> False+      fill = case fmtWidth ufmt of+        Just width | naturalWidth < width ->+          let fillchar = if zero then '0' else ' ' in+          replicate (width - naturalWidth) fillchar+        _ -> ""+  in+   if left+   then pre ++ str ++ fill+   else if zero+        then pre ++ fill ++ str+        else fill ++ pre ++ str++-- For positive numbers with an explicit sign field ("+" or+-- " "), adjust accordingly.+adjustSigned :: FieldFormat -> (String, String) -> String+adjustSigned ufmt@(FieldFormat {fmtSign = Just SignPlus}) ("", str) =+  adjust ufmt ("+", str)+adjustSigned ufmt@(FieldFormat {fmtSign = Just SignSpace}) ("", str) =+  adjust ufmt (" ", str)+adjustSigned ufmt ps =+  adjust ufmt ps++-- Format a signed integer in the "default" fashion.+-- This will be subjected to adjust subsequently.+fmti :: Maybe Int -> Integer -> (String, String)+fmti prec i+  | i < 0 = ("-", integral_prec prec (show (-i)))+  | otherwise = ("", integral_prec prec (show i))++-- Format an unsigned integer in the "default" fashion.+-- This will be subjected to adjust subsequently.  The 'b'+-- argument is the base, the 'pre' argument is the prefix,+-- and the '(Just m)' argument is the implicit lower-bound+-- size of the operand for conversion from signed to+-- unsigned. Thus, this function will refuse to convert an+-- unbounded negative integer to an unsigned string.+fmtu :: Integer -> Maybe String -> Maybe Int -> Maybe Integer -> Integer+     -> (String, String)+fmtu b (Just pre) prec m i =+  let ("", s) = fmtu b Nothing prec m i in+  case pre of+    "0" -> case s of+      '0' : _ -> ("", s)+      _ -> (pre, s)+    _ -> (pre, s)+fmtu b Nothing prec0 m0 i0 =+  case fmtu' prec0 m0 i0 of+    Just s -> ("", s)+    Nothing -> errorBadArgument+  where+    fmtu' :: Maybe Int -> Maybe Integer -> Integer -> Maybe String+    fmtu' prec (Just m) i | i < 0 =+      fmtu' prec Nothing (-2 * m + i)+    fmtu' (Just prec) _ i | i >= 0 =+      fmap (integral_prec (Just prec)) $ fmtu' Nothing Nothing i+    fmtu' Nothing _ i | i >= 0 =+      Just $ showIntAtBase b intToDigit i ""+    fmtu' _ _ _ = Nothing+++-- This is used by 'fmtu' and 'fmti' to zero-pad an+-- int-string to a required precision.+integral_prec :: Maybe Int -> String -> String+integral_prec Nothing integral = integral+integral_prec (Just 0) "0" = ""+integral_prec (Just prec) integral =+  replicate (prec - length integral) '0' ++ integral++stoi :: String -> (Int, String)+stoi cs =+  let (as, cs') = span isDigit cs in+  case as of+    "" -> (0, cs')+    _ -> (read as, cs')++-- Figure out the FormatAdjustment, given:+--   width, precision, left-adjust, zero-fill+adjustment :: Maybe Int -> Maybe a -> Bool -> Bool+           -> Maybe FormatAdjustment+adjustment w p l z =+  case w of+    Just n | n < 0 -> adjl p True z+    _ -> adjl p l z+  where+    adjl _ True _ = Just LeftAdjust+    adjl _ False True = Just ZeroPad+    adjl _ _ _ = Nothing++-- Parse the various format controls to get a format specification.+getSpecs :: Bool -> Bool -> Maybe FormatSign -> Bool -> String -> [UPrintf]+         -> (FieldFormat, String, [UPrintf])+getSpecs _ z s a ('-' : cs0) us = getSpecs True z s a cs0 us+getSpecs l z _ a ('+' : cs0) us = getSpecs l z (Just SignPlus) a cs0 us+getSpecs l z s a (' ' : cs0) us =+  getSpecs l z ss a cs0 us+  where+    ss = case s of+      Just SignPlus -> Just SignPlus+      _ -> Just SignSpace+getSpecs l _ s a ('0' : cs0) us = getSpecs l True s a cs0 us+getSpecs l z s _ ('#' : cs0) us = getSpecs l z s True cs0 us+getSpecs l z s a ('*' : cs0) us =+  let (us', n) = getStar us+      ((p, cs''), us'') = case cs0 of+        '.':'*':r ->+          let (us''', p') = getStar us' in ((Just p', r), us''')+        '.':r ->+          let (p', r') = stoi r in ((Just p', r'), us')+        _ ->+          ((Nothing, cs0), us')+      FormatParse ms c cs =+        case us'' of+          (ufmt, _) : _ -> ufmt cs''+          [] -> errorMissingArgument+  in+   (FieldFormat {+       fmtWidth = Just (abs n),+       fmtPrecision = p,+       fmtAdjust = adjustment (Just n) p l z,+       fmtSign = s,+       fmtAlternate = a,+       fmtModifiers = ms,+       fmtChar = c}, cs, us'')+getSpecs l z s a ('.' : cs0) us =+  let ((p, cs'), us') = case cs0 of+        '*':cs'' -> let (us'', p') = getStar us in ((p', cs''), us'')+        _ ->        (stoi cs0, us)+      FormatParse ms c cs =+        case us' of+          (ufmt, _) : _ -> ufmt cs'+          [] -> errorMissingArgument+  in+   (FieldFormat {+       fmtWidth = Nothing,+       fmtPrecision = Just p,+       fmtAdjust = adjustment Nothing (Just p) l z,+       fmtSign = s,+       fmtAlternate = a,+       fmtModifiers = ms,+       fmtChar = c}, cs, us')+getSpecs l z s a cs0@(c0 : _) us | isDigit c0 =+  let (n, cs') = stoi cs0+      ((p, cs''), us') = case cs' of+        '.' : '*' : r ->+          let (us'', p') = getStar us in ((Just p', r), us'')+        '.' : r ->+          let (p', r') = stoi r in ((Just p', r'), us)+        _ ->+          ((Nothing, cs'), us)+      FormatParse ms c cs =+        case us' of+          (ufmt, _) : _ -> ufmt cs''+          [] -> errorMissingArgument+  in+   (FieldFormat {+       fmtWidth = Just (abs n),+       fmtPrecision = p,+       fmtAdjust = adjustment (Just n) p l z,+       fmtSign = s,+       fmtAlternate = a,+       fmtModifiers = ms,+       fmtChar = c}, cs, us')+getSpecs l z s a cs0@(_ : _) us =+  let FormatParse ms c cs =+        case us of+          (ufmt, _) : _ -> ufmt cs0+          [] -> errorMissingArgument+  in+   (FieldFormat {+       fmtWidth = Nothing,+       fmtPrecision = Nothing,+       fmtAdjust = adjustment Nothing Nothing l z,+       fmtSign = s,+       fmtAlternate = a,+       fmtModifiers = ms,+       fmtChar = c}, cs, us)+getSpecs _ _ _ _ ""       _  =+  errorShortFormat++-- Process a star argument in a format specification.+getStar :: [UPrintf] -> ([UPrintf], Int)+getStar us =+  let ufmt = FieldFormat {+        fmtWidth = Nothing,+        fmtPrecision = Nothing,+        fmtAdjust = Nothing,+        fmtSign = Nothing,+        fmtAlternate = False,+        fmtModifiers = "",+        fmtChar = 'd' } in+  case us of+    [] -> errorMissingArgument+    (_, nu) : us' -> (us', read (nu ufmt ""))++-- Format a RealFloat value.+dfmt :: (RealFloat a) => Char -> Maybe Int -> Bool -> a -> (String, String)+dfmt c p a d =+  let caseConvert = if isUpper c then map toUpper else id+      showFunction = case toLower c of+        'e' -> showEFloat+        'f' -> if a then showFFloatAlt else showFFloat+        'g' -> if a then showGFloatAlt else showGFloat+        _   -> perror "internal error: impossible dfmt"+      result = caseConvert $ showFunction p d ""+  in+   case result of+     '-' : cs -> ("-", cs)+     cs       -> ("" , cs)+++-- | Raises an 'error' with a printf-specific prefix on the+-- message string.+--+-- @since 4.7.0.0+perror :: String -> a+perror s = errorWithoutStackTrace $ "printf: " ++ s++-- | Calls 'perror' to indicate an unknown format letter for+-- a given type.+--+-- @since 4.7.0.0+errorBadFormat :: Char -> a+errorBadFormat c = perror $ "bad formatting char " ++ show c++errorShortFormat, errorMissingArgument, errorBadArgument :: a+-- | Calls 'perror' to indicate that the format string ended+-- early.+--+-- @since 4.7.0.0+errorShortFormat = perror "formatting string ended prematurely"+-- | Calls 'perror' to indicate that there is a missing+-- argument in the argument list.+--+-- @since 4.7.0.0+errorMissingArgument = perror "argument list ended prematurely"+-- | Calls 'perror' to indicate that there is a type+-- error or similar in the given argument.+--+-- @since 4.7.0.0+errorBadArgument = perror "bad argument"
+ src/Text/Read.hs view
@@ -0,0 +1,43 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Text.Read+-- 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 (uses Text.ParserCombinators.ReadP)+--+-- Converting strings to values.+--+-- The "Text.Read" module is the canonical place to import for+-- 'Read'-class facilities.  For GHC only, it offers an extended and much+-- improved 'Read' class, which constitutes a proposed alternative to the+-- Haskell 2010 'Read'.  In particular, writing parsers is easier, and+-- the parsers are much more efficient.+--++module Text.Read+    (-- *  The 'Read' class+     Read(..),+     ReadS,+     -- *  Haskell 2010 functions+     reads,+     read,+     readParen,+     lex,+     -- *  New parsing functions+     module Text.ParserCombinators.ReadPrec,+     Lexeme(..),+     lexP,+     parens,+     readListDefault,+     readListPrecDefault,+     readEither,+     readMaybe+     ) where++import GHC.Internal.Text.Read+import Text.ParserCombinators.ReadPrec
+ src/Text/Read/Lex.hs view
@@ -0,0 +1,35 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Text.Read.Lex+-- Copyright   :  (c) The University of Glasgow 2002+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  non-portable (uses Text.ParserCombinators.ReadP)+--+-- The cut-down Haskell lexer, used by Text.Read+--++module Text.Read.Lex+    (Lexeme(..),+     Number,+     numberToInteger,+     numberToFixed,+     numberToRational,+     numberToRangedRational,+     lex,+     expect,+     hsLex,+     lexChar,+     readBinP,+     readIntP,+     readOctP,+     readDecP,+     readHexP,+     isSymbolChar+     ) where++import GHC.Internal.Text.Read.Lex
+ src/Text/Show.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE Safe #-}++-- |+--+-- Module      :  Text.Show+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Converting values to readable strings:+-- the 'Show' class and associated functions.+--++module Text.Show+    (ShowS,+     Show(showsPrec, show, showList),+     shows,+     showChar,+     showString,+     showParen,+     showListWith+     ) where++import GHC.Internal.Text.Show
+ src/Text/Show/Functions.hs view
@@ -0,0 +1,27 @@+{-# LANGUAGE Safe #-}+-- This module deliberately declares orphan instances:+{-# OPTIONS_GHC -Wno-orphans #-}++-- |+--+-- Module      :  Text.Show.Functions+-- Copyright   :  (c) The University of Glasgow 2001+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  provisional+-- Portability :  portable+--+-- Optional instance of 'Text.Show.Show' for functions:+--+-- > instance Show (a -> b) where+-- >    showsPrec _ _ = showString "<function>"+--++module Text.Show.Functions () where++import Prelude++-- | @since 2.01+instance Show (a -> b) where+        showsPrec _ _ = showString "<function>"
+ src/Type/Reflection.hs view
@@ -0,0 +1,69 @@+{-# LANGUAGE Safe #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE MagicHash #-}++-- |+--+-- Module      :  Type.Reflection+-- Copyright   :  (c) The University of Glasgow, CWI 2001--2017+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- Maintainer  :  libraries@haskell.org+-- Stability   :  stable+-- Portability :  non-portable (requires GADTs and compiler support)+--+-- This provides a type-indexed type representation mechanism, similar to that+-- described by,+--+-- * Simon Peyton-Jones, Stephanie Weirich, Richard Eisenberg,+-- Dimitrios Vytiniotis. "<https://www.microsoft.com/en-us/research/wp-content/uploads/2016/08/dynamic.pdf A reflection on types>".+-- /Proc. Philip Wadler's 60th birthday Festschrift/, Edinburgh (April 2016).+--+-- The interface provides 'I.TypeRep', a type representation which can+-- be safely decomposed and composed. See "Data.Dynamic" for an example of this.+--+-- @since 4.10.0.0+--++module Type.Reflection+    (-- *  The Typeable class+     Typeable,+     typeRep,+     withTypeable,+     -- *  Propositional equality+     (:~:)(Refl),+     (:~~:)(HRefl),+     -- *  Type representations+     -- **  Type-Indexed+     TypeRep,+     pattern TypeRep,+     typeOf,+     pattern App,+     pattern Con,+     pattern Con',+     pattern Fun,+     typeRepTyCon,+     rnfTypeRep,+     eqTypeRep,+     decTypeRep,+     typeRepKind,+     splitApps,+     -- **  Quantified+     SomeTypeRep(..),+     someTypeRep,+     someTypeRepTyCon,+     rnfSomeTypeRep,+     -- *  Type constructors+     TyCon,+     tyConPackage,+     tyConModule,+     tyConName,+     rnfTyCon,+     -- *  Module names+     Module,+     moduleName,+     modulePackage,+     rnfModule+     ) where++import GHC.Internal.Type.Reflection
+ src/Type/Reflection/Unsafe.hs view
@@ -0,0 +1,33 @@+-- |+--+-- Module      :  Type.Reflection.Unsafe+-- Copyright   :  (c) The University of Glasgow, CWI 2001--2015+-- License     :  BSD-style (see the file libraries/base/LICENSE)+--+-- The representations of the types 'TyCon' and 'TypeRep', and the function+-- 'mkTyCon' which is used by derived instances of 'Typeable' to construct+-- 'TyCon's.+--+-- Be warned, these functions can be used to construct ill-kinded+-- type representations.+--++module Type.Reflection.Unsafe+    (-- *  Type representations+     TypeRep,+     mkTrApp,+     mkTyCon,+     typeRepFingerprint,+     someTypeRepFingerprint,+     -- *  Kind representations+     KindRep(..),+     TypeLitSort(..),+     -- *  Type constructors+     TyCon,+     mkTrCon,+     tyConKindRep,+     tyConKindArgs,+     tyConFingerprint+     ) where++import GHC.Internal.Type.Reflection.Unsafe
+ src/Unsafe/Coerce.hs view
@@ -0,0 +1,12 @@+{-# LANGUAGE MagicHash #-}++module Unsafe.Coerce+    (unsafeCoerce,+     unsafeCoerceUnlifted,+     unsafeCoerceAddr,+     unsafeEqualityProof,+     UnsafeEquality(..),+     unsafeCoerce#+     ) where++import GHC.Internal.Unsafe.Coerce