code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE KindSignatures #-} {-# OPTIONS_HADDOCK hide #-} -- | -- Functions which execute DNA routines on remote nodes. Below is -- general algorithms: -- -- 1. Obtain auxiliary parameters ('ActorParam') -- -- 2. Send receive address back to parent ('RecvAddr') -- -- 3. Receive initial parameters and execute program -- -- 4. Send result to latest destination received -- -- One particular problem is related to the need of respawning of -- processes. We must ensure that actor sends its result to real actor -- instead of just terminated actor module DNA.Interpreter.Run ( -- * Run actors runActor -- , runActorManyRanks , runCollectActor , runTreeActor -- * Helpers , doGatherDna , splitEvenly -- * CH , runActor__static -- , runActorManyRanks__static , runCollectActor__static , runTreeActor__static , __remoteTable ) where import Control.Monad import Control.Distributed.Process import Control.Distributed.Process.Serializable import Control.Distributed.Process.Closure import Data.Typeable (Typeable) import Data.List (findIndex) import qualified Data.Foldable as T import DNA.CH import DNA.Types import DNA.DSL import DNA.Interpreter.Types ---------------------------------------------------------------- -- Functions for starting actors ---------------------------------------------------------------- -- | Start execution of standard actor runActor :: Actor a b -> Process () runActor (Actor action) = do -- Obtain parameters p <- expect -- Create channels for communication (chSendParam,chRecvParam) <- newChan -- Send data destination back sendChan (actorSendBack p) $ RcvSimple (makeRecv chSendParam) -- Now we can start execution and send back data a <- receiveChan chRecvParam !b <- runDnaParam p (action a) sendResult p b {- -- | Run actor for group of processes which allow more than 1 task per -- actor. runActorManyRanks :: Actor a b -> Process () runActorManyRanks (Actor action) = do -- Obtain parameters p <- expect -- Create channels for communication (chSendParam,chRecvParam) <- newChan (chSendDst, chRecvDst ) <- newChan (chSendRnk, chRecvRnk ) <- newChan -- Send shell process back sendChan (actorSendBack p) (RcvSimple (wrapMessage chSendParam)) -- let shell = ( RecvVal chSendParam -- , SendVal chSendDst ) -- send (actorParent p) (chSendRnk,shell) -- -- Start actor execution -- a <- receiveChan chRecvParam -- let loop dst = do -- send (actorParent p) (me,chSendRnk) -- mrnk <- receiveChan chRecvRnk -- case mrnk of -- Nothing -> return () -- Just rnk -> do -- !b <- runDnaParam p{actorRank = rnk} (action a) -- dst' <- drainChannel0 chRecvDst dst -- sendToDest dst' b -- send (actorParent p) (me,DoneTask) -- loop dst' -- loop =<< drainChannel chRecvDst -} -- | Start execution of collector actor runCollectActor :: CollectActor a b -> Process () runCollectActor (CollectActor step start fini) = do -- Obtain parameters p <- expect -- Create channels for communication (chSendParam,chRecvParam) <- newChan (chSendN, chRecvN ) <- newChan -- Send shell process description back sendChan (actorSendBack p) $ RcvReduce (makeRecv chSendParam) chSendN -- Start execution of an actor !b <- runDnaParam p $ do case [pCrash | CrashProbably pCrash <- actorDebugFlags p] of pCrash : _ -> crashMaybe pCrash _ -> return () s0 <- start s <- gatherM (Group chRecvParam chRecvN) step s0 fini s sendResult p b -- | Start execution of collector actor runTreeActor :: CollectActor a a -> Process () runTreeActor (CollectActor step start fini) = do -- Obtain parameters p <- expect -- Create channels for communication (chSendParam,chRecvParam) <- newChan (chSendN, chRecvN ) <- newChan -- Send shell process description back sendChan (actorSendBack p) $ RcvReduce (makeRecv chSendParam) chSendN -- Start execution of an actor !a <- runDnaParam p $ do s0 <- start s <- gatherM (Group chRecvParam chRecvN) step s0 fini s sendResult p a ---------------------------------------------------------------- -- Helpers ---------------------------------------------------------------- -- Send result to the destination we sendResult :: (Serializable a) => ActorParam -> a -> Process () sendResult p !a = sendLoop =<< drainExpect where sendLoop dst = do -- Send data to destination case dst of RcvSimple msg -> trySend msg RcvReduce m _ -> trySend m RcvTree msgs -> do let nReducers = length msgs GroupSize nResults = actorGroupSize p Rank rnk = actorRank p case msgs !! findIndexInSplittedList nResults nReducers rnk of RcvReduce ch _ -> trySend ch RcvFailed -> return () RcvCompleted -> return () _ -> doPanic "sendResult: bad tree actor!" RcvGrp msgs -> forM_ msgs $ \case RcvSimple m -> trySend m RcvFailed -> return () RcvCompleted -> return () _ -> doPanic "sendResult: bad group actor!" RcvFailed -> return () RcvCompleted -> return () -- Send confirmation to parent and wait for T.forM_ (actorParent p) $ \pid -> do me <- getSelfPid send pid (SentTo me dst) receiveWait [ match $ \(Terminate msg) -> error msg , match $ \newDest -> sendLoop newDest , match $ \AckSend -> return () ] -- Loop over data trySend (Recv _ msg) = do mch <- unwrapMessage msg case mch of Just ch -> unsafeSendChan ch a Nothing -> doPanic "Type error in channel!" findIndexInSplittedList :: Int -> Int -> Int -> Int findIndexInSplittedList nElems n rnk = case findIndex (\(a,b) -> rnk >= a && rnk < b) bins of Just i -> i _ -> error "Impossible split!" where bins = splitEvenly nElems n splitEvenly :: Int -> Int -> [(Int,Int)] splitEvenly nElems n = offs `zip` tail offs where (bin,rest) = nElems `divMod` n sizes = zipWith (+) (replicate n bin) (replicate rest 1 ++ repeat 0) offs = scanl (+) 0 sizes doGatherDna :: Serializable a => [MatchS] -> Group a -> (b -> a -> DnaMonad b) -> b -> DnaMonad b doGatherDna ms (Group chA chN) f x0 = do let loop n tot !b | n >= tot && tot >= 0 = return b loop n tot !b = do r <- handleRecieve ms [ Right `fmap` matchChan' chA , Left `fmap` matchChan' chN ] case r of Right a -> loop (n + 1) tot =<< f b a Left k -> loop n k b loop 0 (-1) x0 ---------------------------------------------------------------- -- CH's TH ---------------------------------------------------------------- remotable [ 'runActor -- , 'runActorManyRanks , 'runCollectActor , 'runTreeActor ]
SKA-ScienceDataProcessor/RC
MS6/dna/core/DNA/Interpreter/Run.hs
apache-2.0
8,035
0
18
2,528
1,534
779
755
137
13
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} #if __GLASGOW_HASKELL__ >= 786 {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} #endif module Data.Complex.Polar ( #if __GLASGOW_HASKELL__ >= 800 Polar((:<)), #elif __GLASGOW_HASKELL >= 786 Polar, pattern (:<), #else Polar, #endif fromPolar, fromComplex, realPart, imagPart, conjugate, mkPolar, cis, polar, magnitude, phase ) where import Data.Complex (Complex(..)) import qualified Data.Complex as C import Data.Typeable #ifdef __GLASGOW_HASKELL__ import Data.Data (Data) #endif #ifdef __HUGS__ import Hugs.Prelude(Num(fromInt), Fractional(fromDouble)) #endif import Text.Read (parens) import Text.ParserCombinators.ReadPrec (prec, step) import Text.Read.Lex (Lexeme (Ident)) infix 6 :<< -- ----------------------------------------------------------------------------- -- The Polar 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 (RealFloat a) => Polar a = !a :<< !a -- ^ forms a complex number from its magnitude -- and its phase in radians. #if __GLASGOW_HASKELL__ deriving (Eq, Data, Typeable) #else deriving Eq #endif #if __GLASGOW_HASKELL__ >= 786 infix 6 :< -- | Smart constructor that canonicalizes the magnitude and phase. pattern r :< theta <- ( \(r :<< theta) -> Just (r, theta) -> Just (r, theta) ) where r :< theta = mkPolar r theta #endif instance (RealFloat a, Show a) => Show (Polar a) where {-# SPECIALISE instance Show (Polar Float) #-} {-# SPECIALISE instance Show (Polar Double) #-} showsPrec d (r :<< theta) = showParen (d >= 11) (showString "mkPolar " . showsPrec 11 r . showString " " . showsPrec 11 theta) instance (RealFloat a, Read a) => Read (Polar a) where {-# SPECIALISE instance Read (Polar Float) #-} {-# SPECIALISE instance Read (Polar Double) #-} readsPrec d = readParen (d > 10) (\s -> do ("mkPolar", s2) <- lex s (r, s3) <- readsPrec 11 s2 (theta, s4) <- readsPrec 11 s3 return (mkPolar r theta, s4)) -- | Wrap phase back in interval @(-'pi', 'pi']@. wrap :: (RealFloat a) => a -> a {-# SPECIALISE wrap :: Float -> Float #-} {-# SPECIALISE wrap :: Double -> Double #-} wrap phi | phi <= (-pi) = wrap (phi+2*pi) wrap phi | phi > pi = wrap (phi-2*pi) wrap phi = phi -- | Convert to rectangular form. fromPolar :: (RealFloat a) => Polar a -> Complex a {-# INLINE fromPolar #-} fromPolar p = realPart p :+ imagPart p -- | Convert to polar form. fromComplex :: (RealFloat a) => Complex a -> Polar a {-# INLINE fromComplex #-} fromComplex = uncurry mkPolar_ . C.polar -- | Extracts the real part of a complex number. realPart :: (RealFloat a) => Polar a -> a realPart (r :<< theta) = r * cos theta -- | Extracts the imaginary part of a complex number. imagPart :: (RealFloat a) => Polar a -> a imagPart (r :<< theta) = r * sin theta -- | The conjugate of a complex number. conjugate :: (RealFloat a) => Polar a -> Polar a {-# SPECIALISE conjugate :: Polar Float -> Polar Float #-} {-# SPECIALISE conjugate :: Polar Double -> Polar Double #-} conjugate (r :<< theta) = mkPolar r (negate theta) -- | Form a complex number from polar components of magnitude and phase. -- The magnitude and phase are expected to be in canonical form. mkPolar_ :: RealFloat a => a -> a -> Polar a {-# SPECIALISE mkPolar_ :: Float -> Float -> Polar Float #-} {-# SPECIALISE mkPolar_ :: Double -> Double -> Polar Double #-} mkPolar_ r theta = r :<< theta -- | Form a complex number from polar components of magnitude and phase. mkPolar :: RealFloat a => a -> a -> Polar a {-# SPECIALISE mkPolar :: Float -> Float -> Polar Float #-} {-# SPECIALISE mkPolar :: Double -> Double -> Polar Double #-} mkPolar r theta | r == 0 = 0 :<< 0 mkPolar r theta | r < 0 = mkPolar (- r) (theta + pi) mkPolar r theta = mkPolar_ r (wrap theta) -- | @'cis' t@ is a complex value with magnitude @1@ -- and phase @t@ (modulo @2*'pi'@). cis :: (RealFloat a) => a -> Polar a {-# SPECIALISE cis :: Float -> Polar Float #-} {-# SPECIALISE cis :: Double -> Polar Double #-} cis theta = mkPolar 1 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. polar :: (RealFloat a) => Polar a -> (a,a) {-# SPECIALISE polar :: Polar Double -> (Double,Double) #-} {-# SPECIALISE polar :: Polar Float -> (Float,Float) #-} polar (r :<< theta) = (r,theta) -- | The nonnegative magnitude of a complex number. magnitude :: (RealFloat a) => Polar a -> a {-# SPECIALISE magnitude :: Polar Float -> Float #-} {-# SPECIALISE magnitude :: Polar Double -> Double #-} magnitude (r :<< _) = r -- | The phase of a complex number, in the range @(-'pi', 'pi']@. -- If the magnitude is zero, then so is the phase. phase :: (RealFloat a) => Polar a -> a {-# SPECIALISE phase :: Polar Float -> Float #-} {-# SPECIALISE phase :: Polar Double -> Double #-} phase (_ :<< theta) = theta instance (RealFloat a) => Num (Polar a) where {-# SPECIALISE instance Num (Polar Float) #-} {-# SPECIALISE instance Num (Polar Double) #-} z + z' = fromComplex (fromPolar z + fromPolar z') z - z' = fromComplex (fromPolar z - fromPolar z') z * z' = mkPolar (magnitude z * magnitude z') (phase z + phase z') negate z = mkPolar (negate (magnitude z)) (phase z) abs z = mkPolar_ (magnitude z) 0 signum (0 :<< _) = 0 signum z = mkPolar_ 1 (phase z) fromInteger = flip mkPolar 0 . fromInteger instance (RealFloat a) => Fractional (Polar a) where {-# SPECIALISE instance Fractional (Polar Float) #-} {-# SPECIALISE instance Fractional (Polar Double) #-} z / z' = mkPolar (magnitude z / magnitude z') (phase z - phase z') fromRational r = mkPolar (fromRational r) 0 instance (RealFloat a) => Floating (Polar a) where {-# SPECIALISE instance Floating (Polar Float) #-} {-# SPECIALISE instance Floating (Polar Double) #-} pi = mkPolar_ pi 0 exp (r :<< theta) = mkPolar (exp (r * cos theta)) (r * sin theta) log (r :<< theta) = fromComplex (log r :+ theta) -- sqrt (0 :<< _) = 0 -- sqrt z@(r :<< theta) = 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) sqrt = fromComplex.sqrt.fromPolar -- sin (x:+y) = sin x * cosh y :+ cos x * sinh y sin = fromComplex.sin.fromPolar -- cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y) cos = fromComplex.cos.fromPolar -- tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy)) -- where sinx = sin x -- cosx = cos x -- sinhy = sinh y -- coshy = cosh y tan = fromComplex.tan.fromPolar -- sinh (x:+y) = cos y * sinh x :+ sin y * cosh x sinh = fromComplex.sinh.fromPolar -- cosh (x:+y) = cos y * cosh x :+ sin y * sinh x cosh = fromComplex.cosh.fromPolar -- tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx) -- where siny = sin y -- cosy = cos y -- sinhx = sinh x -- coshx = cosh x tanh = fromComplex.tanh.fromPolar -- asin z@(x:+y) = y':+(-x') -- where (x':+y') = log (((-y):+x) + sqrt (1 - z*z)) asin = fromComplex.asin.fromPolar -- acos z = y'':+(-x'') -- where (x'':+y'') = log (z + ((-y'):+x')) -- (x':+y') = sqrt (1 - z*z) acos = fromComplex.acos.fromPolar -- atan z@(x:+y) = y':+(-x') -- where (x':+y') = log (((1-y):+x) / sqrt (1+z*z)) atan = fromComplex.atan.fromPolar asinh z = log (z + sqrt (1+z*z)) acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1))) atanh z = log ((1+z) / sqrt (1-z*z))
kaoskorobase/polar
Data/Complex/Polar.hs
bsd-2-clause
8,785
0
13
2,618
1,799
981
818
124
1
{-# LANGUAGE TemplateHaskell, QuasiQuotes, DeriveDataTypeable, MultiParamTypeClasses, TypeFamilies, FlexibleContexts, FlexibleInstances, OverloadedStrings #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE ScopedTypeVariables #-} module Application.WebLogger.Server.Yesod where import Control.Applicative import Data.Acid import Data.Aeson as A import Data.Attoparsec as P import qualified Data.ByteString as S import Data.Conduit import qualified Data.Conduit.List as CL import Data.Foldable import Network.Wai import Yesod hiding (update) -- import Application.WebLogger.Type import Application.WebLogger.Server.Type -- import Prelude hiding (concat,concatMap) -- | mkYesod "WebLoggerServer" [parseRoutes| / HomeR GET /list ListR GET /upload UploadR POST |] -- | instance Yesod WebLoggerServer where maximumContentLength _ _ = 100000000 -- | getHomeR :: Handler RepHtml getHomeR = do liftIO $ putStrLn "getHomeR called" defaultLayout [whamlet| !!! <html> <head> <title> weblogger <body> <h1> Weblogger |] -- | defhlet :: GWidget s m () defhlet = [whamlet| <h1> HTML output not supported |] -- | showstr :: String -> GWidget s m () showstr str = [whamlet| <h1> output <p> #{str} |] -- | formatLog :: WebLoggerRepo -> GWidget s m () formatLog xs = [whamlet| <h1> output <table> <tr> <td> log $forall x <- xs <tr> <td> #{weblog_content x} |] -- concatMap (\x -> weblog_content x ++ "\n\n") (toList xs) -- | getListR :: Handler RepHtmlJson getListR = do -- setHeader "Access-Control-Allow-Origin" "*" -- setHeader "Access-Control-Allow-Headers" "X-Requested-With, Content-Type" liftIO $ putStrLn "getListR called" acid <- server_acid <$> getYesod r <- liftIO $ query acid QueryAllLog -- liftIO $ putStrLn $ show r defaultLayoutJson (formatLog r) (A.toJSON (Just r)) -- | postUploadR :: Handler RepHtmlJson postUploadR = do liftIO $ putStrLn "postQueueR called" acid <- server_acid <$> getYesod wr <- reqWaiRequest <$> getRequest bs' <- liftIO $ runResourceT (requestBody wr $$ CL.consume) let bs = S.concat bs' let parsed = parse json bs case parsed of Done _ parsedjson -> do case (A.fromJSON parsedjson :: A.Result WebLoggerInfo) of Success minfo -> do r <- liftIO $ update acid (AddLog minfo) liftIO $ print (Just r) liftIO $ print (A.toJSON (Just r)) defaultLayoutJson defhlet (A.toJSON (Just r)) Error err -> do liftIO $ putStrLn err defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebLoggerInfo)) Fail _ ctxts err -> do liftIO $ putStrLn (concat ctxts++err) defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebLoggerInfo)) Partial _ -> do liftIO $ putStrLn "partial" defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebLoggerInfo))
wavewave/weblogger-server
lib/Application/WebLogger/Server/Yesod.hs
bsd-2-clause
3,032
0
22
755
718
374
344
63
4
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE UnboxedTuples #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Codec.Compression.Zlib.OutputWindow ( OutputWindow, emptyWindow, emitExcess, finalizeWindow, addByte, addChunk, addOldChunk, ) where import Control.Monad (foldM) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Short as SBS import Data.ByteString.Short.Internal (ShortByteString (SBS)) import qualified Data.Primitive as Prim import qualified Data.Vector.Primitive as V import qualified Data.Vector.Primitive.Mutable as MV import GHC.ST (ST (..)) import GHC.Word (Word8 (..)) windowSize :: Int windowSize = 128 * 1024 data OutputWindow s = OutputWindow { owWindow :: {-# UNPACK #-} !(MV.MVector s Word8) , owNext :: {-# UNPACK #-} !Int } emptyWindow :: ST s (OutputWindow s) emptyWindow = do window <- MV.new windowSize return (OutputWindow window 0) excessChunkSize :: Int excessChunkSize = 32768 emitExcess :: OutputWindow s -> ST s (Maybe (S.ByteString, OutputWindow s)) emitExcess OutputWindow{owWindow = window, owNext = initialOffset} | initialOffset < excessChunkSize * 2 = return Nothing | otherwise = do toEmit <- V.freeze $ MV.slice 0 excessChunkSize window let excessLength = initialOffset - excessChunkSize -- Need move as these can overlap! MV.move (MV.slice 0 excessLength window) (MV.slice excessChunkSize excessLength window) let ow' = OutputWindow window excessLength return (Just (SBS.fromShort $ toByteString toEmit, ow')) finalizeWindow :: OutputWindow s -> ST s S.ByteString finalizeWindow ow = do -- safe as we're doing it at the end res <- V.unsafeFreeze (MV.slice 0 (owNext ow) (owWindow ow)) pure $ SBS.fromShort $ toByteString res -- ----------------------------------------------------------------------------- addByte :: OutputWindow s -> Word8 -> ST s (OutputWindow s) addByte !ow !b = do let offset = owNext ow MV.write (owWindow ow) offset b return ow{owNext = offset + 1} addChunk :: OutputWindow s -> L.ByteString -> ST s (OutputWindow s) addChunk !ow !bs = foldM copyChunk ow (L.toChunks bs) copyChunk :: OutputWindow s -> S.ByteString -> ST s (OutputWindow s) copyChunk ow sbstr = do -- safe as we're never going to look at this again ba <- V.unsafeThaw $ fromByteString $ SBS.toShort sbstr let offset = owNext ow len = MV.length ba MV.copy (MV.slice offset len (owWindow ow)) ba return ow{owNext = offset + len} addOldChunk :: OutputWindow s -> Int -> Int -> ST s (OutputWindow s, S.ByteString) addOldChunk (OutputWindow window next) dist len = do -- zlib can ask us to copy an "old" chunk that extends past our current offset. -- The intention is that we then start copying the "new" data we just copied into -- place. 'copyChunked' handles this for us. copyChunked (MV.slice next len window) (MV.slice (next - dist) len window) dist result <- V.freeze $ MV.slice next len window return (OutputWindow window (next + len), SBS.fromShort $ toByteString result) {- | A copy function that copies the buffers sequentially in chunks no larger than the stated size. This allows us to handle the insane zlib behaviour. -} copyChunked :: MV.MVector s Word8 -> MV.MVector s Word8 -> Int -> ST s () copyChunked dest src chunkSize = go 0 (MV.length src) where go _ 0 = pure () go copied toCopy = do let thisChunkSize = min toCopy chunkSize MV.copy (MV.slice copied thisChunkSize dest) (MV.slice copied thisChunkSize src) go (copied + thisChunkSize) (toCopy - thisChunkSize) -- TODO: these are a bit questionable. Maybe we can just pass around Vector Word8 in the client code? fromByteString :: SBS.ShortByteString -> V.Vector Word8 fromByteString (SBS ba) = let len = Prim.sizeofByteArray (Prim.ByteArray ba) sz = Prim.sizeOf (undefined :: Word8) in V.Vector 0 (len * sz) (Prim.ByteArray ba) toByteString :: V.Vector Word8 -> SBS.ShortByteString toByteString (V.Vector offset len ba) = let sz = Prim.sizeOf (undefined :: Word8) !(Prim.ByteArray ba') = Prim.cloneByteArray ba (offset * sz) (len * sz) in SBS ba'
GaloisInc/pure-zlib
src/Codec/Compression/Zlib/OutputWindow.hs
bsd-3-clause
4,249
0
13
762
1,310
672
638
84
2
{-# LANGUAGE TupleSections #-} module Main where import Data.Vector.Unboxed as V hiding ((++)) import qualified Data.Vector.Unboxed.Mutable as VM import Data.Word import Data.Bits import qualified Data.List as L import qualified Data.ByteString as B import qualified Control.Monad.State.Strict as S import Control.Monad import Control.Applicative import Control.Monad.ST import System.Environment import Numeric import BinaryCode (setM, addM, subM, regA, regB, lit, binaryCode) import CommonTypes import EmuArgs main :: IO () main = do args <- emu16Args when (L.null $ binary args) $ error "No binary file given!" bs <- B.readFile (binary args) runDCPU (verbose args) $ dcpuFromByteString bs runSimpleTest :: IO () runSimpleTest = runDCPU True . dcpuFromList . binaryCode $ do setM regA (lit 0x1) addM regA (lit 0x2) setM regB (lit 0x2) subM regA regB runDCPU :: Bool -> DCPUData -> IO () runDCPU verbose dcpu = do dcpu' <- execStep verbose dcpu when verbose $ print dcpu' runDCPU verbose dcpu' execStep :: Bool -> DCPUData -> IO DCPUData execStep verbose dcpu = do let (instruc, dcpu') = S.runState readInstruction dcpu when verbose $ print instruc return $! S.execState (execInstruction instruc) dcpu' dcpuFromByteString :: B.ByteString -> DCPUData dcpuFromByteString binary = DCPUData {ram = initRam binary, regs = V.replicate numRegs 0, pc = 0, sp = stackBegin, ov = 0} where initRam = V.unfoldrN ramSize (\bs -> case B.length bs of l | l >= 2 -> do (loByte, bs' ) <- B.uncons bs (hiByte, bs'') <- B.uncons bs' let loWord = toW16 loByte hiWord = toW16 hiByte return (loWord .|. (hiWord .<<. 8), bs'') | l == 1 -> do (loByte, bs') <- B.uncons bs return (toW16 loByte, bs') | otherwise -> Just (0, bs)) dcpuFromList :: [Word16] -> DCPUData dcpuFromList binary = DCPUData {ram = initRam binary, regs = V.replicate numRegs 0, pc = 0, sp = stackBegin, ov = 0} where initRam = V.unfoldrN ramSize (\ls -> if L.null ls then Just (0, ls) else Just (L.head ls, L.tail ls)) execInstruction :: Instruction -> DCPU () execInstruction (BasicInstruction opcode (valA, locA) valB) | opcode <= XOR = do let (a, b) = (toW32 valA, toW32 valB) (res, ovf) = case opcode of SET -> (b, 0) ADD -> let r = a+b in (r, r .>>. 16) SUB -> let r = a-b in (r, r .>>. 16) MUL -> let r = a*b in (r, r .>>. 16) DIV -> if b == 0 then (0, 0) else let r = a `div` b in (r, (a .<<. 16) `div` b) MOD -> if b == 0 then (0, 0) else (a `mod` b, 0) SHL -> let r = a .<<. toInt b in (r, r .>>. 16) SHR -> let r = a .>>. toInt b in (r, (a .<<. 16) .>>. toInt b) AND -> (a .&. b, 0) BOR -> (a .|. b, 0) XOR -> (a `xor` b, 0) setValue (toW16 res) locA S.modify (\dcpu -> dcpu {ov = toW16 ovf}) | opcode == IFE = unless (valA == valB) $ void readInstruction | opcode == IFN = unless (valA /= valB) $ void readInstruction | opcode == IFG = unless (valA > valB) $ void readInstruction | opcode == IFB = unless (valA .&. valB /= 0) $ void readInstruction | otherwise = error "Unexpected case in execInstruction!" execInstruction (NonBasicInstruction opcode val) = case opcode of JSR -> S.modify (\dcpu -> let sp' = sp dcpu - 1 in dcpu {ram = set (ram dcpu) sp' (pc dcpu + 1), sp = sp', pc = val}) readInstruction :: DCPU Instruction readInstruction = do word <- readWord if word .&. 0xf == 0 then NonBasicInstruction (nonBasicOpcode $ valA word) . fst <$> readValue (valB word) else do a <- readValue $ valA word b <- fst <$> readValue (valB word) return $! BasicInstruction (opcode word) a b where valA = (.&. 0x3f) . (.>>. 4) valB = (.&. 0x3f) . (.>>. 10) readValue :: Word16 -> DCPU (Word16, Location) readValue word | word <= 0x07 = do let reg = toEnum $ fromIntegral word (, Register reg) <$> readRegister reg | word <= 0x0f = do let reg = toEnum $ fromIntegral (word - 0x08) addr <- readRegister reg (, RAM addr) <$> readRam addr | word <= 0x17 = do let reg = toEnum $ fromIntegral (word - 0x10) regVal <- readRegister reg nextWord <- readWord let addr = nextWord + regVal (, RAM addr) <$> readRam addr | word == 0x18 = S.state (\dcpu -> let sp_ = sp dcpu in ((get (ram dcpu) sp_, RAM sp_), dcpu {sp = sp_ + 1})) | word == 0x19 = S.gets (\dcpu -> let sp_ = sp dcpu in (get (ram dcpu) sp_, RAM sp_)) | word == 0x1a = S.state (\dcpu -> let sp' = sp dcpu - 1 in ((get (ram dcpu) sp', RAM sp'), dcpu {sp = sp'})) | word == 0x1b = (, SP) . sp <$> S.get | word == 0x1c = (, PC) . pc <$> S.get | word == 0x1d = (, O) . ov <$> S.get | word == 0x1e = readWord >>= \addr -> (, RAM addr) <$> readRam addr | word == 0x1f = (, Literal) <$> readWord | otherwise = return (word - 0x20, Literal) readWord :: DCPU Word16 readWord = do dcpu <- S.get let word = get (ram dcpu) (pc dcpu) S.put dcpu {pc = pc dcpu + 1} return $! word readRegister :: RegName -> DCPU Word16 readRegister reg = S.gets (\dcpu -> get (regs dcpu) (fromEnum reg)) readRam :: Word16 -> DCPU Word16 readRam addr = S.gets (\dcpu -> get (ram dcpu) addr) data Instruction = BasicInstruction Opcode (Value, Location) Value | NonBasicInstruction NonBasicOpcode Value instance Show Instruction where show (BasicInstruction opcode (valA, locA) valB) = "(BasicInstruction " ++ show opcode ++ " (" ++ showHex valA "" ++ ", " ++ show locA ++ ") " ++ showHex valB "" ++ ")" show (NonBasicInstruction opcode val) = "(NonBasicInstruction " ++ show opcode ++ " " ++ showHex val "" ++ ")" type Value = Word16 data Location = RAM Word16 | Register RegName | SP | PC | O | Literal instance Show Location where show (RAM addr) = "(RAM " ++ showHex addr "" ++ ")" show (Register name) = "(Register " ++ show name ++ ")" show SP = "SP" show PC = "PC" show O = "O" show Literal = "Literal" type DCPU = S.State DCPUData data DCPUData = DCPUData { ram :: ! (V.Vector Word16), -- ram regs :: ! (V.Vector Word16), -- registers pc :: ! Word16, -- program counter sp :: ! Word16, -- stack pointer ov :: ! Word16 -- overflow } instance Show DCPUData where show (DCPUData ram regs pc sp ov) = "DCPU: regs=" ++ V.foldl' (\str e -> (if str /= "[" then str ++ "," else str) ++ showHex e "") "[" regs ++ "]" ++ ", pc=" ++ showHex pc "" ++ ", sp=" ++ showHex sp "" ++ ", ov=" ++ showHex ov "" showRam f = V.foldl' foldRam ("ram:", 0) where foldRam (str, addr) cell = if f cell then (str ++ putCell addr cell, addr + 1) else (str, addr + 1) putCell addr cell = " [" ++ showHex addr "]=" ++ showHex cell "" ramSize = 0x10000 videoRam = (0x8000, 0x8400) numRegs = 8 stackBegin = 0xffff (.>>.), (.<<.) :: Bits a => a -> Int -> a (.>>.) = shiftR (.<<.) = shiftL setValue :: Word16 -> Location -> DCPU () setValue value (RAM addr) = S.modify (\dcpu -> dcpu {ram = set (ram dcpu) addr value}) setValue value (Register reg) = S.modify (\dcpu -> dcpu {regs = set (regs dcpu) (fromEnum reg) value}) setValue value PC = S.modify (\dcpu -> dcpu {pc = value}) setValue value SP = S.modify (\dcpu -> dcpu {sp = value}) setValue value O = S.modify (\dcpu -> dcpu {ov = value}) setValue value Literal = return () set :: Integral a => V.Vector Word16 -> a -> Word16 -> V.Vector Word16 set vector index value = runST (setM vector (fromIntegral index) value) where setM vec i val = do mVec <- V.unsafeThaw vec VM.write mVec i val V.unsafeFreeze mVec get :: Integral a => V.Vector Word16 -> a -> Word16 get vector index = vector ! fromIntegral index toInt :: Integral a => a -> Int toInt = fromIntegral toW32 :: Integral a => a -> Word32 toW32 = fromIntegral toW16 :: Integral a => a -> Word16 toW16 = fromIntegral
dan-t/dcpu16
Emulator.hs
bsd-3-clause
9,008
10
20
3,049
3,522
1,813
1,709
212
13
-- UUAGC 0.9.38.6 (./src/SistemaL.ag) module SistemaL where {-# LINE 3 "./src/SistemaL.ag" #-} import Data.List {-# LINE 9 "./src/SistemaL.hs" #-} {-# LINE 69 "./src/SistemaL.ag" #-} addIdentProds prods alfa = let prods' = map (\(Simbolo e,_) -> e) prods resto = alfa \\ prods' iprods = map (\e -> (Simbolo e, [Simbolo e])) resto in prods ++ iprods myElem _ [] = False myElem e1 ((Simbolo e2,_):xs) = if e1 == e2 then True else myElem e1 xs {-# LINE 23 "./src/SistemaL.hs" #-} {-# LINE 125 "./src/SistemaL.ag" #-} ejemplo1 = SistemaL "Koch" alfaK initK prodK alfaK = [Simbolo "F", Simbolo "f", Simbolo "+", Simbolo "-"] initK = [Simbolo "F", Simbolo "a"] prodK = [ (Simbolo "F", [Simbolo "F", Simbolo "g"]) , (Simbolo "F", []) ] ejemplo2 = SistemaL "Koch" alfaK2 initK2 prodK2 alfaK2 = [Simbolo "F", Simbolo "f", Simbolo "+", Simbolo "-"] initK2 = [Simbolo "F", Simbolo "f"] prodK2 = [ (Simbolo "F", [Simbolo "F", Simbolo "+"]) , (Simbolo "f", []) ] getNombre (SistemaL nm _ _ _) = nm testSistemaL :: SistemaL -> Either [String] SistemaL testSistemaL = sem_SistemaL {-# LINE 45 "./src/SistemaL.hs" #-} -- Alfabeto ---------------------------------------------------- type Alfabeto = [Simbolo ] -- cata sem_Alfabeto :: Alfabeto -> T_Alfabeto sem_Alfabeto list = (Prelude.foldr sem_Alfabeto_Cons sem_Alfabeto_Nil (Prelude.map sem_Simbolo list) ) -- semantic domain type T_Alfabeto = ([String]) -> ( ([String]),([String]),Alfabeto ) sem_Alfabeto_Cons :: T_Simbolo -> T_Alfabeto -> T_Alfabeto sem_Alfabeto_Cons hd_ tl_ = (\ _lhsIalf -> (let _tlOalf :: ([String]) _lhsOalf :: ([String]) _lhsOerrores :: ([String]) _lhsOself :: Alfabeto _hdIself :: Simbolo _hdIsimb :: String _tlIalf :: ([String]) _tlIerrores :: ([String]) _tlIself :: Alfabeto _verificar = ({-# LINE 31 "./src/SistemaL.ag" #-} elem _hdIsimb _lhsIalf {-# LINE 73 "./src/SistemaL.hs" #-} ) _tlOalf = ({-# LINE 32 "./src/SistemaL.ag" #-} if _verificar then _lhsIalf else _hdIsimb : _lhsIalf {-# LINE 80 "./src/SistemaL.hs" #-} ) _lhsOalf = ({-# LINE 35 "./src/SistemaL.ag" #-} _tlIalf {-# LINE 85 "./src/SistemaL.hs" #-} ) _lhsOerrores = ({-# LINE 93 "./src/SistemaL.ag" #-} if _verificar then ("El simbolo: '" ++ _hdIsimb ++ "' esta repetido mas de una ves en el alfabeto.") : _tlIerrores else _tlIerrores {-# LINE 92 "./src/SistemaL.hs" #-} ) _self = ({-# LINE 57 "./src/SistemaL.ag" #-} (:) _hdIself _tlIself {-# LINE 97 "./src/SistemaL.hs" #-} ) _lhsOself = ({-# LINE 57 "./src/SistemaL.ag" #-} _self {-# LINE 102 "./src/SistemaL.hs" #-} ) ( _hdIself,_hdIsimb) = hd_ ( _tlIalf,_tlIerrores,_tlIself) = tl_ _tlOalf in ( _lhsOalf,_lhsOerrores,_lhsOself))) sem_Alfabeto_Nil :: T_Alfabeto sem_Alfabeto_Nil = (\ _lhsIalf -> (let _lhsOalf :: ([String]) _lhsOerrores :: ([String]) _lhsOself :: Alfabeto _lhsOalf = ({-# LINE 36 "./src/SistemaL.ag" #-} _lhsIalf {-# LINE 118 "./src/SistemaL.hs" #-} ) _lhsOerrores = ({-# LINE 96 "./src/SistemaL.ag" #-} [] {-# LINE 123 "./src/SistemaL.hs" #-} ) _self = ({-# LINE 57 "./src/SistemaL.ag" #-} [] {-# LINE 128 "./src/SistemaL.hs" #-} ) _lhsOself = ({-# LINE 57 "./src/SistemaL.ag" #-} _self {-# LINE 133 "./src/SistemaL.hs" #-} ) in ( _lhsOalf,_lhsOerrores,_lhsOself))) -- Inicio ------------------------------------------------------ type Inicio = [Simbolo ] -- cata sem_Inicio :: Inicio -> T_Inicio sem_Inicio list = (Prelude.foldr sem_Inicio_Cons sem_Inicio_Nil (Prelude.map sem_Simbolo list) ) -- semantic domain type T_Inicio = ([String]) -> ( ([String]),Inicio ) sem_Inicio_Cons :: T_Simbolo -> T_Inicio -> T_Inicio sem_Inicio_Cons hd_ tl_ = (\ _lhsIalfabeto -> (let _lhsOerrores :: ([String]) _lhsOself :: Inicio _tlOalfabeto :: ([String]) _hdIself :: Simbolo _hdIsimb :: String _tlIerrores :: ([String]) _tlIself :: Inicio _lhsOerrores = ({-# LINE 99 "./src/SistemaL.ag" #-} if elem _hdIsimb _lhsIalfabeto then _tlIerrores else ("El simbolo de inicio: '" ++ _hdIsimb ++ "' no se encuentra en el alfabeto.") : _tlIerrores {-# LINE 163 "./src/SistemaL.hs" #-} ) _self = ({-# LINE 57 "./src/SistemaL.ag" #-} (:) _hdIself _tlIself {-# LINE 168 "./src/SistemaL.hs" #-} ) _lhsOself = ({-# LINE 57 "./src/SistemaL.ag" #-} _self {-# LINE 173 "./src/SistemaL.hs" #-} ) _tlOalfabeto = ({-# LINE 39 "./src/SistemaL.ag" #-} _lhsIalfabeto {-# LINE 178 "./src/SistemaL.hs" #-} ) ( _hdIself,_hdIsimb) = hd_ ( _tlIerrores,_tlIself) = tl_ _tlOalfabeto in ( _lhsOerrores,_lhsOself))) sem_Inicio_Nil :: T_Inicio sem_Inicio_Nil = (\ _lhsIalfabeto -> (let _lhsOerrores :: ([String]) _lhsOself :: Inicio _lhsOerrores = ({-# LINE 102 "./src/SistemaL.ag" #-} [] {-# LINE 193 "./src/SistemaL.hs" #-} ) _self = ({-# LINE 57 "./src/SistemaL.ag" #-} [] {-# LINE 198 "./src/SistemaL.hs" #-} ) _lhsOself = ({-# LINE 57 "./src/SistemaL.ag" #-} _self {-# LINE 203 "./src/SistemaL.hs" #-} ) in ( _lhsOerrores,_lhsOself))) -- Produccion -------------------------------------------------- type Produccion = ( Simbolo ,Succesor ) -- cata sem_Produccion :: Produccion -> T_Produccion sem_Produccion ( x1,x2) = (sem_Produccion_Tuple (sem_Simbolo x1 ) (sem_Succesor x2 ) ) -- semantic domain type T_Produccion = ([String]) -> ( ([String]),Produccion ,String) sem_Produccion_Tuple :: T_Simbolo -> T_Succesor -> T_Produccion sem_Produccion_Tuple x1_ x2_ = (\ _lhsIalfabeto -> (let _lhsOerrores :: ([String]) _lhsOself :: Produccion _lhsOsimb :: String _x2Oalfabeto :: ([String]) _x1Iself :: Simbolo _x1Isimb :: String _x2Ierrores :: ([String]) _x2Iself :: Succesor _lhsOerrores = ({-# LINE 114 "./src/SistemaL.ag" #-} if elem _x1Isimb _lhsIalfabeto then _x2Ierrores else ("El simbolo de la produccion (izq): '" ++ _x1Isimb ++ "' no se encuentra en el alfabeto.") : _x2Ierrores {-# LINE 234 "./src/SistemaL.hs" #-} ) _self = ({-# LINE 57 "./src/SistemaL.ag" #-} (_x1Iself,_x2Iself) {-# LINE 239 "./src/SistemaL.hs" #-} ) _lhsOself = ({-# LINE 57 "./src/SistemaL.ag" #-} _self {-# LINE 244 "./src/SistemaL.hs" #-} ) _lhsOsimb = ({-# LINE 45 "./src/SistemaL.ag" #-} _x1Isimb {-# LINE 249 "./src/SistemaL.hs" #-} ) _x2Oalfabeto = ({-# LINE 39 "./src/SistemaL.ag" #-} _lhsIalfabeto {-# LINE 254 "./src/SistemaL.hs" #-} ) ( _x1Iself,_x1Isimb) = x1_ ( _x2Ierrores,_x2Iself) = x2_ _x2Oalfabeto in ( _lhsOerrores,_lhsOself,_lhsOsimb))) -- Producciones ------------------------------------------------ type Producciones = [Produccion ] -- cata sem_Producciones :: Producciones -> T_Producciones sem_Producciones list = (Prelude.foldr sem_Producciones_Cons sem_Producciones_Nil (Prelude.map sem_Produccion list) ) -- semantic domain type T_Producciones = ([String]) -> Producciones -> ( ([String]),Producciones) sem_Producciones_Cons :: T_Produccion -> T_Producciones -> T_Producciones sem_Producciones_Cons hd_ tl_ = (\ _lhsIalfabeto _lhsIprods -> (let _tlOprods :: Producciones _lhsOprods :: Producciones _lhsOerrores :: ([String]) _hdOalfabeto :: ([String]) _tlOalfabeto :: ([String]) _hdIerrores :: ([String]) _hdIself :: Produccion _hdIsimb :: String _tlIerrores :: ([String]) _tlIprods :: Producciones _verificar = ({-# LINE 60 "./src/SistemaL.ag" #-} myElem _hdIsimb _lhsIprods {-# LINE 291 "./src/SistemaL.hs" #-} ) _tlOprods = ({-# LINE 61 "./src/SistemaL.ag" #-} if _verificar then _lhsIprods else _hdIself : _lhsIprods {-# LINE 298 "./src/SistemaL.hs" #-} ) _lhsOprods = ({-# LINE 64 "./src/SistemaL.ag" #-} _tlIprods {-# LINE 303 "./src/SistemaL.hs" #-} ) _lhsOerrores = ({-# LINE 105 "./src/SistemaL.ag" #-} if _verificar then let error = "La produccion con el simb. izq.:'" ++ _hdIsimb ++ "' esta repetida mas de una ves en la lista de producciones." in (error : _hdIerrores) ++ _tlIerrores else _hdIerrores ++ _tlIerrores {-# LINE 313 "./src/SistemaL.hs" #-} ) _hdOalfabeto = ({-# LINE 39 "./src/SistemaL.ag" #-} _lhsIalfabeto {-# LINE 318 "./src/SistemaL.hs" #-} ) _tlOalfabeto = ({-# LINE 39 "./src/SistemaL.ag" #-} _lhsIalfabeto {-# LINE 323 "./src/SistemaL.hs" #-} ) ( _hdIerrores,_hdIself,_hdIsimb) = hd_ _hdOalfabeto ( _tlIerrores,_tlIprods) = tl_ _tlOalfabeto _tlOprods in ( _lhsOerrores,_lhsOprods))) sem_Producciones_Nil :: T_Producciones sem_Producciones_Nil = (\ _lhsIalfabeto _lhsIprods -> (let _lhsOerrores :: ([String]) _lhsOprods :: Producciones _lhsOerrores = ({-# LINE 111 "./src/SistemaL.ag" #-} [] {-# LINE 339 "./src/SistemaL.hs" #-} ) _lhsOprods = ({-# LINE 58 "./src/SistemaL.ag" #-} _lhsIprods {-# LINE 344 "./src/SistemaL.hs" #-} ) in ( _lhsOerrores,_lhsOprods))) -- Simbolo ----------------------------------------------------- data Simbolo = Simbolo (String) deriving ( Eq,Show) -- cata sem_Simbolo :: Simbolo -> T_Simbolo sem_Simbolo (Simbolo _string ) = (sem_Simbolo_Simbolo _string ) -- semantic domain type T_Simbolo = ( Simbolo ,String) sem_Simbolo_Simbolo :: String -> T_Simbolo sem_Simbolo_Simbolo string_ = (let _lhsOsimb :: String _lhsOself :: Simbolo _lhsOsimb = ({-# LINE 47 "./src/SistemaL.ag" #-} string_ {-# LINE 365 "./src/SistemaL.hs" #-} ) _self = ({-# LINE 57 "./src/SistemaL.ag" #-} Simbolo string_ {-# LINE 370 "./src/SistemaL.hs" #-} ) _lhsOself = ({-# LINE 57 "./src/SistemaL.ag" #-} _self {-# LINE 375 "./src/SistemaL.hs" #-} ) in ( _lhsOself,_lhsOsimb)) -- SistemaL ---------------------------------------------------- data SistemaL = SistemaL (String) (Alfabeto ) (Inicio ) (Producciones ) deriving ( Show) -- cata sem_SistemaL :: SistemaL -> T_SistemaL sem_SistemaL (SistemaL _nombre _alfabeto _inicio _producciones ) = (sem_SistemaL_SistemaL _nombre (sem_Alfabeto _alfabeto ) (sem_Inicio _inicio ) (sem_Producciones _producciones ) ) -- semantic domain type T_SistemaL = ( (Either [String] SistemaL)) sem_SistemaL_SistemaL :: String -> T_Alfabeto -> T_Inicio -> T_Producciones -> T_SistemaL sem_SistemaL_SistemaL nombre_ alfabeto_ inicio_ producciones_ = (let _alfabetoOalf :: ([String]) _inicioOalfabeto :: ([String]) _produccionesOalfabeto :: ([String]) _lhsOresultado :: (Either [String] SistemaL) _produccionesOprods :: Producciones _alfabetoIalf :: ([String]) _alfabetoIerrores :: ([String]) _alfabetoIself :: Alfabeto _inicioIerrores :: ([String]) _inicioIself :: Inicio _produccionesIerrores :: ([String]) _produccionesIprods :: Producciones _alfabetoOalf = ({-# LINE 28 "./src/SistemaL.ag" #-} [] {-# LINE 409 "./src/SistemaL.hs" #-} ) _inicioOalfabeto = ({-# LINE 41 "./src/SistemaL.ag" #-} _alfabetoIalf {-# LINE 414 "./src/SistemaL.hs" #-} ) _produccionesOalfabeto = ({-# LINE 42 "./src/SistemaL.ag" #-} _alfabetoIalf {-# LINE 419 "./src/SistemaL.hs" #-} ) _lhsOresultado = ({-# LINE 52 "./src/SistemaL.ag" #-} if null _errores then let producciones = addIdentProds _produccionesIprods _alfabetoIalf in Right (SistemaL nombre_ _alfabetoIself _inicioIself producciones) else Left _errores {-# LINE 427 "./src/SistemaL.hs" #-} ) _produccionesOprods = ({-# LINE 67 "./src/SistemaL.ag" #-} [] {-# LINE 432 "./src/SistemaL.hs" #-} ) _errores = ({-# LINE 85 "./src/SistemaL.ag" #-} let inicioErr = if null _inicioIself then "La lista de simbolos de inicio no puede ser vacia" : _inicioIerrores else _inicioIerrores errores = map (\err -> nombre_ ++ ": " ++ err) (_alfabetoIerrores ++ inicioErr ++ _produccionesIerrores) in errores {-# LINE 441 "./src/SistemaL.hs" #-} ) ( _alfabetoIalf,_alfabetoIerrores,_alfabetoIself) = alfabeto_ _alfabetoOalf ( _inicioIerrores,_inicioIself) = inicio_ _inicioOalfabeto ( _produccionesIerrores,_produccionesIprods) = producciones_ _produccionesOalfabeto _produccionesOprods in ( _lhsOresultado)) -- Succesor ---------------------------------------------------- type Succesor = [Simbolo ] -- cata sem_Succesor :: Succesor -> T_Succesor sem_Succesor list = (Prelude.foldr sem_Succesor_Cons sem_Succesor_Nil (Prelude.map sem_Simbolo list) ) -- semantic domain type T_Succesor = ([String]) -> ( ([String]),Succesor ) sem_Succesor_Cons :: T_Simbolo -> T_Succesor -> T_Succesor sem_Succesor_Cons hd_ tl_ = (\ _lhsIalfabeto -> (let _lhsOerrores :: ([String]) _lhsOself :: Succesor _tlOalfabeto :: ([String]) _hdIself :: Simbolo _hdIsimb :: String _tlIerrores :: ([String]) _tlIself :: Succesor _lhsOerrores = ({-# LINE 119 "./src/SistemaL.ag" #-} if elem _hdIsimb _lhsIalfabeto then _tlIerrores else ("El simbolo de la produccion (der): '" ++ _hdIsimb ++ "' no se encuentra en el alfabeto.") : _tlIerrores {-# LINE 477 "./src/SistemaL.hs" #-} ) _self = ({-# LINE 57 "./src/SistemaL.ag" #-} (:) _hdIself _tlIself {-# LINE 482 "./src/SistemaL.hs" #-} ) _lhsOself = ({-# LINE 57 "./src/SistemaL.ag" #-} _self {-# LINE 487 "./src/SistemaL.hs" #-} ) _tlOalfabeto = ({-# LINE 39 "./src/SistemaL.ag" #-} _lhsIalfabeto {-# LINE 492 "./src/SistemaL.hs" #-} ) ( _hdIself,_hdIsimb) = hd_ ( _tlIerrores,_tlIself) = tl_ _tlOalfabeto in ( _lhsOerrores,_lhsOself))) sem_Succesor_Nil :: T_Succesor sem_Succesor_Nil = (\ _lhsIalfabeto -> (let _lhsOerrores :: ([String]) _lhsOself :: Succesor _lhsOerrores = ({-# LINE 122 "./src/SistemaL.ag" #-} [] {-# LINE 507 "./src/SistemaL.hs" #-} ) _self = ({-# LINE 57 "./src/SistemaL.ag" #-} [] {-# LINE 512 "./src/SistemaL.hs" #-} ) _lhsOself = ({-# LINE 57 "./src/SistemaL.ag" #-} _self {-# LINE 517 "./src/SistemaL.hs" #-} ) in ( _lhsOerrores,_lhsOself)))
carliros/lsystem
src/SistemaL.hs
bsd-3-clause
19,601
0
19
8,305
2,975
1,755
1,220
385
3
{-# LANGUAGE ScopedTypeVariables #-} -- © 2006 Peter Thiemann {- | Transactional, type-indexed implementation of server-side state. Glossary A transactional entity (TE) is a named multi-versioned global variable. -} module WASH.CGI.Transaction ( T (), init, create, remove, get, set, with, Control (..), TCGI () ) where import qualified WASH.CGI.BaseCombinators as B import qualified WASH.CGI.CGIConfig as Conf import WASH.CGI.CGIMonad import WASH.CGI.CGI hiding (head, div, span, map) import WASH.CGI.TCGI (TCGI) import qualified WASH.CGI.TransactionUtil as TU import WASH.CGI.TransactionUtil (Control (..)) import WASH.CGI.LogEntry import WASH.CGI.MakeTypedName import WASH.CGI.Types import qualified WASH.CGI.HTMLWrapper as H hiding (map,head) import qualified WASH.Utility.Auxiliary as Aux import qualified WASH.Utility.Locking as L import qualified WASH.Utility.Unique as Unique import qualified Data.List as List import System.Directory import System.IO import Control.Exception import Control.Monad import Data.Maybe (isNothing) import Prelude hiding (init) transactionLock = Conf.transactionDir -- |Handle of a transactional variable newtype T a = T String deriving (Read, Show) -- |Attempt to create a new tv @n@ and set its initial value. Returns handle to -- the variable. If the variable already exists, then just returns the handle. init :: (Types a, Read a, Show a) => String -> a -> TCGI b (T a) init name val = let v = show val typedName = makeTypedNameFromVal name val h = T typedName in wrapCGI (\ cgistate -> case inparm cgistate of [] -> -- first time here do Aux.assertDirectoryExists (List.init Conf.transactionDir) (return ()) -- must try to read the variable at this point -- because it may only exist in the log let out = outparm cgistate ev <- try (readValue out typedName) let newparm = case ev of Left (_ :: SomeException) -> -- value did not exist (but don't write it now) PAR_CRE_TV typedName v Right (v', cached) -> -- value did exist (although we have not read its value) PAR_GET_TV typedName v' return (h, cgistate { outparm = newparm : out }) PAR_CRE_TV _ _ : rest -> -- created the variable return (h, cgistate { inparm = rest }) PAR_GET_TV _ _ : rest -> -- touched existing variable return (h, cgistate { inparm = rest }) le : rest -> error ("Transaction.init: got log entry " ++ show le ++ ". This should not happen") ) -- |Read transactional variable through a typed handle. get :: (Read a, Show a) => T a -> TCGI b a get (T typedName) = wrapCGI (\ cgistate -> case inparm cgistate of [] -> -- check the log for preceding reads and writes; -- then fall back to physical read let out = outparm cgistate in do (v, cached) <- readValue out typedName let newparm | cached = PAR_RESULT v | otherwise = PAR_GET_TV typedName v return (read v, cgistate { outparm = newparm : out }) PAR_GET_TV _ v : rest -> return (read v, cgistate { inparm = rest }) PAR_RESULT v : rest -> return (read v, cgistate { inparm = rest }) _ -> error "Transaction.get: this should not happen" ) -- |Write to a transactional variable through typed handle. Only affects the -- log, no /physical/ write happens. Checks physically for existence of the -- variable (but tries the log first). Raises exception if it does not exist. set :: (Read a, Show a) => T a -> a -> TCGI b () set (T typedName) val = let v = show val in wrapCGI (\ cgistate -> case inparm cgistate of [] -> do let newparm = PAR_SET_TV typedName v out = outparm cgistate readValue out typedName -- must not fail return ((), cgistate { outparm = newparm : outparm cgistate }) PAR_SET_TV _ _ : rest -> return ((), cgistate { inparm = rest }) _ -> error "Transaction.set: this should not happen" ) -- |Create a fresh transactional variable with an initial value and return its -- handle. Performs a physical write to ensure that the variable's name is -- unique. Locks the transaction directory during the write operation. create :: (Read a, Show a, Types a) => a -> TCGI b (T a) create val = let v = show val obtainUniqueHandle = do name <- Unique.inventStdKey let typedName = makeTypedNameFromVal name val h = T typedName L.obtainLock transactionLock conflict <- reallyExists typedName unless conflict $ reallyWrite typedName v L.releaseLock transactionLock if conflict then obtainUniqueHandle else return h in do wrapCGI $ \ cgistate -> case inparm cgistate of [] -> do Aux.assertDirectoryExists (List.init Conf.transactionDir) (return ()) h@(T typedName) <- obtainUniqueHandle return (h, cgistate { outparm = PAR_CRE_TV typedName v : outparm cgistate }) PAR_CRE_TV typedName _ : rest -> return (T typedName, cgistate { inparm = rest }) _ -> error "Transaction.create: this should not happen" -- |Remove a transactional variable. Subsequent read accesses to this variable -- will make the transaction fail. May throw an exception if the variable is not -- present. remove :: (Types a) => T a -> TCGI b () remove (T typedName) = wrapCGI (\ cgistate -> case inparm cgistate of [] -> -- check that the variable exists -- will raise an exception otherwise let out = outparm cgistate in do readValue out typedName return ((), cgistate { outparm = PAR_REM_TV typedName : out }) PAR_REM_TV _ : rest -> return ((), cgistate { inparm = rest }) _ -> error "Transaction.remove: this should not happen" ) -- | @with@ creates a transactional scope in which transactional variables can -- be manipulated. Transactions may be nested to an arbitrary depth, although a -- check with the current state of the world only occurs at the point where the -- top-level transaction tries to commit. -- -- @with@ takes three parameters, a default value of type @result@, a -- continuation, and a body function that maps a @Control@ record to a -- transactional computation. There are three ways in which a -- transaction may be completed. First, the transaction may be abandoned -- explicitly by a call to the @abandon@ function supplied as part of the -- @Control@ record. In this case, the continuation is invoked on a pre-set -- failure return value. Second, the transaction body runs to completion but -- fails to commit. In this case, the continuation is also invoked on the -- pre-set failure return value. Third, the transaction body runs to completion -- and commits successfully. In this case, the continuation is invoked, but on -- the pre-set success value. -- The @result@-type argument initializes the default return value for both, the -- success and the failure case. The body function implements the body of the -- transaction. -- class CGIMonad cgi => WithMonad cgi where with :: (Read result, Show result) => result -> (result -> cgi ()) -> (TU.Control (TCGI result) result -> (TCGI result) ()) -> cgi () instance WithMonad CGI where with result onResult fun = TU.withCGI commitFromLog result onResult fun instance WithMonad (TCGI x) where -- !!! needs to be checked !!! with result onResult fun = TU.withTCGI (const $ return True) result onResult fun -- |Read value of a variable first from log prefix. Return value @True@ -- indicates a value from the log, @False@ indicates a value read from file. May -- raise an exception if the variable has been removed. readValue :: [PARAMETER] -> String -> IO (String, Bool) readValue [] n = do v' <- reallyRead n return (v', False) readValue (PAR_SET_TV n' v':rest) n = if n==n' then return (v', True) -- has been overwritten else readValue rest n readValue (PAR_GET_TV n' v':rest) n = if n==n' then return (v', True) -- read before else readValue rest n readValue (PAR_CRE_TV n' v':rest) n = if n==n' then return (v', True) else readValue rest n readValue (PAR_REM_TV n':rest) n = if n==n' then fail ("Transactional variable " ++ n ++ " has vanished") else readValue rest n readValue (PAR_TRANS stid:rest) n = do v' <- reallyRead n return (v', False) readValue (_:rest) n = readValue rest n -- |Descriptor of a transactional variable. data TV_DESC = TV_DESC { tv_name :: String -- ^ variable name , tv_old :: Maybe (Maybe String) -- ^ value on first read -- @Nothing@ if not read -- @Just Nothing@ if created -- @Just (Just val)@ first value , tv_new :: Maybe (Maybe String) -- ^ value after last write -- @Nothing@ if not written to -- @Just Nothing@ if removed -- @Just (Just val)@ if @val@ was written } deriving Show -- |Obtain list of descriptors of transaction variables from a list of log -- entries. Each variable has at most one descriptor. Input list is in reverse -- chronological order, /e.g./, the earliest entries come last. getDescriptors :: [PARAMETER] -> [TV_DESC] getDescriptors logEntries = foldr f [] logEntries where f (PAR_GET_TV n v) r = doRead n v r f (PAR_SET_TV n v) r = doWrite n v r f (PAR_CRE_TV n v) r = doCreate n v r f (PAR_REM_TV n) r = doRemove n r f _ r = r doCreate n v ds = TV_DESC {tv_name = n, tv_old = Just Nothing, tv_new = Just (Just v)} : ds doRemove n ds = doProcess g n ds where g (TV_DESC { tv_old = Just Nothing } : rest) = rest g (tvd : rest) = tvd { tv_new = Just Nothing } : rest g [] = [TV_DESC {tv_name = n, tv_old = Nothing, tv_new = Just Nothing}] doProcess g n ds = f ds where f [] = g [] f ds@(d':ds') = if tv_name d' == n then g ds else d' : f ds' doRead n v ds = doProcess h n ds where h [] = [TV_DESC {tv_name = n, tv_old = Just (Just v), tv_new = Nothing }] h (tvd : rest) = tvd : rest -- not first read doWrite n v ds = doProcess h n ds where h [] = [TV_DESC {tv_name = n, tv_old = Nothing, tv_new = Just (Just v) }] h (tvd : rest) = tvd { tv_new = Just (Just v) } : rest -- do write -- | Get the descriptors and try to commit commitFromLog :: [PARAMETER] -> IO Bool commitFromLog = tryToCommit . getDescriptors -- |Attempt to commit a list of descriptors by checking for the old values to -- match and then overwriting with the new values. A read-only transaction -- always succeeds, even if the values have changed after they have been -- read. Returns @True@ if commit succeeded. tryToCommit :: [TV_DESC] -> IO Bool tryToCommit ds = if checkOnlyReads ds then return True else do L.obtainLock transactionLock oldValuesPreserved <- checkOldValuesPreserved ds when oldValuesPreserved (writeNewValues ds) L.releaseLock transactionLock return oldValuesPreserved -- |Check if the values of all transactional variable in a list of descriptors -- match the current values. Called with all variables locked. checkOldValuesPreserved :: [TV_DESC] -> IO Bool checkOldValuesPreserved [] = return True checkOldValuesPreserved (d:ds) = do b <- checkOldValuePreserved d if b then checkOldValuesPreserved ds else return False checkOldValuePreserved :: TV_DESC -> IO Bool checkOldValuePreserved d = do let n = tv_name d varExists <- reallyExists n case tv_old d of Nothing -> -- not read, check for presence return varExists Just Nothing -> -- created, check that it does *not* exist now return (not varExists) Just (Just ov) -> -- read old value @ov@ if varExists then -- value is still present; check if equal do cv <- reallyRead n return (cv == ov) else -- value has disappeared: fail return False -- |Overwrite transactional variables from a list of descriptors with new values. writeNewValues :: [TV_DESC] -> IO () writeNewValues ds = mapM_ g ds where g d = let n = tv_name d in case tv_new d of Nothing -> -- not written return () Just Nothing -> -- removed reallyRemove n Just (Just nv) -> -- new value reallyWrite n nv -- |Check that no variable has been written to. checkOnlyReads :: [TV_DESC] -> Bool checkOnlyReads ds = and (map wasNotWritten ds) where wasNotWritten d = isNothing (tv_new d) -- |Physically access current shared value of transactional variable. Internal -- use only. reallyRead :: String -> IO String reallyRead n = let fileName = Conf.transactionDir ++ n in Aux.readFileStrictly fileName -- |Physically overwrite current shared value of transactional variable. reallyWrite :: String -> String -> IO () reallyWrite n v = let fileName = Conf.transactionDir ++ n in writeFile fileName v -- |Physically checks the existence of a transactional variable. reallyExists :: String -> IO Bool reallyExists n = let fileName = Conf.transactionDir ++ n in doesFileExist fileName -- |Physically remove transactional variable. reallyRemove :: String -> IO () reallyRemove n = let fileName = Conf.transactionDir ++ n in removeFile fileName
nh2/WashNGo
WASH/CGI/Transaction.hs
bsd-3-clause
13,274
273
13
3,169
2,633
1,619
1,014
270
11
{-# LANGUAGE TemplateHaskell #-} module Snap.StarterTH where ------------------------------------------------------------------------------ import qualified Data.Foldable as F import Data.List import Language.Haskell.TH import Language.Haskell.TH.Syntax import System.Directory.Tree ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Convenience types type FileData = (String, String) type DirData = FilePath ------------------------------------------------------------------------------ -- Gets all the directorys in a DirTree getDirs :: [FilePath] -> DirTree a -> [FilePath] getDirs prefix (Dir n c) = (intercalate "/" (reverse (n:prefix))) : concatMap (getDirs (n:prefix)) c getDirs _ (File _ _) = [] getDirs _ (Failed _ _) = [] ------------------------------------------------------------------------------ -- Reads a directory and returns a tuple of the list of all directories -- encountered and a list of filenames and content strings. readTree :: FilePath -> IO ([DirData], [FileData]) readTree dir = do d <- readDirectory $ dir ++ "/." let ps = zipPaths $ "" :/ (free d) fd = F.foldr (:) [] ps dirs = tail . getDirs [] $ free d return (dirs, fd) ------------------------------------------------------------------------------ -- Calls readTree and returns it's value in a quasiquote. dirQ :: FilePath -> Q Exp dirQ tplDir = do d <- runIO . readTree $ "project_template/" ++ tplDir lift d ------------------------------------------------------------------------------ -- Creates a declaration assigning the specified name the value returned by -- dirQ. buildData :: String -> FilePath -> Q [Dec] buildData dirName tplDir = do let dir = mkName dirName typeSig <- SigD dir `fmap` [t| ([String], [(String, String)]) |] v <- valD (varP dir) (normalB $ dirQ tplDir) [] return [typeSig, v]
janrain/snap
src/Snap/StarterTH.hs
bsd-3-clause
2,006
0
13
344
465
252
213
30
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.GHC -- Copyright : Isaac Jones 2003-2007 -- -- Maintainer : [email protected] -- Portability : portable -- -- This is a fairly large module. It contains most of the GHC-specific code for -- configuring, building and installing packages. It also exports a function -- for finding out what packages are already installed. Configuring involves -- finding the @ghc@ and @ghc-pkg@ programs, finding what language extensions -- this version of ghc supports and returning a 'Compiler' value. -- -- 'getInstalledPackages' involves calling the @ghc-pkg@ program to find out -- what packages are installed. -- -- Building is somewhat complex as there is quite a bit of information to take -- into account. We have to build libs and programs, possibly for profiling and -- shared libs. We have to support building libraries that will be usable by -- GHCi and also ghc's @-split-objs@ feature. We have to compile any C files -- using ghc. Linking, especially for @split-objs@ is remarkably complex, -- partly because there tend to be 1,000's of @.o@ files and this can often be -- more than we can pass to the @ld@ or @ar@ programs in one go. -- -- Installing for libs and exes involves finding the right files and copying -- them to the right places. One of the more tricky things about this module is -- remembering the layout of files in the build directory (which is not -- explicitly documented) and thus what search dirs are used for various kinds -- of files. {- Copyright (c) 2003-2005, Isaac Jones All rights reserved. Redistribution and use in source and binary forms, with or without modiication, 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. * Neither the name of Isaac Jones nor the names of other contributors may 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. -} module Distribution.Simple.GHC ( configure, getInstalledPackages, buildLib, buildExe, buildApp, installLib, installExe, libAbiHash, registerPackage, ghcOptions, ghcVerbosityOptions, ghcPackageDbOptions, ghcLibDir, ) where import Distribution.PackageDescription as PD ( PackageDescription(..), BuildInfo(..), Executable(..), App(..) , Library(..), libModules, hcOptions, allExtensions , ObjcGCMode(..) ) import Distribution.InstalledPackageInfo ( InstalledPackageInfo ) import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo ( InstalledPackageInfo_(..) ) import Distribution.Simple.CCompiler ( cSourceExtensions ) import Distribution.Simple.PackageIndex (PackageIndex) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), ComponentLocalBuildInfo(..) , absoluteInstallDirs ) import Distribution.Simple.InstallDirs hiding ( absoluteInstallDirs ) import Distribution.Simple.BuildPaths import Distribution.Simple.Utils import Distribution.Package ( PackageIdentifier, Package(..), PackageName(..) ) import qualified Distribution.ModuleName as ModuleName import Distribution.Simple.Program ( Program(..), ConfiguredProgram(..), ProgramConfiguration, ProgArg , ProgramLocation(..), rawSystemProgram, rawSystemProgramConf , rawSystemProgramStdout, rawSystemProgramStdoutConf , requireProgramVersion, requireProgram, runProgram, getProgramOutput , userMaybeSpecifyPath, programPath, lookupProgram, addKnownProgram , ghcProgram, ghcPkgProgram, hsc2hsProgram , arProgram, ranlibProgram, ldProgram , gccProgram, stripProgram, touchProgram, ibtoolProgram ) import qualified Distribution.Simple.Program.HcPkg as HcPkg import qualified Distribution.Simple.Program.Ar as Ar import qualified Distribution.Simple.Program.Ld as Ld import Distribution.Simple.Compiler ( CompilerFlavor(..), CompilerId(..), Compiler(..), compilerVersion , OptimisationLevel(..), PackageDB(..), PackageDBStack , Flag, languageToFlags, extensionsToFlags ) import Distribution.Version ( Version(..), anyVersion, orLaterVersion ) import Distribution.System ( OS(..), buildOS ) import Distribution.Verbosity import Distribution.Text ( display, simpleParse ) import Language.Haskell.Extension (Language(..), Extension(..), KnownExtension(..)) import Control.Monad ( unless, when, liftM ) import Data.Char ( isSpace ) import Data.List import Data.Maybe ( catMaybes ) import Data.Monoid ( Monoid(..) ) import System.Directory ( removeFile, getDirectoryContents, doesFileExist , getTemporaryDirectory ) import System.FilePath ( (</>), (<.>), takeExtension, takeDirectory, replaceExtension, splitExtension ) import System.IO (hClose, hPutStrLn) import Distribution.Compat.Exception (catchExit, catchIO) import Distribution.Compat.Filesystem.Posix ( removeDirectoryRecursiveVerbose ) -- ----------------------------------------------------------------------------- -- Configuring configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramConfiguration -> IO (Compiler, ProgramConfiguration) configure verbosity hcPath hcPkgPath conf0 = do (ghcProg, ghcVersion, conf1) <- requireProgramVersion verbosity ghcProgram (orLaterVersion (Version [6,4] [])) (userMaybeSpecifyPath "ghc" hcPath conf0) -- This is slightly tricky, we have to configure ghc first, then we use the -- location of ghc to help find ghc-pkg in the case that the user did not -- specify the location of ghc-pkg directly: (ghcPkgProg, ghcPkgVersion, conf2) <- requireProgramVersion verbosity ghcPkgProgram { programFindLocation = guessGhcPkgFromGhcPath ghcProg } anyVersion (userMaybeSpecifyPath "ghc-pkg" hcPkgPath conf1) when (ghcVersion /= ghcPkgVersion) $ die $ "Version mismatch between ghc and ghc-pkg: " ++ programPath ghcProg ++ " is version " ++ display ghcVersion ++ " " ++ programPath ghcPkgProg ++ " is version " ++ display ghcPkgVersion -- Likewise we try to find the matching hsc2hs program. let hsc2hsProgram' = hsc2hsProgram { programFindLocation = guessHsc2hsFromGhcPath ghcProg } conf3 = addKnownProgram hsc2hsProgram' conf2 languages <- getLanguages verbosity ghcProg extensions <- getExtensions verbosity ghcProg ghcInfo <- if ghcVersion >= Version [6,7] [] then do xs <- getProgramOutput verbosity ghcProg ["--info"] case reads xs of [(i, ss)] | all isSpace ss -> return i _ -> die "Can't parse --info output of GHC" else return [] let comp = Compiler { compilerId = CompilerId GHC ghcVersion, compilerLanguages = languages, compilerExtensions = extensions } conf4 = configureToolchain ghcProg ghcInfo conf3 -- configure gcc and ld return (comp, conf4) -- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find -- the corresponding tool; e.g. if the tool is ghc-pkg, we try looking -- for a versioned or unversioned ghc-pkg in the same dir, that is: -- -- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe) -- > /usr/local/bin/ghc-pkg-6.6.1(.exe) -- > /usr/local/bin/ghc-pkg(.exe) -- guessToolFromGhcPath :: FilePath -> ConfiguredProgram -> Verbosity -> IO (Maybe FilePath) guessToolFromGhcPath tool ghcProg verbosity = do let path = programPath ghcProg dir = takeDirectory path versionSuffix = takeVersionSuffix (dropExeExtension path) guessNormal = dir </> tool <.> exeExtension guessGhcVersioned = dir </> (tool ++ "-ghc" ++ versionSuffix) <.> exeExtension guessVersioned = dir </> (tool ++ versionSuffix) <.> exeExtension guesses | null versionSuffix = [guessNormal] | otherwise = [guessGhcVersioned, guessVersioned, guessNormal] info verbosity $ "looking for tool " ++ show tool ++ " near compiler in " ++ dir exists <- mapM doesFileExist guesses case [ file | (file, True) <- zip guesses exists ] of [] -> return Nothing (fp:_) -> do info verbosity $ "found " ++ tool ++ " in " ++ fp return (Just fp) where takeVersionSuffix :: FilePath -> String takeVersionSuffix = reverse . takeWhile (`elem ` "0123456789.-") . reverse dropExeExtension :: FilePath -> FilePath dropExeExtension filepath = case splitExtension filepath of (filepath', extension) | extension == exeExtension -> filepath' | otherwise -> filepath -- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a -- corresponding ghc-pkg, we try looking for both a versioned and unversioned -- ghc-pkg in the same dir, that is: -- -- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe) -- > /usr/local/bin/ghc-pkg-6.6.1(.exe) -- > /usr/local/bin/ghc-pkg(.exe) -- guessGhcPkgFromGhcPath :: ConfiguredProgram -> Verbosity -> IO (Maybe FilePath) guessGhcPkgFromGhcPath = guessToolFromGhcPath "ghc-pkg" -- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a -- corresponding hsc2hs, we try looking for both a versioned and unversioned -- hsc2hs in the same dir, that is: -- -- > /usr/local/bin/hsc2hs-ghc-6.6.1(.exe) -- > /usr/local/bin/hsc2hs-6.6.1(.exe) -- > /usr/local/bin/hsc2hs(.exe) -- guessHsc2hsFromGhcPath :: ConfiguredProgram -> Verbosity -> IO (Maybe FilePath) guessHsc2hsFromGhcPath = guessToolFromGhcPath "hsc2hs" -- | Adjust the way we find and configure gcc and ld -- configureToolchain :: ConfiguredProgram -> [(String, String)] -> ProgramConfiguration -> ProgramConfiguration configureToolchain ghcProg ghcInfo = addKnownProgram gccProgram { programFindLocation = findProg gccProgram [ if ghcVersion >= Version [6,12] [] then mingwBinDir </> "gcc.exe" else baseDir </> "gcc.exe" ], programPostConf = configureGcc } . addKnownProgram ldProgram { programFindLocation = findProg ldProgram [ if ghcVersion >= Version [6,12] [] then mingwBinDir </> "ld.exe" else libDir </> "ld.exe" ], programPostConf = configureLd } . addKnownProgram arProgram { programFindLocation = findProg arProgram [ if ghcVersion >= Version [6,12] [] then mingwBinDir </> "ar.exe" else libDir </> "ar.exe" ] } where Just ghcVersion = programVersion ghcProg compilerDir = takeDirectory (programPath ghcProg) baseDir = takeDirectory compilerDir mingwBinDir = baseDir </> "mingw" </> "bin" libDir = baseDir </> "gcc-lib" includeDir = baseDir </> "include" </> "mingw" isWindows = case buildOS of Windows -> True; _ -> False -- on Windows finding and configuring ghc's gcc and ld is a bit special findProg :: Program -> [FilePath] -> Verbosity -> IO (Maybe FilePath) findProg prog locations | isWindows = \verbosity -> look locations verbosity | otherwise = programFindLocation prog where look [] verbosity = do warn verbosity ("Couldn't find " ++ programName prog ++ " where I expected it. Trying the search path.") programFindLocation prog verbosity look (f:fs) verbosity = do exists <- doesFileExist f if exists then return (Just f) else look fs verbosity ccFlags = getFlags "C compiler flags" gccLinkerFlags = getFlags "Gcc Linker flags" ldLinkerFlags = getFlags "Ld Linker flags" getFlags key = case lookup key ghcInfo of Nothing -> [] Just flags -> case reads flags of [(args, "")] -> args _ -> [] -- XXX Should should be an error really configureGcc :: Verbosity -> ConfiguredProgram -> IO [ProgArg] configureGcc v cp = liftM (++ (ccFlags ++ gccLinkerFlags)) $ configureGcc' v cp configureGcc' :: Verbosity -> ConfiguredProgram -> IO [ProgArg] configureGcc' | isWindows = \_ gccProg -> case programLocation gccProg of -- if it's found on system then it means we're using the result -- of programFindLocation above rather than a user-supplied path -- Pre GHC 6.12, that meant we should add these flags to tell -- ghc's gcc where it lives and thus where gcc can find its -- various files: FoundOnSystem {} | ghcVersion < Version [6,11] [] -> return ["-B" ++ libDir, "-I" ++ includeDir] _ -> return [] | otherwise = \_ _ -> return [] configureLd :: Verbosity -> ConfiguredProgram -> IO [ProgArg] configureLd v cp = liftM (++ ldLinkerFlags) $ configureLd' v cp -- we need to find out if ld supports the -x flag configureLd' :: Verbosity -> ConfiguredProgram -> IO [ProgArg] configureLd' verbosity ldProg = do tempDir <- getTemporaryDirectory ldx <- withTempFile tempDir ".c" $ \testcfile testchnd -> withTempFile tempDir ".o" $ \testofile testohnd -> do hPutStrLn testchnd "int foo() {}" hClose testchnd; hClose testohnd rawSystemProgram verbosity ghcProg ["-c", testcfile, "-o", testofile] withTempFile tempDir ".o" $ \testofile' testohnd' -> do hClose testohnd' _ <- rawSystemProgramStdout verbosity ldProg ["-x", "-r", testofile, "-o", testofile'] return True `catchIO` (\_ -> return False) `catchExit` (\_ -> return False) if ldx then return ["-x"] else return [] getLanguages :: Verbosity -> ConfiguredProgram -> IO [(Language, Flag)] getLanguages _ ghcProg -- TODO: should be using --supported-languages rather than hard coding | ghcVersion >= Version [7] [] = return [(Haskell98, "-XHaskell98") ,(Haskell2010, "-XHaskell2010")] | otherwise = return [(Haskell98, "")] where Just ghcVersion = programVersion ghcProg getExtensions :: Verbosity -> ConfiguredProgram -> IO [(Extension, Flag)] getExtensions verbosity ghcProg | ghcVersion >= Version [6,7] [] = do str <- rawSystemStdout verbosity (programPath ghcProg) ["--supported-languages"] let extStrs = if ghcVersion >= Version [7] [] then lines str else -- Older GHCs only gave us either Foo or NoFoo, -- so we have to work out the other one ourselves [ extStr'' | extStr <- lines str , let extStr' = case extStr of 'N' : 'o' : xs -> xs _ -> "No" ++ extStr , extStr'' <- [extStr, extStr'] ] let extensions0 = [ (ext, "-X" ++ display ext) | Just ext <- map simpleParse extStrs ] extensions1 = if ghcVersion >= Version [6,8] [] && ghcVersion < Version [6,10] [] then -- ghc-6.8 introduced RecordPuns however it -- should have been NamedFieldPuns. We now -- encourage packages to use NamedFieldPuns -- so for compatability we fake support for -- it in ghc-6.8 by making it an alias for -- the old RecordPuns extension. (EnableExtension NamedFieldPuns, "-XRecordPuns") : (DisableExtension NamedFieldPuns, "-XNoRecordPuns") : extensions0 else extensions0 extensions2 = if ghcVersion < Version [7,1] [] then -- ghc-7.2 split NondecreasingIndentation off -- into a proper extension. Before that it -- was always on. (EnableExtension NondecreasingIndentation, "") : (DisableExtension NondecreasingIndentation, "") : extensions1 else extensions1 return extensions2 | otherwise = return oldLanguageExtensions where Just ghcVersion = programVersion ghcProg -- | For GHC 6.6.x and earlier, the mapping from supported extensions to flags oldLanguageExtensions :: [(Extension, Flag)] oldLanguageExtensions = let doFlag (f, (enable, disable)) = [(EnableExtension f, enable), (DisableExtension f, disable)] fglasgowExts = ("-fglasgow-exts", "") -- This is wrong, but we don't want to turn -- all the extensions off when asked to just -- turn one off fFlag flag = ("-f" ++ flag, "-fno-" ++ flag) in concatMap doFlag [(OverlappingInstances , fFlag "allow-overlapping-instances") ,(TypeSynonymInstances , fglasgowExts) ,(TemplateHaskell , fFlag "th") ,(ForeignFunctionInterface , fFlag "ffi") ,(MonomorphismRestriction , fFlag "monomorphism-restriction") ,(MonoPatBinds , fFlag "mono-pat-binds") ,(UndecidableInstances , fFlag "allow-undecidable-instances") ,(IncoherentInstances , fFlag "allow-incoherent-instances") ,(Arrows , fFlag "arrows") ,(Generics , fFlag "generics") ,(ImplicitPrelude , fFlag "implicit-prelude") ,(ImplicitParams , fFlag "implicit-params") ,(CPP , ("-cpp", ""{- Wrong -})) ,(BangPatterns , fFlag "bang-patterns") ,(KindSignatures , fglasgowExts) ,(RecursiveDo , fglasgowExts) ,(ParallelListComp , fglasgowExts) ,(MultiParamTypeClasses , fglasgowExts) ,(FunctionalDependencies , fglasgowExts) ,(Rank2Types , fglasgowExts) ,(RankNTypes , fglasgowExts) ,(PolymorphicComponents , fglasgowExts) ,(ExistentialQuantification , fglasgowExts) ,(ScopedTypeVariables , fFlag "scoped-type-variables") ,(FlexibleContexts , fglasgowExts) ,(FlexibleInstances , fglasgowExts) ,(EmptyDataDecls , fglasgowExts) ,(PatternGuards , fglasgowExts) ,(GeneralizedNewtypeDeriving , fglasgowExts) ,(MagicHash , fglasgowExts) ,(UnicodeSyntax , fglasgowExts) ,(PatternSignatures , fglasgowExts) ,(UnliftedFFITypes , fglasgowExts) ,(LiberalTypeSynonyms , fglasgowExts) ,(TypeOperators , fglasgowExts) ,(GADTs , fglasgowExts) ,(RelaxedPolyRec , fglasgowExts) ,(ExtendedDefaultRules , fFlag "extended-default-rules") ,(UnboxedTuples , fglasgowExts) ,(DeriveDataTypeable , fglasgowExts) ,(ConstrainedClassMethods , fglasgowExts) ] getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration -> IO PackageIndex getInstalledPackages verbosity packagedbs conf = do checkPackageDbStack packagedbs pkgss <- getInstalledPackages' verbosity packagedbs conf topDir <- ghcLibDir' verbosity ghcProg let indexes = [ PackageIndex.fromList (map (substTopDir topDir) pkgs) | (_, pkgs) <- pkgss ] return $! hackRtsPackage (mconcat indexes) where -- On Windows, various fields have $topdir/foo rather than full -- paths. We need to substitute the right value in so that when -- we, for example, call gcc, we have proper paths to give it Just ghcProg = lookupProgram ghcProgram conf hackRtsPackage index = case PackageIndex.lookupPackageName index (PackageName "rts") of [(_,[rts])] -> PackageIndex.insert (removeMingwIncludeDir rts) index _ -> index -- No (or multiple) ghc rts package is registered!! -- Feh, whatever, the ghc testsuite does some crazy stuff. ghcLibDir :: Verbosity -> LocalBuildInfo -> IO FilePath ghcLibDir verbosity lbi = (reverse . dropWhile isSpace . reverse) `fmap` rawSystemProgramStdoutConf verbosity ghcProgram (withPrograms lbi) ["--print-libdir"] ghcLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath ghcLibDir' verbosity ghcProg = (reverse . dropWhile isSpace . reverse) `fmap` rawSystemProgramStdout verbosity ghcProg ["--print-libdir"] checkPackageDbStack :: PackageDBStack -> IO () checkPackageDbStack (GlobalPackageDB:rest) | GlobalPackageDB `notElem` rest = return () checkPackageDbStack _ = die $ "GHC.getInstalledPackages: the global package db must be " ++ "specified first and cannot be specified multiple times" -- GHC < 6.10 put "$topdir/include/mingw" in rts's installDirs. This -- breaks when you want to use a different gcc, so we need to filter -- it out. removeMingwIncludeDir :: InstalledPackageInfo -> InstalledPackageInfo removeMingwIncludeDir pkg = let ids = InstalledPackageInfo.includeDirs pkg ids' = filter (not . ("mingw" `isSuffixOf`)) ids in pkg { InstalledPackageInfo.includeDirs = ids' } -- | Get the packages from specific PackageDBs, not cumulative. -- getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramConfiguration -> IO [(PackageDB, [InstalledPackageInfo])] getInstalledPackages' verbosity packagedbs conf | ghcVersion >= Version [6,9] [] = sequence [ do pkgs <- HcPkg.dump verbosity ghcPkgProg packagedb return (packagedb, pkgs) | packagedb <- packagedbs ] where Just ghcPkgProg = lookupProgram ghcPkgProgram conf Just ghcProg = lookupProgram ghcProgram conf Just ghcVersion = programVersion ghcProg substTopDir :: FilePath -> InstalledPackageInfo -> InstalledPackageInfo substTopDir topDir ipo = ipo { InstalledPackageInfo.importDirs = map f (InstalledPackageInfo.importDirs ipo), InstalledPackageInfo.libraryDirs = map f (InstalledPackageInfo.libraryDirs ipo), InstalledPackageInfo.includeDirs = map f (InstalledPackageInfo.includeDirs ipo), InstalledPackageInfo.frameworkDirs = map f (InstalledPackageInfo.frameworkDirs ipo), InstalledPackageInfo.haddockInterfaces = map f (InstalledPackageInfo.haddockInterfaces ipo), InstalledPackageInfo.haddockHTMLs = map f (InstalledPackageInfo.haddockHTMLs ipo) } where f ('$':'t':'o':'p':'d':'i':'r':rest) = topDir ++ rest f x = x -- ----------------------------------------------------------------------------- -- Building -- | Build a library with GHC. -- buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildLib verbosity pkg_descr lbi lib clbi = do let pref = buildDir lbi pkgid = packageId pkg_descr runGhcProg = rawSystemProgramConf verbosity ghcProgram (withPrograms lbi) ifVanillaLib forceVanilla = when (forceVanilla || withVanillaLib lbi) ifProfLib = when (withProfLib lbi) ifSharedLib = when (withSharedLib lbi) ifGHCiLib = when (withGHCiLib lbi && withVanillaLib lbi) comp = compiler lbi ghcVersion = compilerVersion comp libBi <- hackThreadedFlag verbosity comp (withProfLib lbi) (libBuildInfo lib) let libTargetDir = pref forceVanillaLib = EnableExtension TemplateHaskell `elem` allExtensions libBi -- TH always needs vanilla libs, even when building for profiling createDirectoryIfMissingVerbose verbosity True libTargetDir -- TODO: do we need to put hs-boot files into place for mutually recurive modules? let ghcArgs = "--make" : ["-package-name", display pkgid ] ++ constructGHCCmdLine lbi libBi clbi libTargetDir verbosity ++ map display (libModules lib) ghcArgsProf = ghcArgs ++ ["-prof", "-hisuf", "p_hi", "-osuf", "p_o" ] ++ ghcProfOptions libBi ghcArgsShared = ghcArgs ++ ["-dynamic", "-hisuf", "dyn_hi", "-osuf", "dyn_o", "-fPIC" ] ++ ghcSharedOptions libBi unless (null (libModules lib)) $ do ifVanillaLib forceVanillaLib (runGhcProg ghcArgs) ifProfLib (runGhcProg ghcArgsProf) ifSharedLib (runGhcProg ghcArgsShared) -- build any C sources foundCSources <- mapM (findFile $ cSourceDirs libBi) $ cSources libBi unless (null (cSources libBi)) $ do info verbosity "Building C Sources..." sequence_ [do let (odir,args) = constructCcCmdLine lbi libBi clbi pref filename verbosity False (withProfLib lbi) createDirectoryIfMissingVerbose verbosity True odir runGhcProg args ifSharedLib (runGhcProg (args ++ ["-fPIC", "-osuf dyn_o"])) | filename <- foundCSources ] -- link: info verbosity "Linking..." let cObjs = map (`replaceExtension` objExtension) foundCSources cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension)) foundCSources vanillaLibFilePath = libTargetDir </> mkLibName pkgid profileLibFilePath = libTargetDir </> mkProfLibName pkgid sharedLibFilePath = libTargetDir </> mkSharedLibName pkgid (compilerId (compiler lbi)) ghciLibFilePath = libTargetDir </> mkGHCiLibName pkgid libInstallPath = libdir $ absoluteInstallDirs pkg_descr lbi NoCopyDest sharedLibInstallPath = libInstallPath </> mkSharedLibName pkgid (compilerId (compiler lbi)) stubObjs <- fmap catMaybes $ sequence [ findFileWithExtension [objExtension] [libTargetDir] (ModuleName.toFilePath x ++"_stub") | ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files , x <- libModules lib ] stubProfObjs <- fmap catMaybes $ sequence [ findFileWithExtension ["p_" ++ objExtension] [libTargetDir] (ModuleName.toFilePath x ++"_stub") | ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files , x <- libModules lib ] stubSharedObjs <- fmap catMaybes $ sequence [ findFileWithExtension ["dyn_" ++ objExtension] [libTargetDir] (ModuleName.toFilePath x ++"_stub") | ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files , x <- libModules lib ] hObjs <- getHaskellObjects lib lbi pref objExtension True hProfObjs <- if (withProfLib lbi) then getHaskellObjects lib lbi pref ("p_" ++ objExtension) True else return [] hSharedObjs <- if (withSharedLib lbi) then getHaskellObjects lib lbi pref ("dyn_" ++ objExtension) False else return [] unless (null hObjs && null cObjs && null stubObjs) $ do -- first remove library files if they exists sequence_ [ removeFile libFilePath `catchIO` \_ -> return () | libFilePath <- [vanillaLibFilePath, profileLibFilePath ,sharedLibFilePath, ghciLibFilePath] ] let staticObjectFiles = hObjs ++ map (pref </>) cObjs ++ stubObjs profObjectFiles = hProfObjs ++ map (pref </>) cObjs ++ stubProfObjs ghciObjFiles = hObjs ++ map (pref </>) cObjs ++ stubObjs dynamicObjectFiles = hSharedObjs ++ map (pref </>) cSharedObjs ++ stubSharedObjs -- After the relocation lib is created we invoke ghc -shared -- with the dependencies spelled out as -package arguments -- and ghc invokes the linker with the proper library paths ghcSharedLinkArgs = [ "-no-auto-link-packages", "-shared", "-dynamic", "-o", sharedLibFilePath ] -- For dynamic libs, Mac OS/X needs to know the install location -- at build time. ++ (if buildOS == OSX then ["-dylib-install-name", sharedLibInstallPath] else []) ++ dynamicObjectFiles ++ ["-package-name", display pkgid ] ++ ghcPackageFlags lbi clbi ++ ["-l"++extraLib | extraLib <- extraLibs libBi] ++ ["-L"++extraLibDir | extraLibDir <- extraLibDirs libBi] ifVanillaLib False $ do (arProg, _) <- requireProgram verbosity arProgram (withPrograms lbi) Ar.createArLibArchive verbosity arProg vanillaLibFilePath staticObjectFiles ifProfLib $ do (arProg, _) <- requireProgram verbosity arProgram (withPrograms lbi) Ar.createArLibArchive verbosity arProg profileLibFilePath profObjectFiles ifGHCiLib $ do (ldProg, _) <- requireProgram verbosity ldProgram (withPrograms lbi) Ld.combineObjectFiles verbosity ldProg ghciLibFilePath ghciObjFiles ifSharedLib $ runGhcProg ghcSharedLinkArgs -- | Build an executable with GHC. -- buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildExe verbosity _pkg_descr lbi exe@Executable { exeName = exeName', modulePath = modPath } clbi = do let pref = buildDir lbi runGhcProg = rawSystemProgramConf verbosity ghcProgram (withPrograms lbi) exeBi <- hackThreadedFlag verbosity (compiler lbi) (withProfExe lbi) (buildInfo exe) -- exeNameReal, the name that GHC really uses (with .exe on Windows) let exeNameReal = exeName' <.> (if null $ takeExtension exeName' then exeExtension else "") let targetDir = pref </> exeName' let exeDir = targetDir </> (exeName' ++ "-tmp") createDirectoryIfMissingVerbose verbosity True targetDir createDirectoryIfMissingVerbose verbosity True exeDir -- TODO: do we need to put hs-boot files into place for mutually recursive modules? -- FIX: what about exeName.hi-boot? -- build executables srcMainFile <- findFile (exeDir : hsSourceDirs exeBi) modPath let foreignMain = elem (drop 1 $ takeExtension modPath) cSourceExtensions hsRootFiles <- do if not foreignMain then return [srcMainFile] else do maybeFiles <- sequence [ findFileWithExtension ["hs", "lhs"] (exeDir : hsSourceDirs exeBi) (ModuleName.toFilePath x) | x <- otherModules exeBi ] return $ catMaybes maybeFiles foundCSources <- mapM (findFile $ cSourceDirs exeBi) $ cSources exeBi let cObjs = map (`replaceExtension` objExtension) foundCSources let binArgs linkExe dynExe profExe = "--make" : (if linkExe then ["-o", targetDir </> exeNameReal] else ["-c"]) ++ constructGHCCmdLine lbi exeBi clbi exeDir verbosity ++ (if linkExe then [exeDir </> x | x <- cObjs] else []) ++ hsRootFiles ++ (if foreignMain then (if linkExe then [srcMainFile] else []) ++ ["-no-hs-main"] else []) ++ ["-optl" ++ opt | opt <- PD.ldOptions exeBi] ++ ["-l"++lib | lib <- extraLibs exeBi] ++ ["-L"++libDir | libDir <- extraLibDirs exeBi] ++ concat [["-framework", f] | f <- PD.frameworks exeBi] ++ (let flagPrefix = if linkExe then "-optl" else "-optc" in case PD.objcGCMode exeBi of PD.ObjcGCDisabled -> [] PD.ObjcGCOptional -> [flagPrefix ++ "-fobjc-gc"] PD.ObjcGCMandatory -> [flagPrefix ++ "-fobjc-gc-only"]) ++ (if dynExe then ["-dynamic"] else []) ++ (if profExe then ["-prof", "-hisuf", "p_hi", "-osuf", "p_o" ] ++ ghcProfOptions exeBi else []) -- For building exe's for profiling that use TH we actually -- have to build twice, once without profiling and the again -- with profiling. This is because the code that TH needs to -- run at compile time needs to be the vanilla ABI so it can -- be loaded up and run by the compiler. when (withProfExe lbi && EnableExtension TemplateHaskell `elem` allExtensions exeBi) (runGhcProg (binArgs False (withDynExe lbi) False)) runGhcProg (binArgs False (withDynExe lbi) (withProfExe lbi)) unless (null (cSources exeBi)) $ do info verbosity "Building C Sources." sequence_ [do let (odir,args) = constructCcCmdLine lbi exeBi clbi exeDir filename verbosity (withDynExe lbi) (withProfExe lbi) createDirectoryIfMissingVerbose verbosity True odir runGhcProg args | filename <- foundCSources] runGhcProg (binArgs True (withDynExe lbi) (withProfExe lbi)) buildApp :: Verbosity -> PackageDescription -> LocalBuildInfo -> App -> ComponentLocalBuildInfo -> IO () buildApp verbosity _pkg_descr lbi app clbi = do appBi <- hackThreadedFlag verbosity (compiler lbi) (withProfExe lbi) (appBuildInfo app) let prefix = buildDir lbi appPath = prefix </> (appName app ++ ".app") contentsPath = appPath </> "Contents" executableDirectoryPath = contentsPath </> "MacOS" resourcesPath = contentsPath </> "Resources" tmpDir = prefix </> (appName app ++ "-tmp") removeDirectoryRecursiveVerbose verbosity appPath createDirectoryIfMissingVerbose verbosity True executableDirectoryPath createDirectoryIfMissingVerbose verbosity True tmpDir let runGhcProg = rawSystemProgramConf verbosity ghcProgram (withPrograms lbi) srcMainFile <- findFile (tmpDir : hsSourceDirs appBi) (appModulePath app) let foreignMain = elem (drop 1 $ takeExtension $ appModulePath app) cSourceExtensions hsRootFiles <- do if not foreignMain then return [srcMainFile] else do maybeFiles <- sequence [ findFileWithExtension ["hs", "lhs"] (tmpDir : hsSourceDirs appBi) (ModuleName.toFilePath x) | x <- otherModules appBi ] return $ catMaybes maybeFiles foundCSources <- mapM (findFile $ cSourceDirs appBi) $ cSources appBi let cObjs = map (`replaceExtension` objExtension) foundCSources let binArgs linkExe dynExe profExe = "--make" : (if linkExe then ["-o", executableDirectoryPath </> appName app] else ["-c"]) ++ constructGHCCmdLine lbi appBi clbi tmpDir verbosity ++ (if linkExe then [tmpDir </> x | x <- cObjs] else []) ++ hsRootFiles ++ (if foreignMain then (if linkExe then [srcMainFile] else []) ++ ["-no-hs-main"] else []) ++ ["-optl" ++ opt | opt <- PD.ldOptions appBi] ++ ["-l"++lib | lib <- extraLibs appBi] ++ ["-L"++libDir | libDir <- extraLibDirs appBi] ++ concat [["-framework", f] | f <- PD.frameworks appBi] ++ (let flagPrefix = if linkExe then "-optl" else "-optc" in case PD.objcGCMode appBi of PD.ObjcGCDisabled -> [] PD.ObjcGCOptional -> [flagPrefix ++ "-fobjc-gc"] PD.ObjcGCMandatory -> [flagPrefix ++ "-fobjc-gc-only"]) ++ (if dynExe then ["-dynamic"] else []) ++ (if profExe then ["-prof", "-hisuf", "p_hi", "-osuf", "p_o" ] ++ ghcProfOptions appBi else []) -- For building exe's for profiling that use TH we actually -- have to build twice, once without profiling and the again -- with profiling. This is because the code that TH needs to -- run at compile time needs to be the vanilla ABI so it can -- be loaded up and run by the compiler. when (withProfExe lbi && EnableExtension TemplateHaskell `elem` allExtensions appBi) (runGhcProg (binArgs False (withDynExe lbi) False)) runGhcProg (binArgs False (withDynExe lbi) (withProfExe lbi)) unless (null (cSources appBi)) $ do info verbosity "Building C Sources." sequence_ [do let (odir,args) = constructCcCmdLine lbi appBi clbi tmpDir filename verbosity (withDynExe lbi) (withProfExe lbi) createDirectoryIfMissingVerbose verbosity True odir runGhcProg args | filename <- foundCSources] runGhcProg (binArgs True (withDynExe lbi) (withProfExe lbi)) (touchConfiguredProgram, _) <- requireProgram verbosity touchProgram $ withPrograms lbi (ibtoolConfiguredProgram, _) <- requireProgram verbosity ibtoolProgram $ withPrograms lbi createDirectoryIfMissingVerbose verbosity False appPath writeFileAtomic (appPath </> "PkgInfo") "APPL????" createDirectoryIfMissingVerbose verbosity False contentsPath let infoPlistSource = appInfoPlist app infoPlistDestination = contentsPath </> "Info.plist" installOrdinaryFile verbosity infoPlistSource infoPlistDestination createDirectoryIfMissingVerbose verbosity False resourcesPath let sourceResourcePath relativePath = case appResourceDirectory app of Nothing -> relativePath Just resourceDirectory -> resourceDirectory </> relativePath mapM_ (\xib -> do let xibPath = sourceResourcePath xib nibPath = resourcesPath </> replaceExtension xib ".nib" runProgram verbosity ibtoolConfiguredProgram ["--warnings", "--errors", "--output-format=human-readable-text", "--compile", nibPath, xibPath]) $ appXIBs app mapM_ (\resource -> do let resourceSource = sourceResourcePath resource resourceDestination = resourcesPath </> resource installOrdinaryFile verbosity resourceSource resourceDestination) $ appOtherResources app runProgram verbosity touchConfiguredProgram [appPath] -- | Filter the "-threaded" flag when profiling as it does not -- work with ghc-6.8 and older. hackThreadedFlag :: Verbosity -> Compiler -> Bool -> BuildInfo -> IO BuildInfo hackThreadedFlag verbosity comp prof bi | not mustFilterThreaded = return bi | otherwise = do warn verbosity $ "The ghc flag '-threaded' is not compatible with " ++ "profiling in ghc-6.8 and older. It will be disabled." return bi { options = filterHcOptions (/= "-threaded") (options bi) } where mustFilterThreaded = prof && compilerVersion comp < Version [6, 10] [] && "-threaded" `elem` hcOptions GHC bi filterHcOptions p hcoptss = [ (hc, if hc == GHC then filter p opts else opts) | (hc, opts) <- hcoptss ] -- when using -split-objs, we need to search for object files in the -- Module_split directory for each module. getHaskellObjects :: Library -> LocalBuildInfo -> FilePath -> String -> Bool -> IO [FilePath] getHaskellObjects lib lbi pref wanted_obj_ext allow_split_objs | splitObjs lbi && allow_split_objs = do let splitSuffix = if compilerVersion (compiler lbi) < Version [6, 11] [] then "_split" else "_" ++ wanted_obj_ext ++ "_split" dirs = [ pref </> (ModuleName.toFilePath x ++ splitSuffix) | x <- libModules lib ] objss <- mapM getDirectoryContents dirs let objs = [ dir </> obj | (objs',dir) <- zip objss dirs, obj <- objs', let obj_ext = takeExtension obj, '.':wanted_obj_ext == obj_ext ] return objs | otherwise = return [ pref </> ModuleName.toFilePath x <.> wanted_obj_ext | x <- libModules lib ] -- | Extracts a String representing a hash of the ABI of a built -- library. It can fail if the library has not yet been built. -- libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO String libAbiHash verbosity pkg_descr lbi lib clbi = do libBi <- hackThreadedFlag verbosity (compiler lbi) (withProfLib lbi) (libBuildInfo lib) let ghcArgs = "--abi-hash" : ["-package-name", display (packageId pkg_descr) ] ++ constructGHCCmdLine lbi libBi clbi (buildDir lbi) verbosity ++ map display (exposedModules lib) -- rawSystemProgramStdoutConf verbosity ghcProgram (withPrograms lbi) ghcArgs constructGHCCmdLine :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> Verbosity -> [String] constructGHCCmdLine lbi bi clbi odir verbosity = ghcVerbosityOptions verbosity -- Unsupported extensions have already been checked by configure ++ ghcOptions lbi bi clbi odir ghcVerbosityOptions :: Verbosity -> [String] ghcVerbosityOptions verbosity | verbosity >= deafening = ["-v"] | verbosity >= normal = [] | otherwise = ["-w", "-v0"] ghcOptions :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> [String] ghcOptions lbi bi clbi odir = ["-hide-all-packages"] ++ ["-fbuilding-cabal-package" | ghcVer >= Version [6,11] [] ] ++ ghcPackageDbOptions (withPackageDB lbi) ++ ["-split-objs" | splitObjs lbi ] ++ ["-i"] ++ ["-i" ++ odir] ++ ["-i" ++ l | l <- nub (hsSourceDirs bi)] ++ ["-i" ++ autogenModulesDir lbi] ++ ["-I" ++ autogenModulesDir lbi] ++ ["-I" ++ odir] ++ ["-I" ++ dir | dir <- PD.includeDirs bi] ++ ["-optP" ++ opt | opt <- cppOptions bi] ++ [ "-optP-include", "-optP"++ (autogenModulesDir lbi </> cppHeaderName) ] ++ [ "-#include \"" ++ inc ++ "\"" | ghcVer < Version [6,11] [] , inc <- PD.includes bi ] ++ [ "-odir", odir, "-hidir", odir ] ++ concat [ ["-stubdir", odir] | ghcVer >= Version [6,8] [] ] ++ ghcPackageFlags lbi clbi ++ (case withOptimization lbi of NoOptimisation -> [] NormalOptimisation -> ["-O"] MaximumOptimisation -> ["-O2"]) ++ (case PD.objcGCMode bi of PD.ObjcGCDisabled -> [] PD.ObjcGCOptional -> ["-optc-fobjc-gc"] PD.ObjcGCMandatory -> ["-optc-fobjc-gc-only"]) ++ hcOptions GHC bi ++ languageToFlags (compiler lbi) (defaultLanguage bi) ++ extensionsToFlags (compiler lbi) (defaultExtensions bi) where ghcVer = compilerVersion (compiler lbi) ghcPackageFlags :: LocalBuildInfo -> ComponentLocalBuildInfo -> [String] ghcPackageFlags lbi clbi | ghcVer >= Version [6,11] [] = concat [ ["-package-id", display ipkgid] | (ipkgid, _) <- componentPackageDeps clbi ] | otherwise = concat [ ["-package", display pkgid] | (_, pkgid) <- componentPackageDeps clbi ] where ghcVer = compilerVersion (compiler lbi) ghcPackageDbOptions :: PackageDBStack -> [String] ghcPackageDbOptions dbstack = case dbstack of (GlobalPackageDB:UserPackageDB:dbs) -> concatMap specific dbs (GlobalPackageDB:dbs) -> "-no-user-package-conf" : concatMap specific dbs _ -> ierror where specific (SpecificPackageDB db) = [ "-package-conf", db ] specific _ = ierror ierror = error ("internal error: unexpected package db stack: " ++ show dbstack) constructCcCmdLine :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> FilePath -> Verbosity -> Bool -> Bool ->(FilePath,[String]) constructCcCmdLine lbi bi clbi pref filename verbosity dynamic profiling = let odir | compilerVersion (compiler lbi) >= Version [6,4,1] [] = pref | otherwise = pref </> takeDirectory filename -- ghc 6.4.1 fixed a bug in -odir handling -- for C compilations. in (odir, ghcCcOptions lbi bi clbi odir ++ (if verbosity >= deafening then ["-v"] else []) ++ ["-c",filename] -- Note: When building with profiling enabled, we pass the -prof -- option to ghc here when compiling C code, so that the PROFILING -- macro gets defined. The macro is used in ghc's Rts.h in the -- definitions of closure layouts (Closures.h). ++ ["-dynamic" | dynamic] ++ ["-prof" | profiling]) ghcCcOptions :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> [String] ghcCcOptions lbi bi clbi odir = ["-I" ++ dir | dir <- odir : PD.includeDirs bi] ++ ghcPackageDbOptions (withPackageDB lbi) ++ ghcPackageFlags lbi clbi ++ ["-optc" ++ opt | opt <- PD.ccOptions bi] ++ (case PD.objcGCMode bi of PD.ObjcGCDisabled -> [] PD.ObjcGCOptional -> ["-optc-fobjc-gc"] PD.ObjcGCMandatory -> ["-optc-fobjc-gc-only"]) ++ (case withOptimization lbi of NoOptimisation -> [] _ -> ["-optc-O2"]) ++ ["-odir", odir] mkGHCiLibName :: PackageIdentifier -> String mkGHCiLibName lib = "HS" ++ display lib <.> "o" -- ----------------------------------------------------------------------------- -- Installing -- |Install executables for GHC. installExe :: Verbosity -> LocalBuildInfo -> InstallDirs FilePath -- ^Where to copy the files to -> FilePath -- ^Build location -> (FilePath, FilePath) -- ^Executable (prefix,suffix) -> PackageDescription -> Executable -> IO () installExe verbosity lbi installDirs buildPref (progprefix, progsuffix) _pkg exe = do let binDir = bindir installDirs createDirectoryIfMissingVerbose verbosity True binDir let exeFileName = exeName exe <.> exeExtension fixedExeBaseName = progprefix ++ exeName exe ++ progsuffix installBinary dest = do installExecutableFile verbosity (buildPref </> exeName exe </> exeFileName) (dest <.> exeExtension) stripExe verbosity lbi exeFileName (dest <.> exeExtension) installBinary (binDir </> fixedExeBaseName) stripExe :: Verbosity -> LocalBuildInfo -> FilePath -> FilePath -> IO () stripExe verbosity lbi name path = when (stripExes lbi) $ case lookupProgram stripProgram (withPrograms lbi) of Just strip -> rawSystemProgram verbosity strip args Nothing -> unless (buildOS == Windows) $ -- Don't bother warning on windows, we don't expect them to -- have the strip program anyway. warn verbosity $ "Unable to strip executable '" ++ name ++ "' (missing the 'strip' program)" where args = path : case buildOS of OSX -> ["-x"] -- By default, stripping the ghc binary on at least -- some OS X installations causes: -- HSbase-3.0.o: unknown symbol `_environ'" -- The -x flag fixes that. _ -> [] -- |Install for ghc, .hi, .a and, if --with-ghci given, .o installLib :: Verbosity -> LocalBuildInfo -> FilePath -- ^install location -> FilePath -- ^install location for dynamic librarys -> FilePath -- ^Build location -> PackageDescription -> Library -> IO () installLib verbosity lbi targetDir dynlibTargetDir builtDir pkg lib = do -- copy .hi files over: let copyHelper installFun src dst n = do createDirectoryIfMissingVerbose verbosity True dst installFun verbosity (src </> n) (dst </> n) copy = copyHelper installOrdinaryFile copyShared = copyHelper installExecutableFile copyModuleFiles ext = findModuleFiles [builtDir] [ext] (libModules lib) >>= installOrdinaryFiles verbosity targetDir ifVanilla $ copyModuleFiles "hi" ifProf $ copyModuleFiles "p_hi" ifShared $ copyModuleFiles "dyn_hi" -- copy the built library files over: ifVanilla $ copy builtDir targetDir vanillaLibName ifProf $ copy builtDir targetDir profileLibName ifGHCi $ copy builtDir targetDir ghciLibName ifShared $ copyShared builtDir dynlibTargetDir sharedLibName -- run ranlib if necessary: ifVanilla $ updateLibArchive verbosity lbi (targetDir </> vanillaLibName) ifProf $ updateLibArchive verbosity lbi (targetDir </> profileLibName) where vanillaLibName = mkLibName pkgid profileLibName = mkProfLibName pkgid ghciLibName = mkGHCiLibName pkgid sharedLibName = mkSharedLibName pkgid (compilerId (compiler lbi)) pkgid = packageId pkg hasLib = not $ null (libModules lib) && null (cSources (libBuildInfo lib)) ifVanilla = when (hasLib && withVanillaLib lbi) ifProf = when (hasLib && withProfLib lbi) ifGHCi = when (hasLib && withGHCiLib lbi) ifShared = when (hasLib && withSharedLib lbi) -- | On MacOS X we have to call @ranlib@ to regenerate the archive index after -- copying. This is because the silly MacOS X linker checks that the archive -- index is not older than the file itself, which means simply -- copying/installing the file breaks it!! -- updateLibArchive :: Verbosity -> LocalBuildInfo -> FilePath -> IO () updateLibArchive verbosity lbi path | buildOS == OSX = do (ranlib, _) <- requireProgram verbosity ranlibProgram (withPrograms lbi) rawSystemProgram verbosity ranlib [path] | otherwise = return () -- ----------------------------------------------------------------------------- -- Registering registerPackage :: Verbosity -> InstalledPackageInfo -> PackageDescription -> LocalBuildInfo -> Bool -> PackageDBStack -> IO () registerPackage verbosity installedPkgInfo _pkg lbi _inplace packageDbs = do let Just ghcPkg = lookupProgram ghcPkgProgram (withPrograms lbi) HcPkg.reregister verbosity ghcPkg packageDbs (Right installedPkgInfo)
IreneKnapp/Faction
libfaction/Distribution/Simple/GHC.hs
bsd-3-clause
53,821
0
30
16,170
11,278
5,895
5,383
904
12
-- | == Single URI Authorization -- -- There are cases in which limited and short-term access to a -- protected resource is granted to a third party which does not have -- access to the shared credentials. For example, displaying a -- protected image on a web page accessed by anyone. __Hawk__ provides -- limited support for such URIs in the form of a /bewit/ — a URI -- query parameter appended to the request URI which contains the -- necessary credentials to authenticate the request. -- -- Because of the significant security risks involved in issuing such -- access, bewit usage is purposely limited only to GET requests and -- for a finite period of time. Both the client and server can issue -- bewit credentials, however, the server should not use the same -- credentials as the client to maintain clear traceability as to who -- issued which credentials. -- -- In order to simplify implementation, bewit credentials do not -- support single-use policy and can be replayed multiple times within -- the granted access timeframe. -- -- This module collects the URI authorization functions in a single -- module, to mirror the @Hawk.uri@ module of the javascript -- implementation. module Network.Hawk.URI ( authenticate , middleware , getBewit ) where import Control.Monad.IO.Class (MonadIO) import Network.Wai (Request) import Network.Hawk.Types import Network.Hawk.Server (authenticateBewitRequest, authenticateBewit, CredentialsFunc, AuthReqOpts, AuthOpts, AuthResult, HawkReq) import Network.Hawk.Middleware (bewitAuth) import Network.Hawk.Client (getBewit) -- | See 'Network.Hawk.Server.authenticateBewitRequest'. authenticateRequest :: MonadIO m => AuthReqOpts -> CredentialsFunc m t -> Request -> m (AuthResult t) authenticateRequest = authenticateBewitRequest -- | See 'Network.Hawk.Server.authenticateBewit'. authenticate :: MonadIO m => AuthOpts -> CredentialsFunc m t -> HawkReq -> m (AuthResult t) authenticate = authenticateBewit -- | See 'Network.Hawk.Middleware.bewitAuth'. middleware = bewitAuth
rvl/hsoz
src/Network/Hawk/URI.hs
bsd-3-clause
2,098
0
11
366
215
135
80
17
1
{-# LANGUAGE RecordWildCards, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, TupleSections #-} module Aws.SimpleDb.Commands.GetAttributes where import Aws.Response import Aws.Signature import Aws.SimpleDb.Info import Aws.SimpleDb.Metadata import Aws.SimpleDb.Model import Aws.SimpleDb.Query import Aws.SimpleDb.Response import Aws.Transaction import Aws.Util import Control.Applicative import Control.Monad import Data.Maybe import Text.XML.Cursor (($//), (&|)) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Text.XML.Cursor as Cu data GetAttributes = GetAttributes { gaItemName :: T.Text , gaAttributeName :: Maybe T.Text , gaConsistentRead :: Bool , gaDomainName :: T.Text } deriving (Show) data GetAttributesResponse = GetAttributesResponse { garAttributes :: [Attribute T.Text] } deriving (Show) getAttributes :: T.Text -> T.Text -> GetAttributes getAttributes item domain = GetAttributes { gaItemName = item, gaAttributeName = Nothing, gaConsistentRead = False, gaDomainName = domain } instance SignQuery GetAttributes where type Info GetAttributes = SdbInfo signQuery GetAttributes{..} = sdbSignQuery $ [("Action", "GetAttributes"), ("ItemName", T.encodeUtf8 gaItemName), ("DomainName", T.encodeUtf8 gaDomainName)] ++ maybeToList (("AttributeName",) <$> T.encodeUtf8 <$> gaAttributeName) ++ (guard gaConsistentRead >> [("ConsistentRead", awsTrue)]) instance ResponseConsumer r GetAttributesResponse where type ResponseMetadata GetAttributesResponse = SdbMetadata responseConsumer _ = sdbResponseConsumer parse where parse cursor = do sdbCheckResponseType () "GetAttributesResponse" cursor attributes <- sequence $ cursor $// Cu.laxElement "Attribute" &| readAttribute return $ GetAttributesResponse attributes instance Transaction GetAttributes GetAttributesResponse
jgm/aws
Aws/SimpleDb/Commands/GetAttributes.hs
bsd-3-clause
2,206
0
14
556
464
268
196
46
1
module HaskQuery ( module HaskQuery.AutoIndex, Relation, Cont, empty, emptyWithIndex, reindex, runQuery, select, runQueryM, executeM, selectM, filterM, selectWithIndex, selectDynamic, selectDynamicWithTypeM, insert, insertRows, insertInto, update, delete ) where import qualified Data.IntMap.Lazy import qualified Data.List import qualified Control.Monad.Trans.Cont import qualified Data.Typeable import qualified Data.Dynamic import qualified Data.Proxy import HaskQuery.AutoIndex data Relation a b = Relation { _relation :: Data.IntMap.Lazy.IntMap a , _lastRowId :: Int, _indices :: UpdatableIndex a b} deriving (Show) type Cont r a = Control.Monad.Trans.Cont.Cont r a empty :: Relation a () empty = Relation { _relation = Data.IntMap.Lazy.empty, _lastRowId = 0, _indices = emptyIndex } emptyWithIndex :: UpdatableIndex a c -> Relation a c emptyWithIndex index = reindex empty index reindex :: Relation a b -> UpdatableIndex a c -> Relation a c reindex indexedRelation newIndex = let originalRelation = _relation indexedRelation in indexedRelation { _relation = originalRelation, _indices = updateAutoWithInput newIndex $ Insert $ InsertSet {inserted = originalRelation} } runQuery :: Control.Monad.Trans.Cont.Cont ([a] -> [a]) a -> [a] runQuery query = (Control.Monad.Trans.Cont.runCont query (\value -> (\list -> value : list))) [] select :: Relation a c -> Control.Monad.Trans.Cont.Cont (b -> b) a select relation = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> Data.IntMap.Lazy.foldl (\foldSeed value -> continuation value foldSeed) seed (_relation relation))) filterM :: Monad m => Bool -> Control.Monad.Trans.Cont.Cont (a -> m a) () filterM predicate = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> if predicate then (continuation () seed ) else return seed)) runQueryM :: Monad m => Control.Monad.Trans.Cont.Cont ([a] -> m [a]) a -> m [a] runQueryM query = (Control.Monad.Trans.Cont.runCont query (\value -> (\list -> return (value : list)))) [] selectM :: Monad m => Relation a c -> Control.Monad.Trans.Cont.Cont (b -> m b) a selectM relation = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> Data.IntMap.Lazy.foldl (\foldSeed value -> foldSeed >>= continuation value) (return seed) (_relation relation))) executeM :: Monad m => m a -> Control.Monad.Trans.Cont.Cont (b -> m b) a executeM computation = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> do value <- computation result <- continuation value seed return result)) selectWithIndex :: (c -> indexValue -> Control.Monad.Trans.Cont.Cont (b -> b) Int) -> Relation a c -> indexValue -> Control.Monad.Trans.Cont.Cont (b -> b) a selectWithIndex indexAccessor relation indexValue = do rowId <- indexAccessor (readAuto $ _indices relation) indexValue return $ (_relation relation) Data.IntMap.Lazy.! rowId selectDynamic :: (Data.Typeable.Typeable a) => Data.Dynamic.Dynamic -> Control.Monad.Trans.Cont.Cont (b->b) a selectDynamic value = Control.Monad.Trans.Cont.cont (\continuation -> (case Data.Dynamic.fromDynamic value of Just typed -> continuation typed ; Nothing -> id)) selectDynamicWithType :: (Data.Typeable.Typeable a) => Data.Proxy.Proxy a -> Data.Dynamic.Dynamic -> Control.Monad.Trans.Cont.Cont (b->b) a selectDynamicWithType proxy value = selectDynamic value selectDynamicWithTypeM :: (Data.Typeable.Typeable a, Monad m) => Data.Proxy.Proxy a -> Data.Dynamic.Dynamic -> Control.Monad.Trans.Cont.Cont (b->m b) a selectDynamicWithTypeM proxy value = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> (case Data.Dynamic.fromDynamic value of Just typed -> continuation typed seed ; Nothing -> return seed))) insert :: Relation a b -> a -> Relation a b insert indexedRelation item = let newRowId = (_lastRowId indexedRelation) + 1 updatedRelation = Data.IntMap.Lazy.insert newRowId item (_relation indexedRelation) updatedIndex = updateAutoWithInput (_indices indexedRelation) (Insert $ InsertSet { inserted = Data.IntMap.Lazy.singleton newRowId item}) in Relation { _relation = updatedRelation, _lastRowId = newRowId, _indices = updatedIndex} insertRows :: Relation a b -> [a] -> Relation a b insertRows indexedRelation rows = Data.List.foldl' (insert) indexedRelation rows insertInto :: Relation a b -> Control.Monad.Trans.Cont.Cont (Relation a b -> Relation a b) a -> Relation a b insertInto indexedRelation insertContinuation = Control.Monad.Trans.Cont.runCont insertContinuation (\ row -> (\seedIndexedRelation -> insert seedIndexedRelation row)) indexedRelation update :: Relation a b-> (a -> Bool) -> (a -> a) -> Relation a b update indexedRelation predicate updateFunction = let originalRelation = (_relation indexedRelation) affectedRows = Data.IntMap.Lazy.filter predicate originalRelation updateMap = Data.IntMap.Lazy.map (\row -> (row, updateFunction row)) affectedRows updatedRows = Data.IntMap.Lazy.map (\ (row, updatedRow) -> updatedRow) updateMap updatedIndex = updateAutoWithInput (_indices indexedRelation) $ Update $ UpdateSet { updated = updateMap } in indexedRelation { _relation = updatedRows, _indices = updatedIndex } delete :: Relation a b -> (a -> Bool) -> Relation a b delete indexedRelation predicate = let originalRelation = (_relation indexedRelation) affectedRows = Data.IntMap.Lazy.filter predicate originalRelation updatedRelation = Data.IntMap.Lazy.difference originalRelation affectedRows updatedIndex = updateAutoWithInput (_indices indexedRelation) $ Delete $ DeleteSet { deleted = affectedRows } in indexedRelation { _relation = updatedRelation, _indices = updatedIndex}
stevechy/haskellEditor
ext-src/HaskQueryPackage/HaskQuery.hs
bsd-3-clause
5,788
0
15
953
1,921
1,058
863
90
2
-- | Physical constants. module DSMC.Util.Constants ( amu , avogadro , boltzmann , unigas ) where -- | Atomic mass unit 1.660538921(73)e-27, inverse to Avogadro's -- constant. amu :: Double amu = 1.6605389217373737e-27 -- | Avogadro constant 6.02214129(27)e23 avogadro :: Double avogadro = 6.0221412927272727e23 -- | Boltzmann constant 1.3806488(13)e-23 boltzmann :: Double boltzmann = 1.3806488131313131e-23 -- | Universal gas constant. unigas :: Double unigas = boltzmann * avogadro
dzhus/dsmc
src/DSMC/Util/Constants.hs
bsd-3-clause
515
0
5
98
71
46
25
13
1
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-missing-signatures #-} {-# LANGUAGE FlexibleInstances, DeriveFunctor, MultiParamTypeClasses, UndecidableInstances, FlexibleContexts, TypeSynonymInstances #-} --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- -- | -- | Module : First attempt at approximate mean -- | Creator: Xiao Ling -- | Created: 11/29/2015 -- | see : https://github.com/snoyberg/conduit -- https://gist.github.com/thoughtpolice/3704890 -- http://blog.ezyang.com/2012/01/problem-set-the-codensity-transformation/ -- http://www.janis-voigtlaender.eu/papers/AsymptoticImprovementOfComputationsOverFreeMonads.pdf -- https://gist.github.com/supki/3776752 -- | --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- module Play1129 where import System.Random import Data.List import Data.Random import Data.Conduit import qualified Data.Conduit.List as Cl import Control.Monad.Identity import Control.Monad.State import qualified Test.QuickCheck as T import Core import Statistics {----------------------------------------------------------------------------- 1. make some examples 2. make 3. see if cassava can be put into a conduit 4. output Row type see : http://stackoverflow.com/questions/2376981/haskell-types-frustrating-a-simple-average-function ------------------------------------------------------------------------------} {----------------------------------------------------------------------------- II. Approximate Median try ii TODO: figure out uniform sampling without knowing length of stream ------------------------------------------------------------------------------} -- * TODO: make this into an array since we'll be doing (!!) which is O(n) in list -- * A reservoir is a list, its max allowed size, and its current size -- * this deign is really bad, cannot gaurantee that currentSize is upToDate with length [a] -- * dependent types would be good, or we can jsut get rid of current size -- * or hide it in Core data Reservoir a = R { run :: [a], size :: Int, currentSize :: Int } deriving (Show,Functor,Eq) instance Num a => T.Arbitrary (Reservoir a) where -- * by construction, an arbitrary reservoir is always 1 item away from full arbitrary = do s <- T.arbitrary :: T.Gen (T.Positive Int) let s' = T.getPositive s let n = s' - 1 :: Int return $ R (replicate n 0) s' n shrink (R xs s n) = (\s' -> let n = max 0 (s' - 1) in (R (replicate n 0) s' n)) <$> T.shrink s -- * constructor an empty resoivor of max size `s` reservoir :: Int -> Reservoir a reservoir s = R [] s 0 -- * check if reservoir is full full :: Reservoir a -> Bool full (R xs s n) = n >= s -- * insert item, note the order (>+) :: Reservoir a -> a -> Reservoir a (>+) t@(R xs s n) x | full t = t | otherwise = R (x:xs) s $ succ n -- * remove the `i`th item from `r` -- * if i > size then no item removed (>-) :: Reservoir a -> Int -> Reservoir a r@(R xs s n) >- i | i > n = r | otherwise = undefined -- * really need to use array here -- * sample an item `x` from the stream with uniform probability place in reservoir -- * keep a conter `c` of elements seen sampl :: Counter -> Sink a (StateT (Reservoir a) RVar) [a] sampl i = do ma <- await case ma of Nothing -> lift get >>= \r -> return $ run r Just a -> do lift $ store i a sampl $ succ i store :: Counter -> a -> StateT (Reservoir a) RVar () store i a = do r <- get case full r of False -> put $ r >+ a _ -> return () where p = (read . show $ size r :: Float)/i -- * test m/2 - e*m < rank(y) < m/2 + e*m -- * quickCheck Resoivor -- * full resoivor is full prop_fullReso :: Reservoir Int -> T.Property prop_fullReso r = (T.==>) (size r > 0) $ full (r>+1) == True ---- * inserting into non-full resoivor resutls in additional element prop_insertNotFull :: Reservoir Int -> T.Property prop_insertNotFull r = (T.==>) (size r > 0) $ currentSize (r>+1) == currentSize r + 1 -- * inserting into full resoivor leaves it unchanged prop_insertFull :: Reservoir Int -> T.Property prop_insertFull r = (T.==>) (size r > 0) $ currentSize (r'>+1) == currentSize r' where r' = r >+ 1 testReservoir :: IO () testReservoir = do T.quickCheck $ prop_fullReso T.quickCheck $ prop_insertFull T.quickCheck $ prop_insertNotFull {----------------------------------------------------------------------------- II. Approximate Median Naive ------------------------------------------------------------------------------} -- * setting problem: can you make this streaming? assuming you know m? -- * can you do running uniform distribution? -- * Find approximate eps e-median of list `xs` -- * Setting: list given before hand for some parameter t -- * Use : runRVar (naive xs e d) StdRandom medianNaive :: (Floating a, Ord a) => [a] -> Eps -> Delta -> RVar a medianNaive xs e d | m <= t = return $ median xs | otherwise = fmap median $ sampl' xs m t where m = length xs t = round $ 7/(e^2) * log (2/d) -- * use vector here due to (!!) -- * sample `t` items from the list `[0..m-1]` *with replacement* -- * Use : runRVar (sample m t) StdRandom sampl' :: [a] -> Int -> Int -> RVar [a] sampl' xs m t | m < 0 || t < 0 = return [] | otherwise = (\is -> [ xs !! i | i <- is]) <$> mis where mis = fmap sort . replicateM t $ uniform 0 (m-1) {----------------------------------------------------------------------------- III. Frequency Moments ------------------------------------------------------------------------------} {----------------------------------------------------------------------------- I. Approximate Counting ------------------------------------------------------------------------------} -- * Run on stream inputs `xs` for t independent trials for `t = 1/eps`, -- * and `m` times in parralell, for `m = 1/(e^2 * d)` -- * and take the median morris :: Eps -> Delta -> [a] -> RVar Counter morris e d xs = fmap rmedian . (fmap . fmap) rmean -- * take median of the means $ Cl.sourceList xs $$ count -- * stream to counter $ replicate m $ replicate t 0 -- * make m counters of length t where t = round $ 1/(e^2*d) m = round $ 1/d -- * Given an m-long list `xs` of lists (each of which is t-lengthed) of counters, -- * consume the stream and output result count :: [[Counter]] -> Sink a RVar [[Counter]] count xxs = (fmap . fmap . fmap) (\x -> 2^(round x) - 1) $ Cl.foldM (\xs _ -> incrs xs) xxs -- * given a list of list of counter `xs` of length `n`, -- * toss a coin and count incrs :: [[Counter]] -> RVar [[Counter]] incrs = sequence . fmap incr where incr xs = do hs <- sequence $ (\x -> toss . coin $ 0.5^(round x)) <$> xs return $ pincr <$> zip hs xs where pincr (h,x) = if isHead h then (seq () succ x) else seq () x -- * Naive solution * -- -- * Run Morris alpha on stream inputs `xs` morrisA :: [a] -> IO Counter morrisA xs = flip runRVar StdRandom $ Cl.sourceList xs $$ alpha -- * Run Morris beta on stream inputs `xs` for `t` independent trials and average morrisB :: Int -> [a] -> IO Counter morrisB t = fmap rmean . replicateM t . morrisA -- * Naive morris algorithm -- * Run on stream inputs `xs` for t independent trials for `t = 1/eps`, -- * and `m` times in parralell, for `m = 1/(e^2 * d)` -- * and take the median -- * Problem : `replicateM n` is O(n) time morris' :: Eps -> Delta -> [a] -> IO Counter morris' e d = fmap rmedian . replicateM m . morrisB t where (t,m) = (round $ 1/(e^2*d), round $ 1/d) -- * A step in morris Algorithm alpha alpha :: Sink a RVar Counter alpha = (\x -> 2^(round x) - 1) <$> Cl.foldM (\x _ -> incr x) 0 -- * Increment a counter `x` with probability 1/2^x incr :: Counter -> RVar Counter incr x = do h <- toss . coin $ 0.5^(round x) return $ if isHead h then (seq () succ x) else seq () x rmean, rmedian :: (Floating a, Ord a, RealFrac a) => [a] -> Float rmean = fromIntegral . round . mean rmedian = fromIntegral . round . median ---- * Increment a counter `x` with probability 1/2^x --incr' :: Counter -> RVar Counter --incr' x = do -- h <- (\q -> q <= (0.5^(round x) :: Prob)) <$> uniform 0 1 -- return $ if h then (seq () succ x) else seq () x -- * Test Morris tMorris :: IO () tMorris = undefined {----------------------------------------------------------------------------- X. Finger Exercises type Source m a = ConduitM () a m () -- no meaningful input or return value type Conduit a m b = ConduitM a b m () -- no meaningful return value type Sink a m b = ConduitM a Void m b -- no meaningful output value ------------------------------------------------------------------------------} -- * generator genRs :: Monad m => Source m Int genRs = Cl.sourceList rs -- * conduits cond :: Monad m => Conduit Int m String cond = Cl.map show add1 :: Monad m => Conduit Int m Int add1 = Cl.map (+1) add2 :: Monad m => Conduit Int m Int add2 = do mx <- await case mx of Nothing -> return () Just x -> (yield $ x + 2) >> add2 -- * sinks sink1 :: Sink Int IO () sink1 = Cl.mapM_ $ putStrLn . show sink2 :: Sink String IO () sink2 = Cl.mapM_ putStrLn -- * accumlate the values in a list sink3 :: Monad m => [Int] -> Sink Int m [Int] sink3 xs = do mx <- await case mx of Nothing -> return xs Just x -> sink3 $ xs ++ [x] -- * accuulate values in a list and increment by 3 add3 :: (Num a, Monad m) => Sink Int m [Int] add3 = Cl.fold (\xs x -> xs ++ [x+3]) [] -- * some trivial pipes pp0, pp1, pp2 :: IO () pp0 = genRs $$ sink1 pp1 = genRs $$ add1 $= cond $= sink2 pp2 = genRs $$ add2 $= cond $= sink2 -- * map and fold pp2' :: Identity [Int] pp2' = genRs $$ add2 $= sink3 [] -- * fold a list pp3 :: Identity [Int] pp3 = genRs $$ add3 -- * counts everything brute :: [a] -> Counter brute xs = runIdentity $ Cl.sourceList xs $$ Cl.fold (\n _ -> succ n) 0 -- * filter a list pp4 :: Int -> Identity [Int] pp4 n = genRs $= Cl.filter (>n) $$ Cl.fold (flip $ (++) . pure) [] -- * map list pp5 :: Identity [Int] pp5 = genRs $= Cl.map (+5) $$ sink3 [] -- * test property tpp2, tpp3, tpp5 :: Bool tpp2 = runIdentity pp2' == fmap (+2) rs tpp3 = runIdentity pp3 == fmap (+3) rs tpp5 = runIdentity pp5 == fmap (+5) rs -- * test uniformness of list, observe it's relatively uniform tpp4 :: [Int] tpp4 = length . runIdentity . pp4 <$> [1..10] {----------------------------------------------------------------------------- X. Test Data ------------------------------------------------------------------------------} -- * random string of choice rs :: (Enum a, Num a) => [a] rs = [1..1000] {----------------------------------------------------------------------------- Depricated ------------------------------------------------------------------------------} --morrisA' :: Sink a RVar Counter --morrisA' = Cl.foldM (\x _ -> incr x) 0 --incr :: MonadRandom m => Counter -> m Counter --incr x = do -- h <- toss . coin $ 0.5^x -- return $ if isHead h then (seq () succ x) else seq () x --morrisB :: Conduit a (StateT Counter RVar) a --morrisB = do -- mi <- await -- case mi of -- Nothing -> return () -- Just i -> do -- yield i -- x <- lift get -- h <- lift . lift . toss . coin $ 0.5^x -- let x' = if isHead h then succ x else x -- lift . put $ seq () x' -- morrisB --cap :: Monad m => Sink a m () --cap = do -- mi <- await -- case mi of -- Nothing -> return () -- _ -> cap --morrisBs = flip runStateT 0 $ Cl.sourceList [1..10000] $= morrisB $= morrisB $$ cap -- * Morris Algorithm Beta, repeat step in morris alpha `t` times --morrisB :: Trials -> Sink a RVar [Counter] --morrisB t = replicateM t morrisA --tmorrisB' :: Trials -> [a] -> IO [Counter] --tmorrisB' t xs = (fmap . fmap) toN . flip runRVar StdRandom $ Cl.sourceList xs $$ morrisB t
lingxiao/CIS700
depricated/Play1129.hs
bsd-3-clause
12,496
0
16
2,798
2,853
1,520
1,333
147
2
module Backend.Generic123 ( mpg321Backend , ogg123Backend ) where import Backend import Control.Concurrent import Control.Monad import System.IO import System.Process (shell,CreateProcess(..),StdStream(..),createProcess,waitForProcess) -- | A backend for controlling mpg321. mpg321Backend :: IO Backend mpg321Backend = generic123Backend "mpg321" "mpg321 -R mp" -- | A backend for controlling ogg123. ogg123Backend :: IO Backend ogg123Backend = generic123Backend "ogg123" "ogg123 -R mp" -- | A generic backend for audio programs that support an mpg123-like interface. generic123Backend :: String -> String -> IO Backend generic123Backend name cmd = do let process = (shell cmd) { std_in = CreatePipe , std_out = CreatePipe , std_err = CreatePipe , close_fds = True } (Just inH, Just outH, Just errH, ph) <- createProcess process hSetBuffering inH NoBuffering hSetBinaryMode inH False hSetBinaryMode outH False hSetBinaryMode errH False status <- newSampleVar "" statusTid <- forkIO $ forever $ do line <- hGetLine outH unless (null line) (writeSampleVar status line) let send ws = do putStrLn ("Sending: " ++ show ws) hPutStrLn inH (unwords ws) cleanup = do send ["QUIT"] killThread statusTid hClose inH hClose outH hClose errH _ <- waitForProcess ph return () return Backend { backendName = name , backendLoad = \ path -> send ["LOAD",path] , backendPause = send ["PAUSE"] , backendPlay = send ["PAUSE"] , backendStop = send ["STOP"] , backendCleanup = cleanup , backendStatus = readSampleVar status , backendSetVolume = \ vol -> send ["GAIN",show vol] }
elliottt/din
src/Backend/Generic123.hs
bsd-3-clause
1,842
0
15
515
494
252
242
49
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DataKinds #-} import Test.Tasty.HUnit ((@?=), Assertion, testCase) import Test.Tasty.TH (defaultMainGenerator) import Language.Cypher case_simpleMatchExample :: Assertion case_simpleMatchExample = show (simpleMatch (PNode (Just n) [] []) (RetE n ::: HNil)) @?= "MATCH (n) RETURN n" where n = EIdent "n" case_simpleMatchExample2 :: Assertion case_simpleMatchExample2 = show ex2 @?= "MATCH (me)-[:KNOWS*1..2]-(remote_friend) RETURN remote_friend.name" where ex2 :: Query '[Str] ex2 = simpleMatch (PRel left right Nothing (Just range) RelBoth [] ["KNOWS"]) (RetE (EProp remote_friend "name") ::: HNil) range = Range (Just 1) (Just 2) remote_friend = EIdent "remote_friend" me = EIdent "me" left = PNode (Just me) [] [] right = PNode (Just remote_friend) [] [] main :: IO () main = $defaultMainGenerator
HaskellDC/neo4j-cypher
tests/Language/cypher-test-suite.hs
bsd-3-clause
939
0
12
177
291
154
137
24
1
module Main where import Data.Ord (comparing) import qualified Data.Vector.Algorithms.Intro as Intro import qualified Data.Vector.Storable as VS import Data.Vector.Storable.Mutable (IOVector) import Numeric.LinearAlgebra hiding (eig, vector) import Numeric.LinearAlgebra.Arnoldi import Test.Hspec import Test.QuickCheck main :: IO () main = hspec $ do describe "Numeric.LinearAlgebra.Arnoldi.eig" $ do it "returns the diagonal of an arbitrary diagonal matrix" $ property $ do dim <- arbitrary `suchThat` (> 3) diagonal <- VS.fromList <$> vector dim let _matrix = diag diagonal :: Matrix Double nev = dim - 3 options = Options { which = SR , number = nev , maxIterations = Nothing } sort = VS.modify Intro.sort actual = (sort . fst) (eig options dim (multiply _matrix)) expected = (VS.take nev . sort) diagonal relative = VS.maximum (VS.zipWith (%) expected actual) pure (counterexample (show (expected, actual)) (relative < 1E-4)) it "returns the diagonal of an arbitrary diagonal matrix" $ property $ do dim <- arbitrary `suchThat` (> 3) diagonal <- VS.fromList <$> vector dim let _matrix = diag diagonal :: Matrix (Complex Double) nev = dim - 3 options = Options { which = SR , number = nev , maxIterations = Nothing } sort = VS.modify (Intro.sortBy (comparing realPart)) actual = (sort . fst) (eig options dim (multiply _matrix)) expected = (VS.take nev . sort) diagonal relative = VS.maximum (VS.zipWith (%%) expected actual) pure (counterexample (show (expected, actual)) (relative < 1E-4)) multiply :: Numeric a => Matrix a -> IOVector a -> IOVector a -> IO () multiply _matrix dst src = do x <- VS.freeze src let y = _matrix #> x VS.copy dst y (%) :: Double -> Double -> Double (%) a b = let a_plus_b = a + b in if a_plus_b /= 0 then abs ((a - b) / a_plus_b) else a - b (%%) :: Complex Double -> Complex Double -> Double (%%) a b = let a_plus_b = a + b in if a_plus_b /= 0 then magnitude ((a - b) / a_plus_b) else magnitude (a - b)
ttuegel/arpack
tests/tests.hs
bsd-3-clause
2,306
0
21
697
807
427
380
57
2
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} -- http://blog.jle.im/entry/effectful-recursive-real-world-autos-intro-to-machine -- -- Auto with on/off behavior and effectful stepping. module Auto where import Control.Category.Associative import Control.Category.Structural import Control.Category.Monoidal import Control.Category.Cartesian import Control.Categorical.Bifunctor.Rules import Control.Category import Prelude hiding (id, (.),fst,snd) import Control.Arrow hiding (first,second,(***),(&&&)) import qualified Control.Arrow as A import Control.Applicative import Control.Arrow.CCA import Control.Arrow.CCA.Optimize import Control.Category import Control.Concurrent.Async import Control.Monad import Control.Monad.Fix -- instance Monad Concurrently where -- return = pure -- Concurrently a >>= f = -- Concurrently $ a >>= runConcurrently . f newtype AutoXIO a b = AutoXIO {runAutoXIO :: AutoX IO a b} deriving (Functor,Applicative,Category,Alternative,ArrowChoice,ArrowLoop) autoIO :: (a -> IO (Maybe b, AutoX IO a b)) -> AutoXIO a b autoIO = AutoXIO . AConsX runAutoIO :: AutoXIO a b -> a -> IO (Maybe b, AutoX IO a b) runAutoIO = runAutoX . runAutoXIO runAutoIO_ :: AutoXIO a b -> a -> IO (Maybe b) runAutoIO_ f a = liftM fst $ (runAutoX . runAutoXIO) f a instance PFunctor (,) AutoXIO where first (AutoXIO a) = AutoXIO $ first a instance QFunctor (,) AutoXIO where second (AutoXIO a) = AutoXIO $ second a instance Bifunctor (,) AutoXIO where (***) = (A.***) instance Contract (,) AutoXIO where (&&&) = (A.&&&) instance Arrow AutoXIO where arr :: (b -> c) -> AutoXIO b c arr f = AutoXIO $ AConsX $ \b -> return (Just $ f b,arr f) first (AutoXIO a) = AutoXIO $ first a second (AutoXIO a) = AutoXIO $ second a a1 *** a2 = autoIO $ \(x1, x2) -> do ( (y1,a1') , (y2,a2') ) <- concurrently (runAutoIO a1 x1) (runAutoIO a2 x2) return (liftA2 (,) y1 y2, a1' *** a2') a1 &&& a2 = autoIO $ \x -> do ( (y1,a1') , (y2,a2') ) <- concurrently (runAutoIO a1 x) (runAutoIO a2 x) return (liftA2 (,) y1 y2, a1' &&& a2') instance ArrowCCA AutoXIO where delay b = AutoXIO $ delay b type M AutoXIO = IO arrM f = AutoXIO $ arrM f arrIO :: (a -> IO b) -> AutoXIO a b arrIO action = AutoXIO $ AConsX $ \a -> do b <- action a return (Just b,runAutoXIO $ arrIO action) arrMonad :: Monad m => (a -> m b) -> AutoX m a b arrMonad action = AConsX $ \a -> do b <- action a return (Just b,arrMonad action) --} -- | The AutoX type: Auto with on/off behavior and effectful stepping. newtype AutoX m a b = AConsX { runAutoX :: a -> m (Maybe b, AutoX m a b) } testAutoM :: Monad m => AutoX m a b -> [a] -> m ([Maybe b], AutoX m a b) testAutoM a [] = return ([], a) testAutoM a (x:xs) = do (y , a' ) <- runAutoX a x (ys, a'') <- testAutoM a' xs return (y:ys, a'') testAutoM_ :: Monad m => AutoX m a b -> [a] -> m [Maybe b] testAutoM_ a as = liftM fst $ testAutoM a as {- newtype AAuto m a b = A {runA :: m a (Maybe b,AAuto m a b)} instance ArrowChoice m => Category (AAuto m) where id = A $ arr (\a->(Just a,id)) g . f= A $ proc x -> do (y, f') <- runA f -< x (z, g') <- case y of Just _y -> runA g -< _y Nothing -> returnA -< (Nothing, g) returnA -< (z, g' . f') instance Arrow m => Functor (AAuto m r) where fmap f a = A $ proc x -> do (y, a') <- runA a -< x returnA -< (fmap f y, fmap f a') instance Arrow m => Applicative (AAuto m r) where pure y = A $ proc _ -> returnA -< (Just y, pure y) af <*> ay = A $ proc x -> do (f, af') <- runA af -< x (y, ay') <- runA ay -< x returnA -< (f <*> y, af' <*> ay') instance ArrowChoice m => Arrow (AAuto m) where arr f = A $ proc x -> returnA -< (Just (f x), arr f) first a = A $ proc (x, z) -> do (y, a') <- runA a -< x returnA -< (fmap (,z) y , first a') -} -- Instances instance Monad m => Category (AutoX m) where id = AConsX $ \x -> return (Just x, id) g . f = AConsX $ \x -> do (y, f') <- runAutoX f x (z, g') <- case y of Just _y -> runAutoX g _y Nothing -> return (Nothing, g) return (z, g' . f') instance Monad m => Functor (AutoX m r) where fmap f a = AConsX $ \x -> do (y, a') <- runAutoX a x return (fmap f y, fmap f a') instance Monad m => Applicative (AutoX m r) where pure y = AConsX $ \_ -> return (Just y, pure y) af <*> ay = AConsX $ \x -> do (f, af') <- runAutoX af x (y, ay') <- runAutoX ay x return (f <*> y, af' <*> ay') instance MonadFix m => PFunctor (,) (AutoX m) where first = A.first instance MonadFix m => Contract (,) (AutoX m) where (&&&) = (A.&&&) instance MonadFix m => QFunctor (,) (AutoX m) where second = A.second instance MonadFix m => Bifunctor (,) (AutoX m) where instance MonadFix m => Arrow (AutoX m) where arr f = AConsX $ \x -> return (Just (f x), arr f) first a = AConsX $ \(x, z) -> do (y, a') <- runAutoX a x return (fmap (,z) y , first a') second a = AConsX $ \(z, x) -> do (y, a') <- runAutoX a x return (fmap (z,) y, second a') a1 *** a2 = AConsX $ \(x1, x2) -> do (y1, a1') <- runAutoX a1 x1 (y2, a2') <- runAutoX a2 x2 return (liftA2 (,) y1 y2, a1' *** a2') a1 &&& a2 = AConsX $ \x -> do (y1, a1') <- runAutoX a1 x (y2, a2') <- runAutoX a2 x return (liftA2 (,) y1 y2, a1' &&& a2') instance MonadFix m => ArrowChoice (AutoX m) where left a = AConsX $ \x -> case x of Left l -> do (l', a') <- runAutoX a l return (fmap Left l', left a') Right r -> return (Just (Right r), left a) instance Monad m => Alternative (AutoX m a) where empty = AConsX $ \_ -> return (Nothing, empty) a1 <|> a2 = AConsX $ \x -> do (y1, a1') <- runAutoX a1 x (y2, a2') <- runAutoX a2 x return (y1 <|> y2, a1' <|> a2') instance MonadFix m => ArrowLoop (AutoX m) where loop a = AConsX $ \x -> do rec {(Just (y, d), a') <- runAutoX a (x, d)} return (Just y, loop a') instance MonadFix m => ArrowCCA (AutoX m) where -- added 2015 TB delay b = AConsX $ \a -> return (Just b,delay a) type M (AutoX m) = m arrM f = aConsM $ \x -> do y <- f x return (y, arrM f) -- urggghh my head hurt so much trying to write this in a clean way using -- recursive do notation instead of explicit calls to `mfix` and `fix`. -- Anyone want to submit a pull request? :) -- -- instance MonadFix m => ArrowLoop (AutoX m) where -- | Smart constructors -- -- aCons: Use as you would use `ACons`, but makes an `AutoX`. aCons :: Monad m => (a -> (b, AutoX m a b)) -> AutoX m a b aCons a = AConsX $ \x -> let (y, aX) = a x in return (Just y, aX) -- aConsM: Use as you would use `AConsM`, but makes an `AutoX`. aConsM :: Monad m => (a -> m (b, AutoX m a b)) -> AutoX m a b aConsM a = AConsX $ \x -> do (y, aX) <- a x return (Just y, aX) -- aConsOn: Use as you would use `AConsOn`, but makes an `AutoX`. aConsOn :: Monad m => (a -> (Maybe b, AutoX m a b)) -> AutoX m a b aConsOn a = AConsX $ \x -> let (y, aX) = a x in return (y, aX) -- | AutoX Test Autos -- -- summer: Outputs the sum of all inputs so far. Demonstrates the usage of -- the `aCons` smart constructor. summer :: (Monad m, Num a) => AutoX m a a summer = sumFrom 0 where sumFrom n = aCons $ \input -> let s = n + input in ( s , sumFrom s ) -- arrMM: Converts an `a -> m b` into an always-on `AutoX` that just runs -- the function on the input and outputs the result. Demonstrates the -- usage of the `aConsM` smart constructor. arrMM :: Monad m => (a -> m b) -> AutoX m a b arrMM f = aConsM $ \x -> do y <- f x return (y, arrMM f) -- untilA: Lets all values pass through until the first one that satisfies -- the predicate. Demonstrates the usage of the `aConsOn` smart -- constructor. untilA :: Monad m => (a -> Bool) -> AutoX m a a untilA p = aConsOn $ \x -> if p x then (Just x , untilA p) else (Nothing, empty )
tomberek/rulestesting
Auto.hs
bsd-3-clause
9,312
0
15
3,104
3,040
1,585
1,455
166
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.StorageGateway.DeleteBandwidthRateLimit -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- This operation deletes the bandwidth rate limits of a gateway. You can -- delete either the upload and download bandwidth rate limit, or you can -- delete both. If you delete only one of the limits, the other limit -- remains unchanged. To specify which gateway to work with, use the Amazon -- Resource Name (ARN) of the gateway in your request. -- -- /See:/ <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_DeleteBandwidthRateLimit.html AWS API Reference> for DeleteBandwidthRateLimit. module Network.AWS.StorageGateway.DeleteBandwidthRateLimit ( -- * Creating a Request deleteBandwidthRateLimit , DeleteBandwidthRateLimit -- * Request Lenses , dbrlbGatewayARN , dbrlbBandwidthType -- * Destructuring the Response , deleteBandwidthRateLimitResponse , DeleteBandwidthRateLimitResponse -- * Response Lenses , delrsGatewayARN , delrsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.StorageGateway.Types import Network.AWS.StorageGateway.Types.Product -- | /See:/ 'deleteBandwidthRateLimit' smart constructor. data DeleteBandwidthRateLimit = DeleteBandwidthRateLimit' { _dbrlbGatewayARN :: !Text , _dbrlbBandwidthType :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteBandwidthRateLimit' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dbrlbGatewayARN' -- -- * 'dbrlbBandwidthType' deleteBandwidthRateLimit :: Text -- ^ 'dbrlbGatewayARN' -> Text -- ^ 'dbrlbBandwidthType' -> DeleteBandwidthRateLimit deleteBandwidthRateLimit pGatewayARN_ pBandwidthType_ = DeleteBandwidthRateLimit' { _dbrlbGatewayARN = pGatewayARN_ , _dbrlbBandwidthType = pBandwidthType_ } -- | Undocumented member. dbrlbGatewayARN :: Lens' DeleteBandwidthRateLimit Text dbrlbGatewayARN = lens _dbrlbGatewayARN (\ s a -> s{_dbrlbGatewayARN = a}); -- | Undocumented member. dbrlbBandwidthType :: Lens' DeleteBandwidthRateLimit Text dbrlbBandwidthType = lens _dbrlbBandwidthType (\ s a -> s{_dbrlbBandwidthType = a}); instance AWSRequest DeleteBandwidthRateLimit where type Rs DeleteBandwidthRateLimit = DeleteBandwidthRateLimitResponse request = postJSON storageGateway response = receiveJSON (\ s h x -> DeleteBandwidthRateLimitResponse' <$> (x .?> "GatewayARN") <*> (pure (fromEnum s))) instance ToHeaders DeleteBandwidthRateLimit where toHeaders = const (mconcat ["X-Amz-Target" =# ("StorageGateway_20130630.DeleteBandwidthRateLimit" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DeleteBandwidthRateLimit where toJSON DeleteBandwidthRateLimit'{..} = object (catMaybes [Just ("GatewayARN" .= _dbrlbGatewayARN), Just ("BandwidthType" .= _dbrlbBandwidthType)]) instance ToPath DeleteBandwidthRateLimit where toPath = const "/" instance ToQuery DeleteBandwidthRateLimit where toQuery = const mempty -- | A JSON object containing the of the gateway whose bandwidth rate -- information was deleted. -- -- /See:/ 'deleteBandwidthRateLimitResponse' smart constructor. data DeleteBandwidthRateLimitResponse = DeleteBandwidthRateLimitResponse' { _delrsGatewayARN :: !(Maybe Text) , _delrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteBandwidthRateLimitResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'delrsGatewayARN' -- -- * 'delrsResponseStatus' deleteBandwidthRateLimitResponse :: Int -- ^ 'delrsResponseStatus' -> DeleteBandwidthRateLimitResponse deleteBandwidthRateLimitResponse pResponseStatus_ = DeleteBandwidthRateLimitResponse' { _delrsGatewayARN = Nothing , _delrsResponseStatus = pResponseStatus_ } -- | Undocumented member. delrsGatewayARN :: Lens' DeleteBandwidthRateLimitResponse (Maybe Text) delrsGatewayARN = lens _delrsGatewayARN (\ s a -> s{_delrsGatewayARN = a}); -- | The response status code. delrsResponseStatus :: Lens' DeleteBandwidthRateLimitResponse Int delrsResponseStatus = lens _delrsResponseStatus (\ s a -> s{_delrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-storagegateway/gen/Network/AWS/StorageGateway/DeleteBandwidthRateLimit.hs
mpl-2.0
5,353
0
13
1,098
666
397
269
90
1
-- | -- Module: SwiftNav.SBP.ExtEvents -- Copyright: Copyright (C) 2015 Swift Navigation, Inc. -- License: LGPL-3 -- Maintainer: Mark Fine <[email protected]> -- Stability: experimental -- Portability: portable -- -- Messages reporting accurately-timestamped external events, e.g. camera -- shutter time. module SwiftNav.SBP.ExtEvents where import BasicPrelude import Control.Lens import Control.Monad.Loops import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier) import Data.Binary import Data.Binary.Get import Data.Binary.IEEE754 import Data.Binary.Put import Data.ByteString import Data.ByteString.Lazy hiding ( ByteString ) import Data.Int import Data.Word import SwiftNav.SBP.Encoding import SwiftNav.SBP.TH import SwiftNav.SBP.Types msgExtEvent :: Word16 msgExtEvent = 0x0101 -- | SBP class for message MSG_EXT_EVENT (0x0101). -- -- Reports detection of an external event, the GPS time it occurred, which pin -- it was and whether it was rising or falling. data MsgExtEvent = MsgExtEvent { _msgExtEvent_wn :: Word16 -- ^ GPS week number , _msgExtEvent_tow :: Word32 -- ^ GPS time of week rounded to the nearest millisecond , _msgExtEvent_ns :: Int32 -- ^ Nanosecond residual of millisecond-rounded TOW (ranges from -500000 to -- 500000) , _msgExtEvent_flags :: Word8 -- ^ Flags , _msgExtEvent_pin :: Word8 -- ^ Pin number. 0..9 = DEBUG0..9. } deriving ( Show, Read, Eq ) instance Binary MsgExtEvent where get = do _msgExtEvent_wn <- getWord16le _msgExtEvent_tow <- getWord32le _msgExtEvent_ns <- liftM fromIntegral getWord32le _msgExtEvent_flags <- getWord8 _msgExtEvent_pin <- getWord8 return MsgExtEvent {..} put MsgExtEvent {..} = do putWord16le _msgExtEvent_wn putWord32le _msgExtEvent_tow putWord32le $ fromIntegral _msgExtEvent_ns putWord8 _msgExtEvent_flags putWord8 _msgExtEvent_pin $(deriveSBP 'msgExtEvent ''MsgExtEvent) $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_msgExtEvent_" . stripPrefix "_msgExtEvent_"} ''MsgExtEvent) $(makeLenses ''MsgExtEvent)
mookerji/libsbp
haskell/src/SwiftNav/SBP/ExtEvents.hs
lgpl-3.0
2,123
0
11
369
361
203
158
-1
-1
{- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-| Functions for generating, reading and writing secrets for use with local authentication method -} module CodeWorld.Auth.Secret ( Secret(..) , generateSecret , readSecret , writeSecret ) where import Crypto.Random (getRandomBytes) import Data.ByteString (ByteString) import qualified Data.ByteString as ByteString (readFile, writeFile) import qualified Data.ByteString.Base64 as Base64 (decode, encode) data Secret = Secret ByteString deriving Eq -- |Generates a new, random secret generateSecret :: IO Secret -- ^ Secret generateSecret = Secret <$> getRandomBytes 32 -- |Writes a secret to a file writeSecret :: FilePath -- ^ File path -> Secret -- ^ Secret -> IO () -- ^ Result writeSecret path (Secret bytes) = ByteString.writeFile path (Base64.encode bytes) -- |Reads a secret from a file readSecret :: FilePath -- ^ File path -> IO Secret -- ^ Result readSecret path = do s <- ByteString.readFile path case Base64.decode s of Left e -> error e Right bytes -> return $ Secret bytes
alphalambda/codeworld
codeworld-auth/src/CodeWorld/Auth/Secret.hs
apache-2.0
1,714
0
11
381
242
136
106
26
2
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="pl-PL"> <title>Authentication Statistics | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/authstats/src/main/javahelp/org/zaproxy/zap/extension/authstats/resources/help_pl_PL/helpset_pl_PL.hs
apache-2.0
987
80
66
160
415
210
205
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : HEP.Kinematics.Vector.LorentzTVector -- Copyright : (c) 2014-2017 Chan Beom Park -- License : BSD-style -- Maintainer : Chan Beom Park <[email protected]> -- Stability : experimental -- Portability : GHC -- -- (2+1)-dimensional vector. -- -------------------------------------------------------------------------------- {-# LANGUAGE BangPatterns #-} module HEP.Kinematics.Vector.LorentzTVector ( -- * Type LorentzTVector -- * Function , setXYM , setXYT , invariantMass ) where import Control.Applicative import Linear.Metric (Metric (..)) import Linear.V2 (V2 (..)) import Linear.V3 (R1 (..), R2 (..), V3 (..)) import Linear.Vector (Additive (..)) -- | Type for (2+1)-dimensional vector. newtype LorentzTVector a = LorentzTVector (V3 a) deriving (Eq, Show) instance Num a => Num (LorentzTVector a) where (+) = liftA2 (+) (*) = liftA2 (*) (-) = liftA2 (-) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = pure . fromInteger instance Functor LorentzTVector where fmap f (LorentzTVector v3) = LorentzTVector (fmap f v3) instance Applicative LorentzTVector where pure a = LorentzTVector (V3 a a a) LorentzTVector v3 <*> LorentzTVector v3' = LorentzTVector (v3 <*> v3') instance Additive LorentzTVector where zero = pure 0 instance Metric LorentzTVector where (LorentzTVector (V3 t x y)) `dot` (LorentzTVector (V3 t' x' y')) = t * t' - x * x' - y * y' instance R1 LorentzTVector where _x f (LorentzTVector (V3 t x y)) = (\x' -> LorentzTVector (V3 t x' y)) <$> f x instance R2 LorentzTVector where _y f (LorentzTVector (V3 t x y)) = LorentzTVector . V3 t x <$> f y _xy f (LorentzTVector (V3 t x y)) = (\(V2 x' y') -> LorentzTVector (V3 t x' y')) <$> f (V2 x y) -- | Makes 'LorentzTVector' out of components based on x, y, t coordinates. setXYT :: a -> a -> a -> LorentzTVector a setXYT px py et = LorentzTVector (V3 et px py) {-# INLINE setXYT #-} -- | Makes 'LorentzTVector' out of components based on x, y, m coordinates. setXYM :: Double -> Double -> Double -> LorentzTVector Double setXYM px py m = let !et = sqrt $ px * px + py * py + m * m in setXYT px py et {-# INLINE setXYM #-} -- | Invariant mass. It would be a transverse mass in (3+1)-dimensional space. invariantMass :: LorentzTVector Double -> LorentzTVector Double -> Double invariantMass v v' = norm (v ^+^ v') {-# INLINE invariantMass #-}
cbpark/hep-kinematics
src/HEP/Kinematics/Vector/LorentzTVector.hs
bsd-3-clause
2,612
0
14
588
757
407
350
47
1
{-# LANGUAGE CPP #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE UndecidableInstances #-} module Language.Embedded.Concurrent.Backend.C where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif import Control.Monad.Operational.Higher import Data.Typeable import Language.Embedded.Expression import Language.Embedded.Concurrent.CMD import Language.Embedded.Imperative.CMD import Language.Embedded.Backend.C.Expression import Language.C.Quote.C import Language.C.Monad import qualified Language.C.Syntax as C instance ToIdent ThreadId where toIdent (TIDComp tid) = C.Id tid instance ToIdent (Chan t a) where toIdent (ChanComp c) = C.Id c threadFun :: ThreadId -> String threadFun tid = "thread_" ++ show tid -- | Compile `ThreadCMD`. -- TODO: sharing for threads with the same body compThreadCMD :: CompExp exp => ThreadCMD (Param3 CGen exp pred) a -> CGen a compThreadCMD (ForkWithId body) = do tid <- TIDComp <$> gensym "t" let funName = threadFun tid _ <- inFunctionTy [cty|void*|] funName $ do addParam [cparam| void* unused |] body tid addStm [cstm| return NULL; |] addSystemInclude "pthread.h" touchVar tid addLocal [cdecl| typename pthread_t $id:tid; |] addStm [cstm| pthread_create(&$id:tid, NULL, $id:funName, NULL); |] return tid compThreadCMD (Kill tid) = do touchVar tid addStm [cstm| pthread_cancel($id:tid); |] compThreadCMD (Wait tid) = do touchVar tid addStm [cstm| pthread_join($id:tid, NULL); |] compThreadCMD (Sleep us) = do us' <- compExp us addSystemInclude "unistd.h" addStm [cstm| usleep($us'); |] -- | Compile `ChanCMD`. compChanCMD :: (CompExp exp, CompTypeClass ct, ct Bool) => ChanCMD (Param3 CGen exp ct) a -> CGen a compChanCMD cmd@(NewChan sz) = do addLocalInclude "chan.h" sz' <-compChanSize sz c <- ChanComp <$> gensym "chan" addGlobal [cedecl| typename chan_t $id:c; |] addStm [cstm| $id:c = chan_new($sz'); |] return c compChanCMD cmd@(WriteOne c (x :: exp a)) = do x' <- compExp x v :: Val a <- freshVar (proxyPred cmd) ok <- freshVar (proxyPred cmd) addStm [cstm| $id:v = $x'; |] addStm [cstm| $id:ok = chan_write($id:c, sizeof($id:v), &$id:v); |] return ok compChanCMD cmd@(WriteChan c from to (ArrComp arr)) = do from' <- compExp from to' <- compExp to ok <- freshVar (proxyPred cmd) addStm [cstm| $id:ok = chan_write($id:c, sizeof(*$id:arr)*(($to')-($from')), &$id:arr[$from']); |] return ok compChanCMD cmd@(ReadOne c) = do v <- freshVar (proxyPred cmd) addStm [cstm| chan_read($id:c, sizeof($id:v), &$id:v); |] return v compChanCMD cmd@(ReadChan c from to (ArrComp arr)) = do ok <- freshVar (proxyPred cmd) from' <- compExp from to' <- compExp to addStm [cstm| chan_read($id:c, sizeof(*$id:arr)*(($to')-($from')), &$id:arr[$from']); |] addStm [cstm| $id:ok = chan_last_read_ok($id:c); |] return ok compChanCMD (CloseChan c) = do addStm [cstm| chan_close($id:c); |] compChanCMD cmd@(ReadOK c) = do var <- freshVar (proxyPred cmd) addStm [cstm| $id:var = chan_last_read_ok($id:c); |] return var compChanSize :: forall exp ct i. (CompExp exp, CompTypeClass ct) => ChanSize exp ct i -> CGen C.Exp compChanSize (OneSize t sz) = do t' <- compType (Proxy :: Proxy ct) t sz' <- compExp sz return [cexp| $sz' * sizeof($ty:t') |] compChanSize (TimesSize n sz) = do n' <- compExp n sz' <- compChanSize sz return [cexp| $n' * $sz' |] compChanSize (PlusSize a b) = do a' <- compChanSize a b' <- compChanSize b return [cexp| $a' + $b' |] instance CompExp exp => Interp ThreadCMD CGen (Param2 exp pred) where interp = compThreadCMD instance (CompExp exp, CompTypeClass ct, ct Bool) => Interp ChanCMD CGen (Param2 exp ct) where interp = compChanCMD
kmate/imperative-edsl
src/Language/Embedded/Concurrent/Backend/C.hs
bsd-3-clause
3,765
0
11
700
1,217
617
600
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 2000 FunDeps - functional dependencies It's better to read it as: "if we know these, then we're going to know these" -} {-# LANGUAGE CPP #-} module Eta.TypeCheck.FunDeps ( FDEq (..), Equation(..), pprEquation, improveFromInstEnv, improveFromAnother, checkInstCoverage, checkFunDeps, pprFundeps ) where #include "HsVersions.h" import Eta.BasicTypes.Name import Eta.BasicTypes.Var import Eta.Types.Class import Eta.Types.Type import Eta.Types.Unify import Eta.Types.InstEnv import Eta.BasicTypes.VarSet import Eta.BasicTypes.VarEnv import Eta.Utils.Outputable import Eta.Main.ErrUtils( Validity(..), allValid ) import Eta.BasicTypes.SrcLoc import Eta.Utils.Util import Eta.Utils.FastString import Data.List ( nubBy ) import Data.Maybe ( isJust ) {- ************************************************************************ * * \subsection{Generate equations from functional dependencies} * * ************************************************************************ Each functional dependency with one variable in the RHS is responsible for generating a single equality. For instance: class C a b | a -> b The constraints ([Wanted] C Int Bool) and [Wanted] C Int alpha FDEq { fd_pos = 1 , fd_ty_left = Bool , fd_ty_right = alpha } However notice that a functional dependency may have more than one variable in the RHS which will create more than one FDEq. Example: class C a b c | a -> b c [Wanted] C Int alpha alpha [Wanted] C Int Bool beta Will generate: fd1 = FDEq { fd_pos = 1, fd_ty_left = alpha, fd_ty_right = Bool } and fd2 = FDEq { fd_pos = 2, fd_ty_left = alpha, fd_ty_right = beta } We record the paremeter position so that can immediately rewrite a constraint using the produced FDEqs and remove it from our worklist. INVARIANT: Corresponding types aren't already equal That is, there exists at least one non-identity equality in FDEqs. Assume: class C a b c | a -> b c instance C Int x x And: [Wanted] C Int Bool alpha We will /match/ the LHS of fundep equations, producing a matching substitution and create equations for the RHS sides. In our last example we'd have generated: ({x}, [fd1,fd2]) where fd1 = FDEq 1 Bool x fd2 = FDEq 2 alpha x To ``execute'' the equation, make fresh type variable for each tyvar in the set, instantiate the two types with these fresh variables, and then unify or generate a new constraint. In the above example we would generate a new unification variable 'beta' for x and produce the following constraints: [Wanted] (Bool ~ beta) [Wanted] (alpha ~ beta) Notice the subtle difference between the above class declaration and: class C a b c | a -> b, a -> c where we would generate: ({x},[fd1]),({x},[fd2]) This means that the template variable would be instantiated to different unification variables when producing the FD constraints. Finally, the position parameters will help us rewrite the wanted constraint ``on the spot'' -} data Equation loc = FDEqn { fd_qtvs :: [TyVar] -- Instantiate these type and kind vars to fresh unification vars , fd_eqs :: [FDEq] -- and then make these equal , fd_pred1, fd_pred2 :: PredType -- The Equation arose from combining these two constraints , fd_loc :: loc } data FDEq = FDEq { fd_pos :: Int -- We use '0' for the first position , fd_ty_left :: Type , fd_ty_right :: Type } instance Outputable FDEq where ppr (FDEq { fd_pos = p, fd_ty_left = tyl, fd_ty_right = tyr }) = parens (int p <> comma <+> ppr tyl <> comma <+> ppr tyr) {- Given a bunch of predicates that must hold, such as C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5 improve figures out what extra equations must hold. For example, if we have class C a b | a->b where ... then improve will return [(t1,t2), (t4,t5)] NOTA BENE: * improve does not iterate. It's possible that when we make t1=t2, for example, that will in turn trigger a new equation. This would happen if we also had C t1 t7, C t2 t8 If t1=t2, we also get t7=t8. improve does *not* do this extra step. It relies on the caller doing so. * The equations unify types that are not already equal. So there is no effect iff the result of improve is empty -} instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type -- A simpler version of instFD_WithPos to be used in checking instance coverage etc. instFD (ls,rs) tvs tys = (map lookup ls, map lookup rs) where env = zipVarEnv tvs tys lookup tv = lookupVarEnv_NF env tv instFD_WithPos :: FunDep TyVar -> [TyVar] -> [Type] -> ([Type], [(Int,Type)]) -- Returns a FunDep between the types accompanied along with their -- position (<=0) in the types argument list. instFD_WithPos (ls,rs) tvs tys = (map (snd . lookup) ls, map lookup rs) where ind_tys = zip [0..] tys env = zipVarEnv tvs ind_tys lookup tv = lookupVarEnv_NF env tv zipAndComputeFDEqs :: (Type -> Type -> Bool) -- Discard this FDEq if true -> [Type] -> [(Int,Type)] -> [FDEq] -- Create a list of FDEqs from two lists of types, making sure -- that the types are not equal. zipAndComputeFDEqs discard (ty1:tys1) ((i2,ty2):tys2) | discard ty1 ty2 = zipAndComputeFDEqs discard tys1 tys2 | otherwise = FDEq { fd_pos = i2 , fd_ty_left = ty1 , fd_ty_right = ty2 } : zipAndComputeFDEqs discard tys1 tys2 zipAndComputeFDEqs _ _ _ = [] -- Improve a class constraint from another class constraint -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ improveFromAnother :: PredType -- Template item (usually given, or inert) -> PredType -- Workitem [that can be improved] -> [Equation ()] -- Post: FDEqs always oriented from the other to the workitem -- Equations have empty quantified variables improveFromAnother pred1 pred2 | Just (cls1, tys1) <- getClassPredTys_maybe pred1 , Just (cls2, tys2) <- getClassPredTys_maybe pred2 , tys1 `lengthAtLeast` 2 && cls1 == cls2 = [ FDEqn { fd_qtvs = [], fd_eqs = eqs, fd_pred1 = pred1, fd_pred2 = pred2, fd_loc = () } | let (cls_tvs, cls_fds) = classTvsFds cls1 , fd <- cls_fds , let (ltys1, rs1) = instFD fd cls_tvs tys1 (ltys2, irs2) = instFD_WithPos fd cls_tvs tys2 , eqTypes ltys1 ltys2 -- The LHSs match , let eqs = zipAndComputeFDEqs eqType rs1 irs2 , not (null eqs) ] improveFromAnother _ _ = [] -- Improve a class constraint from instance declarations -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pprEquation :: Equation a -> SDoc pprEquation (FDEqn { fd_qtvs = qtvs, fd_eqs = pairs }) = vcat [ptext (sLit "forall") <+> braces (pprWithCommas ppr qtvs), nest 2 (vcat [ ppr t1 <+> ptext (sLit "~") <+> ppr t2 | (FDEq _ t1 t2) <- pairs])] improveFromInstEnv :: InstEnvs -> PredType -> [Equation SrcSpan] -- Needs to be an Equation because -- of quantified variables -- Post: Equations oriented from the template (matching instance) to the workitem! improveFromInstEnv _inst_env pred | not (isClassPred pred) = panic "improveFromInstEnv: not a class predicate" improveFromInstEnv inst_env pred | Just (cls, tys) <- getClassPredTys_maybe pred , tys `lengthAtLeast` 2 , let (cls_tvs, cls_fds) = classTvsFds cls instances = classInstances inst_env cls rough_tcs = roughMatchTcs tys = [ FDEqn { fd_qtvs = meta_tvs, fd_eqs = eqs , fd_pred1 = p_inst, fd_pred2=pred , fd_loc = getSrcSpan (is_dfun ispec) } | fd <- cls_fds -- Iterate through the fundeps first, -- because there often are none! , let trimmed_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs -- Trim the rough_tcs based on the head of the fundep. -- Remember that instanceCantMatch treats both argumnents -- symmetrically, so it's ok to trim the rough_tcs, -- rather than trimming each inst_tcs in turn , ispec <- instances , (meta_tvs, eqs) <- checkClsFD fd cls_tvs ispec emptyVarSet tys trimmed_tcs -- NB: orientation , let p_inst = mkClassPred cls (is_tys ispec) ] improveFromInstEnv _ _ = [] checkClsFD :: FunDep TyVar -> [TyVar] -- One functional dependency from the class -> ClsInst -- An instance template -> TyVarSet -> [Type] -> [Maybe Name] -- Arguments of this (C tys) predicate -- TyVarSet are extra tyvars that can be instantiated -> [([TyVar], [FDEq])] checkClsFD fd clas_tvs (ClsInst { is_tvs = qtvs, is_tys = tys_inst, is_tcs = rough_tcs_inst }) extra_qtvs tys_actual rough_tcs_actual -- 'qtvs' are the quantified type variables, the ones which an be instantiated -- to make the types match. For example, given -- class C a b | a->b where ... -- instance C (Maybe x) (Tree x) where .. -- -- and an Inst of form (C (Maybe t1) t2), -- then we will call checkClsFD with -- -- is_qtvs = {x}, is_tys = [Maybe x, Tree x] -- tys_actual = [Maybe t1, t2] -- -- We can instantiate x to t1, and then we want to force -- (Tree x) [t1/x] ~ t2 -- -- This function is also used when matching two Insts (rather than an Inst -- against an instance decl. In that case, qtvs is empty, and we are doing -- an equality check -- -- This function is also used by InstEnv.badFunDeps, which needs to *unify* -- For the one-sided matching case, the qtvs are just from the template, -- so we get matching | instanceCantMatch rough_tcs_inst rough_tcs_actual = [] -- Filter out ones that can't possibly match, | otherwise = ASSERT2( length tys_inst == length tys_actual && length tys_inst == length clas_tvs , ppr tys_inst <+> ppr tys_actual ) case tcUnifyTys bind_fn ltys1 ltys2 of Nothing -> [] Just subst | isJust (tcUnifyTys bind_fn rtys1' rtys2') -- Don't include any equations that already hold. -- Reason: then we know if any actual improvement has happened, -- in which case we need to iterate the solver -- In making this check we must taking account of the fact that any -- qtvs that aren't already instantiated can be instantiated to anything -- at all -- NB: We can't do this 'is-useful-equation' check element-wise -- because of: -- class C a b c | a -> b c -- instance C Int x x -- [Wanted] C Int alpha Int -- We would get that x -> alpha (isJust) and x -> Int (isJust) -- so we would produce no FDs, which is clearly wrong. -> [] | null fdeqs -> [] | otherwise -> [(meta_tvs, fdeqs)] -- We could avoid this substTy stuff by producing the eqn -- (qtvs, ls1++rs1, ls2++rs2) -- which will re-do the ls1/ls2 unification when the equation is -- executed. What we're doing instead is recording the partial -- work of the ls1/ls2 unification leaving a smaller unification problem where rtys1' = map (substTy subst) rtys1 irs2' = map (\(i,x) -> (i,substTy subst x)) irs2 rtys2' = map snd irs2' fdeqs = zipAndComputeFDEqs (\_ _ -> False) rtys1' irs2' -- Don't discard anything! -- We could discard equal types but it's an overkill to call -- eqType again, since we know for sure that /at least one/ -- equation in there is useful) meta_tvs = [ setVarType tv (substTy subst (varType tv)) | tv <- qtvs, tv `notElemTvSubst` subst ] -- meta_tvs are the quantified type variables -- that have not been substituted out -- -- Eg. class C a b | a -> b -- instance C Int [y] -- Given constraint C Int z -- we generate the equation -- ({y}, [y], z) -- -- But note (a) we get them from the dfun_id, so they are *in order* -- because the kind variables may be mentioned in the -- type variabes' kinds -- (b) we must apply 'subst' to the kinds, in case we have -- matched out a kind variable, but not a type variable -- whose kind mentions that kind variable! -- Trac #6015, #6068 where qtv_set = mkVarSet qtvs bind_fn tv | tv `elemVarSet` qtv_set = BindMe | tv `elemVarSet` extra_qtvs = BindMe | otherwise = Skolem (ltys1, rtys1) = instFD fd clas_tvs tys_inst (ltys2, irs2) = instFD_WithPos fd clas_tvs tys_actual {- ************************************************************************ * * The Coverage condition for instance declarations * * ************************************************************************ Note [Coverage condition] ~~~~~~~~~~~~~~~~~~~~~~~~~ Example class C a b | a -> b instance theta => C t1 t2 For the coverage condition, we check (normal) fv(t2) `subset` fv(t1) (liberal) fv(t2) `subset` oclose(fv(t1), theta) The liberal version ensures the self-consistency of the instance, but it does not guarantee termination. Example: class Mul a b c | a b -> c where (.*.) :: a -> b -> c instance Mul Int Int Int where (.*.) = (*) instance Mul Int Float Float where x .*. y = fromIntegral x * y instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]). But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) ) But it is a mistake to accept the instance because then this defn: f = \ b x y -> if b then x .*. [y] else y makes instance inference go into a loop, because it requires the constraint Mul a [b] b -} checkInstCoverage :: Bool -- Be liberal -> Class -> [PredType] -> [Type] -> Validity -- "be_liberal" flag says whether to use "liberal" coverage of -- See Note [Coverage Condition] below -- -- Return values -- Nothing => no problems -- Just msg => coverage problem described by msg checkInstCoverage be_liberal clas theta inst_taus = allValid (map fundep_ok fds) where (tyvars, fds) = classTvsFds clas fundep_ok fd | if be_liberal then liberal_ok else conservative_ok = IsValid | otherwise = NotValid msg where (ls,rs) = instFD fd tyvars inst_taus ls_tvs = tyVarsOfTypes ls rs_tvs = tyVarsOfTypes rs conservative_ok = rs_tvs `subVarSet` closeOverKinds ls_tvs liberal_ok = rs_tvs `subVarSet` oclose theta (closeOverKinds ls_tvs) -- closeOverKinds: see Note [Closing over kinds in coverage] msg = vcat [ -- text "ls_tvs" <+> ppr ls_tvs -- , text "closed ls_tvs" <+> ppr (closeOverKinds ls_tvs) -- , text "theta" <+> ppr theta -- , text "oclose" <+> ppr (oclose theta (closeOverKinds ls_tvs)) -- , text "rs_tvs" <+> ppr rs_tvs sep [ ptext (sLit "The") <+> ppWhen be_liberal (ptext (sLit "liberal")) <+> ptext (sLit "coverage condition fails in class") <+> quotes (ppr clas) , nest 2 $ ptext (sLit "for functional dependency:") <+> quotes (pprFunDep fd) ] , sep [ ptext (sLit "Reason: lhs type")<>plural ls <+> pprQuotedList ls , nest 2 $ (if isSingleton ls then ptext (sLit "does not") else ptext (sLit "do not jointly")) <+> ptext (sLit "determine rhs type")<>plural rs <+> pprQuotedList rs ] , ppWhen (not be_liberal && liberal_ok) $ ptext (sLit "Using UndecidableInstances might help") ] {- Note [Closing over kinds in coverage] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have a fundep (a::k) -> b Then if 'a' is instantiated to (x y), where x:k2->*, y:k2, then fixing x really fixes k2 as well, and so k2 should be added to the lhs tyvars in the fundep check. Example (Trac #8391), using liberal coverage data Foo a = ... -- Foo :: forall k. k -> * class Bar a b | a -> b instance Bar a (Foo a) In the instance decl, (a:k) does fix (Foo k a), but only if we notice that (a:k) fixes k. Trac #10109 is another example. Here is a more subtle example, from HList-0.4.0.0 (Trac #10564) class HasFieldM (l :: k) r (v :: Maybe *) | l r -> v where ... class HasFieldM1 (b :: Maybe [*]) (l :: k) r v | b l r -> v where ... class HMemberM (e1 :: k) (l :: [k]) (r :: Maybe [k]) | e1 l -> r data Label :: k -> * type family LabelsOf (a :: [*]) :: * instance (HMemberM (Label {k} (l::k)) (LabelsOf xs) b, HasFieldM1 b l (r xs) v) => HasFieldM l (r xs) v where Is the instance OK? Does {l,r,xs} determine v? Well: * From the instance constraint HMemberM (Label k l) (LabelsOf xs) b, plus the fundep "| el l -> r" in class HMameberM, we get {l,k,xs} -> b * Note the 'k'!! We must call closeOverKinds on the seed set ls_tvs = {l,r,xs}, BEFORE doing oclose, else the {l,k,xs}->b fundep won't fire. This was the reason for #10564. * So starting from seeds {l,r,xs,k} we do oclose to get first {l,r,xs,k,b}, via the HMemberM constraint, and then {l,r,xs,k,b,v}, via the HasFieldM1 constraint. * And that fixes v. However, we must closeOverKinds whenever augmenting the seed set in oclose! Consider Trac #10109: data Succ a -- Succ :: forall k. k -> * class Add (a :: k1) (b :: k2) (ab :: k3) | a b -> ab instance (Add a b ab) => Add (Succ {k1} (a :: k1)) b (Succ {k3} (ab :: k3}) We start with seed set {a:k1,b:k2} and closeOverKinds to {a,k1,b,k2}. Now use the fundep to extend to {a,k1,b,k2,ab}. But we need to closeOverKinds *again* now to {a,k1,b,k2,ab,k3}, so that we fix all the variables free in (Succ {k3} ab). Bottom line: * closeOverKinds on initial seeds (in checkInstCoverage) * and closeOverKinds whenever extending those seeds (in oclose) Note [The liberal coverage condition] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (oclose preds tvs) closes the set of type variables tvs, wrt functional dependencies in preds. The result is a superset of the argument set. For example, if we have class C a b | a->b where ... then oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z} because if we know x and y then that fixes z. We also use equality predicates in the predicates; if we have an assumption `t1 ~ t2`, then we use the fact that if we know `t1` we also know `t2` and the other way. eg oclose [C (x,y) z, a ~ x] {a,y} = {a,y,z,x} oclose is used (only) when checking the coverage condition for an instance declaration -} oclose :: [PredType] -> TyVarSet -> TyVarSet -- See Note [The liberal coverage condition] oclose preds fixed_tvs | null tv_fds = fixed_tvs -- Fast escape hatch for common case. | otherwise = loop fixed_tvs where loop fixed_tvs | new_fixed_tvs `subVarSet` fixed_tvs = fixed_tvs | otherwise = loop new_fixed_tvs where new_fixed_tvs = foldl extend fixed_tvs tv_fds extend fixed_tvs (ls,rs) | ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` closeOverKinds rs | otherwise = fixed_tvs -- closeOverKinds: see Note [Closing over kinds in coverage] tv_fds :: [(TyVarSet,TyVarSet)] tv_fds = [ (tyVarsOfTypes ls, tyVarsOfTypes rs) | pred <- preds , (ls, rs) <- determined pred ] determined :: PredType -> [([Type],[Type])] determined pred = case classifyPredType pred of ClassPred cls tys -> do let (cls_tvs, cls_fds) = classTvsFds cls fd <- cls_fds return (instFD fd cls_tvs tys) EqPred NomEq t1 t2 -> [([t1],[t2]), ([t2],[t1])] TuplePred ts -> concatMap determined ts _ -> [] {- ************************************************************************ * * Check that a new instance decl is OK wrt fundeps * * ************************************************************************ Here is the bad case: class C a b | a->b where ... instance C Int Bool where ... instance C Int Char where ... The point is that a->b, so Int in the first parameter must uniquely determine the second. In general, given the same class decl, and given instance C s1 s2 where ... instance C t1 t2 where ... Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2). Matters are a little more complicated if there are free variables in the s2/t2. class D a b c | a -> b instance D a b => D [(a,a)] [b] Int instance D a b => D [a] [b] Bool The instance decls don't overlap, because the third parameter keeps them separate. But we want to make sure that given any constraint D s1 s2 s3 if s1 matches -} checkFunDeps :: InstEnvs -> ClsInst -> Maybe [ClsInst] -- Nothing <=> ok -- Just dfs <=> conflict with dfs -- Check whether adding DFunId would break functional-dependency constraints -- Used only for instance decls defined in the module being compiled checkFunDeps inst_envs ispec | null bad_fundeps = Nothing | otherwise = Just bad_fundeps where (ins_tvs, clas, ins_tys) = instanceHead ispec ins_tv_set = mkVarSet ins_tvs cls_inst_env = classInstances inst_envs clas bad_fundeps = badFunDeps cls_inst_env clas ins_tv_set ins_tys badFunDeps :: [ClsInst] -> Class -> TyVarSet -> [Type] -- Proposed new instance type -> [ClsInst] badFunDeps cls_insts clas ins_tv_set ins_tys = nubBy eq_inst $ [ ispec | fd <- fds, -- fds is often empty, so do this first! let trimmed_tcs = trimRoughMatchTcs clas_tvs fd rough_tcs, ispec <- cls_insts, notNull (checkClsFD fd clas_tvs ispec ins_tv_set ins_tys trimmed_tcs) ] where (clas_tvs, fds) = classTvsFds clas rough_tcs = roughMatchTcs ins_tys eq_inst i1 i2 = instanceDFunId i1 == instanceDFunId i2 -- An single instance may appear twice in the un-nubbed conflict list -- because it may conflict with more than one fundep. E.g. -- class C a b c | a -> b, a -> c -- instance C Int Bool Bool -- instance C Int Char Char -- The second instance conflicts with the first by *both* fundeps trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name] -- Computing rough_tcs for a particular fundep -- class C a b c | a -> b where ... -- For each instance .... => C ta tb tc -- we want to match only on the type ta; so our -- rough-match thing must similarly be filtered. -- Hence, we Nothing-ise the tb and tc types right here trimRoughMatchTcs clas_tvs (ltvs, _) mb_tcs = zipWith select clas_tvs mb_tcs where select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc | otherwise = Nothing
rahulmutt/ghcvm
compiler/Eta/TypeCheck/FunDeps.hs
bsd-3-clause
25,305
0
21
8,213
3,015
1,640
1,375
-1
-1
module Settings.Packages.Haddock (haddockPackageArgs) where import Expression haddockPackageArgs :: Args haddockPackageArgs = package haddock ? builder GhcCabal ? pure ["--flag", "in-ghc-tree"]
bgamari/shaking-up-ghc
src/Settings/Packages/Haddock.hs
bsd-3-clause
200
0
7
26
48
27
21
5
1
-- | Basic types used by this library. {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} module Brick.Types ( Location(..) , locL , TerminalLocation(..) , CursorLocation(..) , cursorLocationL , cursorLocationNameL , HandleEvent(..) , Name(..) , suffixLenses ) where import Control.Lens import Data.String import Data.Monoid (Monoid(..)) import Graphics.Vty (Event) import Brick.Types.TH -- | A terminal screen location. data Location = Location { loc :: (Int, Int) -- ^ (Column, Row) } deriving Show suffixLenses ''Location instance Field1 Location Location Int Int where _1 = locL._1 instance Field2 Location Location Int Int where _2 = locL._2 -- | The class of types that behave like terminal locations. class TerminalLocation a where -- | Get the column out of the value columnL :: Lens' a Int column :: a -> Int -- | Get the row out of the value rowL :: Lens' a Int row :: a -> Int instance TerminalLocation Location where columnL = _1 column (Location t) = fst t rowL = _2 row (Location t) = snd t -- | Names of things. Used to name cursor locations, widgets, and -- viewports. newtype Name = Name String deriving (Eq, Show, Ord) instance IsString Name where fromString = Name -- | The origin (upper-left corner). origin :: Location origin = Location (0, 0) instance Monoid Location where mempty = origin mappend (Location (w1, h1)) (Location (w2, h2)) = Location (w1+w2, h1+h2) -- | A cursor location. These are returned by the rendering process. data CursorLocation = CursorLocation { cursorLocation :: !Location -- ^ The location , cursorLocationName :: !(Maybe Name) -- ^ The name of the widget associated with the location } deriving Show suffixLenses ''CursorLocation instance TerminalLocation CursorLocation where columnL = cursorLocationL._1 column = column . cursorLocation rowL = cursorLocationL._2 row = row . cursorLocation -- | The class of types that provide some basic event-handling. class HandleEvent a where -- | Handle a Vty event handleEvent :: Event -> a -> a
FranklinChen/brick
src/Brick/Types.hs
bsd-3-clause
2,308
0
11
623
505
289
216
59
1
module Manual where import System.IO(openFile,hClose,IOMode(..),hPutStr,stdout) import Data.Char(isAlpha,isDigit) -- Parts of the manual are generated automatically from the -- sources, by generating LaTex files by observing the -- data structures of the Omega sources import LangEval(vals) import Syntax(metaHaskellOps) import Infer(typeConstrEnv0,modes_and_doc,predefined) import Commands(commands) import RankN(Sigma,disp0,Exhibit(..),PolyKind(..)) import Version(version,buildtime) ----------------------------------------- -- LaTex-Like macros figure h body caption label = do { hPutStr h "\\begin{figure}[t]\n" ; body ; hPutStr h ("\\caption{"++caption++"}\\label{"++label++"}\n") ; hPutStr h "\\hrule\n" ; hPutStr h "\\end{figure}\n" } figure2 h body caption label = do { hPutStr h "\\begin{figure}[t]\n" ; hPutStr h "\\begin{multicols}{2}\n" ; body ; hPutStr h "\\end{multicols}\n" ; hPutStr h ("\\caption{"++caption++"}\\label{"++label++"}\n") ; hPutStr h "\\hrule\n" ; hPutStr h "\\end{figure}\n" } verbatim h body = do { hPutStr h "{\\small\n\\begin{verbatim}\n" ; hPutStr h body ; hPutStr h "\\end{verbatim}}\n" } itemize f h items = do { hPutStr h "\\begin{itemize}\n" ; mapM (\ x -> hPutStr h "\\item\n" >> f x >> hPutStr h "\n") items ; hPutStr h "\\end{itemize}\n" } --------------------------------------------------------------------- ------------------------------------------------------------------- -- Printing out tables for the manual vals' = map (\(name,maker) -> (name,maker name)) vals infixOperators = (concat (map f metaHaskellOps)) where f x = case lookup x vals' of Nothing -> [] Just (_,y) -> [(x,showSigma y)] main2 = makeManual "d:/Omega/doc" makeManual :: String -> IO() makeManual dir = go where kindfile = dir ++ "/kinds.tex" prefixfile = dir ++ "/infix.tex" comfile = dir ++ "/commands.tex" modefile = dir ++ "/modes.tex" prefile = dir ++ "/predef.tex" versionfile = dir ++ "/version.tex" licenseSrc = "../LICENSE.txt" licensefile = dir ++ "/license.tex" go = do { putStrLn "Writing tables for Manual" ; h <- openFile kindfile WriteMode ; predefinedTypes h ; hClose h ; h <- openFile prefixfile WriteMode ; prefixOp h ; hClose h ; h <- openFile comfile WriteMode ; command h ; hClose h ; h <- openFile modefile WriteMode ; modes h ; hClose h ; h <- openFile prefile WriteMode ; verbatim h predefined ; hClose h ; h <- openFile versionfile WriteMode ; hPutStr h (version++"\\\\"++buildtime++"\\\\") ; hClose h ; h <- openFile licensefile WriteMode ; s <- readFile licenseSrc ; verbatim h s ; hClose h } ------------------------------------------------------ -- helper function showSigma:: Sigma -> String showSigma s = scan (snd(exhibit disp0 s)) showpoly (K lvs s) = showSigma s scan ('f':'o':'r':'a':'l':'l':xs) = dropWhile g (dropWhile f xs) where f c = c /= '.' g c = c `elem` ". " scan xs = xs f ("unsafeCast",_) = "" f ("undefined",_) = "" f (x,(y,z)) = (g x ++ " :: " ++ showSigma z ++ "\n") hf (x,y,z) = (g x ++ " :: " ++ showpoly z ++ "\n") hg (x,y) = "("++x++") :: " ++ y ++ "\n" g [] = [] g "[]" = "[]" g (s@(c:cs)) | isAlpha c = s -- normal names | c == '(' = s | True = "("++s++")" -- infix operators predefinedTypes h = do { figure2 h (verbatim h ("\nType :: Kind \n\n"++(concat (map hf typeConstrEnv0)))) "Predefined types and their kinds." "types" ; figure2 h (verbatim h ("\nValue :: Type \n\n"++(concat (map f vals')))) "Predefined functions and values." "values" } prefixOp h = figure2 h (verbatim h ("\nOperator :: Type \n\n"++(concat (map hg infixOperators)))) "The fixed set of infix operators and their types." "infix" command h = figure h (verbatim h commands) "Legal inputs to the command line interpreter." "commands" modes h = itemize f h modes_and_doc where f (name,init,doc) = hPutStr h line where line = "{\\tt "++under name++"}. Initial value = {\\tt "++show init++"}. "++doc++"\n" under [] = [] under ('_' : xs) = "\\_"++under xs under (x:xs) = x: under xs
cartazio/omega
src/Manual.hs
bsd-3-clause
4,733
0
15
1,408
1,492
767
725
114
2
{- Copyright (C) 2010-2014 John MacFarlane <[email protected]> This program 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Writers.Textile Copyright : Copyright (C) 2010-2014 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Conversion of 'Pandoc' documents to Textile markup. Textile: <http://thresholdstate.com/articles/4312/the-textile-reference-manual> -} module Text.Pandoc.Writers.Textile ( writeTextile ) where import Text.Pandoc.Definition import Text.Pandoc.Options import Text.Pandoc.Shared import Text.Pandoc.Pretty (render) import Text.Pandoc.Writers.Shared import Text.Pandoc.Templates (renderTemplate') import Text.Pandoc.XML ( escapeStringForXML ) import Data.List ( intercalate ) import Control.Monad.State import Control.Applicative ((<$>)) import Data.Char ( isSpace ) data WriterState = WriterState { stNotes :: [String] -- Footnotes , stListLevel :: [Char] -- String at beginning of list items, e.g. "**" , stUseTags :: Bool -- True if we should use HTML tags because we're in a complex list } -- | Convert Pandoc to Textile. writeTextile :: WriterOptions -> Pandoc -> String writeTextile opts document = evalState (pandocToTextile opts document) WriterState { stNotes = [], stListLevel = [], stUseTags = False } -- | Return Textile representation of document. pandocToTextile :: WriterOptions -> Pandoc -> State WriterState String pandocToTextile opts (Pandoc meta blocks) = do metadata <- metaToJSON opts (blockListToTextile opts) (inlineListToTextile opts) meta body <- blockListToTextile opts blocks notes <- liftM (unlines . reverse . stNotes) get let main = body ++ if null notes then "" else ("\n\n" ++ notes) let context = defField "body" main metadata if writerStandalone opts then return $ renderTemplate' (writerTemplate opts) context else return main withUseTags :: State WriterState a -> State WriterState a withUseTags action = do oldUseTags <- liftM stUseTags get modify $ \s -> s { stUseTags = True } result <- action modify $ \s -> s { stUseTags = oldUseTags } return result -- | Escape one character as needed for Textile. escapeCharForTextile :: Char -> String escapeCharForTextile x = case x of '&' -> "&amp;" '<' -> "&lt;" '>' -> "&gt;" '"' -> "&quot;" '*' -> "&#42;" '_' -> "&#95;" '@' -> "&#64;" '|' -> "&#124;" '\x2014' -> " -- " '\x2013' -> " - " '\x2019' -> "'" '\x2026' -> "..." c -> [c] -- | Escape string as needed for Textile. escapeStringForTextile :: String -> String escapeStringForTextile = concatMap escapeCharForTextile -- | Convert Pandoc block element to Textile. blockToTextile :: WriterOptions -- ^ Options -> Block -- ^ Block element -> State WriterState String blockToTextile _ Null = return "" blockToTextile opts (Div attr bs) = do let startTag = render Nothing $ tagWithAttrs "div" attr let endTag = "</div>" contents <- blockListToTextile opts bs return $ startTag ++ "\n\n" ++ contents ++ "\n\n" ++ endTag ++ "\n" blockToTextile opts (Plain inlines) = inlineListToTextile opts inlines -- title beginning with fig: indicates that the image is a figure blockToTextile opts (Para [Image txt (src,'f':'i':'g':':':tit)]) = do capt <- blockToTextile opts (Para txt) im <- inlineToTextile opts (Image txt (src,tit)) return $ im ++ "\n" ++ capt blockToTextile opts (Para inlines) = do useTags <- liftM stUseTags get listLevel <- liftM stListLevel get contents <- inlineListToTextile opts inlines return $ if useTags then "<p>" ++ contents ++ "</p>" else contents ++ if null listLevel then "\n" else "" blockToTextile _ (RawBlock f str) | f == Format "html" || f == Format "textile" = return str | otherwise = return "" blockToTextile _ HorizontalRule = return "<hr />\n" blockToTextile opts (Header level (ident,classes,keyvals) inlines) = do contents <- inlineListToTextile opts inlines let identAttr = if null ident then "" else ('#':ident) let attribs = if null identAttr && null classes then "" else "(" ++ unwords classes ++ identAttr ++ ")" let lang = maybe "" (\x -> "[" ++ x ++ "]") $ lookup "lang" keyvals let styles = maybe "" (\x -> "{" ++ x ++ "}") $ lookup "style" keyvals let prefix = 'h' : show level ++ attribs ++ styles ++ lang ++ ". " return $ prefix ++ contents ++ "\n" blockToTextile _ (CodeBlock (_,classes,_) str) | any (all isSpace) (lines str) = return $ "<pre" ++ classes' ++ ">\n" ++ escapeStringForXML str ++ "\n</pre>\n" where classes' = if null classes then "" else " class=\"" ++ unwords classes ++ "\"" blockToTextile _ (CodeBlock (_,classes,_) str) = return $ "bc" ++ classes' ++ ". " ++ str ++ "\n\n" where classes' = if null classes then "" else "(" ++ unwords classes ++ ")" blockToTextile opts (BlockQuote bs@[Para _]) = do contents <- blockListToTextile opts bs return $ "bq. " ++ contents ++ "\n\n" blockToTextile opts (BlockQuote blocks) = do contents <- blockListToTextile opts blocks return $ "<blockquote>\n\n" ++ contents ++ "\n</blockquote>\n" blockToTextile opts (Table [] aligns widths headers rows') | all (==0) widths = do hs <- mapM (liftM (("_. " ++) . stripTrailingNewlines) . blockListToTextile opts) headers let cellsToRow cells = "|" ++ intercalate "|" cells ++ "|" let header = if all null headers then "" else cellsToRow hs ++ "\n" let blocksToCell (align, bs) = do contents <- stripTrailingNewlines <$> blockListToTextile opts bs let alignMarker = case align of AlignLeft -> "<. " AlignRight -> ">. " AlignCenter -> "=. " AlignDefault -> "" return $ alignMarker ++ contents let rowToCells = mapM blocksToCell . zip aligns bs <- mapM rowToCells rows' let body = unlines $ map cellsToRow bs return $ header ++ body blockToTextile opts (Table capt aligns widths headers rows') = do let alignStrings = map alignmentToString aligns captionDoc <- if null capt then return "" else do c <- inlineListToTextile opts capt return $ "<caption>" ++ c ++ "</caption>\n" let percent w = show (truncate (100*w) :: Integer) ++ "%" let coltags = if all (== 0.0) widths then "" else unlines $ map (\w -> "<col width=\"" ++ percent w ++ "\" />") widths head' <- if all null headers then return "" else do hs <- tableRowToTextile opts alignStrings 0 headers return $ "<thead>\n" ++ hs ++ "\n</thead>\n" body' <- zipWithM (tableRowToTextile opts alignStrings) [1..] rows' return $ "<table>\n" ++ captionDoc ++ coltags ++ head' ++ "<tbody>\n" ++ unlines body' ++ "</tbody>\n</table>\n" blockToTextile opts x@(BulletList items) = do oldUseTags <- liftM stUseTags get let useTags = oldUseTags || not (isSimpleList x) if useTags then do contents <- withUseTags $ mapM (listItemToTextile opts) items return $ "<ul>\n" ++ vcat contents ++ "\n</ul>\n" else do modify $ \s -> s { stListLevel = stListLevel s ++ "*" } level <- get >>= return . length . stListLevel contents <- mapM (listItemToTextile opts) items modify $ \s -> s { stListLevel = init (stListLevel s) } return $ vcat contents ++ (if level > 1 then "" else "\n") blockToTextile opts x@(OrderedList attribs items) = do oldUseTags <- liftM stUseTags get let useTags = oldUseTags || not (isSimpleList x) if useTags then do contents <- withUseTags $ mapM (listItemToTextile opts) items return $ "<ol" ++ listAttribsToString attribs ++ ">\n" ++ vcat contents ++ "\n</ol>\n" else do modify $ \s -> s { stListLevel = stListLevel s ++ "#" } level <- get >>= return . length . stListLevel contents <- mapM (listItemToTextile opts) items modify $ \s -> s { stListLevel = init (stListLevel s) } return $ vcat contents ++ (if level > 1 then "" else "\n") blockToTextile opts (DefinitionList items) = do contents <- withUseTags $ mapM (definitionListItemToTextile opts) items return $ "<dl>\n" ++ vcat contents ++ "\n</dl>\n" -- Auxiliary functions for lists: -- | Convert ordered list attributes to HTML attribute string listAttribsToString :: ListAttributes -> String listAttribsToString (startnum, numstyle, _) = let numstyle' = camelCaseToHyphenated $ show numstyle in (if startnum /= 1 then " start=\"" ++ show startnum ++ "\"" else "") ++ (if numstyle /= DefaultStyle then " style=\"list-style-type: " ++ numstyle' ++ ";\"" else "") -- | Convert bullet or ordered list item (list of blocks) to Textile. listItemToTextile :: WriterOptions -> [Block] -> State WriterState String listItemToTextile opts items = do contents <- blockListToTextile opts items useTags <- get >>= return . stUseTags if useTags then return $ "<li>" ++ contents ++ "</li>" else do marker <- get >>= return . stListLevel return $ marker ++ " " ++ contents -- | Convert definition list item (label, list of blocks) to Textile. definitionListItemToTextile :: WriterOptions -> ([Inline],[[Block]]) -> State WriterState String definitionListItemToTextile opts (label, items) = do labelText <- inlineListToTextile opts label contents <- mapM (blockListToTextile opts) items return $ "<dt>" ++ labelText ++ "</dt>\n" ++ (intercalate "\n" $ map (\d -> "<dd>" ++ d ++ "</dd>") contents) -- | True if the list can be handled by simple wiki markup, False if HTML tags will be needed. isSimpleList :: Block -> Bool isSimpleList x = case x of BulletList items -> all isSimpleListItem items OrderedList (num, sty, _) items -> all isSimpleListItem items && num == 1 && sty `elem` [DefaultStyle, Decimal] _ -> False -- | True if list item can be handled with the simple wiki syntax. False if -- HTML tags will be needed. isSimpleListItem :: [Block] -> Bool isSimpleListItem [] = True isSimpleListItem [x] = case x of Plain _ -> True Para _ -> True BulletList _ -> isSimpleList x OrderedList _ _ -> isSimpleList x _ -> False isSimpleListItem [x, y] | isPlainOrPara x = case y of BulletList _ -> isSimpleList y OrderedList _ _ -> isSimpleList y _ -> False isSimpleListItem _ = False isPlainOrPara :: Block -> Bool isPlainOrPara (Plain _) = True isPlainOrPara (Para _) = True isPlainOrPara _ = False -- | Concatenates strings with line breaks between them. vcat :: [String] -> String vcat = intercalate "\n" -- Auxiliary functions for tables. (TODO: these are common to HTML, MediaWiki, -- and Textile writers, and should be abstracted out.) tableRowToTextile :: WriterOptions -> [String] -> Int -> [[Block]] -> State WriterState String tableRowToTextile opts alignStrings rownum cols' = do let celltype = if rownum == 0 then "th" else "td" let rowclass = case rownum of 0 -> "header" x | x `rem` 2 == 1 -> "odd" _ -> "even" cols'' <- sequence $ zipWith (\alignment item -> tableItemToTextile opts celltype alignment item) alignStrings cols' return $ "<tr class=\"" ++ rowclass ++ "\">\n" ++ unlines cols'' ++ "</tr>" alignmentToString :: Alignment -> [Char] alignmentToString alignment = case alignment of AlignLeft -> "left" AlignRight -> "right" AlignCenter -> "center" AlignDefault -> "left" tableItemToTextile :: WriterOptions -> String -> String -> [Block] -> State WriterState String tableItemToTextile opts celltype align' item = do let mkcell x = "<" ++ celltype ++ " align=\"" ++ align' ++ "\">" ++ x ++ "</" ++ celltype ++ ">" contents <- blockListToTextile opts item return $ mkcell contents -- | Convert list of Pandoc block elements to Textile. blockListToTextile :: WriterOptions -- ^ Options -> [Block] -- ^ List of block elements -> State WriterState String blockListToTextile opts blocks = mapM (blockToTextile opts) blocks >>= return . vcat -- | Convert list of Pandoc inline elements to Textile. inlineListToTextile :: WriterOptions -> [Inline] -> State WriterState String inlineListToTextile opts lst = mapM (inlineToTextile opts) lst >>= return . concat -- | Convert Pandoc inline element to Textile. inlineToTextile :: WriterOptions -> Inline -> State WriterState String inlineToTextile opts (Span _ lst) = inlineListToTextile opts lst inlineToTextile opts (Emph lst) = do contents <- inlineListToTextile opts lst return $ if '_' `elem` contents then "<em>" ++ contents ++ "</em>" else "_" ++ contents ++ "_" inlineToTextile opts (Strong lst) = do contents <- inlineListToTextile opts lst return $ if '*' `elem` contents then "<strong>" ++ contents ++ "</strong>" else "*" ++ contents ++ "*" inlineToTextile opts (Strikeout lst) = do contents <- inlineListToTextile opts lst return $ if '-' `elem` contents then "<del>" ++ contents ++ "</del>" else "-" ++ contents ++ "-" inlineToTextile opts (Superscript lst) = do contents <- inlineListToTextile opts lst return $ if '^' `elem` contents then "<sup>" ++ contents ++ "</sup>" else "[^" ++ contents ++ "^]" inlineToTextile opts (Subscript lst) = do contents <- inlineListToTextile opts lst return $ if '~' `elem` contents then "<sub>" ++ contents ++ "</sub>" else "[~" ++ contents ++ "~]" inlineToTextile opts (SmallCaps lst) = inlineListToTextile opts lst inlineToTextile opts (Quoted SingleQuote lst) = do contents <- inlineListToTextile opts lst return $ "'" ++ contents ++ "'" inlineToTextile opts (Quoted DoubleQuote lst) = do contents <- inlineListToTextile opts lst return $ "\"" ++ contents ++ "\"" inlineToTextile opts (Cite _ lst) = inlineListToTextile opts lst inlineToTextile _ (Code _ str) = return $ if '@' `elem` str then "<tt>" ++ escapeStringForXML str ++ "</tt>" else "@" ++ str ++ "@" inlineToTextile _ (Str str) = return $ escapeStringForTextile str inlineToTextile _ (Math _ str) = return $ "<span class=\"math\">" ++ escapeStringForXML str ++ "</math>" inlineToTextile opts (RawInline f str) | f == Format "html" || f == Format "textile" = return str | (f == Format "latex" || f == Format "tex") && isEnabled Ext_raw_tex opts = return str | otherwise = return "" inlineToTextile _ (LineBreak) = return "\n" inlineToTextile _ Space = return " " inlineToTextile opts (Link txt (src, _)) = do label <- case txt of [Code _ s] | s == src -> return "$" [Str s] | s == src -> return "$" _ -> inlineListToTextile opts txt return $ "\"" ++ label ++ "\":" ++ src inlineToTextile opts (Image alt (source, tit)) = do alt' <- inlineListToTextile opts alt let txt = if null tit then if null alt' then "" else "(" ++ alt' ++ ")" else "(" ++ tit ++ ")" return $ "!" ++ source ++ txt ++ "!" inlineToTextile opts (Note contents) = do curNotes <- liftM stNotes get let newnum = length curNotes + 1 contents' <- blockListToTextile opts contents let thisnote = "fn" ++ show newnum ++ ". " ++ contents' ++ "\n" modify $ \s -> s { stNotes = thisnote : curNotes } return $ "[" ++ show newnum ++ "]" -- note - may not work for notes with multiple blocks
sapek/pandoc
src/Text/Pandoc/Writers/Textile.hs
gpl-2.0
17,790
0
18
5,272
4,781
2,375
2,406
341
18
module B where import A (message) main :: IO () main = do putStrLn message
sdiehl/ghc
testsuite/tests/driver/T16500/B.hs
bsd-3-clause
81
0
7
21
33
18
15
5
1
{-# LANGUAGE OverloadedStrings #-} module Poly1305 (tests) where import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B () import Imports import Crypto.Error import qualified Crypto.MAC.Poly1305 as Poly1305 import qualified Data.ByteArray as B (convert) instance Show Poly1305.Auth where show _ = "Auth" data Chunking = Chunking Int Int deriving (Show,Eq) instance Arbitrary Chunking where arbitrary = Chunking <$> choose (1,34) <*> choose (1,2048) tests = testGroup "Poly1305" [ testCase "V0" $ let key = "\x85\xd6\xbe\x78\x57\x55\x6d\x33\x7f\x44\x52\xfe\x42\xd5\x06\xa8\x01\x03\x80\x8a\xfb\x0d\xb2\xfd\x4a\xbf\xf6\xaf\x41\x49\xf5\x1b" :: ByteString msg = "Cryptographic Forum Research Group" :: ByteString tag = "\xa8\x06\x1d\xc1\x30\x51\x36\xc6\xc2\x2b\x8b\xaf\x0c\x01\x27\xa9" :: ByteString in tag @=? B.convert (Poly1305.auth key msg) , testProperty "Chunking" $ \(Chunking chunkLen totalLen) -> let key = B.replicate 32 0 msg = B.pack $ take totalLen $ concat (replicate 10 [1..255]) in Poly1305.auth key msg == Poly1305.finalize (foldr (flip Poly1305.update) (throwCryptoError $ Poly1305.initialize key) (chunks chunkLen msg)) ] where chunks i bs | B.length bs < i = [bs] | otherwise = let (b1,b2) = B.splitAt i bs in b1 : chunks i b2
tekul/cryptonite
tests/Poly1305.hs
bsd-3-clause
1,410
0
18
306
410
218
192
27
1
module Test15 where f n = n * (f (n - 1)) g = 13 * (f (13 - 1))
SAdams601/HaRe
old/testing/refacFunDef/Test15_AstOut.hs
bsd-3-clause
67
0
9
23
51
28
23
3
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DeriveDataTypeable #-} module TypedIds where import Data.Maybe(isJust) import Data.Generics {-+ Haskell declaration introduce names in two name spaces. Type classes and types live in one name space. Values (functions, data constructors) live in another name space. -} data NameSpace = ClassOrTypeNames | ValueNames deriving (Eq,Ord,Show, Data, Typeable) {-+ Identifiers can denote many different types of entities. It is clear from the defining occurence of an identifier what type of entity it denotes. The type #IdTy# can be seen as a refinement of #NameSpace#. From the use of an identifier, we can tell what name space it refers to, but not the exact type of entity, hence the need for two different types. -} data IdTy i = Value | FieldOf i (TypeInfo i) | MethodOf i Int [i] -- name of class, number of superclasses, names of all methods | ConstrOf i (TypeInfo i) | Class Int [i] -- number of superclasses, names of all methods | Type (TypeInfo i) | Assertion -- P-Logic assertion name | Property -- P-Logic property name deriving (Eq,Ord,Show,Read, Data, Typeable) -- These structures contain a lot of redundancy, so we shouldn't really -- use any comparison operations on them. data ConInfo i = ConInfo { conName :: i , conArity :: Int , conFields :: Maybe [i] -- length agrees with conArity } deriving (Eq,Ord,Show,Read, Data, Typeable) data DefTy = Newtype | Data | Synonym | Primitive deriving (Eq,Ord,Show,Read, Data, Typeable) data TypeInfo i = TypeInfo { defType :: Maybe DefTy , constructors :: [ConInfo i] , fields :: [i] } deriving (Eq,Ord,Show,Read, Data, Typeable) blankTypeInfo = TypeInfo { defType = Nothing, constructors = [], fields = [] } instance Functor ConInfo where fmap f c = c { conName = f (conName c), conFields = fmap (map f) (conFields c) } instance Functor TypeInfo where fmap f t = t { constructors = map (fmap f) (constructors t) , fields = map f (fields t) } instance Functor IdTy where fmap f (FieldOf x tyInfo) = FieldOf (f x) (fmap f tyInfo) fmap f (MethodOf x n xs) = MethodOf (f x) n (map f xs) fmap f (ConstrOf t tyInfo) = ConstrOf (f t) (fmap f tyInfo) fmap _ Value = Value fmap f (Class n xs) = Class n (f `map` xs) fmap f (Type tyInfo) = Type (fmap f tyInfo) fmap _ Assertion = Assertion fmap _ Property = Property class HasNameSpace t where namespace :: t -> NameSpace instance HasNameSpace (IdTy id) where namespace Value = ValueNames namespace (FieldOf {}) = ValueNames namespace (MethodOf {}) = ValueNames namespace (ConstrOf {}) = ValueNames namespace (Class {}) = ClassOrTypeNames namespace (Type {}) = ClassOrTypeNames namespace Assertion = ValueNames -- hmm namespace Property = ValueNames -- hmm -- owner :: IdTy i -> Maybe i owner (FieldOf dt _) = Just dt owner (MethodOf cl _ _) = Just cl owner (ConstrOf dt _) = Just dt owner _ = Nothing -- isSubordinate :: IdTy i -> Bool isSubordinate = isJust . owner -- belongsTo :: idTy i -> i -> Bool idty `belongsTo` t = owner idty == Just t isAssertion Assertion = True isAssertion Property = True isAssertion _ = False isClassOrType,isValue :: HasNameSpace t => t -> Bool isClassOrType = (== ClassOrTypeNames) . namespace isValue = (== ValueNames) . namespace class HasIdTy i t | t->i where idTy :: t -> IdTy i instance HasIdTy i (IdTy i) where idTy = id --instance HasNameSpace NameSpace where namespace = id
kmate/HaRe
old/tools/base/Modules/TypedIds.hs
bsd-3-clause
3,831
2
10
988
1,051
567
484
72
1
-- -- (c) The University of Glasgow -- {-# LANGUAGE DeriveDataTypeable #-} module Avail ( Avails, AvailInfo(..), IsPatSyn(..), avail, patSynAvail, availsToNameSet, availsToNameSetWithSelectors, availsToNameEnv, availName, availNames, availNonFldNames, availNamesWithSelectors, availFlds, stableAvailCmp ) where import Name import NameEnv import NameSet import FieldLabel import Binary import Outputable import Util import Data.Function -- ----------------------------------------------------------------------------- -- The AvailInfo type -- | Records what things are "available", i.e. in scope data AvailInfo = Avail IsPatSyn Name -- ^ An ordinary identifier in scope | AvailTC Name [Name] [FieldLabel] -- ^ A type or class in scope. Parameters: -- -- 1) The name of the type or class -- 2) The available pieces of type or class, -- excluding field selectors. -- 3) The record fields of the type -- (see Note [Representing fields in AvailInfo]). -- -- The AvailTC Invariant: -- * If the type or class is itself -- to be in scope, it must be -- *first* in this list. Thus, -- typically: @AvailTC Eq [Eq, ==, \/=]@ deriving( Eq ) -- Equality used when deciding if the -- interface has changed data IsPatSyn = NotPatSyn | IsPatSyn deriving Eq -- | A collection of 'AvailInfo' - several things that are \"available\" type Avails = [AvailInfo] {- Note [Representing fields in AvailInfo] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When -XDuplicateRecordFields is disabled (the normal case), a datatype like data T = MkT { foo :: Int } gives rise to the AvailInfo AvailTC T [T, MkT] [FieldLabel "foo" False foo], whereas if -XDuplicateRecordFields is enabled it gives AvailTC T [T, MkT] [FieldLabel "foo" True $sel:foo:MkT] since the label does not match the selector name. The labels in a field list are not necessarily unique: data families allow the same parent (the family tycon) to have multiple distinct fields with the same label. For example, data family F a data instance F Int = MkFInt { foo :: Int } data instance F Bool = MkFBool { foo :: Bool} gives rise to AvailTC F [F, MkFInt, MkFBool] [FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" True $sel:foo:MkFBool]. Moreover, note that the flIsOverloaded flag need not be the same for all the elements of the list. In the example above, this occurs if the two data instances are defined in different modules, one with `-XDuplicateRecordFields` enabled and one with it disabled. Thus it is possible to have AvailTC F [F, MkFInt, MkFBool] [FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" False foo]. If the two data instances are defined in different modules, both without `-XDuplicateRecordFields`, it will be impossible to export them from the same module (even with `-XDuplicateRecordfields` enabled), because they would be represented identically. The workaround here is to enable `-XDuplicateRecordFields` on the defining modules. -} -- | Compare lexicographically stableAvailCmp :: AvailInfo -> AvailInfo -> Ordering stableAvailCmp (Avail _ n1) (Avail _ n2) = n1 `stableNameCmp` n2 stableAvailCmp (Avail {}) (AvailTC {}) = LT stableAvailCmp (AvailTC n ns nfs) (AvailTC m ms mfs) = (n `stableNameCmp` m) `thenCmp` (cmpList stableNameCmp ns ms) `thenCmp` (cmpList (stableNameCmp `on` flSelector) nfs mfs) stableAvailCmp (AvailTC {}) (Avail {}) = GT patSynAvail :: Name -> AvailInfo patSynAvail n = Avail IsPatSyn n avail :: Name -> AvailInfo avail n = Avail NotPatSyn n -- ----------------------------------------------------------------------------- -- Operations on AvailInfo availsToNameSet :: [AvailInfo] -> NameSet availsToNameSet avails = foldr add emptyNameSet avails where add avail set = extendNameSetList set (availNames avail) availsToNameSetWithSelectors :: [AvailInfo] -> NameSet availsToNameSetWithSelectors avails = foldr add emptyNameSet avails where add avail set = extendNameSetList set (availNamesWithSelectors avail) availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo availsToNameEnv avails = foldr add emptyNameEnv avails where add avail env = extendNameEnvList env (zip (availNames avail) (repeat avail)) -- | Just the main name made available, i.e. not the available pieces -- of type or class brought into scope by the 'GenAvailInfo' availName :: AvailInfo -> Name availName (Avail _ n) = n availName (AvailTC n _ _) = n -- | All names made available by the availability information (excluding overloaded selectors) availNames :: AvailInfo -> [Name] availNames (Avail _ n) = [n] availNames (AvailTC _ ns fs) = ns ++ [ flSelector f | f <- fs, not (flIsOverloaded f) ] -- | All names made available by the availability information (including overloaded selectors) availNamesWithSelectors :: AvailInfo -> [Name] availNamesWithSelectors (Avail _ n) = [n] availNamesWithSelectors (AvailTC _ ns fs) = ns ++ map flSelector fs -- | Names for non-fields made available by the availability information availNonFldNames :: AvailInfo -> [Name] availNonFldNames (Avail _ n) = [n] availNonFldNames (AvailTC _ ns _) = ns -- | Fields made available by the availability information availFlds :: AvailInfo -> [FieldLabel] availFlds (AvailTC _ _ fs) = fs availFlds _ = [] -- ----------------------------------------------------------------------------- -- Printing instance Outputable AvailInfo where ppr = pprAvail pprAvail :: AvailInfo -> SDoc pprAvail (Avail _ n) = ppr n pprAvail (AvailTC n ns fs) = ppr n <> braces (hsep (punctuate comma (map ppr ns ++ map (ppr . flLabel) fs))) instance Binary AvailInfo where put_ bh (Avail b aa) = do putByte bh 0 put_ bh aa put_ bh b put_ bh (AvailTC ab ac ad) = do putByte bh 1 put_ bh ab put_ bh ac put_ bh ad get bh = do h <- getByte bh case h of 0 -> do aa <- get bh b <- get bh return (Avail b aa) _ -> do ab <- get bh ac <- get bh ad <- get bh return (AvailTC ab ac ad) instance Binary IsPatSyn where put_ bh IsPatSyn = putByte bh 0 put_ bh NotPatSyn = putByte bh 1 get bh = do h <- getByte bh case h of 0 -> return IsPatSyn _ -> return NotPatSyn
tjakway/ghcjvm
compiler/basicTypes/Avail.hs
bsd-3-clause
7,103
0
15
2,075
1,234
648
586
99
1
module Main where import Control.Concurrent import qualified Control.Exception as E trapHandler :: MVar Int -> MVar () -> IO () trapHandler inVar caughtVar = (do E.mask_ $ do trapMsg <- takeMVar inVar putStrLn ("Handler got: " ++ show trapMsg) trapHandler inVar caughtVar ) `E.catch` (trapExc inVar caughtVar) trapExc :: MVar Int -> MVar () -> E.SomeException -> IO () -- If we have been killed then we are done trapExc inVar caughtVar e | Just E.ThreadKilled <- E.fromException e = return () -- Otherwise... trapExc inVar caughtVar e = do putStrLn ("Exception: " ++ show e) putMVar caughtVar () trapHandler inVar caughtVar main :: IO () main = do inVar <- newEmptyMVar caughtVar <- newEmptyMVar tid <- forkIO (trapHandler inVar caughtVar) yield putMVar inVar 1 threadDelay 1000 throwTo tid (E.ErrorCall "1st") takeMVar caughtVar putMVar inVar 2 threadDelay 1000 throwTo tid (E.ErrorCall "2nd") -- the second time around, exceptions will be blocked, because -- the trapHandler is effectively "still in the handler" from the -- first exception. I'm not sure if this is by design or by -- accident. Anyway, the trapHandler will at some point block -- in takeMVar, and thereby become interruptible, at which point -- it will receive the second exception. takeMVar caughtVar -- Running the GHCi way complains that tid is blocked indefinitely if -- it still exists, so kill it. killThread tid putStrLn "All done"
ezyang/ghc
testsuite/tests/concurrent/should_run/conc035.hs
bsd-3-clause
1,544
2
16
365
336
161
175
34
1
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-} -- Trac #2494, should generate an error message module Foo where foo :: (forall m. Monad m => Maybe (m a) -> Maybe (m a)) -> Maybe a -> Maybe a foo _ x = x {-# RULES "foo/foo" forall (f :: forall m. Monad m => Maybe (m a) -> Maybe (m a)) (g :: forall m. Monad m => Maybe (m b) -> Maybe (m b)) x. foo f (foo g x) = foo (f . g) x #-}
wxwxwwxxx/ghc
testsuite/tests/typecheck/should_compile/T2494.hs
bsd-3-clause
400
0
12
105
73
38
35
9
1
-- !!! Duplicate export of constructor module M(T(K1,K1)) where data T = K1
urbanslug/ghc
testsuite/tests/module/mod5.hs
bsd-3-clause
76
0
5
13
23
16
7
4
0
{-# OPTIONS_GHC -Wall #-} module CSI where data Boy = Matthew | Peter | Jack | Arnold | Carl deriving (Eq,Show) boys :: [Boy] boys = [Matthew, Peter, Jack, Arnold, Carl] -- says accuser accused = True says :: Boy -> Boy -> Bool -- None of the kids has claimed guilty, so we assume that all of them claim inocence. says Matthew Matthew = False says Peter Peter = False says Jack Jack = False says Arnold Arnold = False says Carl Carl = False -- Matthew: Carl didn’t do it, and neither did I. -- says Matthew Matthew = False says Matthew Carl = False says Matthew _ = True -- Peter: It was Matthew or it was Jack. says Peter Matthew = True says Peter Jack = True says Peter _ = False -- Jack: Matthew and Peter are both lying. says Jack y = not(says Matthew y) && not(says Peter y) -- Arnold: Matthew or Peter is speaking the truth, but not both. says Arnold y = (says Matthew y && not(says Peter y)) || (not(says Matthew y) && says Peter y) -- Carl: What Arnold says is not true. says Carl y = not(says Arnold y) -- The accusers of a boy is each boy that says he is guilty. accusers :: Boy -> [Boy] accusers accused = [accuser | accuser <- boys, says accuser accused] -- The one that all the honest kids point. Only 3 will say the truth, therefore, -- the one accused by 3 is the right one. guilty :: [Boy] guilty = [boy | boy <- boys, length (accusers boy) == 3] -- The lier is didn't claim guilty therefore is a lier. The kid that didn't accused him too. honest :: [Boy] honest = accusers (head guilty)
Gurrt/software-testing
week-1/CSI.hs
mit
1,530
0
10
322
408
220
188
26
1
import Data.List import Data.Char data Fig = W | B | WD | BD | E deriving (Show, Eq) type Board = [[Fig]] type Pos = (Int, Int) charToFig :: Char -> Fig charToFig 'w' = W charToFig 'W' = WD charToFig 'b' = B charToFig 'B' = BD charToFig '.' = E figToChar :: Fig -> Char figToChar W = 'w' figToChar WD = 'W' figToChar B = 'b' figToChar BD = 'B' figToChar E = '.' initialBoardStr = ".b.b.b.b\n\ \b.b.b.b.\n\ \.b.b.b.b\n\ \........\n\ \........\n\ \w.w.w.w.\n\ \.w.w.w.w\n\ \w.w.w.w." fromStr :: String -> [Fig] fromStr = map charToFig toStr :: [Fig] -> String toStr = intersperse ' ' . map figToChar initBoard :: String -> Board initBoard = map fromStr . lines szachownica = initBoard initialBoardStr boardToStr :: Board -> [String] boardToStr b = map toStr b showBoard :: Board -> String showBoard board = unlines . addColNumbers . addRowNumbers $ boardToStr board where addRowNumber num line = (show num) ++ " " ++ line addRowNumbers board = zipWith addRowNumber [0..7] board addColNumbers board = [" 0 1 2 3 4 5 6 7 "] ++ board getFig :: Board -> Pos -> Fig getFig b (row, column) = b !! row !! column replaceWithFig :: Fig -> [Fig] -> Int -> [Fig] replaceWithFig f (_:t) 0 = f : t replaceWithFig f (h:t) col = h:replaceWithFig f t (col-1) setFig :: Fig -> Board -> Pos -> Board setFig fig (headBoard:tailBoard) (0, column) = replaceWithFig fig headBoard column : tailBoard setFig fig (headBoard:tailBoard) (row, column) = headBoard : setFig fig tailBoard ((row-1), column) --countWhiteFigs :: Board -> Int --countWhiteFigs [] = 0 --countWhiteFigs (h:t) = (countWhiteFigs t) + (length (filter (\f -> f == W || f == WD) h)) boardToNumberOfWhiteFigures :: Board -> Int boardToNumberOfWhiteFigures [] = 0 boardToNumberOfWhiteFigures (h:t) = let isWhiteFig fig = fig == W || fig == WD :: Bool areWhiteFigs figs = filter isWhiteFig figs :: [Fig] in length (areWhiteFigs h) + boardToNumberOfWhiteFigures t --boardToNumberOfBlackFigures :: Board -> Int --boardToNumberOfBlackFigures [] = 0 --boardToNumberOfBlackFigures (h:t) = let -- isBlackFig fig = fig == B || fig == BD :: Bool -- areBlackFigs figs = filter isBlackFig figs :: [Fig] -- in -- length (areBlackFigs h) + boardToNumberOfBlackFigures t boardToNumberOfBlackFigures :: Board -> Int boardToNumberOfBlackFigures b = foldr (\_ acc -> 1 + acc) 0 (foldr (\x acc -> if (isBlackFig x) then x:acc else acc) [] [uhu | uhu<- [ble | ble<-b]]) isBlackFig :: Fig -> Bool isBlackFig f = f `elem` [B,BD] areBlackFigs :: [Fig] -> [Fig] areBlackFigs = foldr (\x acc -> if (isBlackFig x) then x:acc else acc) []-- filter isBlackFig figs :: [Fig] dlugosc :: [t]->Int dlugosc = foldr (\_ acc -> 1 +acc) 0 --blabla :: [Int] -> [Int] --blabla = foldr (\x acc -> x:acc) [] getRow :: Pos -> Int getRow = fst getCol :: Pos -> Int getCol = snd isEmpty :: Board -> Pos -> Bool isEmpty b p = getFig b p == E isWhite :: Board -> Pos -> Bool isWhite b p = getFig b p `elem` [W,WD] isBlack :: Board -> Pos -> Bool isBlack b p = getFig b p `elem` [B,BD] isValidPos :: Pos -> Bool isValidPos (row,col) = let validPositions = [0..7] in (row `elem` validPositions && col `elem` validPositions) countPos :: Pos -> Pos -> Pos countPos (r1,c1) (r2,c2) = (abs (r2-r1)+r2, abs (c2-c1)+c2) countPos2 :: Pos -> Pos -> Pos countPos2 (row, col) (neighborRow, neighborCol) = ((countIndex row neighborRow), (countIndex col neighborCol)) where countIndex index neighborIndex = 2 * neighborIndex - index capturedPos :: Pos -> Pos -> Pos capturedPos prevPos@(r1,c1) newPos@(r2,c2) = ((r1+r2) `quot` 2,(c1+c2) `quot` 2) --setFig :: Fig -> Board -> Pos -> Board --setFig fig (headBoard:tailBoard) (0, column) = replaceWithFig fig headBoard column : tailBoard --setFig fig (headBoard:tailBoard) (row, column) = headBoard : setFig fig tailBoard ((row-1), column) makeCaptureMove :: Board -> Pos -> Pos -> Board makeCaptureMove b curp newp | isWhite b from = (setFig E (setFig W (setFig E b from) to) (capturedPos from to)) | isBlack b from =
RAFIRAF/HASKELL
warcaby-trening.hs
mit
4,456
3
13
1,190
1,425
776
649
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Module : PostgREST.QueryBuilder Description : PostgREST SQL generating functions. This module provides functions to consume data types that represent database objects (e.g. Relation, Schema, SqlQuery) and produces SQL Statements. Any function that outputs a SQL fragment should be in this module. -} module PostgREST.QueryBuilder ( addRelations , addJoinConditions , asJson , callProc , createReadStatement , createWriteStatement , operators , pgFmtIdent , pgFmtLit , requestToQuery , sourceSubqueryName , unquoted ) where import qualified Hasql as H import qualified Hasql.Backend as B import qualified Hasql.Postgres as P import qualified Data.Aeson as JSON import PostgREST.RangeQuery (NonnegRange, rangeLimit, rangeOffset) import Control.Error (note, fromMaybe, mapMaybe) import qualified Data.HashMap.Strict as HM import Data.List (find) import Data.Monoid ((<>)) import Data.Text (Text, intercalate, unwords, replace, isInfixOf, toLower, split) import qualified Data.Text as T (map, takeWhile) import Data.String.Conversions (cs) import Control.Applicative (empty, (<|>)) import Data.Tree (Tree(..)) import qualified Data.Vector as V import PostgREST.Types import qualified Data.Map as M import Text.Regex.TDFA ((=~)) import qualified Data.ByteString.Char8 as BS import Data.Scientific ( FPFormat (..) , formatScientific , isInteger ) import Prelude hiding (unwords) type PStmt = H.Stmt P.Postgres instance Monoid PStmt where mappend (B.Stmt query params prep) (B.Stmt query' params' prep') = B.Stmt (query <> query') (params <> params') (prep && prep') mempty = B.Stmt "" empty True type StatementT = PStmt -> PStmt createReadStatement :: SqlQuery -> NonnegRange -> Bool -> Bool -> Bool -> B.Stmt P.Postgres createReadStatement selectQuery range isSingle countTable asCsv = B.Stmt ( wrapLimitedQuery selectQuery [ if countTable then countAllF else countNoneF, countF, "null", -- location header can not be calucalted if asCsv then asCsvF else if isSingle then asJsonSingleF else asJsonF ] selectStarF range ) V.empty True createWriteStatement :: SqlQuery -> SqlQuery -> Bool -> Bool -> [Text] -> Bool -> Payload -> B.Stmt P.Postgres createWriteStatement _ _ _ _ _ _ (PayloadParseError _) = undefined createWriteStatement selectQuery mutateQuery isSingle echoRequested pKeys asCsv (PayloadJSON (UniformObjects rows)) = B.Stmt ( wrapQuery mutateQuery [ countNoneF, -- when updateing it does not make sense countF, if isSingle then locationF pKeys else "null", if echoRequested then if asCsv then asCsvF else if isSingle then asJsonSingleF else asJsonF else "null" ] selectQuery ) (V.singleton . B.encodeValue . JSON.Array . V.map JSON.Object $ rows) True addRelations :: Schema -> [Relation] -> Maybe ReadRequest -> ReadRequest -> Either Text ReadRequest addRelations schema allRelations parentNode node@(Node n@(query, (table, _)) forest) = case parentNode of Nothing -> Node (query, (table, Nothing)) <$> updatedForest (Just (Node (_, (parentTable, _)) _)) -> Node <$> (addRel n <$> rel) <*> updatedForest where rel = note ("no relation between " <> table <> " and " <> parentTable) $ findRelation schema table parentTable <|> findRelation schema parentTable table addRel :: (ReadQuery, (NodeName, Maybe Relation)) -> Relation -> (ReadQuery, (NodeName, Maybe Relation)) addRel (q, (t, _)) r = (q, (t, Just r)) where updatedForest = mapM (addRelations schema allRelations (Just node)) forest findRelation s t1 t2 = find (\r -> s == (tableSchema . relTable) r && t1 == (tableName . relTable) r && t2 == (tableName . relFTable) r) allRelations addJoinConditions :: Schema -> ReadRequest -> Either Text ReadRequest addJoinConditions schema (Node (query, (n, r)) forest) = case r of Nothing -> Node (updatedQuery, (n,r)) <$> updatedForest -- this is the root node Just rel@(Relation{relType=Child}) -> Node (addCond updatedQuery (getJoinConditions rel),(n,r)) <$> updatedForest Just (Relation{relType=Parent}) -> Node (updatedQuery, (n,r)) <$> updatedForest Just rel@(Relation{relType=Many, relLTable=(Just linkTable)}) -> Node (qq, (n, r)) <$> updatedForest where q = addCond updatedQuery (getJoinConditions rel) qq = q{from=tableName linkTable : from q} _ -> Left "unknown relation" where -- add parentTable and parentJoinConditions to the query updatedQuery = foldr (flip addCond) query parentJoinConditions where parentJoinConditions = map (getJoinConditions . snd) parents parents = mapMaybe (getParents . rootLabel) forest getParents (_, (tbl, Just rel@(Relation{relType=Parent}))) = Just (tbl, rel) getParents _ = Nothing updatedForest = mapM (addJoinConditions schema) forest addCond q con = q{flt_=con ++ flt_ q} asJson :: StatementT asJson s = s { B.stmtTemplate = "array_to_json(coalesce(array_agg(row_to_json(t)), '{}'))::character varying from (" <> B.stmtTemplate s <> ") t" } callProc :: QualifiedIdentifier -> JSON.Object -> PStmt callProc qi params = do let args = intercalate "," $ map assignment (HM.toList params) B.Stmt ("select * from " <> fromQi qi <> "(" <> args <> ")") empty True where assignment (n,v) = pgFmtIdent n <> ":=" <> insertableValue v operators :: [(Text, SqlFragment)] operators = [ ("eq", "="), ("gte", ">="), -- has to be before gt (parsers) ("gt", ">"), ("lte", "<="), -- has to be before lt (parsers) ("lt", "<"), ("neq", "<>"), ("like", "like"), ("ilike", "ilike"), ("in", "in"), ("notin", "not in"), ("isnot", "is not"), -- has to be before is (parsers) ("is", "is"), ("@@", "@@"), ("@>", "@>"), ("<@", "<@") ] pgFmtIdent :: SqlFragment -> SqlFragment pgFmtIdent x = let escaped = replace "\"" "\"\"" (trimNullChars $ cs x) in if (cs escaped :: BS.ByteString) =~ danger then "\"" <> escaped <> "\"" else escaped where danger = "^$|^[^a-z_]|[^a-z_0-9]" :: BS.ByteString pgFmtLit :: SqlFragment -> SqlFragment pgFmtLit x = let trimmed = trimNullChars x escaped = "'" <> replace "'" "''" trimmed <> "'" slashed = replace "\\" "\\\\" escaped in if "\\\\" `isInfixOf` escaped then "E" <> slashed else slashed requestToQuery :: Schema -> DbRequest -> SqlQuery requestToQuery _ (DbMutate (Insert _ (PayloadParseError _))) = undefined requestToQuery _ (DbMutate (Update _ (PayloadParseError _) _)) = undefined requestToQuery schema (DbRead (Node (Select colSelects tbls conditions ord, (mainTbl, _)) forest)) = query where -- TODO! the folloing helper functions are just to remove the "schema" part when the table is "source" which is the name -- of our WITH query part tblSchema tbl = if tbl == sourceSubqueryName then "" else schema qi = QualifiedIdentifier (tblSchema mainTbl) mainTbl toQi t = QualifiedIdentifier (tblSchema t) t query = unwords [ ("WITH " <> intercalate ", " (map fst withs)) `emptyOnNull` withs, "SELECT ", intercalate ", " (map (pgFmtSelectItem qi) colSelects ++ selects), "FROM ", intercalate ", " (map (fromQi . toQi) tbls ++ map snd withs), ("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions, orderF (fromMaybe [] ord) ] orderF ts = if null ts then "" else "ORDER BY " <> clause where clause = intercalate "," (map queryTerm ts) queryTerm :: OrderTerm -> Text queryTerm t = " " <> cs (pgFmtColumn qi $ otTerm t) <> " " <> (cs.show) (otDirection t) <> " " <> maybe "" (cs.show) (otNullOrder t) <> " " (withs, selects) = foldr getQueryParts ([],[]) forest getQueryParts :: Tree ReadNode -> ([(SqlFragment, Text)], [SqlFragment]) -> ([(SqlFragment,Text)], [SqlFragment]) getQueryParts (Node n@(_, (table, Just (Relation {relType=Child}))) forst) (w,s) = (w,sel:s) where sel = "(" <> "SELECT array_to_json(array_agg(row_to_json("<>table<>"))) " <> "FROM (" <> subquery <> ") " <> table <> ") AS " <> table where subquery = requestToQuery schema (DbRead (Node n forst)) getQueryParts (Node n@(_, (table, Just (Relation {relType=Parent}))) forst) (w,s) = (wit:w,sel:s) where sel = "row_to_json(" <> table <> ".*) AS "<>table --TODO must be singular wit = (table <> " AS ( " <> subquery <> " )", table) where subquery = requestToQuery schema (DbRead (Node n forst)) getQueryParts (Node n@(_, (table, Just (Relation {relType=Many}))) forst) (w,s) = (w,sel:s) where sel = "(" <> "SELECT array_to_json(array_agg(row_to_json("<>table<>"))) " <> "FROM (" <> subquery <> ") " <> table <> ") AS " <> table where subquery = requestToQuery schema (DbRead (Node n forst)) --the following is just to remove the warning --getQueryParts is not total but requestToQuery is called only after addJoinConditions which ensures the only --posible relations are Child Parent Many getQueryParts (Node (_,(_,Nothing)) _) _ = undefined requestToQuery schema (DbMutate (Insert mainTbl (PayloadJSON (UniformObjects rows)))) = let qi = QualifiedIdentifier schema mainTbl cols = map pgFmtIdent $ fromMaybe [] (HM.keys <$> (rows V.!? 0)) colsString = intercalate ", " cols in unwords [ "INSERT INTO ", fromQi qi, " (" <> colsString <> ")" <> " SELECT " <> colsString <> " FROM json_populate_recordset(null::" , fromQi qi, ", ?)", " RETURNING " <> fromQi qi <> ".*" ] requestToQuery schema (DbMutate (Update mainTbl (PayloadJSON (UniformObjects rows)) conditions)) = case rows V.!? 0 of Just obj -> let assignments = map (\(k,v) -> pgFmtIdent k <> "=" <> insertableValue v) $ HM.toList obj in unwords [ "UPDATE ", fromQi qi, " SET " <> intercalate "," assignments <> " ", ("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions, "RETURNING " <> fromQi qi <> ".*" ] Nothing -> undefined where qi = QualifiedIdentifier schema mainTbl requestToQuery schema (DbMutate (Delete mainTbl conditions)) = query where qi = QualifiedIdentifier schema mainTbl query = unwords [ "DELETE FROM ", fromQi qi, ("WHERE " <> intercalate " AND " ( map (pgFmtCondition qi ) conditions )) `emptyOnNull` conditions, "RETURNING " <> fromQi qi <> ".*" ] sourceSubqueryName :: SqlFragment sourceSubqueryName = "pg_source" unquoted :: JSON.Value -> Text unquoted (JSON.String t) = t unquoted (JSON.Number n) = cs $ formatScientific Fixed (if isInteger n then Just 0 else Nothing) n unquoted (JSON.Bool b) = cs . show $ b unquoted v = cs $ JSON.encode v -- private functions asCsvF :: SqlFragment asCsvF = asCsvHeaderF <> " || '\n' || " <> asCsvBodyF where asCsvHeaderF = "(SELECT string_agg(a.k, ',')" <> " FROM (" <> " SELECT json_object_keys(r)::TEXT as k" <> " FROM ( " <> " SELECT row_to_json(hh) as r from " <> sourceSubqueryName <> " as hh limit 1" <> " ) s" <> " ) a" <> ")" asCsvBodyF = "coalesce(string_agg(substring(t::text, 2, length(t::text) - 2), '\n'), '')" asJsonF :: SqlFragment asJsonF = "array_to_json(array_agg(row_to_json(t)))::character varying" asJsonSingleF :: SqlFragment --TODO! unsafe when the query actually returns multiple rows, used only on inserting and returning single element asJsonSingleF = "string_agg(row_to_json(t)::text, ',')::character varying " countAllF :: SqlFragment countAllF = "(SELECT pg_catalog.count(1) FROM (SELECT * FROM " <> sourceSubqueryName <> ") a )" countF :: SqlFragment countF = "pg_catalog.count(t)" countNoneF :: SqlFragment countNoneF = "null" locationF :: [Text] -> SqlFragment locationF pKeys = "(" <> " WITH s AS (SELECT row_to_json(ss) as r from " <> sourceSubqueryName <> " as ss limit 1)" <> " SELECT string_agg(json_data.key || '=' || coalesce( 'eq.' || json_data.value, 'is.null'), '&')" <> " FROM s, json_each_text(s.r) AS json_data" <> ( if null pKeys then "" else " WHERE json_data.key IN ('" <> intercalate "','" pKeys <> "')" ) <> ")" fromQi :: QualifiedIdentifier -> SqlFragment fromQi t = (if s == "" then "" else pgFmtIdent s <> ".") <> pgFmtIdent n where n = qiName t s = qiSchema t getJoinConditions :: Relation -> [Filter] getJoinConditions (Relation t cols ft fcs typ lt lc1 lc2) = case typ of Child -> zipWith (toFilter tN ftN) cols fcs Parent -> zipWith (toFilter tN ftN) cols fcs Many -> zipWith (toFilter tN ltN) cols (fromMaybe [] lc1) ++ zipWith (toFilter ftN ltN) fcs (fromMaybe [] lc2) where s = if typ == Parent then "" else tableSchema t tN = tableName t ftN = tableName ft ltN = fromMaybe "" (tableName <$> lt) toFilter :: Text -> Text -> Column -> Column -> Filter toFilter tb ftb c fc = Filter (colName c, Nothing) "=" (VForeignKey (QualifiedIdentifier s tb) (ForeignKey fc{colTable=(colTable fc){tableName=ftb}})) emptyOnNull :: Text -> [a] -> Text emptyOnNull val x = if null x then "" else val insertableValue :: JSON.Value -> SqlFragment insertableValue JSON.Null = "null" insertableValue v = (<> "::unknown") . pgFmtLit $ unquoted v whiteList :: Text -> SqlFragment whiteList val = fromMaybe (cs (pgFmtLit val) <> "::unknown ") (find ((==) . toLower $ val) ["null","true","false"]) pgFmtColumn :: QualifiedIdentifier -> Text -> SqlFragment pgFmtColumn table "*" = fromQi table <> ".*" pgFmtColumn table c = fromQi table <> "." <> pgFmtIdent c pgFmtField :: QualifiedIdentifier -> Field -> SqlFragment pgFmtField table (c, jp) = pgFmtColumn table c <> pgFmtJsonPath jp pgFmtSelectItem :: QualifiedIdentifier -> SelectItem -> SqlFragment pgFmtSelectItem table (f@(_, jp), Nothing) = pgFmtField table f <> pgFmtAsJsonPath jp pgFmtSelectItem table (f@(_, jp), Just cast ) = "CAST (" <> pgFmtField table f <> " AS " <> cast <> " )" <> pgFmtAsJsonPath jp pgFmtCondition :: QualifiedIdentifier -> Filter -> SqlFragment pgFmtCondition table (Filter (col,jp) ops val) = notOp <> " " <> sqlCol <> " " <> pgFmtOperator opCode <> " " <> if opCode `elem` ["is","isnot"] then whiteList (getInner val) else sqlValue where headPredicate:rest = split (=='.') ops hasNot caseTrue caseFalse = if headPredicate == "not" then caseTrue else caseFalse opCode = hasNot (head rest) headPredicate notOp = hasNot headPredicate "" sqlCol = case val of VText _ -> pgFmtColumn table col <> pgFmtJsonPath jp VForeignKey qi _ -> pgFmtColumn qi col sqlValue = valToStr val getInner v = case v of VText s -> s _ -> "" valToStr v = case v of VText s -> pgFmtValue opCode s VForeignKey (QualifiedIdentifier s _) (ForeignKey Column{colTable=Table{tableName=ft}, colName=fc}) -> pgFmtColumn qi fc where qi = QualifiedIdentifier (if ft == sourceSubqueryName then "" else s) ft _ -> "" pgFmtValue :: Text -> Text -> SqlFragment pgFmtValue opCode val = case opCode of "like" -> unknownLiteral $ T.map star val "ilike" -> unknownLiteral $ T.map star val "in" -> "(" <> intercalate ", " (map unknownLiteral $ split (==',') val) <> ") " "notin" -> "(" <> intercalate ", " (map unknownLiteral $ split (==',') val) <> ") " "@@" -> "to_tsquery(" <> unknownLiteral val <> ") " _ -> unknownLiteral val where star c = if c == '*' then '%' else c unknownLiteral = (<> "::unknown ") . pgFmtLit pgFmtOperator :: Text -> SqlFragment pgFmtOperator opCode = fromMaybe "=" $ M.lookup opCode operatorsMap where operatorsMap = M.fromList operators pgFmtJsonPath :: Maybe JsonPath -> SqlFragment pgFmtJsonPath (Just [x]) = "->>" <> pgFmtLit x pgFmtJsonPath (Just (x:xs)) = "->" <> pgFmtLit x <> pgFmtJsonPath ( Just xs ) pgFmtJsonPath _ = "" pgFmtAsJsonPath :: Maybe JsonPath -> SqlFragment pgFmtAsJsonPath Nothing = "" pgFmtAsJsonPath (Just xx) = " AS " <> last xx trimNullChars :: Text -> Text trimNullChars = T.takeWhile (/= '\x0') withSourceF :: SqlFragment -> SqlFragment withSourceF s = "WITH " <> sourceSubqueryName <> " AS (" <> s <>")" fromF :: SqlFragment -> SqlFragment -> SqlFragment fromF sel limit = "FROM (" <> sel <> " " <> limit <> ") t" limitF :: NonnegRange -> SqlFragment limitF r = "LIMIT " <> limit <> " OFFSET " <> offset where limit = maybe "ALL" (cs . show) $ rangeLimit r offset = cs . show $ rangeOffset r selectStarF :: SqlFragment selectStarF = "SELECT * FROM " <> sourceSubqueryName wrapLimitedQuery :: SqlQuery -> [Text] -> Text -> NonnegRange -> SqlQuery wrapLimitedQuery source selectColumns returnSelect range = withSourceF source <> " SELECT " <> intercalate ", " selectColumns <> " " <> fromF returnSelect ( limitF range ) wrapQuery :: SqlQuery -> [Text] -> Text -> SqlQuery wrapQuery source selectColumns returnSelect = withSourceF source <> " SELECT " <> intercalate ", " selectColumns <> " " <> fromF returnSelect ""
NikolayS/postgrest
src/PostgREST/QueryBuilder.hs
mit
17,914
0
24
4,309
5,520
2,955
2,565
361
8
module Problem45 where {-- Task description: Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ... Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ... It can be verified that T285 = P165 = H143 = 40755. Find the next triangle number that is also pentagonal and hexagonal. --} import Control.Arrow as Arrow import Data.List as List type N = Int type Stream = ([N],[N]) type Point = (N,N) -- Definition of number functions: triangle,pentagonal,hexagonal :: N -> N triangle n = n*(n+1) `div` 2 pentagonal n = n*(3*n-1) `div` 2 hexagonal n = n*(2*n-1) -- Evry hexagonal number is also a triangle number. -- n = (sqrt(24x+1)+1)/6 isPentagonal :: N -> Bool isPentagonal n = let m = 24*n+1 o = sqrt $ fromIntegral m :: Double p = (o+1)/6 in ceiling p == floor p solution = last . take 3 . filter isPentagonal $ fmap hexagonal [1..] main = print solution
runjak/projectEuler
src/Problem45.hs
mit
1,073
0
11
282
264
150
114
17
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} module Main where import Filesystem import Control.Applicative import Control.Monad import Stackage.CLI import Options.Applicative (Parser) import Options.Applicative.Builder (strArgument, metavar, value) import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Typeable (Typeable) import Network.HTTP.Client import Network.HTTP.Client.TLS (tlsManagerSettings) import Network.HTTP.Types.Status (statusCode) import Network.HTTP.Types.Header (hUserAgent) import qualified Data.ByteString.Lazy as LBS import System.Exit (exitFailure) import System.Environment (getArgs) import System.IO (hPutStrLn, stderr) import Control.Exception import qualified Paths_stackage_cabal as CabalInfo type Snapshot = String data InitException = InvalidSnapshot | SnapshotNotFound | UnexpectedHttpException HttpException | CabalConfigExists deriving (Show, Typeable) instance Exception InitException version :: String version = $(simpleVersion CabalInfo.version) header :: String header = "Initializes cabal.config" progDesc :: String progDesc = header userAgent :: Text userAgent = "stackage-init/" <> T.pack version snapshotParser :: Parser Snapshot snapshotParser = strArgument mods where mods = (metavar "SNAPSHOT" <> value "lts") toUrl :: Snapshot -> String toUrl t = "https://www.stackage.org/" <> t <> "/cabal.config" snapshotReq :: Snapshot -> IO Request snapshotReq snapshot = case parseUrl (toUrl snapshot) of Left _ -> throwIO $ InvalidSnapshot Right req -> return req { requestHeaders = [(hUserAgent, T.encodeUtf8 userAgent)] } downloadSnapshot :: Snapshot -> IO LBS.ByteString downloadSnapshot snapshot = withManager tlsManagerSettings $ \manager -> do let getResponseLbs req = do response <- httpLbs req manager return $ responseBody response let handle404 firstTry (StatusCodeException s _ _) | statusCode s == 404 = if firstTry then do req <- snapshotReq $ "snapshot/" <> snapshot getResponseLbs req `catch` handle404 False else do throwIO $ SnapshotNotFound handle404 _ e = throwIO $ UnexpectedHttpException e req <- snapshotReq snapshot getResponseLbs req `catch` handle404 True initSnapshot :: Snapshot -> IO () initSnapshot snapshot = do configExists <- isFile "cabal.config" when configExists $ throwIO $ CabalConfigExists downloadSnapshot snapshot >>= LBS.writeFile "cabal.config" handleInitExceptions :: Snapshot -> InitException -> IO () handleInitExceptions snapshot e = hPutStrLn stderr (err e) >> exitFailure where err InvalidSnapshot = "Invalid snapshot: " <> snapshot err SnapshotNotFound = "Snapshot not found: " <> snapshot err CabalConfigExists = "Warning: Cabal config already exists.\n" <> "No action taken." err (UnexpectedHttpException e) = "Unexpected http exception:\n" <> show e main = do (snapshot, ()) <- simpleOptions version header progDesc snapshotParser -- global parser empty -- subcommands initSnapshot snapshot `catch` handleInitExceptions snapshot
fpco/stackage-cabal
main/Init.hs
mit
3,252
0
18
580
833
442
391
91
4
{-# LANGUAGE MultiWayIf #-} module Data.Bitsplit.Types (Address, mkAddress, Split, mkSplit, unpackSplit, isEmpty) where import Data.Ratio import Data.Natural import Data.Map (fromList, toList) --import qualified Network.Bitcoin.Types as BT newtype Address = Address String deriving (Eq, Show, Ord) --BT.Address mkAddress :: String -> Maybe Address mkAddress = Just . Address --BT.mkAddress newtype Split = Split [(Address, Ratio Natural)] deriving (Show, Eq) -- Guarantees from constructor (gen test this!): -- Every Address is unique -- All of the "values" add up to exactly one, or zero if empty -- Because of the above, every number is [0, 1] split = Right . Split dedupe :: Ord a => [(a, b)] -> [(a, b)] dedupe = toList . fromList mkSplit :: [(Address, Ratio Natural)] -> Either String Split mkSplit [] = split [] mkSplit [(address, _)] = split [(address, 1)] mkSplit ratios = let deduped = dedupe ratios total = foldl (+) 0 $ fmap snd deduped in if -- | True -> split deduped -- use for testing failing stuff | length deduped < length ratios -> Left "Duplicate addresses in list" | total == 1 -> split deduped | otherwise -> Left "Total not equal to 1" isEmpty :: Split -> Bool isEmpty (Split []) = True isEmpty _ = False unpackSplit :: Split -> [(Address, Ratio Natural)] unpackSplit (Split split) = split
micmarsh/bitsplit-hs
src/Data/Bitsplit/Types.hs
mit
1,401
0
12
309
417
229
188
28
3
module Jhc.Function where {-# SUPERINLINE id, const, (.), ($), ($!), flip #-} infixr 9 . infixr 0 $, $!, `seq` id x = x const x _ = x f . g = \x -> f (g x) f $ x = f x f $! x = x `seq` f x flip f x y = f y 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. {-# SUPERINLINE asTypeOf #-} asTypeOf :: a -> a -> a asTypeOf = const {-# INLINE seq #-} foreign import primitive seq :: a -> b -> b infixl 0 `on` -- | @'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 -
m-alvarez/jhc
lib/jhc/Jhc/Function.hs
mit
1,869
2
10
549
285
179
106
-1
-1
{-# LANGUAGE CPP #-} module GHCJS.DOM.StyleSheet ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.StyleSheet #else module Graphics.UI.Gtk.WebKit.DOM.StyleSheet #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.StyleSheet #else import Graphics.UI.Gtk.WebKit.DOM.StyleSheet #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/StyleSheet.hs
mit
435
0
5
39
33
26
7
4
0
{-# LANGUAGE CPP #-} module GHCJS.DOM.Coordinates ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.Coordinates #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.Coordinates #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/Coordinates.hs
mit
346
0
5
33
33
26
7
4
0
module MinHS.Evaluator where import qualified MinHS.Env as E import MinHS.Syntax import MinHS.Pretty import qualified Text.PrettyPrint.ANSI.Leijen as PP type VEnv = E.Env Value data VFun = VFun (Value -> Value) instance Show VFun where show _ = error "Tried to show lambda" data Value = I Integer | B Bool | Nil | Cons Integer Value | Lam VFun deriving (Show) instance PP.Pretty Value where pretty (I i) = numeric i pretty (B b) = datacon $ show b pretty (Nil) = datacon "Nil" pretty (Cons x v) = PP.parens (datacon "Cons" PP.<+> numeric x PP.<+> PP.pretty v) pretty _ = undefined -- should not ever be used evaluate :: Program -> Value evaluate bs = evalE E.empty (Let bs (Var "main")) lam :: (Value -> Value) -> Value lam f = Lam $ VFun f evalE :: VEnv -> Exp -> Value evalE env (Var name) = case E.lookup env name of Just v -> v _ -> error $ "Not in scope: " ++ name evalE _ (Prim op) = evalOp op evalE _ (Con val) = case val of "True" -> B True "False" -> B False "Nil" -> Nil "Cons" -> lam $ \(I h) -> lam $ \t -> Cons h t evalE _ (Num n) = I n evalE env (If p t e) = case evalE env p of B True -> evalE env t B False -> evalE env e evalE env (App e1 e2) = let Lam (VFun f) = evalE env e1 x = evalE env e2 in f x evalE env (Let [] body) = evalE env body evalE env (Let (bind : binds) body) = case bind of Bind name _ args def -> let env' = E.add env (name, bindLam env args def) in evalE env' (Let binds body) evalE env f@(Letfun (Bind name _ args body)) = let env' = E.add env (name, evalE env f) in bindLam env' args body evalE env (Letrec binds body) = let eval (Bind name _ args def) = (name, bindLam env' args def) bindVals = eval `map` binds env' = E.addAll env bindVals in evalE env' body bindLam :: VEnv -> [Id] -> Exp -> Value bindLam env [] body = evalE env body bindLam env (arg : args) body = lam $ \v -> let env' = E.add env (arg, v) in bindLam env' args body evalOp :: Op -> Value evalOp op = let intOp f = lam $ \(I n1) -> lam $ \(I n2) -> I (n1 `f` n2) boolOp f = lam $ \(I n1) -> lam $ \(I n2) -> B (n1 `f` n2) in case op of Add -> intOp (+) Sub -> intOp (-) Mul -> intOp (*) Quot -> intOp div Rem -> intOp rem Eq -> boolOp (==) Gt -> boolOp (>) Ge -> boolOp (>=) Lt -> boolOp (<) Le -> boolOp (<=) Ne -> boolOp (/=) Neg -> lam $ \(I n) -> I (-n) Null -> lam $ \l -> case l of Cons _ _ -> B False Nil -> B True Head -> lam $ \l -> case l of Cons i _ -> I i _ -> error "Head of Nil!" Tail -> lam $ \l -> case l of Cons _ t -> t _ -> error "Tail of Nil!"
pierzchalski/cs3161a1
MinHS/Evaluator.hs
mit
2,781
0
15
863
1,356
685
671
91
18
-- Sum of Digits / Digital Root -- http://www.codewars.com/kata/541c8630095125aba6000c00/ module DigitalRoot where import Data.Char (digitToInt) digitalRoot :: Integral a => a -> a digitalRoot n | (n `div` 10) == 0 = n | otherwise = digitalRoot . fromIntegral . sum . map digitToInt . show . fromIntegral $ n
gafiatulin/codewars
src/6 kyu/DigitalRoot.hs
mit
326
0
11
67
95
50
45
5
1
module GHCJS.DOM.ClientRectList ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/ClientRectList.hs
mit
44
0
3
7
10
7
3
1
0
-- Code to deal with star colors module Color where data Color = RGB { colorR :: Double , colorG :: Double , colorB :: Double } deriving (Show,Eq) addColors :: Color -> Color -> Color addColors a b = RGB { colorR = ((colorR a) + (colorR b)) , colorG = ((colorG a) + (colorG b)) , colorB = ((colorB a) + (colorB b)) } scaleColor :: Color -> Double -> Color scaleColor clr sf = RGB { colorR = sf * (colorR clr) , colorG = sf * (colorG clr) , colorB = sf * (colorB clr) }
j3camero/galaxyatlas
OldCrap/haskell/stardata/src/Color.hs
mit
577
0
10
208
216
122
94
16
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module NFKD (specs) where import Data.Monoid import Data.Text.Normal.NFKD import Data.String import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck (Arbitrary(..)) import Test.QuickCheck.Instances () instance Arbitrary Normal where arbitrary = fmap fromText arbitrary angstrom_sign, a_with_ring, e_acute, e_with_acute :: IsString a => a -- should be identical under NFKC angstrom_sign = "\8491" a_with_ring = "\197" e_acute = "\233" e_with_acute = "e\769" specs = do describe "Normal type" $ do prop "should look identical to Text type" $ \a -> show (toText a) == show a prop "should Read identical to Text type" $ \a -> fromText (read (show a)) == read (show $ toText a) it "should normalize when using IsString instance" $ do "a" `shouldBe` fromText "a" angstrom_sign `shouldBe` fromText a_with_ring describe "fromText" $ do prop "is idempotent" $ \a -> toText a == toText (fromText (toText a)) it "normalizes" $ do fromText angstrom_sign `shouldBe` fromText a_with_ring fromText e_with_acute `shouldBe` fromText e_acute describe "appending" $ do describe "follows monoid laws" $ do prop "mappend mempty x = x" $ \(a :: Normal) -> a == mempty <> a prop "mappend x mempty = x" $ \(a :: Normal) -> a == a <> mempty prop "mappend x (mappend y z) = mappend (mappend x y) z" $ \(a :: Normal) b c -> a <> (b <> c) == (a <> b) <> c prop "mconcat = foldr mappend mempty" $ \(as :: [Normal]) -> mconcat as == foldr (<>) mempty as it "normalizes the result" $ property $ \a b -> fromText a <> fromText b == fromText (a <> b) it "normalizes the result, take 2" $ fromText "e" <> fromText "\769" `shouldBe` fromText e_with_acute {-# ANN module ("HLint: ignore Use camelCase" :: String) #-}
pikajude/text-normal
tests/NFKD.hs
mit
2,103
0
19
593
582
295
287
47
1
{-| This module provides 'xmlFormatter' that can be used with 'Test.Hspec.Runner.hspecWith'. Example usage: > import Test.Hspec.Formatters.Jenkins (xmlFormatter) > import Test.Hspec.Runner > > main :: IO () > main = do > summary <- withFile "results.xml" WriteMode $ \h -> do > let c = defaultConfig > { configFormatter = xmlFormatter > , configHandle = h > } > hspecWith c spec > unless (summaryFailures summary == 0) $ > exitFailure An example project is located in @example@ directory. -} {-# LANGUAGE OverloadedStrings #-} module Test.Hspec.Formatters.Jenkins (xmlFormatter) where import Data.List (intercalate) import Test.Hspec.Formatters import Test.Hspec.Runner (Path) import Text.Blaze.Renderer.String (renderMarkup) import Text.Blaze.Internal failure, skipped :: Markup -> Markup failure = customParent "failure" skipped = customParent "skipped" name, className, message :: String -> Attribute name = customAttribute "name" . stringValue className = customAttribute "classname" . stringValue message = customAttribute "message" . stringValue testcase :: Path -> Markup -> Markup testcase (xs,x) = customParent "testcase" ! name x ! className (intercalate "." xs) -- | Format Hspec result to Jenkins-friendly XML. xmlFormatter :: Formatter xmlFormatter = silent { headerFormatter = do writeLine "<?xml version='1.0' encoding='UTF-8'?>" writeLine "<testsuite>" , exampleSucceeded = \path -> do writeLine $ renderMarkup $ testcase path "" , exampleFailed = \path err -> do writeLine $ renderMarkup $ testcase path $ failure ! message (either formatException id err) $ "" , examplePending = \path mdesc -> do writeLine $ renderMarkup $ testcase path $ case mdesc of Just desc -> skipped ! message desc $ "" Nothing -> skipped "" , footerFormatter = do writeLine "</testsuite>" }
worksap-ate/hspec-jenkins
lib/Test/Hspec/Formatters/Jenkins.hs
mit
1,988
0
16
459
374
201
173
36
2
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} -- |Multi-parameter variant of Applicative. -- The contained data type is an explicit type parameter, -- allowing instances to be made dependent on it. -- -- The Applicative type class is split into two classes: -- @Pure f a@, which provides @pure :: a -> f a@, and -- @Applicative' f a b@, which provides -- @(<*>) :: f (a -> b) -> f a -> f b@. -- -- Note that, unlike regular monads, multi-parameter -- monads with restrictions do not always imply the existence -- of (meaningul) instances of Applicative\'. -- For example, Set can be a Monad' (with Ord-restrictions), -- but it cannot be a meaningful Applicative'-instance, since -- '<*> :: f (a -> b) -> f a -> f b' would require the context 'Ord (a -> b)'. -- -- For technical reasons, the instance 'Applicative\' Set a b' is -- provided nonetheless, with the definition -- -- @ -- f <*> x = Set.fromList $ Set.toList f Ap.<*> Set.toList x -- @ -- -- This might as well be undefined, as, by default, a set of functions -- is not constructible. Should the user declare '(Ord (a -> b))', however, -- @<*>@ will work. -- -- Adapted from Oleg Kiselyov's -- 'http://okmij.org/ftp/Haskell/types.html#restricted-datatypes'. module Control.Applicative.MultiParam ( Applicative'(..), Pure(..), ) where import qualified Control.Monad as Mo import qualified Control.Applicative as Ap import qualified Data.Set as Set import Data.Functor.MultiParam import Text.ParserCombinators.ReadP(ReadP) import Text.ParserCombinators.ReadPrec(ReadPrec) import GHC.Conc(STM) class Pure f a where pure :: a -> f a class Functor' f a b => Applicative' f a b where (<*>) :: f (a -> b) -> f a -> f b instance Pure [] a where pure = Mo.return instance Applicative' [] a b where f <*> x = f Ap.<*> x instance Pure IO a where pure = Mo.return instance Applicative' IO a b where f <*> x = f Ap.<*> x instance Pure Maybe a where pure = Mo.return instance Applicative' Maybe a b where f <*> x = f Ap.<*> x instance Pure ReadP a where pure = Mo.return instance Applicative' ReadP a b where f <*> x = f Ap.<*> x instance Pure ReadPrec a where pure = Mo.return instance Applicative' ReadPrec a b where f <*> x = f Ap.<*> x instance Pure STM a where pure = Mo.return instance Applicative' STM a b where f <*> x = f Ap.<*> x instance Ord a => Pure Set.Set a where pure = Set.singleton instance (Ord a, Ord b) => Applicative' Set.Set a b where f <*> x = Set.fromList $ Set.toList f Ap.<*> Set.toList x
ombocomp/MultiParamMonad
Control/Applicative/MultiParam.hs
mit
2,542
0
10
490
563
311
252
31
0
{-# LANGUAGE Arrows, OverlappingInstances, UndecidableInstances, IncoherentInstances, NoMonomorphismRestriction, MultiParamTypeClasses, FlexibleInstances, RebindableSyntax #-} -- Das Modul \hsSource{Circuit.ShowType.Instance} beschreibt, wie die Arrow-Klasse zu implementieren sind um damit später Schaltkreise -- beschreiben, bearbeiten oder benutzen zu können. module System.ArrowVHDL.Circuit.ShowType.Instance where -- Folgenden Module werden benötigt, um die Instanzen definieren zu können: import System.ArrowVHDL.Circuit.ShowType.Class import Prelude hiding (id, (.)) import qualified Prelude as Pr import Control.Category import System.ArrowVHDL.Circuit.Graphs import System.ArrowVHDL.Circuit.Descriptor -- Showtype wird hier für bestimmte Tupel-Typen beschrieben. Einzig die Tupel-Information ist das, was mittels Showtype in Pin-Informationen -- übersetzt wird. -- Die \hsSource{ShowType}-Instanz definiert die verschiedenen Typenvarianten, welche abbildbar sind. -- Mit dem Typ \hsSource{(b, c) -> (c, b)} stellt die folgende Variante eine dar, in der die Ein- und Ausgänge miteinander vertauscht werden. instance ShowType (b, c) (c, b) where showType _ = emptyCircuit { nodeDesc = MkNode { label = "|b,c>c,b|" , nodeId = 0 , sinks = mkPins 2 , sources = mkPins 2 } } where nd = nodeDesc emptyCircuit -- Diese Variante mit dem Typ \hsSource{b -> (b, b)} beschreibt den Fall, in dem ein Eingang verdoppelt wird. instance ShowType b (b, b) where showType _ = emptyCircuit { nodeDesc = MkNode { label = "|b>b,b|" , nodeId = 0 , sinks = mkPins 1 , sources = mkPins 2 } } where nd = nodeDesc emptyCircuit -- Mit dem Typ \hsSource{(b, b) -> b} wir dann der Fall abgebildet, der zwei Eingänge auf einen zusammenfasst. instance ShowType (b, b) b where showType _ = emptyCircuit { nodeDesc = MkNode { label = "|b,b>b|" , nodeId = 0 , sinks = mkPins 2 , sources = mkPins 1 } } where nd = nodeDesc emptyCircuit -- instance ShowType (b, c) (b', c') where -- showType _ = emptyCircuit { label = "b,c>b',c'" -- , sinks = mkPins 1 -- , sources = mkPins 1 -- } -- -- instance ShowType b b where -- showType _ = emptyCircuit { label = "|b>b|" -- , sinks = mkPins 1 -- , sources = mkPins 1 -- } -- -- instance ShowType (b -> (c, d)) where -- showType _ = emptyCircuit { label = "b>c,d" -- , sinks = mkPins 1 -- , sources = mkPins 1 -- } -- -- instance ShowType ((b, c) -> d) where -- showType _ = emptyCircuit { label = "b,c>d" -- , sinks = mkPins 1 -- , sources = mkPins 1 -- } -- Letztlich bleibt noch der allgemeinste Fall der Möglich ist. Diese Varianten ist somit auch eine \begriff{CatchAll} Variante. instance ShowType b c where showType _ = emptyCircuit { nodeDesc = MkNode { label = "|b>c|" , nodeId = 0 , sinks = mkPins 1 , sources = mkPins 1 } } where nd = nodeDesc emptyCircuit
frosch03/arrowVHDL
src/System/ArrowVHDL/Circuit/ShowType/Instance.hs
cc0-1.0
3,970
0
10
1,636
386
243
143
47
0
module Numerical where import Vec3 type Flt = Double type Vec = Vec3 Flt
reuk/rayverb
src/Numerical.hs
gpl-2.0
75
0
5
16
22
14
8
4
0
name2reply str = "nice to meet you " ++ str ++ "\n" ++ "your name is " ++ show (length str) ++ "long" main :: IO() main = do putStrLn "nazdar" inpStr <- getLine putStrLn (name2reply inpStr)
Tr1p0d/realWorldHaskell
rwh7/callingpure.hs
gpl-2.0
196
0
9
43
78
36
42
7
1
module FP.Env where import FP.Type import Autolib.TES.Identifier import Autolib.FiniteMap import Autolib.ToDoc import Autolib.Reader import Data.Typeable data Env = Env ( FiniteMap Identifier Type ) deriving Typeable instance ToDoc Env where toDoc ( Env env ) = dutch ( text "{" , semi, text "}" ) $ do ( n, t ) <- fmToList env return $ toDoc n <+> text "::" <+> toDoc t instance Reader Env where reader = my_braces $ do nts <- do n <- reader my_reserved "::" t <- reader return (n, t ) `Autolib.Reader.sepBy` my_reserved ";" return $ Env $ listToFM nts
marcellussiegburg/autotool
collection/src/FP/Env.hs
gpl-2.0
653
0
14
196
223
113
110
22
0
{-# LANGUAGE OverloadedStrings #-} -- | Implements the generic part of the SSH Connection Protocol (RFC 4254). module Ssh.Channel( -- * Data structures ChannelInfo(..) , Channel(..) , Channels(..) , ChannelHandler(..) , GlobalChannelInfo(..) -- * Perform actions on a 'Channel' , runGlobalChannelsToConnection , insertChannel -- * Request actions related to 'Channel's , openChannel , queueDataOverChannel , handleChannel , setChannelPayloadHandler , addChannelCloseHandler -- * Miscelaneous , initialGlobalChannelsState , getLocalChannelNr ) where import qualified Data.ByteString.Lazy as B import qualified Control.Monad.State as MS import qualified Data.Map as Map import Control.Monad import Data.Maybe import Data.List import Ssh.Packet import Ssh.Transport import Ssh.Debug import Ssh.String -- | Keeps generic information about the channel, such as maximal packet size, and a handler. -- The handler can update the channel information through the 'Channel' State data ChannelInfo = ChannelInfo { channelLocalId :: Int , channelRemoteId :: Maybe Int -- ^ Nothing if we have not yet received the OpenConfirmation with the remote ID, or Just remoteId , closed :: Bool , sentEof :: Bool , gotEof :: Bool , channelLocalWindowSizeLeft :: Int , channelLocalMaxPacketSize :: Int , channelRemoteWindowSizeLeft :: Maybe Int -- ^ Nothing if we have not yet received the OpenConfirmation from the remote, or Just windowSizeLeft , channelRemoteMaxPacketSize :: Maybe Int -- ^ Nothing if we have not yet received the OpenConfirmation from the remote, or Just maxPacketSize , queuedData :: SshString -- ^ If we try to send data when windowsize is too small, store it here until we get WindowsizeAdjust , channelInfoHandler :: ChannelHandler } -- | A channel is stateful, and has to do socket IO over the 'SshConnection' type Channel = MS.StateT ChannelInfo SshConnection -- | The handler for a certain channel type data ChannelHandler = ChannelHandler { channelName :: SshString -- | Handles a given payload, using the 'ChannelInfo' in the 'Channel' state. , handleChannelPayload :: SshString -> Channel ChannelInfo -- | When a channel gets closed, this function is called to handle some cleanup , handleChannelClose :: Channel () } -- | Information about a specific channel, so we can keep a mapping of live channels data GlobalChannelInfo = GlobalChannelInfo { -- Maps active channels (on their local ID, because the remote will send with the recipientChannel) to their 'ChannelInfo' state usedChannels :: Map.Map Int ChannelInfo -- Keep a list of free channel IDs , freeChannels :: [Int] } type Channels = MS.StateT GlobalChannelInfo SshConnection initialGlobalChannelsState = GlobalChannelInfo Map.empty [0 .. 2^31] -- | Set the payload handler for a channel setChannelPayloadHandler :: (SshString -> Channel ChannelInfo) -> Channel ChannelInfo setChannelPayloadHandler handler = do s <- MS.get let cih = channelInfoHandler s cih' = cih { handleChannelPayload = handler } ret = s { channelInfoHandler = cih' } return $ ret -- | Add a close handler for a channel addChannelCloseHandler :: ChannelInfo -> (Channel ()) -> ChannelInfo addChannelCloseHandler s handler = let cih = channelInfoHandler s cih' = cih { handleChannelClose = handler } ret = s { channelInfoHandler = cih' } in ret -- | Run the action of 'Channels ChannelInfo' on the initial 'GlobalChannelInfo', and at the end just return the resulting connection. Can be used for -- an execution loop, after which the connection should be closed runGlobalChannelsToConnection :: GlobalChannelInfo -> Channels a -> SshConnection () runGlobalChannelsToConnection state action = do MS.runStateT action state return () -- | Run the 'Channel ChannelInfo' action on the channel with the specified 'ChannelInfo', get the resulting info and update it in our 'Channels' state insertChannel :: ChannelInfo -> Channel ChannelInfo -> Channels () insertChannel channel action = do newChannelInfo <- MS.lift $ MS.evalStateT action channel let channelNr = channelLocalId channel modifyUsedChannel channelNr newChannelInfo -- | Get the local channel number of a Channel getLocalChannelNr :: Channel Int getLocalChannelNr = channelLocalId `fmap` MS.get modifyUsedChannel :: Int -> ChannelInfo -> Channels () modifyUsedChannel chanNr newChannelInfo = MS.modify $ \s -> s { usedChannels = Map.insert chanNr newChannelInfo $ usedChannels s } -- TODO: handle the open confirmation to map server ID to local ID! -- | Open a channel on the given 'SshConnection' given in the 'Channels' state, with a channel type, a handler, and initial information to put in the packet's payload openChannel :: ChannelHandler -> SshString -> Channels ChannelInfo openChannel handler openInfo = do state <- MS.get -- Get a new local channel nr let name = channelName handler local = head $ freeChannels state free = take 1 $ freeChannels state -- Open the channel let remoteId = Nothing ws = 2^31 ps = 32768 chanInfo = ChannelInfo local remoteId False False False ws ps Nothing Nothing "" handler openRequest = ChannelOpen name local ws ps openInfo -- Request to open the channel MS.lift $ sPutPacket openRequest let used = Map.insert local chanInfo $ usedChannels state MS.put $ GlobalChannelInfo { usedChannels = used, freeChannels = free } return chanInfo -- TODO actually split/queue if the packetSize/windowSize indicates to split! -- | Queue payload to be sent over the channel indicated by 'ChannelInfo'. -- This data might be sent directly, or might be queued, or split, depending on how the size of the payload compares to the channel's -- 'channelRemoteWindowSizeLeft' and 'channelRemotePacketSize'. queueDataOverChannel :: SshString -> ChannelInfo -> Channels () queueDataOverChannel payload channel = do let localChannel = channelLocalId channel sendSize = B.length payload -- The length of the payload we have to send -- See if we have to queue the data, or can send (part of it) it right away (TODO: packet size) let bytesToSend = do remote <- channelRemoteId channel -- If the remote has not yet sent its ChannelOpen, we have to queue the data windowLeft <- channelRemoteWindowSizeLeft channel -- if the remote's windowsize is too small, queue data! let shouldSend = min (toEnum windowLeft) sendSize -- We can send this many bytes if shouldSend <= 0 then Nothing else Just shouldSend -- If the queue already contains data, this *must* also queue (i.e. append) it. Is ok, because we dequeue data automatically when we get a window size increase case bytesToSend of Nothing -> queueBytes payload localChannel -- Queue everything Just bytes -> do -- Send part, queue the rest let (toSend, toQueue) = B.splitAt bytes payload sendDataOverChannel toSend channel localChannel queueBytes toQueue localChannel -- If this is empty, it'll just get ignored when we get a window size increase, etc. -- | Append these bytes to the 'ChannelInfo's send queue queueBytes :: SshString -> Int -> Channels () queueBytes payload localId = do when (not $ B.null payload) $ printDebugLifted logDebug $ "Queuing bytes: " ++ show payload updateInfoWith localId $ \info -> info { queuedData = queuedData info `B.append` payload } return () -- TODO: packetsize? -- | Send (potentially previously queued) data to the remote *now* (the remote channel is assumed to be open, etc) sendDataOverChannel :: SshString -> ChannelInfo -> Int -> Channels () sendDataOverChannel payload channel localId = do let remoteChannel = fromJust $ channelRemoteId channel request = ChannelData remoteChannel payload -- Send the data MS.lift $ sPutPacket request -- We sent some bytes, which decreases the available window size of the remote updateInfoWith localId $ \info -> info { channelRemoteWindowSizeLeft = Just $ (fromJust $ channelRemoteWindowSizeLeft info) - (fromIntegral $ B.length payload) } return () -- | Get the 'ChannelInfo' with this local id, if it exists yet getChannel :: Int -> Channels (Maybe ChannelInfo) getChannel local = do state <- MS.get return $ Map.lookup local (usedChannels state) -- | Looks up the local channel id, applies the update function to it, and return it. Makes handleChannel somewhat less repetitive to write updateInfoWith :: Int -> (ChannelInfo -> ChannelInfo) -> Channels ChannelInfo updateInfoWith nr action = do info <- fromJust `liftM` getChannel nr let newInfo = action info modifyUsedChannel nr newInfo return newInfo -- | Handle a 'Packet' coming to us. Can dispatch the request to a 'Channel's handler, or change the window size of a 'Channel', confirm its opening, closing, etc. handleChannel :: Packet -> Channels ChannelInfo -- The channel was correctly opened. Update the remote information for this channel handleChannel (ChannelOpenConfirmation recipientNr senderNr initWS maxPS payload) = do updateInfoWith recipientNr $ \info -> info { channelRemoteId = Just senderNr, channelRemoteWindowSizeLeft = Just initWS, channelRemoteMaxPacketSize = Just maxPS } -- The remote says we can send some more bytes to this channel. Increase the window size, and send the sendQueue if needed handleChannel (ChannelWindowAdjust nr toAdd) = do info <- fromJust `liftM` getChannel nr -- Remove the payload, increase the window size let queue = queuedData info action = \info -> info { channelRemoteWindowSizeLeft = Just $ toAdd + (fromJust $ channelRemoteWindowSizeLeft info) , queuedData = B.empty } newInfo = action info -- Write new info modifyUsedChannel nr newInfo -- See if we have to try to send (part of) or queue if B.null queue then return newInfo else do printDebugLifted logDebug $ "Window size increased, requeing data" queueDataOverChannel queue newInfo fromJust `liftM` getChannel nr >>= return -- Remote sends that his side has reached an EOF handleChannel (ChannelEof nr) = do updateInfoWith nr $ \info -> info { gotEof = True } -- Remote closed this channel, remove it from our list for later reuse once we have it removed too handleChannel (ChannelClose nr) = do -- We must send back a ChannelClose, and actually close this channel info <- fromJust `liftM` getChannel nr MS.lift $ sPutPacket $ ChannelClose $ fromJust $ channelRemoteId info -- Set this channel to closed locally closed <- updateInfoWith nr $ \info -> info { gotEof = True } -- Now that the channel is closed, call the close handler of this channel: MS.lift $ MS.runStateT (handleChannelClose (channelInfoHandler info)) info -- This channel is free again to be reused in our Channels state state <- MS.get let newUsedChannels = Map.delete nr $ usedChannels state newFreeChannels = nr : freeChannels state MS.put $ GlobalChannelInfo { usedChannels = newUsedChannels, freeChannels = newFreeChannels } return info -- Extended data can be stuff like standard error handleChannel (ChannelExtendedData nr code payload) = do case code of 1 -> -- SSH_EXTENDED_DATA_STDERR -- TODO: handle with handler? MS.liftIO $ putStrLn $ "Server sent back on standard error: " ++ (map (toEnum . fromEnum) $ B.unpack payload) _ -> printDebugLifted logWarning $ "Unknown channel data type: " ++ show code info <- fromJust `liftM` getChannel nr return info -- When data comes in for one of our channels, be sure to see to which one it is, and dispatch the payload data to it to update handleChannel (ChannelData nr payload) = do state <- MS.get -- Which channel handler? let info = Map.lookup nr $ usedChannels state case info of Just cInfo -> do -- Let the handler do its stuff, get the result, update our map with the newly returned ChannelInfo, which can contain a brand new handler let newChannel = handleChannelPayload (channelInfoHandler cInfo) $ payload :: Channel ChannelInfo (newChannelInfo, newState) <- MS.lift $ MS.runStateT newChannel cInfo modifyUsedChannel nr newChannelInfo return newState Nothing -> do printDebugLifted logWarning $ "No handler found at lookup for channel " ++ show nr return $ error "No handler!" -- TODO Handle other cases we don't care about yet -- And these messages we don't know about. Throw to lower level protocol handling functions! TODO handleChannel p = do state <- MS.get printDebugLifted logDebugExtended "HandleChannel: ignored packet" return $ error "Handle Channel: ignored packet handled"
bcoppens/HaskellSshClient
src/Ssh/Channel.hs
gpl-3.0
13,301
0
18
3,059
2,278
1,177
1,101
181
4
{- The overloaded Standard Prelude for the Helium Compiler -} module Prelude(module Prelude, module PreludePrim, module HeliumLang) where import PreludePrim import HeliumLang infixr 9 . infixl 9 !! infixr 8 ^ -- , **. --infixl 7 `quot`, `rem`, `div`, `mod`, / --infixl 6 +, - infixr 5 ++ -- infixr 5 : [HeliumLang] infix 4 ==, /=, <=, <, >, >= infixr 3 && infixr 2 || infixr 0 $ --, $! [PreludePrim] {----------------------------------------------- -- Num -----------------------------------------------} {- imported from PreludePrim (+) :: Num a => a -> a -> a (-) :: Num a => a -> a -> a (*) :: Num a => a -> a -> a negate :: Num a => a -> a fromInt :: Num a => Int -> a -} sum :: Num a => [a] -> a sum = foldl' (+) (fromInt 0) product :: Num a => [a] -> a product = foldl' (*) (fromInt 1) {----------------------------------------------- -- Eq -----------------------------------------------} {- imported from PreludePrim (==) :: Eq a => a -> a -> Bool (/=) :: Eq a => a -> a -> Bool -} elem :: Eq a => a -> [a] -> Bool elem _ [] = False elem x (y:ys) | x == y = True | otherwise = elem x ys notElem :: Eq a => a -> [a] -> Bool notElem x ys = not (x `elem` ys) lookup :: Eq a => a -> [(a,b)] -> Maybe b lookup _ [] = Nothing lookup k ((x,y):xys) | k == x = Just y | otherwise = lookup k xys {----------------------------------------------- -- Ord -----------------------------------------------} {- imported from PreludePrim (<) :: Ord a => a -> a -> Bool (<=) :: Ord a => a -> a -> Bool (>) :: Ord a => a -> a -> Bool (>=) :: Ord a => a -> a -> Bool compare :: Ord a => a -> a -> Ordering -} max :: Ord a => a -> a -> a max x y = if x < y then y else x min :: Ord a => a -> a -> a min x y = if x < y then x else y maximum :: Ord a => [a] -> a maximum = foldl1 max minimum :: Ord a => [a] -> a minimum = foldl1 min {----------------------------------------------- -- Enum -----------------------------------------------} {- imported from PreludePrim succ :: Enum a => a -> a pred :: Enum a => a -> a enumFromTo :: Enum a => a -> a -> [a] enumFromThenTo :: Enum a => a -> a -> a -> [a] toEnum :: Enum a => Int -> a fromEnum :: Enum a => a -> Int enumFrom :: Enum a => a -> [a] enumFromThen :: Enum a => a -> a -> [a] -} {----------------------------------------------- -- Int -----------------------------------------------} class Ord a => Num a where (+) :: a -> a -> a (-) :: a -> a -> a (*) :: a -> a -> a negate :: a -> a abs :: a -> a signum :: a -> a fromInt :: Integer -> a infixl 6 +, - infixl 7 * val = 2 + 3 * 4 {- imported from PreludePrim rem :: Int -> Int -> Int div :: Int -> Int -> Int mod :: Int -> Int -> Int quot :: Int -> Int -> Int -} -- for compatibility with Haskell textbooks type Integer = Int even :: Int -> Bool even n = (n `rem` 2) == 0 odd :: Int -> Bool odd n = not (even n) subtract :: Int -> Int -> Int subtract a b = b - a gcd :: Int -> Int -> Int gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined" gcd x y = gcd' (abs x) (abs y) where gcd' :: Int -> Int -> Int gcd' x' 0 = x' gcd' x' y' = gcd' y' (x' `rem` y') lcm :: Int -> Int -> Int lcm _ 0 = 0 lcm 0 _ = 0 lcm x y = abs ((x `quot` gcd x y) * y) (^) :: Num a => a -> Int -> a _ ^ 0 = fromInt 1 i ^ n | n > 0 = f i (n-1) i | otherwise = error "Prelude.^: negative exponent" where f _ 0 y = y f x m y = g x m where g x' m' | even m' = g (x' * x') (m' `quot` 2) | otherwise = f x' (m' - 1) (x' * y) instance Eq Int where (==) = (==#) instance Ord Int where (<) = (<#) (>) = (>#) (<=) = (<=#) (>=) = (>=#) instance Num Int where (+) = (+#) (-) = (-#) (*) = (*#) negate = negInt fromInt = id abs n = if n < 0 then negate n else n {----------------------------------------------- -- Float -----------------------------------------------} {- imported from PreludePrim (/) :: Float -> Float -> Float sqrt :: Float -> Float (**.) :: Float -> Float -> Float exp :: Float -> Float log :: Float -> Float sin :: Float -> Float cos :: Float -> Float tan :: Float -> Float -} absFloat :: Float -> Float absFloat x = if x < 0.0 then (-. x) else x signumFloat :: Float -> Int signumFloat x = case compare x 0.0 of LT -> -1 EQ -> 0 GT -> 1 pi :: Float pi = 3.141592653589793 instance Eq Float where (==) = (==.) instance Ord Float where (<) = (<.) (>) = (>.) (<=) = (<=.) (>=) = (>=.) instance Num Float where (+) = (+.) (-) = (-.) (*) = (*.) negate = negFloat abs n = if n < 0.0 then negate n else n {----------------------------------------------- -- Bool -----------------------------------------------} not :: Bool -> Bool not False = True not _ = False (||) :: Bool -> Bool -> Bool (&&) :: Bool -> Bool -> Bool x || y = if x then x else y x && y = if x then y else x otherwise :: Bool otherwise = True {----------------------------------------------- -- Maybe -----------------------------------------------} data Maybe a = Nothing | Just a maybe :: b -> (a -> b) -> Maybe a -> b maybe e f m = case m of Nothing -> e Just x -> f x {----------------------------------------------- -- Either -----------------------------------------------} data Either a b = Left a | Right b either :: (a -> c) -> (b -> c) -> Either a b -> c either l r e = case e of Left x -> l x Right y -> r y {----------------------------------------------- -- Ordering -----------------------------------------------} {- imported from PreludePrim data Ordering = LT | EQ | GT -} {----------------------------------------------- -- Tuple -----------------------------------------------} fst :: (a, b) -> a fst (x, _) = x snd :: (a, b) -> b snd (_, x) = x curry :: ((a,b) -> c) -> (a -> b -> c) curry f x y = f (x,y) uncurry :: (a -> b -> c) -> ((a,b) -> c) uncurry f p = f (fst p) (snd p) zip :: [a] -> [b] -> [(a,b)] zip = zipWith (\a b -> (a,b)) zip3 :: [a] -> [b] -> [c] -> [(a,b,c)] zip3 = zipWith3 (\a b c -> (a,b,c)) zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith z (a:as) (b:bs) = z a b : zipWith z as bs 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 :: [(a,b)] -> ([a],[b]) unzip = foldr (\(a,b) (as,bs) -> (a:as, b:bs)) ([], []) unzip3:: [(a,b,c)] -> ([a],[b],[c]) unzip3 = foldr (\(a,b,c) (as,bs,cs) -> (a:as,b:bs,c:cs)) ([],[],[]) {----------------------------------------------- -- List -----------------------------------------------} -- We can't import Char here because that would mean we couldn't import -- it elsewhere. Therefore, we make local copies of the two functions -- from that module localIsSpace :: Char -> Bool localIsSpace c = i == primOrd ' ' || i == primOrd '\t' || i == primOrd '\n' || i == primOrd '\r' || i == primOrd '\f' || i == primOrd '\v' where i = primOrd c localIsDigit :: Char -> Bool localIsDigit c = primOrd c >= primOrd '0' && primOrd c <= primOrd '9' {----------------------------------------------- -- List -----------------------------------------------} head :: [a] -> a head (x:_) = x head _ = error "Prelude.head: empty list" last :: [a] -> a last [x] = x last (_:xs) = last xs last _ = error "Prelude.last: empty list" tail :: [a] -> [a] tail (_:xs) = xs tail _ = error "Prelude.tail: empty list" init :: [a] -> [a] init [_] = [] init (x:xs) = x : init xs init _ = error "Prelude.init: empty list" null :: [a] -> Bool null [] = True null _ = False (++) :: [a] -> [a] -> [a] (x:xs) ++ ys = x : (xs ++ ys) [] ++ ys = ys map :: (a -> b) -> [a] -> [b] map _ [] = [] map f (x:xs) = f x : map f xs filter :: (a -> Bool) -> [a] -> [a] filter p (x:xs) | p x = x : filter p xs | otherwise = filter p xs filter _ [] = [] {- Naive implementation of length (slow because of laziness) length :: [a] -> Int length [] = 0 length (_:xs) = 1 + length xs Optimised implementation using strict foldl: -} length :: [a] -> Int length xs = foldl' (\l _ -> l + 1) 0 xs concat :: [[a]] -> [a] concat = foldr (++) [] (!!) :: [a] -> Int -> a xs !! n | n < 0 = error "Prelude.(!!): negative index" | null xs = error "Prelude.(!!): index too large" | n == 0 = head xs | otherwise = tail xs !! (n - 1) foldl :: (a -> b -> a) -> a -> [b] -> a foldl _ z [] = z foldl f z (x:xs) = foldl f (f z x) xs foldl' :: (a -> b -> a) -> a -> [b] -> a foldl' _ a [] = a foldl' f a (x:xs) = (foldl' f $! f a x) xs foldl1 :: (a -> a -> a) -> [a] -> a foldl1 f (x:xs) = foldl f x xs foldl1 _ [] = error "Prelude.foldl1: empty list" scanl :: (a -> b -> a) -> a -> [b] -> [a] scanl f q xs = q : ( case xs of [] -> [] y:ys -> scanl f (f q y) ys ) scanl1 :: (a -> a -> a) -> [a] -> [a] scanl1 _ [] = [] scanl1 f (x:xs) = scanl f x xs foldr :: (a -> b -> b) -> b -> [a] -> b foldr _ z [] = z foldr f z (x:xs) = f x (foldr f z xs) foldr1 :: (a -> a -> a) -> [a] -> a foldr1 _ [x] = x foldr1 f (x:xs) = f x (foldr1 f xs) foldr1 _ [] = error "Prelude.foldr1: empty list" scanr :: (a -> b -> b) -> b -> [a] -> [b] scanr _ q0 [] = [q0] scanr f q0 (x:xs) = case scanr f q0 xs of qs@(q:_) -> f x q : qs _ -> error "Prelude.scanr" scanr1 :: (a -> a -> a) -> [a] -> [a] scanr1 _ [] = [] scanr1 _ [x] = [x] scanr1 f (x:xs) = case scanr1 f xs of qs@(q:_) -> f x q : qs _ -> error "Prelude.scanr" iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) repeat :: a -> [a] repeat x = xs where xs = x:xs replicate :: Int -> a -> [a] replicate n x = take n (repeat x) cycle :: [a] -> [a] cycle [] = error "Prelude.cycle: empty list" cycle xs = xs' where xs'=xs++xs' take :: Int -> [a] -> [a] take n xs | n <= 0 = [] | otherwise = case xs of [] -> [] (y:ys) -> y : take (n-1) ys drop :: Int -> [a] -> [a] drop n xs | n <= 0 = xs | otherwise = case xs of [] -> [] (_:ys) -> drop (n-1) ys splitAt :: Int -> [a] -> ([a], [a]) splitAt n xs | n <= 0 = ([],xs) | otherwise = case xs of [] -> ([],[]) (y:ys) -> (y:as,bs) where (as,bs) = splitAt (n-1) ys takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile _ [] = [] takeWhile p (x:xs) | p x = x : takeWhile p xs | otherwise = [] dropWhile :: (a -> Bool) -> [a] -> [a] dropWhile _ [] = [] dropWhile p l@(x:xs) | p x = dropWhile p xs | otherwise = l span :: (a -> Bool) -> [a] -> ([a],[a]) span _ [] = ([],[]) span p xs@(x:xs') | p x = (x:ys, zs) | otherwise = ([],xs) where (ys,zs) = span p xs' break :: (a -> Bool) -> [a] -> ([a],[a]) break p = span (not . p) lines :: String -> [String] lines "" = [] lines s = let l,s' :: String (l,s') = break (\x -> x == '\n') s in l : case s' of [] -> [] (_:s'') -> lines s'' words :: String -> [String] words s = case dropWhile localIsSpace s of "" -> [] s' -> w : words s'' where w,s'' :: String (w,s'') = break localIsSpace s' unlines :: [String] -> String unlines [] = [] unlines (l:ls) = l ++ '\n' : unlines ls unwords :: [String] -> String unwords [] = "" unwords [w] = w unwords (w:ws) = w ++ ' ' : unwords ws reverse :: [a] -> [a] reverse = foldl (flip (:)) [] and :: [Bool] -> Bool and = foldr (&&) True or :: [Bool] -> Bool or = foldr (||) False any :: (a -> Bool) -> [a] -> Bool any p = or . map p all :: (a -> Bool) -> [a] -> Bool all p = and . map p concatMap :: (a -> [b]) -> [a] -> [b] concatMap f = concat . map f {----------------------------------------------- -- Conversion -----------------------------------------------} -- see also "read.." and "show.." below {- imported from PreludePrim primOrd :: Char -> Int primChr :: Int -> Char intToFloat :: Int -> Float round :: Float -> Int floor :: Float -> Int ceiling :: Float -> Int truncate :: Float -> Int -} instance Eq Char where c1 == c2 = primOrd c1 ==# primOrd c2 type ShowS = String -> String intercalate :: [a] -> [[a]] -> [a] intercalate _ [] = [] intercalate _ [x] = x intercalate y (x:xs) = x ++ y ++ intercalate y xs {----------------------------------------------- -- Some standard functions -----------------------------------------------} fix :: (a -> a) -> a fix f = x where x = f x id :: a -> a id x = x const :: a -> b -> a const x _ = x (.) :: (b -> c) -> (a -> b) -> (a -> c) (.) f g x = f (g x) flip :: (a -> b -> c) -> b -> a -> c flip f x y = f y x ($) :: (a -> b) -> a -> b f $ x = f x {- imported from PreludePrim seq :: a -> b -> b ($!) :: (a -> b) -> a -> b error :: String -> a -} until :: (a -> Bool) -> (a -> a) -> a -> a until p f x = if p x then x else until p f (f x) undefined :: a undefined = error "undefined" {----------------------------------------------- -- IO -----------------------------------------------} {- putChar :: Char -> IO () putChar c = primPutChar c putStr :: String -> IO () putStr s = primPutStr s putStrLn :: String -> IO () putStrLn s = primPutStrLn s unsafePerformIO :: IO a -> a unsafePerformIO = primUnsafePerformIO -} getLine :: IO String getLine = do c <- getChar if c == '\n' then return "" else getLine >>= (return . (c :)) sequence_ :: [IO a] -> IO () sequence_ = foldr (>>) (return ()) print :: Show a => a -> IO () print e = putStrLn (show e) writeFile :: String -> String -> IO () writeFile fname s = bracketIO (openFile fname WriteMode) (hClose) (\h -> hPutString h s) readFile :: String -> IO String readFile fname = bracketIO (openFile fname ReadMode) (hClose) (\h -> readAll h []) where readAll h acc = do c <- hGetChar h readAll h (c:acc) `catchEof` (return (reverse acc)) bracketIO :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c bracketIO acquire release action = do x <- acquire finallyIO (action x) (release x) finallyIO :: IO a -> IO b -> IO a finallyIO io action = do x <- io `catch` (\exn -> do{ action; raise exn }) action return x {----------------------------------------------- -- Read -----------------------------------------------} readInt :: String -> Int readInt [] = 0 readInt ('-':s) = - readUnsigned s readInt s = readUnsigned s readUnsigned :: String -> Int readUnsigned = foldl (\a b -> a * 10 + b) 0 . map (\c -> primOrd c - primOrd '0') . takeWhile localIsDigit -- Functor -- (<$>) :: Functor f => (a -> b) -> f a -> f b (<$>) = fmap class Functor f where fmap :: (a -> b) -> f a -> f b instance Functor Maybe where fmap f Nothing = Nothing fmap f (Just x) = Just (f x) instance Functor (Either a) where fmap _ (Left x) = Left x fmap f (Right y) = Right (f y) instance Functor [] where fmap = map instance Functor IO where fmap = fmapIO -- Applicative -- class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b instance Applicative Maybe where pure = Just (<*>) (Just f) (Just x) = Just (f x) (<*>) _ _ = Nothing instance Applicative (Either a) where pure = Right (<*>) (Left e) x = Left e (<*>) (Right f) r = fmap f r instance Applicative IO where pure = pureIO (<*>) = apIO -- Monad -- class Applicative m => Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return = pure m >> k = m >>= (\_ -> k) instance Monad IO where return = returnIO (>>=) = bindIO instance Monad Maybe where return = Just (>>=) Nothing f = Nothing (>>=) (Just x) f = f x class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool (==) x y = not (x /= y) (/=) x y = not ( x == y) instance Eq Bool where (==) True True = True (==) False False = True (==) _ _ = False instance Eq a => Eq (Maybe a) where (==) Nothing Nothing = True (==) (Just x) (Just y) = x == y (==) _ _ = False instance (Eq a, Eq b) => Eq (Either a b) where (==) (Left x) (Left y) = x == y (==) (Right x) (Right y) = x == y (==) _ _ = False instance Eq a => Eq [a] where (==) [] [] = True (==) (x:xs) (y:ys) = x == y && xs == ys (==) _ _ = False instance Eq () where () == () = True instance (Eq a, Eq b) => Eq (a, b) where (x1, y1) == (x2, y2) = x1 == x2 && y1 == y2 instance (Eq a, Eq b, Eq c) => Eq (a, b, c) where (x1, y1, z1) == (x2, y2, z2) = x1 == x2 && y1 == y2 && z1 == z2 instance (Eq a, Eq b, Eq c, Eq d) => Eq (a, b, c, d) where (x1, y1, z1, a1) == (x2, y2, z2, a2) = x1 == x2 && y1 == y2 && z1 == z2 && a1 == a2 instance (Eq a, Eq b, Eq c, Eq d, Eq e) => Eq (a, b, c, d, e) where (x1, y1, z1, a1, b1) == (x2, y2, z2, a2, b2) = x1 == x2 && y1 == y2 && z1 == z2 && a1 == a2 && b1 == b2 instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => Eq (a, b, c, d, e, f) where (x1, y1, z1, a1, b1, c1) == (x2, y2, z2, a2, b2, c2) = x1 == x2 && y1 == y2 && z1 == z2 && a1 == a2 && b1 == b2 && c1 == c2 instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g) => Eq (a, b, c, d, e, f, g) where (x1, y1, z1, a1, b1, c1, d1) == (x2, y2, z2, a2, b2, c2, d2) = x1 == x2 && y1 == y2 && z1 == z2 && a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h) => Eq (a, b, c, d, e, f, g, h) where (x1, y1, z1, a1, b1, c1, d1, e1) == (x2, y2, z2, a2, b2, c2, d2, e2) = x1 == x2 && y1 == y2 && z1 == z2 && a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i) => Eq (a, b, c, d, e, f, g, h, i) where (x1, y1, z1, a1, b1, c1, d1, e1, f1) == (x2, y2, z2, a2, b2, c2, d2, e2, f2) = x1 == x2 && y1 == y2 && z1 == z2 && a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j) => Eq (a, b, c, d, e, f, g, h, i, j) where (x1, y1, z1, a1, b1, c1, d1, e1, f1, g1) == (x2, y2, z2, a2, b2, c2, d2, e2, f2, g2) = x1 == x2 && y1 == y2 && z1 == z2 && a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 && e1 == e2 && f1 == f2 && g1 == g2 class Eq a => Ord a where (<) :: a -> a -> Bool (<=) :: a -> a -> Bool (>) :: a -> a -> Bool (>=) :: a -> a -> Bool compare :: a -> a -> Ordering (<) x y = x <= y && x /= y (>) x y = x >= y && x /= y (<=) x y = not (x > y) (>=) x y = not (x < y) compare x y | x == y = EQ | x < y = LT | x > y = GT instance Ord a => Ord [a] where [] < [] = False [] < (_:_) = True (x:xs) < (y:ys) | x == y = xs < ys | otherwise = x < y (x:xs) < [] = False instance (Ord a, Ord b) => Ord (a, b) where (x1, y1) < (x2, y2) | x1 /= x2 = x1 < x2 | otherwise = y1 < y2 instance (Ord a, Ord b, Ord c) => Ord (a, b, c) where (x1, y1, z1) < (x2, y2, z2) | x1 /= x2 = x1 < x2 | otherwise = (y1, z1) < (y2, z2) instance (Ord a, Ord b, Ord c, Ord d) => Ord (a, b, c, d) where (x1, y1, z1, a1) < (x2, y2, z2, a2) | x1 /= x2 = x1 < x2 | otherwise = (y1, z1, a1) < (y2, z2, a2) instance (Ord a, Ord b, Ord c, Ord d, Ord e) => Ord (a, b, c, d, e) where (x1, y1, z1, a1, b1) < (x2, y2, z2, a2, b2) | x1 /= x2 = x1 < x2 | otherwise = (y1, z1, a1, b1) < (y2, z2, a2, b2) instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f) => Ord (a, b, c, d, e, f) where (x1, y1, z1, a1, b1, c1) < (x2, y2, z2, a2, b2, c2) | x1 /= x2 = x1 < x2 | otherwise = (y1, z1, a1, b1, c1) < (y2, z2, a2, b2, c2) instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g) => Ord (a, b, c, d, e, f, g) where (x1, y1, z1, a1, b1, c1, d1) < (x2, y2, z2, a2, b2, c2, d2) | x1 /= x2 = x1 < x2 | otherwise = (y1, z1, a1, b1, c1, d1) < (y2, z2, a2, b2, c2, d2) instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h) => Ord (a, b, c, d, e, f, g, h) where (x1, y1, z1, a1, b1, c1, d1, e1) < (x2, y2, z2, a2, b2, c2, d2, e2) | x1 /= x2 = x1 < x2 | otherwise = (y1, z1, a1, b1, c1, d1, e1) < (y2, z2, a2, b2, c2, d2, e2) instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i) => Ord (a, b, c, d, e, f, g, h, i) where (x1, y1, z1, a1, b1, c1, d1, e1, f1) < (x2, y2, z2, a2, b2, c2, d2, e2, f2) | x1 /= x2 = x1 < x2 | otherwise = (y1, z1, a1, b1, c1, d1, e1, f1) < (y2, z2, a2, b2, c2, d2, e2, f2) instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j) => Ord (a, b, c, d, e, f, g, h, i, j) where (x1, y1, z1, a1, b1, c1, d1, e1, f1, g1) < (x2, y2, z2, a2, b2, c2, d2, e2, f2, g2) | x1 /= x2 = x1 < x2 | otherwise = (y1, z1, a1, b1, c1, d1, e1, f1, g1) < (y2, z2, a2, b2, c2, d2, e2, f2, g2) instance Ord Char where c1 < c2 = primOrd c1 < primOrd c2 c1 > c2 = primOrd c1 > primOrd c2 instance Ord Bool where False < False = False False < True = True True < False = False True < True = False False > False = False False > True = False True > False = True True > True = False instance Ord () where () < () = False shows :: Show a => a -> ShowS shows = showsPrec 0 class Show a where show :: a -> String showList :: [a] -> ShowS showsPrec :: Int -> a -> ShowS showList ls s = "[" ++ intercalate "," (map (flip shows s) ls) ++ "]" showsPrec _ x s = show x ++ s show x = shows x "" instance Show Int where show = showInt instance Show Bool where show True = "True" show False = "False" instance Show Float where show = showFloat instance Show () where show () = "()" instance Show Ordering where show LT = "LT" show GT = "GT" show EQ = "EQ" instance Show Char where show = showChar showList ls s = "\"" ++ concatMap escapeChar ls ++ "\"" ++ s escapeChar :: Char -> String escapeChar '\\' = "\\" escapeChar '"' = "\"" escapeChar c = [c] instance (Show a, Show b) => Show (Either a b) where show (Left x) = "Left " ++ show x show (Right x) = "Right " ++ show x instance Show a => Show (Maybe a) where show Nothing = "Nothing" show (Just x) = "Just " ++ show x instance (Show a, Show b) => Show (a, b) where show (x, y) = "(" ++ show x ++ "," ++ show y ++ ")" instance (Show a, Show b, Show c) => Show (a, b, c) where show (x, y, z) = "(" ++ show x ++ "," ++ show y ++ "," ++ show z ++ ")" instance (Show a, Show b, Show c, Show d) => Show (a, b, c, d) where show (a, b, c, d) = "(" ++ show a ++ "," ++ show b ++ "," ++ show c ++ "," ++ show d ++ ")" instance (Show a, Show b, Show c, Show d, Show e) => Show (a, b, c, d, e) where show (a, b, c, d, e) = "(" ++ show a ++ "," ++ show b ++ "," ++ show c ++ "," ++ show d ++ "," ++ show e ++ ")" instance (Show a, Show b, Show c, Show d, Show e, Show f) => Show (a, b, c, d, e, f) where show (a, b, c, d, e, f) = "(" ++ show a ++ "," ++ show b ++ "," ++ show c ++ "," ++ show d ++ "," ++ show e ++ "," ++ show f ++ ")" instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g) => Show (a, b, c, d, e, f, g) where show (a, b, c, d, e, f, g) = "(" ++ show a ++ "," ++ show b ++ "," ++ show c ++ "," ++ show d ++ "," ++ show e ++ "," ++ show f ++ "," ++ show g ++ ")" 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 show (a, b, c, d, e, f, g, h) = "(" ++ show a ++ "," ++ show b ++ "," ++ show c ++ "," ++ show d ++ "," ++ show e ++ "," ++ show f ++ "," ++ show g ++ "," ++ show h ++ ")" 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 show (a, b, c, d, e, f, g, h, i) = "(" ++ show a ++ "," ++ show b ++ "," ++ show c ++ "," ++ show d ++ "," ++ show e ++ "," ++ show f ++ "," ++ show g ++ "," ++ show h ++ "," ++ show i ++ ")" 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 show (a, b, c, d, e, f, g, h, i, j) = "(" ++ show a ++ "," ++ show b ++ "," ++ show c ++ "," ++ show d ++ "," ++ show e ++ "," ++ show f ++ "," ++ show g ++ "," ++ show h ++ "," ++ show i ++ "," ++ show j ++ ")" instance Show a => Show [a] where show ls = showList ls "" -- Enum class Enum a where succ, pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int enumFrom :: a -> [a] enumFromThen :: a -> a -> [a] enumFromTo :: a -> a -> [a] enumFromThenTo :: a -> a -> a -> [a] enumFromTo x y = map toEnum [fromEnum x .. fromEnum y] enumFromThenTo x y z = map toEnum [fromEnum x, fromEnum y .. fromEnum z] instance Enum Int where succ = enumSuccInt pred = enumPredInt toEnum = id fromEnum = id enumFrom = enumFromInt enumFromThen = enumFromThenInt enumFromTo = enumFromToInt enumFromThenTo = enumFromThenToInt instance Enum Float where succ = enumSuccFloat pred = enumPredFloat toEnum = toEnumFloat fromEnum = truncate enumFrom = enumFromFloat enumFromThen = enumFromThenFloat enumFromTo = enumFromToFloat enumFromThenTo = enumFromThenToFloat instance Enum () where succ = error "There is no successor for ()" pred = error "There is no predecessor for ()" fromEnum = fromEnumVoid toEnum = toEnumVoid enumFrom = enumFromVoid enumFromThen = enumFromThenVoid enumFromTo _ _ = [()] enumFromThenTo _ _ _ = repeat () instance Enum Bool where succ False = True succ _ = error "There is no successor for False" pred True = False pred _ = error "There is no predecessor for True" toEnum = toEnumBool fromEnum = fromEnumBool enumFrom = enumFromBool enumFromThen = enumFromThen instance Enum Char where --primChr primOrd enumFromChar enumFromThenChar succ c = primChr (primOrd c + 1) pred c = primChr (primOrd c - 1) toEnum = primChr fromEnum = primOrd enumFrom = enumFromChar enumFromThen = enumFromThenChar
Helium4Haskell/helium
lib/Prelude.hs
gpl-3.0
27,837
0
26
9,144
13,068
7,028
6,040
632
3
{-# LANGUAGE MultiParamTypeClasses #-} module While.Concrete where import Abstat.Interface.State hiding (State) import Abstat.Interface.Semantics import Abstat.Common.ConcreteState import While.AST type Domain = Integer interpretAExpr :: AExpr -> State Domain -> Domain interpretAExpr expr state = case expr of (Var var) -> load var state (IntConst num) -> num (AUnary Neg a) -> negate (interpretAExpr a state) (ABinary Add a b) -> interpretAExpr a state + interpretAExpr b state (ABinary Subtract a b) -> interpretAExpr a state - interpretAExpr b state (ABinary Multiply a b) -> interpretAExpr a state * interpretAExpr b state (ABinary Divide a b) -> interpretAExpr a state `quot` interpretAExpr b state -- Postcondition: the root node of the resulting BExpr -- is one operation from Not, And, Less, Equal reduceBExpr :: BExpr -> BExpr reduceBExpr expr = case expr of (BBinary Or a b) -> BUnary Not $ BBinary And (BUnary Not a) (BUnary Not b) (RBinary NotEqual a b) -> BUnary Not $ RBinary Equal a b (RBinary GreaterEqual a b) -> BUnary Not $ RBinary Less a b (RBinary Greater a b) -> BBinary And (BUnary Not $ RBinary Less a b) (BUnary Not $ RBinary Equal a b) (RBinary LessEqual a b) -> BUnary Not $ BBinary And (BUnary Not $ RBinary Less a b) (BUnary Not $ RBinary Equal a b) _ -> expr interpretBExpr :: BExpr -> State Domain -> Bool interpretBExpr expr state = case expr of (BoolConst val) -> val (BUnary Not b) -> not (interpretBExpr b state) (BBinary And a b) | interpretBExpr a state -> interpretBExpr b state | interpretBExpr b state -> False | otherwise -> False BBinary{} -> interpretBExpr (reduceBExpr expr) state (RBinary Equal a b) -> interpretAExpr a state == interpretAExpr b state (RBinary Less a b) -> interpretAExpr a state < interpretAExpr b state RBinary{} -> interpretBExpr (reduceBExpr expr) state interpretStmt :: Stmt -> State Domain -> State Domain interpretStmt stmt state = case stmt of Skip -> state (Assign var aexpr) -> store var val state where val = interpretAExpr aexpr state (Seq stmt1 stmt2) -> interpretStmt stmt2 $ interpretStmt stmt1 state (If test thenStmt elseStmt) -> if interpretBExpr test state then interpretStmt thenStmt state else interpretStmt elseStmt state (While test bodyStmt) -> if interpretBExpr test state then interpretStmt stmt $ interpretStmt bodyStmt state else state instance Semantics Stmt State Integer where interpretState = interpretStmt
fpoli/abstat
src/While/Concrete.hs
gpl-3.0
2,725
0
12
713
921
449
472
64
7
{-# LANGUAGE CPP, PackageImports #-} #if __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Safe #-} #endif module Data.Word ( -- * Unsigned integral types -- $notes Word, Word8, Word16, Word32, Word64, ) where import "base" Data.Word -- SDM: removed after 'Prelude.fromIntegral': -- ..., which is specialized for all the common cases -- so should be fast enough -- SDM: removed: It would be very natural to add a type @Natural@ providing an -- unbounded size unsigned integer, just as 'Prelude.Integer' provides -- unbounded size signed integers. We do not do that yet since there is -- no demand for it. -- SDM: removed, after "All arithmetic is performed module 2^n...". Neither -- Ian Lynagh nor I understand what this means: -- One non-obvious consequence of this is that 'Prelude.negate' -- should /not/ raise an error on negative arguments. {- $notes This module provides unsigned integer types of unspecified width ('Word') and fixed widths ('Word8', 'Word16', 'Word32' and 'Word64'). 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'. Coercing word types to and from integer types preserves representation, not sign. The rules that hold for 'Prelude.Enum' instances over a bounded type such as 'Prelude.Int' (see the section of the Haskell language 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. -}
jwiegley/ghc-release
libraries/haskell2010/Data/Word.hs
gpl-3.0
1,844
0
4
348
48
38
10
5
0
module QFeldspar.NameMonad where import Prelude import Control.Monad.State hiding (mapM,sequence) type NamM m a = StateT Int m a newVar :: Monad m => NamM m String newVar = do i <- get put (i + 1) return ("v" ++ show i) runNamM :: Monad m => NamM m a -> m a runNamM = flip evalStateT 0
shayan-najd/QFeldspar
QFeldspar/NameMonad.hs
gpl-3.0
315
0
10
86
131
68
63
10
1
module PhoneNumber where import Control.Applicative import Text.Trifecta -- 4. Write a parser for US/Canada phone numbers with varying -- formats. -- Examples: -- "123-456-7890" -- "1234567890" -- "(123) 456-7890" -- "1-123-456-7890" -- aka area code type NumberingPlanArea = Int type Exchange = Int type LineNumber = Int data PhoneNumber = PhoneNumber NumberingPlanArea Exchange LineNumber deriving (Eq, Show) betweenBraces :: Parser a -> Parser a betweenBraces p = char '(' *> p <* char ')' areaCode :: Parser NumberingPlanArea areaCode = read <$> count 3 digit prefix :: Parser String prefix = string "1-" parseAreaCode :: Parser NumberingPlanArea parseAreaCode = token $ skipOptional prefix >> betweenBraces areaCode <|> areaCode parseExchange :: Parser Exchange parseExchange = token $ read <$> count 3 digit parseLineNumber :: Parser LineNumber parseLineNumber = read <$> count 4 digit parsePhone :: Parser PhoneNumber parsePhone = do areaCode <- parseAreaCode skipOptional (char '-') exchange <- parseExchange skipOptional (char '-') lineNumber <- parseLineNumber return $ PhoneNumber areaCode exchange lineNumber
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
ParserCombinators/src/PhoneNumber.hs
gpl-3.0
1,172
0
9
211
290
149
141
31
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.IAM.ListInstanceProfilesForRole -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists the instance profiles that have the specified associated role. If -- there are none, the action returns an empty list. For more information -- about instance profiles, go to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html About Instance Profiles>. -- -- You can paginate the results using the 'MaxItems' and 'Marker' -- parameters. -- -- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfilesForRole.html AWS API Reference> for ListInstanceProfilesForRole. -- -- This operation returns paginated results. module Network.AWS.IAM.ListInstanceProfilesForRole ( -- * Creating a Request listInstanceProfilesForRole , ListInstanceProfilesForRole -- * Request Lenses , lipfrMarker , lipfrMaxItems , lipfrRoleName -- * Destructuring the Response , listInstanceProfilesForRoleResponse , ListInstanceProfilesForRoleResponse -- * Response Lenses , lipfrrsMarker , lipfrrsIsTruncated , lipfrrsResponseStatus , lipfrrsInstanceProfiles ) where import Network.AWS.IAM.Types import Network.AWS.IAM.Types.Product import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'listInstanceProfilesForRole' smart constructor. data ListInstanceProfilesForRole = ListInstanceProfilesForRole' { _lipfrMarker :: !(Maybe Text) , _lipfrMaxItems :: !(Maybe Nat) , _lipfrRoleName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListInstanceProfilesForRole' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lipfrMarker' -- -- * 'lipfrMaxItems' -- -- * 'lipfrRoleName' listInstanceProfilesForRole :: Text -- ^ 'lipfrRoleName' -> ListInstanceProfilesForRole listInstanceProfilesForRole pRoleName_ = ListInstanceProfilesForRole' { _lipfrMarker = Nothing , _lipfrMaxItems = Nothing , _lipfrRoleName = pRoleName_ } -- | Use this parameter only when paginating results and only after you have -- received a response where the results are truncated. Set it to the value -- of the 'Marker' element in the response you just received. lipfrMarker :: Lens' ListInstanceProfilesForRole (Maybe Text) lipfrMarker = lens _lipfrMarker (\ s a -> s{_lipfrMarker = a}); -- | Use this only when paginating results to indicate the maximum number of -- items you want in the response. If there are additional items beyond the -- maximum you specify, the 'IsTruncated' response element is 'true'. -- -- This parameter is optional. If you do not include it, it defaults to -- 100. lipfrMaxItems :: Lens' ListInstanceProfilesForRole (Maybe Natural) lipfrMaxItems = lens _lipfrMaxItems (\ s a -> s{_lipfrMaxItems = a}) . mapping _Nat; -- | The name of the role to list instance profiles for. lipfrRoleName :: Lens' ListInstanceProfilesForRole Text lipfrRoleName = lens _lipfrRoleName (\ s a -> s{_lipfrRoleName = a}); instance AWSPager ListInstanceProfilesForRole where page rq rs | stop (rs ^. lipfrrsMarker) = Nothing | stop (rs ^. lipfrrsInstanceProfiles) = Nothing | otherwise = Just $ rq & lipfrMarker .~ rs ^. lipfrrsMarker instance AWSRequest ListInstanceProfilesForRole where type Rs ListInstanceProfilesForRole = ListInstanceProfilesForRoleResponse request = postQuery iAM response = receiveXMLWrapper "ListInstanceProfilesForRoleResult" (\ s h x -> ListInstanceProfilesForRoleResponse' <$> (x .@? "Marker") <*> (x .@? "IsTruncated") <*> (pure (fromEnum s)) <*> (x .@? "InstanceProfiles" .!@ mempty >>= parseXMLList "member")) instance ToHeaders ListInstanceProfilesForRole where toHeaders = const mempty instance ToPath ListInstanceProfilesForRole where toPath = const "/" instance ToQuery ListInstanceProfilesForRole where toQuery ListInstanceProfilesForRole'{..} = mconcat ["Action" =: ("ListInstanceProfilesForRole" :: ByteString), "Version" =: ("2010-05-08" :: ByteString), "Marker" =: _lipfrMarker, "MaxItems" =: _lipfrMaxItems, "RoleName" =: _lipfrRoleName] -- | Contains the response to a successful ListInstanceProfilesForRole -- request. -- -- /See:/ 'listInstanceProfilesForRoleResponse' smart constructor. data ListInstanceProfilesForRoleResponse = ListInstanceProfilesForRoleResponse' { _lipfrrsMarker :: !(Maybe Text) , _lipfrrsIsTruncated :: !(Maybe Bool) , _lipfrrsResponseStatus :: !Int , _lipfrrsInstanceProfiles :: ![InstanceProfile] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListInstanceProfilesForRoleResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lipfrrsMarker' -- -- * 'lipfrrsIsTruncated' -- -- * 'lipfrrsResponseStatus' -- -- * 'lipfrrsInstanceProfiles' listInstanceProfilesForRoleResponse :: Int -- ^ 'lipfrrsResponseStatus' -> ListInstanceProfilesForRoleResponse listInstanceProfilesForRoleResponse pResponseStatus_ = ListInstanceProfilesForRoleResponse' { _lipfrrsMarker = Nothing , _lipfrrsIsTruncated = Nothing , _lipfrrsResponseStatus = pResponseStatus_ , _lipfrrsInstanceProfiles = mempty } -- | When 'IsTruncated' is 'true', this element is present and contains the -- value to use for the 'Marker' parameter in a subsequent pagination -- request. lipfrrsMarker :: Lens' ListInstanceProfilesForRoleResponse (Maybe Text) lipfrrsMarker = lens _lipfrrsMarker (\ s a -> s{_lipfrrsMarker = a}); -- | A flag that indicates whether there are more items to return. If your -- results were truncated, you can make a subsequent pagination request -- using the 'Marker' request parameter to retrieve more items. lipfrrsIsTruncated :: Lens' ListInstanceProfilesForRoleResponse (Maybe Bool) lipfrrsIsTruncated = lens _lipfrrsIsTruncated (\ s a -> s{_lipfrrsIsTruncated = a}); -- | The response status code. lipfrrsResponseStatus :: Lens' ListInstanceProfilesForRoleResponse Int lipfrrsResponseStatus = lens _lipfrrsResponseStatus (\ s a -> s{_lipfrrsResponseStatus = a}); -- | A list of instance profiles. lipfrrsInstanceProfiles :: Lens' ListInstanceProfilesForRoleResponse [InstanceProfile] lipfrrsInstanceProfiles = lens _lipfrrsInstanceProfiles (\ s a -> s{_lipfrrsInstanceProfiles = a}) . _Coerce;
fmapfmapfmap/amazonka
amazonka-iam/gen/Network/AWS/IAM/ListInstanceProfilesForRole.hs
mpl-2.0
7,469
0
14
1,506
987
583
404
116
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.Glacier.SetVaultNotifications -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | This operation configures notifications that will be sent when specific -- events happen to a vault. By default, you don't get any notifications. -- -- To configure vault notifications, send a PUT request to the 'notification-configuration' subresource of the vault. The request should include a JSON document that -- provides an Amazon SNS topic and specific events for which you want Amazon -- Glacier to send notifications to the topic. -- -- Amazon SNS topics must grant permission to the vault to be allowed to -- publish notifications to the topic. You can configure a vault to publish a -- notification for the following vault events: -- -- ArchiveRetrievalCompleted This event occurs when a job that was initiated -- for an archive retrieval is completed ('InitiateJob'). The status of the -- completed job can be "Succeeded" or "Failed". The notification sent to the -- SNS topic is the same output as returned from 'DescribeJob'. InventoryRetrievalCompleted -- This event occurs when a job that was initiated for an inventory retrieval -- is completed ('InitiateJob'). The status of the completed job can be -- "Succeeded" or "Failed". The notification sent to the SNS topic is the same -- output as returned from 'DescribeJob'. An AWS account has full permission to -- perform all operations (actions). However, AWS Identity and Access Management -- (IAM) users don't have any permissions by default. You must grant them -- explicit permission to perform specific actions. For more information, see <http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html Access Control Using AWS Identity and Access Management (IAM)>. -- -- For conceptual information and underlying REST API, go to <http://docs.aws.amazon.com/amazonglacier/latest/dev/configuring-notifications.html Configuring VaultNotifications in Amazon Glacier> and <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-vault-notifications-put.html Set Vault Notification Configuration > in -- the /Amazon Glacier Developer Guide/. -- -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-SetVaultNotifications.html> module Network.AWS.Glacier.SetVaultNotifications ( -- * Request SetVaultNotifications -- ** Request constructor , setVaultNotifications -- ** Request lenses , svnAccountId , svnVaultName , svnVaultNotificationConfig -- * Response , SetVaultNotificationsResponse -- ** Response constructor , setVaultNotificationsResponse ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.RestJSON import Network.AWS.Glacier.Types import qualified GHC.Exts data SetVaultNotifications = SetVaultNotifications { _svnAccountId :: Text , _svnVaultName :: Text , _svnVaultNotificationConfig :: Maybe VaultNotificationConfig } deriving (Eq, Read, Show) -- | 'SetVaultNotifications' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'svnAccountId' @::@ 'Text' -- -- * 'svnVaultName' @::@ 'Text' -- -- * 'svnVaultNotificationConfig' @::@ 'Maybe' 'VaultNotificationConfig' -- setVaultNotifications :: Text -- ^ 'svnAccountId' -> Text -- ^ 'svnVaultName' -> SetVaultNotifications setVaultNotifications p1 p2 = SetVaultNotifications { _svnAccountId = p1 , _svnVaultName = p2 , _svnVaultNotificationConfig = Nothing } -- | The 'AccountId' is the AWS Account ID. You can specify either the AWS Account -- ID or optionally a '-', in which case Amazon Glacier uses the AWS Account ID -- associated with the credentials used to sign the request. If you specify your -- Account ID, do not include hyphens in it. svnAccountId :: Lens' SetVaultNotifications Text svnAccountId = lens _svnAccountId (\s a -> s { _svnAccountId = a }) -- | The name of the vault. svnVaultName :: Lens' SetVaultNotifications Text svnVaultName = lens _svnVaultName (\s a -> s { _svnVaultName = a }) -- | Provides options for specifying notification configuration. svnVaultNotificationConfig :: Lens' SetVaultNotifications (Maybe VaultNotificationConfig) svnVaultNotificationConfig = lens _svnVaultNotificationConfig (\s a -> s { _svnVaultNotificationConfig = a }) data SetVaultNotificationsResponse = SetVaultNotificationsResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'SetVaultNotificationsResponse' constructor. setVaultNotificationsResponse :: SetVaultNotificationsResponse setVaultNotificationsResponse = SetVaultNotificationsResponse instance ToPath SetVaultNotifications where toPath SetVaultNotifications{..} = mconcat [ "/" , toText _svnAccountId , "/vaults/" , toText _svnVaultName , "/notification-configuration" ] instance ToQuery SetVaultNotifications where toQuery = const mempty instance ToHeaders SetVaultNotifications instance ToJSON SetVaultNotifications where toJSON SetVaultNotifications{..} = object [ "vaultNotificationConfig" .= _svnVaultNotificationConfig ] instance AWSRequest SetVaultNotifications where type Sv SetVaultNotifications = Glacier type Rs SetVaultNotifications = SetVaultNotificationsResponse request = put response = nullResponse SetVaultNotificationsResponse
kim/amazonka
amazonka-glacier/gen/Network/AWS/Glacier/SetVaultNotifications.hs
mpl-2.0
6,413
0
9
1,238
528
329
199
66
1
module Model.User.Internal where import Prelude import Data.Text (Text) import Yesod.Markdown (Markdown) data UserUpdate = UserUpdate { userUpdateName :: Maybe Text , userUpdateAvatar :: Maybe Text , userUpdateIrcNick :: Maybe Text , userUpdateBlurb :: Maybe Markdown , userUpdateStatement :: Maybe Markdown -- , userUpdateNotificationPreferences :: [(NotificationType, NotificationDelivery)] }
Happy0/snowdrift
Model/User/Internal.hs
agpl-3.0
519
0
9
171
85
50
35
11
0
module StartingOut ( doubleMe, doubleUs, doubleSmallNumber, listComprehension ) where doubleMe x = x + x doubleUs x y = doubleMe x + doubleMe y doubleSmallNumber x = if x > 100 then x else x*2 -- We usually use ' to either denote a strict version of a function (one that isn't lazy) or a slightly modified version of a function or a variable doubleSmallNumber' x = (if x > 100 then x else x*2) + 1 -- functions can't begin with uppercase letters -- When a function doesn't take any parameters, we usually say it's a definition (or a name) conanO'Brien = "It's a-me, Conan O'Brien!" -- a list comprehension is composed of: one output function, at least one list-drawing-function, and any number of predicates listComprehension = [ x*y | x <- [2,5,10], y <- [8,10,11], x*y > 50, x+y > 20] nouns = ["hobo","frog","pope"] adjectives = ["lazy","grouchy","scheming"] adjectiveNoun = [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns] removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']] triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ] rightTriangle a b c = a^2 + b^2 == c^2 rightTriangles = [ (a, b, c) | (a, b, c) <- triangles, rightTriangle a b c ]
mboogerd/hello-haskell
src/lyah/StartingOut.hs
apache-2.0
1,254
0
9
284
411
231
180
20
2
-- 1234567890 -- oooxoxoooo dec2oct 0 = [] dec2oct n = let a = n `mod` 8 b = n `div` 8 in a:(dec2oct b) oct2ans s [] = s oct2ans s (n:ns) = let n' = if n <= 3 then n else if n <= 4 then n + 1 else n + 2 s' = s * 10 + n' in oct2ans s' ns ans i = let t = reverse $ dec2oct i in oct2ans 0 t main = do c <- getContents let i = takeWhile (/= 0) $ map read $ lines c :: [Int] o = map ans i mapM_ print o
a143753/AOJ
0208.hs
apache-2.0
507
0
13
218
246
125
121
22
3
{-# LANGUAGE BangPatterns, FlexibleContexts #-} -- | -- Module : Statistics.Transform -- Copyright : (c) 2011 Bryan O'Sullivan -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Fourier-related transformations of mathematical functions. -- -- These functions are written for simplicity and correctness, not -- speed. If you need a fast FFT implementation for your application, -- you should strongly consider using a library of FFTW bindings -- instead. module Statistics.Transform ( -- * Type synonyms CD -- * Discrete cosine transform , dct , dct_ , idct , idct_ -- * Fast Fourier transform , fft , ifft ) where import Control.Monad (when) import Control.Monad.ST (ST) import Data.Bits (shiftL, shiftR) import Data.Complex (Complex(..), conjugate, realPart) import Numeric.SpecFunctions (log2) import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as M import qualified Data.Vector.Unboxed as U type CD = Complex Double -- | Discrete cosine transform (DCT-II). dct :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v Double -> v Double dct = dctWorker . G.map (:+0) -- | Discrete cosine transform (DCT-II). Only real part of vector is -- transformed, imaginary part is ignored. dct_ :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v CD -> v Double dct_ = dctWorker . G.map (\(i :+ _) -> i :+ 0) dctWorker :: (G.Vector v CD, G.Vector v Double, G.Vector v Int) => v CD -> v Double dctWorker xs -- length 1 is special cased because shuffle algorithms fail for it. | G.length xs == 1 = G.map ((2*) . realPart) xs | vectorOK xs = G.map realPart $ G.zipWith (*) weights (fft interleaved) | otherwise = error "Statistics.Transform.dct: bad vector length" where interleaved = G.backpermute xs $ G.enumFromThenTo 0 2 (len-2) G.++ G.enumFromThenTo (len-1) (len-3) 1 weights = G.cons 2 . G.generate (len-1) $ \x -> 2 * exp ((0:+(-1))*fi (x+1)*pi/(2*n)) where n = fi len len = G.length xs -- | Inverse discrete cosine transform (DCT-III). It's inverse of -- 'dct' only up to scale parameter: -- -- > (idct . dct) x = (* length x) idct :: (G.Vector v CD, G.Vector v Double) => v Double -> v Double idct = idctWorker . G.map (:+0) -- | Inverse discrete cosine transform (DCT-III). Only real part of vector is -- transformed, imaginary part is ignored. idct_ :: U.Vector CD -> U.Vector Double idct_ = idctWorker . G.map (\(i :+ _) -> i :+ 0) idctWorker :: (G.Vector v CD, G.Vector v Double) => v CD -> v Double idctWorker xs | vectorOK xs = G.generate len interleave | otherwise = error "Statistics.Transform.dct: bad vector length" where interleave z | even z = vals `G.unsafeIndex` halve z | otherwise = vals `G.unsafeIndex` (len - halve z - 1) vals = G.map realPart . ifft $ G.zipWith (*) weights xs weights = G.cons n $ G.generate (len - 1) $ \x -> 2 * n * exp ((0:+1) * fi (x+1) * pi/(2*n)) where n = fi len len = G.length xs -- | Inverse fast Fourier transform. ifft :: G.Vector v CD => v CD -> v CD ifft xs | vectorOK xs = G.map ((/fi (G.length xs)) . conjugate) . fft . G.map conjugate $ xs | otherwise = error "Statistics.Transform.ifft: bad vector length" -- | Radix-2 decimation-in-time fast Fourier transform. fft :: G.Vector v CD => v CD -> v CD fft v | vectorOK v = G.create $ do mv <- G.thaw v mfft mv return mv | otherwise = error "Statistics.Transform.fft: bad vector length" -- Vector length must be power of two. It's not checked mfft :: (M.MVector v CD) => v s CD -> ST s () mfft vec = bitReverse 0 0 where bitReverse i j | i == len-1 = stage 0 1 | otherwise = do when (i < j) $ M.swap vec i j let inner k l | k <= l = inner (k `shiftR` 1) (l-k) | otherwise = bitReverse (i+1) (l+k) inner (len `shiftR` 1) j stage l !l1 | l == m = return () | otherwise = do let !l2 = l1 `shiftL` 1 !e = -6.283185307179586/fromIntegral l2 flight j !a | j == l1 = stage (l+1) l2 | otherwise = do let butterfly i | i >= len = flight (j+1) (a+e) | otherwise = do let i1 = i + l1 xi1 :+ yi1 <- M.read vec i1 let !c = cos a !s = sin a d = (c*xi1 - s*yi1) :+ (s*xi1 + c*yi1) ci <- M.read vec i M.write vec i1 (ci - d) M.write vec i (ci + d) butterfly (i+l2) butterfly j flight 0 0 len = M.length vec m = log2 len fi :: Int -> CD fi = fromIntegral halve :: Int -> Int halve = (`shiftR` 1) vectorOK :: G.Vector v a => v a -> Bool {-# INLINE vectorOK #-} vectorOK v = (1 `shiftL` log2 n) == n where n = G.length v
fpco/statistics
Statistics/Transform.hs
bsd-2-clause
5,058
0
29
1,485
1,824
928
896
95
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QCalendarWidget.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:35 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QCalendarWidget ( HorizontalHeaderFormat, eNoHorizontalHeader, eSingleLetterDayNames, eShortDayNames, eLongDayNames , VerticalHeaderFormat, eNoVerticalHeader, eISOWeekNumbers , QCalendarWidgetSelectionMode ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CHorizontalHeaderFormat a = CHorizontalHeaderFormat a type HorizontalHeaderFormat = QEnum(CHorizontalHeaderFormat Int) ieHorizontalHeaderFormat :: Int -> HorizontalHeaderFormat ieHorizontalHeaderFormat x = QEnum (CHorizontalHeaderFormat x) instance QEnumC (CHorizontalHeaderFormat Int) where qEnum_toInt (QEnum (CHorizontalHeaderFormat x)) = x qEnum_fromInt x = QEnum (CHorizontalHeaderFormat x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> HorizontalHeaderFormat -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eNoHorizontalHeader :: HorizontalHeaderFormat eNoHorizontalHeader = ieHorizontalHeaderFormat $ 0 eSingleLetterDayNames :: HorizontalHeaderFormat eSingleLetterDayNames = ieHorizontalHeaderFormat $ 1 eShortDayNames :: HorizontalHeaderFormat eShortDayNames = ieHorizontalHeaderFormat $ 2 eLongDayNames :: HorizontalHeaderFormat eLongDayNames = ieHorizontalHeaderFormat $ 3 data CVerticalHeaderFormat a = CVerticalHeaderFormat a type VerticalHeaderFormat = QEnum(CVerticalHeaderFormat Int) ieVerticalHeaderFormat :: Int -> VerticalHeaderFormat ieVerticalHeaderFormat x = QEnum (CVerticalHeaderFormat x) instance QEnumC (CVerticalHeaderFormat Int) where qEnum_toInt (QEnum (CVerticalHeaderFormat x)) = x qEnum_fromInt x = QEnum (CVerticalHeaderFormat x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> VerticalHeaderFormat -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () eNoVerticalHeader :: VerticalHeaderFormat eNoVerticalHeader = ieVerticalHeaderFormat $ 0 eISOWeekNumbers :: VerticalHeaderFormat eISOWeekNumbers = ieVerticalHeaderFormat $ 1 data CQCalendarWidgetSelectionMode a = CQCalendarWidgetSelectionMode a type QCalendarWidgetSelectionMode = QEnum(CQCalendarWidgetSelectionMode Int) ieQCalendarWidgetSelectionMode :: Int -> QCalendarWidgetSelectionMode ieQCalendarWidgetSelectionMode x = QEnum (CQCalendarWidgetSelectionMode x) instance QEnumC (CQCalendarWidgetSelectionMode Int) where qEnum_toInt (QEnum (CQCalendarWidgetSelectionMode x)) = x qEnum_fromInt x = QEnum (CQCalendarWidgetSelectionMode x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> QCalendarWidgetSelectionMode -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () instance QeNoSelection QCalendarWidgetSelectionMode where eNoSelection = ieQCalendarWidgetSelectionMode $ 0 instance QeSingleSelection QCalendarWidgetSelectionMode where eSingleSelection = ieQCalendarWidgetSelectionMode $ 1
keera-studios/hsQt
Qtc/Enums/Gui/QCalendarWidget.hs
bsd-2-clause
6,712
0
18
1,385
1,667
823
844
146
1
module Main (main) where import Test.Hspec (hspecX, descriptions) import Control.Monad (msum) import qualified Web.MusicBrainz.Testing.XML as X main :: IO () main = hspecX $ descriptions [X.specs]
ocharles/Web-MusicBrainz
Web/MusicBrainz/Testing/Main.hs
bsd-2-clause
200
0
8
29
69
42
27
6
1
{-# LANGUAGE PackageImports #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} module Propellor.PrivData ( withPrivData, withSomePrivData, addPrivData, setPrivData, unsetPrivData, unsetPrivDataUnused, dumpPrivData, editPrivData, filterPrivData, listPrivDataFields, makePrivDataDir, decryptPrivData, readPrivData, readPrivDataFile, PrivMap, PrivInfo, forceHostContext, ) where import System.IO import Data.Maybe import Data.List import Data.Typeable import Control.Monad import Control.Monad.IfElse import "mtl" Control.Monad.Reader import qualified Data.Map as M import qualified Data.Set as S import qualified Data.ByteString.Lazy as L import Control.Applicative import Data.Monoid import Prelude import Propellor.Types import Propellor.Types.PrivData import Propellor.Types.MetaTypes import Propellor.Types.Info import Propellor.Message import Propellor.Info import Propellor.Gpg import Propellor.PrivData.Paths import Utility.Monad import Utility.PartialPrelude import Utility.Exception import Utility.Tmp import Utility.SafeCommand import Utility.Process.NonConcurrent import Utility.Misc import Utility.FileMode import Utility.Env import Utility.Table import Utility.Directory -- | Allows a Property to access the value of a specific PrivDataField, -- for use in a specific Context or HostContext. -- -- Example use: -- -- > withPrivData (PrivFile pemfile) (Context "joeyh.name") $ \getdata -> -- > property "joeyh.name ssl cert" $ getdata $ \privdata -> -- > liftIO $ writeFile pemfile (privDataVal privdata) -- > where pemfile = "/etc/ssl/certs/web.pem" -- -- Note that if the value is not available, the action is not run -- and instead it prints a message to help the user make the necessary -- private data available. -- -- The resulting Property includes Info about the PrivDataField -- being used, which is necessary to ensure that the privdata is sent to -- the remote host by propellor. withPrivData :: ( IsContext c , IsPrivDataSource s , IncludesInfo metatypes ~ 'True ) => s -> c -> (((PrivData -> Propellor Result) -> Propellor Result) -> Property metatypes) -> Property metatypes withPrivData s = withPrivData' snd [s] -- Like withPrivData, but here any one of a list of PrivDataFields can be used. withSomePrivData :: ( IsContext c , IsPrivDataSource s , IncludesInfo metatypes ~ 'True ) => [s] -> c -> ((((PrivDataField, PrivData) -> Propellor Result) -> Propellor Result) -> Property metatypes) -> Property metatypes withSomePrivData = withPrivData' id withPrivData' :: ( IsContext c , IsPrivDataSource s , IncludesInfo metatypes ~ 'True ) => ((PrivDataField, PrivData) -> v) -> [s] -> c -> (((v -> Propellor Result) -> Propellor Result) -> Property metatypes) -> Property metatypes withPrivData' feed srclist c mkprop = addinfo $ mkprop $ \a -> maybe missing (a . feed) =<< getM get fieldlist where get field = do context <- mkHostContext hc <$> asks hostName maybe Nothing (\privdata -> Just (field, privdata)) <$> liftIO (getLocalPrivData field context) missing = do Context cname <- mkHostContext hc <$> asks hostName warningMessage $ "Missing privdata " ++ intercalate " or " fieldnames ++ " (for " ++ cname ++ ")" infoMessage $ "Fix this by running:" : showSet (map (\s -> (privDataField s, Context cname, describePrivDataSource s)) srclist) return FailedChange addinfo p = p `addInfoProperty` (toInfo privset) privset = PrivInfo $ S.fromList $ map (\s -> (privDataField s, describePrivDataSource s, hc)) srclist fieldnames = map show fieldlist fieldlist = map privDataField srclist hc = asHostContext c showSet :: [(PrivDataField, Context, Maybe PrivDataSourceDesc)] -> [String] showSet = concatMap go where go (f, Context c, md) = catMaybes [ Just $ " propellor --set '" ++ show f ++ "' '" ++ c ++ "' \\" , maybe Nothing (\d -> Just $ " " ++ d) md , Just "" ] addPrivData :: (PrivDataField, Maybe PrivDataSourceDesc, HostContext) -> Property (HasInfo + UnixLike) addPrivData v = pureInfoProperty (show v) (PrivInfo (S.singleton v)) {- Gets the requested field's value, in the specified context if it's - available, from the host's local privdata cache. -} getLocalPrivData :: PrivDataField -> Context -> IO (Maybe PrivData) getLocalPrivData field context = getPrivData field context . fromMaybe M.empty <$> localcache where localcache = catchDefaultIO Nothing $ readish <$> readFile privDataLocal type PrivMap = M.Map (PrivDataField, Context) String -- | Get only the set of PrivData that the Host's Info says it uses. filterPrivData :: Host -> PrivMap -> PrivMap filterPrivData host = M.filterWithKey (\k _v -> S.member k used) where used = S.map (\(f, _, c) -> (f, mkHostContext c (hostName host))) $ fromPrivInfo $ fromInfo $ hostInfo host getPrivData :: PrivDataField -> Context -> PrivMap -> Maybe PrivData getPrivData field context m = do s <- M.lookup (field, context) m return (PrivData s) setPrivData :: PrivDataField -> Context -> IO () setPrivData field context = do putStrLn "Enter private data on stdin; ctrl-D when done:" setPrivDataTo field context . PrivData =<< hGetContentsStrict stdin unsetPrivData :: PrivDataField -> Context -> IO () unsetPrivData field context = do modifyPrivData $ M.delete (field, context) descUnset field context descUnset :: PrivDataField -> Context -> IO () descUnset field context = putStrLn $ "Private data unset: " ++ show field ++ " " ++ show context unsetPrivDataUnused :: [Host] -> IO () unsetPrivDataUnused hosts = do deleted <- modifyPrivData' $ \m -> let (keep, del) = M.partitionWithKey (\k _ -> k `M.member` usedby) m in (keep, M.keys del) mapM_ (uncurry descUnset) deleted where usedby = mkUsedByMap hosts dumpPrivData :: PrivDataField -> Context -> IO () dumpPrivData field context = do maybe (error "Requested privdata is not set.") (L.hPut stdout . privDataByteString) =<< (getPrivData field context <$> decryptPrivData) editPrivData :: PrivDataField -> Context -> IO () editPrivData field context = do v <- getPrivData field context <$> decryptPrivData v' <- withTmpFile "propellorXXXX" $ \f th -> do hClose th maybe noop (\p -> writeFileProtected' f (`L.hPut` privDataByteString p)) v editor <- getEnvDefault "EDITOR" "vi" unlessM (boolSystemNonConcurrent editor [File f]) $ error "Editor failed; aborting." PrivData <$> readFile f setPrivDataTo field context v' listPrivDataFields :: [Host] -> IO () listPrivDataFields hosts = do m <- decryptPrivData section "Currently set data:" showtable $ map mkrow (M.keys m) let missing = M.keys $ M.difference wantedmap m unless (null missing) $ do section "Missing data that would be used if set:" showtable $ map mkrow missing section "How to set missing data:" mapM_ putStrLn $ showSet $ map (\(f, c) -> (f, c, join $ M.lookup (f, c) descmap)) missing where header = ["Field", "Context", "Used by"] mkrow k@(field, Context context) = [ shellEscape $ show field , shellEscape context , intercalate ", " $ sort $ fromMaybe [] $ M.lookup k usedby ] usedby = mkUsedByMap hosts wantedmap = M.fromList $ zip (M.keys usedby) (repeat "") descmap = M.unions $ map (`mkPrivDataMap` id) hosts section desc = putStrLn $ "\n" ++ desc showtable rows = do putStr $ unlines $ formatTable $ tableWithHeader header rows mkUsedByMap :: [Host] -> M.Map (PrivDataField, Context) [HostName] mkUsedByMap = M.unionsWith (++) . map (\h -> mkPrivDataMap h $ const [hostName h]) mkPrivDataMap :: Host -> (Maybe PrivDataSourceDesc -> a) -> M.Map (PrivDataField, Context) a mkPrivDataMap host mkv = M.fromList $ map (\(f, d, c) -> ((f, mkHostContext c (hostName host)), mkv d)) (S.toList $ fromPrivInfo $ fromInfo $ hostInfo host) setPrivDataTo :: PrivDataField -> Context -> PrivData -> IO () setPrivDataTo field context (PrivData value) = do modifyPrivData set putStrLn "Private data set." where set = M.insert (field, context) value modifyPrivData :: (PrivMap -> PrivMap) -> IO () modifyPrivData f = modifyPrivData' (\m -> (f m, ())) modifyPrivData' :: (PrivMap -> (PrivMap, a)) -> IO a modifyPrivData' f = do makePrivDataDir m <- decryptPrivData let (m', r) = f m privdata <- privDataFile gpgEncrypt privdata (show m') void $ boolSystem "git" [Param "add", File privdata] return r decryptPrivData :: IO PrivMap decryptPrivData = readPrivData <$> (gpgDecrypt =<< privDataFile) readPrivData :: String -> PrivMap readPrivData = fromMaybe M.empty . readish readPrivDataFile :: FilePath -> IO PrivMap readPrivDataFile f = readPrivData <$> readFileStrict f makePrivDataDir :: IO () makePrivDataDir = createDirectoryIfMissing False privDataDir newtype PrivInfo = PrivInfo { fromPrivInfo :: S.Set (PrivDataField, Maybe PrivDataSourceDesc, HostContext) } deriving (Eq, Ord, Show, Typeable, Monoid) -- PrivInfo always propagates out of containers, so that propellor -- can see which hosts need it. instance IsInfo PrivInfo where propagateInfo _ = PropagatePrivData -- | Sets the context of any privdata that uses HostContext to the -- provided name. forceHostContext :: String -> PrivInfo -> PrivInfo forceHostContext name i = PrivInfo $ S.map go (fromPrivInfo i) where go (f, d, HostContext ctx) = (f, d, HostContext (const $ ctx name))
ArchiveTeam/glowing-computing-machine
src/Propellor/PrivData.hs
bsd-2-clause
9,424
155
17
1,621
2,749
1,476
1,273
-1
-1
module TestModuleMany where import HEP.Automation.EventGeneration.Type import HEP.Automation.JobQueue.JobType import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Model.SM import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Type import HEP.Storage.WebDAV.Type psetup :: ProcessSetup SM psetup = PS { model = SM , process = MGProc [] [ "p p > t t~" ] , processBrief = "ttbar" , workname = "ttbar" , hashSalt = HashSalt Nothing } param :: ModelParam SM param = SMParam rsetupgen :: Int -> RunSetup rsetupgen x = RS { numevent = 10000 , machine = LHC7 ATLAS , rgrun = Auto , rgscale = 200 , match = MLM , cut = DefCut , pythia = RunPYTHIA , lhesanitizer = [] , pgs = RunPGS (AntiKTJet 0.4, WithTau) , uploadhep = NoUploadHEP , setnum = x } eventsets :: [EventSet] eventsets = [ EventSet psetup param (rsetupgen x) | x <- [2..10] ] webdavdir :: WebDAVRemoteDir webdavdir = WebDAVRemoteDir "newtest"
wavewave/jobqueue-sender
TestModuleMany.hs
bsd-2-clause
1,097
0
9
309
282
172
110
33
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Exception (bracketOnError) import Control.Monad.State.Lazy import Data.Maybe (fromMaybe) import qualified Data.Text as T import qualified Data.Text.IO as T import Network hiding (socketPort) import Network.BSD (getProtocolNumber) import Network.Socket hiding (PortNumber, accept, sClose) import Options.Applicative import Purescript.Ide import System.Directory import System.Exit import System.FilePath import System.IO -- Copied from upstream impl of listenOn -- bound to localhost interface instead of iNADDR_ANY listenOnLocalhost :: PortID -> IO Socket listenOnLocalhost (PortNumber port) = do proto <- getProtocolNumber "tcp" localhost <- inet_addr "127.0.0.1" bracketOnError (socket AF_INET Stream proto) sClose (\sock -> do setSocketOption sock ReuseAddr 1 bindSocket sock (SockAddrInet port localhost) listen sock maxListenQueue return sock) data Options = Options { optionsDirectory :: Maybe FilePath , optionsPort :: Maybe Int } main :: IO () main = do Options dir port <- execParser opts maybe (return ()) setCurrentDirectory dir startServer (PortNumber . fromIntegral $ fromMaybe 4242 port) emptyPscState where parser = Options <$> optional (strOption (long "directory" <> short 'd')) <*> optional (option auto (long "port" <> short 'p')) opts = info parser mempty startServer :: PortID -> PscState -> IO () startServer port st_in = withSocketsDo $ do sock <- listenOnLocalhost port evalStateT (forever (loop sock)) st_in where acceptCommand sock = do (h,_,_) <- accept sock hSetEncoding h utf8 cmd <- T.hGetLine h return (cmd, h) loop :: Socket -> PscIde () loop sock = do (cmd,h) <- liftIO $ acceptCommand sock case parseCommand cmd of Right cmd' -> do result <- handleCommand cmd' liftIO $ T.hPutStrLn h result Left err -> liftIO $ hPrint h err liftIO $ hClose h handleCommand :: Command -> PscIde T.Text handleCommand (TypeLookup ident) = fromMaybe "Not found" <$> findTypeForName ident handleCommand (Completion stub) = T.intercalate ", " <$> findCompletion stub handleCommand (Load moduleName) = do path <- liftIO $ filePathFromModule moduleName case path of Right p -> loadModule p >> return "Success" Left err -> return err handleCommand Print = T.intercalate ", " <$> printModules handleCommand Quit = liftIO exitSuccess filePathFromModule :: T.Text -> IO (Either T.Text FilePath) filePathFromModule moduleName = do cwd <- getCurrentDirectory let path = cwd </> "output" </> T.unpack moduleName </> "externs.purs" ex <- doesFileExist path return $ if ex then Right path else Left "Module could not be found"
epost/psc-ide
server/Main.hs
bsd-3-clause
3,181
0
16
958
891
436
455
79
2
module Day20 where {-# LANGUAGE TupleSections #-} -- Improvements to Day18 import Control.Monad.Gen import Control.Monad.Trans.Either import Control.Monad.Reader import qualified Data.Map as Map data Type = Function Type Type -- a -> b | RecordT [(String, Type)] -- a * b | VariantT [(String, Type)] -- a + b deriving (Eq, Show) -- t2 = { x: 10, y: 20 } : { x : Int, y : Int } -- t3 = { x: 10, y: 20, z: 30 } : { x : Int, y : Int, z : Int } -- f : { x : Int } -> Int -- f tuple = tuple.x -- f t3 -- eitherIS = { left : Int | right : String } -- x = left 5 : eitherIS -- Note: In a bidirectional HOAS, functions always take a checked term to -- checked term. Why? Because we want to take in and return canonical values -- (which are possibly neutral), not computations. -- Canonical values data CheckTerm -- Neither a constructor nor change of direction. -- -- The type is the return type. = Let String InferTerm Type (InferTerm -> CheckTerm) -- switch direction (infer -> check) | Neutral InferTerm -- constructors -- \x -> CheckedTerm | Abs String (InferTerm -> CheckTerm) | Record [(String, CheckTerm)] | Variant String CheckTerm -- Computations data InferTerm -- switch direction (check -> infer) = Annot CheckTerm Type -- Used in both reification and typechecking. -- We don't use the type during reification, but do during checking. | Unique Int (Maybe Type) -- eliminators -- -- note that eliminators always take an InferTerm as the inspected term, -- since that's the neutral position, then CheckTerms for the rest | App InferTerm CheckTerm | AccessField InferTerm String | Case InferTerm Type [(String, InferTerm -> CheckTerm)] data NCheckTerm = NLet String NInferTerm Type NCheckTerm | NNeutral NInferTerm | NAbs String NCheckTerm | NRecord [(String, NCheckTerm)] | NVariant String NCheckTerm deriving Show data NInferTerm = NVar String | NAnnot NCheckTerm Type | NApp NInferTerm NCheckTerm | NAccessField NInferTerm String | NCase NInferTerm Type [(String, NCheckTerm)] deriving Show -- In reflection we use a map reader to look up bound variables by name reflect :: NCheckTerm -> CheckTerm reflect t = runReader (cReflect t) Map.empty cReflect :: NCheckTerm -> Reader (Map.Map String InferTerm) CheckTerm cReflect nTm = case nTm of NLet name iTm ty cTm -> do table <- ask iTm' <- iReflect iTm return $ Let name iTm' ty $ \arg -> runReader (cReflect cTm) (Map.insert name arg table) NNeutral iTm -> Neutral <$> iReflect iTm NAbs name cTm -> do table <- ask return $ Abs name $ \arg -> runReader (cReflect cTm) (Map.insert name arg table) NRecord fields -> do fields' <- Map.toList <$> traverse cReflect (Map.fromList fields) return $ Record fields' NVariant str cTm -> Variant str <$> cReflect cTm iReflect :: NInferTerm -> Reader (Map.Map String InferTerm) InferTerm iReflect nTm = case nTm of NVar name -> do let ty = undefined cTm <- reader (Map.! name) return $ Annot cTm ty NAnnot cTm ty -> Annot <$> cReflect cTm <*> pure ty NApp iTm cTm -> App <$> iReflect iTm <*> cReflect cTm NAccessField iTm name -> AccessField <$> iReflect iTm <*> pure name NCase iTm ty cases -> do iTm' <- iReflect iTm table <- ask cases' <- (`Map.traverseWithKey` Map.fromList cases) $ \name cTm -> return $ \cTmArg -> runReader (cReflect cTm) (Map.insert name cTmArg table) return $ Case iTm' ty (Map.toList cases') -- In reification we use a map reader to look up temporarily named variables reify :: CheckTerm -> NCheckTerm reify t = runGen (runReaderT (cReify t) Map.empty) iReify :: InferTerm -> ReaderT (Map.Map Int NInferTerm) (Gen Int) NInferTerm iReify t = case t of Unique ident _ -> (Map.! ident) <$> ask Annot cTm ty -> NAnnot <$> cReify cTm <*> pure ty App t1 t2 -> NApp <$> iReify t1 <*> cReify t2 AccessField subTm name -> NAccessField <$> iReify subTm <*> pure name Case iTm ty branches -> do iTm' <- iReify iTm branches' <- (`Map.traverseWithKey` Map.fromList branches) $ \name f -> do ident <- gen local (Map.insert ident (NVar name)) $ cReify (f (Unique ident Nothing)) return $ NCase iTm' ty (Map.toList branches') cReify :: CheckTerm -> ReaderT (Map.Map Int NInferTerm) (Gen Int) NCheckTerm cReify t = case t of Let name iTm ty f -> do iTm' <- iReify iTm ident <- gen nom <- local (Map.insert ident (NVar name)) $ cReify (f (Unique ident Nothing)) return $ NLet name iTm' ty nom Neutral iTm -> NNeutral <$> iReify iTm Abs name f -> do ident <- gen nom <- local (Map.insert ident (NVar name)) $ cReify (f (Unique ident Nothing)) return $ NAbs name nom Record fields -> do fields' <- Map.toList <$> traverse cReify (Map.fromList fields) return $ NRecord fields' Variant tag content -> NVariant tag <$> cReify content type EvalCtx = Either String type CheckCtx = EitherT String (Gen Int) eval :: InferTerm -> EvalCtx CheckTerm eval t = case t of Annot cTerm _ -> return cTerm Unique _ _ -> Left "invariant violation: found Unique in evaluation" App f x -> do f' <- eval f case f' of -- XXX stop propagating neutrals? Neutral f'' -> return $ Neutral (App f'' x) Abs _ f'' -> return $ Neutral (f'' x) _ -> Left "invariant violation: eval found non-Neutral / Abs in function position" AccessField iTm name -> do evaled <- eval iTm case evaled of Neutral nTm -> return $ Neutral (AccessField nTm name) Record fields -> case Map.lookup name (Map.fromList fields) of Just field -> return field Nothing -> Left "didn't find field in record" _ -> Left "unexpected" Case iTm ty branches -> do evaled <- eval iTm case evaled of Neutral nTm -> return $ Neutral (Case nTm ty branches) Variant name cTm -> case Map.lookup name (Map.fromList branches) of Just branch -> return $ branch cTm Nothing -> Left "invariant violation: evaluation didn't find matching variant in case" _ -> Left "invariant violation: evalutaion found non neutral - variant in case" runChecker :: CheckCtx () -> String runChecker calc = case runGen (runEitherT calc) of Right () -> "success!" Left str -> str -- runInference :: CheckCtx Type -> Type -- runInference calc = case runGen (runEitherT calc) of -- Left str -> error $ "(runInference) invariant violation: " ++ str -- Right ty -> ty unifyTy :: Type -> Type -> CheckCtx Type unifyTy (Function dom1 codom1) (Function dom2 codom2) = Function <$> unifyTy dom1 dom2 <*> unifyTy codom1 codom2 unifyTy (RecordT lTy) (RecordT rTy) = do -- RecordT [(String, Type)] -- Take the intersection of possible records. Make sure the overlap matches! let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy) isect' <- mapM (uncurry unifyTy) isect return $ RecordT (Map.toList isect') unifyTy (VariantT lTy) (VariantT rTy) = do -- Take the union of possible variants. Make sure overlap matches! let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy) isect' <- mapM (uncurry unifyTy) isect let union = Map.union (Map.fromList lTy) (Map.fromList rTy) -- Overwrite with extra data we may have learned from unifying the types in -- the intersection let result = Map.union isect' union return $ VariantT (Map.toList result) unifyTy l r = left ("failed unification " ++ show (l, r)) check :: CheckTerm -> Type -> CheckCtx () check eTm ty = case eTm of -- t1: infered, t2: infer -> check Let _name t1 ty' body -> do t1Ty <- infer t1 _ <- unifyTy t1Ty ty' let bodyVal = body t1 check bodyVal ty Neutral iTm -> do iTy <- infer iTm _ <- unifyTy ty iTy return () Abs _ body -> do let Function domain codomain = ty v <- Unique <$> lift gen <*> pure (Just domain) let evaled = body v check evaled codomain Record fields -> do -- Record [(String, CheckTerm)] -- -- Here we define our notion of record subtyping -- we check that the -- record we've been given has at least the fields expected of it and of -- the right type. let fieldMap = Map.fromList fields case ty of RecordT fieldTys -> mapM_ (\(name, subTy) -> case Map.lookup name fieldMap of Just subTm -> check subTm subTy Nothing -> left "failed to find required field in record" ) fieldTys _ -> left "failed to check a record against a non-record type" -- Variant String CheckTerm -- -- Here we define our notion of variant subtyping -- we check that the -- variant we've been given is in the row Variant name t' -> case ty of VariantT fieldTys -> case Map.lookup name (Map.fromList fieldTys) of Just expectedTy -> check t' expectedTy Nothing -> left "failed to find required field in record" _ -> left "failed to check a record against a non-record type" infer :: InferTerm -> CheckCtx Type infer t = case t of Annot _ ty -> pure ty Unique _ _ -> left "invariant violation: infer found Unique" App t1 t2 -> do Function domain codomain <- infer t1 check t2 domain return codomain -- rec.name AccessField recTm name -> do inspectTy <- infer recTm case inspectTy of RecordT parts -> case Map.lookup name (Map.fromList parts) of Just subTy -> return subTy Nothing -> left "didn't find the accessed key" _ -> left "found non-record unexpectedly" -- (case [varTm] of [cases]) : [ty] Case varTm ty cases -> do -- check that the inspected value is a variant, -- check all of its cases and the branches to see if all are aligned, -- finally that each typechecks varTmTy <- infer varTm case varTmTy of VariantT tyParts -> do let tyMap = Map.fromList tyParts caseMap = Map.fromList cases bothMatch = Map.null (tyMap Map.\\ caseMap) && Map.null (caseMap Map.\\ tyMap) when (not bothMatch) (left "case misalignment") let mergedMap = Map.mergeWithKey (\name l r -> Just (name, l, r)) (const (Map.fromList [])) (const (Map.fromList [])) tyMap caseMap mapM_ (\(_name, branchTy, rhs) -> do v <- Unique <$> lift gen <*> pure (Just branchTy) check (rhs (Neutral v)) ty ) mergedMap _ -> left "found non-variant in case" return ty main :: IO () main = putStrLn "here" -- let unit = Record [] -- unitTy = RecordT [] -- xy = Record -- [ ("x", unit) -- , ("y", unit) -- ] -- xyTy = RecordT -- [ ("x", unitTy) -- , ("y", unitTy) -- ] -- -- boring -- print $ runChecker $ -- let tm = Abs "id" (\x -> x) -- ty = Function unitTy unitTy -- in check tm ty -- -- standard record -- print $ runChecker $ -- let tm = Let -- "xy" -- (Annot xy xyTy) -- xyTy -- (\x -> Neutral -- (AccessField (Annot x xyTy) "x") -- ) -- in check tm unitTy -- -- record subtyping -- print $ runChecker $ -- let xRecTy = RecordT [("x", unitTy)] -- tm = Let -- "xy" -- (Annot xy xRecTy) -- xRecTy -- (\x -> Neutral -- (AccessField (Annot x xRecTy) "x") -- ) -- in check tm unitTy -- -- variant subtyping -- -- -- -- left () : { left () | right () } -- print $ runChecker $ -- let eitherTy = VariantT -- [ ("left", unitTy) -- , ("right", unitTy) -- ] -- in check (Variant "left" unit) eitherTy -- -- let x = left () : { left : () | right : () } -- -- in case x of -- -- left y -> y -- -- right y -> y -- print $ -- let eitherTy = VariantT -- [ ("left", unitTy) -- , ("right", unitTy) -- ] -- tm = Let -- "e" -- (Annot (Variant "left" unit) eitherTy) -- eitherTy -- (\x -> Neutral -- (Case (Annot x eitherTy) unitTy -- [ ("left", \y -> y) -- , ("right", \y -> y) -- ] -- ) -- ) -- in (runChecker (check tm unitTy), reify <$> eval (Annot tm unitTy))
joelburget/daily-typecheckers
src/Day20.hs
bsd-3-clause
12,440
4
20
3,459
3,200
1,595
1,605
-1
-1
module Husky.Wai.FileApplication ( fileApplication ) where import System.FilePath import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB import Data.Enumerator (yield, Stream(EOF)) import Data.CaseInsensitive ( mk ) import Network.Wai import Network.HTTP.Types header :: String -> String -> Header header key value = (mk (B.pack key), (B.pack value)) -- | WAI application to host file at given urlPath fileApplication :: String -> FilePath -> Application fileApplication urlPath file request = do liftIO $ putStrLn $ (show $ remoteHost request) ++ " connected." if tail (B.unpack $ rawPathInfo request) == urlPath then (liftIO . putStrLn) "good URL." >> yield (ResponseFile statusOK headers file Nothing) EOF else (liftIO . putStrLn) "bad URL." >> yield (responseLBS statusNotFound [headerContentType (B.pack "text/plain")] (LB.pack "404 Not Found")) EOF where headers = [ headerContentType (B.pack $ guessContentType file) ] guessContentType :: FilePath -> String guessContentType path = byExt (takeExtension path) where byExt ".org" = "text/plain" byExt ".txt" = "text/plain" byExt _ = "application/octet-stream"
abaw/husky
Husky/Wai/FileApplication.hs
bsd-3-clause
1,362
0
16
327
374
203
171
27
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} module Model where import Data.Time.Clock import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.Types import Database.PostgreSQL.Simple.ToField import Database.PostgreSQL.Simple.FromRow import Database.PostgreSQL.Simple.ToRow import qualified Data.Text as T data Paste = Paste { content :: T.Text } deriving Show instance FromRow Paste where fromRow = Paste <$> field instance ToRow Paste where toRow t = [toField (content t)] -- Initialize database createPasteBox :: Query createPasteBox = [sql| CREATE TABLE IF NOT EXISTS paste ( lid SERIAL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_DATE, content TEXT NOT NULL ); |] addPasteReturningID :: Connection -> Paste -> IO [Only Int] addPasteReturningID con a = query con "INSERT INTO paste (created_at, content) VALUES (NOW (), ?) RETURNING lid" $ a getPasteWithID :: Connection -> Int -> IO [Paste] getPasteWithID c n = query c "SELECT TEXT(content) FROM paste WHERE lid = ?" $ Only n
sivteck/hs-pastebin
src/Model.hs
bsd-3-clause
1,248
0
9
269
225
132
93
26
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} module Main where type X a b = Y a b type Function c d = c -> Int -> d -> Int newtype A = B Int data C = D String | E deriving (Show) data Z a b = Z (X a b) (X a b , X a b) data F = F { c :: String, d :: String } deriving (Eq, Show) data Sql where Sql :: Sql.Connection conn => conn -> Sql build :: F build = F { c = "c" , d = "d" } test :: Num n => n -> F test _ = build { c = "C", d = "D" } :: F class (Num r, Ord r) => Repository r where create :: r -> String -> Int -> IO () read :: String -> IO (Maybe Int) instance Num a => Repository (Dict String Int) where type X = Y create dict string int = Dict.set dict string int read = Dict.get
hecrj/haskell-format
test/specs/types/input.hs
bsd-3-clause
754
0
11
234
344
191
153
34
1
{-# LANGUAGE TypeOperators #-} module LiuMS.Config ( Config (..), Language, SiteInfo (..) , liuMSInfo, mkConfig , askContentPath, askCacheManager, askSiteInfo ) where import Control.Monad.Reader import Control.Monad.Trans.Except import Servant import LiuMS.CacheManager import LiuMS.Compiler import LiuMS.Compiler.Markdown data Config = Config { contentPath :: FilePath , cacheManager :: CacheManager , siteInfo :: [(Language, SiteInfo)] } type Language = String data SiteInfo = SiteInfo { title :: String , description :: String , author :: String , language :: String } deriving (Eq, Show) liuMSInfo :: [(Language, SiteInfo)] liuMSInfo = [ ( "cmn-Hans-CN" , SiteInfo { title = "Liu.ms" , description = "我,刘闽晟,是一位对计算机科学、语言学、政治科学感兴趣的本科生。点击网站来了解我的生活、兴趣、观点。" , author = "刘闽晟" , language = "cmn-Hans-CN" } ) , ( "eng-Latn-US" , SiteInfo { title = "Liu.ms" , description = "I am Minsheng Liu, an undergraduate interested in CS, Linguistics, and Political Science. Click this site to learn more about my life, interests, and viewpoints." , author = "Minsheng Liu" , language = "eng-Latn-US" } ) ] mkConfig :: FilePath -> FilePath -> Config mkConfig contentPath cachePath = Config contentPath manager liuMSInfo where manager = CacheManager (contentPath ++ "/contents") cachePath [("md", markdown)] askContentPath :: (MonadReader Config m) => m FilePath askContentPath = contentPath <$> ask askCacheManager :: (MonadReader Config m) => m CacheManager askCacheManager = cacheManager <$> ask askSiteInfo :: (MonadReader Config m) => m SiteInfo askSiteInfo = do infos <- siteInfo <$> ask return $ snd $ head infos
notcome/liu-ms-adult
src/LiuMS/Config.hs
bsd-3-clause
1,960
0
10
480
413
247
166
-1
-1
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-} module Obsidian.MonadObsidian.PureAPI where import Obsidian.MonadObsidian.Exp import Obsidian.MonadObsidian.Arr -- import Bitwise --import Data.Bits import Control.Monad import Data.Foldable -------------------------------------------------------------------------------- pure f a = return $ f a -------------------------------------------------------------------------------- (??) b (x,y) = ifThenElse b x y intLog 1 = 0 intLog n = 1 + (intLog (div n 2)) -------------------------------------------------------------------------------- {- unriffle' :: Arr s a -> Arr s a unriffle' arr | even (len arr) = mkArr (\ix -> arr ! (rotLocalL ix bits) ) n where n = len arr bits = fromIntegral $ intLog n unriffle' _ = error "unriffle' demands even length" riffle' :: Arr s a -> Arr s a riffle' arr | even (len arr) = mkArr (\ix -> arr ! (rotLocalR ix bits) ) n where n = len arr bits = fromIntegral $ intLog n riffle' _ = error "riffle' demands even length" -} instance Foldable (Arr s) where foldr f o arr = Prelude.foldr f o [arr ! (fromIntegral ix) | ix <- [0.. (len arr - 1)]] -------------------------------------------------------------------------------- flatten :: (Arr s (Arr s a)) -> Arr s a flatten arrs | len (arrs ! 0) == 1 = mkArr (\ix -> (arrs ! ix) ! 0) m where k = len arrs n = len (arrs ! 0) m = k * n flatten arrs = mkArr (\ix -> (arrs ! (ix `divi` fromIntegral k)) ! (ix `modi` fromIntegral n)) m where k = len arrs n = len (arrs ! 0) m = k*n restruct :: Int -> Arr s a -> (Arr s (Arr s a)) restruct n arr = mkArr (\ix -> inner ix) n where m = len arr k = m `div` n inner a = mkArr (\ix -> arr ! ((a * fromIntegral k) + ix) ) k -------------------------------------------------------------------------------- chopN :: Int -> Arr s a -> Arr s (Arr s a) chopN n arr = mkArr (\o -> (mkArr (\i -> arr ! ((o * (fromIntegral n)) + i)) n)) (fromIntegral m) where m = (len arr) `div` n nParts :: Int -> Arr s a -> Arr s (Arr s a) nParts n arr = mkArr (\o -> (mkArr (\i -> arr ! (((fromIntegral m) * o) + i)) m)) (fromIntegral n) where m = (len arr) `div` n unChop :: Arr s (Arr s a) -> Arr s a unChop arr = mkArr (\ix -> let x = ix `modi` fromIntegral w y = ix `divi` fromIntegral w in (arr ! y) ! x) newLen where h = len arr w = len (arr ! 0) newLen = h * w -------------------------------------------------------------------------------- rev :: Arr s a -> Arr s a rev arr = mkArr ixf n where ixf ix = arr ! (fromIntegral (n-1) - ix) n = len arr -------------------------------------------------------------------------------- split :: Int -> Arr s a -> (Arr s a,Arr s a) split m arr = let n = len arr h1 = mkArr (\ix -> arr ! ix) m h2 = mkArr (\ix -> arr ! (ix + (fromIntegral m))) (n-m) in (h1,h2) halve :: Arr s a -> (Arr s a,Arr s a) halve arr = split (len arr `div` 2) arr conc :: Choice a => (Arr s a, Arr s a) -> Arr s a conc (arr1,arr2) = let (n,n') = (len arr1,len arr2) in mkArr (\ix -> ifThenElse (ix <* fromIntegral n) (arr1 ! ix) (arr2 ! (ix - fromIntegral n))) (n+n') {- oeSplit. Odd Even Split. used to create a more general riffle -} oeSplit :: Arr s a -> (Arr s a, Arr s a) oeSplit arr = let n = len arr nhalf = div n 2 in (mkArray (\ix -> arr ! (2 * ix)) (n - nhalf), mkArray (\ix -> arr ! ((2 * ix) + 1)) nhalf) {- shuffle, (use with caution) -} shuffle :: Choice a => (Arr s a, Arr s a) -> (Arr s a) shuffle (arr1,arr2) = let (n1,n2) = (len arr1,len arr2) in (mkArray (\ix -> ifThenElse ((modi ix 2) ==* 0) (arr1 ! (divi ix 2)) (arr2 ! (divi (ix - 1) 2))) (n1 + n2)) -------------------------------------------------------------------------------- evens :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> Arr s a evens f arr = let n = len arr in mkArr (\ix -> ifThenElse ((modi ix 2) ==* 0) (ifThenElse ((ix + 1) <* (fromIntegral n)) (fst (f (arr ! ix,arr ! (ix + 1)))) (arr ! ix)) (ifThenElse (ix <* (fromIntegral n)) (snd (f (arr ! (ix - 1),arr ! ix))) (arr ! ix))) n odds f arr = let (a1,a2) = split 1 arr in conc (a1,evens f a2) -------------------------------------------------------------------------------- {- pair :: Arr s a -> Arr (a,a) pair arr | odd (len arr) = error "Pair: Odd n" | otherwise = mkArr (\ix -> (arr ! (ix * 2), arr ! ((ix * 2) + 1))) nhalf where n = len arr nhalf = div n 2 -} pair :: Arr s a -> Arr s (a,a) pair arr | odd (len arr) = error "Pair: Odd n" | otherwise = mkArr (\ix -> (arr ! (ix * 2), arr ! ((ix * 2 ) + 1))) nhalf where n = len arr nhalf = div n 2 {- unpair :: Choice a => Arr (a,a) -> Arr s a unpair arr = let n = len arr in mkArr (\ix -> ifThenElse ((mod ix 2) ==* 0) (fst (arr ! (div ix 2))) (snd (arr ! (div (ix-1) 2)))) (2*n) -} unpair :: Choice a => Arr s (a,a) -> Arr s a unpair arr = let n = len arr in mkArr (\ix -> ifThenElse ((modi ix 2) ==* 0) (fst (arr ! (divi ix 2))) (snd (arr ! (divi ix 2)))) (2*n) pairwise :: Functor (Arr s) => (a -> a -> b) -> Arr s a -> Arr s b pairwise f = fmap (uncurry f) . pair -------------------------------------------------------------------------------- zipp :: (Arr s a, Arr s b) -> Arr s (a,b) zipp (arr1,arr2) = mkArr (\ix -> (arr1 ! ix,arr2 ! ix)) n where n = min (len arr1) (len arr2) unzipp :: Arr s (a,b) -> (Arr s a, Arr s b) unzipp arr = (mkArr (\ix -> fst (arr ! ix)) n, mkArr (\ix -> snd (arr ! ix)) n) where n = len arr -------------------------------------------------------------------------------- evens2 :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> Arr s a evens2 f arr = let n = len arr in mkArr (\ix -> ifThenElse ((ix `modi` 2) ==* 0) (fst (f (arr ! ix,arr ! (ix + 1)))) (snd (f (arr ! (ix - 1),arr ! ix)))) n odds2 :: Choice a => ((a,a) -> (a,a)) -> Arr s a -> Arr s a odds2 f arr = let n = len arr in mkArr (\ix -> ifThenElse (((ix - 1) `modi` 2) ==* 0) (fst (f (arr ! ix,arr ! (ix + 1)))) (snd (f (arr ! (ix - 1),arr ! ix)))) n endS :: Int -> Arr s a -> Arr s a endS n arr = mkArr (\ix -> arr ! (ix + (fromIntegral n)) ) nl where l = len arr nl = l - n gz :: [Arr s a] -> (Arr s [a]) gz xs = let n1 = len (head xs) -- deal with different lenghts ! in mkArr (\ix -> map (! ix) xs) n1 --gz = undefined guz :: Arr s [a] -> [Arr s a] guz arr = let n = len arr m = length (arr ! (E (LitInt 0))) in [mkArr (\ix -> (arr ! ix) !! i) n | i <- [0..(m-1)]]
svenssonjoel/MonadObsidian
Obsidian/MonadObsidian/PureAPI.hs
bsd-3-clause
7,686
0
20
2,736
3,050
1,600
1,450
132
1
-- | -- Module: Control.Proxy.ByteString.List -- Copyright: (c) 2013 Ertugrul Soeylemez -- License: BSD3 -- Maintainer: Ertugrul Soeylemez <[email protected]> module Control.Proxy.ByteString.List ( -- * Basic operations fromLazyS, unfoldrS, unpackD, -- * Substreams dropD, dropWhileD, takeD, takeWhileD ) where import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as Bl import Control.Proxy hiding (dropD, dropWhileD, takeWhileD) import Data.ByteString (ByteString) import Data.Word -- | Equivalent to 'B.drop'. dropD :: (Monad m, Proxy p) => Int -- ^ Number of initial bytes to drop. -> () -> Pipe p ByteString ByteString m r dropD n = runIdentityK (loop n >=> idT) where loop n = request >=> \bs -> let len = B.length bs in if len < n then loop (n - len) () else respond (B.drop n bs) -- | Equivalent to 'B.dropWhile'. dropWhileD :: (Monad m, Proxy p) => (Word8 -> Bool) -- ^ Drop bytes while this predicate is true. -> () -> Pipe p ByteString ByteString m r dropWhileD p = runIdentityK (loop >=> idT) where loop = request >=> \bs -> let sfx = B.dropWhile p bs in if B.null sfx then loop () else respond sfx -- | Turn the given lazy 'ByteString' into a stream of its strict -- chunks. fromLazyS :: (Monad m, Proxy p) => Bl.ByteString -> () -> Producer p ByteString m () fromLazyS = fromListS . Bl.toChunks -- | Equivalent of 'B.take'. takeD :: (Monad m, Proxy p) => Int -- ^ Number of bytes to take. -> () -> Pipe p ByteString ByteString m () takeD = runIdentityK . loop where loop n = request >=> \bs -> let len = B.length bs in if len < n then respond bs >>= loop (n - len) else respond (B.take n bs) -- | Equivalent to 'B.takeWhile'. takeWhileD :: (Monad m, Proxy p) => (Word8 -> Bool) -- ^ Take bytes while this predicate is true. -> () -> Pipe p ByteString ByteString m () takeWhileD p = runIdentityK loop where loop = request >=> \bs -> let (pfx, sfx) = B.span p bs in if B.null sfx then respond pfx >>= loop else respond pfx -- | Equivalent of 'B.unfoldr'. Generate a 'ByteString' stream using -- the given generator function. Notice that the first argument is only -- the chunk size, not the maximum size. unfoldrS :: (Monad m, Proxy p) => Int -- ^ Chunk size. -> (a -> Maybe (Word8, a)) -- ^ Generator function. -> a -- ^ Seed. -> () -> Producer p ByteString m () unfoldrS n f = runIdentityK . loop where loop x = let (bs, my) = B.unfoldrN n f x in const (respond bs) >=> maybe return loop my -- | Unpack a stream of 'ByteString's into individual bytes. unpackD :: (Monad m, Proxy p) => () -> Pipe p ByteString Word8 m r unpackD = runIdentityK (foreverK $ request >=> mapM_ respond . B.unpack)
ertes/pipes-bytestring
Control/Proxy/ByteString/List.hs
bsd-3-clause
3,137
0
15
998
870
464
406
-1
-1
{- | Maintainer : [email protected] Stability : experimental Portability : portable The preferred method for rendering a 'Document' or single 'Content' is by using the pretty printing facility defined in "Pretty". Pretty-printing does not work well for cases, however, where the formatting in the XML document is significant. Examples of this case are XHTML's @\<pre\>@ tag, Docbook's @\<literallayout\>@ tag, and many more. Theoretically, the document author could avoid this problem by wrapping the contents of these tags in a \<![CDATA[...]]\> section, but often this is not practical, for instance when the literal-layout section contains other elements. Finally, program writers could manually format these elements by transforming them into a 'literal' string in their 'CFliter', etc., but this is annoying to do and prone to omissions and formatting errors. As an alternative, this module provides the function 'verbatim', which will format XML 'Content' as a 'String' while retaining the formatting of the input document unchanged. /Know problems/: * HaXml's parser eats line feeds between two tags. * 'Attribute's should be formatted by making them an instance of 'Verbatim' as well, but since an 'Attribute' is just a tuple, not a full data type, the helper function 'verbAttr' must be used instead. * 'CMisc' is not yet supported. * 'Element's, which contain no content, are formatted as @\<element-name\/\>@, even if they were not defined as being of type @EMPTY@. In XML this perfectly alright, but in SGML it is not. Those, who wish to use 'verbatim' to format parts of say an HTML page will have to (a) replace problematic elements by 'literal's /before/ running 'verbatim' or (b) use a second search-and-replace stage to fix this. -} module Text.XML.HaXml.Verbatim where import Text.XML.HaXml.Types -- |This class promises that the function 'verbatim' knows how to -- format this data type into a string without changing the -- formatting. class Verbatim a where verbatim :: a -> String instance (Verbatim a) => Verbatim [a] where verbatim = concat . (map verbatim) instance Verbatim Char where verbatim c = [c] instance (Verbatim a, Verbatim b) => Verbatim (Either a b) where verbatim (Left v) = verbatim v verbatim (Right v) = verbatim v instance Verbatim (Content i) where verbatim (CElem c _) = verbatim c verbatim (CString _ c _) = c verbatim (CRef c _) = verbatim c verbatim (CMisc _ _) = error "NYI: verbatim not defined for CMisc" instance Verbatim (Element i) where verbatim (Elem nam att []) = "<" ++ nam ++ (concat . (map verbAttr)) att ++ "/>" verbatim (Elem nam att cont) = "<" ++ nam ++ (concat . (map verbAttr)) att ++ ">" ++ verbatim cont ++ "</" ++ nam ++ ">" instance Verbatim Reference where verbatim (RefEntity r) = "&" ++ verbatim r ++ ";" verbatim (RefChar c) = "&#" ++ show c ++ ";" -- |This is a helper function is required because Haskell does not -- allow to make an ordinary tuple (like 'Attribute') an instance of a -- class. The resulting output will preface the actual attribute with -- a single blank so that lists of 'Attribute's can be handled -- implicitly by the definition for lists of 'Verbatim' data types. verbAttr :: Attribute -> String verbAttr (n, AttValue v) = " " ++ n ++ "=\"" ++ verbatim v ++ "\""
FranklinChen/hugs98-plus-Sep2006
packages/HaXml/src/Text/XML/HaXml/Verbatim.hs
bsd-3-clause
3,563
0
16
853
480
247
233
26
1
module ReadPNG where import Data.Array.Repa.IO.DevIL import Data.Array.Repa as R import Data.Array.Repa.Repr.ForeignPtr import Data.Array.Accelerate.IO import Data.Array.Accelerate as A import Data.Array.Accelerate.Interpreter import Control.Monad import ReadDist import Codec.BMP import System.Environment exec = do (filename:_) <- getArgs (testRead filename) >>= putStrLn testRead :: String -> IO String testRead filename = (liftM show) $ readImage' filename trim :: A.Array A.DIM3 Word8 -> A.Array A.DIM2 Word8 trim im = run $ A.slice (use im) (lift (A.Z A.:. A.All A.:. A.All A.:. (0::Int))) readImage' :: FilePath -> IO (A.Array A.DIM2 Word8) readImage' = (liftM fromRepa) . (flip (>>=) copyP) . (liftM strip) . runIL . readImage strip :: Image -> (R.Array F R.DIM2 Word8) strip (Grey x) = x strip _ = error "Image corrupted. Did you use Matrixbmp to generate it?"
vmchale/EMD
src/ReadPNG.hs
bsd-3-clause
884
0
13
139
339
185
154
23
1
-- | Basebull library module module Basebull where import qualified Data.Foldable as F import qualified Data.ByteString.Lazy as BL import Data.Csv.Streaming -- a simple type alias for data type BaseballStats = (BL.ByteString, Int, BL.ByteString, Int) fourth :: (a, b, c, d) -> d fourth (_, _, _, d) = d baseballStats ::BL.ByteString -> Records BaseballStats baseballStats = decode NoHeader summer :: (a, b, c, Int) -> Int -> Int summer = (+). fourth -- FilePath is just an alias for String getAtBatsSum :: FilePath -> IO Int getAtBatsSum battingCsv = do csvData <- BL.readFile battingCsv return $ F.foldr summer 0 (baseballStats csvData)
emaphis/Haskell-Practice
basebull/src/Basebull.hs
bsd-3-clause
653
0
10
116
205
120
85
15
1
module Backend.InterpreterSpec where import Test.Hspec import qualified Data.Map as Map import Frontend.Parser import Backend.Interpreter testEnv = Map.fromList [("x", Int 1), ("y", Int 2)] spec :: Spec spec = describe "eval" $ do it "evaluates ints" $ eval (Int 1) testEnv `shouldBe` 1 it "evaluates variables" $ eval (Var "x") testEnv `shouldBe` 1 it "evaluates binary arithmetic operations" $ do eval (Add (Int 1) (Int 2)) testEnv `shouldBe` 3 eval (Sub (Int 4) (Int 3)) testEnv `shouldBe` 1 eval (Mul (Int 3) (Int 2)) testEnv `shouldBe` 6 eval (Div (Int 4) (Int 2)) testEnv `shouldBe` 2 eval (Neg (Int 3)) testEnv `shouldBe` -3
JCGrant/JLang
test/Backend/InterpreterSpec.hs
bsd-3-clause
690
0
16
160
308
159
149
19
1
{-# LANGUAGE MagicHash,UnboxedTuples #-} module Data.Util.Size ( unsafeSizeof , strictUnsafeSizeof )where import GHC.Exts import Foreign unsafeSizeof :: a -> Int unsafeSizeof a = case unpackClosure# a of (# x, ptrs, nptrs #) -> sizeOf header + I# (sizeofByteArray# (unsafeCoerce# ptrs) +# sizeofByteArray# nptrs) where header :: Int header = undefined strictUnsafeSizeof :: a -> Int strictUnsafeSizeof = (unsafeSizeof $!)
cutsea110/data-util
Data/Util/Size.hs
bsd-3-clause
486
0
14
123
121
67
54
17
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} -- | module VK.App.Actions (VKAction(..) , module Exp) where import Control.DeepSeq import qualified Data.Text as T import Data.Typeable (Typeable) import GHC.Generics (Generic) import Network.API.Builder (APIError (..)) import qualified Web.Routes.TH as WRTH import qualified VK.API as VK import VK.App.Actions.Types as Exp import VK.App.Internal.Orphans () import VK.App.Types data VKAction = AppInit | SetAjaxRunning !Bool | SetApiState !(VK.VKApp ApiState) | Authorize !VKAction | SetAuthState !AuthState | Audios !AudiosAction | Search !T.Text | ApiError !(APIError VK.VKError) | Refresh deriving (Show, Typeable, Generic, NFData) $(WRTH.derivePathInfo ''VKAction)
eryx67/vk-api-example
src/VK/App/Actions.hs
bsd-3-clause
1,208
0
10
418
221
136
85
44
0
{-# LANGUAGE DataKinds, ExplicitForAll, FlexibleContexts, OverloadedStrings #-} {-# LANGUAGE RecursiveDo, ScopedTypeVariables, TypeApplications #-} {-# LANGUAGE TypeFamilies, TypeOperators #-} {-# OPTIONS_GHC -fdefer-typed-holes #-} module Shaped.Reflex where import Reflex import Reflex.Dom import Servant.Reflex import Data.Text import Generics.SOP import qualified Data.Map as Map import Data.Monoid import Shaped import Data.Functor.Const import Data.Functor.Identity -- | A formlet is a way of constructing an input widget for only a part of the -- form (For example, only for the user password). The two parameters that are -- passed are a generic event to force the update of the field, and the error to -- be displayed (as the validation is done elsewhere). newtype Formlet t m a = Formlet { unFormlet :: Event t () -> Dynamic t (Maybe Text) -> m (Dynamic t a) } -- | An endpoint is a reflex function to query an endpoint. It takes as -- arguments the input (in the same format the servant-reflex library takes it), -- and an event to trigger the api request. It returns an event with a nested -- either value: the first either is to track if the communication with the -- server has gone well, the second one to discriminate between an error value -- for the form or a validated input. type Endpoint t m a s = Dynamic t (Either Text a) -> Event t () -> m (Event t (ReqResult (Either (s (Const (Maybe Text))) a))) -- | This is the function that should be called to construct a form for a -- record. It takes as input a Shaped formlet, a Shaped validation, title and -- attributes for the button, and the endpoint to which it should address the -- request for the server. It returns a dynamic value representing the state of -- the form in general, but also an event tracking the server response after a -- request. Internally, the function creates the widgets for input, runs the -- client-side validations, controls the communication via the endpoint. form :: ( Shaped a s , Code a ~ c, SListI2 c, c ~ '[c1] , MonadWidget t m , Code (s (Formlet t m)) ~ Map2 (Formlet t m) c , Code (s (Const (Maybe Text))) ~ Map2 (Const (Maybe Text)) c , Code (s (Either Text)) ~ Map2 (Either Text) c , Code (s Identity) ~ Map2 Identity c , Code (s (Validation (Either Text))) ~ Map2 (Validation (Either Text)) c , Code (s (Event t :.: Const (Maybe Text))) ~ Map2 (Event t :.: Const (Maybe Text)) c , Generic a , Generic (s (Event t :.: Const (Maybe Text))) , Generic (s (Formlet t m)) , Generic (s (Const (Maybe Text))) , Generic (s (Either Text)) , Generic (s (Validation (Either Text))) , Generic (s Identity)) => s (Formlet t m) -> s (Validation (Either Text)) -> Text -> Map.Map AttributeName Text -> Endpoint t m a s -> m ( Dynamic t (Either (s (Const (Maybe Text))) a) , Event t (Either Text (Either (s (Const (Maybe Text))) a)) ) form shapedWidget clientVal buttonTitle btnConfig endpoint = mdo postBuild <- getPostBuild -- Here I read a tentative user from the created interface rawUser <- createInterface send (splitShaped errorEvent) shapedWidget -- Here I define the button. This could probably be mixed with the button code send <- (formButton buttonTitle btnConfig) send (() <$ serverResponse) -- This part does the server request and parses back the response without -- depending on the types in servant-reflex serverResponse <- let query = either (const $ Left "Please fill correctly the fields above") Right <$> validationResult in (fmap . fmap) parseReqResult (endpoint query send) let -- Validation result is the rawUser ran through the validation validationResult = transfGen . flip validateRecord clientVal <$> rawUser validationErrorComponent = either id (const nullError) <$> validationResult -- Error event is the sum of the event from the form and that of the server errorEvent = leftmost [ updated validationErrorComponent , tagPromptlyDyn validationErrorComponent postBuild , formErrorFromServer ] -- Here we retrieve only the error from the server events formErrorFromServer = fst . fanEither . snd . fanEither $ serverResponse -- In the end, I return both the dynamic containing the event and the raw -- event signal from the server. Probably the type could be changed slightly here. -- display validationResult return (validationResult, serverResponse) -- | This function is only concerned with the creation of the visual widget. The -- first argument forces the error, the second argument is the event response -- from the server with an error, the third is the formlet per se. The functions -- return a dynamic of a (non validated) record. This is a function meant to be -- used internally. createInterface :: forall t m a s c c1 . ( Shaped a s, Code a ~ c, SListI2 c, c ~ '[c1] , MonadWidget t m , Code (s (Formlet t m)) ~ Map2 (Formlet t m) c , Code (s (Event t :.: Const (Maybe Text))) ~ Map2 (Event t :.: Const (Maybe Text)) c , Generic (s (Formlet t m)) , Generic (s (Event t :.: Const (Maybe Text))) , Generic a) => Event t () -> s (Event t :.: Const (Maybe Text)) -> s (Formlet t m) -> m (Dynamic t a) createInterface e shapedError shapedFormlet = unComp . fmap to . hsequence $ hzipWith (subFun e) a b where a :: POP (Event t :.: Const (Maybe Text)) c a = singleSOPtoPOP . fromSOPI $ from shapedError b :: SOP (Formlet t m) c b = fromSOPI $ from shapedFormlet -- | This function passes the actual arguments to the formlet. It's meant to be -- used internally in createInterface subFun :: MonadWidget t m => Event t () -> (Event t :.: Const (Maybe Text)) a -> Formlet t m a -> (m :.: Dynamic t) a subFun e (Comp a) (Formlet f) = Comp $ do let eventWithoutConst = getConst <$> a dynamicError <- holdDyn Nothing eventWithoutConst f e dynamicError -- | This function builds a button, which is disabled during the server requests -- (so that the user can't repeatedly submit before the server sent the previous -- response). formButton :: DomBuilder t m => Text -> Map.Map AttributeName Text -> Event t () -> Event t () -> m (Event t ()) formButton buttonTitle initialAttr disable enable = divClass "form-group" $ do (e, _) <- element "button" conf (text buttonTitle) return (domEvent Click e) where conf = def & elementConfig_initialAttributes .~ initialAttr & elementConfig_modifyAttributes .~ mergeWith (\_ b -> b) [ const disableAttr <$> disable , const enableAttr <$> enable ] disableAttr = fmap Just initialAttr <> "disabled" =: Just "true" enableAttr = fmap Just initialAttr <> "disabled" =: Nothing -- Either move this temporary in shaped with the intent of reporting that -- upstream, or define a synonym. Discuss this on the generics-sop tracker! instance (Applicative f, Applicative g) => Applicative (f :.: g) where pure x = Comp (pure (pure x)) Comp f <*> Comp x = Comp ((<*>) <$> f <*> x) -------------------------------------------------------------------------------- -- | Parse the response from the API, to not expose the users to the types in -- servant-reflex parseReqResult :: ReqResult a -> Either Text a parseReqResult (ResponseSuccess a _) = Right a parseReqResult (ResponseFailure t _) = Left t parseReqResult (RequestFailure s) = Left s --------------------------------------------------------------------------------- -- I begin understanding this as belonging to a simple sum, not SOP or POP -- | Create a blank error for a generic data type. nullError :: forall a s c c1. ( Shaped a s, Code a ~ c, c ~ '[c1], SListI2 c , Code (s (Const (Maybe Text))) ~ Map2 (Const (Maybe Text)) c , Generic (s (Const (Maybe Text)))) => s (Const (Maybe Text)) nullError = to . toSOPI -- . id @(SOP (Const (Maybe Text)) c) . singlePOPtoSOP . id @(POP (Const (Maybe Text)) c) $ hpure (Const Nothing)
meditans/shaped
src/Shaped/Reflex.hs
bsd-3-clause
8,282
0
23
1,968
2,155
1,090
1,065
103
1
module YandexDirect.Entity ( module YandexDirect.Entity.Core , module YandexDirect.Entity.Ad , module YandexDirect.Entity.AdExtension , module YandexDirect.Entity.AdGroup , module YandexDirect.Entity.Campaign , module YandexDirect.Entity.Dictionary , module YandexDirect.Entity.Keyword , module YandexDirect.Entity.SitelinksSet ) where import YandexDirect.Entity.Core import YandexDirect.Entity.Ad import YandexDirect.Entity.AdExtension import YandexDirect.Entity.AdGroup import YandexDirect.Entity.Campaign import YandexDirect.Entity.Dictionary import YandexDirect.Entity.Keyword import YandexDirect.Entity.SitelinksSet
effectfully/YandexDirect
src/YandexDirect/Entity.hs
bsd-3-clause
640
0
5
63
112
77
35
17
0
{-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- In the test suite, so OK module Main(main) where import Safe import Safe.Exact import qualified Safe.Foldable as F import Control.DeepSeq import Control.Exception import Control.Monad import Data.Char import Data.List import Data.Maybe import System.IO.Unsafe import Test.QuickCheck.Test import Test.QuickCheck hiding ((===)) --------------------------------------------------------------------- -- TESTS main :: IO () main = do -- All from the docs, so check they match tailMay dNil === Nothing tailMay [1,3,4] === Just [3,4] tailDef [12] [] === [12] tailDef [12] [1,3,4] === [3,4] tailNote "help me" dNil `err` "Safe.tailNote [], help me" tailNote "help me" [1,3,4] === [3,4] tailSafe [] === dNil tailSafe [1,3,4] === [3,4] findJust (== 2) [d1,2,3] === 2 findJust (== 4) [d1,2,3] `err` "Safe.findJust" F.findJust (== 2) [d1,2,3] === 2 F.findJust (== 4) [d1,2,3] `err` "Safe.Foldable.findJust" F.findJustDef 20 (== 4) [d1,2,3] === 20 F.findJustNote "my note" (== 4) [d1,2,3] `errs` ["Safe.Foldable.findJustNote","my note"] takeExact 3 [d1,2] `errs` ["Safe.Exact.takeExact","index=3","length=2"] takeExact (-1) [d1,2] `errs` ["Safe.Exact.takeExact","negative","index=-1"] takeExact 1 (takeExact 3 [d1,2]) === [1] -- test is lazy quickCheck_ $ \(Int10 i) (List10 (xs :: [Int])) -> do let (t,d) = splitAt i xs let good = length t == i let f name exact may note res = if good then do exact i xs === res note "foo" i xs === res may i xs === Just res else do exact i xs `err` ("Safe.Exact." ++ name ++ "Exact") note "foo" i xs `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"] may i xs === Nothing f "take" takeExact takeExactMay takeExactNote t f "drop" dropExact dropExactMay dropExactNote d f "splitAt" splitAtExact splitAtExactMay splitAtExactNote (t, d) return True take 2 (zipExact [1,2,3] [1,2]) === [(1,1),(2,2)] zipExact [d1,2,3] [d1,2] `errs` ["Safe.Exact.zipExact","first list is longer than the second"] zipExact [d1,2] [d1,2,3] `errs` ["Safe.Exact.zipExact","second list is longer than the first"] zipExact dNil dNil === [] predMay (minBound :: Int) === Nothing succMay (maxBound :: Int) === Nothing predMay ((minBound + 1) :: Int) === Just minBound succMay ((maxBound - 1) :: Int) === Just maxBound quickCheck_ $ \(List10 (xs :: [Int])) x -> do let ys = maybeToList x ++ xs let res = zip xs ys let f name exact may note = if isNothing x then do exact xs ys === res note "foo" xs ys === res may xs ys === Just res else do exact xs ys `err` ("Safe.Exact." ++ name ++ "Exact") note "foo" xs ys `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"] may xs ys === Nothing f "zip" zipExact zipExactMay zipExactNote f "zipWith" (zipWithExact (,)) (zipWithExactMay (,)) (`zipWithExactNote` (,)) return True take 2 (zip3Exact [1,2,3] [1,2,3] [1,2]) === [(1,1,1),(2,2,2)] zip3Exact [d1,2] [d1,2,3] [d1,2,3] `errs` ["Safe.Exact.zip3Exact","first list is shorter than the others"] zip3Exact [d1,2,3] [d1,2] [d1,2,3] `errs` ["Safe.Exact.zip3Exact","second list is shorter than the others"] zip3Exact [d1,2,3] [d1,2,3] [d1,2] `errs` ["Safe.Exact.zip3Exact","third list is shorter than the others"] zip3Exact dNil dNil dNil === [] quickCheck_ $ \(List10 (xs :: [Int])) x1 x2 -> do let ys = maybeToList x1 ++ xs let zs = maybeToList x2 ++ xs let res = zip3 xs ys zs let f name exact may note = if isNothing x1 && isNothing x2 then do exact xs ys zs === res note "foo" xs ys zs === res may xs ys zs === Just res else do exact xs ys zs `err` ("Safe.Exact." ++ name ++ "Exact") note "foo" xs ys zs `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"] may xs ys zs === Nothing f "zip3" zip3Exact zip3ExactMay zip3ExactNote f "zipWith3" (zipWith3Exact (,,)) (zipWith3ExactMay (,,)) (flip zipWith3ExactNote (,,)) return True --------------------------------------------------------------------- -- UTILITIES quickCheck_ prop = do r <- quickCheckResult prop unless (isSuccess r) $ error "Test failed" d1 = 1 :: Double dNil = [] :: [Double] (===) :: (Show a, Eq a) => a -> a -> IO () (===) a b = when (a /= b) $ error $ "Mismatch: " ++ show a ++ " /= " ++ show b err :: NFData a => a -> String -> IO () err a b = errs a [b] errs :: NFData a => a -> [String] -> IO () errs a bs = do res <- try $ evaluate $ rnf a case res of Right v -> error $ "Expected error, but succeeded: " ++ show bs Left (msg :: SomeException) -> forM_ bs $ \b -> do let s = show msg unless (b `isInfixOf` s) $ error $ "Invalid error string, got " ++ show s ++ ", want " ++ show b let f xs = " " ++ map (\x -> if sepChar x then ' ' else x) xs ++ " " unless (f b `isInfixOf` f s) $ error $ "Not standalone error string, got " ++ show s ++ ", want " ++ show b sepChar x = isSpace x || x `elem` ",;." newtype Int10 = Int10 Int deriving Show instance Arbitrary Int10 where arbitrary = fmap Int10 $ choose (-3, 10) newtype List10 a = List10 [a] deriving Show instance Arbitrary a => Arbitrary (List10 a) where arbitrary = do i <- choose (0, 10); fmap List10 $ vector i instance Testable a => Testable (IO a) where property = property . unsafePerformIO
ndmitchell/safe
Test.hs
bsd-3-clause
5,953
0
23
1,734
2,399
1,254
1,145
122
4
module Recommendations(recommendedMoviesFor) where import Data as Data(PersonName, title, name, rate, allItems, tryFindByName) import Utils as Utils(tryList, reverseBy, except, groupBy) recommendedMoviesFor :: PersonName -> (PersonName -> PersonName -> Either String Float) -> Either String [(String, Float)] recommendedMoviesFor pn simf = do titles <- map title <$> tryFindByName pn allItems otherItems <- tryList "Has not other users" $ ((except title titles) . (except name [pn])) allItems let groups = groupBy title otherItems rates <- mapM (calculate . summarize . titleize) groups return $ reverseBy snd rates where titleize items = (title $ head items, items) summarizeItem item = do sim <- simf pn $ name item return (sim, rate item * sim) summarize (title, items) = ((,) title) <$> mapM summarizeItem items calculate (Right (title, summaries)) = Right (title, total / simSum) where simSum = (sum . (map fst)) summaries total = (sum . (map snd)) summaries
vprokopchuk256/programming-collective-intelligence
src/Recommendations.hs
bsd-3-clause
1,108
0
14
289
393
205
188
20
1
module PreludeList ( map, (++), filter, concat, concatMap, head, last, tail, init, null, length, (!!), foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1, iterate, repeat, replicate, cycle, take, drop, splitAt, takeWhile, dropWhile, span, break, lines, words, unlines, unwords, reverse, and, or, any, all, elem, notElem, lookup, sum, product, maximum, mininum, zip, zip3, zipWith, zipWith3, unzip, unzip3 ) where import PreludeBase infixl 9 !! infixr 5 ++ infix 4 `elem`, `notElem` isSpace :: Char -> Bool isSpace x = x `elem` " \t\r\n" -- map and append map :: (a -> b) -> [a] -> [b] map f [] = [] map f (x:xs) = f x : map f xs (++) :: [a] -> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys = x : (xs ++ ys) filter :: (a -> Bool) -> [a] -> [a] filter p [] = [] filter p (x:xs) | p x = x : filter p xs | otherwise = filter p xs concat :: [[a]] -> [a] concat = foldr (++) [] concatMap :: (a -> [b]) -> [a] -> [b] concatMap f = concat . map f head :: [a] -> a head (x:_) = x head _ = error "Prelude.head: empty list" tail :: [a] -> [a] tail (_:xs) = xs tail _ = error "Prelude.tail: empty list" last :: [a] -> a last [x] = x last (_:xs) = last xs last [] = error "Prelude.last: empty list" init :: [a] -> [a] init [x] = [] init (x:xs) = x : init xs init [] = error "Prelude.init: empty list" null :: [a] -> Bool null [] = True null _ = False length :: [a] -> Int length [] = 0 length (_:xs) = 1 + length xs (!!) :: [a] -> Int -> a xs !! n | n < 0 = error "Prelude.!!: negative index" [] !! _ = error "Prelude.!!: empty list" (x:_) !! 0 = x (_:xs) !! n = xs !! (n - 1) foldl :: (a -> b -> a) -> a -> [b] -> a foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs foldl1 :: (a -> a -> a) -> [a] -> a foldl1 f (x:xs) = foldl f x xs foldl1 f [] = error "Prelude.foldl1: empty list" scanl :: (a -> b -> a) -> a -> [b] -> [a] scanl f q xs = q : (case xs of [] -> [] x : xs -> scanl f (f q x) xs) scanl1 :: (a -> a -> a) -> [a] -> [a] scanl1 f (x:xs) = scanl f x xs scanl1 _ [] = [] foldr :: (a -> b -> b) -> b -> [a] -> b foldr f v [] = v foldr f v (x:xs) = f x (foldr f v xs) foldr1 :: (a -> a -> a) -> [a] -> a foldr1 _ [x] = x foldr1 f (x:xs) = f x (foldr1 f xs) foldr1 _ [] = error "Prelude.foldr1: empty list" scanr :: (a -> b -> b) -> b -> [a] -> [b] scanr f q0 [] = [q0] scanr f q0 (x:xs) = f x q : qs where qs@(q:_) = scanr f q0 xs scanr1 :: (a -> a -> a) -> [a] -> [a] scanr1 f [] = [] scanr1 f [x] = [x] scanr1 f (x:xs) = f x q : qs where qs@(q:_) = scanr1 f xs iterate :: (a -> a) -> a -> [a] iterate f x = x : iterate f (f x) repeat :: a -> [a] repeat x = x : repeat x replicate :: Int -> a -> [a] replicate n = take n . repeat cycle :: [a] -> [a] cycle [] = error "Prelude.cycle: empty list" cycle xs = xs ++ cycle xs take :: Int -> [a] -> [a] take n _ | n <= 0 = [] take _ [] = [] take n (x:xs) = x : take (n - 1) xs drop :: Int -> [a] -> [a] drop n xs | n <= 0 = xs drop _ [] = [] drop n (_:xs) = drop (n - 1) xs splitAt :: Int -> [a] -> ([a], [a]) splitAt n xs = (take n xs, drop n xs) takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile p [] = [] takeWhile p (x:xs) | p x = x : takeWhile p xs | otherwise = [] dropWhile :: (a -> Bool) -> [a] -> [a] dropWhile p [] = [] dropWhile p (x:xs) | p x = dropWhile p xs | otherwise = xs span, break :: (a -> Bool) -> [a] -> ([a], [a]) span p [] = ([],[]) span p xs@(x:xs') | p x = (x:ys,zs) | otherwise = ([],xs) where (ys,zs) = span p xs' break p = span (not . p) lines :: String -> [String] lines [] = [] lines s = let (l, s') = break (== '\n') s in l : case s' of [] -> [] (_:s'') -> lines s'' words :: String -> [String] words s = case dropWhile isSpace s of "" -> [] s' -> w : words s'' where (w, s'') = break isSpace s' unlines :: [String] -> String unlines = concatMap (++ "\n") unwords :: [String] -> String unwords [] = [] unwords ws = foldr1 (\w s -> w ++ (' ':s)) ws reverse :: [a] -> [a] reverse = foldl (flip (:)) [] and, or :: [Bool] -> Bool and = foldr (&&) True or = foldr (||) False any, all :: (a -> Bool) -> [a] -> Bool any p = or . map p all p = and . map p elem, notElem :: Eq a => a -> [a] -> Bool elem x = any (== x) notElem x = all (/= x) lookup :: Eq a => a -> [(a,b)] -> Maybe b lookup key [] = Nothing lookup key ((x,y):xs) | x == key = Just y | otherwise = lookup key xs sum, product :: Num a => [a] -> a sum = foldr (+) 0 product = foldr (*) 1 maximum, minimum :: Ord a => [a] -> a maximum [] = error "Prelude.maximum: empty list" maximum xs = foldr1 max xs minimum [] = error "Prelude.minimum: empty list" minimum xs = foldr1 min xs zip :: [a] -> [b] -> [(a,b)] zip = zipWith (\a b -> (a,b)) zip3 :: [a] -> [b] -> [c] -> [(a,b,c)] zip3 = zipWith3 (\a b c -> (a,b,c)) zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith f (a:as) (b:bs) = f a b : zipWith f as bs zipWith _ _ _ = [] zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d] zipWith3 f (a:as) (b:bs) (c:cs) = f a b c : zipWith3 f as bs cs zipWith3 _ _ _ _ = [] unzip :: [(a,b)] -> ([a],[b]) unzip = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([],[]) unzip3 :: [(a,b,c)] -> ([a],[b],[c]) unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as, b:bs, c:cs)) ([],[],[]) instance Eq a => Eq [a] where [] == [] = True (x:xs) == (y:ys) = (x == y) && (xs == ys) _ == _ = False sequence :: Monad m => [m a] -> m [a] sequence ms = foldr k (return []) ms where k m m' = do { x <- m; xs <- m'; return (x:xs) } sequence_ :: Monad m => [m a] -> m () sequence_ = foldr (>>) (return ()) mapM :: Monad m => (a -> m b) -> [a] -> m [b] mapM f = sequence . map f mapM_ :: Monad m => (a -> m b) -> [a] -> m () mapM_ f = sequence_ . map f
rodrigogribeiro/mptc
test/Data/Full/PreludeList.hs
bsd-3-clause
6,265
0
12
2,052
3,772
2,026
1,746
184
2
#!/usr/bin/env runhaskell {-# LANGUAGE OverloadedStrings #-} module Main where import Control.Concurrent (threadDelay) import Control.Concurrent.MVar (MVar (..), putMVar, takeMVar) import Control.Exception (tryJust) import Control.Monad (forever, guard) import qualified Data.ByteString.Lazy as BS import System.Environment (getArgs) import System.Exit (exitFailure, exitSuccess) import System.IO (IOMode (ReadMode), SeekMode (AbsoluteSeek), hPutStrLn, hSeek, openFile, stderr) import System.IO.Error (isDoesNotExistError) import System.Posix.Files (fileSize, getFileStatus) -- some type aliases for readability type FilePosition = Integer type MicroSeconds = Int -- TODO: Implement `tail -F` behavior -- streamLines is `tail -f` -- |Tail a file, sending complete lines to the passed-in IO function. -- If the file disappears, streamLines will return, and the function will be -- called one final time with a Left. streamLines :: FilePath -> FilePosition -- ^ Position in the file to start reading at. Very likely -- you want to pass 0. -> MicroSeconds -- ^ delay between each check of the file in microseconds -> (Either String BS.ByteString -> IO ()) -- ^ function to be called with -- each new complete line -> IO () streamLines path sizeSoFar delay callback = go sizeSoFar where go sizeSoFar = do threadDelay delay errorOrStat <- tryJust (guard . isDoesNotExistError) $ getFileStatus path case errorOrStat of Left e -> callback $ Left "File does not exist" Right stat -> do let newSize = fromIntegral $ fileSize stat :: Integer if newSize > sizeSoFar then do handle <- openFile path ReadMode hSeek handle AbsoluteSeek sizeSoFar newContents <- BS.hGetContents handle let lines = BS.splitWith (==10) newContents let startNext = newSize - (toInteger $ BS.length $ last lines) mapM_ (callback . Right) $ init lines go startNext else do go sizeSoFar usage = "usage: tailf file" tailCallback :: Either String BS.ByteString -> IO () tailCallback (Left e) = do hPutStrLn stderr "aborting: file does not exist" exitFailure tailCallback (Right line) = do BS.putStr line BS.putStr $ BS.singleton 10 main = do args <- getArgs case args of [] -> do putStrLn usage exitFailure ["-h"] -> do putStrLn usage exitSuccess ["--help"] -> do putStrLn usage exitSuccess [path] -> do streamLines path 0 1000000 tailCallback
radix/json-log-viewer
src/Messin.hs
mit
2,922
0
24
959
635
328
307
63
4
{-# LANGUAGE TemplateHaskell #-} module Number.Float.Data where import Prelude hiding ( exponent ) import qualified Number.Base.Data as B import Number.Wert import Autolib.Reader import Autolib.ToDoc import Autolib.Reporter import Autolib.Size import Data.Ratio import Data.Typeable ------------------------------------------------------------------- data Signed a = Signed { negative :: Bool , contents :: a } deriving ( Typeable ) instance ( Num b, Wert_at a b ) => Wert_at (Signed a) b where wert_at b s = ( if negative s then negate else id ) $ wert_at b $ contents s instance Size a => Size (Signed a) where size s = size (contents s) instance ( ToDoc a, B.Range a ) => B.Range ( Signed a ) where range b s = silent $ do inform $ fsep [ text "teste Ziffern von", toDoc s , text "bezüglich Basis", toDoc b ] nested 4 $ B.range b $ contents s instance ToDoc a => ToDoc (Signed a) where toDoc s = ( if negative s then Autolib.ToDoc.char '-' else empty ) <> toDoc ( contents s ) instance Reader a => Reader (Signed a) where reader = do sign <- option False $ do Autolib.Reader.char '+' ; my_whiteSpace ; return False <|> do Autolib.Reader.char '-' ; my_whiteSpace ; return True c <- reader return $ Signed { negative = sign, contents = c } ------------------------------------------------------------------- data Natural = Natural { ziffern :: [ B.Ziffer ] } deriving Typeable instance Wert_at Natural Integer where wert_at b n = wert_at b $ ziffern n instance Size Natural where size n = length $ ziffern n instance B.Range Natural where range b n = silent $ do inform $ fsep [ text "teste Ziffern von", toDoc n , text "bezüglich Basis", toDoc b ] nested 4 $ B.range b $ ziffern n instance ToDoc Natural where toDoc n = hcat $ map toDoc $ ziffern n instance Reader Natural where reader = do zs <- many reader return $ Natural { ziffern = zs } ------------------------------------------------------------------- -- | where "decimal" point is mandatory data Fixed = Fixed { pre :: Natural , post :: Natural } deriving ( Typeable ) instance Wert_at Fixed Rational where wert_at b f = let we, wo :: Integer we = wert_at b $ pre f wo = wert_at b $ post f in fromIntegral we + wo % fromIntegral b ^ (length $ ziffern $ post f) instance Size Fixed where size f = size (pre f) + size (post f) instance B.Range Fixed where range b f = silent $ do inform $ fsep [ text "teste Ziffern von", toDoc f , text "bezüglich Basis", toDoc b ] nested 4 $ B.range b $ pre f nested 4 $ B.range b $ post f instance ToDoc Fixed where toDoc f = hcat [ toDoc $ pre f , Autolib.ToDoc.char '.' , toDoc $ post f ] instance Reader Fixed where reader = do e <- reader Autolib.Reader.char '.' o <- reader return $ Fixed { pre = e, post = o } ------------------------------------------------------------------- data Zahl = Zahl { basis :: Int , mantisse :: Signed Fixed , exponent :: Signed Natural } deriving ( Typeable ) example :: Zahl example = Zahl { basis = 2 , mantisse = read "1.01" , exponent = read "-10" } instance Wert Zahl Rational where wert z = let b :: Int b = basis z wm :: Rational wm = wert_at b $ mantisse z we :: Integer we = wert_at b $ exponent z in wm * fromIntegral b ^^ we instance B.Range Zahl where range b z = do B.range b $ mantisse z B.range b $ exponent z instance Size Zahl where size z = size ( mantisse z ) + size ( exponent z ) $(derives [makeReader, makeToDoc] [''Zahl]) ist_normalisiert :: Zahl -> Bool ist_normalisiert z = case ziffern $ pre $ contents $ mantisse z of [ x ] | x > B.Ziffer 0 -> True otherwise -> let zero z = all ( == B.Ziffer 0 ) $ ziffern z in all zero [ pre $ contents $ mantisse z , post $ contents $ mantisse z , contents $ exponent z ] -- Local Variables: -- mode:haskell -- End:
florianpilz/autotool
src/Number/Float/Data.hs
gpl-2.0
4,483
12
16
1,465
1,493
751
742
-1
-1
#!/usr/bin/runhaskell {-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE ScopedTypeVariables #-} module Preprocessor (preprocessAll) where import Control.Exception(catch, evaluate) import Data.List(isInfixOf) import FileHandler import Interface.Args import CommandGenerator import Directive.Identifier import Directive.Parser import Interface.Errors preprocessAll :: SPPOpts -> [BackedUpFile] -> IO [Either SPPError ()] preprocessAll _ [] = return [] preprocessAll opts (x:xs) = do c <- preprocess opts ToPreprocess {current=x,future=xs, depChain=[]} rest <- preprocessAll opts xs return $ c:rest {- An IO Action for either processing a file or producing an error without doing anything -} preprocess :: SPPOpts -> ToPreprocess -> IO (Either SPPError ()) preprocess sppopts buFile = do output sppopts Verbose $ "Output File = " ++ outputFile (current buFile) ++ "\n" -- Ignore the possibility of error at this line. mcontents <- fmap Right (readFile (backupFile . current $ buFile) >>= evaluate) `catch` (return . Left :: IOError -> IO (Either IOError String)) output sppopts Debug $ "Received output = "++ show mcontents ++ "\n" case mcontents of (Left err) | isBinaryError err -> return $ Right () | otherwise -> return $ Left $ sppError ReadIOError (sourceFile . current $ buFile) Nothing err (Right contents) -> do -- There should be no error at this line given that process should throw no error outp <- process sppopts buFile contents case outp of SPPFailure err -> return $ Left err SPPSuccess outputValue -> Right <$> writeFile (outputFile . current $ buFile) (fContents outputValue) isBinaryError :: IOError -> Bool isBinaryError err = "hGetContents: invalid argument (invalid byte sequence)" `isInfixOf` show err performCommands :: SPPOpts -> ToPreprocess -> Directives Command -> IO PreprocessorResult performCommands opts buf (Directives header commands rest) = do output opts Debug $ "Directives =" ++ show (Directives header commands rest) ++ "\n" result <- performAll actions $ SPPState {cFile=current buf, fContents=rest, dependencyChain=depChain buf, possibleFiles=future buf} output opts Debug $ "Result = " ++ show result ++ "\n" return $ mapOverSuccess (mapOverContents (header ++)) result where actions = map (getCommand (preprocess opts) $ current buf) commands {- Creates an IO instance for preprocessing a series of lines. -} process :: SPPOpts -> ToPreprocess -> String -> IO PreprocessorResult process sppopts buf str = either (return . SPPFailure) id result where result :: Either SPPError (IO PreprocessorResult) result = performCommands sppopts buf <$> parseDirectives (directiveStart sppopts) (sourceFile . current $ buf) str {- Perform all the actions in the given list of actions. If any of the values are `Left` errors, the entire result is an error. Otherwise, the result is considered to be all the other actions chained together -} performAll :: [Action] -> Action performAll = foldr comp (return . SPPSuccess) where comp :: Action -> Action -> Action comp g f x = g x >>= \u -> case u of (SPPSuccess y) -> f y (SPPFailure z) -> return $ SPPFailure z
kavigupta/SimplePreprocessor
src/Preprocessor.hs
gpl-3.0
3,529
0
19
915
933
470
463
56
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.IAM.DeleteInstanceProfile -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes the specified instance profile. The instance profile must not -- have an associated role. -- -- Make sure you do not have any Amazon EC2 instances running with the -- instance profile you are about to delete. Deleting a role or instance -- profile that is associated with a running instance will break any -- applications running on the instance. -- -- For more information about instance profiles, go to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html About Instance Profiles>. -- -- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteInstanceProfile.html AWS API Reference> for DeleteInstanceProfile. module Network.AWS.IAM.DeleteInstanceProfile ( -- * Creating a Request deleteInstanceProfile , DeleteInstanceProfile -- * Request Lenses , dipInstanceProfileName -- * Destructuring the Response , deleteInstanceProfileResponse , DeleteInstanceProfileResponse ) where import Network.AWS.IAM.Types import Network.AWS.IAM.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'deleteInstanceProfile' smart constructor. newtype DeleteInstanceProfile = DeleteInstanceProfile' { _dipInstanceProfileName :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteInstanceProfile' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dipInstanceProfileName' deleteInstanceProfile :: Text -- ^ 'dipInstanceProfileName' -> DeleteInstanceProfile deleteInstanceProfile pInstanceProfileName_ = DeleteInstanceProfile' { _dipInstanceProfileName = pInstanceProfileName_ } -- | The name of the instance profile to delete. dipInstanceProfileName :: Lens' DeleteInstanceProfile Text dipInstanceProfileName = lens _dipInstanceProfileName (\ s a -> s{_dipInstanceProfileName = a}); instance AWSRequest DeleteInstanceProfile where type Rs DeleteInstanceProfile = DeleteInstanceProfileResponse request = postQuery iAM response = receiveNull DeleteInstanceProfileResponse' instance ToHeaders DeleteInstanceProfile where toHeaders = const mempty instance ToPath DeleteInstanceProfile where toPath = const "/" instance ToQuery DeleteInstanceProfile where toQuery DeleteInstanceProfile'{..} = mconcat ["Action" =: ("DeleteInstanceProfile" :: ByteString), "Version" =: ("2010-05-08" :: ByteString), "InstanceProfileName" =: _dipInstanceProfileName] -- | /See:/ 'deleteInstanceProfileResponse' smart constructor. data DeleteInstanceProfileResponse = DeleteInstanceProfileResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteInstanceProfileResponse' with the minimum fields required to make a request. -- deleteInstanceProfileResponse :: DeleteInstanceProfileResponse deleteInstanceProfileResponse = DeleteInstanceProfileResponse'
fmapfmapfmap/amazonka
amazonka-iam/gen/Network/AWS/IAM/DeleteInstanceProfile.hs
mpl-2.0
3,794
0
9
679
372
231
141
52
1
module Text.HTML.TagSoup2.Str(module Text.StringLike) where import Text.StringLike data Pos str = Pos Position str instance StringLike str => StringLike (Pos str) where position :: Tag (Position str) -> Tag str position = undefined
ndmitchell/tagsoup
src/Text/HTML/TagSoup2/Str.hs
bsd-3-clause
239
0
8
39
80
44
36
6
1
-- dets.hs -- bugs from the Erlang's dets library -- -- Copyright (c) 2017-2020 Rudy Matela. -- Distributed under the 3-Clause BSD licence (see the file LICENSE). -- -- -- In 2016, John Hughes wrote a paper titled: -- -- "Experiences with QuickCheck: Testing the Hard Stuff And Staying Sane" -- -- http://publications.lib.chalmers.se/records/fulltext/232550/local_232550.pdf -- -- In it, among other things, he describes how he used QuviQ QuickCheck to find -- 5 bugs in Erlang's dets library which were "open problems" at the time. -- -- -- Fastforward to my PhD exam in 2017 (Rudy), John Hughes, one of my examiners -- challenged me to use LeanCheck to try to find one of the bugs of Erlang's -- dets library which he thought would be unreachable by LeanCheck. -- -- Unreachable above means appearing too late in the enumeration to be able -- to practially reach it. -- -- Turns out Hughes was right, LeanCheck runs out of memory before reaching the -- bug. -- -- -- This is a reconstruction of the program written during my PhD exam -- (2017-11-24). -- -- This program does not really test the dets library directly, but merely -- pattern matches the bug. So the dummy property under test returns False for -- the specific bug we're looking for. -- -- -- This version seaches for the 5 bugs found by QuickCheck described in Hughes' -- paper. It is able to find 2 of these 5. We run out of memory before being -- able to reach the other 3. -- -- By cheating a bit, we can increase bugs found to 3, -- but 2 are then still out of reach. -- -- -- Dets library online manual: http://erlang.org/doc/man/dets.html import Test.LeanCheck -- For simplicity, we only stick ourselves with 3 different possible database -- names data Name = A | B | C deriving (Eq, Ord, Show, Read) type Key = Int type Value = Int type Object = (Key, Value) -- The most important operations in Erlang's dets. data Op = All -- all() -> [tab_name()] | Close Name -- close(Name) | Delete Name Key -- delete(Name, Key) | DeleteAllObjects Name -- delete_all_objects(Name) -- | First Name -- first(Name) -> Key | Insert Name [Object] -- insert(Name, Objects) | InsertNew Name [Object] -- insert_new(Name, Objects) -> boolean() | Lookup Name Key -- lookup(Name, Key) -> Objects | Member Name Key -- member(Name, Key) -> boolean() -- | Next Name Key -- next(Name, Key) -> boolean() | Open Name -- open_file(...) | GetContents Name -- get_contents(Name) -> Objects deriving (Eq, Ord, Show, Read) -- NOTE: I couldn't find get_contents on the dets documentation, but it is listed on Hughes paper -- as one of the operations. Perhaps he implemented it using first and next. -- NOTE (2): I am admittedly cheating a bit -- by ommiting First and Next in -- place of GetContents. -- A Program has a prefix and a parallel section that follows immediately data Program = Program [Op] [[Op]] deriving (Eq, Ord, Show, Read) instance Listable Name where list = [A, B, C] -- This is an unoptimized generator as it will generate invalid programs like: -- -- Program [Close A, Lookup B 0] [] instance Listable Op where tiers = cons0 All \/ cons1 Close \/ cons2 Delete \/ cons1 DeleteAllObjects -- \/ cons1 First \/ cons2 Insert \/ cons2 InsertNew \/ cons2 Lookup \/ cons2 Member -- \/ cons2 Next \/ cons1 Open \/ cons1 GetContents instance Listable Program where tiers = cons2 Program -- open(a) -- -------------|----------------- -- insert(a,[]) | insert_new(a,[]) bug1 :: Program bug1 = Program [Open A] -- initialization [ [Insert A []] -- thread 1 , [InsertNew A []] -- thread 2 ] -- open(a) -- ----------------|--------------------- -- insert(a,{0,0}) | insert_new(a,{0,0}) bug2 :: Program bug2 = Program [Open A] [ [Insert A [(0,0)]] , [InsertNew A [(0,0)]] ] -- open(a) -- --------|---------------- -- open(a) | insert(a,{0,0}) -- | get_contents(a) bug3 :: Program bug3 = Program [Open A] [ [Open A] , [ Insert A [(0,0)] , GetContents A ] ] -- This was the one John Hughes originally -- challenged me to find using LeanCheck -- after my PhD examination. (Rudy, 2017) bug4 :: Program bug4 = Program [ Open A , Close A , Open A ] [ [Lookup A 0] , [Insert A [(0,0)]] , [Insert A [(0,0)]] ] bug5 :: Program bug5 = Program [ Open A , Insert A [(1,0)] ] [ [ Lookup A 0 , Delete A 1 ] , [Open A] ] prop1, prop2, prop3, prop4, prop5 :: Program -> Bool prop1 p = p /= bug1 prop2 p = p /= bug2 prop3 p = p /= bug3 prop4 p = p /= bug4 prop5 p = p /= bug5 main :: IO () main = do checkFor 200000 prop1 -- bug found after 88 410 tests checkFor 4000000 prop2 -- bug found after 2 044 950 tests checkFor 2000000 prop3 -- bug not found, more tests and we go out of memory... checkFor 2000000 prop4 -- bug not found, more tests and we go out of memory... checkFor 2000000 prop5 -- bug not found, more tests and we go out of memory... -- If I recall correcly, John Hughes mentioned that each test took 3 seconds to -- run. That means LeanCheck would find the first bug after 3 days, and the -- second bug after 2 months. This could be improved if we cheat by removing -- some of the uneeded operations in our Program datatype. -- -- 1. Supposing we drop the "All" and "DeleteAllObjects" operation: -- -- * bug 1 is found after 18 580 tests -- * bug 3 is found after 300 104 tests -- * bug 3 is found after 1 204 421 tests -- * bugs 4 and 5 are not found -- -- 2. Supposing we just allow a single database name "A" -- -- * bug 1 is found after 10 651 tests -- * bug 3 is found after 144 852 tests -- * bug 3 is found after 534 550 tests -- * bugs 4 and 5 are not found -- -- Other improvements are possible: -- -- * generating a set of parallel programs instead of a list as the order does -- not matter (we would have to change the Program comparison function -- accordingly) -- -- * only generating valid programs (we only operate on A after open'ing it) -- -- * generating a set of operations, then from that generate a set of programs -- with these operations -- -- But I conjecture bugs 4 and 5 will be simply out of reach anyway.
rudymatela/llcheck
bench/dets.hs
bsd-3-clause
6,570
0
15
1,711
873
527
346
77
1
-- |Binary instances for images. Currently it only supports the type -- `Image Grayscale D32`. {-#LANGUAGE ScopedTypeVariables, FlexibleInstances#-} module CV.Binary where import CV.Image (Image,GrayScale,D32) import CV.Conversions import Data.Maybe (fromJust) import Data.Binary import Data.Array.CArray import Data.Array.IArray -- NOTE: This binary instance is NOT PORTABLE.   instance Binary (Image GrayScale D32) where put img = do let arr :: CArray (Int,Int) Double = copyImageToCArray img put (bounds arr) put . unsafeCArrayToByteString $ arr get = do bds <- get get >>= return . copyCArrayToImage . fromJust . unsafeByteStringToCArray bds
BeautifulDestinations/CV
CV/Binary.hs
bsd-3-clause
726
0
13
167
167
89
78
16
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} module Main (main) where import Control.Monad (join) import Control.Monad.Reader (ReaderT(..)) import Control.Concurrent.STM (STM, atomically) import Data.Kind (Type) class Monad (Transaction m) => MonadPersist m where type Transaction m :: Type -> Type atomicTransaction :: Transaction m y -> m y instance MonadPersist (ReaderT () IO) where type Transaction (ReaderT () IO) = ReaderT () STM atomicTransaction act = ReaderT (atomically . runReaderT act) main :: IO () main = join (runReaderT doPure2 ()) >>= \x -> seq x (return ()) doPure2 :: MonadPersist m => m (IO ()) doPure2 = atomicTransaction $ do () <- pure () () <- pure () error "exit never happens"
sdiehl/ghc
testsuite/tests/simplCore/should_run/T16066.hs
bsd-3-clause
778
0
10
137
292
152
140
-1
-1