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 DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
--------------------------------------------------------------------------------
-- |
-- Module : Network.MQTT.Message
-- Copyright : (c) Lars Petersen 2016
-- License : MIT
--
-- Maintainer : info@lars-petersen.net
-- Stability : experimental
--------------------------------------------------------------------------------
module Network.MQTT.Message (
-- * Message
Message (..)
, module Network.MQTT.Message.Topic
-- ** QoS
, QoS (..)
-- ** Retain
, Retain (..)
-- ** Payload
, Payload (..)
-- * Packet
-- ** ClientPacket
, ClientPacket (..)
, clientPacketBuilder
, clientPacketParser
-- ** ServerPacket
, ServerPacket (..)
, serverPacketBuilder
, serverPacketParser
-- ** PacketIdentifier
, PacketIdentifier (..)
-- ** ClientIdentifier
, ClientIdentifier (..)
-- ** Username
, Username (..)
-- ** Password
, Password (..)
-- ** CleanSession
, CleanSession (..)
-- ** SessionPresent
, SessionPresent (..)
-- ** RejectReason
, RejectReason (..)
-- ** Duplicate
, Duplicate (..)
-- ** KeepAliveInterval
, KeepAliveInterval (..)
-- * Other (internal) exports
, lengthParser
, lengthBuilder
, utf8Parser
, utf8Builder
) where
import Control.Monad
import qualified Data.Attoparsec.ByteString as A
import qualified Data.Binary as B
import qualified Data.Binary.Get as SG
import Data.Bits
import Data.Bool
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as BS
import qualified Data.ByteString.Lazy as BSL
import Data.Monoid
import Data.String
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Word
import GHC.Generics
import Network.MQTT.Message.QoS
import Network.MQTT.Message.Topic
import qualified Network.MQTT.Message.Topic as TF
newtype SessionPresent = SessionPresent Bool deriving (Eq, Ord, Show, Generic)
newtype CleanSession = CleanSession Bool deriving (Eq, Ord, Show, Generic)
newtype Retain = Retain Bool deriving (Eq, Ord, Show, Generic)
newtype Payload = Payload BSL.ByteString deriving (Eq, Ord, Show, Generic, IsString)
newtype Duplicate = Duplicate Bool deriving (Eq, Ord, Show, Generic)
newtype KeepAliveInterval = KeepAliveInterval Word16 deriving (Eq, Ord, Show, Generic, Num)
newtype Username = Username T.Text deriving (Eq, Ord, Show, IsString, Generic)
newtype Password = Password BS.ByteString deriving (Eq, Generic)
newtype ClientIdentifier = ClientIdentifier T.Text deriving (Eq, Ord, Show, IsString, Generic)
newtype PacketIdentifier = PacketIdentifier Int deriving (Eq, Ord, Show, Generic)
instance Show Password where
show = const "*********"
instance B.Binary ClientIdentifier
instance B.Binary Username
instance B.Binary Message
instance B.Binary Retain
instance B.Binary Payload
data RejectReason
= UnacceptableProtocolVersion
| IdentifierRejected
| ServerUnavailable
| BadUsernameOrPassword
| NotAuthorized
deriving (Eq, Ord, Show, Enum, Bounded)
data Message
= Message
{ msgTopic :: !TF.Topic
, msgQoS :: !QoS
, msgRetain :: !Retain
, msgPayload :: !Payload
} deriving (Eq, Ord, Show, Generic)
data ClientPacket
= ClientConnect
{ connectClientIdentifier :: !ClientIdentifier
, connectCleanSession :: !CleanSession
, connectKeepAlive :: !KeepAliveInterval
, connectWill :: !(Maybe Message)
, connectCredentials :: !(Maybe (Username, Maybe Password))
}
| ClientConnectUnsupported
| ClientPublish {-# UNPACK #-} !PacketIdentifier !Duplicate !Message
| ClientPublishAcknowledged {-# UNPACK #-} !PacketIdentifier
| ClientPublishReceived {-# UNPACK #-} !PacketIdentifier
| ClientPublishRelease {-# UNPACK #-} !PacketIdentifier
| ClientPublishComplete {-# UNPACK #-} !PacketIdentifier
| ClientSubscribe {-# UNPACK #-} !PacketIdentifier ![(TF.Filter, QoS)]
| ClientUnsubscribe {-# UNPACK #-} !PacketIdentifier ![TF.Filter]
| ClientPingRequest
| ClientDisconnect
deriving (Eq, Show)
data ServerPacket
= ServerConnectionAccepted !SessionPresent
| ServerConnectionRejected !RejectReason
| ServerPublish {-# UNPACK #-} !PacketIdentifier !Duplicate !Message
| ServerPublishAcknowledged {-# UNPACK #-} !PacketIdentifier
| ServerPublishReceived {-# UNPACK #-} !PacketIdentifier
| ServerPublishRelease {-# UNPACK #-} !PacketIdentifier
| ServerPublishComplete {-# UNPACK #-} !PacketIdentifier
| ServerSubscribeAcknowledged {-# UNPACK #-} !PacketIdentifier ![Maybe QoS]
| ServerUnsubscribeAcknowledged {-# UNPACK #-} !PacketIdentifier
| ServerPingResponse
deriving (Eq, Show)
clientPacketParser :: SG.Get ClientPacket
clientPacketParser =
SG.lookAhead SG.getWord8 >>= \h-> case h .&. 0xf0 of
0x10 -> connectParser
0x30 -> publishParser ClientPublish
0x40 -> acknowledgedParser ClientPublishAcknowledged
0x50 -> acknowledgedParser ClientPublishReceived
0x60 -> acknowledgedParser ClientPublishRelease
0x70 -> acknowledgedParser ClientPublishComplete
0x80 -> subscribeParser
0xa0 -> unsubscribeParser
0xc0 -> pingRequestParser
0xe0 -> disconnectParser
_ -> fail "clientPacketParser: Invalid message type."
serverPacketParser :: SG.Get ServerPacket
serverPacketParser =
SG.lookAhead SG.getWord8 >>= \h-> case h .&. 0xf0 of
0x20 -> connectAcknowledgedParser
0x30 -> publishParser ServerPublish
0x40 -> acknowledgedParser ServerPublishAcknowledged
0x50 -> acknowledgedParser ServerPublishReceived
0x60 -> acknowledgedParser ServerPublishRelease
0x70 -> acknowledgedParser ServerPublishComplete
0xb0 -> acknowledgedParser ServerUnsubscribeAcknowledged
0x90 -> subscribeAcknowledgedParser
0xd0 -> pingResponseParser
_ -> fail "serverPacketParser: Packet type not implemented."
connectParser :: SG.Get ClientPacket
connectParser = do
h <- SG.getWord8
when (h .&. 0x0f /= 0) $
fail "connectParser: The header flags are reserved and MUST be set to 0."
void lengthParser -- the remaining length is redundant in this packet type
y <- SG.getWord64be -- get the next 8 bytes all at once and not byte per byte
case y .&. 0xffffffffffffff00 of
0x00044d5154540400 -> do
let cleanSession = CleanSession ( y .&. 0x02 /= 0 )
let retain = Retain ( y .&. 0x20 /= 0 )
keepAlive <- KeepAliveInterval <$> SG.getWord16be
cid <- ClientIdentifier <$> utf8Parser
will <- if y .&. 0x04 == 0
then pure Nothing
else Just <$> do
topic <- fst <$> topicAndLengthParser
bodyLen <- fromIntegral <$> SG.getWord16be
payload <- Payload <$> SG.getLazyByteString bodyLen
qos <- case y .&. 0x18 of
0x00 -> pure QoS0
0x08 -> pure QoS1
0x10 -> pure QoS2
_ -> fail "connectParser: Violation of [MQTT-3.1.2-14]."
pure $ Message topic qos retain payload
cred <- if y .&. 0x80 == 0
then pure Nothing
else Just <$> ( (,)
<$> (Username <$> utf8Parser)
<*> if y .&. 0x40 == 0
then pure Nothing
else Just . Password <$> (SG.getByteString . fromIntegral =<< SG.getWord16be) )
pure ( ClientConnect cid cleanSession keepAlive will cred )
-- This is the prefix of the version 3 protocol.
-- We just assume that this is version 3 and return immediately.
-- The caller shall send return code 0x01 (unacceptable protocol).
0x00064d5149736400 -> pure ClientConnectUnsupported
-- This case is different from the previous as it is either not
-- MQTT or a newer protocol version we don't know (yet).
-- The caller shall close the connection immediately without
-- sending any data in this case.
_ -> fail "connectParser: Unexpected protocol initialization."
connectAcknowledgedParser :: SG.Get ServerPacket
connectAcknowledgedParser = do
x <- SG.getWord32be
case x .&. 0xff of
0 -> pure $ ServerConnectionAccepted $ SessionPresent (x .&. 0x0100 /= 0)
1 -> pure $ ServerConnectionRejected UnacceptableProtocolVersion
2 -> pure $ ServerConnectionRejected IdentifierRejected
3 -> pure $ ServerConnectionRejected ServerUnavailable
4 -> pure $ ServerConnectionRejected BadUsernameOrPassword
5 -> pure $ ServerConnectionRejected NotAuthorized
_ -> fail "connectAcknowledgedParser: Invalid (reserved) return code."
publishParser :: (PacketIdentifier -> Duplicate -> Message -> a) -> SG.Get a
publishParser publish = do
hflags <- SG.getWord8
let dup = Duplicate $ hflags .&. 0x08 /= 0 -- duplicate flag
let ret = Retain $ hflags .&. 0x01 /= 0 -- retain flag
len <- lengthParser
(topic, topicLen) <- topicAndLengthParser
let qosBits = hflags .&. 0x06
if qosBits == 0x00
then do
body <- SG.getLazyByteString $ fromIntegral ( len - topicLen )
pure $ publish (PacketIdentifier (-1)) dup Message {
msgTopic = topic
, msgPayload = Payload body
, msgQoS = QoS0
, msgRetain = ret
}
else do
let qos = if qosBits == 0x02 then QoS1 else QoS2
pid <- PacketIdentifier . fromIntegral <$> SG.getWord16be
body <- SG.getLazyByteString $ fromIntegral ( len - topicLen - 2 )
pure $ publish pid dup Message {
msgTopic = topic
, msgPayload = Payload body
, msgQoS = qos
, msgRetain = ret
}
acknowledgedParser :: (PacketIdentifier -> a) -> SG.Get a
acknowledgedParser f = do
w32 <- SG.getWord32be
pure $ f $ PacketIdentifier $ fromIntegral $ w32 .&. 0xffff
{-# INLINE acknowledgedParser #-}
subscribeParser :: SG.Get ClientPacket
subscribeParser = do
void SG.getWord8
rlen <- lengthParser
pid <- PacketIdentifier . fromIntegral <$> SG.getWord16be
ClientSubscribe pid <$> parseFilters (rlen - 2) []
where
parseFilters r accum
| r <= 0 = pure (reverse accum)
| otherwise = do
(filtr,len) <- filterAndLengthParser
qos <- getQoS
parseFilters ( r - 1 - len ) ( ( filtr, qos ) : accum )
getQoS = SG.getWord8 >>= \w-> case w of
0x00 -> pure QoS0
0x01 -> pure QoS1
0x02 -> pure QoS2
_ -> fail "clientSubscribeParser: Violation of [MQTT-3.8.3-4]."
unsubscribeParser :: SG.Get ClientPacket
unsubscribeParser = do
void SG.getWord8
rlen <- lengthParser
pid <- PacketIdentifier . fromIntegral <$> SG.getWord16be
ClientUnsubscribe pid <$> parseFilters (rlen - 2) []
where
parseFilters r accum
| r <= 0 = pure (reverse accum)
| otherwise = do
(filtr,len) <- filterAndLengthParser
parseFilters ( r - len ) ( filtr : accum )
subscribeAcknowledgedParser :: SG.Get ServerPacket
subscribeAcknowledgedParser = do
void SG.getWord8
rlen <- lengthParser
pid <- PacketIdentifier . fromIntegral <$> SG.getWord16be
ServerSubscribeAcknowledged pid <$> (map f . BS.unpack <$> SG.getByteString (rlen - 2))
where
f 0x00 = Just QoS0
f 0x01 = Just QoS1
f 0x02 = Just QoS2
f _ = Nothing
pingRequestParser :: SG.Get ClientPacket
pingRequestParser = do
void SG.getWord16be
pure ClientPingRequest
{-# INLINE pingRequestParser #-}
pingResponseParser :: SG.Get ServerPacket
pingResponseParser = do
void SG.getWord16be
pure ServerPingResponse
{-# INLINE pingResponseParser #-}
disconnectParser :: SG.Get ClientPacket
disconnectParser = do
void SG.getWord16be
pure ClientDisconnect
{-# INLINE disconnectParser #-}
clientPacketBuilder :: ClientPacket -> BS.Builder
clientPacketBuilder (ClientConnect
(ClientIdentifier cid)
(CleanSession cleanSession)
(KeepAliveInterval keepAlive) will credentials) =
BS.word8 0x10
<> lengthBuilder ( 10 + cidLen + willLen + credLen )
<> BS.word64BE ( 0x00044d5154540400 .|. willFlag .|. credFlag .|. sessFlag )
<> BS.word16BE keepAlive
<> cidBuilder
<> willBuilder
<> credBuilder
where
sessFlag = if cleanSession then 0x02 else 0x00
(cidBuilder, cidLen) = utf8Builder cid
(willBuilder, willLen, willFlag) = case will of
Nothing ->
(mempty, 0, 0x00)
Just (Message t q (Retain r) (Payload b))->
let tlen = TF.topicLength t
blen = fromIntegral (BSL.length b)
qflag = case q of
QoS0 -> 0x04
QoS1 -> 0x0c
QoS2 -> 0x14
rflag = if r then 0x20 else 0x00
x1 = BS.word16BE (fromIntegral tlen)
x2 = TF.topicBuilder t
x3 = BS.word16BE (fromIntegral blen)
x4 = BS.lazyByteString b
in (x1 <> x2 <> x3 <> x4, 4 + tlen + blen, qflag .|. rflag)
(credBuilder, credLen, credFlag) = case credentials of
Nothing ->
(mempty, 0, 0x00)
Just (Username ut, Nothing) ->
let u = T.encodeUtf8 ut
ulen = BS.length u
x1 = BS.word16BE (fromIntegral ulen)
x2 = BS.byteString u
in (x1 <> x2, 2 + ulen, 0x80)
Just (Username ut, Just (Password p)) ->
let u = T.encodeUtf8 ut
ulen = BS.length u
plen = BS.length p
x1 = BS.word16BE (fromIntegral ulen)
x2 = BS.byteString u
x3 = BS.word16BE (fromIntegral plen)
x4 = BS.byteString p
in (x1 <> x2 <> x3 <> x4, 4 + ulen + plen, 0xc0)
clientPacketBuilder ClientConnectUnsupported =
BS.word8 10 <> lengthBuilder 38 <> BS.word64BE 0x00064d514973647063
clientPacketBuilder (ClientPublish pid dup msg) =
publishBuilder pid dup msg
clientPacketBuilder (ClientPublishAcknowledged (PacketIdentifier pid)) =
BS.word32BE $ fromIntegral $ 0x40020000 .|. pid
clientPacketBuilder (ClientPublishReceived (PacketIdentifier pid)) =
BS.word32BE $ fromIntegral $ 0x50020000 .|. pid
clientPacketBuilder (ClientPublishRelease (PacketIdentifier pid)) =
BS.word32BE $ fromIntegral $ 0x62020000 .|. pid
clientPacketBuilder (ClientPublishComplete (PacketIdentifier pid)) =
BS.word32BE $ fromIntegral $ 0x70020000 .|. pid
clientPacketBuilder (ClientSubscribe (PacketIdentifier pid) filters) =
BS.word8 0x82 <> lengthBuilder len <> BS.word16BE (fromIntegral pid)
<> mconcat (fmap filterBuilder' filters)
where
filterBuilder' (f, q) = BS.word16BE (fromIntegral fl) <> fb <> qb
where
fb = TF.filterBuilder f
fl = TF.filterLength f
qb = BS.word8 $ case q of
QoS0 -> 0x00
QoS1 -> 0x01
QoS2 -> 0x02
len = 2 + sum ( map ( (+3) . TF.filterLength . fst ) filters )
clientPacketBuilder (ClientUnsubscribe (PacketIdentifier pid) filters) =
BS.word8 0xa2 <> lengthBuilder len <> BS.word16BE (fromIntegral pid)
<> mconcat ( map filterBuilder' filters )
where
filterBuilder' f = BS.word16BE (fromIntegral fl) <> fb
where
fb = TF.filterBuilder f
fl = TF.filterLength f
len = 2 + sum ( map ( (+2) . TF.filterLength ) filters )
clientPacketBuilder ClientPingRequest =
BS.word16BE 0xc000
clientPacketBuilder ClientDisconnect =
BS.word16BE 0xe000
serverPacketBuilder :: ServerPacket -> BS.Builder
serverPacketBuilder (ServerConnectionAccepted (SessionPresent sessionPresent))
| sessionPresent = BS.word32BE 0x20020100
| otherwise = BS.word32BE 0x20020000
serverPacketBuilder (ServerConnectionRejected reason) =
BS.word32BE $ case reason of
UnacceptableProtocolVersion -> 0x20020001
IdentifierRejected -> 0x20020002
ServerUnavailable -> 0x20020003
BadUsernameOrPassword -> 0x20020004
NotAuthorized -> 0x20020005
serverPacketBuilder (ServerPublish pid dup msg) =
publishBuilder pid dup msg
serverPacketBuilder (ServerPublishAcknowledged (PacketIdentifier pid)) =
BS.word32BE $ fromIntegral $ 0x40020000 .|. pid
serverPacketBuilder (ServerPublishReceived (PacketIdentifier pid)) =
BS.word32BE $ fromIntegral $ 0x50020000 .|. pid
serverPacketBuilder (ServerPublishRelease (PacketIdentifier pid)) =
BS.word32BE $ fromIntegral $ 0x62020000 .|. pid
serverPacketBuilder (ServerPublishComplete (PacketIdentifier pid)) =
BS.word32BE $ fromIntegral $ 0x70020000 .|. pid
serverPacketBuilder (ServerSubscribeAcknowledged (PacketIdentifier pid) rcs) =
BS.word8 0x90 <> lengthBuilder (2 + length rcs)
<> BS.word16BE (fromIntegral pid) <> mconcat ( map ( BS.word8 . f ) rcs )
where
f Nothing = 0x80
f (Just QoS0) = 0x00
f (Just QoS1) = 0x01
f (Just QoS2) = 0x02
serverPacketBuilder (ServerUnsubscribeAcknowledged (PacketIdentifier pid)) =
BS.word16BE 0xb002 <> BS.word16BE (fromIntegral pid)
serverPacketBuilder ServerPingResponse =
BS.word16BE 0xd000
publishBuilder :: PacketIdentifier -> Duplicate -> Message -> BS.Builder
publishBuilder (PacketIdentifier pid) (Duplicate dup) msg =
BS.word8 h
<> lengthBuilder len
<> BS.word16BE (fromIntegral topicLen)
<> topicBuilder'
<> bool (BS.word16BE $ fromIntegral pid) mempty (msgQoS msg == QoS0)
<> BS.lazyByteString body
where
Payload body = msgPayload msg
topicLen = TF.topicLength (msgTopic msg)
topicBuilder' = TF.topicBuilder (msgTopic msg)
len = 2 + topicLen + fromIntegral (BSL.length body)
+ bool 2 0 (msgQoS msg == QoS0)
h = 0x30
.|. bool 0x00 0x01 retain
.|. bool 0x00 0x08 dup
.|. case msgQoS msg of
QoS0 -> 0x00
QoS1 -> 0x02
QoS2 -> 0x04
where
Retain retain = msgRetain msg
topicAndLengthParser :: SG.Get (TF.Topic, Int)
topicAndLengthParser = do
topicLen <- fromIntegral <$> SG.getWord16be
topicBytes <- SG.getByteString topicLen
case A.parseOnly TF.topicParser topicBytes of
Right t -> pure (t, topicLen + 2)
Left _ -> fail "topicAndLengthParser: Invalid topic."
{-# INLINE topicAndLengthParser #-}
filterAndLengthParser :: SG.Get (TF.Filter, Int)
filterAndLengthParser = do
filterLen <- fromIntegral <$> SG.getWord16be
filterBytes <- SG.getByteString filterLen
case A.parseOnly TF.filterParser filterBytes of
Right f -> pure (f, filterLen + 2)
Left _ -> fail "filterAndLengthParser: Invalid filter."
{-# INLINE filterAndLengthParser #-}
utf8Parser :: SG.Get T.Text
utf8Parser = do
str <- SG.getWord16be >>= SG.getByteString . fromIntegral
when (BS.elem 0x00 str) (fail "utf8Parser: Violation of [MQTT-1.5.3-2].")
case T.decodeUtf8' str of
Right txt -> return txt
_ -> fail "utf8Parser: Violation of [MQTT-1.5.3]."
{-# INLINE utf8Parser #-}
utf8Builder :: T.Text -> (BS.Builder, Int)
utf8Builder txt =
if len > 0xffff
then error "utf8Builder: Encoded size must be <= 0xffff."
else (BS.word16BE (fromIntegral len) <> BS.byteString bs, len + 2)
where
bs = T.encodeUtf8 txt
len = BS.length bs
{-# INLINE utf8Builder #-}
lengthParser:: SG.Get Int
lengthParser = do
b0 <- fromIntegral <$> SG.getWord8
if b0 < 128
then pure b0
else do
b1 <- fromIntegral <$> SG.getWord8
if b1 < 128
then pure $ b1 * 128 + (b0 .&. 127)
else do
b2 <- fromIntegral <$> SG.getWord8
if b2 < 128
then pure $ b2 * 128 * 128 + (b1 .&. 127) * 128 + (b0 .&. 127)
else do
b3 <- fromIntegral <$> SG.getWord8
if b3 < 128
then pure $ b3 * 128 * 128 * 128 + (b2 .&. 127) * 128 * 128 + (b1 .&. 127) * 128 + (b0 .&. 127)
else fail "lengthParser: invalid input"
{-# INLINE lengthParser #-}
lengthBuilder :: Int -> BS.Builder
lengthBuilder i
| i < 0x80 = BS.word8 ( fromIntegral i )
| i < 0x80*0x80 = BS.word16LE $ fromIntegral $ 0x0080 -- continuation bit
.|. ( i .&. 0x7f )
.|. unsafeShiftL ( i .&. 0x3f80 ) 1
| i < 0x80*0x80*0x80 = BS.word16LE ( fromIntegral $ 0x8080
.|. ( i .&. 0x7f )
.|. unsafeShiftL ( i .&. 0x3f80 ) 1
)
<> BS.word8 ( fromIntegral
$ unsafeShiftR ( i .&. 0x1fc000 ) 14
)
| i < 0x80*0x80*0x80*0x80 = BS.word32LE $ fromIntegral $ 0x00808080
.|. ( i .&. 0x7f )
.|. unsafeShiftL ( i .&. 0x3f80 ) 1
.|. unsafeShiftL ( i .&. 0x1fc000 ) 2
.|. unsafeShiftL ( i .&. 0x0ff00000) 3
| otherwise = error "lengthBuilder: invalid input"
{-# INLINE lengthBuilder #-}
| lpeterse/haskell-mqtt | src/Network/MQTT/Message.hs | mit | 21,696 | 0 | 26 | 6,031 | 5,640 | 2,892 | 2,748 | 504 | 11 |
module Database.HLINQ(module Database.HLINQ.Info) where
import Database.HLINQ.Info
| juventietis/HLINQ | Database/HLINQ.hs | mit | 84 | 0 | 5 | 7 | 21 | 14 | 7 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module CabalDelete.Parse
( parsePkgId
, parseGhcPkgList
) where
import Control.Applicative
import Data.Attoparsec.Text
import Data.List
import Data.Monoid (mempty)
import qualified Data.Text as T
import Data.Version
import Distribution.Package
import Prelude
import CabalDelete.Types
parseGhcPkgList :: String -> Either String PkgConfList
parseGhcPkgList = eitherResult . flip feed mempty . parse _ghcPkgList . T.pack
_ghcPkgList :: Parser PkgConfList
_ghcPkgList = many (try _warnMsg) *> many ((,) <$> _pkgConfPath <*> _pkgList)
_warnMsg :: Parser ()
_warnMsg = string "WARNING" *> many (notChar '\n') *> _eol
_pkgConfPath :: Parser FilePath
_pkgConfPath = anyChar `manyTill` try (char ':' *> _eol)
_pkgList :: Parser [PackageId]
_pkgList = concat <$> many (_pkgLine <* _eol) <* optional _eol
_pkgLine :: Parser [PackageId]
_pkgLine = many1 (char ' ') *> sepBy p sep
where
p = optional (oneOf "({") *> _pkgId <* optional (oneOf ")}")
sep = char ',' *> many space
oneOf = choice . map char
_eol :: Parser ()
_eol = () <$ (optional (char '\r') >> char '\n')
parsePkgId :: String -> Either String PackageId
parsePkgId = eitherResult . flip feed mempty . parse _pkgId . T.pack
_pkgId :: Parser PackageId
_pkgId = go []
where
go cs = do
c <- _nameChunk
mv <- optional _numVer
case mv of
Nothing -> go (c:cs)
Just v ->
let name = PackageName $ intercalate "-" $ reverse (c:cs)
in return $ PackageIdentifier name v
_nameChunk :: Parser String
_nameChunk = anyChar `manyTill` char '-'
_numVer :: Parser Version
_numVer = (flip Version [] . map read) <$> sepBy1 (many1 digit) (char '.')
| iquiw/cabal-delete | src/CabalDelete/Parse.hs | mit | 1,820 | 0 | 19 | 463 | 621 | 316 | 305 | 46 | 2 |
import System.IO
import Data.List
enumerate = zip [0..]
discatenate :: [a] -> [[a]]
discatenate xs = map (\a -> [a]) xs
parseAud :: String -> [(Int, Int)]
parseAud aud = enumerate $ (map read (discatenate aud) :: [Int])
run :: ([(Int, Int)], Int, Int) -> ([(Int, Int)], Int, Int)
run ([], up, extras) = ([], up, extras)
run (((thresh, num):xs), up, extras)
| up >= thresh = run (xs, (up + num), extras)
| otherwise = ((thresh, num):xs, up + newExtras, extras + newExtras)
where newExtras = thresh - up
solveCase :: String -> Int
solveCase caseString = extras
where [maxS, aud] = words caseString
startAud = parseAud aud
(_, _, extras) = until (\(notStanding, _, _) -> null notStanding ) run (startAud, 0, 0)
format :: (Int, Int) -> String
format (i, n) = "Case #" ++ (show (i + 1)) ++ ": " ++ (show n)
main = do
input <- openFile "a.in" ReadMode >>= hGetContents >>= return . lines
let numCases = read $ head input :: Int
let solved = map solveCase $ tail input
mapM_ putStrLn $ map format (enumerate solved)
| davidrusu/Google-Code-Jam | 2015/qualifiers/A/standingOvation.hs | mit | 1,053 | 3 | 11 | 230 | 539 | 296 | 243 | 25 | 1 |
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Home where
import Import
-- This is a handler function for the GET request method on the HomeR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getHomeR :: Handler RepHtml
getHomeR = do
defaultLayout $ do
aDomId <- lift newIdent
setTitle "Yesod Example"
$(widgetFile "homepage")
| ShaneKilkelly/YesodExample | Handler/Home.hs | mit | 605 | 0 | 12 | 123 | 63 | 34 | 29 | 9 | 1 |
module Exploration.Algebra.Lattice
(
module Exploration.Algebra.Lattice.Definition
) where
import Exploration.Algebra.Lattice.Definition
| SamuelSchlesinger/Exploration | Exploration/Algebra/Lattice.hs | mit | 142 | 0 | 5 | 14 | 24 | 17 | 7 | 4 | 0 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distributed.Data.Map
-- Copyright : (c) Phil Hargett 2014
-- License : MIT (see LICENSE file)
--
-- Maintainer : phil@haphazardhouse.net
-- Stability : experimental
-- Portability : non-portable (requires STM)
--
-- (..... module description .....)
--
-----------------------------------------------------------------------------
module Distributed.Data.Map (
Map,
empty,
MapLog,
mkMapLog,
MapState,
withMap,
insert,
delete,
lookup,
size
) where
-- local imports
import Distributed.Data.Container
-- external imports
import Control.Applicative hiding (empty)
import Control.Consensus.Raft
import qualified Data.Map as M
import Data.Serialize
import Network.Endpoints
import Prelude hiding (log,lookup)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
data MapCommand k v = (Serialize k,Serialize v) => InsertPairs [(k,v)] | DeleteKeys [k]
deriving instance (Eq k,Eq v) => Eq (MapCommand k v)
deriving instance (Show k,Show v) => Show (MapCommand k v)
instance (Serialize k,Serialize v) => Serialize (MapCommand k v) where
get = do
kind <- getWord8
case kind of
0 -> InsertPairs <$> get
_ -> DeleteKeys <$> get
put (InsertPairs pairs) = do
putWord8 0
put pairs
put (DeleteKeys k) = do
putWord8 1
put k
type MapState k v = M.Map k v
instance (Ord k) => State (MapState k v) IO (MapCommand k v) where
canApplyEntry _ _ = return True
applyEntry initial (InsertPairs pairs) = do
return $ foldl (\old (key,value) -> M.insert key value old) initial pairs
applyEntry initial (DeleteKeys keys) = do
return $ foldl (\old key -> M.delete key old) initial keys
type MapLog k v = ListLog (MapCommand k v) (MapState k v)
mkMapLog :: (Ord k,Serialize k,Serialize v) => IO (MapLog k v)
mkMapLog = mkListLog
empty :: IO (MapState k v)
empty = return $ M.empty
type Map k v = Container (MapLog k v) (MapCommand k v) (MapState k v)
withMap :: (Ord k,Serialize k,Serialize v) => Endpoint -> RaftConfiguration -> Name -> MapLog k v -> MapState k v -> (Map k v -> IO ()) -> IO ()
withMap endpoint cfg name initialLog initialState fn = do
withContainer endpoint cfg name initialLog initialState fn
insert :: (Ord k,Serialize k,Serialize v) => k -> v -> Map k v -> Causal ()
insert key value dmap = Causal $ \_ -> do
index <- perform (Cmd $ InsertPairs [(key,value)]) dmap
return $ ((),index)
delete :: (Ord k,Serialize k,Serialize v) => k -> Map k v -> Causal ()
delete key dmap = Causal $ \_ -> do
index <- perform (Cmd $ DeleteKeys [key]) dmap
return $ ((),index)
lookup :: (Ord k,Serialize k,Serialize v) => k -> Map k v -> Causal (Maybe v)
lookup key dmap = Causal $ \index -> do
(state,now) <- containerDataAt dmap index
return $ (M.lookup key state,now)
size :: (Ord k,Serialize k,Serialize v) => Map k v -> Causal Int
size dmap = Causal $ \index -> do
(state,now) <- containerDataAt dmap index
return (M.size state,now)
| hargettp/distributed-containers | src/Distributed/Data/Map.hs | mit | 3,404 | 0 | 15 | 721 | 1,173 | 620 | 553 | 69 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE QuasiQuotes #-}
module Shakespeare.Dynamic.Adapter where
import Control.Applicative
import Control.Monad
import qualified Data.Traversable as TR
import VDOM.Adapter
import GHCJS.Foreign
import GHCJS.Marshal
import GHCJS.Types
import qualified GHCJS.VDOM as VD
-- | The orphan instance is to seperate the GHCJS dependency
-- from the JSProp definition
-- This just pushes the data into a JSRef and then casts
-- it back to the correct type so that
-- toJSRef :: JSProp -> IO (JSRef JSProp)
instance ToJSRef JSProp where
toJSRef (JSPText t) = castToJSRef t
toJSRef (JSPBool b) = castToJSRef b
toJSRef (JSPInt i) = castToJSRef i
toJSRef (JSPFloat f) = castToJSRef f
toJSRef (JSPDouble d) = castToJSRef d
-- | Push a piece of data into a JSRef and cast it
castToJSRef :: ToJSRef a => a -> IO (JSRef b)
castToJSRef x = castRef <$> toJSRef x
-- | Newtype to wrap the [Property] so that
newtype PropList = PropList { unPropList :: [Property]} deriving (Show)
-- | The orphan instance is again to seperate the GHCJS dependency
-- from the definition of property
instance ToJSRef PropList where
toJSRef (PropList xs) = do
attr <- newObj
foldM_ insert attr xs
props <- newObj
setProp "attributes" attr props
return props
where
-- VDom uses the property object like a Map from name to value
-- So we create a map for vdom to access
insert obj (Property name value) = do
val <- toJSRef value
setProp name val obj
return obj
-- | Convert a VNodeAdapter to a VNode in order to diff it with vdom
-- and add the event hooks
toVNode :: VNodeAdapter -> IO VD.VNode
toVNode (VNode events aTagName aProps aChildren) = do
props <- (addEvents events) =<< VD.toProperties . castRef <$> (toJSRef $ PropList aProps)
children <- TR.mapM toVNode aChildren
return $ VD.js_vnode tagName props $ mChildren children
where tagName = toJSString aTagName
mChildren [] = VD.noChildren
mChildren xs = VD.mkChildren xs
toVNode (VText _ev inner) = return $ VD.text $ toJSString inner
-- | Add a list of events to a list of properties
-- that can be added to a dom object
addEvents :: [JSEvent] -> VD.Properties -> IO VD.Properties
addEvents events props = foldM addEvent props events
where addEvent pl (JSInput f) = VD.oninput f pl
addEvent pl (JSKeypress f) = VD.keypress f pl
addEvent pl (JSClick f) = (\cb -> VD.click cb pl) <$> (mkCallback f)
addEvent pl (JSDoubleClick f) = (\cb -> VD.dblclick cb pl) <$> (mkCallback f)
addEvent pl (JSCanvasLoad f) = VD.canvasLoad f pl
mkCallback = syncCallback NeverRetain False | plow-technologies/shakespeare-dynamic | ghcjs-shakespeare-dynamic/src/Shakespeare/Dynamic/Adapter.hs | mit | 2,768 | 0 | 12 | 660 | 707 | 359 | 348 | 48 | 5 |
module DoesItCompile where
-- fixed functions
bigNum arg = (^) 5 $ arg
wahoo = bigNum $ 10
x arg = print arg
y = print "woohoo!"
z = x "hello world"
a = (+)
b = 5
c = a b 10
d = a c 200
a1 = 12 + b1
where
b1 = 10000 * c1
c1 = 1
| Numberartificial/workflow | haskell-first-principles/haskell-from-first-principles-master/05/05.08.03-does-it-compile.hs | mit | 243 | 0 | 7 | 77 | 115 | 63 | 52 | 13 | 1 |
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiWayIf #-}
{-# OPTIONS_GHC -fwarn-unused-imports #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Pane.SourceBuffer
-- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GNU-GPL
--
-- Maintainer : <maintainer at leksah.org>
-- Stability : provisional
-- Portability : portable
--
-- | The source editor part of Leksah
--
-----------------------------------------------------------------------------------
module IDE.Pane.SourceBuffer (
IDEBuffer(..)
, BufferState(..)
, allBuffers
, maybeActiveBuf
, selectSourceBuf
, goToSourceDefinition
, goToSourceDefinition'
, goToDefinition
, insertInBuffer
, fileNew
, fileOpenThis
, filePrint
, fileRevert
, fileClose
, fileCloseAll
, fileCloseAllButPackage
, fileCloseAllButWorkspace
, fileSave
, fileSaveAll
, fileSaveBuffer
, fileCheckAll
, editUndo
, editRedo
, editCut
, editCopy
, editPaste
, editDelete
, editSelectAll
, editComment
, editUncomment
, editShiftRight
, editShiftLeft
, editToCandy
, editFromCandy
, editKeystrokeCandy
, switchBuffersCandy
, updateStyle
, updateStyle'
, addLogRef
, removeLogRefs
, removeBuildLogRefs
, removeTestLogRefs
, removeLintLogRefs
, markRefInSourceBuf
, inBufContext
, inActiveBufContext
, align
, startComplete
, selectedText
, selectedTextOrCurrentLine
, selectedTextOrCurrentIdentifier
, insertTextAfterSelection
, selectedModuleName
, selectedLocation
, recentSourceBuffers
, newTextBuffer
, belongsToPackages
, belongsToPackages'
, belongsToPackage
, belongsToWorkspace
, belongsToWorkspace'
, getIdentifierUnderCursorFromIter
, useCandyFor
) where
import Prelude hiding(getChar, getLine)
import Control.Applicative
import System.FilePath
import System.Directory
import qualified Data.Map as Map
import Data.Map (Map)
import Data.List hiding(insert, delete)
import Data.Maybe
import Data.Char
import Data.Typeable
import IDE.Core.State
import IDE.Utils.GUIUtils
import IDE.Utils.FileUtils
import IDE.Utils.DirectoryUtils
import IDE.SourceCandy
import IDE.SymbolNavigation
import IDE.Completion as Completion (complete,cancel)
import IDE.TextEditor
import Data.IORef (writeIORef,readIORef,newIORef)
import Control.Event (triggerEvent)
import IDE.Metainfo.Provider (getSystemInfo, getWorkspaceInfo)
import Graphics.UI.Gtk
(Notebook, clipboardGet, selectionClipboard, dialogAddButton, widgetDestroy,
fileChooserGetFilename, widgetShow, fileChooserDialogNew,
notebookGetNthPage, notebookPageNum, widgetHide, dialogRun,
messageDialogNew, scrolledWindowSetShadowType,
scrolledWindowSetPolicy, dialogSetDefaultResponse,
fileChooserSelectFilename,
TextSearchFlags(..))
import qualified Graphics.UI.Gtk as Gtk hiding (eventKeyName)
import Graphics.UI.Gtk.Windows.Window
import Graphics.UI.Gtk.General.Enums
(ShadowType(..), PolicyType(..))
import Graphics.UI.Gtk.Windows.MessageDialog
(ButtonsType(..), MessageType(..))
import Graphics.UI.Gtk.Windows.Dialog (ResponseId(..))
import Graphics.UI.Gtk.Selectors.FileChooser
(FileChooserAction(..))
import System.Glib.Attributes (AttrOp(..), set)
import IDE.BufferMode
import Control.Monad.Trans.Reader (ask)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad (filterM, void, unless, when, liftM, forM_)
import Control.Exception as E (catch, SomeException)
import qualified IDE.Command.Print as Print
import Control.Monad.Trans.Class (MonadTrans(..))
import System.Log.Logger (errorM, warningM, debugM)
import Data.Text (Text)
import qualified Data.Text as T
(length, findIndex, replicate, lines,
dropWhileEnd, unlines, strip, null, pack, unpack)
import Data.Monoid ((<>))
import qualified Data.Text.IO as T (writeFile, readFile)
import Data.Time (UTCTime(..))
import Graphics.UI.Gtk.Gdk.EventM
(eventModifier, eventKeyName, eventKeyVal)
import qualified Data.Foldable as F (Foldable(..), forM_, toList)
import Data.Traversable (forM)
import Language.Haskell.HLint3 (Idea(..))
-- import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Data.Sequence as Seq
import Data.Sequence (ViewR(..), (|>))
import Data.Time.Clock (addUTCTime, diffUTCTime)
--time :: MonadIO m => String -> m a -> m a
--time name action = do
-- liftIO . debugM "leksah" $ name <> " start"
-- start <- liftIO $ realToFrac <$> getPOSIXTime
-- result <- action
-- end <- liftIO $ realToFrac <$> getPOSIXTime
-- liftIO . debugM "leksah" $ name <> " took " <> show ((end - start) * 1000000) <> "us"
-- return result
allBuffers :: MonadIDE m => m [IDEBuffer]
allBuffers = liftIDE getPanes
instance RecoverablePane IDEBuffer BufferState IDEM where
saveState (p@IDEBuffer {sourceView=v}) = do
buf <- getBuffer v
ins <- getInsertMark buf
iter <- getIterAtMark buf ins
offset <- getOffset iter
case fileName p of
Nothing -> do
ct <- readIDE candy
text <- getCandylessText ct buf
return (Just (BufferStateTrans (bufferName p) text offset))
Just fn -> return (Just (BufferState fn offset))
recoverState pp (BufferState n i) = do
mbbuf <- newTextBuffer pp (T.pack $ takeFileName n) (Just n)
case mbbuf of
Just (IDEBuffer {sourceView=v}) -> do
postAsyncIDEIdle $ do
liftIO $ debugM "leksah" "SourceBuffer recoverState idle callback"
gtkBuf <- getBuffer v
iter <- getIterAtOffset gtkBuf i
placeCursor gtkBuf iter
mark <- getInsertMark gtkBuf
scrollToMark v mark 0.0 (Just (1.0,0.3))
liftIO $ debugM "leksah" "SourceBuffer recoverState done"
return mbbuf
Nothing -> return Nothing
recoverState pp (BufferStateTrans bn text i) = do
mbbuf <- newTextBuffer pp bn Nothing
case mbbuf of
Just (buf@IDEBuffer {sourceView=v}) -> do
postAsyncIDEIdle $ do
liftIO $ debugM "leksah" "SourceBuffer recoverState idle callback"
useCandy <- useCandyFor buf
gtkBuf <- getBuffer v
setText gtkBuf text
when useCandy $ modeTransformToCandy (mode buf)
(modeEditInCommentOrString (mode buf)) gtkBuf
iter <- getIterAtOffset gtkBuf i
placeCursor gtkBuf iter
mark <- getInsertMark gtkBuf
scrollToMark v mark 0.0 (Just (1.0,0.3))
liftIO $ debugM "leksah" "SourceBuffer recoverState done"
return (Just buf)
Nothing -> return Nothing
makeActive (actbuf@IDEBuffer {sourceView=sv}) = do
ideR <- ask
eBuf <- getBuffer sv
writeCursorPositionInStatusbar sv
writeOverwriteInStatusbar sv
ids1 <- eBuf `afterModifiedChanged` markActiveLabelAsChanged
ids2 <- sv `afterMoveCursor` writeCursorPositionInStatusbar sv
-- ids3 <- sv `onLookupInfo` selectInfo sv -- obsolete by hyperlinks
ids4 <- sv `afterToggleOverwrite` writeOverwriteInStatusbar sv
activateThisPane actbuf $ concat [ids1, ids2, ids4]
triggerEventIDE (Sensitivity [(SensitivityEditor, True)])
grabFocus sv
checkModTime actbuf
return ()
closePane pane = do makeActive pane
fileClose
buildPane panePath notebook builder = return Nothing
builder pp nb w = return (Nothing,[])
-- startComplete :: IDEAction
startComplete = do
mbBuf <- maybeActiveBuf
currentState' <- readIDE currentState
case mbBuf of
Nothing -> return ()
Just (IDEBuffer {sourceView=v}) -> complete v True
-- selectSourceBuf :: FilePath -> IDEM (Maybe IDEBuffer)
selectSourceBuf fp = do
fpc <- liftIO $ myCanonicalizePath fp
buffers <- allBuffers
let buf = filter (\b -> case fileName b of
Just fn -> equalFilePath fn fpc
Nothing -> False) buffers
case buf of
hdb:tl -> do
makeActive hdb
return (Just hdb)
otherwise -> do
fe <- liftIO $ doesFileExist fpc
if fe
then do
prefs <- readIDE prefs
pp <- getBestPathForId "*Buffer"
liftIO $ debugM "lekash" "selectSourceBuf calling newTextBuffer"
nbuf <- newTextBuffer pp (T.pack $ takeFileName fpc) (Just fpc)
liftIO $ debugM "lekash" "selectSourceBuf newTextBuffer returned"
return nbuf
else do
ideMessage Normal (__ "File path not found " <> T.pack fpc)
return Nothing
goToDefinition :: Descr -> IDEAction
goToDefinition idDescr = do
mbWorkspaceInfo <- getWorkspaceInfo
mbSystemInfo <- getSystemInfo
let mbPackagePath = (mbWorkspaceInfo >>= (packagePathFromScope . fst))
<|> (mbSystemInfo >>= packagePathFromScope)
mbSourcePath = (mbWorkspaceInfo >>= (sourcePathFromScope . fst))
<|> (mbSystemInfo >>= sourcePathFromScope)
liftIO . debugM "leksah" $ show (mbPackagePath, dscMbLocation idDescr, mbSourcePath)
case (mbPackagePath, dscMbLocation idDescr, mbSourcePath) of
(Just packagePath, Just loc, _) -> void (goToSourceDefinition (dropFileName packagePath) loc)
(_, Just loc, Just sourcePath) -> void (goToSourceDefinition' sourcePath loc)
(_, _, Just sp) -> void (selectSourceBuf sp)
_ -> return ()
where
packagePathFromScope :: GenScope -> Maybe FilePath
packagePathFromScope (GenScopeC (PackScope l _)) =
case dscMbModu idDescr of
Just mod -> case pack mod `Map.lookup` l of
Just pack -> pdMbSourcePath pack
Nothing -> Nothing
Nothing -> Nothing
sourcePathFromScope :: GenScope -> Maybe FilePath
sourcePathFromScope (GenScopeC (PackScope l _)) =
case dscMbModu idDescr of
Just mod -> case pack mod `Map.lookup` l of
Just pack ->
case filter (\md -> mdModuleId md == fromJust (dscMbModu idDescr))
(pdModules pack) of
(mod : tl) -> mdMbSourcePath mod
[] -> Nothing
Nothing -> Nothing
Nothing -> Nothing
goToSourceDefinition :: FilePath -> Location -> IDEM (Maybe IDEBuffer)
goToSourceDefinition packagePath loc =
goToSourceDefinition' (packagePath </> locationFile loc) loc
goToSourceDefinition' :: FilePath -> Location -> IDEM (Maybe IDEBuffer)
goToSourceDefinition' sourcePath Location{..} = do
mbBuf <- selectSourceBuf sourcePath
case mbBuf of
Just buf ->
inActiveBufContext () $ \_ sv ebuf _ _ -> do
liftIO $ debugM "lekash" "goToSourceDefinition calculating range"
lines <- getLineCount ebuf
iterTemp <- getIterAtLine ebuf (max 0 (min (lines-1)
(locationSLine -1)))
chars <- getCharsInLine iterTemp
iter <- atLineOffset iterTemp (max 0 (min (chars-1) (locationSCol -1)))
iter2Temp <- getIterAtLine ebuf (max 0 (min (lines-1) (locationELine -1)))
chars2 <- getCharsInLine iter2Temp
iter2 <- atLineOffset iter2Temp (max 0 (min (chars2-1) locationECol))
-- ### we had a problem before using postAsyncIDEIdle
postAsyncIDEIdle $ do
liftIO $ debugM "lekash" "goToSourceDefinition triggered selectRange"
selectRange ebuf iter iter2
liftIO $ debugM "lekash" "goToSourceDefinition triggered scrollToIter"
scrollToIter sv iter 0.0 (Just (1.0,0.3))
return ()
Nothing -> return ()
return mbBuf
insertInBuffer :: Descr -> IDEAction
insertInBuffer idDescr = do
mbPaneName <- lastActiveBufferPane
case mbPaneName of
Nothing -> return ()
Just name -> do
PaneC p <- paneFromName name
let mbBuf = cast p
case mbBuf of
Nothing -> return ()
Just buf ->
inBufContext () buf $ \_ _ ebuf buf _ -> do
mark <- getInsertMark ebuf
iter <- getIterAtMark ebuf mark
insert ebuf iter (dscName idDescr)
updateStyle' :: IDEBuffer -> IDEAction
updateStyle' IDEBuffer {sourceView = sv} = getBuffer sv >>= updateStyle
removeLogRefs :: (FilePath -> FilePath -> Bool) -> [LogRefType] -> IDEAction
removeLogRefs toRemove' types = do
(remove, keep) <- Seq.partition toRemove <$> readIDE allLogRefs
let removeDetails = Map.fromListWith (<>) . nub $ map (\ref ->
(logRefRootPath ref </> logRefFilePath ref,
[logRefType ref])) $ F.toList remove
modifyIDE_ (\ide -> ide{allLogRefs = keep})
buffers <- allBuffers
let matchingBufs = filter (maybe False (`Map.member` removeDetails) . fileName) buffers
F.forM_ matchingBufs $ \ (IDEBuffer {..}) -> do
buf <- getBuffer sourceView
F.forM_ (maybe [] (fromMaybe [] . (`Map.lookup` removeDetails)) fileName) $
removeTagByName buf . T.pack . show
triggerEventIDE (ErrorChanged False)
return ()
where
toRemove ref = toRemove' (logRefRootPath ref) (logRefFilePath ref)
&& logRefType ref `elem` types
removeFileLogRefs :: FilePath -> FilePath -> [LogRefType] -> IDEAction
removeFileLogRefs root file types = do
liftIO . debugM "leksah" $ "removeFileLogRefs " <> root <> " " <> file <> " " <> show types
removeLogRefs (\r f -> r == root && f == file) types
removePackageLogRefs :: FilePath -> [LogRefType] -> IDEAction
removePackageLogRefs root types = do
liftIO . debugM "leksah" $ "removePackageLogRefs " <> root <> " " <> show types
removeLogRefs (\r _ -> r == root) types
removeBuildLogRefs :: FilePath -> FilePath -> IDEAction
removeBuildLogRefs root file = removeFileLogRefs root file [ErrorRef, WarningRef]
removeTestLogRefs :: FilePath -> IDEAction
removeTestLogRefs root = removePackageLogRefs root [TestFailureRef]
removeLintLogRefs :: FilePath -> FilePath -> IDEAction
removeLintLogRefs root file = removeFileLogRefs root file [LintRef]
canResolve :: LogRef -> Bool
canResolve LogRef { logRefIdea = Just (_, Idea{..}) }
= ideaHint /= "Reduce duplication" && isJust ideaTo
canResolve _ = False
addLogRef :: Bool -> Bool -> LogRef -> IDEAction
addLogRef hlintFileScope backgroundBuild ref = do
liftIO . debugM "leksah" $ "addLogRef " <> show hlintFileScope <> " " <> show (logRefType ref) <> " " <> logRefFullFilePath ref
-- Put most important errors first.
-- If the importance of two errors is the same then
-- then the older one might be stale (unless it is in the same file)
allLogRefs <- readIDE allLogRefs
currentError <- readIDE currentError
let (moreImportant, rest) =
Seq.spanl (\old ->
let samePackage = logRefRootPath old == logRefRootPath ref
sameFile = logRefFullFilePath old == logRefFullFilePath ref in
-- Work out when the old ref is more important than the new
case (logRefType ref, logRefType old) of
(ErrorRef , ErrorRef ) -> sameFile
(ErrorRef , _ ) -> False
(WarningRef , ErrorRef ) -> samePackage
(WarningRef , WarningRef ) -> samePackage
(WarningRef , _ ) -> False
(TestFailureRef, ErrorRef ) -> samePackage -- Probably should never be True
(TestFailureRef, TestFailureRef) -> samePackage
(TestFailureRef, _ ) -> False
(LintRef , LintRef ) -> (if hlintFileScope then sameFile else samePackage)
&& (canResolve old
|| not (canResolve ref))
(LintRef , _ ) -> samePackage
(ContextRef , _ ) -> False
(BreakpointRef , _ ) -> False) allLogRefs
currErr = if currentError `elem` map Just (F.toList moreImportant)
then currentError
else Nothing
modifyIDE_ $ \ ide ->
ide{ allLogRefs = (moreImportant |> ref) <> rest
, currentEBC = (currErr, currentBreak ide, currentContext ide)
}
buffers <- allBuffers
let matchingBufs = filter (maybe False (equalFilePath (logRefFullFilePath ref)) . fileName) buffers
F.forM_ matchingBufs $ \ buf -> markRefInSourceBuf buf ref False
triggerEventIDE $ ErrorAdded
(not backgroundBuild && Seq.null moreImportant) (Seq.length moreImportant) ref
return ()
markRefInSourceBuf :: IDEBuffer -> LogRef -> Bool -> IDEAction
markRefInSourceBuf buf logRef scrollTo = do
useCandy <- useCandyFor buf
candy' <- readIDE candy
contextRefs <- readIDE contextRefs
prefs <- readIDE prefs
inBufContext () buf $ \_ sv ebuf buf _ -> do
let tagName = T.pack $ show (logRefType logRef)
liftIO . debugM "lekash" . T.unpack $ "markRefInSourceBuf getting or creating tag " <> tagName
liftIO $ debugM "lekash" "markRefInSourceBuf calculating range"
let start' = (srcSpanStartLine (logRefSrcSpan logRef),
srcSpanStartColumn (logRefSrcSpan logRef))
let end' = (srcSpanEndLine (logRefSrcSpan logRef),
srcSpanEndColumn (logRefSrcSpan logRef))
start <- if useCandy
then positionToCandy candy' ebuf start'
else return start'
end <- if useCandy
then positionToCandy candy' ebuf end'
else return end'
lines <- getLineCount ebuf
iterTmp <- getIterAtLine ebuf (max 0 (min (lines-1) (fst start - 1)))
chars <- getCharsInLine iterTmp
iter <- atLineOffset iterTmp (max 0 (min (chars-1) (snd start)))
iter2 <- if start == end
then do
maybeWE <- forwardWordEndC iter
case maybeWE of
Nothing -> atEnd iter
Just we -> return we
else do
newTmp <- getIterAtLine ebuf (max 0 (min (lines-1) (fst end - 1)))
chars <- getCharsInLine newTmp
new <- atLineOffset newTmp (max 0 (min (chars-1) (snd end)))
forwardCharC new
let last (Seq.viewr -> EmptyR) = Nothing
last (Seq.viewr -> xs :> x) = Just x
last _ = Nothing
latest = last contextRefs
isOldContext = case (logRefType logRef, latest) of
(ContextRef, Just ctx) | ctx /= logRef -> True
_ -> False
unless isOldContext $ do
liftIO $ debugM "lekash" "markRefInSourceBuf calling applyTagByName"
lineStart <- backwardToLineStartC iter
createMark sv (logRefType logRef) lineStart $ refDescription logRef
applyTagByName ebuf tagName iter iter2
when scrollTo $ do
liftIO $ debugM "lekash" "markRefInSourceBuf triggered placeCursor"
placeCursor ebuf iter
mark <- getInsertMark ebuf
liftIO $ debugM "lekash" "markRefInSourceBuf trigged scrollToMark"
scrollToMark sv mark 0.3 Nothing
when isOldContext $ selectRange ebuf iter iter2
-- | Tries to create a new text buffer, fails when the given filepath
-- does not exist or when it is not a text file.
newTextBuffer :: PanePath -> Text -> Maybe FilePath -> IDEM (Maybe IDEBuffer)
newTextBuffer panePath bn mbfn =
case mbfn of
Nothing -> buildPane "" Nothing
Just fn ->
do eErrorContents <- liftIO $
catch (Right <$> T.readFile fn)
(\e -> return $ Left (show (e :: IOError)))
case eErrorContents of
Right contents -> do
modTime <- liftIO $ getModificationTime fn
buildPane contents (Just modTime)
Left err -> do
ideMessage Normal (__ "Error reading file " <> T.pack err)
return Nothing
where buildPane contents mModTime = do
nb <- getNotebook panePath
prefs <- readIDE prefs
let bs = candyState prefs
ct <- readIDE candy
(ind,rbn) <- figureOutPaneName bn 0
buildThisPane panePath nb (builder' bs mbfn ind bn rbn ct prefs contents mModTime)
data CharacterCategory = IdentifierCharacter | SpaceCharacter | SyntaxCharacter
deriving (Eq)
getCharacterCategory :: Maybe Char -> CharacterCategory
getCharacterCategory Nothing = SpaceCharacter
getCharacterCategory (Just c)
| isAlphaNum c || c == '\'' || c == '_' = IdentifierCharacter
| isSpace c = SpaceCharacter
| otherwise = SyntaxCharacter
builder' :: Bool ->
Maybe FilePath ->
Int ->
Text ->
Text ->
CandyTable ->
Prefs ->
Text ->
Maybe UTCTime ->
PanePath ->
Gtk.Notebook ->
Gtk.Window ->
IDEM (Maybe IDEBuffer,Connections)
builder' bs mbfn ind bn rbn ct prefs fileContents modTime pp nb windows =
-- display a file
case textEditorType prefs of
"GtkSourceView" -> newGtkBuffer mbfn fileContents >>= makeBuffer modTime
"Yi" -> newYiBuffer mbfn fileContents >>= makeBuffer modTime
"CodeMirror" -> newCMBuffer mbfn fileContents >>= makeBuffer modTime
_ -> newDefaultBuffer mbfn fileContents >>= makeBuffer modTime
where
makeBuffer :: TextEditor editor => Maybe UTCTime -> EditorBuffer editor -> IDEM (Maybe IDEBuffer,Connections)
makeBuffer modTime buffer = do
ideR <- ask
beginNotUndoableAction buffer
let mod = modFromFileName mbfn
when (bs && isHaskellMode mod) $ modeTransformToCandy mod
(modeEditInCommentOrString mod) buffer
endNotUndoableAction buffer
setModified buffer False
siter <- getStartIter buffer
placeCursor buffer siter
iter <- getEndIter buffer
-- create a new SourceView Widget
sv <- newView buffer (textviewFont prefs)
setShowLineNumbers sv $ showLineNumbers prefs
setRightMargin sv $ case rightMargin prefs of
(False,_) -> Nothing
(True,v) -> Just v
setIndentWidth sv $ tabWidth prefs
setTabWidth sv 8 -- GHC treats tabs as 8 we should display them that way
drawTabs sv
updateStyle buffer
-- put it in a scrolled window
sw <- getScrolledWindow sv
if wrapLines prefs
then liftIO $ scrolledWindowSetPolicy sw PolicyNever PolicyAutomatic
else liftIO $ scrolledWindowSetPolicy sw PolicyAutomatic PolicyAutomatic
liftIO $ scrolledWindowSetShadowType sw ShadowIn
modTimeRef <- liftIO $ newIORef modTime
let buf = IDEBuffer {
fileName = mbfn,
bufferName = bn,
addedIndex = ind,
sourceView =sv,
scrolledWindow = sw,
modTime = modTimeRef,
mode = mod}
-- events
ids1 <- sv `afterFocusIn` makeActive buf
ids2 <- onCompletion sv (Completion.complete sv False) Completion.cancel
ids3 <- onButtonPress sv $ do
click <- lift Gtk.eventClick
liftIDE $
case click of
Gtk.DoubleClick -> do
(start, end) <- getIdentifierUnderCursor buffer
selectRange buffer start end
return True
_ -> return False
(GetTextPopup mbTpm) <- triggerEvent ideR (GetTextPopup Nothing)
ids4 <- case mbTpm of
Just tpm -> sv `onPopulatePopup` \menu -> liftIO $ tpm ideR menu
Nothing -> do
sysMessage Normal "SourceBuffer>> no text popup"
return []
hasMatch <- liftIO $ newIORef False
ids5 <- onSelectionChanged buffer $ do
(iStart, iEnd) <- getSelectionBounds buffer
lStart <- (+1) <$> getLine iStart
cStart <- getLineOffset iStart
lEnd <- (+1) <$> getLine iEnd
cEnd <- getLineOffset iEnd
triggerEventIDE_ . SelectSrcSpan $
case mbfn of
Just fn -> Just (SrcSpan fn lStart cStart lEnd cEnd)
Nothing -> Nothing
let tagName = "match"
hasSelection <- hasSelection buffer
m <- liftIO $ readIORef hasMatch
when m $ removeTagByName buffer tagName
r <- if hasSelection
then do
candy' <- readIDE candy
sTxt <- getCandylessPart candy' buffer iStart iEnd
let strippedSTxt = T.strip sTxt
if T.null strippedSTxt
then return False
else do
bi1 <- getStartIter buffer
bi2 <- getEndIter buffer
r1 <- forwardApplying bi1 strippedSTxt (Just iStart) tagName buffer
r2 <- forwardApplying iEnd strippedSTxt (Just bi2) tagName buffer
return (r1 || r2)
else return False
liftIO $ writeIORef hasMatch r
return ()
ids6 <- onKeyPress sv $ do
keyval <- lift eventKeyVal
name <- lift eventKeyName
modifier <- lift eventModifier
liftIDE $ do
let moveToNextWord iterOp sel = do
sel' <- iterOp sel
rs <- isRangeStart sel'
if rs then return sel' else moveToNextWord iterOp sel'
let calculateNewPosition iterOp = getInsertIter buffer >>= moveToNextWord iterOp
let continueSelection keepSelBound nsel = do
if keepSelBound
then do
sb <- getSelectionBoundMark buffer >>= getIterAtMark buffer
selectRange buffer nsel sb
else
placeCursor buffer nsel
scrollToIter sv nsel 0 Nothing
case (name, map mapControlCommand modifier, keyval) of
("Left",[Gtk.Control],_) -> do
calculateNewPosition backwardCharC >>= continueSelection False
return True
("Left",[Gtk.Shift, Gtk.Control],_) -> do
calculateNewPosition backwardCharC >>= continueSelection True
return True
("Right",[Gtk.Control],_) -> do
calculateNewPosition forwardCharC >>= continueSelection False --placeCursor buffer
return True
("Right",[Gtk.Shift, Gtk.Control],_) -> do
calculateNewPosition forwardCharC >>= continueSelection True
return True
("BackSpace",[Gtk.Control],_) -> do -- delete word
here <- getInsertIter buffer
there <- calculateNewPosition backwardCharC
delete buffer here there
return True
("underscore",[Gtk.Shift, Gtk.Control],_) -> do
(start, end) <- getIdentifierUnderCursor buffer
slice <- getSlice buffer start end True
triggerEventIDE (SelectInfo slice False)
return True
-- Redundant should become a go to definition directly
("minus",[Gtk.Control],_) -> do
(start, end) <- getIdentifierUnderCursor buffer
slice <- getSlice buffer start end True
triggerEventIDE (SelectInfo slice True)
return True
_ ->
-- liftIO $ print ("sourcebuffer key:",name,modifier,keyval)
return False
ids7 <- do
ideR <- ask
sw <- getScrolledWindow sv
createHyperLinkSupport sv sw (\ctrl shift iter -> do
(beg, en) <- getIdentifierUnderCursorFromIter (iter, iter)
return (beg, if ctrl then en else beg)) (\_ shift' slice ->
unless (T.null slice) $ do
-- liftIO$ print ("slice",slice)
triggerEventIDE (SelectInfo slice shift')
return ()
)
return (Just buf,concat [ids1, ids2, ids3, ids4, ids5, ids6, ids7])
forwardApplying :: TextEditor editor
=> EditorIter editor
-> Text -- txt
-> Maybe (EditorIter editor)
-> Text -- tagname
-> EditorBuffer editor
-> IDEM Bool
forwardApplying tI txt mbTi tagName ebuf = do
mbFTxt <- forwardSearch tI txt [TextSearchVisibleOnly, TextSearchTextOnly] mbTi
case mbFTxt of
Just (start, end) -> do
startsWord <- startsWord start
endsWord <- endsWord end
when (startsWord && endsWord) $
applyTagByName ebuf tagName start end
(|| (startsWord && endsWord)) <$> forwardApplying end txt mbTi tagName ebuf
Nothing -> return False
isIdent a = isAlphaNum a || a == '\'' || a == '_' -- parts of haskell identifiers
isRangeStart sel = do -- if char and previous char are of different char categories
currentChar <- getChar sel
let mbStartCharCat = getCharacterCategory currentChar
mbPrevCharCat <- getCharacterCategory <$> (backwardCharC sel >>= getChar)
return $ isNothing currentChar || currentChar == Just '\n' || mbStartCharCat /= mbPrevCharCat && (mbStartCharCat == SyntaxCharacter || mbStartCharCat == IdentifierCharacter)
-- | Get an iterator pair (start,end) delimiting the identifier currently under the cursor
getIdentifierUnderCursor :: forall editor. TextEditor editor => EditorBuffer editor -> IDEM (EditorIter editor, EditorIter editor)
getIdentifierUnderCursor buffer = do
(startSel, endSel) <- getSelectionBounds buffer
getIdentifierUnderCursorFromIter (startSel, endSel)
-- | Get an iterator pair (start,end) delimiting the identifier currently contained inside the provided iterator pair
getIdentifierUnderCursorFromIter :: TextEditor editor => (EditorIter editor, EditorIter editor) -> IDEM (EditorIter editor, EditorIter editor)
getIdentifierUnderCursorFromIter (startSel, endSel) = do
let isIdent a = isAlphaNum a || a == '\'' || a == '_'
let isOp a = isSymbol a || a == ':' || a == '\\' || a == '*' || a == '/' || a == '-'
|| a == '!' || a == '@' || a == '%' || a == '&' || a == '?'
mbStartChar <- getChar startSel
mbEndChar <- getChar endSel
let isSelectChar =
case mbStartChar of
Just startChar | isIdent startChar -> isIdent
Just startChar | isOp startChar -> isOp
_ -> const False
start <- case mbStartChar of
Just startChar | isSelectChar startChar -> do
maybeIter <- backwardFindCharC startSel (not.isSelectChar) Nothing
case maybeIter of
Just iter -> forwardCharC iter
Nothing -> return startSel
_ -> return startSel
end <- case mbEndChar of
Just endChar | isSelectChar endChar -> do
maybeIter <- forwardFindCharC endSel (not.isSelectChar) Nothing
case maybeIter of
Just iter -> return iter
Nothing -> return endSel
_ -> return endSel
return (start, end)
checkModTime :: MonadIDE m => IDEBuffer -> m (Bool, Bool)
checkModTime buf = do
currentState' <- readIDE currentState
case currentState' of
IsShuttingDown -> return (False, False)
_ -> do
let name = paneName buf
case fileName buf of
Just fn -> do
exists <- liftIO $ doesFileExist fn
if exists
then do
nmt <- liftIO $ getModificationTime fn
modTime' <- liftIO $ readIORef (modTime buf)
case modTime' of
Nothing -> error $"checkModTime: time not set " ++ show (fileName buf)
Just mt ->
if nmt /= mt -- Fonts get messed up under windows when adding this line.
-- Praises to whoever finds out what happens and how to fix this
then do
load <- readIDE (autoLoad . prefs)
if load
then do
ideMessage Normal $ __ "Auto Loading " <> T.pack fn
revert buf
return (False, True)
else do
window <- liftIDE getMainWindow
resp <- liftIO $ do
md <- messageDialogNew
(Just window) []
MessageQuestion
ButtonsNone
(__ "File \"" <> name <> __ "\" has changed on disk.")
dialogAddButton md (__ "_Load From Disk") (ResponseUser 1)
dialogAddButton md (__ "_Always Load From Disk") (ResponseUser 2)
dialogAddButton md (__ "_Don't Load") (ResponseUser 3)
dialogSetDefaultResponse md (ResponseUser 1)
set md [ windowWindowPosition := WinPosCenterOnParent ]
resp <- dialogRun md
widgetDestroy md
return resp
case resp of
ResponseUser 1 -> do
revert buf
return (False, True)
ResponseUser 2 -> do
revert buf
modifyIDE_ $ \ide -> ide{prefs = (prefs ide) {autoLoad = True}}
return (False, True)
ResponseUser 3 -> do
nmt2 <- liftIO $ getModificationTime fn
liftIO $ writeIORef (modTime buf) (Just nmt2)
return (True, True)
_ -> return (False, False)
else return (False, False)
else return (False, False)
Nothing -> return (False, False)
setModTime :: IDEBuffer -> IDEAction
setModTime buf = do
let name = paneName buf
case fileName buf of
Nothing -> return ()
Just fn -> liftIO $ E.catch
(do
nmt <- getModificationTime fn
writeIORef (modTime buf) (Just nmt))
(\(e:: SomeException) -> do
sysMessage Normal (T.pack $ show e)
return ())
fileRevert :: IDEAction
fileRevert = inActiveBufContext () $ \ _ _ _ currentBuffer _ ->
revert currentBuffer
revert :: MonadIDE m => IDEBuffer -> m ()
revert (buf@IDEBuffer{sourceView = sv}) = do
useCandy <- useCandyFor buf
ct <- readIDE candy
let name = paneName buf
case fileName buf of
Nothing -> return ()
Just fn -> liftIDE $ do
buffer <- getBuffer sv
fc <- liftIO $ readFile fn
mt <- liftIO $ getModificationTime fn
beginNotUndoableAction buffer
setText buffer $ T.pack fc
when useCandy $
modeTransformToCandy (mode buf)
(modeEditInCommentOrString (mode buf))
buffer
endNotUndoableAction buffer
setModified buffer False
return mt
liftIO $ writeIORef (modTime buf) (Just mt)
writeCursorPositionInStatusbar :: TextEditor editor => EditorView editor -> IDEAction
writeCursorPositionInStatusbar sv = do
buf <- getBuffer sv
mark <- getInsertMark buf
iter <- getIterAtMark buf mark
line <- getLine iter
col <- getLineOffset iter
triggerEventIDE (StatusbarChanged [CompartmentBufferPos (line,col)])
return ()
writeOverwriteInStatusbar :: TextEditor editor => EditorView editor -> IDEAction
writeOverwriteInStatusbar sv = do
mode <- getOverwrite sv
triggerEventIDE (StatusbarChanged [CompartmentOverlay mode])
return ()
selectInfo :: TextEditor editor => EditorView editor -> IDEAction
selectInfo sv = do
ideR <- ask
buf <- getBuffer sv
(l,r) <- getIdentifierUnderCursor buf
symbol <- getText buf l r True
triggerEvent ideR (SelectInfo symbol False)
return ()
markActiveLabelAsChanged :: IDEAction
markActiveLabelAsChanged = do
mbPath <- getActivePanePath
case mbPath of
Nothing -> return ()
Just path -> do
nb <- getNotebook path
mbBS <- maybeActiveBuf
F.forM_ mbBS (markLabelAsChanged nb)
markLabelAsChanged :: Notebook -> IDEBuffer -> IDEAction
markLabelAsChanged nb (buf@IDEBuffer{sourceView = sv}) = do
ebuf <- getBuffer sv
modified <- getModified ebuf
liftIO $ markLabel nb (getTopWidget buf) modified
fileSaveBuffer :: MonadIDE m => TextEditor editor => Bool -> Notebook -> EditorView editor -> EditorBuffer editor -> IDEBuffer -> Int -> m Bool
fileSaveBuffer query nb _ ebuf (ideBuf@IDEBuffer{sourceView = sv}) i = liftIDE $ do
ideR <- ask
window <- getMainWindow
prefs <- readIDE prefs
useCandy <- useCandyFor ideBuf
candy <- readIDE candy
(panePath,connects) <- guiPropertiesFromName (paneName ideBuf)
let mbfn = fileName ideBuf
mbpage <- liftIO $ notebookGetNthPage nb i
case mbpage of
Nothing -> throwIDE (__ "fileSave: Page not found")
Just page ->
if isJust mbfn && not query
then do (modifiedOnDiskNotLoaded, modifiedOnDisk) <- checkModTime ideBuf -- The user is given option to reload
modifiedInBuffer <- getModified ebuf
if modifiedOnDiskNotLoaded || modifiedInBuffer
then do
fileSave' (forceLineEnds prefs) (removeTBlanks prefs) nb ideBuf
useCandy candy $fromJust mbfn
setModTime ideBuf
return True
else return modifiedOnDisk
else reifyIDE $ \ideR -> do
dialog <- fileChooserDialogNew
(Just $ __ "Save File")
(Just window)
FileChooserActionSave
[("gtk-cancel" --buttons to display
,ResponseCancel) --you can use stock buttons
,("gtk-save"
, ResponseAccept)]
case mbfn of
Just fn -> void (fileChooserSelectFilename dialog fn)
Nothing -> return ()
widgetShow dialog
response <- dialogRun dialog
mbFileName <- case response of
ResponseAccept -> fileChooserGetFilename dialog
ResponseCancel -> return Nothing
ResponseDeleteEvent-> return Nothing
_ -> return Nothing
widgetDestroy dialog
case mbFileName of
Nothing -> return False
Just fn -> do
dfe <- doesFileExist fn
resp <- if dfe
then do md <- messageDialogNew (Just window) []
MessageQuestion
ButtonsCancel
(__ "File already exist.")
dialogAddButton md (__ "_Overwrite") ResponseYes
dialogSetDefaultResponse md ResponseCancel
set md [ windowWindowPosition := WinPosCenterOnParent ]
resp <- dialogRun md
widgetHide md
return resp
else return ResponseYes
case resp of
ResponseYes -> do
reflectIDE (do
fileSave' (forceLineEnds prefs) (removeTBlanks prefs)
nb ideBuf useCandy candy fn
closePane ideBuf
cfn <- liftIO $ myCanonicalizePath fn
newTextBuffer panePath (T.pack $ takeFileName cfn) (Just cfn)
) ideR
return True
_ -> return False
where
fileSave' :: Bool -> Bool -> Notebook -> IDEBuffer -> Bool -> CandyTable -> FilePath -> IDEAction
fileSave' forceLineEnds removeTBlanks nb ideBuf useCandy candyTable fn = do
buf <- getBuffer sv
text <- getCandylessText candyTable buf
let text' = if removeTBlanks
then T.unlines $ map (T.dropWhileEnd $ \c -> c == ' ') $ T.lines text
else text
alreadyExists <- liftIO $ doesFileExist fn
mbModTimeBefore <- if alreadyExists
then liftIO $ Just <$> getModificationTime fn
else return Nothing
succ <- liftIO $ E.catch (do T.writeFile fn text'; return True)
(\(e :: SomeException) -> do
sysMessage Normal . T.pack $ show e
return False)
-- Truely horrible hack to work around HFS+ only having 1sec resolution
-- and ghc ignoring files unless the modifiction time has moved forward.
-- The limitation means we can do at most 1 reload a second, but
-- this hack allows us to take an advance of up to 30 reloads (by
-- moving the modidification time up to 30s into the future).
modTimeChanged <- liftIO $ case mbModTimeBefore of
Nothing -> return True
Just modTime -> do
newModTime <- getModificationTime fn
let diff = diffUTCTime modTime newModTime
if
| (newModTime > modTime) -> return True -- All good mode time has moved on
| diff < 30 -> do
setModificationTimeOnOSX fn (addUTCTime 1 modTime)
updatedModTime <- getModificationTime fn
return (updatedModTime > modTime)
| diff < 32 -> do
-- Reached our limit of how far in the future we want to set the modifiction time.
-- Using 32 instead of 31 in case NTP or something is adjusting the clock back.
warningM "leksah" $ "Modification time for " <> fn
<> " was already " <> show (diffUTCTime modTime newModTime)
<> " in the future"
-- We still want to keep the modification time the same though.
-- If it went back the future date ghc has might cause it to
-- continue to ignore the file.
setModificationTimeOnOSX fn modTime
return False
| otherwise -> do
-- This should never happen unless something else is messing
-- with the modification time or the clock.
-- If it does happen we will leave the modifiction time alone.
errorM "leksah" $ "Modification time for " <> fn
<> " was already " <> show (diffUTCTime modTime newModTime)
<> " in the future"
return True
-- Only consider the file saved if the modification time changed
-- otherwise another save is really needed to trigger ghc.
when modTimeChanged $ do
setModified buf (not succ)
markLabelAsChanged nb ideBuf
triggerEventIDE_ $ SavedFile fn
fileSave :: Bool -> IDEM Bool
fileSave query = inActiveBufContext False $ fileSaveBuffer query
fileSaveAll :: MonadIDE m => (IDEBuffer -> m Bool) -> m Bool
fileSaveAll filterFunc = do
bufs <- allBuffers
filtered <- filterM filterFunc bufs
results <- forM filtered (\buf -> inBufContext False buf (fileSaveBuffer False))
return $ True `elem` results
fileCheckBuffer :: (MonadIDE m, TextEditor editor) => Notebook -> EditorView editor -> EditorBuffer editor -> IDEBuffer -> Int -> m Bool
fileCheckBuffer nb _ ebuf ideBuf i = do
let mbfn = fileName ideBuf
if isJust mbfn
then do (_, modifiedOnDisk) <- checkModTime ideBuf -- The user is given option to reload
modifiedInBuffer <- liftIDE $ getModified ebuf
return (modifiedOnDisk || modifiedInBuffer)
else return False
fileCheckAll :: MonadIDE m => (IDEBuffer -> m [alpha]) -> m [alpha]
fileCheckAll filterFunc = do
bufs <- allBuffers
liftM concat . forM bufs $ \ buf -> do
ps <- filterFunc buf
case ps of
[] -> return []
_ -> do
modified <- inBufContext False buf fileCheckBuffer
if modified
then return ps
else return []
fileNew :: IDEAction
fileNew = do
prefs <- readIDE prefs
pp <- getBestPathForId "*Buffer"
newTextBuffer pp (__ "Unnamed") Nothing
return ()
fileClose :: IDEM Bool
fileClose = inActiveBufContext True fileClose'
fileClose' :: TextEditor editor => Notebook -> EditorView editor -> EditorBuffer editor -> IDEBuffer -> Int -> IDEM Bool
fileClose' nb _ ebuf currentBuffer i = do
window <- getMainWindow
modified <- getModified ebuf
cancel <- reifyIDE $ \ideR ->
if modified
then do
md <- messageDialogNew (Just window) []
MessageQuestion
ButtonsCancel
(__ "Save changes to document: "
<> paneName currentBuffer
<> "?")
dialogAddButton md (__ "_Save") ResponseYes
dialogAddButton md (__ "_Don't Save") ResponseNo
set md [ windowWindowPosition := WinPosCenterOnParent ]
resp <- dialogRun md
widgetDestroy md
case resp of
ResponseYes -> do
reflectIDE (fileSave False) ideR
return False
ResponseCancel -> return True
ResponseNo -> return False
_ -> return False
else return False
if cancel
then return False
else do
closeThisPane currentBuffer
F.forM_ (fileName currentBuffer) addRecentlyUsedFile
return True
fileCloseAll :: (IDEBuffer -> IDEM Bool) -> IDEM Bool
fileCloseAll filterFunc = do
bufs <- allBuffers
filtered <- filterM filterFunc bufs
if null filtered
then return True
else do
makeActive (head filtered)
r <- fileClose
if r
then fileCloseAll filterFunc
else return False
fileCloseAllButPackage :: IDEAction
fileCloseAllButPackage = do
mbActivePath <- fmap ipdPackageDir <$> readIDE activePack
bufs <- allBuffers
case mbActivePath of
Just p -> mapM_ (close' p) bufs
Nothing -> return ()
where
close' dir (buf@IDEBuffer {sourceView = sv}) = do
(pane,_) <- guiPropertiesFromName (paneName buf)
nb <- getNotebook pane
mbI <- liftIO $notebookPageNum nb (scrolledWindow buf)
case mbI of
Nothing -> throwIDE (__ "notebook page not found: unexpected")
Just i -> do
ebuf <- getBuffer sv
when (isJust (fileName buf)) $ do
modified <- getModified ebuf
when (not modified && not (isSubPath dir (fromJust (fileName buf))))
$ do fileClose' nb sv ebuf buf i; return ()
fileCloseAllButWorkspace :: IDEAction
fileCloseAllButWorkspace = do
mbWorkspace <- readIDE workspace
bufs <- allBuffers
when (not (null bufs) && isJust mbWorkspace) $
mapM_ (close' (fromJust mbWorkspace)) bufs
where
close' workspace (buf@IDEBuffer {sourceView = sv}) = do
(pane,_) <- guiPropertiesFromName (paneName buf)
nb <- getNotebook pane
mbI <- liftIO $notebookPageNum nb (scrolledWindow buf)
case mbI of
Nothing -> throwIDE (__ "notebook page not found: unexpected")
Just i -> do
ebuf <- getBuffer sv
when (isJust (fileName buf)) $ do
modified <- getModified ebuf
when (not modified && not (isSubPathOfAny workspace (fromJust (fileName buf))))
$ do fileClose' nb sv ebuf buf i; return ()
isSubPathOfAny workspace fileName =
let paths = wsPackages workspace >>= ipdAllDirs
in any (`isSubPath` fileName) paths
fileOpenThis :: FilePath -> IDEAction
fileOpenThis fp = do
liftIO . debugM "leksah" $ "fileOpenThis " ++ fp
prefs <- readIDE prefs
fpc <- liftIO $ myCanonicalizePath fp
buffers <- allBuffers
let buf = filter (\b -> case fileName b of
Just fn -> equalFilePath fn fpc
Nothing -> False) buffers
case buf of
hdb:tl -> do
window <- getMainWindow
resp <- liftIO $ do
md <- messageDialogNew
(Just window) []
MessageQuestion
ButtonsNone
(__ "Buffer already open.")
dialogAddButton md (__ "Make _Active") (ResponseUser 1)
dialogAddButton md (__ "_Open Second") (ResponseUser 2)
dialogSetDefaultResponse md (ResponseUser 1)
set md [ windowWindowPosition := WinPosCenterOnParent ]
resp <- dialogRun md
widgetDestroy md
return resp
case resp of
ResponseUser 2 -> reallyOpen prefs fpc
_ -> makeActive hdb
[] -> reallyOpen prefs fpc
where
reallyOpen prefs fpc = do
pp <- getBestPathForId "*Buffer"
newTextBuffer pp (T.pack $ takeFileName fpc) (Just fpc)
return ()
filePrint :: IDEAction
filePrint = inActiveBufContext () filePrint'
filePrint' :: TextEditor editor => Notebook -> EditorView view -> EditorBuffer editor -> IDEBuffer -> Int -> IDEM ()
filePrint' nb _ ebuf currentBuffer _ = do
let pName = paneName currentBuffer
window <- getMainWindow
print <- reifyIDE $ \ideR -> do
md <- messageDialogNew (Just window) []
MessageQuestion
ButtonsNone
(__"Print document: "
<> pName
<> "?")
dialogAddButton md (__"_Print") ResponseYes
dialogAddButton md (__"_Don't Print") ResponseNo
set md [ windowWindowPosition := WinPosCenterOnParent ]
resp <- dialogRun md
widgetDestroy md
case resp of
ResponseYes -> return True
ResponseCancel -> return False
ResponseNo -> return False
_ -> return False
when print $ do
--real code
modified <- getModified ebuf
cancel <- reifyIDE $ \ideR ->
if modified
then do
md <- messageDialogNew (Just window) []
MessageQuestion
ButtonsNone
(__"Save changes to document: "
<> pName
<> "?")
dialogAddButton md (__"_Save") ResponseYes
dialogAddButton md (__"_Don't Save") ResponseNo
dialogAddButton md (__"_Cancel Printing") ResponseCancel
set md [ windowWindowPosition := WinPosCenterOnParent ]
resp <- dialogRun md
widgetDestroy md
case resp of
ResponseYes -> do
reflectIDE (fileSave False) ideR
return False
ResponseCancel -> return True
ResponseNo -> return False
_ -> return False
else
return False
unless cancel $
case fileName currentBuffer of
Just name -> do
status <- liftIO $ Print.print name
case status of
Left error -> liftIO $ showDialog (T.pack $ show error) MessageError
Right _ -> liftIO $ showDialog "Print job has been sent successfully" MessageInfo
return ()
Nothing -> return ()
editUndo :: IDEAction
editUndo = inActiveBufContext () $ \_ view buf _ _ -> do
can <- canUndo buf
when can $ do
undo buf
scrollToCursor view
editRedo :: IDEAction
editRedo = inActiveBufContext () $ \_ view buf _ _ -> do
can <- canRedo buf
when can $ redo buf
scrollToCursor view
editDelete :: IDEAction
editDelete = inActiveBufContext () $ \_ view ebuf _ _ -> do
deleteSelection ebuf
scrollToCursor view
editSelectAll :: IDEAction
editSelectAll = inActiveBufContext () $ \_ _ ebuf _ _ -> do
start <- getStartIter ebuf
end <- getEndIter ebuf
selectRange ebuf start end
editCut :: IDEAction
editCut = inActiveBufContext () $ \_ _ ebuf _ _ -> do
clip <- liftIO $ clipboardGet selectionClipboard
cutClipboard ebuf clip True
editCopy :: IDEAction
editCopy = inActiveBufContext () $ \_ view ebuf _ _ -> do
clip <- liftIO $ clipboardGet selectionClipboard
copyClipboard ebuf clip
scrollToCursor view
editPaste :: IDEAction
editPaste = inActiveBufContext () $ \_ _ ebuf _ _ -> do
mark <- getInsertMark ebuf
iter <- getIterAtMark ebuf mark
clip <- liftIO $ clipboardGet selectionClipboard
pasteClipboard ebuf clip iter True
editShiftLeft :: IDEAction
editShiftLeft = do
prefs <- readIDE prefs
let str = T.replicate (tabWidth prefs) " "
b <- canShiftLeft str prefs
when b $ do
doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
sol2 <- forwardCharsC sol (tabWidth prefs)
delete ebuf sol sol2
return ()
where
canShiftLeft str prefs = do
boolList <- doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
sol2 <- forwardCharsC sol (tabWidth prefs)
str1 <- getText ebuf sol sol2 True
return (str1 == str)
return (F.foldl' (&&) True boolList)
editShiftRight :: IDEAction
editShiftRight = do
prefs <- readIDE prefs
let str = T.replicate (tabWidth prefs) " "
doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
insert ebuf sol str
return ()
alignChar :: Char -> IDEAction
alignChar char = do
positions <- positionsOfChar
let alignTo = F.foldl' max 0 (mapMaybe snd positions)
when (alignTo > 0) $ alignChar (Map.fromList positions) alignTo
where
positionsOfChar :: IDEM [(Int, Maybe Int)]
positionsOfChar = doForSelectedLines [] $ \ebuf lineNr -> do
sol <- getIterAtLine ebuf lineNr
eol <- forwardToLineEndC sol
line <- getText ebuf sol eol True
return (lineNr, T.findIndex (==char) line)
alignChar :: Map Int (Maybe Int) -> Int -> IDEM ()
alignChar positions alignTo = do
doForSelectedLines [] $ \ebuf lineNr ->
case lineNr `Map.lookup` positions of
Just (Just n) -> do
sol <- getIterAtLine ebuf lineNr
insertLoc <- forwardCharsC sol n
insert ebuf insertLoc (T.replicate (alignTo - n) " ")
_ -> return ()
return ()
transChar :: Char -> Char
transChar ':' = toEnum 0x2237 --PROPORTION
transChar '>' = toEnum 0x2192 --RIGHTWARDS ARROW
transChar '<' = toEnum (toEnum 0x2190) --LEFTWARDS ARROW
transChar c = c
align :: Char -> IDEAction
align = alignChar . transChar
addRecentlyUsedFile :: FilePath -> IDEAction
addRecentlyUsedFile fp = do
state <- readIDE currentState
unless (isStartingOrClosing state) $ do
recentFiles' <- readIDE recentFiles
unless (fp `elem` recentFiles') $
modifyIDE_ (\ide -> ide{recentFiles = take 12 (fp : recentFiles')})
triggerEventIDE UpdateRecent
return ()
removeRecentlyUsedFile :: FilePath -> IDEAction
removeRecentlyUsedFile fp = do
state <- readIDE currentState
unless (isStartingOrClosing state) $ do
recentFiles' <- readIDE recentFiles
when (fp `elem` recentFiles') $
modifyIDE_ (\ide -> ide{recentFiles = filter (/= fp) recentFiles'})
triggerEventIDE UpdateRecent
return ()
-- | Get the currently selected text or Nothing is no text is selected
selectedText :: IDEM (Maybe Text)
selectedText = do
candy' <- readIDE candy
inActiveBufContext Nothing $ \_ _ ebuf currentBuffer _ -> do
hasSelection <- hasSelection ebuf
if hasSelection
then do
(i1,i2) <- getSelectionBounds ebuf
text <- getCandylessPart candy' ebuf i1 i2
return $ Just text
else return Nothing
-- | Get the currently selected text, or, if none, the current line text
selectedTextOrCurrentLine :: IDEM (Maybe Text)
selectedTextOrCurrentLine = do
candy' <- readIDE candy
inActiveBufContext Nothing $ \_ _ ebuf currentBuffer _ -> do
hasSelection <- hasSelection ebuf
(i1, i2) <- if hasSelection
then getSelectionBounds ebuf
else do
(i, _) <- getSelectionBounds ebuf
line <- getLine i
iStart <- getIterAtLine ebuf line
iEnd <- forwardToLineEndC iStart
return (iStart, iEnd)
Just <$> getCandylessPart candy' ebuf i1 i2
-- | Get the currently selected text, or, if none, tries to selected the current identifier (the one under the cursor)
selectedTextOrCurrentIdentifier :: IDEM (Maybe Text)
selectedTextOrCurrentIdentifier = do
st <- selectedText
case st of
Just t -> return $ Just t
Nothing -> do
candy' <- readIDE candy
inActiveBufContext Nothing $ \_ _ ebuf currentBuffer _ -> do
(l,r) <- getIdentifierUnderCursor ebuf
t <- getCandylessPart candy' ebuf l r
return $ if T.null t
then Nothing
else Just t
selectedLocation :: IDEM (Maybe (Int, Int))
selectedLocation = do
candy' <- readIDE candy
inActiveBufContext Nothing $ \_ _ ebuf currentBuffer _ -> do
useCandy <- useCandyFor currentBuffer
(start, _) <- getSelectionBounds ebuf
line <- getLine start
lineOffset <- getLineOffset start
res <- if useCandy
then positionFromCandy candy' ebuf (line, lineOffset)
else return (line, lineOffset)
return $ Just res
insertTextAfterSelection :: Text -> IDEAction
insertTextAfterSelection str = do
candy' <- readIDE candy
inActiveBufContext () $ \_ _ ebuf currentBuffer _ -> do
useCandy <- useCandyFor currentBuffer
hasSelection <- hasSelection ebuf
when hasSelection $ do
realString <- if useCandy then stringToCandy candy' str else return str
(_,i) <- getSelectionBounds ebuf
insert ebuf i realString
(_,i1) <- getSelectionBounds ebuf
i2 <- forwardCharsC i1 (T.length realString)
selectRange ebuf i1 i2
-- | Returns the packages to which this file belongs
-- uses the 'bufferProjCache' and might extend it
belongsToPackages :: MonadIDE m => FilePath -> m [IDEPackage]
belongsToPackages fp = do
bufferToProject' <- readIDE bufferProjCache
ws <- readIDE workspace
case Map.lookup fp bufferToProject' of
Just p -> return p
Nothing -> case ws of
Nothing -> return []
Just workspace -> do
let res = filter (belongsToPackage fp) (wsPackages workspace)
modifyIDE_ (\ide -> ide{bufferProjCache = Map.insert fp res bufferToProject'})
return res
-- | Returns the packages to which this buffer belongs
-- uses the 'bufferProjCache' and might extend it
belongsToPackages' :: MonadIDE m => IDEBuffer -> m [IDEPackage]
belongsToPackages' = maybe (return []) belongsToPackages . fileName
-- | Checks whether a file belongs to a package (includes files in
-- sandbox source dirs)
belongsToPackage :: FilePath -> IDEPackage -> Bool
belongsToPackage f = any (`isSubPath` f) . ipdAllDirs
-- | Checks whether a file belongs to the workspace
belongsToWorkspace :: MonadIDE m => FilePath -> m Bool
belongsToWorkspace fp = liftM (not . null) (belongsToPackages fp)
-- | Checks whether a file belongs to the workspace
belongsToWorkspace' :: MonadIDE m => IDEBuffer -> m Bool
belongsToWorkspace' = maybe (return False) belongsToWorkspace . fileName
useCandyFor :: MonadIDE m => IDEBuffer -> m Bool
useCandyFor aBuffer = do
prefs <- readIDE prefs
return (candyState prefs && isHaskellMode (mode aBuffer))
switchBuffersCandy :: IDEAction
switchBuffersCandy = do
prefs <- readIDE prefs
buffers <- allBuffers
forM_ buffers $ \b@IDEBuffer{sourceView=sv} -> do
buf <- getBuffer sv
if candyState prefs
then modeTransformToCandy (mode b) (modeEditInCommentOrString (mode b)) buf
else modeTransformFromCandy (mode b) buf
| jaccokrijnen/leksah | src/IDE/Pane/SourceBuffer.hs | gpl-2.0 | 67,511 | 0 | 40 | 25,999 | 16,409 | 7,901 | 8,508 | 1,324 | 22 |
module Main where
import HOpenCV.OpenCV
import HOpenCV.HighImage
import HOpenCV.HCxCore
import HOpenCV.HVideo
import Control.Monad
import Data.Maybe (isNothing)
showFrames :: String -> IplImage -> Capture -> IO ()
showFrames win target cap = do
let step 0 = return ()
step n = do
frame <- queryFrameCV cap
convertImage frame target 0
canny target target 30 190 3
showImage win target
k <- waitKey 5
case k of
(Return c) -> putStr $ "\r" ++ show n ++ "\t\t frames before exiting...\r"
(Raise s) -> step (n - 1)
step 1000
main :: IO ()
main = do
putStrLn "Running..."
let win = "win"
namedWindow win autoSize
cap <- createCameraCaptureCV 0
frame <- queryFrameCV cap
size <- getSizeCV frame
print ("Size (" ++ show (sizeWidth size) ++ "," ++ show (sizeHeight size) ++ ")\n")
target <- createImageCV size iplDepth8u 1
showFrames win target cap
putStrLn "Fin"
| juanmab37/HOpenCV-0.5.0.1 | src/examples/cannyVideo.hs | gpl-2.0 | 985 | 0 | 17 | 274 | 353 | 163 | 190 | 32 | 3 |
-- Copyright (C) 2006-2013 Angelos Charalambidis <a.charalambidis@di.uoa.gr>
--
-- Adapted from the paper
-- Backtracking, Interleaving, and Terminating Monad Transformers, by
-- Oleg Kiselyov, Chung-chieh Shan, Daniel P. Friedman, Amr Sabry
-- (http://www.cs.rutgers.edu/~ccshan/logicprog/LogicT-icfp2005.pdf)
--
-- 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, 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; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# LANGUAGE MultiParamTypeClasses #-}
module Infer.Class (
module Infer.Class,
module Logic.Class
) where
import Logic.Class
import Lang
import Types
import CoreLang
class (Symbol a, HasType a) => MonadFreeVarProvider a m where
freshVarOfType :: Type -> m a
class Monad m => MonadClauseProvider a m where
clausesOf :: a -> m [Expr a]
| acharal/hopes | src/prover/Infer/Class.hs | gpl-2.0 | 1,420 | 0 | 10 | 258 | 130 | 80 | 50 | 12 | 0 |
-- implements Spec128/128 - as defined in http://eprint.iacr.org/2013/404.pdf
-- Frank Recker, 2013
module Speck(self_test,key_expansion,encryption,decryption) where
import Data.Bits
import Data.Word
-- Tests the test vector
self_test
| cipher /= cipher' = error "encryption failed"
| plain /= plain' = error "decryption failed"
| otherwise = True
where
keys = [0x0f0e0d0c0b0a0908,0x0706050403020100]
plain = (0x6c61766975716520,0x7469206564616d20)
cipher = (0xa65d985179783265,0x7860fedf5c570d18)
rks = key_expansion keys
cipher' = uncurry (encryption rks) plain
plain' = uncurry (decryption (reverse rks)) cipher'
-- keys are in the order 1 0
-- round keys are in order 0..T-1
key_expansion :: [Word64] -> [Word64]
key_expansion [l0,k0] =
take 32 $ k0:help 0 l0 k0
where
help i li ki = let i' = i+1
li' = (ki + (rotate li (-8))) `xor` i
ki' = (rotate ki 3) `xor` li'
in ki':help i' li' ki'
-- round_keys are in order 0..T-1
encryption :: [Word64] -> Word64 -> Word64 -> (Word64,Word64)
encryption (k:ks) x y =
encryption ks x_new y_new
where
x_new = (rotate x (-8) + y) `xor` k
y_new = (rotate y 3) `xor` x_new
encryption [] x y = (x,y)
-- round_keys are in order T-1..0
-- in fact, this function is not used in counter-mode but provided anyway
decryption :: [Word64] -> Word64 -> Word64 -> (Word64,Word64)
decryption (k:ks) x y =
decryption ks x_new y_new
where
y_new = rotate (x `xor` y) (-3)
x_new = rotate ((x `xor` k) - y_new) 8
decryption [] x y = (x,y)
| frecker/speck | Speck.hs | gpl-2.0 | 1,597 | 0 | 17 | 375 | 542 | 299 | 243 | 32 | 1 |
module Utility where
import Control.Applicative
if' :: Bool -> a -> a -> a
if' True x _ = x
if' False _ y = y
ifF :: (a -> Bool) -> (a -> b) -> (a -> b) -> a -> b
ifF = liftA3 if'
| kmandelbaum/kamisado | src/Utility.hs | gpl-2.0 | 182 | 0 | 9 | 49 | 100 | 54 | 46 | 7 | 1 |
--
-- Copyright (c) 2014 Nicola Bonelli <nicola@pfq.io>
--
-- 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.
--
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Development.SimpleBuilder (
Target(..),
BuilderScript,
Command,
Options,
(*>>),
requires,
into,
simpleBuilder,
numberOfPhyCores,
-- predefined actions
Development.SimpleBuilder.empty,
cabalConfigure,
cabalBuild,
cabalInstall,
cabalClean,
cabalDistClean,
cmake,
cmake_distclean,
make,
make_install,
make_clean,
make_distclean,
ldconfig,
configure,
cmd
) where
import System.Console.GetOpt
import System.Directory
import System.FilePath
import System.Process
import System.Exit
import System.IO.Unsafe
import Control.Monad
import Control.Monad.Writer.Lazy
import Control.Monad.IO.Class
import Control.Monad.RWS.Lazy
import Control.Applicative
import qualified Control.Exception as E
import Data.Data
import Data.List
import Data.Maybe
-- version
verString = "v0.4" :: String
-- predefined commands
empty = return () :: Action ()
cabalConfigure = tellCmd $
DynamicCmd
(\o ->
case () of
_ | Just path <- sandbox o -> "cabal sandbox init --sandbox=" ++ path ++ " && cabal configure"
| otherwise -> "runhaskell Setup configure --user")
cabalBuild = tellCmd $ StaticCmd "runhaskell Setup build"
cabalInstall = tellCmd $ StaticCmd "runhaskell Setup install"
cabalClean = tellCmd $ StaticCmd "runhaskell Setup clean"
cabalDistClean = tellCmd $ StaticCmd "rm -rf dist; rm -f cabal.sandbox.config"
make_install = tellCmd $ StaticCmd "make install"
make_clean = tellCmd $ StaticCmd "make clean"
make_distclean = tellCmd $ StaticCmd "make distclean"
ldconfig = tellCmd $ StaticCmd "ldconfig"
configure = tellCmd $ StaticCmd "./configure"
make = tellCmd $
DynamicCmd
(\o ->
case () of
_ | jobs o == 0 -> "make"
| jobs o > numberOfPhyCores -> "make -j " ++ show (numberOfPhyCores + 1)
| otherwise -> "make -j " ++ show (jobs o))
cmake = tellCmd $
DynamicCmd
(\o ->
let build = case buildType o of
Nothing -> ""
Just Release -> "-DCMAKE_BUILD_TYPE=Release"
Just Debug -> "-DCMAKE_BUILD_TYPE=Debug"
cc = case ccComp o of
Nothing -> ""
Just xs -> "-DCMAKE_C_COMPILER=" ++ xs
cxx = case cxxComp o of
Nothing -> ""
Just xs -> "-DCMAKE_CXX_COMPILER=" ++ xs
in unwords ["cmake", build, cc, cxx, "."])
cmake_distclean :: Action ()
cmake_distclean = do
cmd "rm -f install_manifest.txt"
cmd "rm -f cmake.depends"
cmd "rm -f cmake.chek_depends"
cmd "rm -f CMakeCache.txt"
cmd "rm -f *.cmake"
cmd "rm -f Makefile"
cmd "rm -rf CMakeFiles"
cmd :: String -> Action ()
cmd xs = tell ([StaticCmd xs], [])
tellCmd :: Command -> Action ()
tellCmd c = tell ([c], [])
-- options...
data Options = Options
{ buildType :: Maybe BuildType
, cxxComp :: Maybe String
, ccComp :: Maybe String
, sandbox :: Maybe String
, dryRun :: Bool
, verbose :: Bool
, version :: Bool
, help :: Bool
, jobs :: Int
} deriving (Show, Read)
defaultOptions :: Options
defaultOptions = Options
{ buildType = Nothing
, cxxComp = Nothing
, ccComp = Nothing
, sandbox = Nothing
, dryRun = False
, verbose = False
, version = False
, help = False
, jobs = 0
}
options :: [OptDescr (Options -> Options)]
options = [ Option "v" ["verbose"]
(NoArg (\o -> o { verbose = True }))
"Verbose mode"
, Option "V" ["version"]
(NoArg (\o -> o { version = True }))
"Print version information"
, Option "h?" ["help"]
(NoArg (\o -> o { help = True }))
"Print this help"
, Option "d" ["dry-run"]
(NoArg (\o -> o { dryRun = True }))
"Print commands, don't actually run them"
, Option "j" ["jobs"]
(OptArg ((\f o -> o { jobs = read f :: Int }) . fromMaybe "jobs") "NUM")
"Allow N jobs at once"
, Option [] ["build-type"]
(OptArg ((\f o -> o { buildType = Just (read f) }) . fromMaybe "build-type") "type")
"Specify the build type (Release, Debug)"
, Option [] ["sandbox"]
(OptArg ((\f o -> o { sandbox = Just f }) . fromMaybe "sandbox") "DIR")
"Shared sandbox among Haskell tools/libs"
, Option [] ["cxx-comp"]
(OptArg ((\f o -> o { cxxComp = Just f }) . fromMaybe "cxx-comp") "COMP")
"Compiler to use for C++ programs"
, Option [] ["c-comp"]
(OptArg ((\f o -> o { ccComp = Just f }) . fromMaybe "c-comp") "COMP")
"Compiler to use for C programs"]
helpBanner :: String
helpBanner = "[ITEMS] = COMMAND [TARGETS]\n" <> "\n" <> "Commands:\n" <>
" configure Prepare to build PFQ framework.\n" <>
" build Build PFQ framework.\n" <>
" install Copy the files into the install location.\n" <>
" clean Clean up after a build.\n" <>
" distclean Clean up additional files/dirs.\n" <>
" show Show targets.\n" <> "\n" <> "Options:"
-- data types...
data Target = Configure { getTargetName :: String}
| Build { getTargetName :: String}
| Install { getTargetName :: String}
| Clean { getTargetName :: String}
| DistClean { getTargetName :: String}
instance Show Target where
show (Configure x) = "configure " ++ x
show (Build x) = "build " ++ x
show (Install x) = "install " ++ x
show (Clean x) = "clean " ++ x
show (DistClean x) = "distclean " ++ x
instance Eq Target where
(Configure a) == (Configure b) = a == b || a == "*" || b == "*"
(Build a) == (Build b) = a == b || a == "*" || b == "*"
(Install a) == (Install b) = a == b || a == "*" || b == "*"
(Clean a) == (Clean b) = a == b || a == "*" || b == "*"
(DistClean a) == (DistClean b) = a == b || a == "*" || b == "*"
_ == _ = False
data Command = StaticCmd String | DynamicCmd (Options -> String)
instance Show Command where
show (StaticCmd xs) = xs
show (DynamicCmd f) = f defaultOptions
evalCmd :: Options -> Command -> String
evalCmd _ (StaticCmd xs) = xs
evalCmd opt (DynamicCmd fun) = fun opt
execCmd :: Options -> Command -> IO ExitCode
execCmd opt cmd' = let raw = evalCmd opt cmd'
in system raw
data BuildType = Release | Debug
deriving (Data, Typeable, Show, Read, Eq)
type ActionLog = ([Command], [Target])
newtype Action a = Action { runAction :: Writer ActionLog a }
deriving(Functor, Applicative, Monad, MonadWriter ActionLog)
instance (Show a) => Show (Action a) where
show act = (\(cs, ts) -> show cs ++ ": " ++ show ts) $ (runWriter . runAction) act
data Component = Component { getTarget :: Target, getActionInfo :: ActionInfo }
data ActionInfo = ActionInfo { basedir :: FilePath, action :: Action () }
type BuilderScript = Writer Script ()
type Script = [Component]
type BuilderT = RWST Options () [Target]
infixr 0 *>>
(*>>) :: Target -> ActionInfo -> Writer [Component] ()
t *>> r = tell [Component t r]
into :: FilePath -> Action () -> ActionInfo
into = ActionInfo
requires :: Action () -> [Target] -> Action ()
ac `requires` xs = ac >> Action (tell ([],xs))
buildTargets :: [Target] -> Script -> FilePath -> Int -> BuilderT IO ()
buildTargets tgts script baseDir level = do
opt <- ask
let targets = map getTarget script
let script' = filter (\(Component tar' _) -> tar' `elem` tgts) script
when (length tgts > length script') $
liftIO $ error ("SimpleBuilder: " ++ unwords (map getTargetName $ filter (`notElem` targets) tgts) ++ ": target not found!")
forM_ (zip [1 ..] script') $
\(n,Component target (ActionInfo path action)) ->
do let (cmds',deps') = execWriter $ runAction action
done <- get
unless (target `elem` done) $
do put (target : done)
putStrLnVerbose Nothing $ replicate level '.' ++ "[" ++ show n ++ "/" ++ show (length script') ++ "] " ++ show target ++ ":"
-- satisfy dependencies
unless
(null deps') $
do putStrLnVerbose
(Just $ verbose opt) $ "# Satisfying dependencies for " ++ show target ++ ": " ++ show deps'
forM_ deps' $
\t -> when (t `notElem` done) $
buildTargets [t] script baseDir (level + 1)
putStrLnVerbose
(Just $ verbose opt) $ "# Building target " ++ show target ++ ": " ++ show (map (evalCmd opt) cmds')
liftIO $
do -- set working dir...
let workDir = dropTrailingPathSeparator $ baseDir </> path
cur <- getCurrentDirectory
when (cur /= workDir) $
do setCurrentDirectory workDir
when (dryRun opt || verbose opt) $
putStrLn $ "cd " ++ workDir
-- build target
if dryRun opt
then void $
mapM (putStrLn . evalCmd opt) cmds'
else void $
do ec <- mapM (execCmd opt) cmds'
unless (all (== ExitSuccess) ec) $
let show_cmd (c,e) = show c ++ " -> (" ++ show e ++ ")" in
error ("SimpleBuilder: " ++ show target ++ " aborted: " ++ intercalate ", " (zipWith (curry show_cmd) cmds' ec) ++ "!")
putStrLnVerbose :: Maybe Bool -> String -> BuilderT IO ()
putStrLnVerbose Nothing xs = liftIO $ putStrLn xs
putStrLnVerbose (Just v) xs = when v (liftIO $ putStrLn xs)
parseOpts :: [String] -> IO (Options, [String])
parseOpts argv =
case getOpt Permute options argv of
(o,n,[] ) -> return (foldl (flip id) defaultOptions o, n)
(_,_,errs) -> ioError (userError (concat errs ++ usageInfo "--help for additional information" options))
simpleBuilder :: BuilderScript -> [String] -> IO ()
simpleBuilder script' args = do
(opt,cmds) <- parseOpts args
baseDir <- getCurrentDirectory
when (help opt) $
putStrLn (usageInfo helpBanner options) >>
exitSuccess
when (version opt) $
putStrLn ("SimpleBuilder " ++ verString) >>
exitSuccess
sb <- let sb = sandbox opt
in if isJust sb
then liftM Just $
checkDir (fromJust sb) >>
canonicalizePath
(fromJust sb)
else return sb
let script = execWriter script'
E.catch (case cmds of
("configure":xs) -> evalRWST (buildTargets (map Configure (mkTargets xs)) script baseDir 0) opt { sandbox = sb } [] >> putStrLn "Done."
("build":xs) -> evalRWST (buildTargets (map Build (mkTargets xs)) script baseDir 0) opt { sandbox = sb } [] >> putStrLn "Done."
("install":xs) -> evalRWST (buildTargets (map Install (mkTargets xs)) script baseDir 0) opt { sandbox = sb } [] >> putStrLn "Done."
("clean":xs) -> evalRWST (buildTargets (map Clean (mkTargets xs)) script baseDir 0) opt { sandbox = sb } [] >> putStrLn "Done."
("distclean":xs) -> evalRWST (buildTargets (map DistClean (mkTargets xs)) script baseDir 0) opt { sandbox = sb } [] >> putStrLn "Done."
("show":_) -> showTargets script
_ -> putStr $ usageInfo helpBanner options)
(\e -> setCurrentDirectory baseDir >> print (e :: E.SomeException))
where mkTargets xs = if null xs
then ["*"]
else xs
checkDir :: FilePath -> IO ()
checkDir path = do
v <- doesDirectoryExist path
unless v $ error ("SimpleBuilder: " ++ path ++ " directory does not exist")
showTargets :: Script -> IO ()
showTargets script =
putStrLn "targets:" >> mapM_ putStrLn (nub (map (\(Component t _) -> " " ++ getTargetName t) script))
{-# NOINLINE numberOfPhyCores #-}
numberOfPhyCores :: Int
numberOfPhyCores = unsafePerformIO $
liftM (length . filter (isInfixOf "processor") . lines) $ readFile "/proc/cpuinfo"
| pandaychen/PFQ | Development/SimpleBuilder.hs | gpl-2.0 | 14,129 | 0 | 32 | 4,876 | 4,066 | 2,113 | 1,953 | 287 | 9 |
module IdempotenceTest where
import Data.List
import Lib
-- Use QuickCheck and the following helper functions to demonstrate
-- idempotence for the following:
twice f = f . f
fourTimes = twice . twice
-- 1.
f :: String -> Bool
f x =
(capitalizeWord x == twice capitalizeWord x)
&&
(capitalizeWord x == fourTimes capitalizeWord x)
f' :: [String] -> Bool
f' x =
(sort x == twice sort x)
&&
(sort x == fourTimes sort x)
| nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles | Testing/quickcheck-testing/test/IdempotenceTest.hs | gpl-3.0 | 448 | 0 | 8 | 108 | 141 | 74 | 67 | 15 | 1 |
module HSParedit.PareditSpec (main, spec) where
import Data.Tree
import Data.Tree.Pretty
import Data.Tree.Zipper
import HSParedit
import Prelude hiding (last)
import System.Console.Terminfo.PrettyPrint
import Test.Hspec (hspec, describe, it, Spec)
import Test.Hspec.Expectations.Pretty
import Text.PrettyPrint.Free
instance Show a => Pretty (Tree a) where
pretty = text . ("\n" ++) . drawVerticalTree . fmap show
prettyList = list . map pretty
instance Show a => PrettyTerm (Tree a)
main :: IO ()
main = hspec spec
basicTree' :: Tree Code
basicTree' = Node { rootLabel = TopLevel
, subForest = [ sc "foo"
, sc "bar"
, Node { rootLabel = RoundNode
, subForest = [ sc "qux"
, sc "quux"
]
}
]
}
tinyTree :: Tree Code
tinyTree = Node { rootLabel = TopLevel
, subForest = [sc "foo"]
}
zipTree' :: TreePos Full Code
zipTree' = fromTree basicTree
spec :: Spec
spec = do
let x `tShouldBe` y = toTree x `shouldBe` y
describe "when checking sanity" $ do
it "ensures fromTree . toTree identity" $ do
fromTree (toTree zipTree') == zipTree'
describe "paren insertion" $ do
it "inserts round parens at after code symbol if immediately after it" $ do
openRound tinyFocus `tShouldBe` editedTree RoundNode
it "inserts square parens at after code symbol if immediately after it" $ do
openSquare tinyFocus `tShouldBe` editedTree SquareNode
it "splits code symbol when inserting round parens" $ do
openRound codeFocus `tShouldBe` editedCodeTree RoundNode
it "splits code symbol when inserting square parens" $ do
openSquare codeFocus `tShouldBe` editedCodeTree SquareNode
-- it "inserts char at code symbol if immediately after it" $ do
-- toTree (insT (SymbolChar 'z') tinyFocus) `shouldBe` editedTree'
codeFocus = Right $ case firstChild (fromTree tinyTree') >>= lastChild of
Just x -> x
_ -> undefined
tinyTree' :: Tree Code
tinyTree' = Node { rootLabel = TopLevel
, subForest = [sc "foo"]
}
editedTree :: Code -> Tree Code
editedTree c = Node { rootLabel = TopLevel
, subForest = [ sc "foo"
, Node c []
]
}
editedCodeTree :: Code -> Tree Code
editedCodeTree c = Node { rootLabel = TopLevel
, subForest = [ sc "fo"
, Node c []
, sc "o"
]
}
tinyFocus' t =
case firstChild t of
Just x -> last $ children x
_ -> undefined
tinyFocus = Left $ tinyFocus' $ fromTree tinyTree'
| Fuuzetsu/hs-paredit | test/HSParedit/PareditSpec.hs | gpl-3.0 | 3,010 | 0 | 16 | 1,134 | 713 | 373 | 340 | 63 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Main
( main
) where
import Criterion.Main
import qualified Data.Text as T
import qualified Data.Text.IO as TO
import System.Posix.Directory
import System.Process
import System.Unix.Directory
main :: IO ()
main = withTemporaryDirectory "security-log-test" test
test :: FilePath -> IO ()
test _ =
let dir = "/users/peterhrvola/Desktop" in
do
_ <- writeFile (dir ++ "/config.yaml") (unlines [ "tag: Config"
, "input:"
, " tag: File"
, " contents: " ++ dir ++ "/stream"
, "output:"
, " tag: Std"
, "asDaemon: false"
, "serverType: Apache"
])
_ <- TO.writeFile (dir ++ "/stream") (T.replicate 100000 "10.5.252.1 - - [22/May/2017:16:07:09 +0200] \"GET /pulp/repos/Govcert/Govcert_Stable/Servery_Centos_7/custom/Epel/epel_7_x86_64/repodata/repomd.xml HTTP/1.1\" 200 2178 \"-\" \"urlgrabber/3.10 yum/3.4.3\"\n")
defaultMain [ bench "1" $ nfIO (rawSystem "stack" ["exec", "security-log", "--", "--configpath=" ++ dir ++ "/config.yaml"] ) ]
return ()
| retep007/security-log | test/performance/Stream.hs | gpl-3.0 | 1,389 | 0 | 17 | 536 | 245 | 134 | 111 | 26 | 1 |
{-- |
This module holds the configuration for the Mixture-of-Musings
website and feed, as used by Hakyll
-}
module Site.Configuration (config, feedConfig) where
import Hakyll
ignoreFile' :: String -> Bool
ignoreFile' ".htaccess" = False
ignoreFile' path = ignoreFile defaultConfiguration path
config :: Configuration
config = defaultConfiguration { ignoreFile = ignoreFile'
, previewHost = "0.0.0.0"
, deployCommand = "rsync -avz -e ssh _site bfeeney@amixtureofmusings.com:/var/www/html"
}
-- Details for the atom feed.
feedConfig :: FeedConfiguration
feedConfig = FeedConfiguration
{ feedTitle = "A Mixture of Musings"
, feedDescription = "Bryan Feeney’s blog on tech, programming and machine-learning"
, feedAuthorName = "Bryan Feeney"
, feedAuthorEmail = "bryan@amixtureofmusings.com"
, feedRoot = "http://amixtureofmusings.com"
}
| budgefeeney/amixtureofmusings | Site/Configuration.hs | gpl-3.0 | 967 | 0 | 6 | 239 | 121 | 74 | 47 | 16 | 1 |
-- Haskell Practical 4 Code - Semantics for N1
-- By James Cowgill
import Prac4.DomFunc
-- N1 Abstract Syntax Tree
data E = Plus E E
| Minus E E
| Times E E
| Number Int
| Variable String
data B = Not B
| And B B
| Or B B
| Equal E E
| Less E E
| Greater E E
| BTrue
| BFalse
data S = Skip
| Print E
| Seq S S
| Assign String E
| If B S S
| While B S
-- Evaluation
type Env = DomFunc String Int
type Output = [Int]
-- Evaluate numeric expression
evalExpr :: Env -> E -> Int
evalExpr env (Plus e1 e2) = (evalExpr env e1) + (evalExpr env e2)
evalExpr env (Minus e1 e2) = (evalExpr env e1) - (evalExpr env e2)
evalExpr env (Times e1 e2) = (evalExpr env e1) * (evalExpr env e2)
evalExpr _ (Number n) = n
evalExpr env (Variable v) = fetch v env
-- Evaluate boolean expression
evalBExpr :: Env -> B -> Bool
evalBExpr env (Not b) = not (evalBExpr env b)
evalBExpr env (And b1 b2) = (evalBExpr env b1) && (evalBExpr env b2)
evalBExpr env (Or b1 b2) = (evalBExpr env b1) || (evalBExpr env b2)
evalBExpr env (Equal e1 e2) = (evalExpr env e1) == (evalExpr env e2)
evalBExpr env (Less e1 e2) = (evalExpr env e1) < (evalExpr env e2)
evalBExpr env (Greater e1 e2) = (evalExpr env e1) > (evalExpr env e2)
evalBExpr _ BTrue = True
evalBExpr _ BFalse = False
-- Evaluate statement
evalStatement :: Env -> S -> (Env, Output)
evalStatement env Skip = (env, [])
evalStatement env (Print e) = (env, [evalExpr env e])
evalStatement env (Seq s1 s2) = (rEnv, lOut ++ rOut)
where
(lEnv, lOut) = evalStatement env s1
(rEnv, rOut) = evalStatement lEnv s2
evalStatement env (Assign v e) = (update v (evalExpr env e) env, [])
evalStatement env (If b s1 s2)
| evalBExpr env b = evalStatement env s1
| otherwise = evalStatement env s2
evalStatement env w@(While b s) = evalStatement env (If b (Seq s w) Skip)
-- Run program with blank initial environment
runProgram :: S -> Output
runProgram s = snd (evalStatement empty s)
-- Test program
-- Calculates smallest power of 2 greater than 10000
n1TestProgram :: S
n1TestProgram = (Seq (Seq
(Assign "x" (Number 1))
(While (Less (Variable "x") (Number 10000))
(Assign "x" (Times (Variable "x") (Number 2)))))
(Print (Variable "x")))
| jcowgill/cs-work | syac/compilers/Prac4/3N1Semantics.hs | gpl-3.0 | 2,518 | 2 | 16 | 788 | 976 | 510 | 466 | 56 | 1 |
{-# Language GeneralizedNewtypeDeriving,
DeriveDataTypeable,
OverloadedStrings,
DataKinds,
KindSignatures,
GADTs,
TypeFamilies,
ScopedTypeVariables,
RankNTypes,
TemplateHaskell,
EmptyCase
#-}
-- without -O0 GHC 7.6.3 loops while building, probably related to
-- https://git.haskell.org/ghc.git/commitdiff/c1edbdfd9148ad9f74bfe41e76c524f3e775aaaa
--
-- -fno-warn-unused-binds is used because the Singletons TH magic generates a
-- lot of unused binds and GHC has no way to disable warnings locally
{-# OPTIONS_GHC -O0 -fno-warn-unused-binds #-}
{-|
Module: MQTT.Types
Copyright: Lukas Braun 2014-2016
License: GPL-3
Maintainer: koomi+mqtt@hackerspace-bamberg.de
Types representing MQTT messages.
-}
module Network.MQTT.Types
( -- * Messages
Message(..)
, SomeMessage(..)
, MqttHeader(..)
, setDup
-- * Message body
, MessageBody(..)
-- * Miscellaneous
, Will(..)
, QoS(..)
, MsgID
, getMsgID
, Topic
, matches
, fromTopic
, toTopic
, getLevels
, fromLevels
, MqttText(..)
, ConnectError(..)
, toConnectError
-- * Message types
, MsgType(..)
, toMsgType
, toMsgType'
-- ** Singletons
-- | Singletons are used to build a bridge between the type and value level.
-- See the @singletons@ package for more information.
--
-- You do not have to use or understand these in order to use this
-- library, they are mostly used internally to get better guarantees
-- about the flow of 'Message's.
, toSMsgType
, SMsgType
, withSomeSingI
, Sing( SCONNECT
, SCONNACK
, SPUBLISH
, SPUBACK
, SPUBREC
, SPUBREL
, SPUBCOMP
, SSUBSCRIBE
, SSUBACK
, SUNSUBSCRIBE
, SUNSUBACK
, SPINGREQ
, SPINGRESP
, SDISCONNECT)
) where
import Control.Exception (Exception)
import Data.ByteString (ByteString)
import Data.Singletons
import Data.Singletons.TH
import Data.String (IsString(..))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Typeable (Typeable)
import Data.Word
-- | A MQTT message, indexed by the type of the message ('MsgType').
data Message (t :: MsgType)
= Message
{ header :: MqttHeader
, body :: MessageBody t
}
-- | Any message, hiding the index.
data SomeMessage where
SomeMessage :: SingI t => Message t -> SomeMessage
-- | Fixed header required in every message.
data MqttHeader
= Header
{ dup :: Bool -- ^ Has this message been sent before?
, qos :: QoS -- ^ Quality of Service-level
, retain :: Bool -- ^ Should the broker retain the message for
-- future subscribers?
}
deriving (Eq, Ord, Show)
-- | Set the 'dup' flag to 'True'.
setDup :: Message t -> Message t
setDup (Message h b) = Message h { dup = True } b
-- | The body of a MQTT message, indexed by the type of the message ('MsgType').
data MessageBody (t :: MsgType) where
Connect :: { cleanSession :: Bool
-- ^ Should the server forget subscriptions and other state on
-- disconnects?
, will :: Maybe Will
-- ^ Optional 'Will' message.
, clientID :: MqttText
-- ^ Client ID used by the server to identify clients.
, username :: Maybe MqttText
-- ^ Optional username used for authentication.
, password :: Maybe MqttText
-- ^ Optional password used for authentication.
, keepAlive :: Word16
-- ^ Time (in seconds) after which a 'PingReq' is sent to the broker if
-- no regular message was sent. 0 means no limit.
} -> MessageBody 'CONNECT
ConnAck :: { returnCode :: Word8 } -> MessageBody 'CONNACK
Publish :: { topic :: Topic
-- ^ The 'Topic' to which the message should be published.
, pubMsgID :: Maybe MsgID
-- ^ 'MsgID' of the message if 'QoS' > 'NoConfirm'.
, payload :: ByteString
-- ^ The content that will be published.
} -> MessageBody 'PUBLISH
PubAck :: { pubAckMsgID :: MsgID } -> MessageBody 'PUBACK
PubRec :: { pubRecMsgID :: MsgID } -> MessageBody 'PUBREC
PubRel :: { pubRelMsgID :: MsgID } -> MessageBody 'PUBREL
PubComp :: { pubCompMsgID :: MsgID } -> MessageBody 'PUBCOMP
Subscribe :: { subscribeMsgID :: MsgID
, subTopics :: [(Topic, QoS)]
-- ^ The 'Topic's and corresponding requested 'QoS'.
} -> MessageBody 'SUBSCRIBE
SubAck :: { subAckMsgID :: MsgID
, granted :: [QoS]
-- ^ The 'QoS' granted for each 'Topic' in the order they were sent
-- in the SUBSCRIBE.
} -> MessageBody 'SUBACK
Unsubscribe :: { unsubMsgID :: MsgID
, unsubTopics :: [Topic]
-- ^ The 'Topic's from which the client should be unsubscribed.
} -> MessageBody 'UNSUBSCRIBE
UnsubAck :: { unsubAckMsgID :: MsgID } -> MessageBody 'UNSUBACK
PingReq :: MessageBody 'PINGREQ
PingResp :: MessageBody 'PINGRESP
Disconnect :: MessageBody 'DISCONNECT
-- | The different levels of QoS
data QoS
= NoConfirm -- ^ Fire and forget, message will be published at most once.
| Confirm -- ^ Acknowledged delivery, message will be published at least once.
| Handshake -- ^ Assured delivery, message will be published exactly once.
deriving (Eq, Ord, Enum, Show)
-- | A Will message is published by the broker if a client disconnects
-- without sending a DISCONNECT.
data Will
= Will
{ wRetain :: Bool
, wQoS :: QoS
, wTopic :: Topic
, wMsg :: MqttText
}
deriving (Eq, Show)
-- | MQTT uses length-prefixed UTF-8 as text encoding.
newtype MqttText = MqttText { text :: Text }
deriving (Eq, Show, IsString)
type MsgID = Word16
-- | Get the message ID of any message, if it exists.
getMsgID :: MessageBody t -> Maybe MsgID
getMsgID (Connect{}) = Nothing
getMsgID (ConnAck{}) = Nothing
getMsgID (Publish _ mMsgid _) = mMsgid
getMsgID (PubAck msgid) = Just msgid
getMsgID (PubRec msgid) = Just msgid
getMsgID (PubRel msgid) = Just msgid
getMsgID (PubComp msgid) = Just msgid
getMsgID (Subscribe msgid _) = Just msgid
getMsgID (SubAck msgid _) = Just msgid
getMsgID (Unsubscribe msgid _) = Just msgid
getMsgID (UnsubAck msgid) = Just msgid
getMsgID PingReq = Nothing
getMsgID PingResp = Nothing
getMsgID Disconnect = Nothing
-- | A topic is a \"hierarchical name space that defines a taxonomy of
-- information sources for which subscribers can register an interest.\"
-- See the
-- <http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#appendix-a specification>
-- for more details.
--
-- A topic can be inspected by using the 'matches' function or after using
-- 'getLevels', e.g.:
--
-- > f1 topic
-- > | topic `matches` "mqtt/hs/example" = putStrLn "example"
-- > | topic `matches` "mqtt/hs/#" = putStrLn "wildcard"
-- >
-- > f2 topic = case getLevels topic of
-- > ["mqtt", "hs", "example"] -> putStrLn "example"
-- > "mqtt" : "hs" : _ -> putStrLn "wildcard"
data Topic = Topic { levels :: [Text], orig :: Text }
-- levels and orig should always refer to the same topic, so no text has to be
-- copied when converting from/to text
instance Show Topic where
show (Topic _ t) = show t
instance Eq Topic where
Topic _ t1 == Topic _ t2 = t1 == t2
-- | Check if one of the 'Topic's matches the other, taking
-- <http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#appendix-a wildcards>
-- into consideration.
matches :: Topic -> Topic -> Bool
matches (Topic t1 _) (Topic t2 _) = go t1 t2
where
go [] [] = True
go [] (l:_) = l == "#"
go (l:_) [] = l == "#"
go (l1:ls1) (l2:ls2) = l1 == "#" || l2 == "#"
|| ((l1 == "+" || l2 == "+" || l1 == l2)
&& go ls1 ls2)
toTopic :: MqttText -> Topic
toTopic (MqttText txt) = Topic (T.split (== '/') txt) txt
fromTopic :: Topic -> MqttText
fromTopic = MqttText . orig
-- | Split a topic into its individual levels.
getLevels :: Topic -> [Text]
getLevels = levels
-- | Create a 'Topic' from its individual levels.
fromLevels :: [Text] -> Topic
fromLevels ls = Topic ls (T.intercalate "/" ls)
instance IsString Topic where
fromString str = let txt = T.pack str in
Topic (T.split (== '/') txt) txt
-- | Reasons why connecting to a broker might fail.
data ConnectError
= WrongProtocolVersion
| IdentifierRejected
| ServerUnavailable
| BadLogin
| Unauthorized
| UnrecognizedReturnCode
| InvalidResponse
deriving (Show, Typeable)
instance Exception ConnectError where
-- | Convert a return code to a 'ConnectError'.
toConnectError :: Word8 -> ConnectError
toConnectError 1 = WrongProtocolVersion
toConnectError 2 = IdentifierRejected
toConnectError 3 = ServerUnavailable
toConnectError 4 = BadLogin
toConnectError 5 = Unauthorized
toConnectError _ = UnrecognizedReturnCode
-- | The various types of messages.
data MsgType
= CONNECT
| CONNACK
| PUBLISH
| PUBACK
| PUBREC
| PUBREL
| PUBCOMP
| SUBSCRIBE
| SUBACK
| UNSUBSCRIBE
| UNSUBACK
| PINGREQ
| PINGRESP
| DISCONNECT
deriving (Eq, Enum, Ord, Show)
genSingletons [''MsgType]
singDecideInstance ''MsgType
-- | Determine the 'MsgType' of a 'Message'.
toMsgType :: SingI t => Message t -> MsgType
toMsgType = fromSing . toSMsgType
-- | Determine the 'MsgType' of a 'SomeMessage'.
toMsgType' :: SomeMessage -> MsgType
toMsgType' (SomeMessage msg) = toMsgType msg
-- | Determine the singleton 'SMsgType' of a 'Message'.
toSMsgType :: SingI t => Message t -> SMsgType t
toSMsgType _ = sing
-- | Helper to generate both an implicit and explicit singleton.
withSomeSingI :: MsgType -> (forall t. SingI t => SMsgType t -> r) -> r
withSomeSingI t f = withSomeSing t $ \s -> withSingI s $ f s
| k00mi/mqtt-hs | Network/MQTT/Types.hs | gpl-3.0 | 10,817 | 0 | 15 | 3,359 | 1,889 | 1,093 | 796 | 205 | 4 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Storage.DefaultObjectAccessControls.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates a default object ACL entry on the specified bucket.
--
-- /See:/ <https://developers.google.com/storage/docs/json_api/ Cloud Storage JSON API Reference> for @storage.defaultObjectAccessControls.update@.
module Network.Google.Resource.Storage.DefaultObjectAccessControls.Update
(
-- * REST Resource
DefaultObjectAccessControlsUpdateResource
-- * Creating a Request
, defaultObjectAccessControlsUpdate
, DefaultObjectAccessControlsUpdate
-- * Request Lenses
, doacuBucket
, doacuPayload
, doacuEntity
) where
import Network.Google.Prelude
import Network.Google.Storage.Types
-- | A resource alias for @storage.defaultObjectAccessControls.update@ method which the
-- 'DefaultObjectAccessControlsUpdate' request conforms to.
type DefaultObjectAccessControlsUpdateResource =
"storage" :>
"v1" :>
"b" :>
Capture "bucket" Text :>
"defaultObjectAcl" :>
Capture "entity" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ObjectAccessControl :>
Put '[JSON] ObjectAccessControl
-- | Updates a default object ACL entry on the specified bucket.
--
-- /See:/ 'defaultObjectAccessControlsUpdate' smart constructor.
data DefaultObjectAccessControlsUpdate = DefaultObjectAccessControlsUpdate'
{ _doacuBucket :: !Text
, _doacuPayload :: !ObjectAccessControl
, _doacuEntity :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'DefaultObjectAccessControlsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'doacuBucket'
--
-- * 'doacuPayload'
--
-- * 'doacuEntity'
defaultObjectAccessControlsUpdate
:: Text -- ^ 'doacuBucket'
-> ObjectAccessControl -- ^ 'doacuPayload'
-> Text -- ^ 'doacuEntity'
-> DefaultObjectAccessControlsUpdate
defaultObjectAccessControlsUpdate pDoacuBucket_ pDoacuPayload_ pDoacuEntity_ =
DefaultObjectAccessControlsUpdate'
{ _doacuBucket = pDoacuBucket_
, _doacuPayload = pDoacuPayload_
, _doacuEntity = pDoacuEntity_
}
-- | Name of a bucket.
doacuBucket :: Lens' DefaultObjectAccessControlsUpdate Text
doacuBucket
= lens _doacuBucket (\ s a -> s{_doacuBucket = a})
-- | Multipart request metadata.
doacuPayload :: Lens' DefaultObjectAccessControlsUpdate ObjectAccessControl
doacuPayload
= lens _doacuPayload (\ s a -> s{_doacuPayload = a})
-- | The entity holding the permission. Can be user-userId,
-- user-emailAddress, group-groupId, group-emailAddress, allUsers, or
-- allAuthenticatedUsers.
doacuEntity :: Lens' DefaultObjectAccessControlsUpdate Text
doacuEntity
= lens _doacuEntity (\ s a -> s{_doacuEntity = a})
instance GoogleRequest
DefaultObjectAccessControlsUpdate where
type Rs DefaultObjectAccessControlsUpdate =
ObjectAccessControl
type Scopes DefaultObjectAccessControlsUpdate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/devstorage.full_control"]
requestClient DefaultObjectAccessControlsUpdate'{..}
= go _doacuBucket _doacuEntity (Just AltJSON)
_doacuPayload
storageService
where go
= buildClient
(Proxy ::
Proxy DefaultObjectAccessControlsUpdateResource)
mempty
| rueshyna/gogol | gogol-storage/gen/Network/Google/Resource/Storage/DefaultObjectAccessControls/Update.hs | mpl-2.0 | 4,304 | 0 | 15 | 930 | 466 | 279 | 187 | 78 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Tasks.TaskLists.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the authenticated user\'s specified task list. This method
-- supports patch semantics.
--
-- /See:/ <https://developers.google.com/tasks/ Tasks API Reference> for @tasks.tasklists.patch@.
module Network.Google.Resource.Tasks.TaskLists.Patch
(
-- * REST Resource
TaskListsPatchResource
-- * Creating a Request
, taskListsPatch
, TaskListsPatch
-- * Request Lenses
, tlpXgafv
, tlpUploadProtocol
, tlpAccessToken
, tlpUploadType
, tlpPayload
, tlpTaskList
, tlpCallback
) where
import Network.Google.AppsTasks.Types
import Network.Google.Prelude
-- | A resource alias for @tasks.tasklists.patch@ method which the
-- 'TaskListsPatch' request conforms to.
type TaskListsPatchResource =
"tasks" :>
"v1" :>
"users" :>
"@me" :>
"lists" :>
Capture "tasklist" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TaskList :> Patch '[JSON] TaskList
-- | Updates the authenticated user\'s specified task list. This method
-- supports patch semantics.
--
-- /See:/ 'taskListsPatch' smart constructor.
data TaskListsPatch =
TaskListsPatch'
{ _tlpXgafv :: !(Maybe Xgafv)
, _tlpUploadProtocol :: !(Maybe Text)
, _tlpAccessToken :: !(Maybe Text)
, _tlpUploadType :: !(Maybe Text)
, _tlpPayload :: !TaskList
, _tlpTaskList :: !Text
, _tlpCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TaskListsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tlpXgafv'
--
-- * 'tlpUploadProtocol'
--
-- * 'tlpAccessToken'
--
-- * 'tlpUploadType'
--
-- * 'tlpPayload'
--
-- * 'tlpTaskList'
--
-- * 'tlpCallback'
taskListsPatch
:: TaskList -- ^ 'tlpPayload'
-> Text -- ^ 'tlpTaskList'
-> TaskListsPatch
taskListsPatch pTlpPayload_ pTlpTaskList_ =
TaskListsPatch'
{ _tlpXgafv = Nothing
, _tlpUploadProtocol = Nothing
, _tlpAccessToken = Nothing
, _tlpUploadType = Nothing
, _tlpPayload = pTlpPayload_
, _tlpTaskList = pTlpTaskList_
, _tlpCallback = Nothing
}
-- | V1 error format.
tlpXgafv :: Lens' TaskListsPatch (Maybe Xgafv)
tlpXgafv = lens _tlpXgafv (\ s a -> s{_tlpXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
tlpUploadProtocol :: Lens' TaskListsPatch (Maybe Text)
tlpUploadProtocol
= lens _tlpUploadProtocol
(\ s a -> s{_tlpUploadProtocol = a})
-- | OAuth access token.
tlpAccessToken :: Lens' TaskListsPatch (Maybe Text)
tlpAccessToken
= lens _tlpAccessToken
(\ s a -> s{_tlpAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
tlpUploadType :: Lens' TaskListsPatch (Maybe Text)
tlpUploadType
= lens _tlpUploadType
(\ s a -> s{_tlpUploadType = a})
-- | Multipart request metadata.
tlpPayload :: Lens' TaskListsPatch TaskList
tlpPayload
= lens _tlpPayload (\ s a -> s{_tlpPayload = a})
-- | Task list identifier.
tlpTaskList :: Lens' TaskListsPatch Text
tlpTaskList
= lens _tlpTaskList (\ s a -> s{_tlpTaskList = a})
-- | JSONP
tlpCallback :: Lens' TaskListsPatch (Maybe Text)
tlpCallback
= lens _tlpCallback (\ s a -> s{_tlpCallback = a})
instance GoogleRequest TaskListsPatch where
type Rs TaskListsPatch = TaskList
type Scopes TaskListsPatch =
'["https://www.googleapis.com/auth/tasks"]
requestClient TaskListsPatch'{..}
= go _tlpTaskList _tlpXgafv _tlpUploadProtocol
_tlpAccessToken
_tlpUploadType
_tlpCallback
(Just AltJSON)
_tlpPayload
appsTasksService
where go
= buildClient (Proxy :: Proxy TaskListsPatchResource)
mempty
| brendanhay/gogol | gogol-apps-tasks/gen/Network/Google/Resource/Tasks/TaskLists/Patch.hs | mpl-2.0 | 4,940 | 0 | 20 | 1,226 | 792 | 461 | 331 | 115 | 1 |
module Main ( main ) where
import ADNS
import ADNS.Base
import Control.Concurrent.MVar
import System.Environment
main :: IO ()
main = initResolver [NoErrPrint, NoServerWarn] $ \resolver -> do
args <- getArgs
case args of
[name] -> traverseDNSSEC resolver name
[t,name] -> work resolver (read t) name
_ -> putStrLn "Usage: t [typeid] fqdn"
-- | Test function to see the raw results of a given query type
work :: Resolver -> RRType -> String -> IO ()
work resolver t n = do
putStrLn $ showString "Querying " . shows t $ showString " for " n
print =<< takeMVar =<< resolver n t [QuoteOk_Query]
-- | Example implementation to traverse a DNSSEC signed zone.
--
-- This implementation is clearly wrong, because any real zone traversal
-- is done using the NSEC records in the authority section of a NXDOMAIN
-- response.
--
-- Unfortunly the adns library does not provide access to other sections
-- than the answer section, so this walk is done by querying NSEC directly.
--
-- If there are signed subzones, the traversal switches to the subzone
-- and stops if this subzone is traversed. You may continue the traversal
-- by providing the next entry after the subzone.
--
-- You may try this mechanism on "dnssec.iks-jena.de"
traverseDNSSEC :: Resolver -> String -> IO ()
traverseDNSSEC resolver x = do
putStrLn x
answer <- takeMVar =<< resolver x NSEC [QuoteOk_Query]
case rrs answer of
[RRNSEC y] | not (x `endsWith` ('.':y)) -> traverseDNSSEC resolver y
_ -> return ()
endsWith :: String -> String -> Bool
endsWith x y = startsWith (reverse x) (reverse y)
startsWith :: String -> String -> Bool
startsWith (x:xs) (y:ys) = x == y && startsWith xs ys
startsWith _ ys = null ys
| peti/hsdns | example/adns-test-and-traverse.hs | lgpl-3.0 | 1,729 | 0 | 17 | 350 | 440 | 227 | 213 | 28 | 3 |
import Tree
import Data.Maybe (mapMaybe)
import Data.Set (difference, elems, fromList, Set)
solutions :: Set Int
solutions = fromList $ mapMaybe evalToInt $ trees $ replicate 4 Four
main :: IO ()
main = print $ elems $ difference (fromList [0..20]) solutions
| jmgimeno/haskell-playground | src/FourFours/missing.hs | unlicense | 261 | 0 | 9 | 43 | 105 | 56 | 49 | 7 | 1 |
-----------------------------------------------------------------------------
-- Copyright 2019, Ideas project team. This file is distributed under the
-- terms of the Apache License 2.0. For more information, see the files
-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution.
-----------------------------------------------------------------------------
-- |
-- Maintainer : bastiaan.heeren@ou.nl
-- Stability : provisional
-- Portability : portable (depends on ghc)
--
-----------------------------------------------------------------------------
module Ideas.Encoding.RulesInfo
( rulesInfoXML, rewriteRuleToFMP, collectExamples, ExampleMap
) where
import Data.Char
import Data.Monoid
import Ideas.Common.Library
import Ideas.Encoding.OpenMathSupport (toOMOBJ)
import Ideas.Text.OpenMath.FMP
import Ideas.Text.OpenMath.Object
import Ideas.Text.XML hiding (name)
import Ideas.Utils.Prelude (munless)
import qualified Data.Map as M
rulesInfoXML :: Exercise a -> (a -> XMLBuilder) -> XMLBuilder
rulesInfoXML ex enc = mconcat (map ruleInfoXML (ruleset ex))
where
exampleMap = collectExamples ex
ruleInfoXML r = element "rule"
[ "name" .=. showId r
, "buggy" .=. f (isBuggy r)
, "rewriterule" .=. f (isRewriteRule r)
-- More information
, let descr = description r
-- to do: rules should carry descriptions
txt = if null descr then showId r else descr
in munless (null txt) $
tag "description" $ string txt
, mconcat [ tag "argument" (text a) | Some a <- getRefs r ]
, mconcat [ tag "sibling" $ text s | s <- ruleSiblings r ]
-- FMPs and CMPs
, mconcat [ case showRewriteRule ok rr of
Nothing -> mempty
Just s -> tag "CMP" (string s)
<> tag "FMP" (builder (omobj2xml (toObject fmp)))
| Some rr <- getRewriteRules (transformation r)
, let ok = not $ isBuggy r
, let fmp = rewriteRuleToFMP ok rr
]
-- Examples
, mconcat [ element "example" [enc a, enc b]
| let pairs = M.findWithDefault [] (getId r) exampleMap
, (a, b) <- take 3 pairs
]
]
f = map toLower . show
rewriteRuleToFMP :: Bool -> RewriteRule a -> FMP
rewriteRuleToFMP sound r
| sound = eqFMP a b
| otherwise = buggyFMP a b
where
a :~> b = fmap toOMOBJ (ruleSpecTerm r)
type ExampleMap a = M.Map Id [(a, a)]
collectExamples :: Exercise a -> ExampleMap a
collectExamples ex = foldr add M.empty (examplesAsList ex)
where
add a m = let f = foldr g m . maybe [] triples
g (x, (r, _), y) =
case fromContextWith2 (,) x y of
Just p -> M.insertWith (++) (getId r) [p]
Nothing -> id
in f (defaultDerivation ex a) | ideas-edu/ideas | src/Ideas/Encoding/RulesInfo.hs | apache-2.0 | 3,014 | 0 | 18 | 918 | 810 | 420 | 390 | 49 | 3 |
{-# LANGUAGE RecordWildCards #-}
module PrivateCloud.Aws.S3
( downloadFile
, uploadFile
) where
import Aws.Core (defServiceConfig)
import Aws.S3 (getObject, multipartUploadSink, GetObjectResponse(..))
import Conduit
import Control.Monad (unless)
import Network.HTTP.Client (responseBody)
import PrivateCloud.Aws.Logging
import PrivateCloud.Aws.Monad
import PrivateCloud.Aws.Util
import PrivateCloud.Cloud.Exception
import PrivateCloud.Provider.Types
import Sodium.Hash
uploadFile :: FilePath -> AwsMonad (StorageId, Length, Hash)
uploadFile localPath = do
storageId <- StorageId <$> mkUUID
s3LogInfo $ "S3_UPLOAD_START #objid " ++ show storageId
-- S3 requires Content-Length header for uploads, and to provide
-- it for encrypted data it is necessary to encrypt and keep in memory
-- all the [multigigabyte] encrypted stream. Another option is to
-- calculate the size using knowledge of encryption mode, but this
-- looks like a hack.
-- Also (TODO) chunked uploads allow for restarts in case of network failures.
AwsContext{..} <- awsContext
(len, hash) <- liftIO $ runResourceT $ runConduit $
sourceFileBS localPath
.| getZipSink
( (,)
<$> ZipSink lengthCE
<*> ZipSink hashSink
<* ZipSink (uploadSink acConf acManager acBucket storageId)
)
s3LogInfo $ "S3_UPLOAD_END #objid " ++ show storageId
++ " #len " ++ show len ++ " #hash " ++ show hash
pure (storageId, len, hash)
where
uploadChunk = 100*1024*1024
uploadSink conf manager bucket (StorageId objectId) =
multipartUploadSink conf defServiceConfig manager bucket objectId uploadChunk
hashSink = do
ctx <- liftIO hashInit
mapM_C (liftIO . hashUpdate ctx)
encodeHash <$> liftIO (hashFinal ctx)
downloadFile :: StorageId -> Hash -> FilePath -> AwsMonad ()
downloadFile storageId expectedHash localPath = do
s3LogInfo $ "S3_DOWNLOAD_START #file " ++ show storageId
AwsContext{..} <- awsContext
GetObjectResponse{..} <- awsReq $ getObject acBucket (storageid2text storageId)
liftIO $ runResourceT $ runConduit $
responseBody gorResponse
.| getZipSink
( ZipSink hashCheckSink
*> ZipSink (sinkFileCautious localPath)
)
s3LogInfo $ "S3_DOWNLOAD_END #objid " ++ show storageId
where
hashCheckSink = do
ctx <- liftIO hashInit
mapM_C (liftIO . hashUpdate ctx)
realHash <- encodeHash <$> liftIO (hashFinal ctx)
unless (realHash == expectedHash) $
throwM $ ServiceInternalError "hmac mismatch in downloaded file"
| rblaze/private-cloud | src/PrivateCloud/Aws/S3.hs | apache-2.0 | 2,681 | 0 | 14 | 638 | 622 | 315 | 307 | 54 | 1 |
{-# LANGUAGE ImpredicativeTypes #-}
module Types.Agent.Intelligent.Affect.Fragments where
import Control.Lens
import Control.Monad.Supply
import Control.Monad.Writer
import qualified Data.Graph as G
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import Types.Agent.Intelligent
import Types.Agent.Intelligent.Filter
-- |Type of a PSBC-fragment.
data PSBCFragmentType = Weak | Strong
deriving (Show, Eq, Ord, Read, Enum, Bounded)
-- |Type of an SJS-fragment
data SJSFragmentType = Friendly | Hostile
deriving (Show, Eq, Ord, Read, Enum, Bounded)
-- |Settings for an anger template.
data AngerSettings = AngerSettings {
_angerSettingsWumpusDiedVal :: Rational,
_angerSettingsKilledWumpusVal :: Rational,
_angerSettingsKilledAgentVal :: Rational,
_angerSettingsHighTempVal :: Rational,
_angerSettingsGoodHealthVal :: Rational,
_angerSettingsHighHealthVal :: Rational,
_angerSettingsHighStaminaVal :: Rational,
_angerSettingsStench1Val :: Rational,
_angerSettingsStench2Val :: Rational,
_angerSettingsAttackedVal :: Rational,
_angerSettingsWumpusRadiusVal :: Rational,
_angerSettingsWumpusIntensityVal :: Rational,
_angerSettingsWumpusLimitVal :: Rational,
_angerSettingsAgentRadiusVal :: Rational,
_angerSettingsAgentIntensityVal :: Rational
}
-- |Settings for a fear template.
data FearSettings = FearSettings {
_fearSettingsQuarterHealthLossVal :: Rational,
_fearSettingsHalfHealthLossVal :: Rational,
_fearSettingsThreeQuarterHealthLossVal :: Rational,
_fearSettingsDiedVal :: Rational,
_fearSettingsHighTempVal :: Rational,
_fearSettingsLowTempVal :: Rational,
_fearSettingsLowHealthVal :: Rational,
_fearSettingsBadHealthVal :: Rational,
_fearSettingsVeryBadHealthVal :: Rational,
_fearSettingsCriticalHealthVal :: Rational,
_fearSettingsGoodHealthVal :: Rational,
_fearSettingsHealthGainVal :: Rational,
_fearSettingsLowStaminaVal :: Rational,
_fearSettingsWumpusRadiusVal :: Rational,
_fearSettingsWumpusIntensityVal :: Rational,
_fearSettingsWeakEnemyRadiusVal :: Rational,
_fearSettingsWeakEnemyIntensityVal :: Rational,
_fearSettingsNormalEnemyRadiusVal :: Rational,
_fearSettingsNormalEnemyIntensityVal :: Rational,
_fearSettingsStrongEnemyRadiusVal :: Rational,
_fearSettingsStrongEnemyIntensityVal :: Rational,
_fearSettingsVeryStrongEnemyRadiusVal :: Rational,
_fearSettingsVeryStrongEnemyIntensityVal :: Rational,
_fearSettingsFriendRadiusVal :: Rational,
_fearSettingsFriendIntensityVal :: Rational,
_fearSettingsPitRadiusVal :: Rational,
_fearSettingsPitIntensityVal :: Rational,
_fearSettingsStench1Val :: Rational,
_fearSettingsStench2Val :: Rational,
_fearSettingsBreeze1Val :: Rational,
_fearSettingsBreeze2Val :: Rational
}
-- |Settings for an enthusiasm template.
data EnthusiasmSettings = EnthusiasmSettings {
_enthusiasmSettingsQuarterHealthLossVal :: Rational,
_enthusiasmSettingsHalfHealthLossVal :: Rational,
_enthusiasmSettingsHighTempVal :: Rational,
_enthusiasmSettingsLowTempVal :: Rational,
_enthusiasmSettingsLowStaminaVal :: Rational,
_enthusiasmSettingsGaveGoldVal :: Rational,
_enthusiasmSettingsGaveMeatVal :: Rational,
_enthusiasmSettingsGaveFruitVal :: Rational,
_enthusiasmSettingsPlantHarvestedVal :: Rational,
_enthusiasmSettingsHealthIncreasedVal :: Rational,
_enthusiasmSettingsStaminaLostVal :: Rational,
_enthusiasmSettingsGainedGoldVal :: Rational,
_enthusiasmSettingsGainedFruitVal :: Rational,
_enthusiasmSettingsGainedMeatVal :: Rational,
_enthusiasmSettingsHunger1Val :: Rational,
_enthusiasmSettingsHunger2Val :: Rational,
_enthusiasmSettingsHunger3Val :: Rational,
_enthusiasmSettingsHunger4Val :: Rational,
_enthusiasmSettingsHunger5Val :: Rational,
_enthusiasmSettingsStrongFriendRadiusVal :: Rational,
_enthusiasmSettingsStrongFriendIntensityVal :: Rational,
_enthusiasmSettingsNormalFriendRadiusVal :: Rational,
_enthusiasmSettingsNormalFriendIntensityVal :: Rational,
_enthusiasmSettingsWeakFriendRadiusVal :: Rational,
_enthusiasmSettingsWeakFriendIntensityVal :: Rational,
_enthusiasmSettingsPlant1RadiusVal :: Rational,
_enthusiasmSettingsPlant1IntensityVal :: Rational,
_enthusiasmSettingsPlant2RadiusVal :: Rational,
_enthusiasmSettingsPlant2IntensityVal :: Rational,
_enthusiasmSettingsPlant3RadiusVal :: Rational,
_enthusiasmSettingsPlant3IntensityVal :: Rational,
_enthusiasmSettingsPlant4RadiusVal :: Rational,
_enthusiasmSettingsPlant4IntensityVal :: Rational,
_enthusiasmSettingsPlant5RadiusVal :: Rational,
_enthusiasmSettingsPlant5IntensityVal :: Rational,
_enthusiasmSettingsGoldRadiusVal :: Rational,
_enthusiasmSettingsGoldIntensityVal :: Rational,
_enthusiasmSettingsMeatRadiusVal :: Rational,
_enthusiasmSettingsMeatIntensityVal :: Rational,
_enthusiasmSettingsFruitRadiusVal :: Rational,
_enthusiasmSettingsFruitIntensityVal :: Rational
}
-- |Settings for a contentment template.
data ContentmentSettings = ContentmentSettings {
_contentmentSettingsQuarterHealthLossVal :: Rational,
_contentmentSettingsHalfHealthLossVal :: Rational,
_contentmentSettingsBadHealthVal :: Rational,
_contentmentSettingsVeryBadHealthVal :: Rational,
_contentmentSettingsCriticalHealthVal :: Rational,
_contentmentSettingsStaminaLossVal :: Rational,
_contentmentSettingsHighHealthVal :: Rational,
_contentmentSettingsVeryHighHealthVal :: Rational,
_contentmentSettingsExcellentHealthVal :: Rational,
_contentmentSettingsHaveGoldVal :: Rational,
_contentmentSettingsHaveFruitVal :: Rational,
_contentmentSettingsHaveMuchFruitVal :: Rational,
_contentmentSettingsHaveMeatVal :: Rational,
_contentmentSettingsHaveMuchMeatVal :: Rational,
_contentmentSettingsLowTempVal :: Rational,
_contentmentSettingsGainedGoldVal :: Rational,
_contentmentSettingsGainedFruitVal :: Rational,
_contentmentSettingsGainedMeatVal :: Rational,
_contentmentSettingsPlantRadiusVal :: Rational,
_contentmentSettingsPlantIntensityVal :: Rational,
_contentmentSettingsEmptyRadiusVal :: Rational,
_contentmentSettingsEmptyIntensityVal :: Rational
}
-- |Settings for a sympathy template.
data SocialSettings = SocialSettings {
_socialSettingsAttackedVal :: Rational,
_socialSettingsHostileGestureVal :: Rational,
_socialSettingsReceivedGoldVal :: Rational,
_socialSettingsReceivedMeatVal :: Rational,
_socialSettingsReceivedFruitVal :: Rational,
_socialSettingsFriendlyGestureVal :: Rational,
_socialSettingsGrudgeMinVal :: Rational,
_socialSettingsGrudgeMaxVal :: Rational,
_socialSettingsGrudgeImproveVal :: Rational
}
type FilterNodeInd = [(AgentMessageName, Maybe RelInd, G.Vertex)]
type FilterM a = WriterT FilterNodeInd (Supply SInt) a
-- |A function that takes a list of coordinate-significance pairs and
-- a starting vertex and returns a forest of filters, with
-- a list of output nodes.
type AreaFilter = [(Rational, RelInd)]
-> FilterM (HM.HashMap G.Vertex (FilterNode AgentMessage),
HS.HashSet G.Vertex)
-- |A check that an 'AreaFilter' can perform on a cell.
type AreaFilterCheck = (NodeName, Traversal' AgentMessage RelInd, AgentMessageName, Maybe (NodeCondition AgentMessage))
| jtapolczai/wumpus | Types/Agent/Intelligent/Affect/Fragments.hs | apache-2.0 | 7,386 | 0 | 10 | 999 | 1,028 | 665 | 363 | 143 | 0 |
module Converter.Data where
import ClassyPrelude
import qualified Data.Bimap as BM
import qualified Data.Map as M
import Converter.Types
wNames :: BM.Bimap WeightUnit Text
wNames = BM.fromList
[(MilliGram, "mg"),
(Gram, "g"),
(KiloGram, "kg"),
(MetricTon, "t"),
(Ounce, "oz"),
(Pound, "lbs"),
(Stone, "st")]
vNames :: BM.Bimap VolumeUnit Text
vNames = BM.fromList
[(MilliLiter, "ml"),
(CentiLiter, "cl"),
(DeciLiter, "dl"),
(Liter, "l"),
(HectoLiter, "hl"),
(FluidOunce, "floz"),
(Cup, "cup"),
(Pint, "pt"),
(Quart, "qt"),
(Gallon, "g")]
lNames :: BM.Bimap LengthUnit Text
lNames = BM.fromList
[(MilliMeter, "mm"),
(CentiMeter, "cm"),
(Meter, "m"),
(KiloMeter, "km"),
(Inch, "in"),
(Foot, "ft"),
(Yard, "yd"),
(Mile, "mi")]
aNames :: BM.Bimap AreaUnit Text
aNames = BM.fromList
[(SquareMilliMeter, "mm2"),
(SquareCentiMeter, "cm2"),
(SquareMeter, "m2"),
(SquareKiloMeter, "km2"),
(Hectare, "ha"),
(Acre, "ac"),
(SquareInch, "in2"),
(SquareFoot, "ft2"),
(SquareYard, "yd2")]
wScales ::M.Map WeightUnit Double
wScales = M.fromList
[(MilliGram, 0.001),
(Gram, 1),
(DekaGram, 10),
(KiloGram, 1000),
(MetricTon, 1000000),
(Ounce, 28.3495),
(Pound, 453.592),
(Stone, 6350.29)]
vScales :: M.Map VolumeUnit Double
vScales = M.fromList
[(MilliLiter, 0.001),
(CentiLiter, 0.01),
(DeciLiter, 0.1),
(Liter, 1),
(HectoLiter, 100),
(FluidOunce, 0.0295735),
(Cup, 0.284131),
(Pint, 0.473176),
(Quart, 0.946353),
(Gallon, 3.78541)]
lScales :: M.Map LengthUnit Double
lScales = M.fromList
[(MilliMeter, 0.001),
(CentiMeter, 0.01),
(Meter, 1),
(KiloMeter, 1000),
(Inch, 0.0254),
(Foot, 0.3048),
(Yard, 0.9144),
(Mile, 1609.34)]
aScales :: M.Map AreaUnit Double
aScales = M.fromList
[(SquareMilliMeter, 0.000001),
(SquareCentiMeter, 0.0001),
(SquareMeter, 1),
(SquareKiloMeter, 1000000),
(Hectare, 10000),
(Acre, 4046.86),
(SquareInch, 0.00064516),
(SquareFoot, 0.092903),
(SquareYard, 0.836127)]
| jtapolczai/Scratchpad | src/Converter/Data.hs | apache-2.0 | 2,158 | 0 | 7 | 498 | 827 | 523 | 304 | 90 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE TemplateHaskell #-}
module Topical.VSpace.Types
( VSpaceModel
, vsmTokenMap
, vsmIndexMap
, newVSpaceModel
, VSpace(VS)
, vsVector
) where
import Control.Lens
import Data.Data
import Data.Foldable ()
import qualified Data.HashMap.Strict as M
import GHC.Generics
data VSpaceModel s t
= VSM
{ _vsmTokenMap :: M.HashMap t Int
, _vsmIndexMap :: M.HashMap Int t
} deriving (Show, Eq, Data, Typeable, Generic)
$(makeLenses ''VSpaceModel)
instance Foldable (VSpaceModel s) where
foldr f s = foldr f s . M.keys . _vsmTokenMap
newVSpaceModel :: VSpaceModel s t
newVSpaceModel = VSM M.empty M.empty
data VSpace s v t
= VS { _vsVector :: v t }
deriving (Show, Eq, Data, Typeable, Generic, Functor, Traversable, Foldable)
$(makeLenses ''VSpace)
| erochest/topical | src/Topical/VSpace/Types.hs | apache-2.0 | 1,004 | 0 | 10 | 252 | 271 | 152 | 119 | 34 | 1 |
{-# LANGUAGE RankNTypes #-}
module Lycopene.Process.Internal
( Process'
, module Lycopene.Process.Internal.Core
) where
import Lycopene.Process.Internal.Core
-- | Simplified Process type with Domain monad
type Process' a = Process a IO ()
| utky/lycopene | backup/Process/Internal.hs | apache-2.0 | 263 | 0 | 6 | 55 | 45 | 30 | 15 | 6 | 0 |
main = do
l <- getLine
let i = unwords $ filter (\x -> length(x) >= 3 && length(x) <= 6) $ map (filter (\x-> x /= ',' && x /= '.') ) $ words l
putStrLn i
| a143753/AOJ | 0084.hs | apache-2.0 | 177 | 0 | 20 | 61 | 107 | 52 | 55 | 4 | 1 |
import Control.Concurrent
import Control.Monad
import qualified Control.Concurrent.BoundedChan as BC
import System.Process
import Lux.Core
import Lux.Inputs.Nagios
main = do
putStrLn "Starting Lux"
putStrLn "Loading config"
-- TODO load config
channel <- BC.newBoundedChan channelSize
putStrLn "Starting input threads"
-- TODO Map below over LuxConfig commands
_ <- mapM (commandThread channel) dummyCommands
putStrLn "Starting output thread"
_ <- forkIO $ forever $ do
event <- BC.readChan channel
print event
putStrLn "Running"
forever $ threadDelay 1000 -- FIXME Block forever hack
runCheck :: Command -> IO Response
runCheck (NagiosPlugin fp) =
do
(code, stdout, _) <- readProcessWithExitCode fp [] ""
return $ parseNagiosOutput code stdout
commandThread :: BC.BoundedChan Response -> Command -> IO ThreadId
commandThread channel command =
do
putStrLn $ "Starting input thread for TODO" -- TODO Show
forkIO $ forever $
do
threadDelay $ 10 * 1000 * 1000
result <- runCheck command
BC.writeChan channel result
--type LuxConfig = [Command] -- FIXME
data Command = NagiosPlugin FilePath
-- | InternalCommand (IO Response)
dummyCommands :: [Command]
dummyCommands = [NagiosPlugin "/usr/bin/uptime"]
channelSize :: Int
channelSize = 10
| doismellburning/lux | src/Lux/Main.hs | apache-2.0 | 1,313 | 6 | 13 | 252 | 341 | 167 | 174 | 37 | 1 |
{-# LANGUAGE PackageImports #-}
import "yesod-cwl" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, settingsPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
main :: IO ()
main = do
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings defaultSettings
{ settingsPort = port
} app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "dist/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
| qzchenwl/myweb | devel.hs | bsd-2-clause | 703 | 0 | 10 | 123 | 186 | 101 | 85 | 23 | 2 |
module Hassium.Main where
import Control.Monad(liftM, when)
import Data.Maybe(isJust, fromJust)
import System.Environment(getArgs)
import System.Exit(exitWith, ExitCode(ExitFailure))
import System.IO(readFile)
import Hassium.Args(parseOpt, Flag(..))
_main :: IO ()
_main = do
parsedArgs <- liftM parseOpt getArgs
(flags, filePath) <- case parsedArgs of
Right (flags, filePath) -> do
when (Verbose `elem` flags) $
putStrLn $ "options: " ++ (show flags) ++ "\n"
when (not $ isJust filePath) $ do
putStrLn "no file path specification"
exitWith $ ExitFailure 1
return (flags, fromJust filePath)
Left e -> do
putStrLn $ show e
exitWith $ ExitFailure 1
fileContext <- readFile filePath
-- compile flags fileContext
return ()
-- compile :: String -> [Flags] -> IO ()
-- compile fullName flags =
-- (filePath, moduleName, extension) =
-- (takeDirectory filePath, takeBaseName filePath, takeExtension filePath)
| tonosaman/haskell-code-snippets | src/Hassium/Main.hs | bsd-2-clause | 987 | 0 | 19 | 209 | 285 | 149 | 136 | 23 | 2 |
{-# LANGUAGE TemplateHaskell, CPP #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
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 HOLDER 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 Test.Ganeti.Utils (testUtils) where
import Test.QuickCheck hiding (Result)
import Test.HUnit
import Data.Char (isSpace)
import qualified Data.Either as Either
import Data.List
import System.Time
import qualified Text.JSON as J
#ifndef NO_REGEX_PCRE
import Text.Regex.PCRE
#endif
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Ganeti.BasicTypes
import qualified Ganeti.Constants as C
import qualified Ganeti.JSON as JSON
import Ganeti.Utils
-- | Helper to generate a small string that doesn't contain commas.
genNonCommaString :: Gen String
genNonCommaString = do
size <- choose (0, 20) -- arbitrary max size
vectorOf size (arbitrary `suchThat` (/=) ',')
-- | If the list is not just an empty element, and if the elements do
-- not contain commas, then join+split should be idempotent.
prop_commaJoinSplit :: Property
prop_commaJoinSplit =
forAll (choose (0, 20)) $ \llen ->
forAll (vectorOf llen genNonCommaString `suchThat` (/=) [""]) $ \lst ->
sepSplit ',' (commaJoin lst) ==? lst
-- | Split and join should always be idempotent.
prop_commaSplitJoin :: String -> Property
prop_commaSplitJoin s =
commaJoin (sepSplit ',' s) ==? s
-- | fromObjWithDefault, we test using the Maybe monad and an integer
-- value.
prop_fromObjWithDefault :: Integer -> String -> Bool
prop_fromObjWithDefault def_value random_key =
-- a missing key will be returned with the default
JSON.fromObjWithDefault [] random_key def_value == Just def_value &&
-- a found key will be returned as is, not with default
JSON.fromObjWithDefault [(random_key, J.showJSON def_value)]
random_key (def_value+1) == Just def_value
-- | Test that functional if' behaves like the syntactic sugar if.
prop_if'if :: Bool -> Int -> Int -> Gen Prop
prop_if'if cnd a b =
if' cnd a b ==? if cnd then a else b
-- | Test basic select functionality
prop_select :: Int -- ^ Default result
-> [Int] -- ^ List of False values
-> [Int] -- ^ List of True values
-> Gen Prop -- ^ Test result
prop_select def lst1 lst2 =
select def (flist ++ tlist) ==? expectedresult
where expectedresult = defaultHead def lst2
flist = zip (repeat False) lst1
tlist = zip (repeat True) lst2
{-# ANN prop_select_undefd "HLint: ignore Use alternative" #-}
-- | Test basic select functionality with undefined default
prop_select_undefd :: [Int] -- ^ List of False values
-> NonEmptyList Int -- ^ List of True values
-> Gen Prop -- ^ Test result
prop_select_undefd lst1 (NonEmpty lst2) =
-- head is fine as NonEmpty "guarantees" a non-empty list, but not
-- via types
select undefined (flist ++ tlist) ==? head lst2
where flist = zip (repeat False) lst1
tlist = zip (repeat True) lst2
{-# ANN prop_select_undefv "HLint: ignore Use alternative" #-}
-- | Test basic select functionality with undefined list values
prop_select_undefv :: [Int] -- ^ List of False values
-> NonEmptyList Int -- ^ List of True values
-> Gen Prop -- ^ Test result
prop_select_undefv lst1 (NonEmpty lst2) =
-- head is fine as NonEmpty "guarantees" a non-empty list, but not
-- via types
select undefined cndlist ==? head lst2
where flist = zip (repeat False) lst1
tlist = zip (repeat True) lst2
cndlist = flist ++ tlist ++ [undefined]
prop_parseUnit :: NonNegative Int -> Property
prop_parseUnit (NonNegative n) =
conjoin
[ parseUnit (show n) ==? (Ok n::Result Int)
, parseUnit (show n ++ "m") ==? (Ok n::Result Int)
, parseUnit (show n ++ "M") ==? (Ok (truncate n_mb)::Result Int)
, parseUnit (show n ++ "g") ==? (Ok (n*1024)::Result Int)
, parseUnit (show n ++ "G") ==? (Ok (truncate n_gb)::Result Int)
, parseUnit (show n ++ "t") ==? (Ok (n*1048576)::Result Int)
, parseUnit (show n ++ "T") ==? (Ok (truncate n_tb)::Result Int)
, printTestCase "Internal error/overflow?"
(n_mb >=0 && n_gb >= 0 && n_tb >= 0)
, property (isBad (parseUnit (show n ++ "x")::Result Int))
]
where n_mb = (fromIntegral n::Rational) * 1000 * 1000 / 1024 / 1024
n_gb = n_mb * 1000
n_tb = n_gb * 1000
{-# ANN case_niceSort_static "HLint: ignore Use camelCase" #-}
case_niceSort_static :: Assertion
case_niceSort_static = do
assertEqual "empty list" [] $ niceSort []
assertEqual "punctuation" [",", "."] $ niceSort [",", "."]
assertEqual "decimal numbers" ["0.1", "0.2"] $ niceSort ["0.1", "0.2"]
assertEqual "various numbers" ["0,099", "0.1", "0.2", "0;099"] $
niceSort ["0;099", "0,099", "0.1", "0.2"]
assertEqual "simple concat" ["0000", "a0", "a1", "a2", "a20", "a99",
"b00", "b10", "b70"] $
niceSort ["a0", "a1", "a99", "a20", "a2", "b10", "b70", "b00", "0000"]
assertEqual "ranges" ["A", "Z", "a0-0", "a0-4", "a1-0", "a9-1", "a09-2",
"a20-3", "a99-3", "a99-10", "b"] $
niceSort ["a0-0", "a1-0", "a99-10", "a20-3", "a0-4", "a99-3", "a09-2",
"Z", "a9-1", "A", "b"]
assertEqual "large"
["3jTwJPtrXOY22bwL2YoW", "Eegah9ei", "KOt7vn1dWXi",
"KVQqLPDjcPjf8T3oyzjcOsfkb", "WvNJd91OoXvLzdEiEXa6",
"Z8Ljf1Pf5eBfNg171wJR", "a07h8feON165N67PIE", "bH4Q7aCu3PUPjK3JtH",
"cPRi0lM7HLnSuWA2G9", "guKJkXnkULealVC8CyF1xefym",
"pqF8dkU5B1cMnyZuREaSOADYx", "uHXAyYYftCSG1o7qcCqe",
"xij88brTulHYAv8IEOyU", "xpIUJeVT1Rp"] $
niceSort ["Eegah9ei", "xij88brTulHYAv8IEOyU", "3jTwJPtrXOY22bwL2YoW",
"Z8Ljf1Pf5eBfNg171wJR", "WvNJd91OoXvLzdEiEXa6",
"uHXAyYYftCSG1o7qcCqe", "xpIUJeVT1Rp", "KOt7vn1dWXi",
"a07h8feON165N67PIE", "bH4Q7aCu3PUPjK3JtH",
"cPRi0lM7HLnSuWA2G9", "KVQqLPDjcPjf8T3oyzjcOsfkb",
"guKJkXnkULealVC8CyF1xefym", "pqF8dkU5B1cMnyZuREaSOADYx"]
-- | Tests single-string behaviour of 'niceSort'.
prop_niceSort_single :: Property
prop_niceSort_single =
forAll genName $ \name ->
conjoin
[ printTestCase "single string" $ [name] ==? niceSort [name]
, printTestCase "single plus empty" $ ["", name] ==? niceSort [name, ""]
]
-- | Tests some generic 'niceSort' properties. Note that the last test
-- must add a non-digit prefix; a digit one might change ordering.
prop_niceSort_generic :: Property
prop_niceSort_generic =
forAll (resize 20 arbitrary) $ \names ->
let n_sorted = niceSort names in
conjoin [ printTestCase "length" $ length names ==? length n_sorted
, printTestCase "same strings" $ sort names ==? sort n_sorted
, printTestCase "idempotence" $ n_sorted ==? niceSort n_sorted
, printTestCase "static prefix" $ n_sorted ==?
map tail (niceSort $ map (" "++) names)
]
-- | Tests that niceSorting numbers is identical to actual sorting
-- them (in numeric form).
prop_niceSort_numbers :: Property
prop_niceSort_numbers =
forAll (listOf (arbitrary::Gen (NonNegative Int))) $ \numbers ->
map show (sort numbers) ==? niceSort (map show numbers)
-- | Tests that 'niceSort' and 'niceSortKey' are equivalent.
prop_niceSortKey_equiv :: Property
prop_niceSortKey_equiv =
forAll (resize 20 arbitrary) $ \names ->
forAll (vectorOf (length names) (arbitrary::Gen Int)) $ \numbers ->
let n_sorted = niceSort names in
conjoin
[ printTestCase "key id" $ n_sorted ==? niceSortKey id names
, printTestCase "key rev" $ niceSort (map reverse names) ==?
map reverse (niceSortKey reverse names)
, printTestCase "key snd" $ n_sorted ==? map snd (niceSortKey snd $
zip numbers names)
]
-- | Tests 'rStripSpace'.
prop_rStripSpace :: NonEmptyList Char -> Property
prop_rStripSpace (NonEmpty str) =
forAll (resize 50 $ listOf1 (arbitrary `suchThat` isSpace)) $ \whitespace ->
conjoin [ printTestCase "arb. string last char is not space" $
case rStripSpace str of
[] -> True
xs -> not . isSpace $ last xs
, printTestCase "whitespace suffix is stripped" $
rStripSpace str ==? rStripSpace (str ++ whitespace)
, printTestCase "whitespace reduced to null" $
rStripSpace whitespace ==? ""
, printTestCase "idempotent on empty strings" $
rStripSpace "" ==? ""
]
#ifndef NO_REGEX_PCRE
{-# ANN case_new_uuid "HLint: ignore Use camelCase" #-}
-- | Tests that the newUUID function produces valid UUIDs.
case_new_uuid :: Assertion
case_new_uuid = do
uuid <- newUUID
assertBool "newUUID" $ uuid =~ C.uuidRegex
#endif
prop_clockTimeToString :: Integer -> Integer -> Property
prop_clockTimeToString ts pico =
clockTimeToString (TOD ts pico) ==? show ts
-- | Test normal operation for 'chompPrefix'.
--
-- Any random prefix of a string must be stripped correctly, including the empty
-- prefix, and the whole string.
prop_chompPrefix_normal :: String -> Property
prop_chompPrefix_normal str =
forAll (choose (0, length str)) $ \size ->
chompPrefix (take size str) str ==? (Just $ drop size str)
-- | Test that 'chompPrefix' correctly allows the last char (the separator) to
-- be absent if the string terminates there.
prop_chompPrefix_last :: Property
prop_chompPrefix_last =
forAll (choose (1, 20)) $ \len ->
forAll (vectorOf len arbitrary) $ \pfx ->
chompPrefix pfx pfx ==? Just "" .&&.
chompPrefix pfx (init pfx) ==? Just ""
-- | Test that chompPrefix on the empty string always returns Nothing for
-- prefixes of length 2 or more.
prop_chompPrefix_empty_string :: Property
prop_chompPrefix_empty_string =
forAll (choose (2, 20)) $ \len ->
forAll (vectorOf len arbitrary) $ \pfx ->
chompPrefix pfx "" ==? Nothing
-- | Test 'chompPrefix' returns Nothing when the prefix doesn't match.
prop_chompPrefix_nothing :: Property
prop_chompPrefix_nothing =
forAll (choose (1, 20)) $ \len ->
forAll (vectorOf len arbitrary) $ \pfx ->
forAll (arbitrary `suchThat`
(\s -> not (pfx `isPrefixOf` s) && s /= init pfx)) $ \str ->
chompPrefix pfx str ==? Nothing
-- | Tests 'trim'.
prop_trim :: NonEmptyList Char -> Property
prop_trim (NonEmpty str) =
forAll (listOf1 $ elements " \t\n\r\f") $ \whitespace ->
forAll (choose (0, length whitespace)) $ \n ->
let (preWS, postWS) = splitAt n whitespace in
conjoin [ printTestCase "arb. string first and last char are not space" $
case trim str of
[] -> True
xs -> (not . isSpace . head) xs && (not . isSpace . last) xs
, printTestCase "whitespace is striped" $
trim str ==? trim (preWS ++ str ++ postWS)
, printTestCase "whitespace reduced to null" $
trim whitespace ==? ""
, printTestCase "idempotent on empty strings" $
trim "" ==? ""
]
-- | Tests 'splitEithers' and 'recombineEithers'.
prop_splitRecombineEithers :: [Either Int Int] -> Property
prop_splitRecombineEithers es =
conjoin
[ printTestCase "only lefts are mapped correctly" $
splitEithers (map Left lefts) ==? (reverse lefts, emptylist, falses)
, printTestCase "only rights are mapped correctly" $
splitEithers (map Right rights) ==? (emptylist, reverse rights, trues)
, printTestCase "recombination is no-op" $
recombineEithers splitleft splitright trail ==? Ok es
, printTestCase "fail on too long lefts" $
isBad (recombineEithers (0:splitleft) splitright trail)
, printTestCase "fail on too long rights" $
isBad (recombineEithers splitleft (0:splitright) trail)
, printTestCase "fail on too long trail" $
isBad (recombineEithers splitleft splitright (True:trail))
]
where (lefts, rights) = Either.partitionEithers es
falses = map (const False) lefts
trues = map (const True) rights
(splitleft, splitright, trail) = splitEithers es
emptylist = []::[Int]
-- | Test the update function for standard deviations against the naive
-- implementation.
prop_stddev_update :: Property
prop_stddev_update =
forAll (choose (0, 6) >>= flip vectorOf (choose (0, 1))) $ \xs ->
forAll (choose (0, 1)) $ \a ->
forAll (choose (0, 1)) $ \b ->
forAll (choose (1, 6) >>= flip vectorOf (choose (0, 1))) $ \ys ->
let original = xs ++ [a] ++ ys
modified = xs ++ [b] ++ ys
with_update = getStatisticValue
$ updateStatistics (getStdDevStatistics original) (a,b)
direct = stdDev modified
in printTestCase ("Value computed by update " ++ show with_update
++ " differs too much from correct value " ++ show direct)
(abs (with_update - direct) < 1e-12)
-- | Test list for the Utils module.
testSuite "Utils"
[ 'prop_commaJoinSplit
, 'prop_commaSplitJoin
, 'prop_fromObjWithDefault
, 'prop_if'if
, 'prop_select
, 'prop_select_undefd
, 'prop_select_undefv
, 'prop_parseUnit
, 'case_niceSort_static
, 'prop_niceSort_single
, 'prop_niceSort_generic
, 'prop_niceSort_numbers
, 'prop_niceSortKey_equiv
, 'prop_rStripSpace
, 'prop_trim
#ifndef NO_REGEX_PCRE
, 'case_new_uuid
#endif
, 'prop_clockTimeToString
, 'prop_chompPrefix_normal
, 'prop_chompPrefix_last
, 'prop_chompPrefix_empty_string
, 'prop_chompPrefix_nothing
, 'prop_splitRecombineEithers
, 'prop_stddev_update
]
| apyrgio/snf-ganeti | test/hs/Test/Ganeti/Utils.hs | bsd-2-clause | 15,006 | 0 | 21 | 3,471 | 3,453 | 1,849 | 1,604 | 253 | 2 |
{-# OPTIONS -cpp #-}
-----------------------------------------------------------------------------
-- | Separate module for HTTP actions, using a proxy server if one exists
-----------------------------------------------------------------------------
module Distribution.Client.HttpUtils (
downloadURI,
getHTTP,
cabalBrowse,
proxy,
isOldHackageURI
) where
import Network.HTTP
( Request (..), Response (..), RequestMethod (..)
, Header(..), HeaderName(..) )
import Network.URI
( URI (..), URIAuth (..), parseAbsoluteURI )
import Network.Stream
( Result, ConnError(..) )
import Network.Browser
( Proxy (..), Authority (..), BrowserAction, browse
, setOutHandler, setErrHandler, setProxy, setAuthorityGen, request)
import Control.Monad
( mplus, join, liftM, liftM2 )
import qualified Data.ByteString.Lazy.Char8 as ByteString
import Data.ByteString.Lazy (ByteString)
#ifdef WIN32
import System.Win32.Types
( DWORD, HKEY )
import System.Win32.Registry
( hKEY_CURRENT_USER, regOpenKey, regCloseKey
, regQueryValue, regQueryValueEx )
import Control.Exception
( bracket )
import Distribution.Compat.Exception
( handleIO )
import Foreign
( toBool, Storable(peek, sizeOf), castPtr, alloca )
#endif
import System.Environment (getEnvironment)
import qualified Paths_faction (version)
import Distribution.Verbosity (Verbosity)
import Distribution.Simple.Utils
( die, info, warn, debug
, copyFileVerbose, writeFileAtomic )
import Distribution.Text
( display )
import qualified System.FilePath.Posix as FilePath.Posix
( splitDirectories )
-- FIXME: all this proxy stuff is far too complicated, especially parsing
-- the proxy strings. Network.Browser should have a way to pick up the
-- proxy settings hiding all this system-dependent stuff below.
-- try to read the system proxy settings on windows or unix
proxyString, envProxyString, registryProxyString :: IO (Maybe String)
#ifdef WIN32
-- read proxy settings from the windows registry
registryProxyString = handleIO (\_ -> return Nothing) $
bracket (regOpenKey hive path) regCloseKey $ \hkey -> do
enable <- fmap toBool $ regQueryValueDWORD hkey "ProxyEnable"
if enable
then fmap Just $ regQueryValue hkey (Just "ProxyServer")
else return Nothing
where
-- some sources say proxy settings should be at
-- HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows
-- \CurrentVersion\Internet Settings\ProxyServer
-- but if the user sets them with IE connection panel they seem to
-- end up in the following place:
hive = hKEY_CURRENT_USER
path = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
regQueryValueDWORD :: HKEY -> String -> IO DWORD
regQueryValueDWORD hkey name = alloca $ \ptr -> do
regQueryValueEx hkey name (castPtr ptr) (sizeOf (undefined :: DWORD))
peek ptr
#else
registryProxyString = return Nothing
#endif
-- read proxy settings by looking for an env var
envProxyString = do
env <- getEnvironment
return (lookup "http_proxy" env `mplus` lookup "HTTP_PROXY" env)
proxyString = liftM2 mplus envProxyString registryProxyString
-- |Get the local proxy settings
proxy :: Verbosity -> IO Proxy
proxy verbosity = do
mstr <- proxyString
case mstr of
Nothing -> return NoProxy
Just str -> case parseHttpProxy str of
Nothing -> do
warn verbosity $ "invalid http proxy uri: " ++ show str
warn verbosity $ "proxy uri must be http with a hostname"
warn verbosity $ "ignoring http proxy, trying a direct connection"
return NoProxy
Just p -> return p
--TODO: print info message when we're using a proxy
-- | We need to be able to parse non-URIs like @\"wwwcache.example.com:80\"@
-- which lack the @\"http://\"@ URI scheme. The problem is that
-- @\"wwwcache.example.com:80\"@ is in fact a valid URI but with scheme
-- @\"wwwcache.example.com:\"@, no authority part and a path of @\"80\"@.
--
-- So our strategy is to try parsing as normal uri first and if it lacks the
-- 'uriAuthority' then we try parsing again with a @\"http://\"@ prefix.
--
parseHttpProxy :: String -> Maybe Proxy
parseHttpProxy str = join
. fmap uri2proxy
$ parseHttpURI str
`mplus` parseHttpURI ("http://" ++ str)
where
parseHttpURI str' = case parseAbsoluteURI str' of
Just uri@URI { uriAuthority = Just _ }
-> Just (fixUserInfo uri)
_ -> Nothing
fixUserInfo :: URI -> URI
fixUserInfo uri = uri{ uriAuthority = f `fmap` uriAuthority uri }
where
f a@URIAuth{ uriUserInfo = s } =
a{ uriUserInfo = case reverse s of
'@':s' -> reverse s'
_ -> s
}
uri2proxy :: URI -> Maybe Proxy
uri2proxy uri@URI{ uriScheme = "http:"
, uriAuthority = Just (URIAuth auth' host port)
} = Just (Proxy (host ++ port) auth)
where auth = if null auth'
then Nothing
else Just (AuthBasic "" usr pwd uri)
(usr,pwd') = break (==':') auth'
pwd = case pwd' of
':':cs -> cs
_ -> pwd'
uri2proxy _ = Nothing
mkRequest :: URI -> Request ByteString
mkRequest uri = Request{ rqURI = uri
, rqMethod = GET
, rqHeaders = [Header HdrUserAgent userAgent]
, rqBody = ByteString.empty }
where userAgent = "faction/" ++ display Paths_faction.version
-- |Carry out a GET request, using the local proxy settings
getHTTP :: Verbosity -> URI -> IO (Result (Response ByteString))
getHTTP verbosity uri = liftM (\(_, resp) -> Right resp) $
cabalBrowse verbosity (return ()) (request (mkRequest uri))
cabalBrowse :: Verbosity
-> BrowserAction s ()
-> BrowserAction s a
-> IO a
cabalBrowse verbosity auth act = do
p <- proxy verbosity
browse $ do
setProxy p
setErrHandler (warn verbosity . ("http error: "++))
setOutHandler (debug verbosity)
auth
setAuthorityGen (\_ _ -> return Nothing)
act
downloadURI :: Verbosity
-> URI -- ^ What to download
-> FilePath -- ^ Where to put it
-> IO ()
downloadURI verbosity uri path | uriScheme uri == "file:" =
copyFileVerbose verbosity (uriPath uri) path
downloadURI verbosity uri path = do
result <- getHTTP verbosity uri
let result' = case result of
Left err -> Left err
Right rsp -> case rspCode rsp of
(2,0,0) -> Right (rspBody rsp)
(a,b,c) -> Left err
where
err = ErrorMisc $ "Unsucessful HTTP code: "
++ concatMap show [a,b,c]
case result' of
Left err -> die $ "Failed to download " ++ show uri ++ " : " ++ show err
Right body -> do
info verbosity ("Downloaded to " ++ path)
writeFileAtomic path (ByteString.unpack body)
--FIXME: check the content-length header matches the body length.
--TODO: stream the download into the file rather than buffering the whole
-- thing in memory.
-- remember the ETag so we can not re-download if nothing changed.
-- Utility function for legacy support.
isOldHackageURI :: URI -> Bool
isOldHackageURI uri
= case uriAuthority uri of
Just (URIAuth {uriRegName = "hackage.haskell.org"}) ->
FilePath.Posix.splitDirectories (uriPath uri) == ["/","packages","archive"]
_ -> False
| IreneKnapp/Faction | faction/Distribution/Client/HttpUtils.hs | bsd-3-clause | 7,732 | 0 | 20 | 2,090 | 1,742 | 939 | 803 | 124 | 4 |
-----------------------------------------------------------------------------
-- |
-- Module : Language.Haskell.Exts.Desugaring
-- Copyright : (c) Shayan Najd
-- License : BSD-style (see the file LICENSE.txt)
--
-- Maintainer : Shayan Najd, shayan@chalmers.se
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -Wall -fno-warn-orphans #-}
module Language.Haskell.Exts.Desugar.Generic
(module Language.Haskell.Exts.Unique
,module Language.Haskell.Exts.Desugar.Basic
,module Language.Haskell.Exts.Desugar.Generic.Type
,module Language.Haskell.Exts.Desugar.Generic.Pattern
,module Language.Haskell.Exts.Desugar.Generic.Case
,module Language.Haskell.Exts.Desugar.Conversion
,module Language.Haskell.Exts.Desugar.Generic.Expression
,module Language.Haskell.Exts.Desugar.Generic.Others
,module Language.Haskell.Exts.Desugar.Generic.Declaration
,module Language.Haskell.Exts.SimpleGenerics
) where
import Language.Haskell.Exts.Unique
import Language.Haskell.Exts.Desugar.Generic.Others
import Language.Haskell.Exts.Desugar.Basic
import Language.Haskell.Exts.Desugar.Generic.Type
import Language.Haskell.Exts.Desugar.Generic.Case
import Language.Haskell.Exts.Desugar.Generic.Expression
import Language.Haskell.Exts.Desugar.Generic.Pattern
import Language.Haskell.Exts.Desugar.Generic.Declaration
import Language.Haskell.Exts.Desugar.Conversion
import Language.Haskell.Exts.SimpleGenerics | shayan-najd/Haskell-Desugar-Generic | Language/Haskell/Exts/Desugar/Generic.hs | bsd-3-clause | 1,576 | 0 | 5 | 185 | 200 | 157 | 43 | 22 | 0 |
module Main where
import ARM.Processor.Base
import ARM.Assembler.Types
import ARM.Assembler.Smart
import ARM.Assembler.Pretty
main :: IO ()
main = undefined
| tranma/arm-edsl | Main.hs | bsd-3-clause | 159 | 0 | 6 | 20 | 43 | 27 | 16 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Network.Socks5
import Network.Socket hiding (recv, sClose)
import Network.Socket.ByteString
import Network.BSD
import Network
import Data.ByteString.Char8 ()
import qualified Data.ByteString.Char8 as BC
import System.IO (hClose, hFlush)
import System.Environment (getArgs)
main = do
args <- getArgs
let serverName = "localhost"
let serverPort = 1080
let destinationName = case args of
[] -> "www.google.com"
(x:_) -> x
-- socks server is expected to be running on localhost port 1080
he <- getHostByName serverName
let socksServerAddr = SockAddrInet serverPort (head $ hostAddresses he)
example1 socksServerAddr destinationName
example2 socksServerAddr destinationName
example3 serverName serverPort destinationName 80
where
-- connect to @destName on port 80 through the socks server
-- www.google.com get resolve on the client here and then the sockaddr is
-- passed to socksConnectAddr
example1 socksServerAddr destName = do
socket <- socket AF_INET Stream defaultProtocol
socksConnectWithSocket socket (defaultSocksConfFromSockAddr socksServerAddr)
(SocksAddress (SocksAddrDomainName $ BC.pack destName) 80)
sendAll socket "GET / HTTP/1.0\r\n\r\n"
recv socket 4096 >>= putStrLn . show
sClose socket
-- connect to @destName on port 80 through the socks server
-- the server is doing the resolution itself
example2 socksServerAddr destName = do
socket <- socket AF_INET Stream defaultProtocol
socksConnectName socket socksServerAddr destName 80
sendAll socket "GET / HTTP/1.0\r\n\r\n"
recv socket 4096 >>= putStrLn . show
sClose socket
example3 sname sport dname dport = do
handle <- socksConnectTo sname (PortNumber sport) dname (PortNumber dport)
BC.hPut handle "GET / HTTP/1.0\r\n\r\n"
hFlush handle
BC.hGet handle 1024 >>= putStrLn . show
hClose handle
| erikd/hs-socks | Example.hs | bsd-3-clause | 2,153 | 0 | 15 | 591 | 448 | 217 | 231 | 41 | 2 |
-- | This is the module which binds it all together
--
{-# LANGUAGE GeneralizedNewtypeDeriving, OverloadedStrings #-}
module Hakyll.Core.Run
( run
) where
import Control.Applicative (Applicative, (<$>))
import Control.Monad (filterM, forM_)
import Control.Monad.Error (ErrorT, runErrorT, throwError)
import Control.Monad.Reader (ReaderT, runReaderT, ask)
import Control.Monad.State.Strict (StateT, runStateT, get, put)
import Control.Monad.Trans (liftIO)
import Data.Map (Map)
import Data.Monoid (mempty, mappend)
import Prelude hiding (reverse)
import System.FilePath ((</>))
import qualified Data.Map as M
import qualified Data.Set as S
import Hakyll.Core.Compiler
import Hakyll.Core.Compiler.Internal
import Hakyll.Core.Configuration
import Hakyll.Core.DependencyAnalyzer
import Hakyll.Core.DirectedGraph
import Hakyll.Core.Identifier
import Hakyll.Core.Logger
import Hakyll.Core.Resource
import Hakyll.Core.Resource.Provider
import Hakyll.Core.Resource.Provider.File
import Hakyll.Core.Routes
import Hakyll.Core.Rules.Internal
import Hakyll.Core.Store
import Hakyll.Core.Util.File
import Hakyll.Core.Writable
-- | Run all rules needed, return the rule set used
--
run :: HakyllConfiguration -> RulesM a -> IO RuleSet
run configuration rules = do
logger <- makeLogger putStrLn
section logger "Initialising"
store <- timed logger "Creating store" $
makeStore (inMemoryCache configuration) $ storeDirectory configuration
provider <- timed logger "Creating provider" $
fileResourceProvider configuration
-- Fetch the old graph from the store. If we don't find it, we consider this
-- to be the first run
graph <- storeGet store "Hakyll.Core.Run.run" "dependencies"
let (firstRun, oldGraph) = case graph of Found g -> (False, g)
_ -> (True, mempty)
let ruleSet = runRules rules provider
compilers = rulesCompilers ruleSet
-- Extract the reader/state
reader = unRuntime $ addNewCompilers compilers
stateT = runReaderT reader $ RuntimeEnvironment
{ hakyllLogger = logger
, hakyllConfiguration = configuration
, hakyllRoutes = rulesRoutes ruleSet
, hakyllResourceProvider = provider
, hakyllStore = store
, hakyllFirstRun = firstRun
}
-- Run the program and fetch the resulting state
result <- runErrorT $ runStateT stateT $ RuntimeState
{ hakyllAnalyzer = makeDependencyAnalyzer mempty (const False) oldGraph
, hakyllCompilers = M.empty
}
case result of
Left e ->
thrown logger e
Right ((), state') ->
-- We want to save the final dependency graph for the next run
storeSet store "Hakyll.Core.Run.run" "dependencies" $
analyzerGraph $ hakyllAnalyzer state'
-- Flush and return
flushLogger logger
return ruleSet
data RuntimeEnvironment = RuntimeEnvironment
{ hakyllLogger :: Logger
, hakyllConfiguration :: HakyllConfiguration
, hakyllRoutes :: Routes
, hakyllResourceProvider :: ResourceProvider
, hakyllStore :: Store
, hakyllFirstRun :: Bool
}
data RuntimeState = RuntimeState
{ hakyllAnalyzer :: DependencyAnalyzer (Identifier ())
, hakyllCompilers :: Map (Identifier ()) (Compiler () CompileRule)
}
newtype Runtime a = Runtime
{ unRuntime :: ReaderT RuntimeEnvironment
(StateT RuntimeState (ErrorT String IO)) a
} deriving (Functor, Applicative, Monad)
-- | Add a number of compilers and continue using these compilers
--
addNewCompilers :: [(Identifier (), Compiler () CompileRule)]
-- ^ Compilers to add
-> Runtime ()
addNewCompilers newCompilers = Runtime $ do
-- Get some information
logger <- hakyllLogger <$> ask
section logger "Adding new compilers"
provider <- hakyllResourceProvider <$> ask
store <- hakyllStore <$> ask
firstRun <- hakyllFirstRun <$> ask
-- Old state information
oldCompilers <- hakyllCompilers <$> get
oldAnalyzer <- hakyllAnalyzer <$> get
let -- All known compilers
universe = M.keys oldCompilers ++ map fst newCompilers
-- Create a new partial dependency graph
dependencies = flip map newCompilers $ \(id', compiler) ->
let deps = runCompilerDependencies compiler id' universe
in (id', deps)
-- Create the dependency graph
newGraph = fromList dependencies
-- Check which items have been modified
modified <- fmap S.fromList $ flip filterM (map fst newCompilers) $
liftIO . resourceModified provider store . fromIdentifier
let checkModified = if firstRun then const True else (`S.member` modified)
-- Create a new analyzer and append it to the currect one
let newAnalyzer = makeDependencyAnalyzer newGraph checkModified $
analyzerPreviousGraph oldAnalyzer
analyzer = mappend oldAnalyzer newAnalyzer
-- Update the state
put $ RuntimeState
{ hakyllAnalyzer = analyzer
, hakyllCompilers = M.union oldCompilers (M.fromList newCompilers)
}
-- Continue
unRuntime stepAnalyzer
stepAnalyzer :: Runtime ()
stepAnalyzer = Runtime $ do
-- Step the analyzer
state <- get
let (signal, analyzer') = step $ hakyllAnalyzer state
put $ state { hakyllAnalyzer = analyzer' }
case signal of Done -> return ()
Cycle c -> unRuntime $ dumpCycle c
Build id' -> unRuntime $ build id'
-- | Dump cyclic error and quit
--
dumpCycle :: [Identifier ()] -> Runtime ()
dumpCycle cycle' = Runtime $ do
logger <- hakyllLogger <$> ask
section logger "Dependency cycle detected! Conflict:"
forM_ (zip cycle' $ drop 1 cycle') $ \(x, y) ->
report logger $ show x ++ " -> " ++ show y
build :: Identifier () -> Runtime ()
build id' = Runtime $ do
logger <- hakyllLogger <$> ask
routes <- hakyllRoutes <$> ask
provider <- hakyllResourceProvider <$> ask
store <- hakyllStore <$> ask
compilers <- hakyllCompilers <$> get
section logger $ "Compiling " ++ show id'
-- Fetch the right compiler from the map
let compiler = compilers M.! id'
-- Check if the resource was modified
isModified <- liftIO $ resourceModified provider store $ fromIdentifier id'
-- Run the compiler
result <- timed logger "Total compile time" $ liftIO $
runCompiler compiler id' provider (M.keys compilers) routes
store isModified logger
case result of
-- Compile rule for one item, easy stuff
Right (CompileRule compiled) -> do
case runRoutes routes id' of
Nothing -> return ()
Just url -> timed logger ("Routing to " ++ url) $ do
destination <-
destinationDirectory . hakyllConfiguration <$> ask
let path = destination </> url
liftIO $ makeDirectories path
liftIO $ write path compiled
-- Continue for the remaining compilers
unRuntime stepAnalyzer
-- Metacompiler, slightly more complicated
Right (MetaCompileRule newCompilers) ->
-- Actually I was just kidding, it's not hard at all
unRuntime $ addNewCompilers newCompilers
-- Some error happened, rethrow in Runtime monad
Left err -> throwError err
| sol/hakyll | src/Hakyll/Core/Run.hs | bsd-3-clause | 7,684 | 0 | 22 | 2,143 | 1,727 | 903 | 824 | 143 | 4 |
{-# LANGUAGE TypeFamilies, UndecidableInstances #-}
module PrioritySync.Internal.Receipt
(Receipt(..))
where
import PrioritySync.Internal.UserData
import PrioritySync.Internal.RoomGroup
import PrioritySync.Internal.ClaimContext
import Control.Concurrent.STM
-- | Get a notification when a claim is approved or scheduled.
data Receipt c = Receipt {
receipt_base_context :: c,
receipt_entering_callback, receipt_exiting_callback :: ClaimHandle c -> STM () }
type instance UserData (Receipt c) = UserData c
instance (RoomGroup c) => RoomGroup (Receipt c) where
roomsOf r = roomsOf $ receipt_base_context r
instance (ClaimContext c) => ClaimContext (Receipt c) where
type ClaimHandle (Receipt c) = ClaimHandle c
approveClaimsEntering r cs =
do result <- approveClaimsEntering (receipt_base_context r) cs
receipt_entering_callback r $ result
return result
approveClaimsExiting r cs =
do result <- approveClaimsExiting (receipt_base_context r) cs
receipt_exiting_callback r $ result
return result
waitingAction r = waitingAction $ receipt_base_context r
| clanehin/priority-sync | PrioritySync/Internal/Receipt.hs | bsd-3-clause | 1,151 | 0 | 11 | 229 | 279 | 145 | 134 | 24 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Monad.Except (MonadError(..), runExceptT, withExceptT)
import Control.Monad.IO.Class (liftIO)
import Data.Monoid ((<>))
import qualified Data.Text as TS
import Data.Yaml (ParseException)
import Options.Applicative
import System.Exit (exitWith, ExitCode(..))
import Config
import LuminescentDreams.AuthDB
data Options = Options { configPath :: FilePath
, cmdOptions :: CommandOptions
}
deriving (Show)
data CommandOptions = AddUser { uname :: String
, pword :: String
, admin :: Bool
}
| DeleteUser { uname :: String }
| ListUsers
-- | GrantAdmin { uname :: String }
-- | RevokeAdmin { uname :: String }
deriving (Show)
data AppException = ConfigException ParseException
| AuthDBExc AuthException
deriving (Show)
main :: IO ()
main = do
res <- runExceptT $ do
cliOpts@Options{..} <- liftIO $ execParser opts
liftIO $ print cliOpts
config@Config{..} <- withExceptT ConfigException (loadConfig configPath)
liftIO $ print config
authdb <- connectAuthDB authDBPath >>= either (throwError . AuthDBExc) return
case cmdOptions of
AddUser{..} -> withExceptT AuthDBExc $ runAuthDBE authdb $
setPassword (Username $ TS.pack uname) (Password $ TS.pack pword)
DeleteUser{..} -> undefined
ListUsers -> withExceptT AuthDBExc (runAuthDBE authdb listUsers >>= liftIO . print)
-- GrantAdmin{..} -> undefined
-- RevokeAdmin{..} -> undefined
case res of
Left err -> print err >> exitWith (ExitFailure 1)
Right _ -> return ()
where
opts = info (helper <*> cliOptions) fullDesc
cliOptions :: Parser Options
cliOptions =
Options <$> strOption (long "config" <> value "config.yml")
<*> subparser (
command "add" (info addOptions (progDesc "add a user"))
<> command "delete" (info deleteOptions (progDesc "delete a user"))
<> command "list" (info listOptions (progDesc "list users")))
-- <> command "grant-admin" (info grantAdminOptions (progDesc "set the admin flag on a user"))
-- <> command "revoke-admin" (info revokeAdminOptions (progDesc "revoke the admin flag on a user")))
addOptions :: Parser CommandOptions
addOptions = AddUser <$> argument str (metavar "username")
<*> argument str (metavar "password")
<*> switch (long "admin" <> help "set the admin flag on the user")
deleteOptions :: Parser CommandOptions
deleteOptions = DeleteUser <$> argument str (metavar "username")
listOptions :: Parser CommandOptions
listOptions = pure ListUsers
-- grantAdminOptions :: Parser CommandOptions
-- grantAdminOptions = GrantAdmin <$> argument str (metavar "username")
--
-- revokeAdminOptions :: Parser CommandOptions
-- revokeAdminOptions = RevokeAdmin <$> argument str (metavar "username")
| savannidgerinel/mead | scripts/user-manager.hs | bsd-3-clause | 3,317 | 0 | 19 | 1,046 | 709 | 374 | 335 | 55 | 4 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.VertexWeighting
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/EXT/vertex_weighting.txt EXT_vertex_weighting> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.VertexWeighting (
-- * Enums
gl_CURRENT_VERTEX_WEIGHT_EXT,
gl_MODELVIEW0_EXT,
gl_MODELVIEW0_MATRIX_EXT,
gl_MODELVIEW0_STACK_DEPTH_EXT,
gl_MODELVIEW1_EXT,
gl_MODELVIEW1_MATRIX_EXT,
gl_MODELVIEW1_STACK_DEPTH_EXT,
gl_VERTEX_WEIGHTING_EXT,
gl_VERTEX_WEIGHT_ARRAY_EXT,
gl_VERTEX_WEIGHT_ARRAY_POINTER_EXT,
gl_VERTEX_WEIGHT_ARRAY_SIZE_EXT,
gl_VERTEX_WEIGHT_ARRAY_STRIDE_EXT,
gl_VERTEX_WEIGHT_ARRAY_TYPE_EXT,
-- * Functions
glVertexWeightPointerEXT,
glVertexWeightfEXT,
glVertexWeightfvEXT
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/EXT/VertexWeighting.hs | bsd-3-clause | 1,172 | 0 | 4 | 130 | 91 | 68 | 23 | 19 | 0 |
module RandomUniform
(
uniform,
rejectUniform,
fastRejectUniform,
recycleUniform,
biasedBit,
uniformViaReal,
randomDecision,
efficientDecision,
vnUnbias,
module Uniform,
module RandomValue
)where
import Bit(bitsToInt, maxInBits)
import Uniform
import RandomValue
import Control.Monad(liftM)
import Data.Ratio
-- Implement some of the algorithms from Uniform using the new type
uniform :: (Integral i) => i -> RValue Bool (UnifNat i)
uniform = recycleUniform
--simple rejection sampling
rejectUniform max =
untilSuccess . fmap (maybeUnifNat max . bitsToInt) . pP $ maxInBits max
--fail fast rejection sampling
fastRejectUniform max =
fmap (UnifNat max . bitsToInt) . untilSuccess . attempt $ maxInBits max
where b <:> bs = liftM (liftM (b :)) bs
attempt [] = Done $ Just []
attempt (m:ms) = NotDone $ \b ->
case (m, b) of
(True, True ) -> b <:> attempt ms {- append and continue -}
(True, False) -> liftM Just $ pP ms {- append, no further checks -}
(False, True ) -> Done Nothing {- discard and restart -}
(False, False) -> b <:> attempt ms {- append and continue -}
--recycle rejected portion of interval
recycleUniform max = rU max mempty
where rU max u =
if maxValue u < max
then NotDone $ \b -> rU max (addBit u b)
else case decision max u of
(False, u') -> Done u'
(True, u') -> rU max u'
-- False with probability num/den
biasedBit _ 0 = Done True
biasedBit den num = NotDone $ \b ->
let num' = 2 * num
in if num' >= den
then if b
then biasedBit den (num' - den)
else Done b
else if b
then Done b
else biasedBit den num'
-- denom >= max
-- try \in [0, denom)
-- consider try as [try * max, (try + 1) * max) \subset [0, denom * max)
-- find q such that q * denom <= try * max < (q + 1) * denom
-- q * denom + r = try * max
-- check for containment in [q * denom, (q + 1) * denom):
-- need (try + 1) max < (q + 1) * denom
-- q * denom + r + max < q * denom + denom
-- r + max < denom
uniformViaReal max =
uVR max denom =<< pP mib
where mib = maxInBits max
denom = 2 ^ length mib
uVR max denom x =
let try = bitsToInt x
(q, r) = quotRem (try * max) denom
denomMinusR = denom - r
f b = if b
then UnifNat max (q+1)
else UnifNat max q
in if max <= denomMinusR
then Done (UnifNat max q)
else fmap f (biasedBit max denomMinusR)
randomDecision threshold max =
fmap (decision threshold) (uniform max)
-- q' * leftoverSize == b * stillNeeded == maxValue (newInt `mappend` n)
efficientDecision :: (Integral i) => Ratio i -> UnifNat i -> RValue Bool (Bool, UnifNat i)
efficientDecision r n@(UnifNat b _) =
let stillNeeded = denominator (r * (b % 1))
d newInt = ratioDecision r (newInt `mappend` n)
in fmap d (uniform stillNeeded)
vnUnbias :: RValue Bool Bool
vnUnbias = g Nothing
where g Nothing = NotDone $ \b -> g (Just b)
g (Just a) = NotDone $ \b -> if a == b then g Nothing else Done a | cullina/Extractor | src/RandomUniform.hs | bsd-3-clause | 3,544 | 0 | 14 | 1,304 | 963 | 507 | 456 | 74 | 5 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, InstanceSigs #-}
module Utility.ListMemory where
import Spec.Memory
import Utility.Utility
import Data.Word
helpStore mem addr bytes = f ++ bytes ++ drop (length bytes) s
where (f,s) = splitAt addr mem
instance Memory [Word8] Int where
loadByte :: [Word8] -> Int -> Word8
loadByte mem addr = mem !! addr
loadHalf :: [Word8] -> Int -> Word16
loadHalf mem addr = combineBytes $ take 2 $ drop addr mem
loadWord :: [Word8] -> Int -> Word32
loadWord mem addr = combineBytes $ take 4 $ drop addr mem
loadDouble :: [Word8] -> Int -> Word64
loadDouble mem addr = combineBytes $ take 8 $ drop addr mem
storeByte :: [Word8] -> Int -> Word8 -> [Word8]
storeByte mem addr val = setIndex addr val mem
storeHalf :: [Word8] -> Int -> Word16 -> [Word8]
storeHalf mem addr val = helpStore mem addr (splitHalf val)
storeWord :: [Word8] -> Int -> Word32 -> [Word8]
storeWord mem addr val = helpStore mem addr (splitWord val)
storeDouble :: [Word8] -> Int -> Word64 -> [Word8]
storeDouble mem addr val = helpStore mem addr (splitDouble val)
| mit-plv/riscv-semantics | src/Utility/ListMemory.hs | bsd-3-clause | 1,119 | 0 | 9 | 228 | 427 | 222 | 205 | 24 | 1 |
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE DoAndIfThenElse #-}
module Hslogic.Solve where
import Data.List
import Data.Functor.Identity
import "mtl" Control.Monad.State
import Hslogic.Types
import Hslogic.Unify
import Hslogic.Parse
type Clauses = [ Clause ]
-- | Maintains a list of goals and a context for generating more goals
data Goal = Goal {
varIndex :: Int -- ^Index to use for assigning fresh variables, should increase monotonically to
-- ensure uniquenesse of variables name across a run.
, goalSubstitution :: Subst -- ^ Substitution leading to that goal
, goals :: [Formula] -- ^ Current list of goals
, assumptions :: Clauses -- ^ Clauses used in proving this goal, might be reduced to single clause in case of
-- resolution through unification of terms
} | EmptyGoal -- ^ An unsolvable goal, eg. 'false'
deriving (Eq, Show)
-- | Select the first clause s.t. its head unifies with the given Term.
--
-- This is the heart of the solver where it selects a unifiable clause for the given term among
-- all given 'Clauses'.
--
-- First, the clause is instantiated with all its variables /fresh/, eg. s.t. they do not occur anywhere
-- else in the program. Currently this is implemented naively using the 'Int' given parameter which is
-- and index that is incremented for each new fresh variable.
--
-- If the clause's head can be unified with given 'Term' then 'selectClause' returns a new 'Goal'
-- containing an updated variables index, the 'Substitution' resulting from the unification of terms
-- and the clause's premises with inferred substitution applied. It also returns the remaining list of clauses
-- not applied, and the prefix of clauses skipped. eg. it returns the list of clauses split in half with the
-- selected clause removed.
--
-- >>> selectClause 1 (map clause ["foo(bar) <= qix.", "foo(X) <= baz (X)."]) (term "foo(foo)")
-- Just (Goal {varIndex = 2, goalSubstitution = [X1 -> foo], goals = [baz(foo)], assumptions = [foo(X) <= baz(X).]},[])
--
-- >>> selectClause 1 (map clause ["foo(bar) <= qix.", "foo(X) <= baz (X)."]) (term "foo(X)")
-- Just (Goal {varIndex = 1, goalSubstitution = [X -> bar], goals = [qix], assumptions = [foo(bar) <= qix.]},[foo(X) <= baz(X).])
--
selectClause :: Int -> Clauses -> Term -> Maybe (Goal, Clauses)
selectClause _ [] _ = Nothing
selectClause i (c:cs) t = let (i',c') = fresh i c
in case clauseHead c' <-> t of
Nothing -> selectClause i cs t
Just s -> Just (Goal i' s (map T (s `apply` clausePremises c')) [c],cs)
mkClauses :: [ String ] -> Clauses
mkClauses = map (fromRight . doParse clauseParser)
sampleClauses :: Clauses
sampleClauses = mkClauses [
"foo(bar) <= qix.",
"foo(baz) <= quux.",
"foo(X) <= baz (X).",
"baz(quux).",
"qix."
]
sampleClauses2 :: Clauses
sampleClauses2 = mkClauses [
"took(sue,cs120).",
"took(sue,cs121).",
"took(sue,cs240).",
"took(bob,cs120).",
"took(bob,cs370).",
"canGraduate(X) <= took(X,cs120), took(X,cs121), took(X,cs240), took(X,cs370)."
]
cakes :: Clauses
cakes = mkClauses [
"have(X) <= X.",
"eat(X) <= X."
]
data Logic = Intuitionistic | Linear deriving (Eq, Show)
type Trace = [ String ]
data Context = Context {
ctxLogic :: Logic
, ctxClauses :: Clauses
, ctxTrace :: Trace
}
addTrace :: String -> Context -> Context
addTrace trace c@(Context { ctxTrace }) = c { ctxTrace = trace : ctxTrace}
newtype SolverT m a = Solver { runSolver :: StateT Context m a }
deriving (Functor, Monad, MonadState Context)
type Solver a = SolverT Identity a
-- |Solves a list of terms (a query) providing a substitution for any variable occuring in it
-- if it succeeds.
--
solve :: Goal -> Solver [Goal]
-- end case : no more goals so success
solve g@(Goal _ s [] _) = do
modify (addTrace $ "success: " ++ show s)
return [g]
solve EmptyGoal = do
modify (addTrace $ "failure")
return [EmptyGoal]
-- base case
solve goal = do
c@(Context _ cs _) <- get
if cs == [] then
return [EmptyGoal]
else
solve' c goal
solve' :: Context -> Goal -> Solver [Goal]
solve' (Context _ cs traces) (Goal i s (e@(l :-> f):ts) us) =
put (Context Intuitionistic ((Clause l []):cs) (("implication: " ++ show e) : traces)) >> solve (Goal i s (f:ts) us)
solve' (Context _ cs traces) (Goal i s (e@(l :-@ f):ts) us) =
put (Context Linear ((Clause l []):cs) (("implication: " ++ show e): traces)) >> solve (Goal i s (f:ts) us)
solve' (Context Intuitionistic cs traces) (Goal i s (e@(l :* f):ts) us) =
(put (Context Intuitionistic cs (("left conjunction: " ++ show e) : traces)) >> solve (Goal i s (T l:ts) us)) >>=
(\ gs -> mapM ( \ (Goal i' s' ts' _) -> put (Context Intuitionistic cs (("right conjunction: " ++ show e) : traces)) >> solve (Goal i' s' (f:ts') us)) (filter (/= EmptyGoal) gs)) >>= return . concat
solve' (Context Linear cs traces) (Goal i s (e@(l :* f):ts) us) =
(put (Context Linear cs (("left tensor: " ++ show e) : traces)) >> solve (Goal i s (T l:ts) us)) >>=
(\ gs -> mapM ( \ (Goal i' s' ts' us') -> put (Context Linear (cs \\ us') (("right tensor: " ++ show e) : traces)) >> solve (Goal i' s' (f:ts') us)) (filter (/= EmptyGoal) gs)) >>= return . concat
solve' (Context Intuitionistic cs traces) (Goal i s terms@(T t:ts) us)=
case selectClause i cs t of
Just (Goal i' s' ts' [u],cs') -> let s''= s `extend_with` s'
in do
a <- (put (Context Intuitionistic cs (("int. term: "++ show t) : traces)) >> solve (Goal i' s'' (ts' ++ map (s'' `apply`) ts) (u:us)))
b <- (put (Context Intuitionistic cs' (("int. term (bktrack): "++ show t) : traces)) >> solve (Goal i' s terms us))
return $ a ++ b
_ -> return [ EmptyGoal ]
solve'(Context Linear cs traces) (Goal i s terms@(T t:ts) us) =
case selectClause i (cs \\ us) t of
Just (Goal i' s' ts' [u],cs') -> let s''= s `extend_with` s'
in do
a <- (put (Context Linear (cs \\ (u:us)) (("lin. term " ++ show t) : traces)) >> solve (Goal i' s'' (ts' ++ map (s'' `apply`) ts) (u:us)))
b <- (put (Context Linear cs' (("lin. term (bktrack)" ++ show t) : traces)) >> solve (Goal i' s terms us))
return $ a ++ b
_ -> return [ EmptyGoal ]
solve' _ _ = return []
-- |Generate all solutions for given query against given clauses.
--
-- >>> solutions sampleClauses (map formula ["foo(X)", "baz(Y)"])
-- [[Y -> quux,X -> bar],[Y -> quux,X -> quux]]
--
-- >>> solutions sampleClauses (map formula ["foo(X)", "baz(X)"])
-- [[X -> quux]]
--
-- >>> solutions sampleClauses2 (map formula ["took(sue,cs370) => canGraduate(sue)"])
-- [[]]
--
-- >>> solutions cakes (map formula ["cake -o have(cake), eat(cake)"])
-- []
-- >>> solutions cakes (map formula ["cake => have(cake), eat(cake)"])
-- [[]]
solutions :: Clauses -> [Formula] -> Solver [Subst]
solutions cs ts = do
let vars = vars_in ts
sols <- solve (Goal 1 emptySubstitution ts [])
return $ map ((-/- vars) . goalSubstitution) (filter (/= EmptyGoal) sols)
| abailly/hslogic | src/Hslogic/Solve.hs | bsd-3-clause | 7,768 | 0 | 22 | 2,160 | 2,114 | 1,137 | 977 | 102 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr,
pgPoolSize, runSqlPool)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai.Handler.Warp (Settings, defaultSettings,
defaultShouldDisplayException,
runSettings, setHost,
setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger (Destination (Logger),
IPAddrSource (..),
OutputFormat (..), destination,
mkRequestLogger, outputFormat)
import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet,
toLogStr)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Common
import Handler.Home
import Handler.PostEdit
import Handler.PostNew
import Handler.PostDetails
import Handler.Posts
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and return a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings = do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings then staticDevel else static)
(appStaticDir appSettings)
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
-- The App {..} syntax is an example of record wild cards. For more
-- information, see:
-- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html
tempFoundation = mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
-- Create the database connection pool
pool <- flip runLoggingT logFunc $ createPostgresqlPool
(pgConnStr $ appDatabaseConf appSettings)
(pgPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc
-- Return the foundation
return $ mkFoundation pool
-- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and
-- applyng some additional middlewares.
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromSocket)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare $ defaultMiddlewaresNoLogging appPlain
-- | Warp settings for the given foundation value.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadAppSettings [configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadAppSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
-- Run the application with Warp
runSettings (warpSettings foundation) app
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a
db = handler . runDB
| roggenkamps/steveroggenkamp.com | Application.hs | bsd-3-clause | 6,892 | 0 | 16 | 1,766 | 1,032 | 554 | 478 | -1 | -1 |
{- $Id: AFRPTestsUtils.hs,v 1.2 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* A F R P *
* *
* Module: AFRPTestsUtils *
* Purpose: Test cases for utilities (AFRPUtilities) *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
-- Not really intended to test all definitions in the utilities module.
module AFRPTestsUtils (utils_tr, utils_trs) where
import FRP.Yampa
import FRP.Yampa.Internals (Event(NoEvent, Event))
import FRP.Yampa.Utilities
import AFRPTestsCommon
------------------------------------------------------------------------------
-- Test cases for utilities (AFRPUtils)
------------------------------------------------------------------------------
-- Should re-order these test cases to reflect the order in AFRPUtils
-- at some point.
utils_inp1 = deltaEncode 1.0 $
[NoEvent, NoEvent, Event 1.0, NoEvent,
Event 2.0, NoEvent, NoEvent, NoEvent,
Event 3.0, Event 4.0, Event 4.0, NoEvent,
Event 0.0, NoEvent, NoEvent, NoEvent]
++ repeat NoEvent
utils_inp2 = deltaEncode 1.0 $
[Event 1.0, NoEvent, NoEvent, NoEvent,
Event 2.0, NoEvent, NoEvent, NoEvent,
Event 3.0, Event 4.0, Event 4.0, NoEvent,
Event 0.0, NoEvent, NoEvent, NoEvent]
++ repeat NoEvent
utils_t0 :: [Double]
utils_t0 = take 16 $ embed (dHold 99.99) utils_inp1
utils_t0r =
[99.99, 99.99, 99.99, 1.0,
1.0, 2.0, 2.0, 2.0,
2.0, 3.0, 4.0, 4.0,
4.0, 0.0, 0.0, 0.0]
utils_t1 :: [Double]
utils_t1 = take 16 $ embed (dHold 99.99) utils_inp2
utils_t1r =
[99.99, 1.0, 1.0, 1.0,
1.0, 2.0, 2.0, 2.0,
2.0, 3.0, 4.0, 4.0,
4.0, 0.0, 0.0, 0.0]
utils_inp3 = deltaEncode 1.0 $
[Nothing, Nothing, Just 1.0, Just 2.0, Just 3.0,
Just 4.0, Nothing, Nothing, Nothing, Just 3.0,
Just 2.0, Nothing, Just 1.0, Just 0.0, Just 1.0,
Just 2.0, Just 3.0, Nothing, Nothing, Just 4.0]
++ repeat Nothing
utils_inp4 = deltaEncode 1.0 $
[Just 0.0, Nothing, Just 1.0, Just 2.0, Just 3.0,
Just 4.0, Nothing, Nothing, Nothing, Just 3.0,
Just 2.0, Nothing, Just 1.0, Just 0.0, Just 1.0,
Just 2.0, Just 3.0, Nothing, Nothing, Just 4.0]
++ repeat Nothing
utils_t2 :: [Double]
utils_t2 = take 25 $ embed (dTrackAndHold 99.99) utils_inp3
utils_t2r =
[99.99, 99.99, 99.99, 1.0, 2.0,
3.0, 4.0, 4.0, 4.0, 4.0,
3.0, 2.0, 2.0, 1.0, 0.0,
1.0, 2.0, 3.0, 3.0, 3.0,
4.0, 4.0, 4.0, 4.0, 4.0]
utils_t3 :: [Double]
utils_t3 = take 25 $ embed (dTrackAndHold 99.99) utils_inp4
utils_t3r =
[99.99, 0.0, 0.0, 1.0, 2.0,
3.0, 4.0, 4.0, 4.0, 4.0,
3.0, 2.0, 2.0, 1.0, 0.0,
1.0, 2.0, 3.0, 3.0, 3.0,
4.0, 4.0, 4.0, 4.0, 4.0]
utils_t4 :: [Event Int]
utils_t4 = take 16 $ embed count utils_inp1
utils_t4r :: [Event Int]
utils_t4r =
[NoEvent, NoEvent, Event 1, NoEvent,
Event 2, NoEvent, NoEvent, NoEvent,
Event 3, Event 4, Event 5, NoEvent,
Event 6, NoEvent, NoEvent, NoEvent]
utils_t5 :: [Event Int]
utils_t5 = take 16 $ embed count utils_inp2
utils_t5r :: [Event Int]
utils_t5r =
[Event 1, NoEvent, NoEvent, NoEvent,
Event 2, NoEvent, NoEvent, NoEvent,
Event 3, Event 4, Event 5, NoEvent,
Event 6, NoEvent, NoEvent, NoEvent]
dynDelayLine :: a -> SF (a, Event Bool) a
dynDelayLine a0 =
second (arr (fmap (\p -> if p then addDelay else delDelay)))
>>> loop (arr (\((a, e), as) -> (a:as, e))
>>> rpSwitchZ [iPre a0]
>>> arr (\as -> (last as, init as)))
where
addDelay ds = ds ++ [last ds]
delDelay [d] = [d]
delDelay ds = init ds
utils_t6 :: [Int]
utils_t6 = take 200 $ embed (dynDelayLine 0)
(deltaEncode 0.1 (zip [1..] evSeq))
where
evSeq = NoEvent : Event True : NoEvent : NoEvent : Event True :
NoEvent : NoEvent : Event False : evSeq
utils_t6r =
[0,1,1,2,3,3,4,6,7,8,8,9,10,10,11,13,14,15,15,16,17,17,18,20,21,22,22,23,
24,24,25,27,28,29,29,30,31,31,32,34,35,36,36,37,38,38,39,41,42,43,43,44,
45,45,46,48,49,50,50,51,52,52,53,55,56,57,57,58,59,59,60,62,63,64,64,65,
66,66,67,69,70,71,71,72,73,73,74,76,77,78,78,79,80,80,81,83,84,85,85,86,
87,87,88,90,91,92,92,93,94,94,95,97,98,99,99,100,101,101,102,104,105,106,
106,107,108,108,109,111,112,113,113,114,115,115,116,118,119,120,120,121,
122,122,123,125,126,127,127,128,129,129,130,132,133,134,134,135,136,136,
137,139,140,141,141,142,143,143,144,146,147,148,148,149,150,150,151,153,
154,155,155,156,157,157,158,160,161,162,162,163,164,164,165,167,168,169,
169,170,171,171,172,174]
utils_t7 :: [Double]
utils_t7 = take 50 $ embed impulseIntegral
(deltaEncode 0.1 (zip (repeat 1.0) evSeq))
where
evSeq = replicate 9 NoEvent ++ [Event 10.0]
++ replicate 9 NoEvent ++ [Event (-10.0)]
++ evSeq
utils_t7r =
[ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 10.9,
11.0, 11.1, 11.2, 11.3, 11.4, 11.5, 11.6, 11.7, 11.8, 1.9,
2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 12.9,
13.0, 13.1, 13.2, 13.3, 13.4, 13.5, 13.6, 13.7, 13.8, 3.9,
4.0, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 14.9]
utils_t8 :: [Double]
utils_t8 = take 50 $ embed (provided (even . floor) integral (constant (-1)))
(deltaEncode 0.1 input)
where
input = replicate 10 1
++ replicate 10 2
++ replicate 10 3
++ replicate 10 4
++ input
utils_t8r =
[-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0,
0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8,
-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0,
0.0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4, 2.8, 3.2, 3.6,
-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0]
utils_t9 :: [Double]
utils_t9 = take 50 $ embed (provided (odd . floor) integral (constant (-1)))
(deltaEncode 0.1 input)
where
input = replicate 10 1
++ replicate 10 2
++ replicate 10 3
++ replicate 10 4
++ input
utils_t9r =
[ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,
-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0,
0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7,
-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0,
0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
utils_t10 :: [Event Double]
utils_t10 = testSF1 snap
utils_t10r =
[Event 0.0, NoEvent, NoEvent, NoEvent, -- 0.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 1.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 2.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 3.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 4.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 5.0 s
NoEvent]
utils_t11 :: [Event Double]
utils_t11 = testSF1 (snapAfter 2.6)
utils_t11r =
[NoEvent, NoEvent, NoEvent, NoEvent, -- 0.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 1.0 s
NoEvent, NoEvent, NoEvent, Event 11.0, -- 2.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 3.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 4.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 5.0 s
NoEvent]
utils_t12 :: [Event Double]
utils_t12 = testSF1 (sample 0.99)
utils_t12r =
[NoEvent, NoEvent, NoEvent, NoEvent, -- 0.0 s
Event 4.0, NoEvent, NoEvent, NoEvent, -- 1.0 s
Event 8.0, NoEvent, NoEvent, NoEvent, -- 2.0 s
Event 12.0, NoEvent, NoEvent, NoEvent, -- 3.0 s
Event 16.0, NoEvent, NoEvent, NoEvent, -- 4.0 s
Event 20.0, NoEvent, NoEvent, NoEvent, -- 5.0 s
Event 24.0]
utils_t13 :: [Event ()]
utils_t13 = testSF1 (recur (after 0.99 ()))
utils_t13r =
[NoEvent, NoEvent, NoEvent, NoEvent, -- 0.0 s
Event (), NoEvent, NoEvent, NoEvent, -- 1.0 s
Event (), NoEvent, NoEvent, NoEvent, -- 2.0 s
Event (), NoEvent, NoEvent, NoEvent, -- 3.0 s
Event (), NoEvent, NoEvent, NoEvent, -- 4.0 s
Event (), NoEvent, NoEvent, NoEvent, -- 5.0 s
Event ()]
utils_t14 :: [Event Int]
utils_t14 = testSF1 (after 1.0 1 `andThen` now 2 `andThen` after 2.0 3)
utils_t14r =
[NoEvent, NoEvent, NoEvent, NoEvent, -- 0.0 s
Event 1, NoEvent, NoEvent, NoEvent, -- 1.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 2.0 s
Event 3, NoEvent, NoEvent, NoEvent, -- 3.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 4.0 s
NoEvent, NoEvent, NoEvent, NoEvent, -- 5.0 s
NoEvent]
utils_t15 = take 50 (embed (time >>> sampleWindow 5 0.5)
(deltaEncode 0.125 (repeat ())))
utils_t15r =
[ NoEvent, NoEvent, NoEvent, NoEvent, -- 0.0 s
Event [0.5], NoEvent, NoEvent, NoEvent, -- 0.5 s
Event [0.5,1.0], NoEvent, NoEvent, NoEvent, -- 1.0 s
Event [0.5,1.0,1.5], NoEvent, NoEvent, NoEvent, -- 1.5 s
Event [0.5,1.0,1.5,2.0], NoEvent, NoEvent, NoEvent, -- 2.0 s
Event [0.5,1.0,1.5,2.0,2.5], NoEvent, NoEvent, NoEvent, -- 2.5 s
Event [1.0,1.5,2.0,2.5,3.0], NoEvent, NoEvent, NoEvent, -- 3.0 s
Event [1.5,2.0,2.5,3.0,3.5], NoEvent, NoEvent, NoEvent, -- 3.5 s
Event [2.0,2.5,3.0,3.5,4.0], NoEvent, NoEvent, NoEvent, -- 4.0 s
Event [2.5,3.0,3.5,4.0,4.5], NoEvent, NoEvent, NoEvent, -- 4.5 s
Event [3.0,3.5,4.0,4.5,5.0], NoEvent, NoEvent, NoEvent, -- 5.0 s
Event [3.5,4.0,4.5,5.0,5.5], NoEvent, NoEvent, NoEvent, -- 5.5 s
Event [4.0,4.5,5.0,5.5,6.0], NoEvent -- 6.0 s
]
{-
-- Not robust
utils_t16 = take 50 (embed (time >>> sampleWindow 5 0.5) input)
where
input = ((), [(dt, Just ()) | dt <- dts])
dts = replicate 15 0.1
++ [1.0, 1.0]
++ replicate 15 0.1
++ [2.0]
++ replicate 10 0.1
utils_t16r =
[ NoEvent, NoEvent, NoEvent, NoEvent, NoEvent, -- 0.0
NoEvent, Event [0.6], NoEvent, NoEvent, NoEvent, -- 0.5
NoEvent, Event [0.6, 1.1], NoEvent, NoEvent, NoEvent, -- 1.0
NoEvent, -- 1.5
Event [0.6,1.1,2.5,2.5,2.5], -- 2.5
Event [2.5,2.5,2.5,3.5,3.5], NoEvent, NoEvent, NoEvent, NoEvent, -- 3.5
NoEvent, Event [2.5,2.5,3.5,3.5,4.1], NoEvent, NoEvent, NoEvent, -- 4.0
NoEvent, Event [2.5,3.5,3.5,4.1,4.6], NoEvent, NoEvent, NoEvent, -- 4.5
NoEvent, -- 5.0
Event [7.0,7.0,7.0,7.0,7.0], NoEvent, NoEvent, NoEvent, NoEvent, -- 7.0
NoEvent, Event [7.0,7.0,7.0,7.0,7.6], NoEvent, NoEvent, NoEvent, -- 7.5
NoEvent -- 8.0
]
-}
utils_t16 = take 50 (embed (time >>> sampleWindow 5 0.4999) input)
where
input = ((), [(dt, Just ()) | dt <- dts])
dts = replicate 15 0.1
++ [1.0, 1.0]
++ replicate 15 0.1
++ [2.0]
++ replicate 10 0.1
utils_t16r =
[ NoEvent, NoEvent, NoEvent, NoEvent, NoEvent, -- 0.0
Event [0.5], NoEvent, NoEvent, NoEvent, NoEvent, -- 0.5
Event [0.5, 1.0], NoEvent, NoEvent, NoEvent, NoEvent, -- 1.0
Event [0.5, 1.0, 1.5], -- 1.5
Event [0.5, 1.0, 1.5, 2.5, 2.5], -- 2.5
Event [1.5, 2.5, 2.5, 3.5, 3.5], NoEvent, NoEvent, NoEvent, -- 3.5
NoEvent,
Event [2.5, 2.5, 3.5, 3.5, 4.0], NoEvent, NoEvent, NoEvent, -- 4.0
NoEvent,
Event [2.5, 3.5, 3.5, 4.0, 4.5], NoEvent, NoEvent, NoEvent, -- 4.5
NoEvent,
Event [3.5, 3.5, 4.0, 4.5, 5.0], -- 5.0
Event [5.0, 7.0, 7.0, 7.0, 7.0], NoEvent, NoEvent, NoEvent, -- 7.0
NoEvent,
Event [7.0, 7.0, 7.0, 7.0, 7.5], NoEvent, NoEvent, NoEvent, -- 7.5
NoEvent,
Event [7.0, 7.0, 7.0, 7.5, 8.0] -- 8.0
]
utils_trs =
[ utils_t0 ~= utils_t0r,
utils_t1 ~= utils_t1r,
utils_t2 ~= utils_t2r,
utils_t3 ~= utils_t3r,
utils_t4 ~= utils_t4r,
utils_t5 ~= utils_t5r,
utils_t6 ~= utils_t6r,
utils_t7 ~= utils_t7r,
utils_t8 ~= utils_t8r,
utils_t9 ~= utils_t9r,
utils_t10 ~= utils_t10r,
utils_t11 ~= utils_t11r,
utils_t12 ~= utils_t12r,
utils_t13 ~= utils_t13r,
utils_t14 ~= utils_t14r,
utils_t15 ~= utils_t15r,
utils_t16 ~= utils_t16r
]
utils_tr = and utils_trs
| eamsden/Animas | tests/AFRPTestsUtils.hs | bsd-3-clause | 12,850 | 14 | 15 | 3,699 | 4,446 | 2,675 | 1,771 | 250 | 3 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
module Examples where
import Data.RDF
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Text as T
import Data.FileEmbed
import qualified Data.ByteString.Char8 as BS
import Text.Pandoc.Definition
import Data.Default (def)
import Text.Scalar
import Test.Hspec (Expectation, shouldBe, shouldSatisfy)
examples :: [(FilePath, BS.ByteString)]
examples = $(embedDir "test/examples")
getExample :: FilePath -> String
getExample ex = case (lookup ex examples) of
Just s -> BS.unpack s
Nothing -> error $ ex ++ " not found"
singlePage :: HashMapS
singlePage = mkRdf triples baseurl prefixes
where baseurl = Just (BaseUrl "")
prefixes = PrefixMappings $ Map.fromList [ ("dcterms", "http://purl.org/dc/terms/")
, ("ov", "http://open.vocab.org/terms/")
, ("prov", "http://www.w3.org/ns/prov#")
, ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
, ("scalar", "http://scalar.usc.edu/2012/01/scalar-ns#")
, ("sioc", "http://rdfs.org/sioc/ns#") ]
triples = [ Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index") (UNode "scalar:citation") (LNode (PlainL "method=instancesof/content;methodNumNodes=1;"))
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index") (UNode "dcterms:hasVersion") (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1")
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index") (UNode "scalar:version") (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1"),Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index") (UNode "scalar:urn") (UNode "urn:scalar:content:297474")
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index") (UNode "dcterms:created") (LNode (PlainL "2016-06-20T12:41:52-07:00"))
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index") (UNode "prov:wasAttributedTo") (UNode "http://scalar.usc.edu/works/scalar-export-test/users/11802")
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index") (UNode "scalar:isLive") (LNode (PlainL "1"))
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index") (UNode "rdf:type") (UNode "http://scalar.usc.edu/2012/01/scalar-ns#Composite")
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1") (UNode "rdf:type") (UNode "http://scalar.usc.edu/2012/01/scalar-ns#Version")
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1") (UNode "dcterms:isVersionOf") (UNode "http://scalar.usc.edu/works/scalar-export-test/index")
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1") (UNode "scalar:urn") (UNode "urn:scalar:version:791282")
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1") (UNode "dcterms:created") (LNode (PlainL "2016-06-20T12:41:52-07:00"))
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1") (UNode "prov:wasAttributedTo") (UNode "http://scalar.usc.edu/works/scalar-export-test/users/11802")
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1") (UNode "scalar:defaultView") (LNode (PlainL "plain"))
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1") (UNode "sioc:content") (LNode (PlainL "This is a test book for the <a href=\"https://github.com/corajr/scalar-export\">scalar-export</a> package. It contains different formatting, such as <strong>bold</strong> and <em>italics</em>."))
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1") (UNode "dcterms:title") (LNode (PlainL "Introduction"))
, Triple (UNode "http://scalar.usc.edu/works/scalar-export-test/index.1") (UNode "ov:versionnumber") (LNode (PlainL "1"))
]
singlePageContent :: T.Text
singlePageContent = "This is a test book for the <a href=\"https://github.com/corajr/scalar-export\">scalar-export</a> package. It contains different formatting, such as <strong>bold</strong> and <em>italics</em>."
singlePageContentPandoc :: [Block]
singlePageContentPandoc = [Para [Str "This",Space,Str "is",Space,Str "a",Space,Str "test",Space,Str "book",Space,Str "for",Space,Str "the",Space,Link ("",[],[]) [Str "scalar-export"] ("https://github.com/corajr/scalar-export",""),Str "\160package.",Space,Str "It",Space,Str "contains",Space,Str "different",Space,Str "formatting,",Space,Str "such",Space,Str "as",Space,Strong [Str "bold"],Space,Str "and\160",Emph [Str "italics"],Str "."]]
singlePageTitle :: Block
singlePageTitle = Header 1 ("introduction", [], []) [Str "Introduction"]
singlePagePandoc :: Pandoc
singlePagePandoc = Pandoc nullMeta (singlePageTitle : singlePageContentPandoc)
singlePageScalarPage :: Page
singlePageScalarPage = Page { pageTitle = "Introduction", pageContent = singlePageContent }
singlePageScalar :: Scalar
singlePageScalar =
Scalar { scalarOptions = def
, scalarPaths = Map.empty
, scalarPages = Map.singleton singlePageVersionURI singlePageScalarPage
}
indexURI :: URI
indexURI = "http://scalar.usc.edu/works/scalar-export-test/index"
singlePageVersionURI :: VersionURI
singlePageVersionURI = mkVersionURI $ indexURI `mappend` ".1"
fullBookRdf :: HashMapS
fullBookRdf =
case fst (runScalarM (readScalarString (getExample "full_book.xml"))) of
Left err -> error (show err)
Right x -> x
fullBookScalar :: Scalar
fullBookScalar = case runScalarM (parseScalar fullBookRdf def) of
(Left err, _) -> error (show err)
(Right x, _) -> x
shouldBeScalar :: (Eq a, Show a) => ScalarM a -> Either ScalarError a -> Expectation
action `shouldBeScalar` result = fst (runScalarM action) `shouldBe` result
shouldSatisfyScalar :: (Show a) => ScalarM a -> (Either ScalarError a -> Bool) -> Expectation
action `shouldSatisfyScalar` predicate = fst (runScalarM action) `shouldSatisfy` predicate
| corajr/scalar-convert | test/Examples.hs | bsd-3-clause | 6,375 | 0 | 12 | 1,116 | 1,440 | 774 | 666 | 76 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Sheets where
import ClassyPrelude
import Codec.Xlsx
import Control.Lens
import qualified Control.Foldl as F
class ToCellValue a where
toCellValue :: a -> CellValue
instance ToCellValue Double where
toCellValue = CellDouble
instance ToCellValue Text where
toCellValue = CellText
instance ToCellValue Bool where
toCellValue = CellBool
instance ToCellValue Int where
toCellValue = CellDouble . fromIntegral
| limaner2002/EPC-tools | sheets/src/Sheets.hs | bsd-3-clause | 499 | 0 | 7 | 79 | 101 | 58 | 43 | 17 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MonadComprehensions #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
-- | A set of DSH examples for the demo session at SIGMOD 2015
--
-- This package contains selected examples that demonstrate various aspects of
-- database queries in DSH. The set of examples was used for the demo session at
-- SIGMOD 15.
--
-- Ulrich, Grust: <http://db.inf.uni-tuebingen.de/publications/TheFlatter-theBetter-QueryCompilationBasedontheFlatteningTransformation.html The Flatter the Better> (SIGMOD'15)
module Queries.SIGMOD
( module Queries.SIGMOD.Simple
, module Queries.SIGMOD.Order
, module Queries.SIGMOD.Layered
, module Queries.SIGMOD.Nested
) where
import Queries.SIGMOD.Simple
import Queries.SIGMOD.Order
import Queries.SIGMOD.Layered
import Queries.SIGMOD.Nested
| ulricha/dsh-example-queries | Queries/SIGMOD.hs | bsd-3-clause | 973 | 0 | 5 | 182 | 73 | 54 | 19 | 15 | 0 |
module ReadData where
import System.IO
import Perceptron
import Prelude hiding (Bool, True, False)
import qualified Prelude as P
import Data.Ratio ( (%), numerator, denominator )
import Data.List ( isInfixOf )
-- Assumes string is a string representation of rational or float
readRational :: String -> Rational
readRational input =
if (isInfixOf "%" input) then
read input
else
((read intPart)*(10 ^ length fracPart) + (read fracPart)) % (10 ^ length fracPart)
where (intPart, fromDot) = span (/='.') input
fracPart = if null fromDot then "0" else tail fromDot
-- Assumes z >= 1
intToPos :: Integral a => a -> Positive
intToPos z
| z == 1 = XH
| P.odd z = XI (intToPos (z `P.quot` 2))
| otherwise = XO (intToPos (z `P.quot` 2))
intToZ :: Integral a => a -> Z
intToZ z
| z == 0 = Z0
| z < 0 = Zneg (intToPos (P.abs z))
| otherwise = Zpos (intToPos z)
-- Assumes Z >= 0
intToNat :: Integral a => a -> Nat
intToNat z
| z == 0 = O
| otherwise = S (intToNat (z-1))
-- See Assumptions for intToZ and intToPos
ratToQ :: Rational -> Q
ratToQ q =
Qmake (intToZ (numerator q)) (intToPos (denominator q))
debug = P.False
-- Not tail-recursive...should rewrite to use an acc.
read_vec' :: Nat -> IO Qvec
read_vec' n =
case n of
O -> return []
S n' ->
do { feat <- hGetLine stdin
; if debug then do { putStr "feat = "; putStrLn (show feat) } else return ()
; rest <- read_vec' n'
; return $ (:) (ratToQ (readRational feat)) rest
}
read_vec :: Nat -> IO ((,) Qvec P.Bool)
read_vec nfeats =
do { lbl <- hGetLine stdin
; let l = if read lbl == 0 then P.False else P.True -- no error-handling here
; if debug then do { putStr "label = "; putStrLn (show lbl) } else return ()
; res <- read_vec' nfeats
; return (res, l)
}
read_vecs :: Int -> Int -> IO (([]) ((,) Qvec P.Bool))
read_vecs nvecs nfeats
| nvecs <= 0 = return []
| otherwise
= do { let feats = intToNat nfeats
; v <- read_vec feats
; rest <- read_vecs (nvecs-1) nfeats
; return $ (:) v rest
}
zero_vec :: Nat -> Qvec
zero_vec O = []
zero_vec (S n') = (:) (Qmake Z0 XH) (zero_vec n')
-- Functionality to Convert from Q to Rat and Print Qvecs and Lists of Qvecs
posToInt :: Positive -> Integer
posToInt p =
case p of
XH -> 1
XI p' -> (2 * (posToInt p') + 1)
XO p' -> (2 * (posToInt p'))
zToInt :: Z -> Integer
zToInt z =
case z of
Z0 -> 0
Zneg p -> (- posToInt p)
Zpos p -> (posToInt p)
qToRat :: Q -> Rational
qToRat r =
case r of
Qmake z p -> (zToInt z)%(posToInt p)
printQvec :: Qvec -> IO ()
printQvec qv =
do {
; putStr "<"
; go qv
; putStr ">"
}
where go :: Qvec -> IO ()
go qv =
case qv of
(:) q [] -> putStr (show (qToRat q))
(:) q qv' -> do { putStr (show (qToRat q)); putStr ", "; go qv' }
putQvec :: Qvec -> IO ()
putQvec qv =
case qv of
[] -> putStr ""
(:) q qv' -> do { putStrLn (show (qToRat q)); putQvec qv' }
printQvecL :: ([]) ((,) Qvec P.Bool) -> IO ()
printQvecL l =
case l of
[] -> putStr ""
(:) ((,) qv lbl) l' -> do { putStr "("
; printQvec qv
; putStr ", "
; putStr (show lbl)
; putStrLn ")"
; printQvecL l'
}
putQvecL :: ([]) ((,) Qvec P.Bool) -> IO ()
putQvecL l =
case l of
[] -> putStr ""
(:) ((,) qv lbl) l' -> do { if lbl == P.True then putStrLn "1" else putStrLn "0"
; putQvec qv
; putQvecL l'
}
| tm507211/CoqPerceptron | Benchmarks/hs/ReadData.hs | bsd-3-clause | 3,746 | 4 | 16 | 1,245 | 1,604 | 811 | 793 | 108 | 3 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
#endif
#if __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Trustworthy #-}
#endif
#if __GLASGOW_HASKELL__ >= 708
{-# LANGUAGE TypeFamilies #-}
#endif
#include "containers.h"
-----------------------------------------------------------------------------
-- |
-- Module : Data.Sequence
-- Copyright : (c) Ross Paterson 2005
-- (c) Louis Wasserman 2009
-- (c) David Feuer, Ross Paterson, and Milan Straka 2014
-- License : BSD-style
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- General purpose finite sequences.
-- Apart from being finite and having strict operations, sequences
-- also differ from lists in supporting a wider variety of operations
-- efficiently.
--
-- An amortized running time is given for each operation, with /n/ referring
-- to the length of the sequence and /i/ being the integral index used by
-- some operations. These bounds hold even in a persistent (shared) setting.
--
-- The implementation uses 2-3 finger trees annotated with sizes,
-- as described in section 4.2 of
--
-- * Ralf Hinze and Ross Paterson,
-- \"Finger trees: a simple general-purpose data structure\",
-- /Journal of Functional Programming/ 16:2 (2006) pp 197-217.
-- <http://staff.city.ac.uk/~ross/papers/FingerTree.html>
--
-- /Note/: Many of these operations have the same names as similar
-- operations on lists in the "Prelude". The ambiguity may be resolved
-- using either qualification or the @hiding@ clause.
--
-----------------------------------------------------------------------------
module Data.Sequence (
#if !defined(TESTING)
Seq,
#else
Seq(..), Elem(..), FingerTree(..), Node(..), Digit(..),
#endif
-- * Construction
empty, -- :: Seq a
singleton, -- :: a -> Seq a
(<|), -- :: a -> Seq a -> Seq a
(|>), -- :: Seq a -> a -> Seq a
(><), -- :: Seq a -> Seq a -> Seq a
fromList, -- :: [a] -> Seq a
fromFunction, -- :: Int -> (Int -> a) -> Seq a
fromArray, -- :: Ix i => Array i a -> Seq a
-- ** Repetition
replicate, -- :: Int -> a -> Seq a
replicateA, -- :: Applicative f => Int -> f a -> f (Seq a)
replicateM, -- :: Monad m => Int -> m a -> m (Seq a)
-- ** Iterative construction
iterateN, -- :: Int -> (a -> a) -> a -> Seq a
unfoldr, -- :: (b -> Maybe (a, b)) -> b -> Seq a
unfoldl, -- :: (b -> Maybe (b, a)) -> b -> Seq a
-- * Deconstruction
-- | Additional functions for deconstructing sequences are available
-- via the 'Foldable' instance of 'Seq'.
-- ** Queries
null, -- :: Seq a -> Bool
length, -- :: Seq a -> Int
-- ** Views
ViewL(..),
viewl, -- :: Seq a -> ViewL a
ViewR(..),
viewr, -- :: Seq a -> ViewR a
-- * Scans
scanl, -- :: (a -> b -> a) -> a -> Seq b -> Seq a
scanl1, -- :: (a -> a -> a) -> Seq a -> Seq a
scanr, -- :: (a -> b -> b) -> b -> Seq a -> Seq b
scanr1, -- :: (a -> a -> a) -> Seq a -> Seq a
-- * Sublists
tails, -- :: Seq a -> Seq (Seq a)
inits, -- :: Seq a -> Seq (Seq a)
-- ** Sequential searches
takeWhileL, -- :: (a -> Bool) -> Seq a -> Seq a
takeWhileR, -- :: (a -> Bool) -> Seq a -> Seq a
dropWhileL, -- :: (a -> Bool) -> Seq a -> Seq a
dropWhileR, -- :: (a -> Bool) -> Seq a -> Seq a
spanl, -- :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
spanr, -- :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
breakl, -- :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
breakr, -- :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
partition, -- :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
filter, -- :: (a -> Bool) -> Seq a -> Seq a
-- * Sorting
sort, -- :: Ord a => Seq a -> Seq a
sortBy, -- :: (a -> a -> Ordering) -> Seq a -> Seq a
unstableSort, -- :: Ord a => Seq a -> Seq a
unstableSortBy, -- :: (a -> a -> Ordering) -> Seq a -> Seq a
-- * Indexing
index, -- :: Seq a -> Int -> a
adjust, -- :: (a -> a) -> Int -> Seq a -> Seq a
update, -- :: Int -> a -> Seq a -> Seq a
take, -- :: Int -> Seq a -> Seq a
drop, -- :: Int -> Seq a -> Seq a
splitAt, -- :: Int -> Seq a -> (Seq a, Seq a)
-- ** Indexing with predicates
-- | These functions perform sequential searches from the left
-- or right ends of the sequence, returning indices of matching
-- elements.
elemIndexL, -- :: Eq a => a -> Seq a -> Maybe Int
elemIndicesL, -- :: Eq a => a -> Seq a -> [Int]
elemIndexR, -- :: Eq a => a -> Seq a -> Maybe Int
elemIndicesR, -- :: Eq a => a -> Seq a -> [Int]
findIndexL, -- :: (a -> Bool) -> Seq a -> Maybe Int
findIndicesL, -- :: (a -> Bool) -> Seq a -> [Int]
findIndexR, -- :: (a -> Bool) -> Seq a -> Maybe Int
findIndicesR, -- :: (a -> Bool) -> Seq a -> [Int]
-- * Folds
-- | General folds are available via the 'Foldable' instance of 'Seq'.
foldlWithIndex, -- :: (b -> Int -> a -> b) -> b -> Seq a -> b
foldrWithIndex, -- :: (Int -> a -> b -> b) -> b -> Seq a -> b
-- * Transformations
mapWithIndex, -- :: (Int -> a -> b) -> Seq a -> Seq b
reverse, -- :: Seq a -> Seq a
-- ** Zips
zip, -- :: Seq a -> Seq b -> Seq (a, b)
zipWith, -- :: (a -> b -> c) -> Seq a -> Seq b -> Seq c
zip3, -- :: Seq a -> Seq b -> Seq c -> Seq (a, b, c)
zipWith3, -- :: (a -> b -> c -> d) -> Seq a -> Seq b -> Seq c -> Seq d
zip4, -- :: Seq a -> Seq b -> Seq c -> Seq d -> Seq (a, b, c, d)
zipWith4, -- :: (a -> b -> c -> d -> e) -> Seq a -> Seq b -> Seq c -> Seq d -> Seq e
#if TESTING
Sized(..),
deep,
node2,
node3,
#endif
) where
import Prelude hiding (
Functor(..),
null, length, take, drop, splitAt, foldl, foldl1, foldr, foldr1,
scanl, scanl1, scanr, scanr1, replicate, zip, zipWith, zip3, zipWith3,
takeWhile, dropWhile, iterate, reverse, filter, mapM, sum, all)
import qualified Data.List
import Control.Applicative (Applicative(..), (<$>), Alternative,
WrappedMonad(..), liftA, liftA2, liftA3)
import qualified Control.Applicative as Applicative (Alternative(..))
import Control.DeepSeq (NFData(rnf))
import Control.Monad (MonadPlus(..), ap)
import Data.Monoid (Monoid(..))
import Data.Functor (Functor(..))
import Data.Foldable (Foldable(foldl, foldl1, foldr, foldr1, foldMap), foldl', toList)
#if MIN_VERSION_base(4,8,0)
import Data.Foldable (foldr')
#endif
import Data.Traversable
import Data.Typeable
-- GHC specific stuff
#ifdef __GLASGOW_HASKELL__
import GHC.Exts (build)
import Text.Read (Lexeme(Ident), lexP, parens, prec,
readPrec, readListPrec, readListPrecDefault)
import Data.Data
#endif
-- Array stuff, with GHC.Arr on GHC
import Data.Array (Ix, Array)
#ifdef __GLASGOW_HASKELL__
import qualified GHC.Arr
#endif
-- Coercion on GHC 7.8+
#if __GLASGOW_HASKELL__ >= 708
import Data.Coerce
import qualified GHC.Exts
#else
#endif
-- Identity functor on base 4.8 (GHC 7.10+)
#if MIN_VERSION_base(4,8,0)
import Data.Functor.Identity (Identity(..))
#endif
infixr 5 `consTree`
infixl 5 `snocTree`
infixr 5 `appendTree0`
infixr 5 ><
infixr 5 <|, :<
infixl 5 |>, :>
class Sized a where
size :: a -> Int
-- | General-purpose finite sequences.
newtype Seq a = Seq (FingerTree (Elem a))
instance Functor Seq where
fmap = fmapSeq
#ifdef __GLASGOW_HASKELL__
x <$ s = replicate (length s) x
#endif
fmapSeq :: (a -> b) -> Seq a -> Seq b
fmapSeq f (Seq xs) = Seq (fmap (fmap f) xs)
#ifdef __GLASGOW_HASKELL__
{-# NOINLINE [1] fmapSeq #-}
{-# RULES
"fmapSeq/fmapSeq" forall f g xs . fmapSeq f (fmapSeq g xs) = fmapSeq (f . g) xs
#-}
#endif
#if __GLASGOW_HASKELL__ >= 709
-- Safe coercions were introduced in 7.8, but did not work well with RULES yet.
{-# RULES
"fmapSeq/coerce" fmapSeq coerce = coerce
#-}
#endif
instance Foldable Seq where
foldMap f (Seq xs) = foldMap (foldMap f) xs
foldr f z (Seq xs) = foldr (flip (foldr f)) z xs
foldl f z (Seq xs) = foldl (foldl f) z xs
foldr1 f (Seq xs) = getElem (foldr1 f' xs)
where f' (Elem x) (Elem y) = Elem (f x y)
foldl1 f (Seq xs) = getElem (foldl1 f' xs)
where f' (Elem x) (Elem y) = Elem (f x y)
#if MIN_VERSION_base(4,8,0)
length = length
{-# INLINE length #-}
null = null
{-# INLINE null #-}
#endif
instance Traversable Seq where
traverse f (Seq xs) = Seq <$> traverse (traverse f) xs
instance NFData a => NFData (Seq a) where
rnf (Seq xs) = rnf xs
instance Monad Seq where
return = singleton
xs >>= f = foldl' add empty xs
where add ys x = ys >< f x
(>>) = (*>)
instance Applicative Seq where
pure = singleton
Seq Empty <*> xs = xs `seq` empty
fs <*> Seq Empty = fs `seq` empty
fs <*> Seq (Single (Elem x)) = fmap ($ x) fs
fs <*> xs
| length fs < 4 = foldl' add empty fs
where add ys f = ys >< fmap f xs
fs <*> xs | length xs < 4 = apShort fs xs
fs <*> xs = apty fs xs
xs *> ys = replicateSeq (length xs) ys
-- <*> when the length of the first argument is at least two and
-- the length of the second is two or three.
apShort :: Seq (a -> b) -> Seq a -> Seq b
apShort (Seq fs) xs = Seq $ case toList xs of
[a,b] -> ap2FT fs (a,b)
[a,b,c] -> ap3FT fs (a,b,c)
_ -> error "apShort: not 2-3"
ap2FT :: FingerTree (Elem (a->b)) -> (a,a) -> FingerTree (Elem b)
ap2FT fs (x,y) = Deep (size fs * 2)
(Two (Elem $ firstf x) (Elem $ firstf y))
(mapMulFT 2 (\(Elem f) -> Node2 2 (Elem (f x)) (Elem (f y))) m)
(Two (Elem $ lastf x) (Elem $ lastf y))
where
(Elem firstf, m, Elem lastf) = trimTree fs
ap3FT :: FingerTree (Elem (a->b)) -> (a,a,a) -> FingerTree (Elem b)
ap3FT fs (x,y,z) = Deep (size fs * 3)
(Three (Elem $ firstf x) (Elem $ firstf y) (Elem $ firstf z))
(mapMulFT 3 (\(Elem f) -> Node3 3 (Elem (f x)) (Elem (f y)) (Elem (f z))) m)
(Three (Elem $ lastf x) (Elem $ lastf y) (Elem $ lastf z))
where
(Elem firstf, m, Elem lastf) = trimTree fs
-- <*> when the length of each argument is at least four.
apty :: Seq (a -> b) -> Seq a -> Seq b
apty (Seq fs) (Seq xs@Deep{}) = Seq $
Deep (s' * size fs)
(fmap (fmap firstf) pr')
(aptyMiddle (fmap firstf) (fmap lastf) fmap fs' xs')
(fmap (fmap lastf) sf')
where
(Elem firstf, fs', Elem lastf) = trimTree fs
xs'@(Deep s' pr' _m' sf') = rigidify xs
apty _ _ = error "apty: expects a Deep constructor"
-- | 'aptyMiddle' does most of the hard work of computing @fs<*>xs@.
-- It produces the center part of a finger tree, with a prefix corresponding
-- to the prefix of @xs@ and a suffix corresponding to the suffix of @xs@
-- omitted; the missing suffix and prefix are added by the caller.
-- For the recursive call, it squashes the prefix and the suffix into
-- the center tree. Once it gets to the bottom, it turns the tree into
-- a 2-3 tree, applies 'mapMulFT' to produce the main body, and glues all
-- the pieces together.
aptyMiddle
:: Sized c =>
(c -> d)
-> (c -> d)
-> ((a -> b) -> c -> d)
-> FingerTree (Elem (a -> b))
-> FingerTree c
-> FingerTree (Node d)
-- Not at the bottom yet
aptyMiddle firstf
lastf
map23
fs
(Deep s pr (Deep sm prm mm sfm) sf)
= Deep (sm + s * (size fs + 1)) -- note: sm = s - size pr - size sf
(fmap (fmap firstf) prm)
(aptyMiddle (fmap firstf)
(fmap lastf)
(\f -> fmap (map23 f))
fs
(Deep s (squashL pr prm) mm (squashR sfm sf)))
(fmap (fmap lastf) sfm)
-- At the bottom
aptyMiddle firstf
lastf
map23
fs
(Deep s pr m sf)
= (fmap (fmap firstf) m `snocTree` fmap firstf (digitToNode sf))
`appendTree0` middle `appendTree0`
(fmap lastf (digitToNode pr) `consTree` fmap (fmap lastf) m)
where middle = case trimTree $ mapMulFT s (\(Elem f) -> fmap (fmap (map23 f)) converted) fs of
(firstMapped, restMapped, lastMapped) ->
Deep (size firstMapped + size restMapped + size lastMapped)
(nodeToDigit firstMapped) restMapped (nodeToDigit lastMapped)
converted = case m of
Empty -> Node2 s lconv rconv
Single q -> Node3 s lconv q rconv
Deep{} -> error "aptyMiddle: impossible"
lconv = digitToNode pr
rconv = digitToNode sf
aptyMiddle _ _ _ _ _ = error "aptyMiddle: expected Deep finger tree"
{-# SPECIALIZE
aptyMiddle
:: (Node c -> d)
-> (Node c -> d)
-> ((a -> b) -> Node c -> d)
-> FingerTree (Elem (a -> b))
-> FingerTree (Node c)
-> FingerTree (Node d)
#-}
{-# SPECIALIZE
aptyMiddle
:: (Elem c -> d)
-> (Elem c -> d)
-> ((a -> b) -> Elem c -> d)
-> FingerTree (Elem (a -> b))
-> FingerTree (Elem c)
-> FingerTree (Node d)
#-}
digitToNode :: Sized a => Digit a -> Node a
digitToNode (Two a b) = node2 a b
digitToNode (Three a b c) = node3 a b c
digitToNode _ = error "digitToNode: not representable as a node"
type Digit23 = Digit
type Digit12 = Digit
-- Squash the first argument down onto the left side of the second.
squashL :: Sized a => Digit23 a -> Digit12 (Node a) -> Digit23 (Node a)
squashL (Two a b) (One n) = Two (node2 a b) n
squashL (Two a b) (Two n1 n2) = Three (node2 a b) n1 n2
squashL (Three a b c) (One n) = Two (node3 a b c) n
squashL (Three a b c) (Two n1 n2) = Three (node3 a b c) n1 n2
squashL _ _ = error "squashL: wrong digit types"
-- Squash the second argument down onto the right side of the first
squashR :: Sized a => Digit12 (Node a) -> Digit23 a -> Digit23 (Node a)
squashR (One n) (Two a b) = Two n (node2 a b)
squashR (Two n1 n2) (Two a b) = Three n1 n2 (node2 a b)
squashR (One n) (Three a b c) = Two n (node3 a b c)
squashR (Two n1 n2) (Three a b c) = Three n1 n2 (node3 a b c)
squashR _ _ = error "squashR: wrong digit types"
-- | /O(m*n)/ (incremental) Takes an /O(m)/ function and a finger tree of size
-- /n/ and maps the function over the tree leaves. Unlike the usual 'fmap', the
-- function is applied to the "leaves" of the 'FingerTree' (i.e., given a
-- @FingerTree (Elem a)@, it applies the function to elements of type @Elem
-- a@), replacing the leaves with subtrees of at least the same height, e.g.,
-- @Node(Node(Elem y))@. The multiplier argument serves to make the annotations
-- match up properly.
mapMulFT :: Int -> (a -> b) -> FingerTree a -> FingerTree b
mapMulFT _ _ Empty = Empty
mapMulFT _mul f (Single a) = Single (f a)
mapMulFT mul f (Deep s pr m sf) = Deep (mul * s) (fmap f pr) (mapMulFT mul (mapMulNode mul f) m) (fmap f sf)
mapMulNode :: Int -> (a -> b) -> Node a -> Node b
mapMulNode mul f (Node2 s a b) = Node2 (mul * s) (f a) (f b)
mapMulNode mul f (Node3 s a b c) = Node3 (mul * s) (f a) (f b) (f c)
trimTree :: Sized a => FingerTree a -> (a, FingerTree a, a)
trimTree Empty = error "trim: empty tree"
trimTree Single{} = error "trim: singleton"
trimTree t = case splitTree 0 t of
Split _ hd r ->
case splitTree (size r - 1) r of
Split m tl _ -> (hd, m, tl)
-- | /O(log n)/ (incremental) Takes the extra flexibility out of a 'FingerTree'
-- to make it a genuine 2-3 finger tree. The result of 'rigidify' will have
-- only 'Two' and 'Three' digits at the top level and only 'One' and 'Two'
-- digits elsewhere. It gives an error if the tree has fewer than four
-- elements.
rigidify :: Sized a => FingerTree a -> FingerTree a
-- Note that 'rigidify' may call itself, but it will do so at most
-- once: each call to 'rigidify' will either fix the whole tree or fix one digit
-- and leave the other alone. The patterns below just fix up the top level of
-- the tree; 'rigidify' delegates the hard work to 'thin'.
-- The top of the tree is fine.
rigidify (Deep s pr@Two{} m sf@Three{}) = Deep s pr (thin m) sf
rigidify (Deep s pr@Three{} m sf@Three{}) = Deep s pr (thin m) sf
rigidify (Deep s pr@Two{} m sf@Two{}) = Deep s pr (thin m) sf
rigidify (Deep s pr@Three{} m sf@Two{}) = Deep s pr (thin m) sf
-- One of the Digits is a Four.
rigidify (Deep s (Four a b c d) m sf) =
rigidify $ Deep s (Two a b) (node2 c d `consTree` m) sf
rigidify (Deep s pr m (Four a b c d)) =
rigidify $ Deep s pr (m `snocTree` node2 a b) (Two c d)
-- One of the Digits is a One. If the middle is empty, we can only rigidify the
-- tree if the other Digit is a Three.
rigidify (Deep s (One a) Empty (Three b c d)) = Deep s (Two a b) Empty (Two c d)
rigidify (Deep s (One a) m sf) = rigidify $ case viewLTree m of
Just2 (Node2 _ b c) m' -> Deep s (Three a b c) m' sf
Just2 (Node3 _ b c d) m' -> Deep s (Two a b) (node2 c d `consTree` m') sf
Nothing2 -> error "rigidify: small tree"
rigidify (Deep s (Three a b c) Empty (One d)) = Deep s (Two a b) Empty (Two c d)
rigidify (Deep s pr m (One e)) = rigidify $ case viewRTree m of
Just2 m' (Node2 _ a b) -> Deep s pr m' (Three a b e)
Just2 m' (Node3 _ a b c) -> Deep s pr (m' `snocTree` node2 a b) (Two c e)
Nothing2 -> error "rigidify: small tree"
rigidify Empty = error "rigidify: empty tree"
rigidify Single{} = error "rigidify: singleton"
-- | /O(log n)/ (incremental) Rejigger a finger tree so the digits are all ones
-- and twos.
thin :: Sized a => FingerTree a -> FingerTree a
-- Note that 'thin' may call itself at most once before passing the job on to
-- 'thin12'. 'thin12' will produce a 'Deep' constructor immediately before
-- calling 'thin'.
thin Empty = Empty
thin (Single a) = Single a
thin t@(Deep s pr m sf) =
case pr of
One{} -> thin12 t
Two{} -> thin12 t
Three a b c -> thin $ Deep s (One a) (node2 b c `consTree` m) sf
Four a b c d -> thin $ Deep s (Two a b) (node2 c d `consTree` m) sf
thin12 :: Sized a => FingerTree a -> FingerTree a
thin12 (Deep s pr m sf@One{}) = Deep s pr (thin m) sf
thin12 (Deep s pr m sf@Two{}) = Deep s pr (thin m) sf
thin12 (Deep s pr m (Three a b c)) = Deep s pr (thin $ m `snocTree` node2 a b) (One c)
thin12 (Deep s pr m (Four a b c d)) = Deep s pr (thin $ m `snocTree` node2 a b) (Two c d)
thin12 _ = error "thin12 expects a Deep FingerTree."
instance MonadPlus Seq where
mzero = empty
mplus = (><)
instance Alternative Seq where
empty = empty
(<|>) = (><)
instance Eq a => Eq (Seq a) where
xs == ys = length xs == length ys && toList xs == toList ys
instance Ord a => Ord (Seq a) where
compare xs ys = compare (toList xs) (toList ys)
#if TESTING
instance Show a => Show (Seq a) where
showsPrec p (Seq x) = showsPrec p x
#else
instance Show a => Show (Seq a) where
showsPrec p xs = showParen (p > 10) $
showString "fromList " . shows (toList xs)
#endif
instance Read a => Read (Seq a) where
#ifdef __GLASGOW_HASKELL__
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
xs <- readPrec
return (fromList xs)
readListPrec = readListPrecDefault
#else
readsPrec p = readParen (p > 10) $ \ r -> do
("fromList",s) <- lex r
(xs,t) <- reads s
return (fromList xs,t)
#endif
instance Monoid (Seq a) where
mempty = empty
mappend = (><)
INSTANCE_TYPEABLE1(Seq,seqTc,"Seq")
#if __GLASGOW_HASKELL__
instance Data a => Data (Seq a) where
gfoldl f z s = case viewl s of
EmptyL -> z empty
x :< xs -> z (<|) `f` x `f` xs
gunfold k z c = case constrIndex c of
1 -> z empty
2 -> k (k (z (<|)))
_ -> error "gunfold"
toConstr xs
| null xs = emptyConstr
| otherwise = consConstr
dataTypeOf _ = seqDataType
dataCast1 f = gcast1 f
emptyConstr, consConstr :: Constr
emptyConstr = mkConstr seqDataType "empty" [] Prefix
consConstr = mkConstr seqDataType "<|" [] Infix
seqDataType :: DataType
seqDataType = mkDataType "Data.Sequence.Seq" [emptyConstr, consConstr]
#endif
-- Finger trees
data FingerTree a
= Empty
| Single a
| Deep {-# UNPACK #-} !Int !(Digit a) (FingerTree (Node a)) !(Digit a)
#if TESTING
deriving Show
#endif
instance Sized a => Sized (FingerTree a) where
{-# SPECIALIZE instance Sized (FingerTree (Elem a)) #-}
{-# SPECIALIZE instance Sized (FingerTree (Node a)) #-}
size Empty = 0
size (Single x) = size x
size (Deep v _ _ _) = v
instance Foldable FingerTree where
foldMap _ Empty = mempty
foldMap f (Single x) = f x
foldMap f (Deep _ pr m sf) =
foldMap f pr `mappend` (foldMap (foldMap f) m `mappend` foldMap f sf)
foldr _ z Empty = z
foldr f z (Single x) = x `f` z
foldr f z (Deep _ pr m sf) =
foldr f (foldr (flip (foldr f)) (foldr f z sf) m) pr
foldl _ z Empty = z
foldl f z (Single x) = z `f` x
foldl f z (Deep _ pr m sf) =
foldl f (foldl (foldl f) (foldl f z pr) m) sf
foldr1 _ Empty = error "foldr1: empty sequence"
foldr1 _ (Single x) = x
foldr1 f (Deep _ pr m sf) =
foldr f (foldr (flip (foldr f)) (foldr1 f sf) m) pr
foldl1 _ Empty = error "foldl1: empty sequence"
foldl1 _ (Single x) = x
foldl1 f (Deep _ pr m sf) =
foldl f (foldl (foldl f) (foldl1 f pr) m) sf
instance Functor FingerTree where
fmap _ Empty = Empty
fmap f (Single x) = Single (f x)
fmap f (Deep v pr m sf) =
Deep v (fmap f pr) (fmap (fmap f) m) (fmap f sf)
instance Traversable FingerTree where
traverse _ Empty = pure Empty
traverse f (Single x) = Single <$> f x
traverse f (Deep v pr m sf) =
Deep v <$> traverse f pr <*> traverse (traverse f) m <*>
traverse f sf
instance NFData a => NFData (FingerTree a) where
rnf (Empty) = ()
rnf (Single x) = rnf x
rnf (Deep _ pr m sf) = rnf pr `seq` rnf sf `seq` rnf m
{-# INLINE deep #-}
deep :: Sized a => Digit a -> FingerTree (Node a) -> Digit a -> FingerTree a
deep pr m sf = Deep (size pr + size m + size sf) pr m sf
{-# INLINE pullL #-}
pullL :: Sized a => Int -> FingerTree (Node a) -> Digit a -> FingerTree a
pullL s m sf = case viewLTree m of
Nothing2 -> digitToTree' s sf
Just2 pr m' -> Deep s (nodeToDigit pr) m' sf
{-# INLINE pullR #-}
pullR :: Sized a => Int -> Digit a -> FingerTree (Node a) -> FingerTree a
pullR s pr m = case viewRTree m of
Nothing2 -> digitToTree' s pr
Just2 m' sf -> Deep s pr m' (nodeToDigit sf)
{-# SPECIALIZE deepL :: Maybe (Digit (Elem a)) -> FingerTree (Node (Elem a)) -> Digit (Elem a) -> FingerTree (Elem a) #-}
{-# SPECIALIZE deepL :: Maybe (Digit (Node a)) -> FingerTree (Node (Node a)) -> Digit (Node a) -> FingerTree (Node a) #-}
deepL :: Sized a => Maybe (Digit a) -> FingerTree (Node a) -> Digit a -> FingerTree a
deepL Nothing m sf = pullL (size m + size sf) m sf
deepL (Just pr) m sf = deep pr m sf
{-# SPECIALIZE deepR :: Digit (Elem a) -> FingerTree (Node (Elem a)) -> Maybe (Digit (Elem a)) -> FingerTree (Elem a) #-}
{-# SPECIALIZE deepR :: Digit (Node a) -> FingerTree (Node (Node a)) -> Maybe (Digit (Node a)) -> FingerTree (Node a) #-}
deepR :: Sized a => Digit a -> FingerTree (Node a) -> Maybe (Digit a) -> FingerTree a
deepR pr m Nothing = pullR (size m + size pr) pr m
deepR pr m (Just sf) = deep pr m sf
-- Digits
data Digit a
= One a
| Two a a
| Three a a a
| Four a a a a
#if TESTING
deriving Show
#endif
instance Foldable Digit where
foldMap f (One a) = f a
foldMap f (Two a b) = f a `mappend` f b
foldMap f (Three a b c) = f a `mappend` (f b `mappend` f c)
foldMap f (Four a b c d) = f a `mappend` (f b `mappend` (f c `mappend` f d))
foldr f z (One a) = a `f` z
foldr f z (Two a b) = a `f` (b `f` z)
foldr f z (Three a b c) = a `f` (b `f` (c `f` z))
foldr f z (Four a b c d) = a `f` (b `f` (c `f` (d `f` z)))
foldl f z (One a) = z `f` a
foldl f z (Two a b) = (z `f` a) `f` b
foldl f z (Three a b c) = ((z `f` a) `f` b) `f` c
foldl f z (Four a b c d) = (((z `f` a) `f` b) `f` c) `f` d
foldr1 _ (One a) = a
foldr1 f (Two a b) = a `f` b
foldr1 f (Three a b c) = a `f` (b `f` c)
foldr1 f (Four a b c d) = a `f` (b `f` (c `f` d))
foldl1 _ (One a) = a
foldl1 f (Two a b) = a `f` b
foldl1 f (Three a b c) = (a `f` b) `f` c
foldl1 f (Four a b c d) = ((a `f` b) `f` c) `f` d
instance Functor Digit where
{-# INLINE fmap #-}
fmap f (One a) = One (f a)
fmap f (Two a b) = Two (f a) (f b)
fmap f (Three a b c) = Three (f a) (f b) (f c)
fmap f (Four a b c d) = Four (f a) (f b) (f c) (f d)
instance Traversable Digit where
{-# INLINE traverse #-}
traverse f (One a) = One <$> f a
traverse f (Two a b) = Two <$> f a <*> f b
traverse f (Three a b c) = Three <$> f a <*> f b <*> f c
traverse f (Four a b c d) = Four <$> f a <*> f b <*> f c <*> f d
instance NFData a => NFData (Digit a) where
rnf (One a) = rnf a
rnf (Two a b) = rnf a `seq` rnf b
rnf (Three a b c) = rnf a `seq` rnf b `seq` rnf c
rnf (Four a b c d) = rnf a `seq` rnf b `seq` rnf c `seq` rnf d
instance Sized a => Sized (Digit a) where
{-# INLINE size #-}
size = foldl1 (+) . fmap size
{-# SPECIALIZE digitToTree :: Digit (Elem a) -> FingerTree (Elem a) #-}
{-# SPECIALIZE digitToTree :: Digit (Node a) -> FingerTree (Node a) #-}
digitToTree :: Sized a => Digit a -> FingerTree a
digitToTree (One a) = Single a
digitToTree (Two a b) = deep (One a) Empty (One b)
digitToTree (Three a b c) = deep (Two a b) Empty (One c)
digitToTree (Four a b c d) = deep (Two a b) Empty (Two c d)
-- | Given the size of a digit and the digit itself, efficiently converts
-- it to a FingerTree.
digitToTree' :: Int -> Digit a -> FingerTree a
digitToTree' n (Four a b c d) = Deep n (Two a b) Empty (Two c d)
digitToTree' n (Three a b c) = Deep n (Two a b) Empty (One c)
digitToTree' n (Two a b) = Deep n (One a) Empty (One b)
digitToTree' n (One a) = n `seq` Single a
-- Nodes
data Node a
= Node2 {-# UNPACK #-} !Int a a
| Node3 {-# UNPACK #-} !Int a a a
#if TESTING
deriving Show
#endif
instance Foldable Node where
foldMap f (Node2 _ a b) = f a `mappend` f b
foldMap f (Node3 _ a b c) = f a `mappend` (f b `mappend` f c)
foldr f z (Node2 _ a b) = a `f` (b `f` z)
foldr f z (Node3 _ a b c) = a `f` (b `f` (c `f` z))
foldl f z (Node2 _ a b) = (z `f` a) `f` b
foldl f z (Node3 _ a b c) = ((z `f` a) `f` b) `f` c
instance Functor Node where
{-# INLINE fmap #-}
fmap f (Node2 v a b) = Node2 v (f a) (f b)
fmap f (Node3 v a b c) = Node3 v (f a) (f b) (f c)
instance Traversable Node where
{-# INLINE traverse #-}
traverse f (Node2 v a b) = Node2 v <$> f a <*> f b
traverse f (Node3 v a b c) = Node3 v <$> f a <*> f b <*> f c
instance NFData a => NFData (Node a) where
rnf (Node2 _ a b) = rnf a `seq` rnf b
rnf (Node3 _ a b c) = rnf a `seq` rnf b `seq` rnf c
instance Sized (Node a) where
size (Node2 v _ _) = v
size (Node3 v _ _ _) = v
{-# INLINE node2 #-}
node2 :: Sized a => a -> a -> Node a
node2 a b = Node2 (size a + size b) a b
{-# INLINE node3 #-}
node3 :: Sized a => a -> a -> a -> Node a
node3 a b c = Node3 (size a + size b + size c) a b c
nodeToDigit :: Node a -> Digit a
nodeToDigit (Node2 _ a b) = Two a b
nodeToDigit (Node3 _ a b c) = Three a b c
-- Elements
newtype Elem a = Elem { getElem :: a }
#if TESTING
deriving Show
#endif
instance Sized (Elem a) where
size _ = 1
instance Functor Elem where
#if __GLASGOW_HASKELL__ >= 708
-- This cuts the time for <*> by around a fifth.
fmap = coerce
#else
fmap f (Elem x) = Elem (f x)
#endif
instance Foldable Elem where
foldMap f (Elem x) = f x
foldr f z (Elem x) = f x z
foldl f z (Elem x) = f z x
instance Traversable Elem where
traverse f (Elem x) = Elem <$> f x
instance NFData a => NFData (Elem a) where
rnf (Elem x) = rnf x
-------------------------------------------------------
-- Applicative construction
-------------------------------------------------------
#if !MIN_VERSION_base(4,8,0)
newtype Identity a = Identity {runIdentity :: a}
instance Functor Identity where
fmap f (Identity x) = Identity (f x)
instance Applicative Identity where
pure = Identity
Identity f <*> Identity x = Identity (f x)
#endif
-- | This is essentially a clone of Control.Monad.State.Strict.
newtype State s a = State {runState :: s -> (s, a)}
instance Functor (State s) where
fmap = liftA
instance Monad (State s) where
{-# INLINE return #-}
{-# INLINE (>>=) #-}
return x = State $ \ s -> (s, x)
m >>= k = State $ \ s -> case runState m s of
(s', x) -> runState (k x) s'
instance Applicative (State s) where
pure = return
(<*>) = ap
execState :: State s a -> s -> a
execState m x = snd (runState m x)
-- | 'applicativeTree' takes an Applicative-wrapped construction of a
-- piece of a FingerTree, assumed to always have the same size (which
-- is put in the second argument), and replicates it as many times as
-- specified. This is a generalization of 'replicateA', which itself
-- is a generalization of many Data.Sequence methods.
{-# SPECIALIZE applicativeTree :: Int -> Int -> State s a -> State s (FingerTree a) #-}
{-# SPECIALIZE applicativeTree :: Int -> Int -> Identity a -> Identity (FingerTree a) #-}
-- Special note: the Identity specialization automatically does node sharing,
-- reducing memory usage of the resulting tree to /O(log n)/.
applicativeTree :: Applicative f => Int -> Int -> f a -> f (FingerTree a)
applicativeTree n mSize m = mSize `seq` case n of
0 -> pure Empty
1 -> fmap Single m
2 -> deepA one emptyTree one
3 -> deepA two emptyTree one
4 -> deepA two emptyTree two
5 -> deepA three emptyTree two
6 -> deepA three emptyTree three
7 -> deepA four emptyTree three
8 -> deepA four emptyTree four
_ -> case n `quotRem` 3 of
(q,0) -> deepA three (applicativeTree (q - 2) mSize' n3) three
(q,1) -> deepA four (applicativeTree (q - 2) mSize' n3) three
(q,_) -> deepA four (applicativeTree (q - 2) mSize' n3) four
where
one = fmap One m
two = liftA2 Two m m
three = liftA3 Three m m m
four = liftA3 Four m m m <*> m
deepA = liftA3 (Deep (n * mSize))
mSize' = 3 * mSize
n3 = liftA3 (Node3 mSize') m m m
emptyTree = pure Empty
------------------------------------------------------------------------
-- Construction
------------------------------------------------------------------------
-- | /O(1)/. The empty sequence.
empty :: Seq a
empty = Seq Empty
-- | /O(1)/. A singleton sequence.
singleton :: a -> Seq a
singleton x = Seq (Single (Elem x))
-- | /O(log n)/. @replicate n x@ is a sequence consisting of @n@ copies of @x@.
replicate :: Int -> a -> Seq a
replicate n x
| n >= 0 = runIdentity (replicateA n (Identity x))
| otherwise = error "replicate takes a nonnegative integer argument"
-- | 'replicateA' is an 'Applicative' version of 'replicate', and makes
-- /O(log n)/ calls to '<*>' and 'pure'.
--
-- > replicateA n x = sequenceA (replicate n x)
replicateA :: Applicative f => Int -> f a -> f (Seq a)
replicateA n x
| n >= 0 = Seq <$> applicativeTree n 1 (Elem <$> x)
| otherwise = error "replicateA takes a nonnegative integer argument"
-- | 'replicateM' is a sequence counterpart of 'Control.Monad.replicateM'.
--
-- > replicateM n x = sequence (replicate n x)
replicateM :: Monad m => Int -> m a -> m (Seq a)
replicateM n x
| n >= 0 = unwrapMonad (replicateA n (WrapMonad x))
| otherwise = error "replicateM takes a nonnegative integer argument"
-- | @'replicateSeq' n xs@ concatenates @n@ copies of @xs@.
replicateSeq :: Int -> Seq a -> Seq a
replicateSeq n s
| n < 0 = error "replicateSeq takes a nonnegative integer argument"
| n == 0 = empty
| otherwise = go n s
where
-- Invariant: k >= 1
go 1 xs = xs
go k xs | even k = kxs
| otherwise = xs >< kxs
where kxs = go (k `quot` 2) $! (xs >< xs)
-- | /O(1)/. Add an element to the left end of a sequence.
-- Mnemonic: a triangle with the single element at the pointy end.
(<|) :: a -> Seq a -> Seq a
x <| Seq xs = Seq (Elem x `consTree` xs)
{-# SPECIALIZE consTree :: Elem a -> FingerTree (Elem a) -> FingerTree (Elem a) #-}
{-# SPECIALIZE consTree :: Node a -> FingerTree (Node a) -> FingerTree (Node a) #-}
consTree :: Sized a => a -> FingerTree a -> FingerTree a
consTree a Empty = Single a
consTree a (Single b) = deep (One a) Empty (One b)
consTree a (Deep s (Four b c d e) m sf) = m `seq`
Deep (size a + s) (Two a b) (node3 c d e `consTree` m) sf
consTree a (Deep s (Three b c d) m sf) =
Deep (size a + s) (Four a b c d) m sf
consTree a (Deep s (Two b c) m sf) =
Deep (size a + s) (Three a b c) m sf
consTree a (Deep s (One b) m sf) =
Deep (size a + s) (Two a b) m sf
-- | /O(1)/. Add an element to the right end of a sequence.
-- Mnemonic: a triangle with the single element at the pointy end.
(|>) :: Seq a -> a -> Seq a
Seq xs |> x = Seq (xs `snocTree` Elem x)
{-# SPECIALIZE snocTree :: FingerTree (Elem a) -> Elem a -> FingerTree (Elem a) #-}
{-# SPECIALIZE snocTree :: FingerTree (Node a) -> Node a -> FingerTree (Node a) #-}
snocTree :: Sized a => FingerTree a -> a -> FingerTree a
snocTree Empty a = Single a
snocTree (Single a) b = deep (One a) Empty (One b)
snocTree (Deep s pr m (Four a b c d)) e = m `seq`
Deep (s + size e) pr (m `snocTree` node3 a b c) (Two d e)
snocTree (Deep s pr m (Three a b c)) d =
Deep (s + size d) pr m (Four a b c d)
snocTree (Deep s pr m (Two a b)) c =
Deep (s + size c) pr m (Three a b c)
snocTree (Deep s pr m (One a)) b =
Deep (s + size b) pr m (Two a b)
-- | /O(log(min(n1,n2)))/. Concatenate two sequences.
(><) :: Seq a -> Seq a -> Seq a
Seq xs >< Seq ys = Seq (appendTree0 xs ys)
-- The appendTree/addDigits gunk below is machine generated
{-# SPECIALIZE appendTree0 :: FingerTree (Elem a) -> FingerTree (Elem a) -> FingerTree (Elem a) #-}
{-# SPECIALIZE appendTree0 :: FingerTree (Node a) -> FingerTree (Node a) -> FingerTree (Node a) #-}
appendTree0 :: Sized a => FingerTree a -> FingerTree a -> FingerTree a
appendTree0 Empty xs =
xs
appendTree0 xs Empty =
xs
appendTree0 (Single x) xs =
x `consTree` xs
appendTree0 xs (Single x) =
xs `snocTree` x
appendTree0 (Deep s1 pr1 m1 sf1) (Deep s2 pr2 m2 sf2) =
Deep (s1 + s2) pr1 (addDigits0 m1 sf1 pr2 m2) sf2
{-# SPECIALIZE addDigits0 :: FingerTree (Node (Elem a)) -> Digit (Elem a) -> Digit (Elem a) -> FingerTree (Node (Elem a)) -> FingerTree (Node (Elem a)) #-}
{-# SPECIALIZE addDigits0 :: FingerTree (Node (Node a)) -> Digit (Node a) -> Digit (Node a) -> FingerTree (Node (Node a)) -> FingerTree (Node (Node a)) #-}
addDigits0 :: Sized a => FingerTree (Node a) -> Digit a -> Digit a -> FingerTree (Node a) -> FingerTree (Node a)
addDigits0 m1 (One a) (One b) m2 =
appendTree1 m1 (node2 a b) m2
addDigits0 m1 (One a) (Two b c) m2 =
appendTree1 m1 (node3 a b c) m2
addDigits0 m1 (One a) (Three b c d) m2 =
appendTree2 m1 (node2 a b) (node2 c d) m2
addDigits0 m1 (One a) (Four b c d e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits0 m1 (Two a b) (One c) m2 =
appendTree1 m1 (node3 a b c) m2
addDigits0 m1 (Two a b) (Two c d) m2 =
appendTree2 m1 (node2 a b) (node2 c d) m2
addDigits0 m1 (Two a b) (Three c d e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits0 m1 (Two a b) (Four c d e f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits0 m1 (Three a b c) (One d) m2 =
appendTree2 m1 (node2 a b) (node2 c d) m2
addDigits0 m1 (Three a b c) (Two d e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits0 m1 (Three a b c) (Three d e f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits0 m1 (Three a b c) (Four d e f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits0 m1 (Four a b c d) (One e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits0 m1 (Four a b c d) (Two e f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits0 m1 (Four a b c d) (Three e f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits0 m1 (Four a b c d) (Four e f g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
appendTree1 :: FingerTree (Node a) -> Node a -> FingerTree (Node a) -> FingerTree (Node a)
appendTree1 Empty a xs =
a `consTree` xs
appendTree1 xs a Empty =
xs `snocTree` a
appendTree1 (Single x) a xs =
x `consTree` a `consTree` xs
appendTree1 xs a (Single x) =
xs `snocTree` a `snocTree` x
appendTree1 (Deep s1 pr1 m1 sf1) a (Deep s2 pr2 m2 sf2) =
Deep (s1 + size a + s2) pr1 (addDigits1 m1 sf1 a pr2 m2) sf2
addDigits1 :: FingerTree (Node (Node a)) -> Digit (Node a) -> Node a -> Digit (Node a) -> FingerTree (Node (Node a)) -> FingerTree (Node (Node a))
addDigits1 m1 (One a) b (One c) m2 =
appendTree1 m1 (node3 a b c) m2
addDigits1 m1 (One a) b (Two c d) m2 =
appendTree2 m1 (node2 a b) (node2 c d) m2
addDigits1 m1 (One a) b (Three c d e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits1 m1 (One a) b (Four c d e f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits1 m1 (Two a b) c (One d) m2 =
appendTree2 m1 (node2 a b) (node2 c d) m2
addDigits1 m1 (Two a b) c (Two d e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits1 m1 (Two a b) c (Three d e f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits1 m1 (Two a b) c (Four d e f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits1 m1 (Three a b c) d (One e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits1 m1 (Three a b c) d (Two e f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits1 m1 (Three a b c) d (Three e f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits1 m1 (Three a b c) d (Four e f g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits1 m1 (Four a b c d) e (One f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits1 m1 (Four a b c d) e (Two f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits1 m1 (Four a b c d) e (Three f g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits1 m1 (Four a b c d) e (Four f g h i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
appendTree2 :: FingerTree (Node a) -> Node a -> Node a -> FingerTree (Node a) -> FingerTree (Node a)
appendTree2 Empty a b xs =
a `consTree` b `consTree` xs
appendTree2 xs a b Empty =
xs `snocTree` a `snocTree` b
appendTree2 (Single x) a b xs =
x `consTree` a `consTree` b `consTree` xs
appendTree2 xs a b (Single x) =
xs `snocTree` a `snocTree` b `snocTree` x
appendTree2 (Deep s1 pr1 m1 sf1) a b (Deep s2 pr2 m2 sf2) =
Deep (s1 + size a + size b + s2) pr1 (addDigits2 m1 sf1 a b pr2 m2) sf2
addDigits2 :: FingerTree (Node (Node a)) -> Digit (Node a) -> Node a -> Node a -> Digit (Node a) -> FingerTree (Node (Node a)) -> FingerTree (Node (Node a))
addDigits2 m1 (One a) b c (One d) m2 =
appendTree2 m1 (node2 a b) (node2 c d) m2
addDigits2 m1 (One a) b c (Two d e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits2 m1 (One a) b c (Three d e f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits2 m1 (One a) b c (Four d e f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits2 m1 (Two a b) c d (One e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits2 m1 (Two a b) c d (Two e f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits2 m1 (Two a b) c d (Three e f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits2 m1 (Two a b) c d (Four e f g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits2 m1 (Three a b c) d e (One f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits2 m1 (Three a b c) d e (Two f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits2 m1 (Three a b c) d e (Three f g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits2 m1 (Three a b c) d e (Four f g h i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
addDigits2 m1 (Four a b c d) e f (One g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits2 m1 (Four a b c d) e f (Two g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits2 m1 (Four a b c d) e f (Three g h i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
addDigits2 m1 (Four a b c d) e f (Four g h i j) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2
appendTree3 :: FingerTree (Node a) -> Node a -> Node a -> Node a -> FingerTree (Node a) -> FingerTree (Node a)
appendTree3 Empty a b c xs =
a `consTree` b `consTree` c `consTree` xs
appendTree3 xs a b c Empty =
xs `snocTree` a `snocTree` b `snocTree` c
appendTree3 (Single x) a b c xs =
x `consTree` a `consTree` b `consTree` c `consTree` xs
appendTree3 xs a b c (Single x) =
xs `snocTree` a `snocTree` b `snocTree` c `snocTree` x
appendTree3 (Deep s1 pr1 m1 sf1) a b c (Deep s2 pr2 m2 sf2) =
Deep (s1 + size a + size b + size c + s2) pr1 (addDigits3 m1 sf1 a b c pr2 m2) sf2
addDigits3 :: FingerTree (Node (Node a)) -> Digit (Node a) -> Node a -> Node a -> Node a -> Digit (Node a) -> FingerTree (Node (Node a)) -> FingerTree (Node (Node a))
addDigits3 m1 (One a) b c d (One e) m2 =
appendTree2 m1 (node3 a b c) (node2 d e) m2
addDigits3 m1 (One a) b c d (Two e f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits3 m1 (One a) b c d (Three e f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits3 m1 (One a) b c d (Four e f g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits3 m1 (Two a b) c d e (One f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits3 m1 (Two a b) c d e (Two f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits3 m1 (Two a b) c d e (Three f g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits3 m1 (Two a b) c d e (Four f g h i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
addDigits3 m1 (Three a b c) d e f (One g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits3 m1 (Three a b c) d e f (Two g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits3 m1 (Three a b c) d e f (Three g h i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
addDigits3 m1 (Three a b c) d e f (Four g h i j) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2
addDigits3 m1 (Four a b c d) e f g (One h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits3 m1 (Four a b c d) e f g (Two h i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
addDigits3 m1 (Four a b c d) e f g (Three h i j) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2
addDigits3 m1 (Four a b c d) e f g (Four h i j k) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node3 g h i) (node2 j k) m2
appendTree4 :: FingerTree (Node a) -> Node a -> Node a -> Node a -> Node a -> FingerTree (Node a) -> FingerTree (Node a)
appendTree4 Empty a b c d xs =
a `consTree` b `consTree` c `consTree` d `consTree` xs
appendTree4 xs a b c d Empty =
xs `snocTree` a `snocTree` b `snocTree` c `snocTree` d
appendTree4 (Single x) a b c d xs =
x `consTree` a `consTree` b `consTree` c `consTree` d `consTree` xs
appendTree4 xs a b c d (Single x) =
xs `snocTree` a `snocTree` b `snocTree` c `snocTree` d `snocTree` x
appendTree4 (Deep s1 pr1 m1 sf1) a b c d (Deep s2 pr2 m2 sf2) =
Deep (s1 + size a + size b + size c + size d + s2) pr1 (addDigits4 m1 sf1 a b c d pr2 m2) sf2
addDigits4 :: FingerTree (Node (Node a)) -> Digit (Node a) -> Node a -> Node a -> Node a -> Node a -> Digit (Node a) -> FingerTree (Node (Node a)) -> FingerTree (Node (Node a))
addDigits4 m1 (One a) b c d e (One f) m2 =
appendTree2 m1 (node3 a b c) (node3 d e f) m2
addDigits4 m1 (One a) b c d e (Two f g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits4 m1 (One a) b c d e (Three f g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits4 m1 (One a) b c d e (Four f g h i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
addDigits4 m1 (Two a b) c d e f (One g) m2 =
appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2
addDigits4 m1 (Two a b) c d e f (Two g h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits4 m1 (Two a b) c d e f (Three g h i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
addDigits4 m1 (Two a b) c d e f (Four g h i j) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2
addDigits4 m1 (Three a b c) d e f g (One h) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2
addDigits4 m1 (Three a b c) d e f g (Two h i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
addDigits4 m1 (Three a b c) d e f g (Three h i j) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2
addDigits4 m1 (Three a b c) d e f g (Four h i j k) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node3 g h i) (node2 j k) m2
addDigits4 m1 (Four a b c d) e f g h (One i) m2 =
appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2
addDigits4 m1 (Four a b c d) e f g h (Two i j) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2
addDigits4 m1 (Four a b c d) e f g h (Three i j k) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node3 g h i) (node2 j k) m2
addDigits4 m1 (Four a b c d) e f g h (Four i j k l) m2 =
appendTree4 m1 (node3 a b c) (node3 d e f) (node3 g h i) (node3 j k l) m2
-- | Builds a sequence from a seed value. Takes time linear in the
-- number of generated elements. /WARNING:/ If the number of generated
-- elements is infinite, this method will not terminate.
unfoldr :: (b -> Maybe (a, b)) -> b -> Seq a
unfoldr f = unfoldr' empty
-- uses tail recursion rather than, for instance, the List implementation.
where unfoldr' as b = maybe as (\ (a, b') -> unfoldr' (as |> a) b') (f b)
-- | @'unfoldl' f x@ is equivalent to @'reverse' ('unfoldr' ('fmap' swap . f) x)@.
unfoldl :: (b -> Maybe (b, a)) -> b -> Seq a
unfoldl f = unfoldl' empty
where unfoldl' as b = maybe as (\ (b', a) -> unfoldl' (a <| as) b') (f b)
-- | /O(n)/. Constructs a sequence by repeated application of a function
-- to a seed value.
--
-- > iterateN n f x = fromList (Prelude.take n (Prelude.iterate f x))
iterateN :: Int -> (a -> a) -> a -> Seq a
iterateN n f x
| n >= 0 = replicateA n (State (\ y -> (f y, y))) `execState` x
| otherwise = error "iterateN takes a nonnegative integer argument"
------------------------------------------------------------------------
-- Deconstruction
------------------------------------------------------------------------
-- | /O(1)/. Is this the empty sequence?
null :: Seq a -> Bool
null (Seq Empty) = True
null _ = False
-- | /O(1)/. The number of elements in the sequence.
length :: Seq a -> Int
length (Seq xs) = size xs
-- Views
data Maybe2 a b = Nothing2 | Just2 a b
-- | View of the left end of a sequence.
data ViewL a
= EmptyL -- ^ empty sequence
| a :< Seq a -- ^ leftmost element and the rest of the sequence
#if __GLASGOW_HASKELL__
deriving (Eq, Ord, Show, Read, Data)
#else
deriving (Eq, Ord, Show, Read)
#endif
INSTANCE_TYPEABLE1(ViewL,viewLTc,"ViewL")
instance Functor ViewL where
{-# INLINE fmap #-}
fmap _ EmptyL = EmptyL
fmap f (x :< xs) = f x :< fmap f xs
instance Foldable ViewL where
foldr _ z EmptyL = z
foldr f z (x :< xs) = f x (foldr f z xs)
foldl _ z EmptyL = z
foldl f z (x :< xs) = foldl f (f z x) xs
foldl1 _ EmptyL = error "foldl1: empty view"
foldl1 f (x :< xs) = foldl f x xs
instance Traversable ViewL where
traverse _ EmptyL = pure EmptyL
traverse f (x :< xs) = (:<) <$> f x <*> traverse f xs
-- | /O(1)/. Analyse the left end of a sequence.
viewl :: Seq a -> ViewL a
viewl (Seq xs) = case viewLTree xs of
Nothing2 -> EmptyL
Just2 (Elem x) xs' -> x :< Seq xs'
{-# SPECIALIZE viewLTree :: FingerTree (Elem a) -> Maybe2 (Elem a) (FingerTree (Elem a)) #-}
{-# SPECIALIZE viewLTree :: FingerTree (Node a) -> Maybe2 (Node a) (FingerTree (Node a)) #-}
viewLTree :: Sized a => FingerTree a -> Maybe2 a (FingerTree a)
viewLTree Empty = Nothing2
viewLTree (Single a) = Just2 a Empty
viewLTree (Deep s (One a) m sf) = Just2 a (pullL (s - size a) m sf)
viewLTree (Deep s (Two a b) m sf) =
Just2 a (Deep (s - size a) (One b) m sf)
viewLTree (Deep s (Three a b c) m sf) =
Just2 a (Deep (s - size a) (Two b c) m sf)
viewLTree (Deep s (Four a b c d) m sf) =
Just2 a (Deep (s - size a) (Three b c d) m sf)
-- | View of the right end of a sequence.
data ViewR a
= EmptyR -- ^ empty sequence
| Seq a :> a -- ^ the sequence minus the rightmost element,
-- and the rightmost element
#if __GLASGOW_HASKELL__
deriving (Eq, Ord, Show, Read, Data)
#else
deriving (Eq, Ord, Show, Read)
#endif
INSTANCE_TYPEABLE1(ViewR,viewRTc,"ViewR")
instance Functor ViewR where
{-# INLINE fmap #-}
fmap _ EmptyR = EmptyR
fmap f (xs :> x) = fmap f xs :> f x
instance Foldable ViewR where
foldMap _ EmptyR = mempty
foldMap f (xs :> x) = foldMap f xs `mappend` f x
foldr _ z EmptyR = z
foldr f z (xs :> x) = foldr f (f x z) xs
foldl _ z EmptyR = z
foldl f z (xs :> x) = foldl f z xs `f` x
foldr1 _ EmptyR = error "foldr1: empty view"
foldr1 f (xs :> x) = foldr f x xs
#if MIN_VERSION_base(4,8,0)
-- The default definitions are sensible for ViewL, but not so much for
-- ViewR.
null EmptyR = True
null (_ :> _) = False
length = foldr' (\_ k -> k+1) 0
#endif
instance Traversable ViewR where
traverse _ EmptyR = pure EmptyR
traverse f (xs :> x) = (:>) <$> traverse f xs <*> f x
-- | /O(1)/. Analyse the right end of a sequence.
viewr :: Seq a -> ViewR a
viewr (Seq xs) = case viewRTree xs of
Nothing2 -> EmptyR
Just2 xs' (Elem x) -> Seq xs' :> x
{-# SPECIALIZE viewRTree :: FingerTree (Elem a) -> Maybe2 (FingerTree (Elem a)) (Elem a) #-}
{-# SPECIALIZE viewRTree :: FingerTree (Node a) -> Maybe2 (FingerTree (Node a)) (Node a) #-}
viewRTree :: Sized a => FingerTree a -> Maybe2 (FingerTree a) a
viewRTree Empty = Nothing2
viewRTree (Single z) = Just2 Empty z
viewRTree (Deep s pr m (One z)) = Just2 (pullR (s - size z) pr m) z
viewRTree (Deep s pr m (Two y z)) =
Just2 (Deep (s - size z) pr m (One y)) z
viewRTree (Deep s pr m (Three x y z)) =
Just2 (Deep (s - size z) pr m (Two x y)) z
viewRTree (Deep s pr m (Four w x y z)) =
Just2 (Deep (s - size z) pr m (Three w x y)) z
------------------------------------------------------------------------
-- Scans
--
-- These are not particularly complex applications of the Traversable
-- functor, though making the correspondence with Data.List exact
-- requires the use of (<|) and (|>).
--
-- Note that save for the single (<|) or (|>), we maintain the original
-- structure of the Seq, not having to do any restructuring of our own.
--
-- wasserman.louis@gmail.com, 5/23/09
------------------------------------------------------------------------
-- | 'scanl' is similar to 'foldl', but returns a sequence of reduced
-- values from the left:
--
-- > scanl f z (fromList [x1, x2, ...]) = fromList [z, z `f` x1, (z `f` x1) `f` x2, ...]
scanl :: (a -> b -> a) -> a -> Seq b -> Seq a
scanl f z0 xs = z0 <| snd (mapAccumL (\ x z -> let x' = f x z in (x', x')) z0 xs)
-- | 'scanl1' is a variant of 'scanl' that has no starting value argument:
--
-- > scanl1 f (fromList [x1, x2, ...]) = fromList [x1, x1 `f` x2, ...]
scanl1 :: (a -> a -> a) -> Seq a -> Seq a
scanl1 f xs = case viewl xs of
EmptyL -> error "scanl1 takes a nonempty sequence as an argument"
x :< xs' -> scanl f x xs'
-- | 'scanr' is the right-to-left dual of 'scanl'.
scanr :: (a -> b -> b) -> b -> Seq a -> Seq b
scanr f z0 xs = snd (mapAccumR (\ z x -> let z' = f x z in (z', z')) z0 xs) |> z0
-- | 'scanr1' is a variant of 'scanr' that has no starting value argument.
scanr1 :: (a -> a -> a) -> Seq a -> Seq a
scanr1 f xs = case viewr xs of
EmptyR -> error "scanr1 takes a nonempty sequence as an argument"
xs' :> x -> scanr f x xs'
-- Indexing
-- | /O(log(min(i,n-i)))/. The element at the specified position,
-- counting from 0. The argument should thus be a non-negative
-- integer less than the size of the sequence.
-- If the position is out of range, 'index' fails with an error.
index :: Seq a -> Int -> a
index (Seq xs) i
| 0 <= i && i < size xs = case lookupTree i xs of
Place _ (Elem x) -> x
| otherwise = error "index out of bounds"
data Place a = Place {-# UNPACK #-} !Int a
#if TESTING
deriving Show
#endif
{-# SPECIALIZE lookupTree :: Int -> FingerTree (Elem a) -> Place (Elem a) #-}
{-# SPECIALIZE lookupTree :: Int -> FingerTree (Node a) -> Place (Node a) #-}
lookupTree :: Sized a => Int -> FingerTree a -> Place a
lookupTree _ Empty = error "lookupTree of empty tree"
lookupTree i (Single x) = Place i x
lookupTree i (Deep totalSize pr m sf)
| i < spr = lookupDigit i pr
| i < spm = case lookupTree (i - spr) m of
Place i' xs -> lookupNode i' xs
| otherwise = lookupDigit (i - spm) sf
where
spr = size pr
spm = totalSize - size sf
{-# SPECIALIZE lookupNode :: Int -> Node (Elem a) -> Place (Elem a) #-}
{-# SPECIALIZE lookupNode :: Int -> Node (Node a) -> Place (Node a) #-}
lookupNode :: Sized a => Int -> Node a -> Place a
lookupNode i (Node2 _ a b)
| i < sa = Place i a
| otherwise = Place (i - sa) b
where
sa = size a
lookupNode i (Node3 _ a b c)
| i < sa = Place i a
| i < sab = Place (i - sa) b
| otherwise = Place (i - sab) c
where
sa = size a
sab = sa + size b
{-# SPECIALIZE lookupDigit :: Int -> Digit (Elem a) -> Place (Elem a) #-}
{-# SPECIALIZE lookupDigit :: Int -> Digit (Node a) -> Place (Node a) #-}
lookupDigit :: Sized a => Int -> Digit a -> Place a
lookupDigit i (One a) = Place i a
lookupDigit i (Two a b)
| i < sa = Place i a
| otherwise = Place (i - sa) b
where
sa = size a
lookupDigit i (Three a b c)
| i < sa = Place i a
| i < sab = Place (i - sa) b
| otherwise = Place (i - sab) c
where
sa = size a
sab = sa + size b
lookupDigit i (Four a b c d)
| i < sa = Place i a
| i < sab = Place (i - sa) b
| i < sabc = Place (i - sab) c
| otherwise = Place (i - sabc) d
where
sa = size a
sab = sa + size b
sabc = sab + size c
-- | /O(log(min(i,n-i)))/. Replace the element at the specified position.
-- If the position is out of range, the original sequence is returned.
update :: Int -> a -> Seq a -> Seq a
update i x = adjust (const x) i
-- | /O(log(min(i,n-i)))/. Update the element at the specified position.
-- If the position is out of range, the original sequence is returned.
adjust :: (a -> a) -> Int -> Seq a -> Seq a
adjust f i (Seq xs)
| 0 <= i && i < size xs = Seq (adjustTree (const (fmap f)) i xs)
| otherwise = Seq xs
{-# SPECIALIZE adjustTree :: (Int -> Elem a -> Elem a) -> Int -> FingerTree (Elem a) -> FingerTree (Elem a) #-}
{-# SPECIALIZE adjustTree :: (Int -> Node a -> Node a) -> Int -> FingerTree (Node a) -> FingerTree (Node a) #-}
adjustTree :: Sized a => (Int -> a -> a) ->
Int -> FingerTree a -> FingerTree a
adjustTree _ _ Empty = error "adjustTree of empty tree"
adjustTree f i (Single x) = Single (f i x)
adjustTree f i (Deep s pr m sf)
| i < spr = Deep s (adjustDigit f i pr) m sf
| i < spm = Deep s pr (adjustTree (adjustNode f) (i - spr) m) sf
| otherwise = Deep s pr m (adjustDigit f (i - spm) sf)
where
spr = size pr
spm = spr + size m
{-# SPECIALIZE adjustNode :: (Int -> Elem a -> Elem a) -> Int -> Node (Elem a) -> Node (Elem a) #-}
{-# SPECIALIZE adjustNode :: (Int -> Node a -> Node a) -> Int -> Node (Node a) -> Node (Node a) #-}
adjustNode :: Sized a => (Int -> a -> a) -> Int -> Node a -> Node a
adjustNode f i (Node2 s a b)
| i < sa = Node2 s (f i a) b
| otherwise = Node2 s a (f (i - sa) b)
where
sa = size a
adjustNode f i (Node3 s a b c)
| i < sa = Node3 s (f i a) b c
| i < sab = Node3 s a (f (i - sa) b) c
| otherwise = Node3 s a b (f (i - sab) c)
where
sa = size a
sab = sa + size b
{-# SPECIALIZE adjustDigit :: (Int -> Elem a -> Elem a) -> Int -> Digit (Elem a) -> Digit (Elem a) #-}
{-# SPECIALIZE adjustDigit :: (Int -> Node a -> Node a) -> Int -> Digit (Node a) -> Digit (Node a) #-}
adjustDigit :: Sized a => (Int -> a -> a) -> Int -> Digit a -> Digit a
adjustDigit f i (One a) = One (f i a)
adjustDigit f i (Two a b)
| i < sa = Two (f i a) b
| otherwise = Two a (f (i - sa) b)
where
sa = size a
adjustDigit f i (Three a b c)
| i < sa = Three (f i a) b c
| i < sab = Three a (f (i - sa) b) c
| otherwise = Three a b (f (i - sab) c)
where
sa = size a
sab = sa + size b
adjustDigit f i (Four a b c d)
| i < sa = Four (f i a) b c d
| i < sab = Four a (f (i - sa) b) c d
| i < sabc = Four a b (f (i - sab) c) d
| otherwise = Four a b c (f (i- sabc) d)
where
sa = size a
sab = sa + size b
sabc = sab + size c
-- | /O(n)/. A generalization of 'fmap', 'mapWithIndex' takes a mapping
-- function that also depends on the element's index, and applies it to every
-- element in the sequence.
mapWithIndex :: (Int -> a -> b) -> Seq a -> Seq b
mapWithIndex f' (Seq xs') = Seq $ mapWithIndexTree (\s (Elem a) -> Elem (f' s a)) 0 xs'
where
{-# SPECIALIZE mapWithIndexTree :: (Int -> Elem y -> b) -> Int -> FingerTree (Elem y) -> FingerTree b #-}
{-# SPECIALIZE mapWithIndexTree :: (Int -> Node y -> b) -> Int -> FingerTree (Node y) -> FingerTree b #-}
mapWithIndexTree :: Sized a => (Int -> a -> b) -> Int -> FingerTree a -> FingerTree b
mapWithIndexTree _ s Empty = s `seq` Empty
mapWithIndexTree f s (Single xs) = Single $ f s xs
mapWithIndexTree f s (Deep n pr m sf) = sPspr `seq` sPsprm `seq`
Deep n
(mapWithIndexDigit f s pr)
(mapWithIndexTree (mapWithIndexNode f) sPspr m)
(mapWithIndexDigit f sPsprm sf)
where
sPspr = s + size pr
sPsprm = s + n - size sf
{-# SPECIALIZE mapWithIndexDigit :: (Int -> Elem y -> b) -> Int -> Digit (Elem y) -> Digit b #-}
{-# SPECIALIZE mapWithIndexDigit :: (Int -> Node y -> b) -> Int -> Digit (Node y) -> Digit b #-}
mapWithIndexDigit :: Sized a => (Int -> a -> b) -> Int -> Digit a -> Digit b
mapWithIndexDigit f s (One a) = One (f s a)
mapWithIndexDigit f s (Two a b) = sPsa `seq` Two (f s a) (f sPsa b)
where
sPsa = s + size a
mapWithIndexDigit f s (Three a b c) = sPsa `seq` sPsab `seq`
Three (f s a) (f sPsa b) (f sPsab c)
where
sPsa = s + size a
sPsab = sPsa + size b
mapWithIndexDigit f s (Four a b c d) = sPsa `seq` sPsab `seq` sPsabc `seq`
Four (f s a) (f sPsa b) (f sPsab c) (f sPsabc d)
where
sPsa = s + size a
sPsab = sPsa + size b
sPsabc = sPsab + size c
{-# SPECIALIZE mapWithIndexNode :: (Int -> Elem y -> b) -> Int -> Node (Elem y) -> Node b #-}
{-# SPECIALIZE mapWithIndexNode :: (Int -> Node y -> b) -> Int -> Node (Node y) -> Node b #-}
mapWithIndexNode :: Sized a => (Int -> a -> b) -> Int -> Node a -> Node b
mapWithIndexNode f s (Node2 ns a b) = sPsa `seq` Node2 ns (f s a) (f sPsa b)
where
sPsa = s + size a
mapWithIndexNode f s (Node3 ns a b c) = sPsa `seq` sPsab `seq`
Node3 ns (f s a) (f sPsa b) (f sPsab c)
where
sPsa = s + size a
sPsab = sPsa + size b
#ifdef __GLASGOW_HASKELL__
{-# NOINLINE [1] mapWithIndex #-}
{-# RULES
"mapWithIndex/mapWithIndex" forall f g xs . mapWithIndex f (mapWithIndex g xs) =
mapWithIndex (\k a -> f k (g k a)) xs
"mapWithIndex/fmapSeq" forall f g xs . mapWithIndex f (fmapSeq g xs) =
mapWithIndex (\k a -> f k (g a)) xs
"fmapSeq/mapWithIndex" forall f g xs . fmapSeq f (mapWithIndex g xs) =
mapWithIndex (\k a -> f (g k a)) xs
#-}
#endif
-- | /O(n)/. Convert a given sequence length and a function representing that
-- sequence into a sequence.
fromFunction :: Int -> (Int -> a) -> Seq a
fromFunction len f | len < 0 = error "Data.Sequence.fromFunction called with negative len"
| len == 0 = empty
| otherwise = Seq $ create (lift_elem f) 1 0 len
where
create :: (Int -> a) -> Int -> Int -> Int -> FingerTree a
create b{-tree_builder-} s{-tree_size-} i{-start_index-} trees = i `seq` s `seq` case trees of
1 -> Single $ b i
2 -> Deep (2*s) (One (b i)) Empty (One (b (i+s)))
3 -> Deep (3*s) (createTwo i) Empty (One (b (i+2*s)))
4 -> Deep (4*s) (createTwo i) Empty (createTwo (i+2*s))
5 -> Deep (5*s) (createThree i) Empty (createTwo (i+3*s))
6 -> Deep (6*s) (createThree i) Empty (createThree (i+3*s))
_ -> case trees `quotRem` 3 of
(trees', 1) -> Deep (trees*s) (createTwo i)
(create mb (3*s) (i+2*s) (trees'-1))
(createTwo (i+(2+3*(trees'-1))*s))
(trees', 2) -> Deep (trees*s) (createThree i)
(create mb (3*s) (i+3*s) (trees'-1))
(createTwo (i+(3+3*(trees'-1))*s))
(trees', _) -> Deep (trees*s) (createThree i)
(create mb (3*s) (i+3*s) (trees'-2))
(createThree (i+(3+3*(trees'-2))*s))
where
createTwo j = Two (b j) (b (j + s))
{-# INLINE createTwo #-}
createThree j = Three (b j) (b (j + s)) (b (j + 2*s))
{-# INLINE createThree #-}
mb j = Node3 (3*s) (b j) (b (j + s)) (b (j + 2*s))
{-# INLINE mb #-}
lift_elem :: (Int -> a) -> (Int -> Elem a)
#if __GLASGOW_HASKELL__ >= 708
lift_elem g = coerce g
#else
lift_elem g = Elem . g
#endif
{-# INLINE lift_elem #-}
-- | /O(n)/. Create a sequence consisting of the elements of an 'Array'.
-- Note that the resulting sequence elements may be evaluated lazily (as on GHC),
-- so you must force the entire structure to be sure that the original array
-- can be garbage-collected.
fromArray :: Ix i => Array i a -> Seq a
#ifdef __GLASGOW_HASKELL__
fromArray a = fromFunction (GHC.Arr.numElements a) (GHC.Arr.unsafeAt a)
#else
fromArray a = fromList2 (Data.Array.rangeSize (Data.Array.bounds a)) (Data.Array.elems a)
#endif
-- Splitting
-- | /O(log(min(i,n-i)))/. The first @i@ elements of a sequence.
-- If @i@ is negative, @'take' i s@ yields the empty sequence.
-- If the sequence contains fewer than @i@ elements, the whole sequence
-- is returned.
take :: Int -> Seq a -> Seq a
take i = fst . splitAt' i
-- | /O(log(min(i,n-i)))/. Elements of a sequence after the first @i@.
-- If @i@ is negative, @'drop' i s@ yields the whole sequence.
-- If the sequence contains fewer than @i@ elements, the empty sequence
-- is returned.
drop :: Int -> Seq a -> Seq a
drop i = snd . splitAt' i
-- | /O(log(min(i,n-i)))/. Split a sequence at a given position.
-- @'splitAt' i s = ('take' i s, 'drop' i s)@.
splitAt :: Int -> Seq a -> (Seq a, Seq a)
splitAt i (Seq xs) = (Seq l, Seq r)
where (l, r) = split i xs
-- | /O(log(min(i,n-i))) A strict version of 'splitAt'.
splitAt' :: Int -> Seq a -> (Seq a, Seq a)
splitAt' i (Seq xs) = case split i xs of
(l, r) -> (Seq l, Seq r)
split :: Int -> FingerTree (Elem a) ->
(FingerTree (Elem a), FingerTree (Elem a))
split i Empty = i `seq` (Empty, Empty)
split i xs
| size xs > i = case splitTree i xs of
Split l x r -> (l, consTree x r)
| otherwise = (xs, Empty)
data Split t a = Split t a t
#if TESTING
deriving Show
#endif
{-# SPECIALIZE splitTree :: Int -> FingerTree (Elem a) -> Split (FingerTree (Elem a)) (Elem a) #-}
{-# SPECIALIZE splitTree :: Int -> FingerTree (Node a) -> Split (FingerTree (Node a)) (Node a) #-}
splitTree :: Sized a => Int -> FingerTree a -> Split (FingerTree a) a
splitTree _ Empty = error "splitTree of empty tree"
splitTree i (Single x) = i `seq` Split Empty x Empty
splitTree i (Deep _ pr m sf)
| i < spr = case splitDigit i pr of
Split l x r -> Split (maybe Empty digitToTree l) x (deepL r m sf)
| i < spm = case splitTree im m of
Split ml xs mr -> case splitNode (im - size ml) xs of
Split l x r -> Split (deepR pr ml l) x (deepL r mr sf)
| otherwise = case splitDigit (i - spm) sf of
Split l x r -> Split (deepR pr m l) x (maybe Empty digitToTree r)
where
spr = size pr
spm = spr + size m
im = i - spr
{-# SPECIALIZE splitNode :: Int -> Node (Elem a) -> Split (Maybe (Digit (Elem a))) (Elem a) #-}
{-# SPECIALIZE splitNode :: Int -> Node (Node a) -> Split (Maybe (Digit (Node a))) (Node a) #-}
splitNode :: Sized a => Int -> Node a -> Split (Maybe (Digit a)) a
splitNode i (Node2 _ a b)
| i < sa = Split Nothing a (Just (One b))
| otherwise = Split (Just (One a)) b Nothing
where
sa = size a
splitNode i (Node3 _ a b c)
| i < sa = Split Nothing a (Just (Two b c))
| i < sab = Split (Just (One a)) b (Just (One c))
| otherwise = Split (Just (Two a b)) c Nothing
where
sa = size a
sab = sa + size b
{-# SPECIALIZE splitDigit :: Int -> Digit (Elem a) -> Split (Maybe (Digit (Elem a))) (Elem a) #-}
{-# SPECIALIZE splitDigit :: Int -> Digit (Node a) -> Split (Maybe (Digit (Node a))) (Node a) #-}
splitDigit :: Sized a => Int -> Digit a -> Split (Maybe (Digit a)) a
splitDigit i (One a) = i `seq` Split Nothing a Nothing
splitDigit i (Two a b)
| i < sa = Split Nothing a (Just (One b))
| otherwise = Split (Just (One a)) b Nothing
where
sa = size a
splitDigit i (Three a b c)
| i < sa = Split Nothing a (Just (Two b c))
| i < sab = Split (Just (One a)) b (Just (One c))
| otherwise = Split (Just (Two a b)) c Nothing
where
sa = size a
sab = sa + size b
splitDigit i (Four a b c d)
| i < sa = Split Nothing a (Just (Three b c d))
| i < sab = Split (Just (One a)) b (Just (Two c d))
| i < sabc = Split (Just (Two a b)) c (Just (One d))
| otherwise = Split (Just (Three a b c)) d Nothing
where
sa = size a
sab = sa + size b
sabc = sab + size c
-- | /O(n)/. Returns a sequence of all suffixes of this sequence,
-- longest first. For example,
--
-- > tails (fromList "abc") = fromList [fromList "abc", fromList "bc", fromList "c", fromList ""]
--
-- Evaluating the /i/th suffix takes /O(log(min(i, n-i)))/, but evaluating
-- every suffix in the sequence takes /O(n)/ due to sharing.
tails :: Seq a -> Seq (Seq a)
tails (Seq xs) = Seq (tailsTree (Elem . Seq) xs) |> empty
-- | /O(n)/. Returns a sequence of all prefixes of this sequence,
-- shortest first. For example,
--
-- > inits (fromList "abc") = fromList [fromList "", fromList "a", fromList "ab", fromList "abc"]
--
-- Evaluating the /i/th prefix takes /O(log(min(i, n-i)))/, but evaluating
-- every prefix in the sequence takes /O(n)/ due to sharing.
inits :: Seq a -> Seq (Seq a)
inits (Seq xs) = empty <| Seq (initsTree (Elem . Seq) xs)
-- This implementation of tails (and, analogously, inits) has the
-- following algorithmic advantages:
-- Evaluating each tail in the sequence takes linear total time,
-- which is better than we could say for
-- @fromList [drop n xs | n <- [0..length xs]]@.
-- Evaluating any individual tail takes logarithmic time, which is
-- better than we can say for either
-- @scanr (<|) empty xs@ or @iterateN (length xs + 1) (\ xs -> let _ :< xs' = viewl xs in xs') xs@.
--
-- Moreover, if we actually look at every tail in the sequence, the
-- following benchmarks demonstrate that this implementation is modestly
-- faster than any of the above:
--
-- Times (ms)
-- min mean +/-sd median max
-- Seq.tails: 21.986 24.961 10.169 22.417 86.485
-- scanr: 85.392 87.942 2.488 87.425 100.217
-- iterateN: 29.952 31.245 1.574 30.412 37.268
--
-- The algorithm for tails (and, analogously, inits) is as follows:
--
-- A Node in the FingerTree of tails is constructed by evaluating the
-- corresponding tail of the FingerTree of Nodes, considering the first
-- Node in this tail, and constructing a Node in which each tail of this
-- Node is made to be the prefix of the remaining tree. This ends up
-- working quite elegantly, as the remainder of the tail of the FingerTree
-- of Nodes becomes the middle of a new tail, the suffix of the Node is
-- the prefix, and the suffix of the original tree is retained.
--
-- In particular, evaluating the /i/th tail involves making as
-- many partial evaluations as the Node depth of the /i/th element.
-- In addition, when we evaluate the /i/th tail, and we also evaluate
-- the /j/th tail, and /m/ Nodes are on the path to both /i/ and /j/,
-- each of those /m/ evaluations are shared between the computation of
-- the /i/th and /j/th tails.
--
-- wasserman.louis@gmail.com, 7/16/09
tailsDigit :: Digit a -> Digit (Digit a)
tailsDigit (One a) = One (One a)
tailsDigit (Two a b) = Two (Two a b) (One b)
tailsDigit (Three a b c) = Three (Three a b c) (Two b c) (One c)
tailsDigit (Four a b c d) = Four (Four a b c d) (Three b c d) (Two c d) (One d)
initsDigit :: Digit a -> Digit (Digit a)
initsDigit (One a) = One (One a)
initsDigit (Two a b) = Two (One a) (Two a b)
initsDigit (Three a b c) = Three (One a) (Two a b) (Three a b c)
initsDigit (Four a b c d) = Four (One a) (Two a b) (Three a b c) (Four a b c d)
tailsNode :: Node a -> Node (Digit a)
tailsNode (Node2 s a b) = Node2 s (Two a b) (One b)
tailsNode (Node3 s a b c) = Node3 s (Three a b c) (Two b c) (One c)
initsNode :: Node a -> Node (Digit a)
initsNode (Node2 s a b) = Node2 s (One a) (Two a b)
initsNode (Node3 s a b c) = Node3 s (One a) (Two a b) (Three a b c)
{-# SPECIALIZE tailsTree :: (FingerTree (Elem a) -> Elem b) -> FingerTree (Elem a) -> FingerTree (Elem b) #-}
{-# SPECIALIZE tailsTree :: (FingerTree (Node a) -> Node b) -> FingerTree (Node a) -> FingerTree (Node b) #-}
-- | Given a function to apply to tails of a tree, applies that function
-- to every tail of the specified tree.
tailsTree :: (Sized a, Sized b) => (FingerTree a -> b) -> FingerTree a -> FingerTree b
tailsTree _ Empty = Empty
tailsTree f (Single x) = Single (f (Single x))
tailsTree f (Deep n pr m sf) =
Deep n (fmap (\ pr' -> f (deep pr' m sf)) (tailsDigit pr))
(tailsTree f' m)
(fmap (f . digitToTree) (tailsDigit sf))
where
f' ms = let Just2 node m' = viewLTree ms in
fmap (\ pr' -> f (deep pr' m' sf)) (tailsNode node)
{-# SPECIALIZE initsTree :: (FingerTree (Elem a) -> Elem b) -> FingerTree (Elem a) -> FingerTree (Elem b) #-}
{-# SPECIALIZE initsTree :: (FingerTree (Node a) -> Node b) -> FingerTree (Node a) -> FingerTree (Node b) #-}
-- | Given a function to apply to inits of a tree, applies that function
-- to every init of the specified tree.
initsTree :: (Sized a, Sized b) => (FingerTree a -> b) -> FingerTree a -> FingerTree b
initsTree _ Empty = Empty
initsTree f (Single x) = Single (f (Single x))
initsTree f (Deep n pr m sf) =
Deep n (fmap (f . digitToTree) (initsDigit pr))
(initsTree f' m)
(fmap (f . deep pr m) (initsDigit sf))
where
f' ms = let Just2 m' node = viewRTree ms in
fmap (\ sf' -> f (deep pr m' sf')) (initsNode node)
{-# INLINE foldlWithIndex #-}
-- | 'foldlWithIndex' is a version of 'foldl' that also provides access
-- to the index of each element.
foldlWithIndex :: (b -> Int -> a -> b) -> b -> Seq a -> b
foldlWithIndex f z xs = foldl (\ g x i -> i `seq` f (g (i - 1)) i x) (const z) xs (length xs - 1)
{-# INLINE foldrWithIndex #-}
-- | 'foldrWithIndex' is a version of 'foldr' that also provides access
-- to the index of each element.
foldrWithIndex :: (Int -> a -> b -> b) -> b -> Seq a -> b
foldrWithIndex f z xs = foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0
{-# INLINE listToMaybe' #-}
-- 'listToMaybe\'' is a good consumer version of 'listToMaybe'.
listToMaybe' :: [a] -> Maybe a
listToMaybe' = foldr (\ x _ -> Just x) Nothing
-- | /O(i)/ where /i/ is the prefix length. 'takeWhileL', applied
-- to a predicate @p@ and a sequence @xs@, returns the longest prefix
-- (possibly empty) of @xs@ of elements that satisfy @p@.
takeWhileL :: (a -> Bool) -> Seq a -> Seq a
takeWhileL p = fst . spanl p
-- | /O(i)/ where /i/ is the suffix length. 'takeWhileR', applied
-- to a predicate @p@ and a sequence @xs@, returns the longest suffix
-- (possibly empty) of @xs@ of elements that satisfy @p@.
--
-- @'takeWhileR' p xs@ is equivalent to @'reverse' ('takeWhileL' p ('reverse' xs))@.
takeWhileR :: (a -> Bool) -> Seq a -> Seq a
takeWhileR p = fst . spanr p
-- | /O(i)/ where /i/ is the prefix length. @'dropWhileL' p xs@ returns
-- the suffix remaining after @'takeWhileL' p xs@.
dropWhileL :: (a -> Bool) -> Seq a -> Seq a
dropWhileL p = snd . spanl p
-- | /O(i)/ where /i/ is the suffix length. @'dropWhileR' p xs@ returns
-- the prefix remaining after @'takeWhileR' p xs@.
--
-- @'dropWhileR' p xs@ is equivalent to @'reverse' ('dropWhileL' p ('reverse' xs))@.
dropWhileR :: (a -> Bool) -> Seq a -> Seq a
dropWhileR p = snd . spanr p
-- | /O(i)/ where /i/ is the prefix length. 'spanl', applied to
-- a predicate @p@ and a sequence @xs@, returns a pair whose first
-- element is the longest prefix (possibly empty) of @xs@ of elements that
-- satisfy @p@ and the second element is the remainder of the sequence.
spanl :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
spanl p = breakl (not . p)
-- | /O(i)/ where /i/ is the suffix length. 'spanr', applied to a
-- predicate @p@ and a sequence @xs@, returns a pair whose /first/ element
-- is the longest /suffix/ (possibly empty) of @xs@ of elements that
-- satisfy @p@ and the second element is the remainder of the sequence.
spanr :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
spanr p = breakr (not . p)
{-# INLINE breakl #-}
-- | /O(i)/ where /i/ is the breakpoint index. 'breakl', applied to a
-- predicate @p@ and a sequence @xs@, returns a pair whose first element
-- is the longest prefix (possibly empty) of @xs@ of elements that
-- /do not satisfy/ @p@ and the second element is the remainder of
-- the sequence.
--
-- @'breakl' p@ is equivalent to @'spanl' (not . p)@.
breakl :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
breakl p xs = foldr (\ i _ -> splitAt i xs) (xs, empty) (findIndicesL p xs)
{-# INLINE breakr #-}
-- | @'breakr' p@ is equivalent to @'spanr' (not . p)@.
breakr :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
breakr p xs = foldr (\ i _ -> flipPair (splitAt (i + 1) xs)) (xs, empty) (findIndicesR p xs)
where flipPair (x, y) = (y, x)
-- | /O(n)/. The 'partition' function takes a predicate @p@ and a
-- sequence @xs@ and returns sequences of those elements which do and
-- do not satisfy the predicate.
partition :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
partition p = foldl part (empty, empty)
where
part (xs, ys) x
| p x = (xs |> x, ys)
| otherwise = (xs, ys |> x)
-- | /O(n)/. The 'filter' function takes a predicate @p@ and a sequence
-- @xs@ and returns a sequence of those elements which satisfy the
-- predicate.
filter :: (a -> Bool) -> Seq a -> Seq a
filter p = foldl (\ xs x -> if p x then xs |> x else xs) empty
-- Indexing sequences
-- | 'elemIndexL' finds the leftmost index of the specified element,
-- if it is present, and otherwise 'Nothing'.
elemIndexL :: Eq a => a -> Seq a -> Maybe Int
elemIndexL x = findIndexL (x ==)
-- | 'elemIndexR' finds the rightmost index of the specified element,
-- if it is present, and otherwise 'Nothing'.
elemIndexR :: Eq a => a -> Seq a -> Maybe Int
elemIndexR x = findIndexR (x ==)
-- | 'elemIndicesL' finds the indices of the specified element, from
-- left to right (i.e. in ascending order).
elemIndicesL :: Eq a => a -> Seq a -> [Int]
elemIndicesL x = findIndicesL (x ==)
-- | 'elemIndicesR' finds the indices of the specified element, from
-- right to left (i.e. in descending order).
elemIndicesR :: Eq a => a -> Seq a -> [Int]
elemIndicesR x = findIndicesR (x ==)
-- | @'findIndexL' p xs@ finds the index of the leftmost element that
-- satisfies @p@, if any exist.
findIndexL :: (a -> Bool) -> Seq a -> Maybe Int
findIndexL p = listToMaybe' . findIndicesL p
-- | @'findIndexR' p xs@ finds the index of the rightmost element that
-- satisfies @p@, if any exist.
findIndexR :: (a -> Bool) -> Seq a -> Maybe Int
findIndexR p = listToMaybe' . findIndicesR p
{-# INLINE findIndicesL #-}
-- | @'findIndicesL' p@ finds all indices of elements that satisfy @p@,
-- in ascending order.
findIndicesL :: (a -> Bool) -> Seq a -> [Int]
#if __GLASGOW_HASKELL__
findIndicesL p xs = build (\ c n -> let g i x z = if p x then c i z else z in
foldrWithIndex g n xs)
#else
findIndicesL p xs = foldrWithIndex g [] xs
where g i x is = if p x then i:is else is
#endif
{-# INLINE findIndicesR #-}
-- | @'findIndicesR' p@ finds all indices of elements that satisfy @p@,
-- in descending order.
findIndicesR :: (a -> Bool) -> Seq a -> [Int]
#if __GLASGOW_HASKELL__
findIndicesR p xs = build (\ c n ->
let g z i x = if p x then c i z else z in foldlWithIndex g n xs)
#else
findIndicesR p xs = foldlWithIndex g [] xs
where g is i x = if p x then i:is else is
#endif
------------------------------------------------------------------------
-- Lists
------------------------------------------------------------------------
-- The implementation below, by Ross Paterson, avoids the rebuilding
-- the previous (|>)-based implementation suffered from.
-- | /O(n)/. Create a sequence from a finite list of elements.
-- There is a function 'toList' in the opposite direction for all
-- instances of the 'Foldable' class, including 'Seq'.
fromList :: [a] -> Seq a
fromList = Seq . mkTree 1 . map_elem
where
{-# SPECIALIZE mkTree :: Int -> [Elem a] -> FingerTree (Elem a) #-}
{-# SPECIALIZE mkTree :: Int -> [Node a] -> FingerTree (Node a) #-}
mkTree :: (Sized a) => Int -> [a] -> FingerTree a
STRICT_1_OF_2(mkTree)
mkTree _ [] = Empty
mkTree _ [x1] = Single x1
mkTree s [x1, x2] = Deep (2*s) (One x1) Empty (One x2)
mkTree s [x1, x2, x3] = Deep (3*s) (One x1) Empty (Two x2 x3)
mkTree s (x1:x2:x3:x4:xs) = case getNodes (3*s) x4 xs of
(ns, sf) -> case mkTree (3*s) ns of
m -> m `seq` Deep (3*size x1 + size m + size sf) (Three x1 x2 x3) m sf
getNodes :: Int -> a -> [a] -> ([Node a], Digit a)
STRICT_1_OF_3(getNodes)
getNodes _ x1 [] = ([], One x1)
getNodes _ x1 [x2] = ([], Two x1 x2)
getNodes _ x1 [x2, x3] = ([], Three x1 x2 x3)
getNodes s x1 (x2:x3:x4:xs) = (Node3 s x1 x2 x3:ns, d)
where (ns, d) = getNodes s x4 xs
map_elem :: [a] -> [Elem a]
#if __GLASGOW_HASKELL__ >= 708
map_elem xs = coerce xs
#else
map_elem xs = Data.List.map Elem xs
#endif
{-# INLINE map_elem #-}
#if __GLASGOW_HASKELL__ >= 708
instance GHC.Exts.IsList (Seq a) where
type Item (Seq a) = a
fromList = fromList
fromListN = fromList2
toList = toList
#endif
------------------------------------------------------------------------
-- Reverse
------------------------------------------------------------------------
-- | /O(n)/. The reverse of a sequence.
reverse :: Seq a -> Seq a
reverse (Seq xs) = Seq (reverseTree id xs)
reverseTree :: (a -> a) -> FingerTree a -> FingerTree a
reverseTree _ Empty = Empty
reverseTree f (Single x) = Single (f x)
reverseTree f (Deep s pr m sf) =
Deep s (reverseDigit f sf)
(reverseTree (reverseNode f) m)
(reverseDigit f pr)
{-# INLINE reverseDigit #-}
reverseDigit :: (a -> a) -> Digit a -> Digit a
reverseDigit f (One a) = One (f a)
reverseDigit f (Two a b) = Two (f b) (f a)
reverseDigit f (Three a b c) = Three (f c) (f b) (f a)
reverseDigit f (Four a b c d) = Four (f d) (f c) (f b) (f a)
reverseNode :: (a -> a) -> Node a -> Node a
reverseNode f (Node2 s a b) = Node2 s (f b) (f a)
reverseNode f (Node3 s a b c) = Node3 s (f c) (f b) (f a)
------------------------------------------------------------------------
-- Mapping with a splittable value
------------------------------------------------------------------------
-- For zipping, it is useful to build a result by
-- traversing a sequence while splitting up something else. For zipping, we
-- traverse the first sequence while splitting up the second.
--
-- What makes all this crazy code a good idea:
--
-- Suppose we zip together two sequences of the same length:
--
-- zs = zip xs ys
--
-- We want to get reasonably fast indexing into zs immediately, rather than
-- needing to construct the entire thing first, as the previous implementation
-- required. The first aspect is that we build the result "outside-in" or
-- "top-down", rather than left to right. That gives us access to both ends
-- quickly. But that's not enough, by itself, to give immediate access to the
-- center of zs. For that, we need to be able to skip over larger segments of
-- zs, delaying their construction until we actually need them. The way we do
-- this is to traverse xs, while splitting up ys according to the structure of
-- xs. If we have a Deep _ pr m sf, we split ys into three pieces, and hand off
-- one piece to the prefix, one to the middle, and one to the suffix of the
-- result. The key point is that we don't need to actually do anything further
-- with those pieces until we actually need them; the computations to split
-- them up further and zip them with their matching pieces can be delayed until
-- they're actually needed. We do the same thing for Digits (splitting into
-- between one and four pieces) and Nodes (splitting into two or three). The
-- ultimate result is that we can index into, or split at, any location in zs
-- in polylogarithmic time *immediately*, while still being able to force all
-- the thunks in O(n) time.
--
-- Benchmark info, and alternatives:
--
-- The old zipping code used mapAccumL to traverse the first sequence while
-- cutting down the second sequence one piece at a time.
--
-- An alternative way to express that basic idea is to convert both sequences
-- to lists, zip the lists, and then convert the result back to a sequence.
-- I'll call this the "listy" implementation.
--
-- I benchmarked two operations: Each started by zipping two sequences
-- constructed with replicate and/or fromList. The first would then immediately
-- index into the result. The second would apply deepseq to force the entire
-- result. The new implementation worked much better than either of the others
-- on the immediate indexing test, as expected. It also worked better than the
-- old implementation for all the deepseq tests. For short sequences, the listy
-- implementation outperformed all the others on the deepseq test. However, the
-- splitting implementation caught up and surpassed it once the sequences grew
-- long enough. It seems likely that by avoiding rebuilding, it interacts
-- better with the cache hierarchy.
--
-- David Feuer, with excellent guidance from Carter Schonwald, December 2014
-- | /O(n)/. Constructs a new sequence with the same structure as an existing
-- sequence using a user-supplied mapping function along with a splittable
-- value and a way to split it. The value is split up lazily according to the
-- structure of the sequence, so one piece of the value is distributed to each
-- element of the sequence. The caller should provide a splitter function that
-- takes a number, @n@, and a splittable value, breaks off a chunk of size @n@
-- from the value, and returns that chunk and the remainder as a pair. The
-- following examples will hopefully make the usage clear:
--
-- > zipWith :: (a -> b -> c) -> Seq a -> Seq b -> Seq c
-- > zipWith f s1 s2 = splitMap splitAt (\b a -> f a (b `index` 0)) s2' s1'
-- > where
-- > minLen = min (length s1) (length s2)
-- > s1' = take minLen s1
-- > s2' = take minLen s2
--
-- > mapWithIndex :: (Int -> a -> b) -> Seq a -> Seq b
-- > mapWithIndex f = splitMap (\n i -> (i, n+i)) f 0
splitMap :: (Int -> s -> (s,s)) -> (s -> a -> b) -> s -> Seq a -> Seq b
splitMap splt' = go
where
go f s (Seq xs) = Seq $ splitMapTree splt' (\s' (Elem a) -> Elem (f s' a)) s xs
{-# SPECIALIZE splitMapTree :: (Int -> s -> (s,s)) -> (s -> Elem y -> b) -> s -> FingerTree (Elem y) -> FingerTree b #-}
{-# SPECIALIZE splitMapTree :: (Int -> s -> (s,s)) -> (s -> Node y -> b) -> s -> FingerTree (Node y) -> FingerTree b #-}
splitMapTree :: Sized a => (Int -> s -> (s,s)) -> (s -> a -> b) -> s -> FingerTree a -> FingerTree b
splitMapTree _ _ _ Empty = Empty
splitMapTree _ f s (Single xs) = Single $ f s xs
splitMapTree splt f s (Deep n pr m sf) = Deep n (splitMapDigit splt f prs pr) (splitMapTree splt (splitMapNode splt f) ms m) (splitMapDigit splt f sfs sf)
where
(prs, r) = splt (size pr) s
(ms, sfs) = splt (n - size pr - size sf) r
{-# SPECIALIZE splitMapDigit :: (Int -> s -> (s,s)) -> (s -> Elem y -> b) -> s -> Digit (Elem y) -> Digit b #-}
{-# SPECIALIZE splitMapDigit :: (Int -> s -> (s,s)) -> (s -> Node y -> b) -> s -> Digit (Node y) -> Digit b #-}
splitMapDigit :: Sized a => (Int -> s -> (s,s)) -> (s -> a -> b) -> s -> Digit a -> Digit b
splitMapDigit _ f s (One a) = One (f s a)
splitMapDigit splt f s (Two a b) = Two (f first a) (f second b)
where
(first, second) = splt (size a) s
splitMapDigit splt f s (Three a b c) = Three (f first a) (f second b) (f third c)
where
(first, r) = splt (size a) s
(second, third) = splt (size b) r
splitMapDigit splt f s (Four a b c d) = Four (f first a) (f second b) (f third c) (f fourth d)
where
(first, s') = splt (size a) s
(middle, fourth) = splt (size b + size c) s'
(second, third) = splt (size b) middle
{-# SPECIALIZE splitMapNode :: (Int -> s -> (s,s)) -> (s -> Elem y -> b) -> s -> Node (Elem y) -> Node b #-}
{-# SPECIALIZE splitMapNode :: (Int -> s -> (s,s)) -> (s -> Node y -> b) -> s -> Node (Node y) -> Node b #-}
splitMapNode :: Sized a => (Int -> s -> (s,s)) -> (s -> a -> b) -> s -> Node a -> Node b
splitMapNode splt f s (Node2 ns a b) = Node2 ns (f first a) (f second b)
where
(first, second) = splt (size a) s
splitMapNode splt f s (Node3 ns a b c) = Node3 ns (f first a) (f second b) (f third c)
where
(first, r) = splt (size a) s
(second, third) = splt (size b) r
{-# INLINE splitMap #-}
getSingleton :: Seq a -> a
getSingleton (Seq (Single (Elem a))) = a
getSingleton (Seq Empty) = error "getSingleton: Empty"
getSingleton _ = error "getSingleton: Not a singleton."
------------------------------------------------------------------------
-- Zipping
------------------------------------------------------------------------
-- | /O(min(n1,n2))/. 'zip' takes two sequences and returns a sequence
-- of corresponding pairs. If one input is short, excess elements are
-- discarded from the right end of the longer sequence.
zip :: Seq a -> Seq b -> Seq (a, b)
zip = zipWith (,)
-- | /O(min(n1,n2))/. 'zipWith' generalizes 'zip' by zipping with the
-- function given as the first argument, instead of a tupling function.
-- For example, @zipWith (+)@ is applied to two sequences to take the
-- sequence of corresponding sums.
zipWith :: (a -> b -> c) -> Seq a -> Seq b -> Seq c
zipWith f s1 s2 = zipWith' f s1' s2'
where
minLen = min (length s1) (length s2)
s1' = take minLen s1
s2' = take minLen s2
-- | A version of zipWith that assumes the sequences have the same length.
zipWith' :: (a -> b -> c) -> Seq a -> Seq b -> Seq c
zipWith' f s1 s2 = splitMap splitAt' (\s a -> f a (getSingleton s)) s2 s1
-- | /O(min(n1,n2,n3))/. 'zip3' takes three sequences and returns a
-- sequence of triples, analogous to 'zip'.
zip3 :: Seq a -> Seq b -> Seq c -> Seq (a,b,c)
zip3 = zipWith3 (,,)
-- | /O(min(n1,n2,n3))/. 'zipWith3' takes a function which combines
-- three elements, as well as three sequences and returns a sequence of
-- their point-wise combinations, analogous to 'zipWith'.
zipWith3 :: (a -> b -> c -> d) -> Seq a -> Seq b -> Seq c -> Seq d
zipWith3 f s1 s2 s3 = zipWith' ($) (zipWith' f s1' s2') s3'
where
minLen = minimum [length s1, length s2, length s3]
s1' = take minLen s1
s2' = take minLen s2
s3' = take minLen s3
zipWith3' :: (a -> b -> c -> d) -> Seq a -> Seq b -> Seq c -> Seq d
zipWith3' f s1 s2 s3 = zipWith' ($) (zipWith' f s1 s2) s3
-- | /O(min(n1,n2,n3,n4))/. 'zip4' takes four sequences and returns a
-- sequence of quadruples, analogous to 'zip'.
zip4 :: Seq a -> Seq b -> Seq c -> Seq d -> Seq (a,b,c,d)
zip4 = zipWith4 (,,,)
-- | /O(min(n1,n2,n3,n4))/. 'zipWith4' takes a function which combines
-- four elements, as well as four sequences and returns a sequence of
-- their point-wise combinations, analogous to 'zipWith'.
zipWith4 :: (a -> b -> c -> d -> e) -> Seq a -> Seq b -> Seq c -> Seq d -> Seq e
zipWith4 f s1 s2 s3 s4 = zipWith' ($) (zipWith3' f s1' s2' s3') s4'
where
minLen = minimum [length s1, length s2, length s3, length s4]
s1' = take minLen s1
s2' = take minLen s2
s3' = take minLen s3
s4' = take minLen s4
------------------------------------------------------------------------
-- Sorting
--
-- sort and sortBy are implemented by simple deforestations of
-- \ xs -> fromList2 (length xs) . Data.List.sortBy cmp . toList
-- which does not get deforested automatically, it would appear.
--
-- Unstable sorting is performed by a heap sort implementation based on
-- pairing heaps. Because the internal structure of sequences is quite
-- varied, it is difficult to get blocks of elements of roughly the same
-- length, which would improve merge sort performance. Pairing heaps,
-- on the other hand, are relatively resistant to the effects of merging
-- heaps of wildly different sizes, as guaranteed by its amortized
-- constant-time merge operation. Moreover, extensive use of SpecConstr
-- transformations can be done on pairing heaps, especially when we're
-- only constructing them to immediately be unrolled.
--
-- On purely random sequences of length 50000, with no RTS options,
-- I get the following statistics, in which heapsort is about 42.5%
-- faster: (all comparisons done with -O2)
--
-- Times (ms) min mean +/-sd median max
-- to/from list: 103.802 108.572 7.487 106.436 143.339
-- unstable heapsort: 60.686 62.968 4.275 61.187 79.151
--
-- Heapsort, it would seem, is less of a memory hog than Data.List.sortBy.
-- The gap is narrowed when more memory is available, but heapsort still
-- wins, 15% faster, with +RTS -H128m:
--
-- Times (ms) min mean +/-sd median max
-- to/from list: 42.692 45.074 2.596 44.600 56.601
-- unstable heapsort: 37.100 38.344 3.043 37.715 55.526
--
-- In addition, on strictly increasing sequences the gap is even wider
-- than normal; heapsort is 68.5% faster with no RTS options:
-- Times (ms) min mean +/-sd median max
-- to/from list: 52.236 53.574 1.987 53.034 62.098
-- unstable heapsort: 16.433 16.919 0.931 16.681 21.622
--
-- This may be attributed to the elegant nature of the pairing heap.
--
-- wasserman.louis@gmail.com, 7/20/09
------------------------------------------------------------------------
-- | /O(n log n)/. 'sort' sorts the specified 'Seq' by the natural
-- ordering of its elements. The sort is stable.
-- If stability is not required, 'unstableSort' can be considerably
-- faster, and in particular uses less memory.
sort :: Ord a => Seq a -> Seq a
sort = sortBy compare
-- | /O(n log n)/. 'sortBy' sorts the specified 'Seq' according to the
-- specified comparator. The sort is stable.
-- If stability is not required, 'unstableSortBy' can be considerably
-- faster, and in particular uses less memory.
sortBy :: (a -> a -> Ordering) -> Seq a -> Seq a
sortBy cmp xs = fromList2 (length xs) (Data.List.sortBy cmp (toList xs))
-- | /O(n log n)/. 'unstableSort' sorts the specified 'Seq' by
-- the natural ordering of its elements, but the sort is not stable.
-- This algorithm is frequently faster and uses less memory than 'sort',
-- and performs extremely well -- frequently twice as fast as 'sort' --
-- when the sequence is already nearly sorted.
unstableSort :: Ord a => Seq a -> Seq a
unstableSort = unstableSortBy compare
-- | /O(n log n)/. A generalization of 'unstableSort', 'unstableSortBy'
-- takes an arbitrary comparator and sorts the specified sequence.
-- The sort is not stable. This algorithm is frequently faster and
-- uses less memory than 'sortBy', and performs extremely well --
-- frequently twice as fast as 'sortBy' -- when the sequence is already
-- nearly sorted.
unstableSortBy :: (a -> a -> Ordering) -> Seq a -> Seq a
unstableSortBy cmp (Seq xs) =
fromList2 (size xs) $ maybe [] (unrollPQ cmp) $
toPQ cmp (\ (Elem x) -> PQueue x Nil) xs
-- | fromList2, given a list and its length, constructs a completely
-- balanced Seq whose elements are that list using the applicativeTree
-- generalization.
fromList2 :: Int -> [a] -> Seq a
fromList2 n = execState (replicateA n (State ht))
where
ht (x:xs) = (xs, x)
ht [] = error "fromList2: short list"
-- | A 'PQueue' is a simple pairing heap.
data PQueue e = PQueue e (PQL e)
data PQL e = Nil | {-# UNPACK #-} !(PQueue e) :& PQL e
infixr 8 :&
#if TESTING
instance Functor PQueue where
fmap f (PQueue x ts) = PQueue (f x) (fmap f ts)
instance Functor PQL where
fmap f (q :& qs) = fmap f q :& fmap f qs
fmap _ Nil = Nil
instance Show e => Show (PQueue e) where
show = unlines . draw . fmap show
-- borrowed wholesale from Data.Tree, as Data.Tree actually depends
-- on Data.Sequence
draw :: PQueue String -> [String]
draw (PQueue x ts0) = x : drawSubTrees ts0
where
drawSubTrees Nil = []
drawSubTrees (t :& Nil) =
"|" : shift "`- " " " (draw t)
drawSubTrees (t :& ts) =
"|" : shift "+- " "| " (draw t) ++ drawSubTrees ts
shift first other = Data.List.zipWith (++) (first : repeat other)
#endif
-- | 'unrollPQ', given a comparator function, unrolls a 'PQueue' into
-- a sorted list.
unrollPQ :: (e -> e -> Ordering) -> PQueue e -> [e]
unrollPQ cmp = unrollPQ'
where
{-# INLINE unrollPQ' #-}
unrollPQ' (PQueue x ts) = x:mergePQs0 ts
(<>) = mergePQ cmp
mergePQs0 Nil = []
mergePQs0 (t :& Nil) = unrollPQ' t
mergePQs0 (t1 :& t2 :& ts) = mergePQs (t1 <> t2) ts
mergePQs t ts = t `seq` case ts of
Nil -> unrollPQ' t
t1 :& Nil -> unrollPQ' (t <> t1)
t1 :& t2 :& ts' -> mergePQs (t <> (t1 <> t2)) ts'
-- | 'toPQ', given an ordering function and a mechanism for queueifying
-- elements, converts a 'FingerTree' to a 'PQueue'.
toPQ :: (e -> e -> Ordering) -> (a -> PQueue e) -> FingerTree a -> Maybe (PQueue e)
toPQ _ _ Empty = Nothing
toPQ _ f (Single x) = Just (f x)
toPQ cmp f (Deep _ pr m sf) = Just (maybe (pr' <> sf') ((pr' <> sf') <>) (toPQ cmp fNode m))
where
fDigit digit = case fmap f digit of
One a -> a
Two a b -> a <> b
Three a b c -> a <> b <> c
Four a b c d -> (a <> b) <> (c <> d)
(<>) = mergePQ cmp
fNode = fDigit . nodeToDigit
pr' = fDigit pr
sf' = fDigit sf
-- | 'mergePQ' merges two 'PQueue's.
mergePQ :: (a -> a -> Ordering) -> PQueue a -> PQueue a -> PQueue a
mergePQ cmp q1@(PQueue x1 ts1) q2@(PQueue x2 ts2)
| cmp x1 x2 == GT = PQueue x2 (q1 :& ts2)
| otherwise = PQueue x1 (q2 :& ts1)
| DavidAlphaFox/ghc | libraries/containers/Data/Sequence.hs | bsd-3-clause | 97,789 | 0 | 23 | 25,878 | 33,553 | 17,204 | 16,349 | -1 | -1 |
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE UndecidableInstances #-}
module Dynamizer.Module
( computeModules
, Modulable (..)
, FunName
) where
import Control.Arrow ((&&&))
import Control.Monad.State.Lazy (State, runState, get, put)
import qualified Data.DList as DL
import Data.Foldable (fold, foldMap)
import Data.Function (on)
import Data.Graph (flattenSCC, stronglyConnComp)
import Data.List (sortBy)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe, fromJust)
import Data.Monoid (Sum (..), (<>))
import Language.Grift.Common.Syntax
import Language.Grift.Source.Syntax
import Language.Grift.Source.Utils
import Dynamizer.Dynamizable
type Key = Int
type Size = Sum Int
type FunName = Name
type FunInfo = (FunName, (Key, Size))
type CallGraph = [(FunName, Key, [Key])]
type FunInfoMap = M.Map FunName (Key, Size)
class Dynamizable t => Modulable t where
pickModuleConfiguration :: M.Map FunName Bool -> t -> t
instance Modulable e => Modulable (ProgramF e) where
pickModuleConfiguration configuration = fmap (pickModuleConfiguration configuration)
instance Modulable e => Modulable (ScopeF e) where
pickModuleConfiguration configuration = fmap (pickModuleConfiguration configuration)
instance Modulable e => Modulable (ModuleF e) where
pickModuleConfiguration _ = id
instance Modulable (e (Ann a e)) => Modulable (Ann a e) where
pickModuleConfiguration configuration (Ann a e) = Ann a $ pickModuleConfiguration configuration e
instance {-# OVERLAPPING #-} Modulable t => Modulable (BindF t (Ann a (ExpF t))) where
pickModuleConfiguration configuration e@(Bind name _ (Ann _ Lam{})) =
case M.lookup name configuration of
Just True -> dynamize e
_ -> fmap (pickModuleConfiguration configuration) e
pickModuleConfiguration configuration e = fmap (pickModuleConfiguration configuration) e
instance (Modulable t, Modulable e) => Modulable (BindF t e) where
pickModuleConfiguration configuration = fmap (pickModuleConfiguration configuration)
instance (Modulable t, Modulable e) => Modulable (ExpF t e) where
pickModuleConfiguration configuration e@(DLam name _ _ _) =
case M.lookup name configuration of
Just True -> dynamize e
_ -> fmap (pickModuleConfiguration configuration) e
pickModuleConfiguration configuration e = fmap (pickModuleConfiguration configuration) e
instance Modulable t => Modulable (Type t) where
pickModuleConfiguration _ = id
computeModules :: forall a t. Int -> ScopeF (Ann a (ExpF t)) -> [[FunName]]
computeModules desiredCount p =
if modulesCount <= desiredCount
then modules
else mergeModules (modulesCount - desiredCount) $ sortBy (compare `on` snd) $ map f modules
where
f :: [FunName] -> ([FunName], Size)
f = id &&& foldMap (snd . fromJust . flip M.lookup funInfo)
mergeModules :: Int -> [([FunName], Size)] -> [[FunName]]
mergeModules 0 ms = map fst ms
mergeModules _ [] = []
mergeModules _ [(x, _)] = [x]
mergeModules n (x:y:l) = mergeModules (n - 1) $ sortBy (compare `on` snd) (x <> y : l)
(cg, funInfo) = buildCallGraph $ annotateFunsWithKeys p
scc = stronglyConnComp cg
modules = map flattenSCC scc
modulesCount = length modules
buildCallGraph :: forall a t. (ScopeF (Ann (a, Maybe Key) (ExpF t)), [FunInfo])
-> (CallGraph, FunInfoMap)
buildCallGraph (p, l) = (DL.toList $ foldMap (mapAnn Nothing Nothing) p, info)
where
info = M.fromList l
findApps :: ExpF t (DL.DList Key) -> DL.DList Key
findApps (P (Var name)) = case M.lookup name info of
(Just (key, _)) -> [key]
_ -> []
findApps e = fold e
mapAnn :: Maybe FunName
-> Maybe Key
-> Ann (a, Maybe Key) (ExpF t)
-> DL.DList (FunName, Key, [Key])
mapAnn name _ (Ann (_, k) e) = f name k e
f :: Maybe FunName
-> Maybe Key
-> ExpF t (Ann (a, Maybe Key) (ExpF t))
-> DL.DList (FunName, Key, [Key])
f _ k (DLam name _ e _) = [(name, fromJust k, DL.toList $ cata (const findApps) e)]
f name k (Lam _ e _) = [(fromJust name, fromJust k, DL.toList $ cata (const findApps) e)]
f name k e = foldMap (mapAnn name k) e
annotateFunsWithKeys :: forall a t. ScopeF (Ann a (ExpF t)) -> (ScopeF (Ann (a, Maybe Key) (ExpF t)), [FunInfo])
annotateFunsWithKeys p = (p', l)
where
(p', (_, l)) = runState (mapM (mapAnn Nothing) p) (0, [])
mapAnn :: Maybe FunName
-> Ann a (ExpF t)
-> State (Key, [FunInfo]) (Ann (a, Maybe Key) (ExpF t))
mapAnn name (Ann a e) = f name a e
f :: Maybe FunName
-> a
-> ExpF t (Ann a (ExpF t))
-> State (Key, [FunInfo]) (Ann (a, Maybe Key) (ExpF t))
f _ a e@(DLam name args b t) = do
val <- getNewId name e
return $ Ann (a, Just val) $ DLam name args (bottomUp (\a' _ -> (a', Nothing)) b) t
f name a e@(Lam args b t) = do
-- if it is an anonymous lambda, no other application will be able to call
-- it, so it does not matter what name we give it
val <- getNewId (fromMaybe "" name) e
return $ Ann (a, Just val) $ Lam args (bottomUp (\a' _ -> (a', Nothing)) b) t
f name a e = Ann (a, Nothing) <$> traverse (mapAnn name) e
getNewId :: FunName -> ExpF t (Ann a (ExpF t)) -> State (Key, [FunInfo]) Key
getNewId name e = do
(val, ls) <- get
put (val + 1, (name, (val, cata getExprSize $ Ann err e)):ls)
return val
where
err = error "getNewId: unexpected evaluation of unused annotated information"
getExprSize :: forall a t. a -> ExpF t Size -> Size
getExprSize _ = (+) 1 . fold
| deyaaeldeen/nAnnotizer | Dynamizer/Module.hs | gpl-3.0 | 6,039 | 0 | 15 | 1,637 | 2,332 | 1,233 | 1,099 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiWayIf #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Hans.Socket.Handle(makeHansHandle) where
import Control.Concurrent(threadDelay)
import Control.Exception(throwIO)
import qualified Data.ByteString as BSS
import qualified Data.ByteString.Lazy as BS
import Data.Typeable(Typeable)
import Foreign.Ptr(Ptr, castPtr, plusPtr)
import GHC.IO.Buffer(newByteBuffer)
import GHC.IO.BufferedIO(BufferedIO(..),
readBuf, readBufNonBlocking,
writeBuf, writeBufNonBlocking)
import GHC.IO.Device(IODevice(..), RawIO(..), IODeviceType(..))
import GHC.IO.Handle(mkFileHandle, noNewlineTranslation)
import Hans.Network(Network(..))
import Hans.Socket(Socket(..), DataSocket(..))
import Prelude hiding (read)
import System.IO(Handle, IOMode)
instance (Socket sock, DataSocket sock, Network addr) =>
IODevice (sock addr) where
ready dev forWrite msecs =
do let tester = if forWrite then sCanWrite else sCanRead
canDo <- tester dev
if | canDo -> return True
| msecs <= 0 -> return False
| otherwise -> do let delay = min msecs 100
threadDelay (delay * 1000)
ready dev forWrite (msecs - delay)
close bs = sClose bs
isTerminal _ = return False
isSeekable _ = return False
seek _ _ _ = throwIO (userError "Seek on HaNS socket.")
tell _ = throwIO (userError "Tell on HaNS socket.")
getSize _ = throwIO (userError "getSize on HaNS socket.")
setSize _ _ = throwIO (userError "setSize on HaNS socket.")
setEcho _ _ = throwIO (userError "setEcho on HaNS socket.")
getEcho _ = throwIO (userError "getEcho on HaNS socket.")
setRaw _ _ = return ()
devType _ = return Stream
dup _ = throwIO (userError "dup on HaNS socket.")
dup2 _ _ = throwIO (userError "dup2 on HaNS socket.")
instance (Socket sock, DataSocket sock, Network addr) =>
RawIO (sock addr) where
read sock dptr sz =
do bstr <- sRead sock (fromIntegral sz)
copyToPtr dptr sz bstr
readNonBlocking sock dptr sz =
do mbstr <- sTryRead sock (fromIntegral sz)
case mbstr of
Nothing -> return Nothing
Just bstr -> Just `fmap` copyToPtr dptr sz bstr
write sock ptr sz =
do bstr <- BSS.packCStringLen (castPtr ptr, sz)
sendAll (BS.fromStrict bstr)
where
sendAll bstr
| BS.null bstr = return ()
| otherwise = do num <- sWrite sock bstr
sendAll (BS.drop (fromIntegral num) bstr)
writeNonBlocking sock ptr sz =
do bstr <- BSS.packCStringLen (castPtr ptr, sz)
num <- sWrite sock (BS.fromStrict bstr)
return (fromIntegral num)
instance (Socket sock, DataSocket sock, Network addr) =>
BufferedIO (sock addr) where
newBuffer _ = newByteBuffer (64 * 1024)
fillReadBuffer = readBuf
fillReadBuffer0 = readBufNonBlocking
flushWriteBuffer = writeBuf
flushWriteBuffer0 = writeBufNonBlocking
-- |Make a GHC Handle from a Hans handle.
makeHansHandle :: (Socket sock, DataSocket sock, Network addr, Typeable sock) =>
sock addr -> IOMode -> IO Handle
makeHansHandle socket mode =
mkFileHandle socket "<socket>" mode Nothing noNewlineTranslation
copyToPtr :: Num a => Ptr b -> Int -> BS.ByteString -> IO a
copyToPtr ptr sz bstr
| BS.length bstr == 0 = return 0
| BS.length bstr > fromIntegral sz = fail "Too big a chunk for copy!"
| otherwise =
do copyBS (BS.toChunks bstr) ptr sz
return (fromIntegral (BS.length bstr))
copyBS :: [BSS.ByteString] -> Ptr a -> Int -> IO ()
copyBS [] _ _ = return ()
copyBS (f:rest) sptr szLeft
| BSS.null f = copyBS rest sptr szLeft
| szLeft <= 0 = return ()
| otherwise =
do let (chunk1, chunk2) = BSS.splitAt szLeft f
amt = fromIntegral (BSS.length chunk1)
BSS.useAsCString chunk1 $ \ dptr -> memcpy dptr sptr amt
copyBS (chunk2 : rest) (sptr `plusPtr` amt) (szLeft - amt)
foreign import ccall unsafe "string.h memcpy"
memcpy :: Ptr a -> Ptr b -> Int -> IO ()
| GaloisInc/HaNS | src/Hans/Socket/Handle.hs | bsd-3-clause | 4,369 | 0 | 15 | 1,271 | 1,423 | 714 | 709 | 94 | 1 |
{-# LANGUAGE GADTs, TypeOperators, DataKinds, TypeFamilies, PolyKinds, TypeFamilyDependencies #-}
module T14749 where
import Data.Kind
data KIND = STAR | KIND :> KIND
data Ty :: KIND -> Type where
TMaybe :: Ty (STAR :> STAR)
TApp :: Ty (a :> b) -> (Ty a -> Ty b)
type family IK (k :: KIND) = (res :: Type) where
IK STAR = Type
IK (a:>b) = IK a -> IK b
type family I (t :: Ty k) = (res :: IK k) where
I TMaybe = Maybe
I (TApp f a) = (I f) (I a)
data TyRep (k :: KIND) (t :: Ty k) where
TyMaybe :: TyRep (STAR:>STAR) TMaybe
TyApp :: TyRep (a:>b) f -> TyRep a x -> TyRep b (TApp f x)
zero :: TyRep STAR a -> I a
zero x = case x of
TyApp TyMaybe _ -> Nothing
| sdiehl/ghc | testsuite/tests/dependent/should_compile/T14749.hs | bsd-3-clause | 702 | 0 | 10 | 192 | 325 | 176 | 149 | 19 | 1 |
module Language.Mecha.Assembly
( Assembly
, part
, assemble
, Scene
, Camera (..)
, view
, animate
) where
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Digest.CRC32
import Language.Mecha.Solid
import Language.Mecha.Types
import System.Directory
import System.Process
import Text.Printf
-- | An Assembly holds all the parts and sub-assemblies.
data Assembly
= Assembly [Assembly]
| Part Solid
| Label String Assembly
deriving Eq
-- | General assembly.
class Assemble a where assemble :: a -> Assembly
instance Assemble Assembly where assemble = id
instance Assemble Solid where assemble = Part
instance Assemble a => Assemble [a] where assemble = Assembly . map assemble
-- | A general model transformer.
class SMap a where smap :: (Solid -> Solid) -> a -> a
instance SMap Solid where smap = ($)
instance SMap Assembly where
smap f a = case a of
Assembly a -> Assembly $ map (smap f) a
Part a -> Part $ smap f a
Label n a -> Label n $ smap f a
instance Colorable Assembly where color c = smap . color c
instance Moveable Assembly where
move a = smap . move a
rotateX a = smap . rotateX a
rotateY a = smap . rotateY a
rotateZ a = smap . rotateZ a
instance Scaleable Assembly where scale v = smap . scale v
-- | A Scene is a light position, camera configuration, and an assembly.
type Scene = (Camera, Asm)
-- | Defines a camera configuration.
data Camera
= Orthographic -- ^ Orthographgic projection at the origin with a radius.
| Perspective -- ^ Perspective projection given a camera location and a target.
deriving Eq
-- | Renders 3 orthographic views and 1 perspective view and creates a little html page or the images. Assembly should be within 1 of origin.
view :: FilePath -> Int -> Int -> Asm -> IO ()
view f h w a = do
writeFile (f ++ ".html") $ unlines
[ printf "<table border=\"1\">"
, printf "<tr><td><img src=\"%sTop.png\"/></td><td><img src=\"%sPersp.png\"/></td></tr>\n" f f
, printf "<tr><td><img src=\"%sFront.png\"/></td><td><img src=\"%sRight.png\"/></td></tr>\n" f f
, printf "</table>"
]
render (f ++ "Top") h w Orthographic $ rotateX (pi/2) a
render (f ++ "Front") h w Orthographic $ a
render (f ++ "Right") h w Orthographic $ rotateZ (-pi/2) a
render (f ++ "Persp") h w Perspective $ moveY 1 $ rotateX (pi/4) $ rotateZ (-pi/6) a
-- | Renders a MPEG movie with POVRay and ffmpeg given a file name (w/o file extension), heigth, width, frames-per-second, and a list of scenes.
animate :: FilePath -> Int -> Int -> Int -> [Scene] -> IO ()
animate file h w fps scenes = do
sequence_ [ printf "[ %d of %d ]\n" i n >> render (printf "%s%05d" file i) h w camera asm | (i, (camera, asm)) <- zip [1 .. n] scenes ]
rm $ file ++ ".mpg"
readProcess "ffmpeg" ["-sameq", "-i", file ++ "%05d.png", "-r", show fps, file ++ ".mpg"] ""
sequence_ [ rm $ printf "%s%05d.png" file i | i <- [1 .. n] ]
where
n = length scenes
-- | Renders a scene.
render :: String -> Int -> Int -> Camera -> Asm -> IO ()
render file h w camera (Asm a) = do
ln image link
a <- doesFileExist image
when (not a) $ do
writeFile (file ++ ".pov") povray'
readProcess "povray" ["-D", "-V", "+H" ++ show h, "+W" ++ show w, "+I" ++ file ++ ".pov", "+O" ++ image] ""
--rm $ file ++ ".pov"
return ()
where
checksum = printf "%08X" $ crc32 $ BS.pack $ show (h, w, povray')
image = checksum ++ ".png"
link = file ++ ".png"
r :: Double
r = fromIntegral w / fromIntegral h
povray' :: String
povray' = unlines
[ "#include \"colors.inc\""
, "background { color White }"
, printf "light_source { <100, 100, -100> color White }"
, case camera of
Perspective -> printf "camera { perspective location <0, 0, 0> right x*%f direction <0, 0, 1> }" r
Orthographic -> printf "camera { orthographic location <0,0,-100> up y*1 right x*%f }" r
] ++ concatMap povray a
rm :: FilePath -> IO ()
rm f = system ("rm -f " ++ f) >> return ()
ln :: FilePath -> FilePath -> IO ()
ln a b = system ("ln -f -s " ++ a ++ " " ++ b) >> return ()
| tomahawkins/mecha | attic/Assembly.hs | bsd-3-clause | 4,171 | 0 | 13 | 983 | 1,319 | 678 | 641 | 88 | 2 |
module Aws.S3.Commands.HeadObject
where
import Aws.Core
import Aws.S3.Core
import Control.Applicative
import Control.Monad.Trans.Resource (throwM)
import Data.ByteString.Char8 ({- IsString -})
import qualified Data.ByteString.Char8 as B8
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.HTTP.Conduit as HTTP
import qualified Network.HTTP.Types as HTTP
data HeadObject
= HeadObject {
hoBucket :: Bucket
, hoObjectName :: Object
, hoVersionId :: Maybe T.Text
}
deriving (Show)
headObject :: Bucket -> T.Text -> HeadObject
headObject b o = HeadObject b o Nothing
data HeadObjectResponse
= HeadObjectResponse {
horMetadata :: Maybe ObjectMetadata
}
data HeadObjectMemoryResponse
= HeadObjectMemoryResponse (Maybe ObjectMetadata)
deriving (Show)
-- | ServiceConfiguration: 'S3Configuration'
instance SignQuery HeadObject where
type ServiceConfiguration HeadObject = S3Configuration
signQuery HeadObject {..} = s3SignQuery S3Query {
s3QMethod = Head
, s3QBucket = Just $ T.encodeUtf8 hoBucket
, s3QObject = Just $ T.encodeUtf8 hoObjectName
, s3QSubresources = HTTP.toQuery [
("versionId" :: B8.ByteString,) <$> hoVersionId
]
, s3QQuery = []
, s3QContentType = Nothing
, s3QContentMd5 = Nothing
, s3QAmzHeaders = []
, s3QOtherHeaders = []
, s3QRequestBody = Nothing
}
instance ResponseConsumer HeadObject HeadObjectResponse where
type ResponseMetadata HeadObjectResponse = S3Metadata
responseConsumer HeadObject{..} _ resp
| status == HTTP.status200 = HeadObjectResponse . Just <$> parseObjectMetadata headers
| status == HTTP.status404 = return $ HeadObjectResponse Nothing
| otherwise = throwM $ HTTP.StatusCodeException status headers cookies
where
status = HTTP.responseStatus resp
headers = HTTP.responseHeaders resp
cookies = HTTP.responseCookieJar resp
instance Transaction HeadObject HeadObjectResponse
instance AsMemoryResponse HeadObjectResponse where
type MemoryResponse HeadObjectResponse = HeadObjectMemoryResponse
loadToMemory (HeadObjectResponse om) = return (HeadObjectMemoryResponse om)
| Soostone/aws | Aws/S3/Commands/HeadObject.hs | bsd-3-clause | 2,739 | 0 | 13 | 937 | 528 | 297 | 231 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}
-- #3437
-- When we do SpecConstr on 'go', we want the specialised
-- function to *still* be strict in k. Otherwise we get
-- a bad space leak!
-- The test is run with +RTS -M10m to limit the amount of heap
-- It should run in constant space, but if the function isn't
-- strict enough it'll run out of heap
module Main where
go :: [Int] -> [Int] -> [Int]
go (0:xs) !k = k
go (n:xs) !k = go (n-1 : xs) (k ++ k)
main = print (go [100000000] [])
| sdiehl/ghc | testsuite/tests/simplCore/should_run/T3437.hs | bsd-3-clause | 505 | 0 | 8 | 110 | 115 | 66 | 49 | 7 | 1 |
{-
(c) The AQUA Project, Glasgow University, 1993-1998
\section[CoreMonad]{The core pipeline monad}
-}
{-# LANGUAGE CPP, UndecidableInstances #-}
module CoreMonad (
-- * Configuration of the core-to-core passes
CoreToDo(..), runWhen, runMaybe,
SimplifierMode(..),
FloatOutSwitches(..),
pprPassDetails,
-- * Plugins
PluginPass, bindsOnlyPass,
-- * Counting
SimplCount, doSimplTick, doFreeSimplTick, simplCountN,
pprSimplCount, plusSimplCount, zeroSimplCount,
isZeroSimplCount, hasDetailedCounts, Tick(..),
-- * The monad
CoreM, runCoreM,
-- ** Reading from the monad
getHscEnv, getRuleBase, getModule,
getDynFlags, getOrigNameCache, getPackageFamInstEnv,
getVisibleOrphanMods,
getPrintUnqualified, getSrcSpanM,
-- ** Writing to the monad
addSimplCount,
-- ** Lifting into the monad
liftIO, liftIOWithCount,
liftIO1, liftIO2, liftIO3, liftIO4,
-- ** Global initialization
reinitializeGlobals,
-- ** Dealing with annotations
getAnnotations, getFirstAnnotations,
-- ** Screen output
putMsg, putMsgS, errorMsg, errorMsgS, warnMsg,
fatalErrorMsg, fatalErrorMsgS,
debugTraceMsg, debugTraceMsgS,
dumpIfSet_dyn,
#ifdef GHCI
-- * Getting 'Name's
thNameToGhcName
#endif
) where
#ifdef GHCI
import Name( Name )
import TcRnMonad ( initTcForLookup )
#endif
import CoreSyn
import HscTypes
import Module
import DynFlags
import StaticFlags
import BasicTypes ( CompilerPhase(..) )
import Annotations
import IOEnv hiding ( liftIO, failM, failWithM )
import qualified IOEnv ( liftIO )
import TcEnv ( lookupGlobal )
import Var
import Outputable
import FastString
import qualified ErrUtils as Err
import ErrUtils( Severity(..) )
import Maybes
import UniqSupply
import UniqFM ( UniqFM, mapUFM, filterUFM )
import MonadUtils
import SrcLoc
import ListSetOps ( runs )
import Data.List
import Data.Ord
import Data.Dynamic
import Data.IORef
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Word
import qualified Control.Applicative as A
import Control.Monad
import Prelude hiding ( read )
#ifdef GHCI
import Control.Concurrent.MVar (MVar)
import Linker ( PersistentLinkerState, saveLinkerGlobals, restoreLinkerGlobals )
import {-# SOURCE #-} TcSplice ( lookupThName_maybe )
import qualified Language.Haskell.TH as TH
#else
saveLinkerGlobals :: IO ()
saveLinkerGlobals = return ()
restoreLinkerGlobals :: () -> IO ()
restoreLinkerGlobals () = return ()
#endif
{-
************************************************************************
* *
The CoreToDo type and related types
Abstraction of core-to-core passes to run.
* *
************************************************************************
-}
data CoreToDo -- These are diff core-to-core passes,
-- which may be invoked in any order,
-- as many times as you like.
= CoreDoSimplify -- The core-to-core simplifier.
Int -- Max iterations
SimplifierMode
| CoreDoPluginPass String PluginPass
| CoreDoFloatInwards
| CoreDoFloatOutwards FloatOutSwitches
| CoreLiberateCase
| CoreDoPrintCore
| CoreDoStaticArgs
| CoreDoCallArity
| CoreDoStrictness
| CoreDoWorkerWrapper
| CoreDoSpecialising
| CoreDoSpecConstr
| CoreCSE
| CoreDoRuleCheck CompilerPhase String -- Check for non-application of rules
-- matching this string
| CoreDoVectorisation
| CoreDoNothing -- Useful when building up
| CoreDoPasses [CoreToDo] -- lists of these things
| CoreDesugar -- Right after desugaring, no simple optimisation yet!
| CoreDesugarOpt -- CoreDesugarXXX: Not strictly a core-to-core pass, but produces
-- Core output, and hence useful to pass to endPass
| CoreTidy
| CorePrep
instance Outputable CoreToDo where
ppr (CoreDoSimplify _ _) = ptext (sLit "Simplifier")
ppr (CoreDoPluginPass s _) = ptext (sLit "Core plugin: ") <+> text s
ppr CoreDoFloatInwards = ptext (sLit "Float inwards")
ppr (CoreDoFloatOutwards f) = ptext (sLit "Float out") <> parens (ppr f)
ppr CoreLiberateCase = ptext (sLit "Liberate case")
ppr CoreDoStaticArgs = ptext (sLit "Static argument")
ppr CoreDoCallArity = ptext (sLit "Called arity analysis")
ppr CoreDoStrictness = ptext (sLit "Demand analysis")
ppr CoreDoWorkerWrapper = ptext (sLit "Worker Wrapper binds")
ppr CoreDoSpecialising = ptext (sLit "Specialise")
ppr CoreDoSpecConstr = ptext (sLit "SpecConstr")
ppr CoreCSE = ptext (sLit "Common sub-expression")
ppr CoreDoVectorisation = ptext (sLit "Vectorisation")
ppr CoreDesugar = ptext (sLit "Desugar (before optimization)")
ppr CoreDesugarOpt = ptext (sLit "Desugar (after optimization)")
ppr CoreTidy = ptext (sLit "Tidy Core")
ppr CorePrep = ptext (sLit "CorePrep")
ppr CoreDoPrintCore = ptext (sLit "Print core")
ppr (CoreDoRuleCheck {}) = ptext (sLit "Rule check")
ppr CoreDoNothing = ptext (sLit "CoreDoNothing")
ppr (CoreDoPasses {}) = ptext (sLit "CoreDoPasses")
pprPassDetails :: CoreToDo -> SDoc
pprPassDetails (CoreDoSimplify n md) = vcat [ ptext (sLit "Max iterations =") <+> int n
, ppr md ]
pprPassDetails _ = Outputable.empty
data SimplifierMode -- See comments in SimplMonad
= SimplMode
{ sm_names :: [String] -- Name(s) of the phase
, sm_phase :: CompilerPhase
, sm_rules :: Bool -- Whether RULES are enabled
, sm_inline :: Bool -- Whether inlining is enabled
, sm_case_case :: Bool -- Whether case-of-case is enabled
, sm_eta_expand :: Bool -- Whether eta-expansion is enabled
}
instance Outputable SimplifierMode where
ppr (SimplMode { sm_phase = p, sm_names = ss
, sm_rules = r, sm_inline = i
, sm_eta_expand = eta, sm_case_case = cc })
= ptext (sLit "SimplMode") <+> braces (
sep [ ptext (sLit "Phase =") <+> ppr p <+>
brackets (text (concat $ intersperse "," ss)) <> comma
, pp_flag i (sLit "inline") <> comma
, pp_flag r (sLit "rules") <> comma
, pp_flag eta (sLit "eta-expand") <> comma
, pp_flag cc (sLit "case-of-case") ])
where
pp_flag f s = ppUnless f (ptext (sLit "no")) <+> ptext s
data FloatOutSwitches = FloatOutSwitches {
floatOutLambdas :: Maybe Int, -- ^ Just n <=> float lambdas to top level, if
-- doing so will abstract over n or fewer
-- value variables
-- Nothing <=> float all lambdas to top level,
-- regardless of how many free variables
-- Just 0 is the vanilla case: float a lambda
-- iff it has no free vars
floatOutConstants :: Bool, -- ^ True <=> float constants to top level,
-- even if they do not escape a lambda
floatOutOverSatApps :: Bool -- ^ True <=> float out over-saturated applications
-- based on arity information.
-- See Note [Floating over-saturated applications]
-- in SetLevels
}
instance Outputable FloatOutSwitches where
ppr = pprFloatOutSwitches
pprFloatOutSwitches :: FloatOutSwitches -> SDoc
pprFloatOutSwitches sw
= ptext (sLit "FOS") <+> (braces $
sep $ punctuate comma $
[ ptext (sLit "Lam =") <+> ppr (floatOutLambdas sw)
, ptext (sLit "Consts =") <+> ppr (floatOutConstants sw)
, ptext (sLit "OverSatApps =") <+> ppr (floatOutOverSatApps sw) ])
-- The core-to-core pass ordering is derived from the DynFlags:
runWhen :: Bool -> CoreToDo -> CoreToDo
runWhen True do_this = do_this
runWhen False _ = CoreDoNothing
runMaybe :: Maybe a -> (a -> CoreToDo) -> CoreToDo
runMaybe (Just x) f = f x
runMaybe Nothing _ = CoreDoNothing
{-
Note [RULEs enabled in SimplGently]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
RULES are enabled when doing "gentle" simplification. Two reasons:
* We really want the class-op cancellation to happen:
op (df d1 d2) --> $cop3 d1 d2
because this breaks the mutual recursion between 'op' and 'df'
* I wanted the RULE
lift String ===> ...
to work in Template Haskell when simplifying
splices, so we get simpler code for literal strings
But watch out: list fusion can prevent floating. So use phase control
to switch off those rules until after floating.
************************************************************************
* *
Types for Plugins
* *
************************************************************************
-}
-- | A description of the plugin pass itself
type PluginPass = ModGuts -> CoreM ModGuts
bindsOnlyPass :: (CoreProgram -> CoreM CoreProgram) -> ModGuts -> CoreM ModGuts
bindsOnlyPass pass guts
= do { binds' <- pass (mg_binds guts)
; return (guts { mg_binds = binds' }) }
{-
************************************************************************
* *
Counting and logging
* *
************************************************************************
-}
verboseSimplStats :: Bool
verboseSimplStats = opt_PprStyle_Debug -- For now, anyway
zeroSimplCount :: DynFlags -> SimplCount
isZeroSimplCount :: SimplCount -> Bool
hasDetailedCounts :: SimplCount -> Bool
pprSimplCount :: SimplCount -> SDoc
doSimplTick :: DynFlags -> Tick -> SimplCount -> SimplCount
doFreeSimplTick :: Tick -> SimplCount -> SimplCount
plusSimplCount :: SimplCount -> SimplCount -> SimplCount
data SimplCount
= VerySimplCount !Int -- Used when don't want detailed stats
| SimplCount {
ticks :: !Int, -- Total ticks
details :: !TickCounts, -- How many of each type
n_log :: !Int, -- N
log1 :: [Tick], -- Last N events; <= opt_HistorySize,
-- most recent first
log2 :: [Tick] -- Last opt_HistorySize events before that
-- Having log1, log2 lets us accumulate the
-- recent history reasonably efficiently
}
type TickCounts = Map Tick Int
simplCountN :: SimplCount -> Int
simplCountN (VerySimplCount n) = n
simplCountN (SimplCount { ticks = n }) = n
zeroSimplCount dflags
-- This is where we decide whether to do
-- the VerySimpl version or the full-stats version
| dopt Opt_D_dump_simpl_stats dflags
= SimplCount {ticks = 0, details = Map.empty,
n_log = 0, log1 = [], log2 = []}
| otherwise
= VerySimplCount 0
isZeroSimplCount (VerySimplCount n) = n==0
isZeroSimplCount (SimplCount { ticks = n }) = n==0
hasDetailedCounts (VerySimplCount {}) = False
hasDetailedCounts (SimplCount {}) = True
doFreeSimplTick tick sc@SimplCount { details = dts }
= sc { details = dts `addTick` tick }
doFreeSimplTick _ sc = sc
doSimplTick dflags tick
sc@(SimplCount { ticks = tks, details = dts, n_log = nl, log1 = l1 })
| nl >= historySize dflags = sc1 { n_log = 1, log1 = [tick], log2 = l1 }
| otherwise = sc1 { n_log = nl+1, log1 = tick : l1 }
where
sc1 = sc { ticks = tks+1, details = dts `addTick` tick }
doSimplTick _ _ (VerySimplCount n) = VerySimplCount (n+1)
-- Don't use Map.unionWith because that's lazy, and we want to
-- be pretty strict here!
addTick :: TickCounts -> Tick -> TickCounts
addTick fm tick = case Map.lookup tick fm of
Nothing -> Map.insert tick 1 fm
Just n -> n1 `seq` Map.insert tick n1 fm
where
n1 = n+1
plusSimplCount sc1@(SimplCount { ticks = tks1, details = dts1 })
sc2@(SimplCount { ticks = tks2, details = dts2 })
= log_base { ticks = tks1 + tks2, details = Map.unionWith (+) dts1 dts2 }
where
-- A hackish way of getting recent log info
log_base | null (log1 sc2) = sc1 -- Nothing at all in sc2
| null (log2 sc2) = sc2 { log2 = log1 sc1 }
| otherwise = sc2
plusSimplCount (VerySimplCount n) (VerySimplCount m) = VerySimplCount (n+m)
plusSimplCount _ _ = panic "plusSimplCount"
-- We use one or the other consistently
pprSimplCount (VerySimplCount n) = ptext (sLit "Total ticks:") <+> int n
pprSimplCount (SimplCount { ticks = tks, details = dts, log1 = l1, log2 = l2 })
= vcat [ptext (sLit "Total ticks: ") <+> int tks,
blankLine,
pprTickCounts dts,
if verboseSimplStats then
vcat [blankLine,
ptext (sLit "Log (most recent first)"),
nest 4 (vcat (map ppr l1) $$ vcat (map ppr l2))]
else Outputable.empty
]
pprTickCounts :: Map Tick Int -> SDoc
pprTickCounts counts
= vcat (map pprTickGroup groups)
where
groups :: [[(Tick,Int)]] -- Each group shares a comon tag
-- toList returns common tags adjacent
groups = runs same_tag (Map.toList counts)
same_tag (tick1,_) (tick2,_) = tickToTag tick1 == tickToTag tick2
pprTickGroup :: [(Tick, Int)] -> SDoc
pprTickGroup group@((tick1,_):_)
= hang (int (sum [n | (_,n) <- group]) <+> text (tickString tick1))
2 (vcat [ int n <+> pprTickCts tick
-- flip as we want largest first
| (tick,n) <- sortBy (flip (comparing snd)) group])
pprTickGroup [] = panic "pprTickGroup"
data Tick
= PreInlineUnconditionally Id
| PostInlineUnconditionally Id
| UnfoldingDone Id
| RuleFired FastString -- Rule name
| LetFloatFromLet
| EtaExpansion Id -- LHS binder
| EtaReduction Id -- Binder on outer lambda
| BetaReduction Id -- Lambda binder
| CaseOfCase Id -- Bndr on *inner* case
| KnownBranch Id -- Case binder
| CaseMerge Id -- Binder on outer case
| AltMerge Id -- Case binder
| CaseElim Id -- Case binder
| CaseIdentity Id -- Case binder
| FillInCaseDefault Id -- Case binder
| BottomFound
| SimplifierDone -- Ticked at each iteration of the simplifier
instance Outputable Tick where
ppr tick = text (tickString tick) <+> pprTickCts tick
instance Eq Tick where
a == b = case a `cmpTick` b of
EQ -> True
_ -> False
instance Ord Tick where
compare = cmpTick
tickToTag :: Tick -> Int
tickToTag (PreInlineUnconditionally _) = 0
tickToTag (PostInlineUnconditionally _) = 1
tickToTag (UnfoldingDone _) = 2
tickToTag (RuleFired _) = 3
tickToTag LetFloatFromLet = 4
tickToTag (EtaExpansion _) = 5
tickToTag (EtaReduction _) = 6
tickToTag (BetaReduction _) = 7
tickToTag (CaseOfCase _) = 8
tickToTag (KnownBranch _) = 9
tickToTag (CaseMerge _) = 10
tickToTag (CaseElim _) = 11
tickToTag (CaseIdentity _) = 12
tickToTag (FillInCaseDefault _) = 13
tickToTag BottomFound = 14
tickToTag SimplifierDone = 16
tickToTag (AltMerge _) = 17
tickString :: Tick -> String
tickString (PreInlineUnconditionally _) = "PreInlineUnconditionally"
tickString (PostInlineUnconditionally _)= "PostInlineUnconditionally"
tickString (UnfoldingDone _) = "UnfoldingDone"
tickString (RuleFired _) = "RuleFired"
tickString LetFloatFromLet = "LetFloatFromLet"
tickString (EtaExpansion _) = "EtaExpansion"
tickString (EtaReduction _) = "EtaReduction"
tickString (BetaReduction _) = "BetaReduction"
tickString (CaseOfCase _) = "CaseOfCase"
tickString (KnownBranch _) = "KnownBranch"
tickString (CaseMerge _) = "CaseMerge"
tickString (AltMerge _) = "AltMerge"
tickString (CaseElim _) = "CaseElim"
tickString (CaseIdentity _) = "CaseIdentity"
tickString (FillInCaseDefault _) = "FillInCaseDefault"
tickString BottomFound = "BottomFound"
tickString SimplifierDone = "SimplifierDone"
pprTickCts :: Tick -> SDoc
pprTickCts (PreInlineUnconditionally v) = ppr v
pprTickCts (PostInlineUnconditionally v)= ppr v
pprTickCts (UnfoldingDone v) = ppr v
pprTickCts (RuleFired v) = ppr v
pprTickCts LetFloatFromLet = Outputable.empty
pprTickCts (EtaExpansion v) = ppr v
pprTickCts (EtaReduction v) = ppr v
pprTickCts (BetaReduction v) = ppr v
pprTickCts (CaseOfCase v) = ppr v
pprTickCts (KnownBranch v) = ppr v
pprTickCts (CaseMerge v) = ppr v
pprTickCts (AltMerge v) = ppr v
pprTickCts (CaseElim v) = ppr v
pprTickCts (CaseIdentity v) = ppr v
pprTickCts (FillInCaseDefault v) = ppr v
pprTickCts _ = Outputable.empty
cmpTick :: Tick -> Tick -> Ordering
cmpTick a b = case (tickToTag a `compare` tickToTag b) of
GT -> GT
EQ -> cmpEqTick a b
LT -> LT
cmpEqTick :: Tick -> Tick -> Ordering
cmpEqTick (PreInlineUnconditionally a) (PreInlineUnconditionally b) = a `compare` b
cmpEqTick (PostInlineUnconditionally a) (PostInlineUnconditionally b) = a `compare` b
cmpEqTick (UnfoldingDone a) (UnfoldingDone b) = a `compare` b
cmpEqTick (RuleFired a) (RuleFired b) = a `compare` b
cmpEqTick (EtaExpansion a) (EtaExpansion b) = a `compare` b
cmpEqTick (EtaReduction a) (EtaReduction b) = a `compare` b
cmpEqTick (BetaReduction a) (BetaReduction b) = a `compare` b
cmpEqTick (CaseOfCase a) (CaseOfCase b) = a `compare` b
cmpEqTick (KnownBranch a) (KnownBranch b) = a `compare` b
cmpEqTick (CaseMerge a) (CaseMerge b) = a `compare` b
cmpEqTick (AltMerge a) (AltMerge b) = a `compare` b
cmpEqTick (CaseElim a) (CaseElim b) = a `compare` b
cmpEqTick (CaseIdentity a) (CaseIdentity b) = a `compare` b
cmpEqTick (FillInCaseDefault a) (FillInCaseDefault b) = a `compare` b
cmpEqTick _ _ = EQ
{-
************************************************************************
* *
Monad and carried data structure definitions
* *
************************************************************************
-}
newtype CoreState = CoreState {
cs_uniq_supply :: UniqSupply
}
data CoreReader = CoreReader {
cr_hsc_env :: HscEnv,
cr_rule_base :: RuleBase,
cr_module :: Module,
cr_print_unqual :: PrintUnqualified,
cr_loc :: SrcSpan, -- Use this for log/error messages so they
-- are at least tagged with the right source file
cr_visible_orphan_mods :: !ModuleSet,
#ifdef GHCI
cr_globals :: (MVar PersistentLinkerState, Bool)
#else
cr_globals :: ()
#endif
}
-- Note: CoreWriter used to be defined with data, rather than newtype. If it
-- is defined that way again, the cw_simpl_count field, at least, must be
-- strict to avoid a space leak (Trac #7702).
newtype CoreWriter = CoreWriter {
cw_simpl_count :: SimplCount
}
emptyWriter :: DynFlags -> CoreWriter
emptyWriter dflags = CoreWriter {
cw_simpl_count = zeroSimplCount dflags
}
plusWriter :: CoreWriter -> CoreWriter -> CoreWriter
plusWriter w1 w2 = CoreWriter {
cw_simpl_count = (cw_simpl_count w1) `plusSimplCount` (cw_simpl_count w2)
}
type CoreIOEnv = IOEnv CoreReader
-- | The monad used by Core-to-Core passes to access common state, register simplification
-- statistics and so on
newtype CoreM a = CoreM { unCoreM :: CoreState -> CoreIOEnv (a, CoreState, CoreWriter) }
instance Functor CoreM where
fmap f ma = do
a <- ma
return (f a)
instance Monad CoreM where
return x = CoreM (\s -> nop s x)
mx >>= f = CoreM $ \s -> do
(x, s', w1) <- unCoreM mx s
(y, s'', w2) <- unCoreM (f x) s'
let w = w1 `plusWriter` w2
return $ seq w (y, s'', w)
-- forcing w before building the tuple avoids a space leak
-- (Trac #7702)
instance A.Applicative CoreM where
pure = return
(<*>) = ap
(*>) = (>>)
instance MonadPlus IO => A.Alternative CoreM where
empty = mzero
(<|>) = mplus
-- For use if the user has imported Control.Monad.Error from MTL
-- Requires UndecidableInstances
instance MonadPlus IO => MonadPlus CoreM where
mzero = CoreM (const mzero)
m `mplus` n = CoreM (\rs -> unCoreM m rs `mplus` unCoreM n rs)
instance MonadUnique CoreM where
getUniqueSupplyM = do
us <- getS cs_uniq_supply
let (us1, us2) = splitUniqSupply us
modifyS (\s -> s { cs_uniq_supply = us2 })
return us1
getUniqueM = do
us <- getS cs_uniq_supply
let (u,us') = takeUniqFromSupply us
modifyS (\s -> s { cs_uniq_supply = us' })
return u
runCoreM :: HscEnv
-> RuleBase
-> UniqSupply
-> Module
-> ModuleSet
-> PrintUnqualified
-> SrcSpan
-> CoreM a
-> IO (a, SimplCount)
runCoreM hsc_env rule_base us mod orph_imps print_unqual loc m
= do { glbls <- saveLinkerGlobals
; liftM extract $ runIOEnv (reader glbls) $ unCoreM m state }
where
reader glbls = CoreReader {
cr_hsc_env = hsc_env,
cr_rule_base = rule_base,
cr_module = mod,
cr_visible_orphan_mods = orph_imps,
cr_globals = glbls,
cr_print_unqual = print_unqual,
cr_loc = loc
}
state = CoreState {
cs_uniq_supply = us
}
extract :: (a, CoreState, CoreWriter) -> (a, SimplCount)
extract (value, _, writer) = (value, cw_simpl_count writer)
{-
************************************************************************
* *
Core combinators, not exported
* *
************************************************************************
-}
nop :: CoreState -> a -> CoreIOEnv (a, CoreState, CoreWriter)
nop s x = do
r <- getEnv
return (x, s, emptyWriter $ (hsc_dflags . cr_hsc_env) r)
read :: (CoreReader -> a) -> CoreM a
read f = CoreM (\s -> getEnv >>= (\r -> nop s (f r)))
getS :: (CoreState -> a) -> CoreM a
getS f = CoreM (\s -> nop s (f s))
modifyS :: (CoreState -> CoreState) -> CoreM ()
modifyS f = CoreM (\s -> nop (f s) ())
write :: CoreWriter -> CoreM ()
write w = CoreM (\s -> return ((), s, w))
-- \subsection{Lifting IO into the monad}
-- | Lift an 'IOEnv' operation into 'CoreM'
liftIOEnv :: CoreIOEnv a -> CoreM a
liftIOEnv mx = CoreM (\s -> mx >>= (\x -> nop s x))
instance MonadIO CoreM where
liftIO = liftIOEnv . IOEnv.liftIO
-- | Lift an 'IO' operation into 'CoreM' while consuming its 'SimplCount'
liftIOWithCount :: IO (SimplCount, a) -> CoreM a
liftIOWithCount what = liftIO what >>= (\(count, x) -> addSimplCount count >> return x)
{-
************************************************************************
* *
Reader, writer and state accessors
* *
************************************************************************
-}
getHscEnv :: CoreM HscEnv
getHscEnv = read cr_hsc_env
getRuleBase :: CoreM RuleBase
getRuleBase = read cr_rule_base
getVisibleOrphanMods :: CoreM ModuleSet
getVisibleOrphanMods = read cr_visible_orphan_mods
getPrintUnqualified :: CoreM PrintUnqualified
getPrintUnqualified = read cr_print_unqual
getSrcSpanM :: CoreM SrcSpan
getSrcSpanM = read cr_loc
addSimplCount :: SimplCount -> CoreM ()
addSimplCount count = write (CoreWriter { cw_simpl_count = count })
-- Convenience accessors for useful fields of HscEnv
instance HasDynFlags CoreM where
getDynFlags = fmap hsc_dflags getHscEnv
instance HasModule CoreM where
getModule = read cr_module
-- | The original name cache is the current mapping from 'Module' and
-- 'OccName' to a compiler-wide unique 'Name'
getOrigNameCache :: CoreM OrigNameCache
getOrigNameCache = do
nameCacheRef <- fmap hsc_NC getHscEnv
liftIO $ fmap nsNames $ readIORef nameCacheRef
getPackageFamInstEnv :: CoreM PackageFamInstEnv
getPackageFamInstEnv = do
hsc_env <- getHscEnv
eps <- liftIO $ hscEPS hsc_env
return $ eps_fam_inst_env eps
{-
************************************************************************
* *
Initializing globals
* *
************************************************************************
This is a rather annoying function. When a plugin is loaded, it currently
gets linked against a *newly loaded* copy of the GHC package. This would
not be a problem, except that the new copy has its own mutable state
that is not shared with that state that has already been initialized by
the original GHC package.
(NB This mechanism is sufficient for granting plugins read-only access to
globals that are guaranteed to be initialized before the plugin is loaded. If
any further synchronization is necessary, I would suggest using the more
sophisticated mechanism involving GHC.Conc.Sync.sharedCAF and rts/Globals.c to
share a single instance of the global variable among the compiler and the
plugins. Perhaps we should migrate all global variables to use that mechanism,
for robustness... -- NSF July 2013)
This leads to loaded plugins calling GHC code which pokes the static flags,
and then dying with a panic because the static flags *it* sees are uninitialized.
There are two possible solutions:
1. Export the symbols from the GHC executable from the GHC library and link
against this existing copy rather than a new copy of the GHC library
2. Carefully ensure that the global state in the two copies of the GHC
library matches
I tried 1. and it *almost* works (and speeds up plugin load times!) except
on Windows. On Windows the GHC library tends to export more than 65536 symbols
(see #5292) which overflows the limit of what we can export from the EXE and
causes breakage.
(Note that if the GHC executable was dynamically linked this wouldn't be a
problem, because we could share the GHC library it links to.)
We are going to try 2. instead. Unfortunately, this means that every plugin
will have to say `reinitializeGlobals` before it does anything, but never mind.
I've threaded the cr_globals through CoreM rather than giving them as an
argument to the plugin function so that we can turn this function into
(return ()) without breaking any plugins when we eventually get 1. working.
-}
reinitializeGlobals :: CoreM ()
reinitializeGlobals = do
linker_globals <- read cr_globals
hsc_env <- getHscEnv
let dflags = hsc_dflags hsc_env
liftIO $ restoreLinkerGlobals linker_globals
liftIO $ setUnsafeGlobalDynFlags dflags
{-
************************************************************************
* *
Dealing with annotations
* *
************************************************************************
-}
-- | Get all annotations of a given type. This happens lazily, that is
-- no deserialization will take place until the [a] is actually demanded and
-- the [a] can also be empty (the UniqFM is not filtered).
--
-- This should be done once at the start of a Core-to-Core pass that uses
-- annotations.
--
-- See Note [Annotations]
getAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM [a])
getAnnotations deserialize guts = do
hsc_env <- getHscEnv
ann_env <- liftIO $ prepareAnnotations hsc_env (Just guts)
return (deserializeAnns deserialize ann_env)
-- | Get at most one annotation of a given type per Unique.
getFirstAnnotations :: Typeable a => ([Word8] -> a) -> ModGuts -> CoreM (UniqFM a)
getFirstAnnotations deserialize guts
= liftM (mapUFM head . filterUFM (not . null))
$ getAnnotations deserialize guts
{-
Note [Annotations]
~~~~~~~~~~~~~~~~~~
A Core-to-Core pass that wants to make use of annotations calls
getAnnotations or getFirstAnnotations at the beginning to obtain a UniqFM with
annotations of a specific type. This produces all annotations from interface
files read so far. However, annotations from interface files read during the
pass will not be visible until getAnnotations is called again. This is similar
to how rules work and probably isn't too bad.
The current implementation could be optimised a bit: when looking up
annotations for a thing from the HomePackageTable, we could search directly in
the module where the thing is defined rather than building one UniqFM which
contains all annotations we know of. This would work because annotations can
only be given to things defined in the same module. However, since we would
only want to deserialise every annotation once, we would have to build a cache
for every module in the HTP. In the end, it's probably not worth it as long as
we aren't using annotations heavily.
************************************************************************
* *
Direct screen output
* *
************************************************************************
-}
msg :: Severity -> SDoc -> CoreM ()
msg sev doc
= do { dflags <- getDynFlags
; loc <- getSrcSpanM
; unqual <- getPrintUnqualified
; let sty = case sev of
SevError -> err_sty
SevWarning -> err_sty
SevDump -> dump_sty
_ -> user_sty
err_sty = mkErrStyle dflags unqual
user_sty = mkUserStyle unqual AllTheWay
dump_sty = mkDumpStyle unqual
; liftIO $
(log_action dflags) dflags sev loc sty doc }
-- | Output a String message to the screen
putMsgS :: String -> CoreM ()
putMsgS = putMsg . text
-- | Output a message to the screen
putMsg :: SDoc -> CoreM ()
putMsg = msg SevInfo
-- | Output a string error to the screen
errorMsgS :: String -> CoreM ()
errorMsgS = errorMsg . text
-- | Output an error to the screen
errorMsg :: SDoc -> CoreM ()
errorMsg = msg SevError
warnMsg :: SDoc -> CoreM ()
warnMsg = msg SevWarning
-- | Output a fatal string error to the screen. Note this does not by itself cause the compiler to die
fatalErrorMsgS :: String -> CoreM ()
fatalErrorMsgS = fatalErrorMsg . text
-- | Output a fatal error to the screen. Note this does not by itself cause the compiler to die
fatalErrorMsg :: SDoc -> CoreM ()
fatalErrorMsg = msg SevFatal
-- | Output a string debugging message at verbosity level of @-v@ or higher
debugTraceMsgS :: String -> CoreM ()
debugTraceMsgS = debugTraceMsg . text
-- | Outputs a debugging message at verbosity level of @-v@ or higher
debugTraceMsg :: SDoc -> CoreM ()
debugTraceMsg = msg SevDump
-- | Show some labelled 'SDoc' if a particular flag is set or at a verbosity level of @-v -ddump-most@ or higher
dumpIfSet_dyn :: DumpFlag -> String -> SDoc -> CoreM ()
dumpIfSet_dyn flag str doc
= do { dflags <- getDynFlags
; unqual <- getPrintUnqualified
; when (dopt flag dflags) $ liftIO $
Err.dumpSDoc dflags unqual flag str doc }
{-
************************************************************************
* *
Finding TyThings
* *
************************************************************************
-}
instance MonadThings CoreM where
lookupThing name = do { hsc_env <- getHscEnv
; liftIO $ lookupGlobal hsc_env name }
{-
************************************************************************
* *
Template Haskell interoperability
* *
************************************************************************
-}
#ifdef GHCI
-- | Attempt to convert a Template Haskell name to one that GHC can
-- understand. Original TH names such as those you get when you use
-- the @'foo@ syntax will be translated to their equivalent GHC name
-- exactly. Qualified or unqualifed TH names will be dynamically bound
-- to names in the module being compiled, if possible. Exact TH names
-- will be bound to the name they represent, exactly.
thNameToGhcName :: TH.Name -> CoreM (Maybe Name)
thNameToGhcName th_name = do
hsc_env <- getHscEnv
liftIO $ initTcForLookup hsc_env (lookupThName_maybe th_name)
#endif
| acowley/ghc | compiler/simplCore/CoreMonad.hs | bsd-3-clause | 35,003 | 0 | 18 | 10,746 | 6,643 | 3,577 | 3,066 | -1 | -1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE AutoDeriveTypeable #-}
{-# LANGUAGE StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Complex
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Complex numbers.
--
-----------------------------------------------------------------------------
module Data.Complex
(
-- * Rectangular form
Complex((:+))
, realPart
, imagPart
-- * Polar form
, mkPolar
, cis
, polar
, magnitude
, phase
-- * Conjugate
, conjugate
) where
import Prelude
import Data.Typeable
import Data.Data (Data)
infix 6 :+
-- -----------------------------------------------------------------------------
-- The Complex type
-- | Complex numbers are an algebraic type.
--
-- For a complex number @z@, @'abs' z@ is a number with the magnitude of @z@,
-- but oriented in the positive real direction, whereas @'signum' z@
-- has the phase of @z@, but unit magnitude.
data Complex a
= !a :+ !a -- ^ forms a complex number from its real and imaginary
-- rectangular components.
deriving (Eq, Show, Read, Data, Typeable)
-- -----------------------------------------------------------------------------
-- Functions over Complex
-- | Extracts the real part of a complex number.
realPart :: Complex a -> a
realPart (x :+ _) = x
-- | Extracts the imaginary part of a complex number.
imagPart :: Complex a -> a
imagPart (_ :+ y) = y
-- | The conjugate of a complex number.
{-# SPECIALISE conjugate :: Complex Double -> Complex Double #-}
conjugate :: Num a => Complex a -> Complex a
conjugate (x:+y) = x :+ (-y)
-- | Form a complex number from polar components of magnitude and phase.
{-# SPECIALISE mkPolar :: Double -> Double -> Complex Double #-}
mkPolar :: Floating a => a -> a -> Complex a
mkPolar r theta = r * cos theta :+ r * sin theta
-- | @'cis' t@ is a complex value with magnitude @1@
-- and phase @t@ (modulo @2*'pi'@).
{-# SPECIALISE cis :: Double -> Complex Double #-}
cis :: Floating a => a -> Complex a
cis theta = cos theta :+ sin theta
-- | The function 'polar' takes a complex number and
-- returns a (magnitude, phase) pair in canonical form:
-- the magnitude is nonnegative, and the phase in the range @(-'pi', 'pi']@;
-- if the magnitude is zero, then so is the phase.
{-# SPECIALISE polar :: Complex Double -> (Double,Double) #-}
polar :: (RealFloat a) => Complex a -> (a,a)
polar z = (magnitude z, phase z)
-- | The nonnegative magnitude of a complex number.
{-# SPECIALISE magnitude :: Complex Double -> Double #-}
magnitude :: (RealFloat a) => Complex a -> a
magnitude (x:+y) = scaleFloat k
(sqrt (sqr (scaleFloat mk x) + sqr (scaleFloat mk y)))
where k = max (exponent x) (exponent y)
mk = - k
sqr z = z * z
-- | The phase of a complex number, in the range @(-'pi', 'pi']@.
-- If the magnitude is zero, then so is the phase.
{-# SPECIALISE phase :: Complex Double -> Double #-}
phase :: (RealFloat a) => Complex a -> a
phase (0 :+ 0) = 0 -- SLPJ July 97 from John Peterson
phase (x:+y) = atan2 y x
-- -----------------------------------------------------------------------------
-- Instances of Complex
instance (RealFloat a) => Num (Complex a) where
{-# SPECIALISE instance Num (Complex Float) #-}
{-# SPECIALISE instance Num (Complex Double) #-}
(x:+y) + (x':+y') = (x+x') :+ (y+y')
(x:+y) - (x':+y') = (x-x') :+ (y-y')
(x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x')
negate (x:+y) = negate x :+ negate y
abs z = magnitude z :+ 0
signum (0:+0) = 0
signum z@(x:+y) = x/r :+ y/r where r = magnitude z
fromInteger n = fromInteger n :+ 0
instance (RealFloat a) => Fractional (Complex a) where
{-# SPECIALISE instance Fractional (Complex Float) #-}
{-# SPECIALISE instance Fractional (Complex Double) #-}
(x:+y) / (x':+y') = (x*x''+y*y'') / d :+ (y*x''-x*y'') / d
where x'' = scaleFloat k x'
y'' = scaleFloat k y'
k = - max (exponent x') (exponent y')
d = x'*x'' + y'*y''
fromRational a = fromRational a :+ 0
instance (RealFloat a) => Floating (Complex a) where
{-# SPECIALISE instance Floating (Complex Float) #-}
{-# SPECIALISE instance Floating (Complex Double) #-}
pi = pi :+ 0
exp (x:+y) = expx * cos y :+ expx * sin y
where expx = exp x
log z = log (magnitude z) :+ phase z
sqrt (0:+0) = 0
sqrt z@(x:+y) = u :+ (if y < 0 then -v else v)
where (u,v) = if x < 0 then (v',u') else (u',v')
v' = abs y / (u'*2)
u' = sqrt ((magnitude z + abs x) / 2)
sin (x:+y) = sin x * cosh y :+ cos x * sinh y
cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y)
tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))
where sinx = sin x
cosx = cos x
sinhy = sinh y
coshy = cosh y
sinh (x:+y) = cos y * sinh x :+ sin y * cosh x
cosh (x:+y) = cos y * cosh x :+ sin y * sinh x
tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)
where siny = sin y
cosy = cos y
sinhx = sinh x
coshx = cosh x
asin z@(x:+y) = y':+(-x')
where (x':+y') = log (((-y):+x) + sqrt (1 - z*z))
acos z = y'':+(-x'')
where (x'':+y'') = log (z + ((-y'):+x'))
(x':+y') = sqrt (1 - z*z)
atan z@(x:+y) = y':+(-x')
where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))
asinh z = log (z + sqrt (1+z*z))
acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))
atanh z = 0.5 * log ((1.0+z) / (1.0-z))
| frantisekfarka/ghc-dsi | libraries/base/Data/Complex.hs | bsd-3-clause | 6,522 | 2 | 14 | 2,171 | 1,944 | 1,036 | 908 | 111 | 1 |
-- GHC 6.7 at one point said wog's type was:
--
-- wog :: forall t e (m :: * -> *).
-- (Monad GHC.Prim.Any1, Monad m) =>
-- t -> Something (m Bool) e
--
-- The stupid 'GHC.Prim.Any1' arose because of type ambiguity
-- which should be reported, and wasn't.
module ShouldFail where
data Something d e = Something{ bar:: d, initializer::e }
foo :: (Monad m) => Something (m Bool) n
foo = undefined
wog x = foo{bar = return True}
| ezyang/ghc | testsuite/tests/typecheck/should_fail/tcfail181.hs | bsd-3-clause | 457 | 0 | 8 | 115 | 84 | 52 | 32 | 5 | 1 |
{-# LANGUAGE ViewPatterns #-}
module Haks.NGram where
import BasicPrelude
import Data.Foldable hiding (concat)
import Haks.Types
ngram :: Int -> [Particle] -> [NGram]
ngram _ [] = []
ngram n particles = item : (ngram n rest)
where
item = concat $ toList (take n particles)
rest = drop 1 particles
| mlitchard/haks | src/Haks/NGram.hs | isc | 311 | 0 | 10 | 64 | 113 | 62 | 51 | 10 | 1 |
import Test.Tasty
import Test.Tasty.Golden
import System.FilePath
import qualified Data.ByteString.Lazy.Char8 as LBS
all_numbers, non_square_numbers :: [Int]
all_numbers = [1..1000]
non_square_numbers = filter (\x -> (round . sqrt . fromIntegral) x ^ 2 /= x) all_numbers
all_numbers_str = LBS.pack $ unlines $ map show all_numbers
non_square_numbers_str = LBS.pack $ unlines $ map show non_square_numbers
diff ref new = ["diff", ref, new]
main = defaultMain $ localOption (SizeCutoff 140) $ testGroup "Tests"
[ testGroup (if success then "Successful tests" else "Failing tests") $
let
dir = "example/golden" </> if success then "success" else "fail"
value = if success then all_numbers_str else non_square_numbers_str
in
[ let
golden = dir </> "goldenVsFile.golden"
actual = dir </> "goldenVsFile.actual"
in
goldenVsFile "goldenVsFile" golden actual
(createDirectoriesAndWriteFile actual value)
, let
golden = dir </> "goldenVsFileDiff.golden"
actual = dir </> "goldenVsFileDiff.actual"
in
goldenVsFileDiff "goldenVsFileDiff" diff golden actual
(createDirectoriesAndWriteFile actual value)
, let
golden = dir </> "goldenVsString.golden"
in
goldenVsString "goldenVsString" golden (return value)
, let
golden = dir </> "goldenVsStringDiff.golden"
in
goldenVsStringDiff "goldenVsStringDiff" diff golden (return value)
]
| success <- [True, False]
]
| feuerbach/tasty-golden | example/example.hs | mit | 1,518 | 0 | 16 | 347 | 398 | 212 | 186 | 32 | 4 |
module Network.Sendgrid.Utils
( urlEncode
) where
import Data.Char ( digitToInt, intToDigit, toLower, isDigit,
isAscii, isAlphaNum )
urlEncode :: String -> String
urlEncode [] = []
urlEncode (ch:t)
| (isAscii ch && isAlphaNum ch) || ch `elem` "-_.~" = ch : urlEncode t
| not (isAscii ch) = foldr escape (urlEncode t) (eightBs [] (fromEnum ch))
| otherwise = escape (fromEnum ch) (urlEncode t)
where
escape b rs = '%':showH (b `div` 16) (showH (b `mod` 16) rs)
showH x xs
| x <= 9 = toEnum (o_0 + x) : xs
| otherwise = toEnum (o_A + (x-10)) : xs
where
o_0 = fromEnum '0'
o_A = fromEnum 'A'
eightBs :: [Int] -> Int -> [Int]
eightBs acc x
| x <= 0xff = (x:acc)
| otherwise = eightBs ((x `mod` 256) : acc) (x `div` 256)
| owainlewis/sendgrid-hs | src/Network/Sendgrid/Utils.hs | mit | 833 | 0 | 13 | 254 | 396 | 206 | 190 | 20 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.DOMSettableTokenList
(js__get, _get, js_setValue, setValue, js_getValue, getValue,
DOMSettableTokenList, castToDOMSettableTokenList,
gTypeDOMSettableTokenList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"_get\"]($2)" js__get ::
JSRef DOMSettableTokenList -> Word -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMSettableTokenList._get Mozilla DOMSettableTokenList._get documentation>
_get ::
(MonadIO m, FromJSString result) =>
DOMSettableTokenList -> Word -> m (Maybe result)
_get self index
= liftIO
(fromMaybeJSString <$>
(js__get (unDOMSettableTokenList self) index))
foreign import javascript unsafe "$1[\"value\"] = $2;" js_setValue
:: JSRef DOMSettableTokenList -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMSettableTokenList.value Mozilla DOMSettableTokenList.value documentation>
setValue ::
(MonadIO m, ToJSString val) => DOMSettableTokenList -> val -> m ()
setValue self val
= liftIO
(js_setValue (unDOMSettableTokenList self) (toJSString val))
foreign import javascript unsafe "$1[\"value\"]" js_getValue ::
JSRef DOMSettableTokenList -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMSettableTokenList.value Mozilla DOMSettableTokenList.value documentation>
getValue ::
(MonadIO m, FromJSString result) =>
DOMSettableTokenList -> m result
getValue self
= liftIO
(fromJSString <$> (js_getValue (unDOMSettableTokenList self))) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/DOMSettableTokenList.hs | mit | 2,422 | 22 | 11 | 356 | 592 | 349 | 243 | 43 | 1 |
{-#LANGUAGE OverloadedStrings #-}
module WebServer where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Map.Strict as Map
import qualified System.FilePath as FP
import qualified Network.URL as URL
import Data.String.Conversions
import Data.Maybe
import Data.List
import Data.Word
import Network.HTTP.Server
import Network.HTTP.Server.Logger
import Network.Mime
import Control.Monad
import Control.Monad.Reader
import Control.Monad.IO.Class
import Control.Monad.Trans.Maybe
import System.Directory
import System.Environment
import SimpleArgvParser
data ServerSettings = ServerSettings { webRoot :: FP.FilePath, port :: Int }
data FileResponse =
PermissionDenied String
| FileNotFound String
| FileOK String
| RedirectToIndex
type ServerMonad = ReaderT ServerSettings IO
headers :: [Header]
headers = [Header HdrPragma "no-cache"
, Header HdrConnection "close"
, Header HdrServer "HashtagViewerWebServer"]
redirectHeaders :: Int -> [Header]
redirectHeaders port = [Header HdrPragma "no-cache"
, Header HdrConnection "keep-alive"
, Header HdrLocation $ "http://localhost:" ++ (show port) ++ "/index.html"
, Header HdrServer "HashtagViewerWebServer"]
respondForFile :: FileResponse -> ServerMonad (Response BL.ByteString)
respondForFile (PermissionDenied path) = return $ Response (4,0,3) "Permission denied" headers $ BL.append "Permission denied: " (cs path)
respondForFile (FileNotFound path) = return $ Response (4,0,4) "File not found" headers $ BL.append "File not found: " (cs path)
respondForFile RedirectToIndex = do
port <- asks port
return $ Response (3,0,1) "Moved Permanently" (redirectHeaders port) "Redirect"
respondForFile (FileOK path) = do
contents <- liftIO $ BL.readFile path
return $ Response (2,0,0) "Ok" modifiedHeaders contents
where
mimeTypeHeader = Header HdrContentType $ cs $ defaultMimeLookup (cs path)
modifiedHeaders = mimeTypeHeader:headers
getResponseForFile :: String -> ServerMonad FileResponse
getResponseForFile urlPath | urlPath == "" = return RedirectToIndex
getResponseForFile urlPath = (asks webRoot) >>= (getFileResponse urlPath)
where
isPathAllowed canonicalPath webRoot = isPrefixOf (FP.splitPath webRoot) (FP.splitPath canonicalPath)
urlPathToSystemPath urlPath = (FP.joinPath . FP.splitPath) urlPath
getFileResponse urlPath webRoot = liftIO $ do
candidatePath <- canonicalizePath $ FP.combine webRoot $ urlPathToSystemPath urlPath
if isPathAllowed candidatePath webRoot
then do
exists <- doesFileExist candidatePath
if exists
then (getPermissions candidatePath) >>=
(\perms -> if readable perms
then return $ FileOK candidatePath
else return $ PermissionDenied urlPath)
else return $ FileNotFound urlPath
else return $ PermissionDenied urlPath
doRespond :: URL.URL -> ServerMonad (Response BL.ByteString)
doRespond url = do
file <- getResponseForFile $ URL.url_path url
respondForFile file
handler :: URL.URL -> Request BL.ByteString -> ServerMonad (Response BL.ByteString)
handler url req = case rqMethod req of
GET -> doRespond url
_ -> return $ err_response NotImplemented
getPortFromArgs :: (Num a) => Map.Map String String -> a
getPortFromArgs argMap = case Map.lookup "port" argMap of
Just port -> fromIntegral (read port :: Integer)
Nothing -> 8001
getBindAddressFromArgs :: Map.Map String String -> String
getBindAddressFromArgs argMap = fromMaybe "localhost" $ Map.lookup "bind" argMap
makeServerConfig :: Map.Map String String -> Config
makeServerConfig argMap = Config stdLogger (getBindAddressFromArgs argMap) (getPortFromArgs argMap)
getWebRoot :: Map.Map String String -> MaybeT IO FP.FilePath
getWebRoot argMap = MaybeT $ mapM canonicalizePath $ Map.lookup "root" argMap
main :: IO ()
main = do
args <- getArgs
maybe (putStrLn usage) handleArgMap (pairArguments args)
where
handleArgMap argMap = do
fullWebRootPath <- runMaybeT (getWebRoot argMap)
case fullWebRootPath of
Just path -> serverWith (makeServerConfig argMap) $ handler' path (getPortFromArgs argMap)
Nothing -> putStrLn usage
usage = "./WebServer --root <web_root> [--port <port>] [--bind <address>]"
handler' webRoot port _ url req = runReaderT (handler url req) (ServerSettings webRoot port)
| davidfontenot/haskell-hashtag-viewer | src/WebServer.hs | mit | 4,597 | 0 | 19 | 947 | 1,274 | 652 | 622 | 94 | 4 |
import qualified Data.Map as M
type Index = Int
data Load
= Get -- going in accepting mode
| Set -- using an accepting mode
| Known Index -- telling others who is on the air
data Message = Message Index Load
data Operation = Scanning [Index] | Accepting [Index] | Operation [Index] [Index] [Index]
incoming :: [Bool] -- random stream (True is transmit)
-> Index -- id of the node
-> Operation -- node state
-> Maybe Message -- a message is on the air
-> (Operation, Maybe Message, [Bool]) -- (new state for the node, a possible message production, the left random stream)
-- while scanning, known ids' are collected
incoming rs k (Scanning is) (Just (Message _ (Known j))) = (Scanning (j:is), Nothing,rs)
-- while scanning, receiving a Get, trigger a Set message, and put the node in Operation state with the collected ids'
incoming rs k (Scanning is) (Just (Message j Get)) = (Operation is is [],Just (Message k Set),rs)
-- what ever received or not leave the node in Scanning state
incoming rs k (Scanning is) _ = (Scanning is, Nothing,rs)
-- while accepting, if a Set message is received, the id is collected and we go into Operation state
incoming rs k (Accepting is) (Just (Message j Set)) = (Operation (j:is) (j:is) [], Nothing,rs)
-- we go into Operation state anyway
incoming rs k (Accepting is) _ = (Operation is is [], Nothing,rs)
-- while in Operation, if we spit out all the known ids and nothing was collected we go in Scanning mode
incoming rs k (Operation _ [] []) _ = (Scanning [],Nothing,rs)
-- while in Operation, if we spit out all the known ids and something was collected we go in Accepting mode and trigger a Get message
incoming rs k (Operation _ [] zs) _ = (Accepting zs , Just (Message k Get),rs)
-- when known ids are left, if the next boolean is true we spit it out else we do nothing aside consuming the boolean
incoming (r:rs) k (Operation is (j:js) zs) (Just (Message i (Known w))) =
let zs' = if i `elem` is then w:zs else zs
(m,js') = if r then (Just (Message k (Known j)),js) else (Nothing,j:js)
in (Operation is js' zs', m, rs)
| paolino/touchnet | Message.hs | mit | 2,221 | 0 | 15 | 539 | 642 | 354 | 288 | 24 | 3 |
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
module Data.NGH.Formats.Tests.Gff
( tests ) where
import Test.Framework.TH
import Test.HUnit
import Test.QuickCheck
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Data.Maybe
import Data.NGH.Annotation
import Data.NGH.Formats.Gff
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as L8
test_file = "\
\##gff-version 3\n\
\##sequence-region Pf3D7_01_v3 1 640851\n\
\Pf3D7_01_v3\tchado\trepeat_region\t1\t360\t.\t+\t.\tID=Pfalciparum_REP_20;isObsolete=false;feature_id=20734007;timelastmodified=07.09.2011+06:34:16+BST\n\
\Pf3D7_01_v3\tchado\trepeat_region\t361\t1418\t.\t+\t.\tID=Pfalciparum_REP_15;isObsolete=false;feature_id=20734008;timelastmodified=07.09.2011+06:34:16+BST\n\
\Pf3D7_01_v3\tchado\trepeat_region\t2160\t3858\t.\t+\t.\tID=Pfalciparum_REP_35;isObsolete=false;feature_id=20734009;timelastmodified=07.09.2011+06:34:16+BST\n\
\Pf3D7_01_v3\tchado\trepeat_region\t8856\t9021\t.\t+\t.\tID=Pfalciparum_REP_5;isObsolete=false;feature_id=20734010;timelastmodified=07.09.2011+06:34:16+BST\n\
\Pf3D7_01_v3\tchado\trepeat_region\t9313\t9529\t.\t+\t.\tID=Pfalciparum_REP_25;isObsolete=false;feature_id=20734011;timelastmodified=07.09.2011+06:34:16+BST\n\
\Pf3D7_01_v3\tchado\trepeat_region\t11315\t27336\t.\t+\t.\tID=Pfalciparum_REP_55;isObsolete=false;feature_id=20734013;timelastmodified=07.09.2011+06:34:17+BST\n\
\Pf3D7_01_v3\tchado\tgene\t29510\t37126\t.\t+\t.\tID=PF3D7_0100100;Name=VAR;isObsolete=false;feature_id=20734001;timelastmodified=07.09.2011+06:34:15+BST\n\
\Pf3D7_01_v3\tchado\tCDS\t29510\t34762\t.\t+\t.\tID=PF3D7_0100100.1:exon:1;Parent=PF3D7_0100100.1;isObsolete=false;timelastmodified=07.09.2011+06:34:18+BST\n\
\Pf3D7_01_v3\tchado\tCDS\t35888\t37126\t.\t+\t.\tID=PF3D7_0100100.1:exon:2;Parent=PF3D7_0100100.1;isObsolete=false;timelastmodified=07.09.2011+06:34:18+BST\n\
\Pf3D7_01_v3\tchado\tmRNA\t29510\t37126\t.\t+\t.\tID=PF3D7_0100100.1;Parent=PF3D7_0100100;isObsolete=false;feature_id=20731410;timelastmodified=07.09.2011+06:13:46+BST\n\
\Pf3D7_01_v3\tchado\tpolypeptide\t29510\t37126\t.\t+\t.\tID=PF3D7_0100100.1:pep;Derives_from=PF3D7_0100100.1\n\
\Pf3D7_01_v3\tchado\tpolypeptide_motif\t29568\t29581\t.\t+\t.\tID=chr01:motif:1;isObsolete=false;feature_id=20734020;literature=PMID:16507167\n\
\Pf3D7_01_v3\tchado\tgene\t38982\t40207\t.\t-\t.\tID=PF3D7_0100200;Name=RIF;isObsolete=false;feature_id=20725865;timelastmodified=07.09.2011+05:28:48+BST\n\
\Pf3D7_01_v3\tchado\tCDS\t40154\t40207\t.\t-\t.\tID=PF3D7_0100200.1:exon:2;Parent=PF3D7_0100200.1;isObsolete=false;timelastmodified=07.09.2011+06:34:19+BST\n\
\Pf3D7_01_v3\tchado\tCDS\t38982\t39923\t.\t-\t.\tID=PF3D7_0100200.1:exon:1;Parent=PF3D7_0100200.1;isObsolete=false;timelastmodified=07.09.2011+06:34:19+BST\n\
\Pf3D7_01_v3\tchado\tmRNA\t38982\t40207\t.\t-\t.\tID=PF3D7_0100200.1;Parent=PF3D7_0100200;isObsolete=false;feature_id=20725864;timelastmodified=07.09.2011+05:28:47+BST\n\
\Pf3D7_01_v3\tchado\tpolypeptide\t38982\t40207\t.\t-\t.\tID=PF3D7_0100200.1:pep;Derives_from=PF3D7_0100200.1;Dbxref=UniProtKB:Q9NFB5%2CMPMP:cytoadherencescheme.html%2CMPMP:rosetting.html\n\
\Pf3D7_01_v3\tchado\tpolypeptide_motif\t39847\t39860\t.\t-\t.\tID=chr01:motif:2;Parent=PF3D7_0100200.1;Note=PEXEL;isObsolete=false;timelastmodified=07.09.2011+06:34:21+BST\n\
\Pf3D7_01_v3\tchado\tgene\t42367\t46507\t.\t-\t.\tID=PF3D7_0100300;isObsolete=false;feature_id=20725861;timelastmodified=07.09.2011+05:28:46+BST;previous_systematic_id=PFA0015c\n\
\Pf3D7_01_v3\tchado\tCDS\t43775\t46507\t.\t-\t.\tID=PF3D7_0100300.1:exon:2;Parent=PF3D7_0100300.1;isObsolete=false;timelastmodified=07.09.2011+06:34:20+BST;colour=2"
annotations = readAnnotations test_file
tests = $(testGroupGenerator)
case_all = (length annotations) @?= ((length $ L8.lines test_file) - 2)
case_genes = (length genes) @?= 3
where
genes = filter ((== GffGene) . gffType) annotations
| luispedro/NGH | Data/NGH/Formats/Tests/Gff.hs | mit | 4,057 | 0 | 11 | 212 | 176 | 109 | 67 | 19 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Api.ResourceContent
(
apiGetResourceContent
, apiUpdateResourceContent
)
where
import qualified Data.ByteString.Lazy as BSL
( fromStrict, toStrict, empty )
import qualified Data.Text as T ( Text )
import qualified Data.Text.Lazy as TL
( fromStrict )
import Network.HTTP.Types.Status ( ok200, noContent204, notFound404 )
import Web.Scotty.Trans ( body )
import ApiUtility ( RawResponse(..), runApiRaw, readKey, liftDB, liftWeb, validateDbExists, apiFail )
import Core ( BrandyActionM )
import DataAccess.ResourceContent ( dbGetResourceContent, dbUpdateResourceContent )
apiGetResourceContent :: T.Text -> BrandyActionM ()
apiGetResourceContent keyText =
runApiRaw ok200 $ do
key <- readKey keyText
maybeDb <- liftDB $ dbGetResourceContent key
validateDbExists (toRawResponse <$> maybeDb)
where
toRawResponse (ct, bv) = RawResponse (Just $ TL.fromStrict ct) (BSL.fromStrict bv)
apiUpdateResourceContent :: T.Text -> BrandyActionM ()
apiUpdateResourceContent keyText =
runApiRaw noContent204 $ do
key <- readKey keyText
bv <- liftWeb body
found <- liftDB $ dbUpdateResourceContent key $ BSL.toStrict bv
if found
then return $ RawResponse Nothing BSL.empty
else apiFail notFound404 "Not found."
| stu-smith/Brandy | src/Api/ResourceContent.hs | mit | 1,471 | 0 | 11 | 392 | 352 | 193 | 159 | 31 | 2 |
-- Project: dka-2-mka (FLP 2016/2017)
-- Author: Dávid Mikuš (xmikus15)
module Parser.Config where
import Type.Config
parseArguments :: [String] -> Either String Config
parseArguments [] = Left $ "Missing arguments"
parseArguments [_] = Left $ "Missing arguments"
parseArguments [x,y]
| x == "-t" = Right $ Config Minimize y
| x == "-i" = Right $ Config Dump y
| x == "-f" = Right $ Config MinimizeN y
| otherwise = Left $ "Unknown argument"
parseArguments _ = Left $ "Too many arguments"
| Dasio/FIT-Projects | FLP/Parser/Config.hs | mit | 510 | 0 | 8 | 102 | 161 | 81 | 80 | 11 | 1 |
module TransportTestSuite
(
transportTestSuite,
testTransportEndpointSendReceive,
testTransportEndpointSend2Receive2,
testTransportEndpointSendReceive2SerialServers,
testTransportEndpointSendReceive2SerialClients,
testTransportOneHearCall,
testTransportOneCallHear,
testTransportConcurrentCallHear,
testTransportOneHandler,
testTransportTwoHandlers,
testTransportGroupCall,
testTransportAnyCall,
module TestUtils
)
where
-- local imports
import Network.Endpoints
import Network.RPC
import Network.Transport
import TestUtils
-- external imports
import Control.Concurrent.Async
import qualified Data.Map as M
import Data.Serialize
import Test.Framework
import Test.HUnit
import Test.Framework.Providers.HUnit
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
transportTestSuite :: IO Transport -> String -> Name -> Name -> Name -> Name -> [Test.Framework.Test]
transportTestSuite transport transportLabel name1 name2 name3 name4 = [
testCase (transportLabel ++ "-sendReceive") $
testTransportEndpointSendReceive transport name1 name2,
testCase (transportLabel ++ "-send2Receive2") $
testTransportEndpointSend2Receive2 transport name1 name2,
testCase (transportLabel ++ "-sendReceive-2-serial-servers") $
testTransportEndpointSendReceive2SerialServers transport name1 name2,
testCase (transportLabel ++ "-sendReceive-2-serial-clients") $
testTransportEndpointSendReceive2SerialClients transport name1 name2,
testCase (transportLabel ++ "-withClient-withServer") $
testWithClientWithServer transport name1 name2,
testCase (transportLabel ++ "-rpc-one-hear-call") $
testTransportOneHearCall transport name1 name2,
testCase (transportLabel ++ "-rpc-one-call-hear") $
testTransportOneCallHear transport name1 name2,
testCase (transportLabel ++ "-rpc-concurrent-call-hear") $
testTransportConcurrentCallHear transport name1 name2,
testCase (transportLabel ++ "-rpc-one-handler") $
testTransportOneHandler transport name1 name2,
testCase (transportLabel ++ "-rpc-two-handlers") $
testTransportTwoHandlers transport name1 name2,
testCase (transportLabel ++ "-rpc-group-call") $
testTransportGroupCall transport name1 name2 name3 name4,
testCase (transportLabel ++ "-rpc-any-call") $
testTransportAnyCall transport name1 name2 name3 name4
]
timeLimited :: Assertion -> Assertion
timeLimited assn = timeBound (2 * 1000000 :: Int) assn
testTransportEndpointSendReceive :: IO Transport -> Name -> Name -> Assertion
testTransportEndpointSendReceive transportFactory name1 name2 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint2 transport $ \endpoint1 endpoint2 -> do
withBinding2 transport (endpoint1,name1) (endpoint2,name2) $ do
withConnection transport endpoint1 name2 $ do
sendMessage endpoint1 name2 $ encode "hello!"
msg <- receiveMessage endpoint2
assertEqual "Received message not same as sent" (Right "hello!") (decode msg)
return ()
testTransportEndpointSend2Receive2 :: IO Transport -> Name -> Name -> Assertion
testTransportEndpointSend2Receive2 transportFactory name1 name2 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint2 transport $ \endpoint1 endpoint2 -> do
withBinding2 transport (endpoint1,name1) (endpoint2,name2) $ do
withConnection transport endpoint1 name2 $ do
sendMessage endpoint1 name2 $ encode "hello!"
msg1 <- receiveMessage endpoint2
assertEqual "Received message not same as sent" (Right "hello!") (decode msg1)
sendMessage endpoint1 name2 $ encode "ciao!"
msg2 <- receiveMessage endpoint2
assertEqual "Received message not same as sent" (Right "ciao!") (decode msg2)
return ()
testTransportEndpointSendReceive2SerialServers :: IO Transport -> Name -> Name -> Assertion
testTransportEndpointSendReceive2SerialServers transportFactory name1 name2 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint2 transport $ \endpoint1 endpoint2 -> do
withName endpoint1 name1 $ do
withBinding transport endpoint2 name2 $ do
withConnection transport endpoint1 name2 $ do
sendMessage endpoint1 name2 $ encode "hello!"
msg <- receiveMessage endpoint2
assertEqual "Received message not same as sent" (Right "hello!") (decode msg)
return ()
withBinding transport endpoint2 name2 $ do
withConnection transport endpoint1 name2 $ do
sendMessage endpoint1 name2 $ encode "hello!"
msg <- receiveMessage endpoint2
assertEqual "Received message not same as sent" (Right "hello!") (decode msg)
return ()
testTransportEndpointSendReceive2SerialClients :: IO Transport -> Name -> Name -> Assertion
testTransportEndpointSendReceive2SerialClients transportFactory name1 name2 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint2 transport $ \endpoint1 endpoint2 ->
withBinding transport endpoint2 name2 $ do
withName endpoint1 name1 $
withConnection transport endpoint1 name2 $ do
sendMessage endpoint1 name2 $ encode "hello!"
msg <- receiveMessage endpoint2
assertEqual "Received message not same as sent" (Right "hello!") (decode msg)
return ()
withName endpoint1 name1 $
withConnection transport endpoint1 name2 $ do
sendMessage endpoint1 name2 $ encode "hello!"
msg <- receiveMessage endpoint2
assertEqual "Received message not same as sent" (Right "hello!") (decode msg)
return ()
testWithClientWithServer :: IO Transport -> Name -> Name -> Assertion
testWithClientWithServer transportFactory name1 name2 = timeLimited $ do
sharedTransportFactory <- shareTransport transportFactory
server2 <- async $ withServer sharedTransportFactory name2 $ \_ endpoint2 ->
receiveMessage endpoint2
withClient sharedTransportFactory name1 $ \endpoint1 -> do
transport <- sharedTransportFactory
withConnection transport endpoint1 name2 $ do
sendMessage endpoint1 name2 $ encode "hello!"
msg <- wait server2
assertEqual "Received message not same as sent" (Right "hello!") (decode msg)
return ()
testTransportOneHearCall :: IO Transport -> Name -> Name -> Assertion
testTransportOneHearCall transportFactory name1 name2 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint2 transport $ \endpoint1 endpoint2 ->
withBinding2 transport (endpoint1,name1) (endpoint2,name2) $ do
withConnection transport endpoint1 name2 $
withAsync (do
(bytes,reply) <- hear endpoint2 name2 "foo"
let Right msg = decode bytes
reply $ encode $ msg ++ "!") $ \_ -> do
let cs = newCallSite endpoint1 name1
bytes <- call cs name2 "foo" $ encode "hello"
let Right result = decode bytes
assertEqual "Result not expected value" "hello!" result
testTransportOneCallHear :: IO Transport -> Name -> Name -> Assertion
testTransportOneCallHear transportFactory name1 name2 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint transport $ \endpoint1 ->
withNewEndpoint transport $ \endpoint2 ->
withBinding transport endpoint1 name1 $
withBinding transport endpoint2 name2 $ do
withConnection transport endpoint1 name2 $ do
let cs = newCallSite endpoint1 name1
acall <- async $ call cs name2 "foo" $ encode "hello"
withAsync (do
(bytes,reply) <- hear endpoint2 name2 "foo"
let Right msg = decode bytes
reply $ encode $ msg ++ "!") $ \_ -> do
bytes <- wait acall
let Right result = decode bytes
assertEqual "Result not expected value" "hello!" result
testTransportConcurrentCallHear :: IO Transport -> Name -> Name -> Assertion
testTransportConcurrentCallHear transportFactory name1 name2 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint transport $ \endpoint1 ->
withNewEndpoint transport $ \endpoint2 ->
withBinding transport endpoint1 name1 $
withBinding transport endpoint2 name2 $
withConnection transport endpoint1 name2 $ do
let cs1 = newCallSite endpoint1 name1
cs2 = newCallSite endpoint2 name2
let call1 = call cs1 name2 "foo" $ encode "hello"
hear1 = do
(bytes,reply) <- hear endpoint2 name2 "foo"
let Right msg = decode bytes
reply $ encode $ msg ++ "!"
call2 = call cs2 name1 "bar" $ encode "ciao"
hear2 = do
(bytes,reply) <- hear endpoint1 name1 "bar"
let Right msg = decode bytes
reply $ encode $ msg ++ "!"
(result1,(),result2,()) <- runConcurrently $ (,,,)
<$> Concurrently call1
<*> Concurrently hear1
<*> Concurrently call2
<*> Concurrently hear2
assertEqual "Result not expected value" (Right "hello!") (decode result1)
assertEqual "Result not expected value" (Right "ciao!") (decode result2)
testTransportOneHandler :: IO Transport -> Name -> Name -> Assertion
testTransportOneHandler transportFactory name1 name2 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint transport $ \endpoint1 ->
withNewEndpoint transport $ \endpoint2 ->
withBinding transport endpoint1 name1 $
withBinding transport endpoint2 name2 $
withConnection transport endpoint1 name2 $ do
h <- handle endpoint2 name2 "foo" $ \bytes ->
let Right msg = decode bytes
in return $ encode $ msg ++ "!"
let cs = newCallSite endpoint1 name1
bytes <- call cs name2 "foo" $ encode "hello"
let Right result = decode bytes
assertEqual "Result not expected value" "hello!" result
hangup h
testTransportTwoHandlers :: IO Transport -> Name -> Name -> Assertion
testTransportTwoHandlers transportFactory name1 name2 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint transport $ \endpoint1 ->
withNewEndpoint transport $ \endpoint2 ->
withBinding transport endpoint1 name1 $
withBinding transport endpoint2 name2 $
withConnection transport endpoint1 name2 $ do
h1 <- handle endpoint2 name2 "foo" $ \bytes ->
let Right msg = decode bytes
in return $ encode $ msg ++ "!"
h2 <- handle endpoint2 name2 "bar" $ \bytes ->
let Right msg = decode bytes
in return $ encode $ msg ++ "?"
let cs = newCallSite endpoint1 name1
bytes1 <- call cs name2 "foo" $ encode "hello"
let Right result1 = decode bytes1
assertEqual "Result not expected value" "hello!" result1
bytes2 <- call cs name2 "bar" $ encode "hello"
let Right result2 = decode bytes2
assertEqual "Result not expected value" "hello?" result2
hangup h1
hangup h2
testTransportGroupCall :: IO Transport -> Name -> Name -> Name -> Name -> Assertion
testTransportGroupCall transportFactory name1 name2 name3 name4 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint4 transport $ \endpoint1 endpoint2 endpoint3 endpoint4 -> do
withBinding4 transport (endpoint1,name1) (endpoint2,name2) (endpoint3,name3) (endpoint4,name4) $
withConnection3 transport endpoint1 name2 name3 name4 $ do
h2 <- handle endpoint2 name2 "foo" $ \bytes -> let Right msg = decode bytes in
return $ encode $ if msg == "hello" then "foo" else ""
h3 <- handle endpoint3 name3 "foo" $ \bytes -> let Right msg = decode bytes in
return $ encode $ if msg == "hello" then "bar" else ""
h4 <- handle endpoint4 name4 "foo" $ \bytes -> let Right msg = decode bytes in
return $ encode $ if msg == "hello" then "baz" else ""
let cs = newCallSite endpoint1 name1
results <- (gcall cs [name2,name3,name4] "foo" $ encode "hello")
assertBool "Foo not present in results" (elem (encode "foo") $ M.elems results)
assertBool "Bar not present in results" (elem (encode "bar") $ M.elems results)
assertBool "Bar not present in results" (elem (encode "baz") $ M.elems results)
assertEqual "Unxpected number of results" 3 (M.size results)
hangup h2
hangup h3
hangup h4
testTransportAnyCall :: IO Transport -> Name -> Name -> Name -> Name -> Assertion
testTransportAnyCall transportFactory name1 name2 name3 name4 = timeLimited $ do
withTransport transportFactory $ \transport ->
withNewEndpoint4 transport $ \endpoint1 endpoint2 endpoint3 endpoint4 -> do
withBinding4 transport (endpoint1,name1) (endpoint2,name2) (endpoint3,name3) (endpoint4,name4) $
withConnection3 transport endpoint1 name2 name3 name4 $ do
h2 <- handle endpoint2 name2 "foo" $ \bytes -> let Right msg = decode bytes in
return $ encode $ if msg == "hello" then "foo" else ""
h3 <- handle endpoint3 name3 "foo" $ \bytes -> let Right msg = decode bytes in
return $ encode $ if msg == "hello" then "foo" else ""
h4 <- handle endpoint4 name4 "foo" $ \bytes -> let Right msg = decode bytes in
return $ encode $ if msg == "hello" then "foo" else ""
let cs = newCallSite endpoint1 name1
(result,responder) <- (anyCall cs [name2,name3,name4] "foo" $ encode "hello")
assertEqual "Response should have been 'foo'" (encode "foo") result
assertBool "Responder was not in original list of names" $ elem responder [name2,name3,name4]
hangup h2
hangup h3
hangup h4
| hargettp/courier | tests/TransportTestSuite.hs | mit | 14,842 | 5 | 39 | 4,022 | 3,874 | 1,823 | 2,051 | 259 | 4 |
import Control.Monad (replicateM)
import Ann
main :: IO ()
main = print result
where
width = 10
depth = 10
values = [0, 0.5, 1]
ann = fromList (replicate depth width) (sin <$> [1 ..])
inputs = replicateM width values
results = execute logsig ann <$> inputs
result = sum $ concat results
| tysonzero/hs-ann | list/benchmark.hs | mit | 319 | 0 | 10 | 85 | 123 | 67 | 56 | 11 | 1 |
{- |
Module : $Header$
Description : Handling of simple extended parameters
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : ewaryst.schulz@dfki.de
Stability : experimental
Portability : portable
This module contains a simple extended parameter representation
Extended parameters may be based on one of the following
relations:
> =, <=, >=, !=, <, >, -|
We reduce the relations to one of the Data items in 'NormEP'. We
handle @-|@ as @*@ for comparison and range computations, i.e.,
we remove it, and @< n@ is turned into @<= n-1@
(or @'LeftOf' n-1@) and accordingly for @>@.
We could work more generally (and we do it) as in
CSL.GeneralExtendedParameter .
-}
module CSL.SimpleExtendedParameter where
import CSL.BoolBasic
import CSL.TreePO
import CSL.AS_BASIC_CSL
import Common.Id (tokStr)
import Common.Doc
import Common.DocUtils
-- ----------------------------------------------------------------------
-- * Datatypes for efficient Extended Parameter comparison
-- ----------------------------------------------------------------------
-- | Normalized representation of an extended param relation
data NormEP = LeftOf | RightOf | Equal | Except deriving (Eq, Ord)
instance Show NormEP where
show LeftOf = "<="
show RightOf = ">="
show Equal = "="
show Except = "/="
instance Pretty NormEP where
pretty x = text $ show x
type EPExp = (NormEP, APInt)
cmpOp :: NormEP -> APInt -> APInt -> Bool
cmpOp LeftOf = (<=)
cmpOp RightOf = (>=)
cmpOp Equal= (==)
cmpOp Except = (/=)
evalEP :: Int -> EPExp -> Bool
evalEP i (n, j) = cmpOp n (toInteger i) j
showEP :: (String, EPExp) -> String
showEP (s, (n, i)) = s ++ show n ++ show i
-- | Conversion function into the more efficient representation.
toEPExp :: EXTPARAM -> Maybe (String, EPExp)
toEPExp (EP t r i) =
case r of
"<=" -> Just (tokStr t, (LeftOf, i))
"<" -> Just (tokStr t, (LeftOf, i-1))
">=" -> Just (tokStr t, (RightOf, i))
">" -> Just (tokStr t, (RightOf, i+1))
"=" -> Just (tokStr t, (Equal, i))
"!=" -> Just (tokStr t, (Except, i))
"-|" -> Nothing
_ -> error $ "toEPExp: unsupported relation: " ++ r
toBoolRep :: String -> EPExp -> BoolRep
toBoolRep s (x, i) = Pred (show x) [s, show i]
complementEP :: EPExp -> EPExp
complementEP (x, i) = case x of
LeftOf -> (RightOf, i+1)
RightOf -> (LeftOf, i-1)
Equal -> (Except, i)
Except -> (Equal, i)
-- ----------------------------------------------------------------------
-- * Extended Parameter comparison
-- ----------------------------------------------------------------------
-- | Compares two 'EPExp': They are uncompareable if they overlap or are disjoint.
compareEP :: EPExp -> EPExp -> SetOrdering
compareEP ep1@(r1, n1) ep2@(r2, n2)
| r1 == r2 = compareSameRel r1 n1 n2
| otherwise =
case (r1, r2) of
(Equal, Except) | n1 == n2 -> Incomparable Disjoint
| otherwise -> Comparable LT
(Equal, LeftOf) | n1 > n2 -> Incomparable Disjoint
| otherwise -> Comparable LT
(Equal, RightOf) | n1 < n2 -> Incomparable Disjoint
| otherwise -> Comparable LT
(Except, LeftOf) | n1 > n2 -> Comparable GT
| otherwise -> Incomparable Overlap
(Except, RightOf) | n1 < n2 -> Comparable GT
| otherwise -> Incomparable Overlap
(LeftOf, RightOf) | n1 < n2 -> Incomparable Disjoint
| otherwise -> Incomparable Overlap
_ -> swapCmp $ compareEP ep2 ep1
compareSameRel :: NormEP -> APInt -> APInt -> SetOrdering
compareSameRel r n1 n2
| n1 == n2 = Comparable EQ
| otherwise =
case r of
LeftOf -> Comparable (compare n1 n2)
RightOf -> Comparable (compare n2 n1)
Equal -> Incomparable Disjoint
Except -> Incomparable Overlap
| nevrenato/Hets_Fork | CSL/SimpleExtendedParameter.hs | gpl-2.0 | 4,142 | 0 | 12 | 1,157 | 1,066 | 558 | 508 | 71 | 8 |
module MasterGui where
| imalsogreg/arte-ephys | arte-decoder/exec/MasterGui.hs | gpl-3.0 | 23 | 0 | 2 | 3 | 4 | 3 | 1 | 1 | 0 |
-- Join channels
module Handlers.JoinChannel
( handler
) where
import Network.Socket
import Request
defaultChannel = "#qwerasdf"
joinChannel :: EventHandler
joinChannel _ botState = do
putStrLn "Setting channel"
send socket (formatRequest (Nothing, "JOIN", [defaultChannel]))
return (botState {botChannels = [defaultChannel]})
where socket = botSocket botState
nick = botNick botState
handler = joinChannel
| UndeadMastodon/ShrubBot | Handlers/JoinChannel.hs | gpl-3.0 | 431 | 0 | 11 | 74 | 115 | 63 | 52 | 13 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module RunSchedule
(
-- types
Scheduler(..)
-- functions
, runWorkScheduler
, newSchedulerState
, runWork
) where
import RunAuxiliary
import RunEnvironment
import RunNode
import RunProcess
import RunWork
import RunWorkSet
import Data.Maybe (fromJust, catMaybes, isNothing)
import Data.List (intercalate)
import qualified Data.Set as Set (member)
import Data.Traversable (mapM)
import Data.Time.Clock (getCurrentTime)
import qualified Data.Map.Strict as Map
import Text.Printf (printf)
import qualified System.Process as Process
import System.Posix.Signals (Handler, Handler(CatchOnce), installHandler,
sigINT, sigTERM, raiseSignal)
import System.Random
import Control.Monad (forM_, filterM)
import Control.Monad.Loops (whileM_)
import Control.Monad.Reader
import Control.Monad.State
import Control.Concurrent
import Control.Concurrent.Async
------------------------------------------------------------
-- auxiliary type used during determination of the next work package
-- data of this type contains: (group id, threads, node)
type GroupThreadsNode = (GroupId,NumThreads,AnyNode)
------------------------------------------------------------
data JobData = JobData {
jNode :: AnyNode -- node used for the job
, jThreads :: NumThreads -- number of threads used for the job
, jWork :: AnyWork -- work unit computed by the job
, jHandle :: Async JobResult -- the result of the job is just the job id,
-- and exit status of the job
}
data SchedulerState = SchedulerState {
sdWorkSet :: WorkSet -- remaining work set
, sdNodeThreads :: Map.Map String NumThreads
-- currently available threads for each compute node,
-- accessed by the name of the node
, sdJobs :: Map.Map JobId JobData -- currently running jobs
, sdJobId :: JobId -- counter for job id
, sdProcessStore :: MVar (Map.Map JobId Process.ProcessHandle)
-- store all currently active process handles
, sdRandomGen :: StdGen
}
newtype Scheduler a = Scheduler {
runScheduler :: ReaderT RunEnv (StateT SchedulerState IO) a
} deriving (Functor, Applicative, Monad, MonadIO,
MonadState SchedulerState, MonadReader RunEnv)
------------------------------------------------------------
-- config :: RunEnv
-- state :: SchedulerState
-- runStateT (runReaderT (runScheduler k) config) state
runWorkScheduler :: Scheduler a -> RunEnv -> SchedulerState -> IO a
runWorkScheduler k r s = fst <$> runStateT (runReaderT (runScheduler k) r) s
-- construct a new scheduler state
-- it already set the work set data, but node and thread data are just nulled
newSchedulerState :: WorkSet -> IO SchedulerState
newSchedulerState wm = do
-- to runenv
-- create a lock for atomic IO and a process handle map
-- lockIO <- newMVar ()
pstoreVar <- newMVar Map.empty
-- get a new random number generator
rgen <- newStdGen
return SchedulerState {
sdWorkSet = wm
, sdNodeThreads = Map.empty
, sdJobs = Map.empty
, sdJobId = 0
, sdProcessStore = pstoreVar
, sdRandomGen = rgen
}
-- initialise the map storing available threads for each node
initNodeResources :: Scheduler ()
initNodeResources = do
ntm <- Map.map threadsTotal <$> reader envNodes
modify (\sd -> sd { sdNodeThreads = ntm })
------------------------------------------------------------
-- we are finished if there is no work left and no running jobs left
isFinished :: SchedulerState -> Bool
isFinished sd = null (sdWorkSet sd) && null (sdJobs sd)
getRandom :: SchedulerState -> (Int,SchedulerState)
getRandom sd = let (i,rgen') = random $ sdRandomGen sd
in (i, sd { sdRandomGen = rgen' })
getRandomR :: (Int,Int) -> SchedulerState -> (Int,SchedulerState)
getRandomR r sd = let (i,rgen') = randomR r $ sdRandomGen sd
in (i, sd { sdRandomGen = rgen' })
-- depending on order settings it either returns 0 (for first element)
-- or a random index
getIndex :: Scheduler Int
getIndex = do
isSorted <- reader envExecSorted
if isSorted
then return 0
else state getRandom
getJobId :: Scheduler Int
getJobId = do
jid <- (+1) <$> gets sdJobId
modify (\sd -> sd { sdJobId = jid })
return jid
addJob :: JobId -> JobData -> Scheduler ()
addJob jid jd = do
jobs <- gets sdJobs
let threads = jThreads jd
nd = jNode jd
-- reduce available threads for node
modify $ subThreads nd threads
modify (\sd -> sd { sdJobs = Map.insert jid jd jobs })
-- release the job resources
removeJob :: JobId -> Scheduler ()
removeJob jid = do
jobs <- gets sdJobs
let jd = fromJust $ Map.lookup jid jobs
threads = jThreads jd
nd = jNode jd
-- increase available threads for node
modify $ addThreads nd threads
modify (\sd -> sd { sdJobs = Map.delete jid jobs })
------------------------------------------------------------
schedulerJobIds :: Scheduler [JobId]
schedulerJobIds = gets $ Map.keys . sdJobs
schedulerJobsData :: Scheduler [JobData]
schedulerJobsData = gets $ Map.elems . sdJobs
schedulerJobsAsyncs :: Scheduler [Async JobResult]
schedulerJobsAsyncs = map jHandle <$> schedulerJobsData
getJobById :: JobId -> Scheduler JobData
getJobById jid = do
job_maybe <- gets $ Map.lookup jid . sdJobs
case job_maybe of
Just job -> return job
_ -> error "getJobById: invalid job id"
-- return the number of threads used by a job
schedulerJobsThreads :: JobId -> Scheduler NumThreads
schedulerJobsThreads jid = jThreads <$> getJobById jid
schedulerJobsNode :: JobId -> Scheduler AnyNode
schedulerJobsNode jid = jNode <$> getJobById jid
schedulerJobsWork :: JobId -> Scheduler AnyWork
schedulerJobsWork jid = jWork <$> getJobById jid
------------------------------------------------------------
checkSufficientThreads :: GroupThreadsNode -> Scheduler Bool
checkSufficientThreads (_,threads,nd) = do
let name = nodeName nd
lookupThreads = fromJust . Map.lookup name
tavail <- lookupThreads <$> gets sdNodeThreads
return $ threads <= tavail
-- add available threads for a given node
addThreads :: AnyNode -> NumThreads -> SchedulerState -> SchedulerState
addThreads nd threads sd = sd { sdNodeThreads = nt' }
where nt' = Map.adjust (threads+) (nodeName nd) $ sdNodeThreads sd
-- subtract available threads for a given node
subThreads :: AnyNode -> NumThreads -> SchedulerState -> SchedulerState
subThreads nd threads = addThreads nd (-threads)
supplementThreads :: (GroupId, AnyNode) -> Scheduler GroupThreadsNode
supplementThreads (gid,nd) = do
-- take a random number of threads between tmin and tupper
-- at this point we cannot take available threads into account (for tupper),
-- as otherwise we end up using the tmin number of threads after awhile
-- (if a task with lots of threads is finished we get a small random number and can
-- schedule two or more works with a few threads, now if a work unit with few threads
-- is finished, tupper is small and we use a few number of threads for the new task,
-- and we will never be able to schedule with lots of threads)
let
ttotal = threadsTotal nd
(tmin, tmax) = getThreadsForGroup gid nd
-- use at least tmin, to make sure that the range is proper
tupper = max tmin $ min tmax ttotal
r = (tmin, tupper)
threads <- state $ getRandomR r
return (gid, threads, nd)
-- for each group find all compute nodes which have enough resources to execute
-- a work unit from the given group, return a list of all valid combinations
allGroupThreadsNode :: Scheduler [GroupThreadsNode]
allGroupThreadsNode = do
-- groups which are still present in the workset map
gs <- getWorkSetGroups <$> gets sdWorkSet
-- list of node names available to the scheduler
ns <- Map.keys <$> gets sdNodeThreads
nm <- reader envNodes
-- replace name with complete node
let ns' = map (\n -> fromJust $ Map.lookup n nm) ns
-- get a list of all (gid,threads,nd) tuples, and filter for those combinations,
-- which are valid (node has sufficiently many threads available for the selected number of threads)
gns_all <- mapM supplementThreads [(gid,nd) | gid <- gs, nd <- ns']
filterM checkSufficientThreads gns_all
-- select the next group and node (and the number of threads to use for it),
-- the work unit of the selected group is selected later on
selectGroupThreadsNode :: Scheduler (Maybe GroupThreadsNode)
selectGroupThreadsNode = do
gtns <- allGroupThreadsNode
i <- getIndex
return (fst $ removeList i gtns)
removeWork :: GroupId -> Int -> SchedulerState -> (AnyWork,SchedulerState)
removeWork gid i sd = (w, sd { sdWorkSet = wm' })
where
wm = sdWorkSet sd
gs = head $ filter (Set.member gid) $ Map.keys wm
(Just w, wm') = removeMapLists gs i wm
-- helper function which deals with the regular case and selects a concrete work
-- once a node and a group have been choosen
takeWork :: GroupThreadsNode -> Scheduler (GroupId,NumThreads,AnyNode,AnyWork)
takeWork (gid,threads,nd) = do
-- from the preparations we know that the list of work units for gid is not empty,
-- so we can take an element, no need to check that we took Nothing
i <- getIndex
w <- state $ removeWork gid i
return (gid, threads, nd, w)
-- select a compute node, work unit and number of threads to use
selectNodeWork :: Scheduler (Maybe (GroupId,NumThreads,AnyNode,AnyWork))
selectNodeWork = do
gtn_maybe <- selectGroupThreadsNode
case gtn_maybe of
Nothing -> return Nothing
Just gtn -> Just <$> takeWork gtn
------------------------------------------------------------
showStatusNodes :: Scheduler String
showStatusNodes = do
nts <- gets $ Map.toList . sdNodeThreads
let ss = map (uncurry $ printf "%s<%d>") nts
return $ printf "*** available threads on nodes = %s" $ intercalate ", " ss
showWorkQueue :: Scheduler String
showWorkQueue = do
gwsl <- gets $ Map.toList . sdWorkSet
let wss = map (\(gs, ws) -> printf " group = %s, work %s " (showGroups gs)
(intercalate ", " $ map workName ws)) gwsl
return $ printf "work units not executed: \n%s" (intercalate "\n" wss)
showJobList :: Scheduler String
showJobList = do
js <- schedulerJobIds
ts <- mapM schedulerJobsThreads js
ns <- mapM (nodeName <-< schedulerJobsNode) js
let jtns = zipWith3 (printf "%d<%s:%d>") js ns ts
return $ intercalate ", " jtns
showStatusWork :: Scheduler String
showStatusWork = do
gwsl <- gets $ Map.toList . sdWorkSet
let showGroupStatus (gs,wsl) = printf "%s<%d>" (showGroups gs) (length wsl)
strRemain = intercalate ", " $ map showGroupStatus gwsl
return $ if null gwsl
then "*** no work units left"
else "*** remaining work units (groupdId<#work>): " ++ strRemain
showStatusAsync :: Scheduler String
showStatusAsync = do
as <- schedulerJobsAsyncs
ps <- liftIO $ mapM poll as
if all isNothing ps
then printf "*** waiting for (jobId<node:threads>): %s" <$> showJobList
else return $ printf "*** handling further %d finished work unit(s)"
(length $ catMaybes ps)
showStatusWaitForJobs :: Scheduler [String]
showStatusWaitForJobs =
sequence [showStatusNodes, showStatusWork, showStatusAsync]
------------------------------------------------------------
-- check that the queue is not empty, this indicates a misconfiguration
-- or network problems (ssh errors)
checkJobQueue :: Scheduler ()
checkJobQueue = do
isJobQueueEmpty <- gets $ Map.null . sdJobs
when isJobQueueEmpty $ do
workQueueOut <- showWorkQueue
let pf = printf "%s"
msg = "there are work units which cannot be executed\n"
++ "(no groups specified, number of threads too large, ssh failures, etc)\n"
++ workQueueOut
lockIO <- reader envLockIO
liftIO $ atomicPutStrLn lockIO $ pf msg
error "revise configuration setup"
-- if an ssh error occurs, remove the node and reschedule the work unit
updateSSHError :: JobId -> Scheduler ()
updateSSHError jid = do
jobs <- gets sdJobs
let jd = fromJust $ Map.lookup jid jobs
nd = jNode jd
w = jWork jd
jobs' = Map.delete jid jobs
nts' <- Map.delete (nodeName nd) <$> gets sdNodeThreads
wm' <- insertMapLists (workGroups w) w <$> gets sdWorkSet
modify (\sd -> sd { sdNodeThreads = nts'
, sdJobs = jobs'
, sdWorkSet = wm'
})
-- update scheduler if an ssh error occurs and print some messages
-- of what has been done
runWorkSSHError :: JobId -> Scheduler ()
runWorkSSHError jid = do
nd <- schedulerJobsNode jid
w <- schedulerJobsWork jid
nm <- gets sdNodeThreads
lockIO <- reader envLockIO
liftIO $ when (Map.member (nodeName nd) nm) $
withMVar_ lockIO $
putStrLn $ printf "*** removing remote node due to ssh error: %s" (nodeName nd)
liftIO $ atomicPutStrLn lockIO $
printf "*** rescheduling work unit due to ssh error: %s" (workName w)
updateSSHError jid
------------------------------------------------------------
runWorkLoopWait :: Scheduler ()
runWorkLoopWait = do
checkJobQueue
lockIO <- reader envLockIO
strInfo <- showStatusWaitForJobs
liftIO $ withMVar_ lockIO $ mapM_ putStrLn strInfo
aj <- schedulerJobsAsyncs
(_,(jid,status)) <- liftIO $ waitAny aj
-- liftIO $ putStrLn $ printf "&&& status = %d, %s" jid (show status)
case status of
SSH_ERROR -> runWorkSSHError jid
CTRLC_ERROR -> liftIO $ raiseSignal sigINT
_ -> removeJob jid
return ()
runWorkLoopNewJob :: (GroupId,NumThreads,AnyNode,AnyWork) -> Scheduler ()
runWorkLoopNewJob (gid,threads,nd,w) = do
lockIO <- reader envLockIO
jid <- getJobId
pstoreVar <- gets sdProcessStore
timeout_maybe <- Map.lookup gid <$> reader envTimeout
-- scale timeout if we use less than the maximal number of threads for a group
-- (we assume that the timeout value is with respect to the maximal number of threads for this group)
let (_, tmax) = getThreadsForGroup gid nd
scale = (fromIntegral tmax) / (fromIntegral threads)
timeout_maybe' = scaleInteger scale <$> timeout_maybe -- within the Maybe monad
let pf1 = printf "%s jobId = %4d, node = %s, work unit = %s"
liftIO $ atomicPutStrLn lockIO $ pf1 "*** fire up" jid (nodeName nd) (workName w)
let pd = ProcessData { pdNode = nd
, pdThreads = threads
, pdTimeout = timeout_maybe'
, pdWork = w
, pdJobId = jid
, pdProcessStore = pstoreVar
}
-- create a new async job and store it in the jobs map
r <- ask
jh <- liftIO (async $ runProcess executeWork pd r)
addJob jid JobData { jNode = nd
, jThreads = threads
, jWork = w
, jHandle = jh
}
-- get a work unit and a compute unit, if both were obtained, fire up the next job
-- if no compute unit is available the wait until one becomes available and
-- remove the finished job from the jobs list and
-- return the updated loop data
runWorkLoopBody :: Scheduler ()
runWorkLoopBody = do
gtnw_maybe <- selectNodeWork
case gtnw_maybe of
-- not enough execution threads available, wait for another job to finish
Nothing -> runWorkLoopWait
-- fire up a new job
Just gtnw -> runWorkLoopNewJob gtnw
runWorkLoop :: Scheduler ()
runWorkLoop = whileM_ (gets $ not . isFinished) runWorkLoopBody
------------------------------------------------------------
cleanupProcesses :: MVar (Map.Map JobId Process.ProcessHandle) -> IO ()
cleanupProcesses pstoreVar =
modifyMVar_ pstoreVar
(\pstore -> do
-- get list of all currently active processes
let phs = Map.elems pstore
jsout = intercalate ", " $ map show (Map.keys pstore)
putStrLn $ printf "\nkilling jobs: %s" jsout
forM_ phs Process.interruptProcessGroupOf
-- forM_ phs Process.terminateProcess
return Map.empty
)
sigIntTermHandler :: MVar (Map.Map JobId Process.ProcessHandle) -> Handler
sigIntTermHandler = CatchOnce . cleanupProcesses
------------------------------------------------------------
runWork :: Scheduler ()
runWork = do
initNodeResources
pstoreVar <- gets sdProcessStore
old_sigIntHandler <- liftIO $ installHandler sigINT (sigIntTermHandler pstoreVar) Nothing
old_sigTermHandler <- liftIO $ installHandler sigTERM (sigIntTermHandler pstoreVar) Nothing
-- we want to measure time for profiling purposes
timeStart <- liftIO getCurrentTime
-- this is the main loop, which starts all jobs and waits until all
-- work units are executed and all jobs are finished
local (setTimeBase timeStart) runWorkLoop
timeAll <- liftIO $ relativeTime timeStart
let outFinished = printf "*** work queue finished, overall execution time = %8.1f" timeAll
liftIO $ putStrLn outFinished
-- reinstall the original signal handlers
_ <- liftIO $ installHandler sigINT old_sigIntHandler Nothing
_ <- liftIO $ installHandler sigTERM old_sigTermHandler Nothing
return ()
| hexenroehrling/hs-scheduler | src/RunSchedule.hs | gpl-3.0 | 17,617 | 0 | 17 | 4,147 | 3,893 | 2,003 | 1,890 | 307 | 3 |
{-
Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan <ram@rkrishnan.org>
This file is part of FuncTorrent.
FuncTorrent is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
FuncTorrent 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 FuncTorrent; if not, see <http://www.gnu.org/licenses/>
-}
{-# LANGUAGE OverloadedStrings #-}
-- | Parse magnet URI
-- The spec for magnetURI: https://en.wikipedia.org/wiki/Magnet_URI_scheme
-- An example from tpb:
-- magnet:?xt=urn:btih:1f8a4ee3c3f57e81f8f0b4e658177201fc2a3118&dn=Honey+Bee+2+%5B2017%5D+Malayalam+DVDRiP+x264+AAC+700MB+ZippyMovieZ+E&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969
-- xt - extra topic - urn containing filehash
-- btih - bittorrent infohash
-- dn - display name (for the user)
-- tr - tracker URL
-- xl - exact length
-- mt - link to a meta file (manifest topic) that contains a list of magnet links
-- urn - uniform resource name
-- How does a client join the swarm with only the magnet uri?
-- This is detailed in http://www.bittorrent.org/beps/bep_0009.html
-- The protocol depends on the extensions protocol specified in BEP 0010.
-- http://www.bittorrent.org/beps/bep_0009.html
-- 1. First we parse the magnet uri and get a list of trackers
-- 2. We then use the usual tracker protocol to get a list of peers.
-- 3. Then we talk to the peers to create the metadata via the BEP 0009 protocol
module FuncTorrent.MagnetURI where
import Text.ParserCombinators.Parsec
import qualified Text.Parsec.ByteString as ParsecBS
import Data.ByteString.Char8 (ByteString, pack)
import Network.HTTP.Base (urlDecode)
data Magnetinfo = Magnetinfo { infoHash :: ByteString
, trackerlist :: [String]
, name :: String
, xlen :: Maybe Integer
}
deriving (Eq, Show)
magnetHdr :: ParsecBS.Parser String
magnetHdr = string "magnet:?"
kvpair :: ParsecBS.Parser (String, String)
kvpair = do
k <- many1 letter
_ <- char '='
v <- many1 (noneOf "&")
return (k, v)
magnetBody :: ParsecBS.Parser Magnetinfo
magnetBody = do
pairs <- kvpair `sepBy1` (char '&')
-- walk through pairs, populate Magnetinfo (fold?)
return $ foldl f magnetInfo pairs
where f magnetRecord pair =
let (k, v) = pair
in
case k of
"xt" -> magnetRecord { infoHash = pack v }
"tr" -> let trVal = trackerlist magnetRecord
in
magnetRecord { trackerlist = trVal ++ [urlDecode v] }
"dn" -> magnetRecord { name = urlDecode v }
"xl" -> magnetRecord { xlen = Just (read v :: Integer) }
_ -> magnetInfo
magnetInfo = Magnetinfo { infoHash = mempty
, trackerlist = mempty
, name = mempty
, xlen = Nothing }
magnetUri :: ParsecBS.Parser Magnetinfo
magnetUri = magnetHdr >> magnetBody
parseMagneturi :: ByteString -> Either String Magnetinfo
parseMagneturi input =
case parse magnetUri "magnetParse" input of
Right minfo -> Right minfo
Left e -> Left $ "Cannot parse the magnet URI: " ++ show e
| vu3rdd/functorrent | src/FuncTorrent/MagnetURI.hs | gpl-3.0 | 3,852 | 0 | 18 | 968 | 505 | 279 | 226 | 43 | 5 |
{-# 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.S3.UploadPartCopy
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Uploads a part by copying data from an existing object as data source.
--
-- <http://docs.aws.amazon.com/AmazonS3/latest/API/UploadPartCopy.html>
module Network.AWS.S3.UploadPartCopy
(
-- * Request
UploadPartCopy
-- ** Request constructor
, uploadPartCopy
-- ** Request lenses
, upcBucket
, upcCopySource
, upcCopySourceIfMatch
, upcCopySourceIfModifiedSince
, upcCopySourceIfNoneMatch
, upcCopySourceIfUnmodifiedSince
, upcCopySourceRange
, upcCopySourceSSECustomerAlgorithm
, upcCopySourceSSECustomerKey
, upcCopySourceSSECustomerKeyMD5
, upcKey
, upcPartNumber
, upcSSECustomerAlgorithm
, upcSSECustomerKey
, upcSSECustomerKeyMD5
, upcUploadId
-- * Response
, UploadPartCopyResponse
-- ** Response constructor
, uploadPartCopyResponse
-- ** Response lenses
, upcrCopyPartResult
, upcrCopySourceVersionId
, upcrSSECustomerAlgorithm
, upcrSSECustomerKeyMD5
, upcrSSEKMSKeyId
, upcrServerSideEncryption
) where
import Network.AWS.Prelude
import Network.AWS.Request.S3
import Network.AWS.S3.Types
import qualified GHC.Exts
data UploadPartCopy = UploadPartCopy
{ _upcBucket :: Text
, _upcCopySource :: Text
, _upcCopySourceIfMatch :: Maybe Text
, _upcCopySourceIfModifiedSince :: Maybe RFC822
, _upcCopySourceIfNoneMatch :: Maybe Text
, _upcCopySourceIfUnmodifiedSince :: Maybe RFC822
, _upcCopySourceRange :: Maybe Text
, _upcCopySourceSSECustomerAlgorithm :: Maybe Text
, _upcCopySourceSSECustomerKey :: Maybe (Sensitive Text)
, _upcCopySourceSSECustomerKeyMD5 :: Maybe Text
, _upcKey :: Text
, _upcPartNumber :: Int
, _upcSSECustomerAlgorithm :: Maybe Text
, _upcSSECustomerKey :: Maybe (Sensitive Text)
, _upcSSECustomerKeyMD5 :: Maybe Text
, _upcUploadId :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'UploadPartCopy' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'upcBucket' @::@ 'Text'
--
-- * 'upcCopySource' @::@ 'Text'
--
-- * 'upcCopySourceIfMatch' @::@ 'Maybe' 'Text'
--
-- * 'upcCopySourceIfModifiedSince' @::@ 'Maybe' 'UTCTime'
--
-- * 'upcCopySourceIfNoneMatch' @::@ 'Maybe' 'Text'
--
-- * 'upcCopySourceIfUnmodifiedSince' @::@ 'Maybe' 'UTCTime'
--
-- * 'upcCopySourceRange' @::@ 'Maybe' 'Text'
--
-- * 'upcCopySourceSSECustomerAlgorithm' @::@ 'Maybe' 'Text'
--
-- * 'upcCopySourceSSECustomerKey' @::@ 'Maybe' 'Text'
--
-- * 'upcCopySourceSSECustomerKeyMD5' @::@ 'Maybe' 'Text'
--
-- * 'upcKey' @::@ 'Text'
--
-- * 'upcPartNumber' @::@ 'Int'
--
-- * 'upcSSECustomerAlgorithm' @::@ 'Maybe' 'Text'
--
-- * 'upcSSECustomerKey' @::@ 'Maybe' 'Text'
--
-- * 'upcSSECustomerKeyMD5' @::@ 'Maybe' 'Text'
--
-- * 'upcUploadId' @::@ 'Text'
--
uploadPartCopy :: Text -- ^ 'upcBucket'
-> Text -- ^ 'upcCopySource'
-> Text -- ^ 'upcKey'
-> Int -- ^ 'upcPartNumber'
-> Text -- ^ 'upcUploadId'
-> UploadPartCopy
uploadPartCopy p1 p2 p3 p4 p5 = UploadPartCopy
{ _upcBucket = p1
, _upcCopySource = p2
, _upcKey = p3
, _upcPartNumber = p4
, _upcUploadId = p5
, _upcCopySourceIfMatch = Nothing
, _upcCopySourceIfModifiedSince = Nothing
, _upcCopySourceIfNoneMatch = Nothing
, _upcCopySourceIfUnmodifiedSince = Nothing
, _upcCopySourceRange = Nothing
, _upcSSECustomerAlgorithm = Nothing
, _upcSSECustomerKey = Nothing
, _upcSSECustomerKeyMD5 = Nothing
, _upcCopySourceSSECustomerAlgorithm = Nothing
, _upcCopySourceSSECustomerKey = Nothing
, _upcCopySourceSSECustomerKeyMD5 = Nothing
}
upcBucket :: Lens' UploadPartCopy Text
upcBucket = lens _upcBucket (\s a -> s { _upcBucket = a })
-- | The name of the source bucket and key name of the source object, separated by
-- a slash (/). Must be URL-encoded.
upcCopySource :: Lens' UploadPartCopy Text
upcCopySource = lens _upcCopySource (\s a -> s { _upcCopySource = a })
-- | Copies the object if its entity tag (ETag) matches the specified tag.
upcCopySourceIfMatch :: Lens' UploadPartCopy (Maybe Text)
upcCopySourceIfMatch =
lens _upcCopySourceIfMatch (\s a -> s { _upcCopySourceIfMatch = a })
-- | Copies the object if it has been modified since the specified time.
upcCopySourceIfModifiedSince :: Lens' UploadPartCopy (Maybe UTCTime)
upcCopySourceIfModifiedSince =
lens _upcCopySourceIfModifiedSince
(\s a -> s { _upcCopySourceIfModifiedSince = a })
. mapping _Time
-- | Copies the object if its entity tag (ETag) is different than the specified
-- ETag.
upcCopySourceIfNoneMatch :: Lens' UploadPartCopy (Maybe Text)
upcCopySourceIfNoneMatch =
lens _upcCopySourceIfNoneMatch
(\s a -> s { _upcCopySourceIfNoneMatch = a })
-- | Copies the object if it hasn't been modified since the specified time.
upcCopySourceIfUnmodifiedSince :: Lens' UploadPartCopy (Maybe UTCTime)
upcCopySourceIfUnmodifiedSince =
lens _upcCopySourceIfUnmodifiedSince
(\s a -> s { _upcCopySourceIfUnmodifiedSince = a })
. mapping _Time
-- | The range of bytes to copy from the source object. The range value must use
-- the form bytes=first-last, where the first and last are the zero-based byte
-- offsets to copy. For example, bytes=0-9 indicates that you want to copy the
-- first ten bytes of the source. You can copy a range only if the source object
-- is greater than 5 GB.
upcCopySourceRange :: Lens' UploadPartCopy (Maybe Text)
upcCopySourceRange =
lens _upcCopySourceRange (\s a -> s { _upcCopySourceRange = a })
-- | Specifies the algorithm to use when decrypting the source object (e.g.,
-- AES256).
upcCopySourceSSECustomerAlgorithm :: Lens' UploadPartCopy (Maybe Text)
upcCopySourceSSECustomerAlgorithm =
lens _upcCopySourceSSECustomerAlgorithm
(\s a -> s { _upcCopySourceSSECustomerAlgorithm = a })
-- | Specifies the customer-provided encryption key for Amazon S3 to use to
-- decrypt the source object. The encryption key provided in this header must be
-- one that was used when the source object was created.
upcCopySourceSSECustomerKey :: Lens' UploadPartCopy (Maybe Text)
upcCopySourceSSECustomerKey =
lens _upcCopySourceSSECustomerKey
(\s a -> s { _upcCopySourceSSECustomerKey = a })
. mapping _Sensitive
-- | Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321.
-- Amazon S3 uses this header for a message integrity check to ensure the
-- encryption key was transmitted without error.
upcCopySourceSSECustomerKeyMD5 :: Lens' UploadPartCopy (Maybe Text)
upcCopySourceSSECustomerKeyMD5 =
lens _upcCopySourceSSECustomerKeyMD5
(\s a -> s { _upcCopySourceSSECustomerKeyMD5 = a })
upcKey :: Lens' UploadPartCopy Text
upcKey = lens _upcKey (\s a -> s { _upcKey = a })
-- | Part number of part being copied.
upcPartNumber :: Lens' UploadPartCopy Int
upcPartNumber = lens _upcPartNumber (\s a -> s { _upcPartNumber = a })
-- | Specifies the algorithm to use to when encrypting the object (e.g., AES256,
-- aws:kms).
upcSSECustomerAlgorithm :: Lens' UploadPartCopy (Maybe Text)
upcSSECustomerAlgorithm =
lens _upcSSECustomerAlgorithm (\s a -> s { _upcSSECustomerAlgorithm = a })
-- | Specifies the customer-provided encryption key for Amazon S3 to use in
-- encrypting data. This value is used to store the object and then it is
-- discarded; Amazon does not store the encryption key. The key must be
-- appropriate for use with the algorithm specified in the
-- x-amz-server-side-encryption-customer-algorithm header. This must be the
-- same encryption key specified in the initiate multipart upload request.
upcSSECustomerKey :: Lens' UploadPartCopy (Maybe Text)
upcSSECustomerKey =
lens _upcSSECustomerKey (\s a -> s { _upcSSECustomerKey = a })
. mapping _Sensitive
-- | Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321.
-- Amazon S3 uses this header for a message integrity check to ensure the
-- encryption key was transmitted without error.
upcSSECustomerKeyMD5 :: Lens' UploadPartCopy (Maybe Text)
upcSSECustomerKeyMD5 =
lens _upcSSECustomerKeyMD5 (\s a -> s { _upcSSECustomerKeyMD5 = a })
-- | Upload ID identifying the multipart upload whose part is being copied.
upcUploadId :: Lens' UploadPartCopy Text
upcUploadId = lens _upcUploadId (\s a -> s { _upcUploadId = a })
data UploadPartCopyResponse = UploadPartCopyResponse
{ _upcrCopyPartResult :: Maybe CopyPartResult
, _upcrCopySourceVersionId :: Maybe Text
, _upcrSSECustomerAlgorithm :: Maybe Text
, _upcrSSECustomerKeyMD5 :: Maybe Text
, _upcrSSEKMSKeyId :: Maybe (Sensitive Text)
, _upcrServerSideEncryption :: Maybe ServerSideEncryption
} deriving (Eq, Read, Show)
-- | 'UploadPartCopyResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'upcrCopyPartResult' @::@ 'Maybe' 'CopyPartResult'
--
-- * 'upcrCopySourceVersionId' @::@ 'Maybe' 'Text'
--
-- * 'upcrSSECustomerAlgorithm' @::@ 'Maybe' 'Text'
--
-- * 'upcrSSECustomerKeyMD5' @::@ 'Maybe' 'Text'
--
-- * 'upcrSSEKMSKeyId' @::@ 'Maybe' 'Text'
--
-- * 'upcrServerSideEncryption' @::@ 'Maybe' 'ServerSideEncryption'
--
uploadPartCopyResponse :: UploadPartCopyResponse
uploadPartCopyResponse = UploadPartCopyResponse
{ _upcrCopySourceVersionId = Nothing
, _upcrCopyPartResult = Nothing
, _upcrServerSideEncryption = Nothing
, _upcrSSECustomerAlgorithm = Nothing
, _upcrSSECustomerKeyMD5 = Nothing
, _upcrSSEKMSKeyId = Nothing
}
upcrCopyPartResult :: Lens' UploadPartCopyResponse (Maybe CopyPartResult)
upcrCopyPartResult =
lens _upcrCopyPartResult (\s a -> s { _upcrCopyPartResult = a })
-- | The version of the source object that was copied, if you have enabled
-- versioning on the source bucket.
upcrCopySourceVersionId :: Lens' UploadPartCopyResponse (Maybe Text)
upcrCopySourceVersionId =
lens _upcrCopySourceVersionId (\s a -> s { _upcrCopySourceVersionId = a })
-- | If server-side encryption with a customer-provided encryption key was
-- requested, the response will include this header confirming the encryption
-- algorithm used.
upcrSSECustomerAlgorithm :: Lens' UploadPartCopyResponse (Maybe Text)
upcrSSECustomerAlgorithm =
lens _upcrSSECustomerAlgorithm
(\s a -> s { _upcrSSECustomerAlgorithm = a })
-- | If server-side encryption with a customer-provided encryption key was
-- requested, the response will include this header to provide round trip
-- message integrity verification of the customer-provided encryption key.
upcrSSECustomerKeyMD5 :: Lens' UploadPartCopyResponse (Maybe Text)
upcrSSECustomerKeyMD5 =
lens _upcrSSECustomerKeyMD5 (\s a -> s { _upcrSSECustomerKeyMD5 = a })
-- | If present, specifies the ID of the AWS Key Management Service (KMS) master
-- encryption key that was used for the object.
upcrSSEKMSKeyId :: Lens' UploadPartCopyResponse (Maybe Text)
upcrSSEKMSKeyId = lens _upcrSSEKMSKeyId (\s a -> s { _upcrSSEKMSKeyId = a }) . mapping _Sensitive
-- | The Server-side encryption algorithm used when storing this object in S3
-- (e.g., AES256, aws:kms).
upcrServerSideEncryption :: Lens' UploadPartCopyResponse (Maybe ServerSideEncryption)
upcrServerSideEncryption =
lens _upcrServerSideEncryption
(\s a -> s { _upcrServerSideEncryption = a })
instance ToPath UploadPartCopy where
toPath UploadPartCopy{..} = mconcat
[ "/"
, toText _upcBucket
, "/"
, toText _upcKey
]
instance ToQuery UploadPartCopy where
toQuery UploadPartCopy{..} = mconcat
[ "partNumber" =? _upcPartNumber
, "uploadId" =? _upcUploadId
]
instance ToHeaders UploadPartCopy where
toHeaders UploadPartCopy{..} = mconcat
[ "x-amz-copy-source" =: _upcCopySource
, "x-amz-copy-source-if-match" =: _upcCopySourceIfMatch
, "x-amz-copy-source-if-modified-since" =: _upcCopySourceIfModifiedSince
, "x-amz-copy-source-if-none-match" =: _upcCopySourceIfNoneMatch
, "x-amz-copy-source-if-unmodified-since" =: _upcCopySourceIfUnmodifiedSince
, "x-amz-copy-source-range" =: _upcCopySourceRange
, "x-amz-server-side-encryption-customer-algorithm" =: _upcSSECustomerAlgorithm
, "x-amz-server-side-encryption-customer-key" =: _upcSSECustomerKey
, "x-amz-server-side-encryption-customer-key-MD5" =: _upcSSECustomerKeyMD5
, "x-amz-copy-source-server-side-encryption-customer-algorithm" =: _upcCopySourceSSECustomerAlgorithm
, "x-amz-copy-source-server-side-encryption-customer-key" =: _upcCopySourceSSECustomerKey
, "x-amz-copy-source-server-side-encryption-customer-key-MD5" =: _upcCopySourceSSECustomerKeyMD5
]
instance ToXMLRoot UploadPartCopy where
toXMLRoot = const (namespaced ns "UploadPartCopy" [])
instance ToXML UploadPartCopy
instance AWSRequest UploadPartCopy where
type Sv UploadPartCopy = S3
type Rs UploadPartCopy = UploadPartCopyResponse
request = put
response = xmlHeaderResponse $ \h x -> UploadPartCopyResponse
<$> x .@? "CopyPartResult"
<*> h ~:? "x-amz-copy-source-version-id"
<*> h ~:? "x-amz-server-side-encryption-customer-algorithm"
<*> h ~:? "x-amz-server-side-encryption-customer-key-MD5"
<*> h ~:? "x-amz-server-side-encryption-aws-kms-key-id"
<*> h ~:? "x-amz-server-side-encryption"
| dysinger/amazonka | amazonka-s3/gen/Network/AWS/S3/UploadPartCopy.hs | mpl-2.0 | 15,168 | 0 | 19 | 3,461 | 1,980 | 1,165 | 815 | 209 | 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.EC2.ReplaceRoute
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Replaces an existing route within a route table in a VPC. You must provide
-- only one of the following: Internet gateway or virtual private gateway, NAT
-- instance, VPC peering connection, or network interface.
--
-- For more information about route tables, see <http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html Route Tables> in the /AmazonVirtual Private Cloud User Guide/.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceRoute.html>
module Network.AWS.EC2.ReplaceRoute
(
-- * Request
ReplaceRoute
-- ** Request constructor
, replaceRoute
-- ** Request lenses
, rrDestinationCidrBlock
, rrDryRun
, rrGatewayId
, rrInstanceId
, rrNetworkInterfaceId
, rrRouteTableId
, rrVpcPeeringConnectionId
-- * Response
, ReplaceRouteResponse
-- ** Response constructor
, replaceRouteResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data ReplaceRoute = ReplaceRoute
{ _rrDestinationCidrBlock :: Text
, _rrDryRun :: Maybe Bool
, _rrGatewayId :: Maybe Text
, _rrInstanceId :: Maybe Text
, _rrNetworkInterfaceId :: Maybe Text
, _rrRouteTableId :: Text
, _rrVpcPeeringConnectionId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'ReplaceRoute' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'rrDestinationCidrBlock' @::@ 'Text'
--
-- * 'rrDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'rrGatewayId' @::@ 'Maybe' 'Text'
--
-- * 'rrInstanceId' @::@ 'Maybe' 'Text'
--
-- * 'rrNetworkInterfaceId' @::@ 'Maybe' 'Text'
--
-- * 'rrRouteTableId' @::@ 'Text'
--
-- * 'rrVpcPeeringConnectionId' @::@ 'Maybe' 'Text'
--
replaceRoute :: Text -- ^ 'rrRouteTableId'
-> Text -- ^ 'rrDestinationCidrBlock'
-> ReplaceRoute
replaceRoute p1 p2 = ReplaceRoute
{ _rrRouteTableId = p1
, _rrDestinationCidrBlock = p2
, _rrDryRun = Nothing
, _rrGatewayId = Nothing
, _rrInstanceId = Nothing
, _rrNetworkInterfaceId = Nothing
, _rrVpcPeeringConnectionId = Nothing
}
-- | The CIDR address block used for the destination match. The value you provide
-- must match the CIDR of an existing route in the table.
rrDestinationCidrBlock :: Lens' ReplaceRoute Text
rrDestinationCidrBlock =
lens _rrDestinationCidrBlock (\s a -> s { _rrDestinationCidrBlock = a })
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have the
-- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'.
rrDryRun :: Lens' ReplaceRoute (Maybe Bool)
rrDryRun = lens _rrDryRun (\s a -> s { _rrDryRun = a })
-- | The ID of an Internet gateway or virtual private gateway.
rrGatewayId :: Lens' ReplaceRoute (Maybe Text)
rrGatewayId = lens _rrGatewayId (\s a -> s { _rrGatewayId = a })
-- | The ID of a NAT instance in your VPC.
rrInstanceId :: Lens' ReplaceRoute (Maybe Text)
rrInstanceId = lens _rrInstanceId (\s a -> s { _rrInstanceId = a })
-- | The ID of a network interface.
rrNetworkInterfaceId :: Lens' ReplaceRoute (Maybe Text)
rrNetworkInterfaceId =
lens _rrNetworkInterfaceId (\s a -> s { _rrNetworkInterfaceId = a })
-- | The ID of the route table.
rrRouteTableId :: Lens' ReplaceRoute Text
rrRouteTableId = lens _rrRouteTableId (\s a -> s { _rrRouteTableId = a })
-- | The ID of a VPC peering connection.
rrVpcPeeringConnectionId :: Lens' ReplaceRoute (Maybe Text)
rrVpcPeeringConnectionId =
lens _rrVpcPeeringConnectionId
(\s a -> s { _rrVpcPeeringConnectionId = a })
data ReplaceRouteResponse = ReplaceRouteResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'ReplaceRouteResponse' constructor.
replaceRouteResponse :: ReplaceRouteResponse
replaceRouteResponse = ReplaceRouteResponse
instance ToPath ReplaceRoute where
toPath = const "/"
instance ToQuery ReplaceRoute where
toQuery ReplaceRoute{..} = mconcat
[ "DestinationCidrBlock" =? _rrDestinationCidrBlock
, "DryRun" =? _rrDryRun
, "GatewayId" =? _rrGatewayId
, "InstanceId" =? _rrInstanceId
, "NetworkInterfaceId" =? _rrNetworkInterfaceId
, "RouteTableId" =? _rrRouteTableId
, "VpcPeeringConnectionId" =? _rrVpcPeeringConnectionId
]
instance ToHeaders ReplaceRoute
instance AWSRequest ReplaceRoute where
type Sv ReplaceRoute = EC2
type Rs ReplaceRoute = ReplaceRouteResponse
request = post "ReplaceRoute"
response = nullResponse ReplaceRouteResponse
| romanb/amazonka | amazonka-ec2/gen/Network/AWS/EC2/ReplaceRoute.hs | mpl-2.0 | 5,870 | 0 | 9 | 1,350 | 760 | 457 | 303 | 86 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module CountdownGame.State.Rounds
(
)where
import GHC.Generics (Generic)
import Control.Concurrent.Async (Async, async, wait, poll, asyncThreadId, waitBoth)
import Control.Concurrent (forkIO, threadDelay, ThreadId)
import Data.Aeson (ToJSON)
import Data.Function (on)
import Data.IORef (IORef(..), newIORef, readIORef, atomicModifyIORef')
import Data.List (sortBy)
import Data.Maybe (isJust)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import Data.Time (UTCTime, NominalDiffTime, getCurrentTime, addUTCTime)
import CountdownGame.References
import CountdownGame.State.Definitions
import CountdownGame.Database (insertChallange)
import Countdown.Game (Attempt, AttemptsMap, Challange)
import qualified Countdown.Game as G
-- $doc
-- Es gibt zwei Zustände:
--
-- - warten auf den Begin der nächsten Runde
-- - die Runde läuft
--
-- Beide Zustände laufen nur eine bestimmte Zeitland und
-- wechseln dann in den jeweils anderen Zustand
--
-- Während des Wartens wird zusätzlich die Challange für die nächste
-- Runde berechnet und die Ergebnise der letzen Runde (falls vorhanden)
-- sind verfügbar.
-- Am Ende dieser Wartezeit ist ist die nächste Challange verfügbar
--
-- Während einer Runde ist die aktuelle Challange verfügbar und die
-- Spieler können ihre Attempts schicken (die gespeichert werden)
-- Am Ende dieser Phase sind die Ergebnise der Runde verfügbar
startGameLoop :: SpielParameter -> IO (Reference Phasen)
startGameLoop params = do
ref <- createRef Start
_ <- forkIO $ gameLoop params [] ref
return ref
gameLoop :: SpielParameter -> Ergebnisse -> Reference Phasen -> IO ()
gameLoop params ltErg phase = do
warten <- wartePhase params ltErg
modifyRef (const (warten, ())) phase
aufg <- wait . naechsteChallange $ warten
runde <- rundenPhase params aufg
modifyRef (const (runde, ())) phase
erg <- wait . ergebnisse $ runde
gameLoop params erg phase
wartePhase :: SpielParameter -> Ergebnisse -> IO Phasen
wartePhase params ltErg = do
wartenBis <- (warteZeit params `addUTCTime`) <$> getCurrentTime
start <- async $ warteStart wartenBis
return $ WartePhase wartenBis ltErg start
warteStart :: UTCTime -> IO Challange
warteStart startZeit = do
neue <- async G.generateChallange
warte <- async $ warteBis startZeit
(chal, _) <- waitBoth neue warte
return chal
rundenPhase :: SpielParameter -> Challange -> IO Phasen
rundenPhase params chal = do
chId <- insertChallange chal
rundeBis <- (rundenZeit params `addUTCTime`) <$> getCurrentTime
vers <- createRef M.empty
erg <- async $ warteErgebnise rundeBis chal vers
return $ RundePhase rundeBis chal vers chId erg
warteErgebnise :: UTCTime -> Challange -> Versuche -> IO Ergebnisse
warteErgebnise endeZeit aufg refVers = do
warteBis endeZeit
readRef berechneErgebnisse refVers
warteBis :: UTCTime -> IO ()
warteBis zeit = do
now <- getCurrentTime
if now < zeit then do
threadDelay 250000
warteBis zeit
else return ()
| CarstenKoenig/DOS2015 | CountdownGame/src/web/CountdownGame/State/Rounds.hs | unlicense | 3,075 | 0 | 11 | 536 | 789 | 414 | 375 | 63 | 2 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, UnicodeSyntax, GADTs, FlexibleInstances, LambdaCase #-}
module Sweetroll.Micropub.Request where
import Sweetroll.Prelude
import Data.Aeson.Types (parseMaybe)
import Web.FormUrlEncoded hiding (parseMaybe)
type ObjType = [Text]
type ObjProperties = Object
type ObjSyndication = Text
type ObjUrl = Text
type ObjAcl = Maybe [Text]
data MicropubUpdate = ReplaceProps ObjProperties
| AddToProps ObjProperties
| DelFromProps ObjProperties
| DelProps [Text]
| SetAcl [Text]
deriving (Eq, Show)
instance {-# OVERLAPPING #-} FromJSON [MicropubUpdate] where
parseJSON v@(Object _) =
let rplc = ReplaceProps <$> v ^? key "replace" . _Object
addp = AddToProps <$> v ^? key "add" . _Object
delf = DelFromProps <$> v ^? key "delete" . _Object
delp = DelProps <$> mapMaybe (^? _String) . toList <$> v ^? key "delete" . _Array
aclp = SetAcl <$> mapMaybe (^? _String) . toList <$> v ^? key "acl" . _Array
in return $ catMaybes [ rplc, addp, delf, delp, aclp ]
parseJSON _ = mzero
data MicropubRequest = Create ObjType ObjProperties ObjAcl [ObjSyndication]
| Update ObjUrl [MicropubUpdate]
| Delete ObjUrl
| Undelete ObjUrl
deriving (Eq, Show)
instance FromJSON MicropubRequest where
parseJSON v@(Object _) =
case v ^? key "action" . _String of
Just "delete" →
case v ^? key "url" . _String of
Nothing → fail "Delete with no url"
Just url → return $ Delete url
Just "undelete" →
case v ^? key "url" . _String of
Nothing → fail "Undelete with no url"
Just url → return $ Undelete url
Just "update" →
case v ^? key "url" . _String of
Nothing → fail "Update with no url"
Just url → return $ Update url $ fromMaybe [] $ parseMaybe parseJSON v
Nothing → return $
Create ((\case [] → ["h-entry"]; x → x) $ v ^.. key "type" . values . _String)
(fromMaybe (object [] ^. _Object) $ v ^? key "properties" . _Object)
(map (mapMaybe (^? _String) . toList) $ v ^? key "acl" . _Array)
(v ^.. key "mp-syndicate-to" . values . _String)
_ → fail "Unknown action type"
parseJSON _ = mzero
instance FromForm MicropubRequest where
fromForm f' = let f = formList f' in
case lookup "action" f <|> lookup "mp-action" f of
Just "delete" →
case lookup "url" f of
Nothing → fail "Delete with no url"
Just url → return $ Delete url
Just "undelete" →
case lookup "url" f of
Nothing → fail "Undelete with no url"
Just url → return $ Undelete url
Just "update" →
case lookup "url" f of
Nothing → fail "Update with no url"
Just url → return $ Update url $ fromMaybe [] $ parseMaybe parseJSON $ formToObject f
Nothing →
let v@(Object o') = formToObject f
o = deleteMap "access_token" $ deleteMap "syndicate-to" $ deleteMap "mp-syndicate-to" $ deleteMap "h" o'
h = "h-" ++ fromMaybe "entry" (lookup "h" f)
synd = nub $ (v ^.. key "mp-syndicate-to" . values . _String) ++
(v ^.. key "syndicate-to" . values . _String)
-- no syndicate-to[], the [] is handled in formToObject
in Right $ Create [h] o Nothing synd
_ → Left "Unknown action type"
| myfreeweb/sweetroll | sweetroll-be/library/Sweetroll/Micropub/Request.hs | unlicense | 3,653 | 0 | 21 | 1,171 | 1,094 | 548 | 546 | -1 | -1 |
-----------------------------------------------------------------------------
-- Copyright 2019, Ideas project team. This file is distributed under the
-- terms of the Apache License 2.0. For more information, see the files
-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution.
-----------------------------------------------------------------------------
-- |
-- Maintainer : bastiaan.heeren@ou.nl
-- Stability : provisional
-- Portability : portable (depends on ghc)
--
-- Collection of common operation on XML documents
--
-----------------------------------------------------------------------------
module Ideas.Text.XML
( -- * XML types
XML, Name, Attributes, Attribute(..)
-- * Parsing XML
, parseXML, parseXMLFile
-- * Building/constructing XML
, BuildXML(..), XMLBuilder, makeXML
-- * Pretty-printing XML
, prettyXML, compactXML
-- * Simple decoding queries
, name, attributes, findAttribute, children, findChildren, findChild
, getData, expecting
-- * Decoding XML
, decodeData, decodeAttribute, decodeChild, decodeFirstChild
-- * Type classes for converting to/from XML
, ToXML(..), builderXML, InXML(..)
-- * Processing XML
, foldXML, trimXML
-- * Deprecated functions
, content, emptyContent, fromBuilder
) where
import Control.Monad.State
import Data.Char (chr, ord, isSpace)
import Data.Foldable (toList)
import Data.List
import Data.Maybe
import Data.Semigroup as Sem
import Data.String
import Ideas.Text.XML.Document (escape, Name, prettyElement)
import Ideas.Text.XML.Parser (document)
import Ideas.Text.XML.Unicode
import Ideas.Utils.Decoding
import Ideas.Utils.Parsing (parseSimple)
import System.IO
import qualified Data.Map as M
import qualified Data.Sequence as Seq
import qualified Ideas.Text.XML.Document as D
-------------------------------------------------------------------------------
-- XML types
-- invariants content: no two adjacent Lefts, no Left with empty string,
-- valid tag/attribute names
data XML = Tag
{ name :: Name
, attributes :: Attributes
, content :: [Either String XML]
}
deriving Eq
instance Show XML where
show = compactXML
type Attributes = [Attribute]
data Attribute = Name := String
deriving Eq
-------------------------------------------------------------------------------
-- Parsing XML
parseXML :: String -> Either String XML
parseXML input = do
doc <- parseSimple document input
return (fromXMLDoc doc)
parseXMLFile :: FilePath -> IO XML
parseXMLFile file =
withBinaryFile file ReadMode $
hGetContents >=> either fail return . parseXML
fromXMLDoc :: D.XMLDoc -> XML
fromXMLDoc doc = fromElement (D.root doc)
where
fromElement (D.Element n as c) =
makeXML n (fromAttributes as <> fromContent c)
fromAttributes = mconcat . map fromAttribute
fromAttribute (n D.:= v) =
n .=. concatMap (either return refToString) v
fromContent :: D.Content -> XMLBuilder
fromContent = mconcat . map f
where
f :: D.XML -> XMLBuilder
f (D.Tagged e) = builder (fromElement e)
f (D.CharData s) = string s
f (D.CDATA s) = string s
f (D.Reference r) = fromReference r
refToString :: D.Reference -> String
refToString (D.CharRef i) = [chr i]
refToString (D.EntityRef s) = maybe "" return (lookup s general)
fromReference :: D.Reference -> XMLBuilder
fromReference (D.CharRef i) = char (chr i)
fromReference (D.EntityRef s) = fromMaybe mempty (lookup s entities)
entities :: [(String, XMLBuilder)]
entities =
[ (n, fromContent (snd ext)) | (n, ext) <- D.externals doc ] ++
-- predefined entities
[ (n, char c) | (n, c) <- general ]
general :: [(String, Char)]
general = [("lt",'<'), ("gt",'>'), ("amp",'&'), ("apos",'\''), ("quot",'"')]
-------------------------------------------------------------------------------
-- Building/constructing XML
infix 7 .=.
class (Sem.Semigroup a, Monoid a) => BuildXML a where
(.=.) :: String -> String -> a -- attribute
string :: String -> a -- (escaped) text
builder :: XML -> a -- (named) xml element
tag :: String -> a -> a -- tag (with content)
-- functions with a default
char :: Char -> a
text :: Show s => s -> a -- escaped text with Show class
element :: String -> [a] -> a
emptyTag :: String -> a
-- implementations
char c = string [c]
text = string . show
element s = tag s . mconcat
emptyTag s = tag s mempty
instance BuildXML a => BuildXML (Decoder env s a) where
n .=. s = pure (n .=. s)
string = pure . string
builder = pure . builder
tag = fmap . tag
data XMLBuilder = BS (Seq.Seq Attribute) (Seq.Seq (Either String XML))
instance Sem.Semigroup XMLBuilder where
BS as1 elts1 <> BS as2 elts2 = BS (as1 <> as2) (elts1 <> elts2)
instance Monoid XMLBuilder where
mempty = BS mempty mempty
mappend = (<>)
instance BuildXML XMLBuilder where
n .=. s = nameCheck n $ BS (Seq.singleton (n := s)) mempty
string s = BS mempty (if null s then mempty else Seq.singleton (Left s))
builder = BS mempty . Seq.singleton . Right
tag n = builder . uncurry (Tag n) . fromBS . nameCheck n
instance IsString XMLBuilder where
fromString = string
makeXML :: String -> XMLBuilder -> XML
makeXML s = uncurry (Tag s) . fromBS . nameCheck s
nameCheck :: String -> a -> a
nameCheck s = if isName s then id else fail $ "Invalid name " ++ s
isName :: String -> Bool
isName [] = False
isName (x:xs) = (isLetter x || x `elem` "_:") && all isNameChar xs
isNameChar :: Char -> Bool
isNameChar c = any ($ c) [isLetter, isDigit, isCombiningChar, isExtender, (`elem` ".-_:")]
-- local helper: merge attributes, but preserve order
fromBS :: XMLBuilder -> (Attributes, [Either String XML])
fromBS (BS as elts) = (attrList, merge (toList elts))
where
attrMap = foldr add M.empty as
add (k := v) = M.insertWith (\x y -> x ++ " " ++ y) k v
attrList = nubBy eqKey (map make (toList as))
make (k := _) = k := M.findWithDefault "" k attrMap
eqKey (k1 := _) (k2 := _) = k1 == k2
merge [] = []
merge (Left x:Left y:rest) = merge (Left (x++y):rest)
merge (Left x:rest) = Left x : merge rest
merge (Right y:rest) = Right y : merge rest
-------------------------------------------------------------------------------
-- Pretty-printing XML
prettyXML :: XML -> String
prettyXML = show . prettyElement False . toElement
compactXML :: XML -> String
compactXML = show . prettyElement True . toElement
toElement :: XML -> D.Element
toElement = foldXML make mkAttribute mkString
where
make n as = D.Element n as . concatMap (either id (return . D.Tagged))
mkAttribute :: Attribute -> D.Attribute
mkAttribute (m := s) = (D.:=) m (map Left s)
mkString :: String -> [D.XML]
mkString [] = []
mkString xs@(hd:tl)
| null xs1 = D.Reference (D.CharRef (ord hd)) : mkString tl
| otherwise = D.CharData xs1 : mkString xs2
where
(xs1, xs2) = break ((> 127) . ord) xs
-------------------------------------------------------------------------------
-- Simple decoding queries
findAttribute :: Monad m => String -> XML -> m String
findAttribute s (Tag _ as _) =
case [ t | n := t <- as, s==n ] of
[hd] -> return hd
_ -> fail $ "Invalid attribute: " ++ show s
children :: XML -> [XML]
children e = [ c | Right c <- content e ]
findChildren :: String -> XML -> [XML]
findChildren s = filter ((==s) . name) . children
findChild :: Monad m => String -> XML -> m XML
findChild s e =
case findChildren s e of
[] -> fail $ "Child not found: " ++ show s
[a] -> return a
_ -> fail $ "Multiple children found: " ++ show s
getData :: XML -> String
getData e = concat [ s | Left s <- content e ]
expecting :: Monad m => String -> XML -> m ()
expecting s xml =
unless (name xml == s) $ fail $ "Expecting element " ++ s ++ ", but found " ++ name xml
-------------------------------------------------------------------------------
-- Decoding XML
decodeData :: Decoder env XML String
decodeData = get >>= \xml ->
case content xml of
Left s:rest -> put xml {content = rest} >> return s
_ -> fail "Could not find data"
decodeAttribute :: String -> Decoder env XML String
decodeAttribute s = get >>= \xml ->
case break hasName (attributes xml) of
(xs, (_ := val):ys) -> put xml {attributes = xs ++ ys } >> return val
_ -> fail $ "Could not find attribute " ++ s
where
hasName (n := _) = n == s
decodeChild :: Name -> Decoder env XML a -> Decoder env XML a
decodeChild s p = get >>= \xml ->
case break hasName (content xml) of
(xs, Right y:ys) -> do
put y
a <- p
put xml { content = xs ++ ys }
return a
_ -> fail $ "Could not find child " ++ s
where
hasName = either (const False) ((==s) . name)
decodeFirstChild :: Name -> Decoder env XML a -> Decoder env XML a
decodeFirstChild s p = get >>= \xml ->
case content xml of
Right y:ys | name y == s -> do
put y
a <- p
put xml { content = ys }
return a
_ -> fail $ "Could not find first child " ++ s
-------------------------------------------------------------------------------
-- Type classes for converting to/from XML
class ToXML a where
toXML :: a -> XML
listToXML :: [a] -> XML
-- default definitions
listToXML = makeXML "list" . mconcat . map builderXML
instance ToXML () where
toXML _ = makeXML "Unit" mempty
instance ToXML a => ToXML (Maybe a) where
toXML = maybe (makeXML "Nothing" mempty) toXML
builderXML :: (ToXML a, BuildXML b) => a -> b
builderXML = builder . toXML
class ToXML a => InXML a where
fromXML :: Monad m => XML -> m a
listFromXML :: Monad m => XML -> m [a]
listFromXML xml
| name xml == "list" && null (attributes xml) =
mapM fromXML (children xml)
| otherwise = fail "expecting a list tag"
-------------------------------------------------------------------------------
-- Processing XML
foldXML :: (Name -> [a] -> [Either s e] -> e) -> (Attribute -> a) -> (String -> s) -> XML -> e
foldXML fe fa fs = rec
where
rec (Tag n as cs) = fe n (map fa as) (map (either (Left . fs) (Right . rec)) cs)
trimXML :: XML -> XML
trimXML = foldXML make fa (string . trim)
where
fa (n := s) = n .=. trim s
make :: String -> [XMLBuilder] -> [Either XMLBuilder XML] -> XML
make s as = makeXML s . mconcat . (as ++) . map (either id builder)
trim, trimLeft, trimRight :: String -> String
trim = trimLeft . trimRight
trimLeft = dropWhile isSpace
trimRight = reverse . trimLeft . reverse
-------------------------------------------------------------------------------
-- Deprecated functions
emptyContent :: XML -> Bool
emptyContent = null . content
fromBuilder :: XMLBuilder -> Maybe XML
fromBuilder m =
case fromBS m of
([], [Right a]) -> Just a
_ -> Nothing
-------------------------------------------------------------------------------
-- Tests
_runTests :: IO ()
_runTests = do
forM_ [testDataP, testAttrP, testDataB, testAttrB] $ \f ->
pp $ map f tests
forM_ [mkPD, mkPA, mkBD, mkBA] $ \f ->
pp $ map (testXML . f) tests
where
pp = putStrLn . map (\b -> if b then '.' else 'X')
tests :: [String]
tests =
[ "input"
, "<>&"'"
, "<>&'\""
, "p & q' => p"
, ""
, " "
, "eerste \n\n derde regel"
]
testDataP, testAttrP, testDataB, testAttrB :: String -> Bool
testDataP s = let xml = mkPD s in getData xml == s
testAttrP s = let xml = mkPA s in findAttribute "a" xml == Just s
testDataB s = let xml = mkBD s in getData xml == s
testAttrB s = let xml = mkBA s in findAttribute "a" xml == Just s
testXML :: XML -> Bool
testXML xml =
case parseXML (compactXML xml) of
Left msg -> error msg
Right a -> a == xml
mkPD, mkPA, mkBD, mkBA :: String -> XML
mkPD s = either error id $ parseXML $ "<a>" ++ escape s ++ "</a>"
mkPA s = either error id $ parseXML $ "<t a='" ++ escape s ++ "'/>"
mkBD s = makeXML "a" (string s)
mkBA s = makeXML "t" ("a".=. s) | ideas-edu/ideas | src/Ideas/Text/XML.hs | apache-2.0 | 12,711 | 0 | 15 | 3,312 | 4,243 | 2,232 | 2,011 | -1 | -1 |
-- Copyright (c) 2013-2015 PivotCloud, Inc.
--
-- Aws.Kinesis.Client.Internal.Queue
--
-- Please feel free to contact us at licensing@pivotmail.com with any
-- contributions, additions, or other feedback; we would love to hear from
-- you.
--
-- 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.
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UnicodeSyntax #-}
-- |
-- Module: Aws.Kinesis.Client.Internal.Queue
-- Copyright: Copyright © 2013-2015 PivotCloud, Inc.
-- License: Apache-2.0
-- Maintainer: Jon Sterling <jsterling@alephcloud.com>
-- Stability: experimental
--
module Aws.Kinesis.Client.Internal.Queue
( BoundedCloseableQueue(..)
) where
import Control.Applicative
import Control.Concurrent.STM
import Control.Concurrent.STM.TBMQueue
import Control.Concurrent.STM.TBMChan
import Control.Monad.Unicode
import Numeric.Natural
import Prelude.Unicode
-- | A signature for bounded, closeable queues.
--
class BoundedCloseableQueue q α | q → α where
-- Create a queue with size @n@.
newQueue
∷ Natural -- ^ the size @n@ of the queue
→ IO q
-- Close the queue.
closeQueue
∷ q
→ IO ()
-- | Returns 'False' if and only if the queue is closed. If the queue is full
-- this function shall block.
writeQueue
∷ q
→ α
→ IO Bool
-- | Non-blocking version of 'writeQueue'. Returns 'Nothing' if the queue was
-- full. Otherwise it returns 'Just True' if the value was successfully
-- written and 'Just False' if the queue was closed.
tryWriteQueue
∷ q
→ α
→ IO (Maybe Bool)
-- | Returns 'Nothing' if and only if the queue is closed. If this queue is
-- empty this function blocks.
readQueue
∷ q
→ IO (Maybe α)
-- | Take up to @n@ items from the queue with a timeout of @t@.
takeQueueTimeout
∷ q
→ Natural -- ^ the number of items @n@ to take
→ Natural -- ^ the timeout @t@ in microseconds
→ IO [α]
-- | Whether the queue is empty.
isEmptyQueue
∷ q
→ IO Bool
-- | Whether the queue is closed.
isClosedQueue
∷ q
→ IO Bool
-- | Whether the queue is empty and closed. The trivial default
-- implementation may be overridden with one which provides transactional
-- guarantees.
isClosedAndEmptyQueue
∷ q
→ IO Bool
isClosedAndEmptyQueue q =
(&&) <$> isEmptyQueue q <*> isClosedQueue q
instance BoundedCloseableQueue (TBMQueue a) a where
newQueue =
newTBMQueueIO ∘ fromIntegral
closeQueue =
atomically ∘ closeTBMQueue
writeQueue q a =
atomically $ isClosedTBMQueue q ≫= \case
True → return False
False → True <$ writeTBMQueue q a
tryWriteQueue q a =
atomically $ tryWriteTBMQueue q a ≫= \case
Nothing → return $ Just False
Just False → return Nothing
Just True → return $ Just True
readQueue =
atomically ∘ readTBMQueue
takeQueueTimeout q n timeoutDelay = do
timedOutVar ← registerDelay $ fromIntegral timeoutDelay
let
timeout =
readTVar timedOutVar ≫= check
readItems xs = do
atomically (Left <$> timeout <|> Right <$> readTBMQueue q) ≫= \case
Left _ → return xs
Right Nothing → return xs
Right (Just x) → go (x:xs)
go xs
| length xs ≥ fromIntegral n = return xs
| otherwise = readItems xs
go []
isClosedQueue =
atomically ∘ isClosedTBMQueue
isEmptyQueue =
atomically ∘ isEmptyTBMQueue
isClosedAndEmptyQueue q =
atomically $
(&&) <$> isClosedTBMQueue q <*> isEmptyTBMQueue q
instance BoundedCloseableQueue (TBMChan a) a where
newQueue =
newTBMChanIO ∘ fromIntegral
closeQueue =
atomically ∘ closeTBMChan
writeQueue q a =
atomically $ isClosedTBMChan q ≫= \case
True → return False
False → True <$ writeTBMChan q a
tryWriteQueue q a =
atomically $ tryWriteTBMChan q a ≫= \case
Nothing → return $ Just False
Just False → return Nothing
Just True → return $ Just True
readQueue =
atomically ∘ readTBMChan
isClosedQueue =
atomically ∘ isClosedTBMChan
isEmptyQueue =
atomically ∘ isEmptyTBMChan
isClosedAndEmptyQueue q =
atomically $
(&&) <$> isClosedTBMChan q <*> isEmptyTBMChan q
takeQueueTimeout q n timeoutDelay = do
timedOutVar ← registerDelay $ fromIntegral timeoutDelay
let
timeout =
readTVar timedOutVar ≫= check
readItems xs = do
atomically (Left <$> timeout <|> Right <$> readTBMChan q) ≫= \case
Left _ → return xs
Right Nothing → return xs
Right (Just x) → go (x:xs)
go xs
| length xs ≥ fromIntegral n = return xs
| otherwise = readItems xs
go []
| alephcloud/hs-aws-kinesis-client | src/Aws/Kinesis/Client/Internal/Queue.hs | apache-2.0 | 5,396 | 11 | 26 | 1,303 | 1,060 | 535 | 525 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
module Neovim.EmbeddedRPCSpec
where
import Test.Hspec
import Test.HUnit
import Neovim
import Neovim.Test
import qualified Neovim.Context.Internal as Internal
import Neovim.Quickfix
import Neovim.RPC.Common
import Neovim.RPC.EventHandler
import Neovim.RPC.FunctionCall (atomically')
import Neovim.RPC.SocketReader
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad.Reader (runReaderT)
import Control.Monad.State (runStateT)
import Control.Monad.Trans.Resource (runResourceT)
import qualified Data.Map as Map
import System.Directory
import System.Exit (ExitCode (..))
import System.IO (hClose)
import System.Process
spec :: Spec
spec = parallel $ do
let helloFile = "test-files/hello"
withNeovimEmbedded f a = testWithEmbeddedNeovim f 3 () () a
describe "Read hello test file" .
it "should match 'Hello, World!'" . withNeovimEmbedded (Just helloFile) $ do
bs <- vim_get_buffers
l <- vim_get_current_line
liftIO $ l `shouldBe` Right "Hello, World!"
liftIO $ length bs `shouldBe` 1
describe "New empty buffer test" $ do
it "should contain the test text" . withNeovimEmbedded Nothing $ do
cl0 <- vim_get_current_line
liftIO $ cl0 `shouldBe` Right ""
bs <- vim_get_buffers
liftIO $ length bs `shouldBe` 1
let testContent = "Test on empty buffer"
vim_set_current_line testContent
cl1 <- vim_get_current_line
liftIO $ cl1 `shouldBe` Right testContent
it "should create a new buffer" . withNeovimEmbedded Nothing $ do
bs0 <- vim_get_buffers
liftIO $ length bs0 `shouldBe` 1
vim_command "new"
bs1 <- vim_get_buffers
liftIO $ length bs1 `shouldBe` 2
vim_command "new"
bs2 <- vim_get_buffers
liftIO $ length bs2 `shouldBe` 3
it "should set the quickfix list" . withNeovimEmbedded Nothing $ do
let q = quickfixListItem (Left 1) (Left 0) :: QuickfixListItem String
setqflist [q] Replace
Right q' <- vim_eval "getqflist()"
liftIO $ fromObjectUnsafe q' `shouldBe` [q]
| lslah/nvim-hs | test-suite/Neovim/EmbeddedRPCSpec.hs | apache-2.0 | 2,403 | 0 | 19 | 747 | 580 | 296 | 284 | 56 | 1 |
factorial n = product [1..n]
| WillianLauber/haskell | fat.hs | apache-2.0 | 30 | 0 | 6 | 6 | 17 | 8 | 9 | 1 | 1 |
{-# LANGUAGE RankNTypes #-}
module Lycopene.Process
( runCommand
-- , buildProcess
-- , runProcess
-- , Chunk
-- , module Lycopene.Process.Internal
) where
import Lycopene.Option (LycoCommand(..), Command(..))
import Lycopene.Configuration (Configuration(..))
import Lycopene.Action
import Lycopene.Action.Version (version)
import Lycopene.Action.Configure (prepareConfigure, configure)
import Lycopene.Action.Init (initialize)
import Lycopene.Action.Ls (listIssues)
import Lycopene.Action.New (newIssue)
import Lycopene.Action.Pj (listProjects)
import Lycopene.Action.Sp (listSprints)
import Lycopene.Action.Run (record)
import Lycopene.Action.Hs (listHistories)
import Lycopene.Action.Done (doneIssue)
import Control.Concurrent (threadDelay)
import Data.Time.Clock (getCurrentTime)
import Data.Time.LocalTime (utcToLocalTime, getCurrentTimeZone, LocalTime)
getCurrentLocalTime :: IO LocalTime
getCurrentLocalTime = utcToLocalTime <$> getCurrentTimeZone <*> getCurrentTime
runCommand :: Configuration -> LycoCommand -> IO ()
runCommand cfg (LycoCommand commonOpt cmd) =
let execAction :: Action () -> IO ()
execAction = (>>= either print return) . handleResult . runAction cfg
subcmd Version = execAction (version >>= send)
subcmd Configure = execAction ((prepareConfigure (datapath cfg) >> configure >> return (datapath cfg)) >>= send)
subcmd (Init mName mDesc path) = execAction (initialize mName mDesc path >>= send)
subcmd (Ls showAll) = execAction (listIssues showAll >>= mapM_ send)
subcmd (New iTitle mDesc) = execAction (newIssue iTitle mDesc >>= send)
subcmd Pj = execAction (listProjects >>= mapM_ send)
subcmd Sp = execAction (listSprints >>= mapM_ send)
subcmd (Hs i) = execAction (listHistories i >>= mapM_ send)
subcmd (Run i md mc) = do
clt <- getCurrentLocalTime
threadDelay (pomodoroMinutes cfg)
execAction (record i clt)
putStrLn "Successfully end"
subcmd (Done i) = execAction (doneIssue i)
in subcmd cmd
| utky/lycopene | backup/Process.hs | apache-2.0 | 2,402 | 0 | 17 | 707 | 630 | 336 | 294 | 40 | 10 |
module System.EtCetera.Internal.Utils where
import Data.Char (toLower, toUpper)
capitalize :: String -> String
capitalize [] = []
capitalize (c:cs) = toUpper c:cs
| paluh/et-cetera | src/System/EtCetera/Internal/Utils.hs | bsd-3-clause | 175 | 0 | 7 | 33 | 64 | 36 | 28 | 5 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Languages.FILL.Parser.Tokenizer (module Languages.FILL.Parser.Token,
triv,
inT,
be,
void,
tensor,
par,
linImp,
top,
bottom,
leT,
symbol,
var,
parens) where
import Text.Parsec hiding (satisfy)
import Languages.FILL.Parser.Token
satisfy :: Monad m => (Token -> Maybe a) -> ParsecT [Token] u m a
satisfy = tokenPrim show next_pos
where
next_pos :: SourcePos -> Token -> [Token] -> SourcePos
next_pos p _ [] = p
next_pos p _ ((_, AlexPn _ l c):_) = setSourceColumn (setSourceLine p l) c
constParser :: Monad m => ALLTok -> ParsecT [Token] u m ()
constParser t = satisfy p <?> show t
where
p (t',_) | t == t' = Just ()
p _ = Nothing
triv :: Monad m => ParsecT [Token] u m ()
triv = constParser Triv
inT :: Monad m => ParsecT [Token] u m ()
inT = constParser In
be :: Monad m => ParsecT [Token] u m ()
be = constParser Be
void :: Monad m => ParsecT [Token] u m ()
void = constParser Void
tensor :: Monad m => ParsecT [Token] u m ()
tensor = constParser Tensor
par :: Monad m => ParsecT [Token] u m ()
par = constParser Par
linImp :: Monad m => ParsecT [Token] u m ()
linImp = constParser LinImp
top :: Monad m => ParsecT [Token] u m ()
top = constParser Top
bottom :: Monad m => ParsecT [Token] u m ()
bottom = constParser Bottom
leT :: Monad m => ParsecT [Token] u m ()
leT = constParser Let
symbol :: Monad m => Char -> ParsecT [Token] u m Char
symbol s = satisfy p <?> show s
where
p (Sym s',_) | s == s' = Just s
p _ = Nothing
var :: Monad m => ParsecT [Token] u m String
var = satisfy p <?> "variable"
where
p (Var s,_) = Just s
p _ = Nothing
parens :: Monad m => ParsecT [Token] u m a -> ParsecT [Token] u m a
parens pr = do
symbol '('
x <- pr
symbol ')'
return x | heades/Agda-LLS | Source/ALL/Languages/FILL/Parser/Tokenizer.hs | bsd-3-clause | 2,294 | 0 | 11 | 932 | 857 | 437 | 420 | 60 | 2 |
{-# LANGUAGE TemplateHaskell #-}
-- |
-- Module: CommandWrapper.Subcommand.Options
-- Description: Command line option parser for Command Wrapper subcommand.
-- Copyright: (c) 2018-2020 Peter Trško
-- License: BSD3
--
-- Maintainer: peter.trsko@gmail.com
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- Command line option parser for Command Wrapper subcommand.
module CommandWrapper.Subcommand.Options
(
-- * Parse Subcommand Options
SubcommandProps(..)
, noPreprocessing
, runSubcommand
-- ** Help
, helpFlag
, helpFlag'
, helpFlagFields
-- ** Completion
, completionInfoFlag
, completionInfoFlagFields
, completionInfoHashFlag
, completionInfoHashFlagFields
, completionOptions
, printCommandWrapperStyleCompletionInfoExpression
, printCommandWrapperStyleCompletionInfoExpressionHash
, printOptparseCompletionInfoExpression
, printOptparseCompletionInfoExpressionHash
-- * Internals
, Mode(..)
)
where
import Control.Applicative ((<*>), many)
import Data.Foldable (asum)
import Data.Function (($), (.), const)
import Data.Functor (Functor, (<$>), fmap)
import Data.Maybe (Maybe(Just, Nothing), maybe)
import Data.Monoid (Endo(Endo, appEndo), Monoid, mempty)
import Data.Semigroup ((<>))
import Data.String (String)
import Data.Void (Void)
import Data.Word (Word)
import GHC.Generics (Generic)
import System.IO (Handle, IO, stdout)
import Text.Show (Show)
import qualified Data.CaseInsensitive as CI (mk)
import Data.Text (Text)
import qualified Data.Text.IO as Text (hPutStr)
import qualified Dhall.Core as Dhall (Expr, denote)
import qualified Dhall.Import as Dhall (hashExpressionToCode)
import qualified Dhall.Parser as Dhall (Src)
import qualified Dhall.Pretty as Dhall (CharacterSet(Unicode))
import qualified Dhall.TH (staticDhallExpression)
import Data.Generics.Product.Typed (HasType, getTyped)
import Data.Monoid.Endo (mapEndo)
import Data.Monoid.Endo.Fold (dualFoldEndo)
import qualified Data.Text.Prettyprint.Doc as Pretty (Doc)
import qualified Data.Text.Prettyprint.Doc.Render.Terminal as Pretty (AnsiStyle)
import qualified Options.Applicative as Options
( HasName
, Mod
, Parser
, ParserInfo
, auto
, defaultPrefs
, flag
, flag'
, strArgument
, info
, internal
, long
, maybeReader
, metavar
, option
, short
)
import CommandWrapper.Core.Config.ColourOutput (ColourOutput(Never))
import CommandWrapper.Core.Config.Shell (Shell)
import qualified CommandWrapper.Core.Config.Shell as Shell (parse)
import qualified CommandWrapper.Core.Dhall as Dhall (hPutExpr)
import CommandWrapper.Core.Environment (Params(Params, colour, verbosity))
import CommandWrapper.Core.Message (Result, defaultLayoutOptions, outWith)
import CommandWrapper.Core.Options.Optparse (subcommandParse)
-- | Mode of operation of a subcommand. It can be either 'Action', which is
-- the functionality of the subcommand or one of the modes expected by the
-- Subcommand Protocol (see @command-wrapper-subcommand-protocol(7)@ manual
-- page for more information).
data Mode action
= Action action
-- ^ Subcommand @action@, i.e. the functionality provided by the subcommand
-- itself.
| DefaultAction
-- ^ Invoke a default action based on what subcommand declared as one.
| CompletionInfo
-- ^ Mode initiated by @--completion-info@ command line option that is
-- mandated by Subcommand Protocol.
--
-- In this mode we display a Dhall expressions that tells Command Wrapper
-- how to call command line completion on the subcommand. This way
-- subcommand is free to implement completion as it wants.
| CompletionInfoHash
-- ^ Mode initiated by @--completion-info-hash@ that prints semantic hash
-- of Dhall expressions printed by 'CompletionInfo' mode.
| Completion Word Shell [String]
-- ^ Command line completion mode initiated when subcommand is called using
-- convention described by 'CompletionInfo' mode.
| Help
-- ^ Print help message mode initiated by @--help|-h@ options. This mode
-- is also mandated by Subcommand Protocol.
deriving stock (Functor, Generic, Show)
-- | Parameters of 'runSubcommand' function.
data SubcommandProps params action = SubcommandProps
{ preprocess :: params -> [String] -> (params, [String])
-- ^ Pre-process inputs before doing anything. This is useful to e.g.
-- split\/filter arguments.
, doCompletion :: params -> Word -> Shell -> [String] -> IO ()
-- ^ Perform command line completion using this action.
, helpMsg :: params -> Pretty.Doc (Result Pretty.AnsiStyle)
-- ^ Help message to be printed if @--help|-h@ is invoked.
, actionOptions :: Options.Parser (Endo (Maybe action))
-- ^ Subcommand options parser. It will be integrated into bigger parser
-- that handles options mandated by Subcommand Protocol as well.
, defaultAction :: Maybe action
-- ^ Default action to be used when `actionOptions` is either not invoked
-- or returns `Nothing`.
--
-- If this value is set to `Nothing` and `actionOptions` doesn't change it
-- we'll print `Help` information. This is usually the case when there
-- were no options passed to our application. If you want to provide
-- custom error message for this then define an action for this purpose and
-- set it as 'defaultAction'.
, params :: params
-- ^ Subcommand parameters, usually just parsed environment variables. It
-- has to contain a field of type 'Params'. Those are values passed by
-- Command Wrapper via Subcommand Protocol.
, arguments :: [String]
-- ^ Subcommand command line arguments.
}
-- | Identity to use when there is no need to do anything as part of
-- 'preprocess' stage.
noPreprocessing :: params -> [String] -> (params, [String])
noPreprocessing = (,)
-- | Parse subcommand options and run subcommand main action.
runSubcommand
:: forall params action
. HasType Params params
=> SubcommandProps params action
-> (params -> action -> IO ())
-> IO ()
runSubcommand SubcommandProps{..} doAction = do
let (params', arguments') = preprocess params arguments
protoParams = getTyped @Params params'
updateMode
<- subcommandParse protoParams Options.defaultPrefs info arguments'
case updateMode `appEndo` DefaultAction of
Action action ->
doAction params' action
DefaultAction ->
case defaultAction of
Nothing ->
doHelpMsg params' protoParams
Just action ->
doAction params' action
CompletionInfo ->
printCommandWrapperStyleCompletionInfoExpression stdout
CompletionInfoHash ->
printCommandWrapperStyleCompletionInfoExpressionHash stdout
Completion index shell words ->
doCompletion params' index shell words
Help ->
doHelpMsg params' protoParams
where
info :: Options.ParserInfo (Endo (Mode action))
info = (`Options.info` mempty) $ asum
[ helpFlag' (constEndo Help)
, dualFoldEndo
<$> fmap (mapEndo mapActionMode) actionOptions
<*> helpFlag (constEndo Help)
, completionOptions (\i s as -> constEndo (Completion i s as))
, completionInfoFlag (constEndo CompletionInfo)
, completionInfoHashFlag (constEndo CompletionInfoHash)
]
constEndo :: a -> Endo a
constEndo a = Endo (const a)
mapActionMode
:: (Maybe action -> Maybe action)
-> Mode action -> Mode action
mapActionMode f = \case
Action action ->
maybe DefaultAction Action (f (Just action))
DefaultAction ->
maybe DefaultAction Action (f defaultAction)
mode ->
mode
doHelpMsg params' protoParams = do
let Params{colour, verbosity} = protoParams
outWith defaultLayoutOptions verbosity colour stdout (helpMsg params')
-- {{{ Help Options -----------------------------------------------------------
helpFlag :: Monoid mode => mode -> Options.Parser mode
helpFlag helpMode = Options.flag mempty helpMode helpFlagFields
helpFlag' :: mode -> Options.Parser mode
helpFlag' helpMode = Options.flag' helpMode helpFlagFields
helpFlagFields :: Options.HasName f => Options.Mod f a
helpFlagFields = Options.long "help" <> Options.short 'h'
-- }}} Help Options -----------------------------------------------------------
-- {{{ Completion Options -----------------------------------------------------
completionOptions
:: (Word -> Shell -> [String] -> mode)
-> Options.Parser mode
completionOptions completionMode =
Options.flag' completionMode
(Options.long "completion" <> Options.internal)
<*> Options.option Options.auto (Options.long "index" <> Options.internal)
<*> Options.option (Options.maybeReader $ Shell.parse . CI.mk)
(Options.long "shell" <> Options.internal)
<*> many (Options.strArgument (Options.metavar "WORD" <> Options.internal))
completionInfoFlag :: mode -> Options.Parser mode
completionInfoFlag completionInfoMode =
Options.flag' completionInfoMode completionInfoFlagFields
completionInfoFlagFields :: Options.HasName f => Options.Mod f a
completionInfoFlagFields =
Options.long "completion-info" <> Options.internal
completionInfoHashFlag :: mode -> Options.Parser mode
completionInfoHashFlag completionInfoHashMode =
Options.flag' completionInfoHashMode completionInfoHashFlagFields
completionInfoHashFlagFields :: Options.HasName f => Options.Mod f a
completionInfoHashFlagFields =
Options.long "completion-info-hash" <> Options.internal
-- {{{ Optparse-applicative-style Completion Expression ----------------------
-- | Style of calling a subcommand completion functionality that is used by
-- [optparse-applicative](https://hackage.haskell.org/package/optparse-applicative)
-- package.
--
-- > --bash-completion-index=NUM [--bash-completion-word=WORD ...]
printOptparseCompletionInfoExpression
:: Handle
-- ^ Output handle.
-> IO ()
printOptparseCompletionInfoExpression outHandle =
let completionInfo :: Dhall.Expr Dhall.Src Void =
$(Dhall.TH.staticDhallExpression
"./dhall/optparse-completion-info.dhall"
)
in Dhall.hPutExpr Never Dhall.Unicode outHandle completionInfo
printOptparseCompletionInfoExpressionHash :: Handle -> IO ()
printOptparseCompletionInfoExpressionHash h =
Text.hPutStr h optparseCompletionInfoExpressionHash
optparseCompletionInfoExpression :: Dhall.Expr Dhall.Src Void
optparseCompletionInfoExpression =
$(Dhall.TH.staticDhallExpression
"./dhall/optparse-completion-info.dhall"
)
{-# INLINE optparseCompletionInfoExpression #-}
optparseCompletionInfoExpressionHash :: Text
optparseCompletionInfoExpressionHash =
Dhall.hashExpressionToCode (Dhall.denote optparseCompletionInfoExpression)
{-# INLINE optparseCompletionInfoExpressionHash #-}
-- }}} Optparse-applicative-style Completion Expression ----------------------
-- {{{ Command Wrapper-style Completion Expression ----------------------------
-- | Style of calling a subcommand completion functionality that is similar to
-- how Command Wrapper's own @completion@ subcommand works.
--
-- > --completion --index=NUM --shell=SHELL -- [WORD ...]
printCommandWrapperStyleCompletionInfoExpression
:: Handle
-- ^ Output handle.
-> IO ()
printCommandWrapperStyleCompletionInfoExpression outHandle =
Dhall.hPutExpr Never Dhall.Unicode outHandle
commandWrapperStyleCompletionInfoExpression
printCommandWrapperStyleCompletionInfoExpressionHash :: Handle -> IO ()
printCommandWrapperStyleCompletionInfoExpressionHash h =
Text.hPutStr h commandWrapperStyleCompletionInfoExpressionHash
commandWrapperStyleCompletionInfoExpression :: Dhall.Expr Dhall.Src Void
commandWrapperStyleCompletionInfoExpression =
$(Dhall.TH.staticDhallExpression
"./dhall/command-wrapper-style-completion-info.dhall"
)
{-# INLINE commandWrapperStyleCompletionInfoExpression #-}
commandWrapperStyleCompletionInfoExpressionHash :: Text
commandWrapperStyleCompletionInfoExpressionHash = Dhall.hashExpressionToCode
(Dhall.denote commandWrapperStyleCompletionInfoExpression)
{-# INLINE commandWrapperStyleCompletionInfoExpressionHash #-}
-- }}} Command Wrapper-style Completion Expression ----------------------------
| trskop/command-wrapper | command-wrapper-subcommand/src/CommandWrapper/Subcommand/Options.hs | bsd-3-clause | 12,597 | 0 | 15 | 2,373 | 2,101 | 1,195 | 906 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Monad
import CoreSyn
import Data.List
import DynFlags
import GHC
import GHC.Paths (libdir)
import GhcMonad
import DataCon
import HscTypes
import Var
import Outputable
import Name hiding (varName)
import Literal
main = do
forever $ do
defaultErrorHandler defaultLogAction $ do
runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
let dflags' = foldl xopt_set dflags [Opt_ImplicitPrelude]
setSessionDynFlags (updOptLevel 2 (dflags' { ghcLink = LinkBinary
, hscTarget = HscAsm
, ghcMode = OneShot
, optLevel = 2
}))
core <- compileToCoreSimplified "C.hs"
-- liftIO . putStrLn . showppr $ core
-- liftIO $ putStrLn "------------------"
liftIO . putStrLn . ppmodule $ core
ppmodule :: CoreModule -> String
ppmodule CoreModule{..} = intercalate ";" (map ppbind cm_binds)
ppbind :: Bind CoreBndr -> String
ppbind (NonRec a e) = ppbinding a e
ppbind (Rec xs) = intercalate ";" (map (uncurry ppbinding) xs)
ppbinding :: CoreBndr -> Expr CoreBndr -> String
ppbinding name exp = ppname name ++ " = " ++ ppexp exp
ppname :: CoreBndr -> String
ppname v = showppr (nameOccName (varName v))
ppexp :: Expr CoreBndr -> String
ppexp (Var i) = ppvar i
ppexp (Lit lit) = pplit lit
ppexp (App f arg) = parensl f ++ " " ++ parensr arg where
parensl e@Lam{} = wrap (ppexp e)
parensl e = ppexp e
parensr e@Lam{} = wrap (ppexp e)
parensr e@App{} = wrap (ppexp e)
parensr e = ppexp e
wrap x = "(" ++ x ++ ")"
ppexp (Lam i e) = "\\" ++ ppvar i ++ "→" ++ ppexp e
ppexp (Case cond i _ty alts) =
"case " ++ ppexp cond ++ "(" ++ ppname i ++ ")of{" ++ intercalate ";" (map ppalt alts) ++ "}"
ppalt :: Alt CoreBndr -> String
ppalt (con,vars,exp) = ppcon con ++ concat (map (" "++) (map showppr vars)) ++ "→" ++ ppexp exp
ppcon :: AltCon -> String
ppcon (DataAlt c) = ppdatacon c
ppcon (LitAlt l) = pplit l
ppcon DEFAULT = "_"
ppdatacon :: DataCon -> String
ppdatacon = showppr . nameOccName . dataConName
ppvar :: CoreBndr -> String
ppvar v = showppr (nameOccName (varName v))
pplit :: Literal -> String
pplit x = showppr x
showppr :: Outputable a => a -> String
showppr = showSDoc . ppr
| chrisdone/corebot | src/Main.hs | bsd-3-clause | 2,433 | 0 | 21 | 683 | 874 | 441 | 433 | 63 | 4 |
{-# LANGUAGE ForeignFunctionInterface #-}
module LV2
( Desc(..)
, Handle
, exportDesc
, getPort
, readPort
, writePort
, registerDesc
)
where
import Language.Haskell.TH
import Foreign.C.Types
import Foreign.C.String
import Foreign.Ptr
import Foreign.StablePtr
import Foreign.Storable
import Foreign.Marshal.Array
import Foreign.Marshal.Alloc
import Control.Monad
data Desc a = Desc { uri :: String
, ports :: Int
, instantiate :: Ptr () -> CDouble -> CString -> Ptr () -> IO a
--, extensionData :: CString -> IO (Ptr ())
, cleanup :: Handle a -> IO ()
, activate :: Handle a -> IO ()
, deactivate :: Handle a -> IO ()
, run :: Handle a -> Int -> IO ()
}
type Port = Ptr CFloat
data HandleData a = HandleData { hports :: Ptr Port
, desc :: StablePtr (Desc a)
, userData :: a
}
type Handle a = StablePtr (HandleData a)
getPort :: Handle a -> Int -> IO Port
getPort h i = deRefStablePtr h >>= \h' -> peekElemOff (hports h') i
readPort :: Handle a -> Int -> Int -> IO [CFloat]
readPort h i s = getPort h i >>= \p -> peekArray s p
writePort :: Handle a -> Int -> [CFloat] -> IO ()
writePort h i d = getPort h i >>= \p -> pokeArray p d
instantiateHs :: StablePtr (Desc a) -> Ptr () -> CDouble -> CString -> Ptr () -> IO (Handle a)
instantiateHs h x1 x2 x3 x4 = do
d@Desc{instantiate=i} <- deRefStablePtr h
ud <- i x1 x2 x3 x4
p <- mallocArray $ ports d
newStablePtr HandleData { hports = p, desc = h, userData = ud }
callbackWrapper f h = liftM f (deRefStablePtr h >>= deRefStablePtr . desc)
cleanupHs :: Handle a -> IO ()
cleanupHs h = do
callbackWrapper cleanup h >>= \f -> f h
liftM hports (deRefStablePtr h) >>= free
freeStablePtr h
activateHs :: Handle a -> IO ()
activateHs h = callbackWrapper activate h >>= \f -> f h
deactivateHs :: Handle a -> IO ()
deactivateHs h = callbackWrapper deactivate h >>= \f -> f h
connectPortHs :: Handle a -> Int -> Ptr CFloat -> IO ()
connectPortHs h i d = do
p <- liftM hports $ deRefStablePtr h
pokeElemOff p i d
runHs:: Handle a -> Int -> IO ()
runHs h s = callbackWrapper run h >>= \f -> f h s
--extensionDataHs :: CString -> Ptr ()
--extensionDataHs _ = nullPtr
foreign export ccall cleanupHs :: Handle a -> IO ()
--foreign export ccall extensionDataHs :: CString -> Ptr ()
foreign export ccall activateHs :: Handle a -> IO ()
foreign export ccall deactivateHs :: Handle a -> IO ()
foreign export ccall connectPortHs :: Handle a -> Int -> Ptr CFloat -> IO ()
foreign export ccall runHs :: Handle a -> Int -> IO ()
descUri :: StablePtr (Desc a) -> IO CString
descUri h = deRefStablePtr h >>= newCString . uri
type Inst a = Ptr () -> CDouble -> CString -> Ptr () -> IO (Handle a)
descInst :: StablePtr (Desc a) -> IO (FunPtr (Inst a))
descInst h = mkInst $ instantiateHs h
foreign export ccall descUri :: StablePtr (Desc a) -> IO CString
foreign import ccall "wrapper" mkInst :: Inst a -> IO (FunPtr (Inst a))
foreign export ccall descInst :: StablePtr (Desc a) -> IO (FunPtr (Inst a))
foreign import ccall "register_plugin" c_register_plugin :: StablePtr (Desc ()) -> IO ()
registerDesc :: Desc () -> IO ()
registerDesc d = newStablePtr d >>= c_register_plugin
exportDesc :: Name -> Q [Dec]
exportDesc name = do
VarI _ t _ _ <- reify name -- TODO: force function type
return [ForeignD (ExportF CCall "hs_register_plugins" name t)]
| mmartin/haskell-lv2 | src/LV2.hs | bsd-3-clause | 3,656 | 0 | 14 | 1,005 | 1,384 | 695 | 689 | 78 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
module Data.Pairing
( Zap(..)
, pairEffect
) where
import Control.Comonad (Comonad, extract)
import Control.Comonad.Cofree (Cofree (..), unwrap)
import Control.Comonad.Trans.Cofree (CofreeT ())
import Control.Monad.Free (Free (..))
class Zap f g | f -> g, g -> f where
zap :: (a -> b -> r) -> f a -> g b -> r
instance {-# OVERLAPPABLE #-} Zap f g => Zap g f where
zap f a b = zap (flip f) b a
instance Zap f g => Zap (Free f) (Cofree g) where
zap p (Pure a ) (b :< _ ) = p a b
zap p (Free as) (_ :< bs) = zap (zap p) as bs
instance Zap ((,) a) ((->) a) where
zap f (x, a) xtob = f a (xtob x)
pairEffect :: ( Zap f g
, Comonad w
, Functor g
)
=> (a -> b -> c)
-> Free f a
-> CofreeT g w b
-> c
pairEffect f (Pure a ) b = f a $ extract b
pairEffect f (Free as) b = zap (pairEffect f) as $ unwrap b
| isovector/rpg-gen | src/Data/Pairing.hs | bsd-3-clause | 1,093 | 0 | 10 | 344 | 467 | 249 | 218 | 29 | 1 |
{-# Language RecordWildCards #-}
{-# Language OverloadedStrings #-}
{-# Language DataKinds #-}
{-# Language TypeFamilies #-}
{-# Language FlexibleContexts #-}
{-# Language ScopedTypeVariables #-}
{-# Language TemplateHaskell #-}
module Network.IRC.Runner where
import Hooks.Algebra
import Network.IRC
import Network.Socket hiding (connect)
import Network.Simple.TCP
import Control.Monad.Writer
import Control.Monad.Reader
import Data.Text (Text)
import System.IO (IOMode(..), hClose, Handle)
import qualified Data.Text.IO as T
import qualified Data.Text as T
import Control.Concurrent.STM.TChan
import Control.Concurrent.STM (atomically)
import Control.Concurrent.Async.Lifted (async, Async)
import Control.Concurrent (forkIO, ThreadId, threadDelay)
import Data.Acid.Database
import Control.Exception (SomeException, catch)
import Control.Exception.Lifted (bracket)
import Control.Monad.Logger
import Control.Monad.Trans.Control
import Plugin
import Types
data IrcInfo ps = IrcInfo {
hostname :: String
, port :: !Int
, nick :: !Text
, channels :: [Text]
, hooks :: Plugins InMsg ps
}
connectIrc :: IrcInfo ps -> IO ()
connectIrc info@IrcInfo{..} = run `catch` (\e -> let _ = e :: SomeException in threadDelay 30000000 >> connectIrc info)
where
run = runStdoutLoggingT $ do
chans@(inChan, outChan) <- liftIO ((,) <$> atomically newTChan <*> atomically newTChan)
connect hostname (show port) $ \(sock, addr) ->
bracket
(liftIO $ socketToHandle sock ReadWriteMode)
(liftIO . hClose) $ \handle -> do
async $ do
liftIO $ threadDelay (2 * 10^6)
mapM_ (sendMessage' outChan) (initial nick channels)
async (ircWriter outChan handle)
runPlugins chans hooks
ircReader outChan inChan handle
liftIO $ hClose handle
initial :: Text -> [Text] -> [OutMsg]
initial nick channels = [Nick nick, User "foo" "foo" "foo" "foo"] ++ [Join c | c <- channels]
ircWriter :: TChan OutMsg -> Handle -> LoggingT IO ()
ircWriter out handle = forever $ do
msg <- liftIO $ atomically $ readTChan out
let bs = renderMessage msg <> "\r\n"
$logInfo bs
liftIO $ T.hPutStr handle bs
ircReader :: TChan OutMsg -> TChan InMsg -> Handle -> LoggingT IO ()
ircReader outChan inChan h = forever $ do
line <- liftIO (T.strip <$> T.hGetLine h)
let msg = parseLine line
case msg of
Right (Ping response) -> liftIO $ atomically $ writeTChan outChan (Pong response)
Right m -> liftIO $ atomically $ writeTChan inChan m
Left err -> $logWarn ("Unparsed " <> err)
runPlugins :: Hook -> Plugins InMsg apps -> LoggingT IO [Async ()]
runPlugins _ PNil = return []
runPlugins original (plugin :> ps) = do
t <- runPlugin original plugin
ts <- runPlugins original ps
return $ t : ts
runPlugin :: HasApp app (ReadState app) => Hook -> Plugin InMsg app -> LoggingT IO (Async ())
runPlugin original (Plugin env _ w) = do
(inChan, outChan) <- liftIO $ atomically $ duplicate original
async $ forever $ do
msg <- liftIO $ atomically $ readTChan inChan
runReaderT (w msg) (ReadState outChan env)
where
duplicate (a,b) = (,) <$> dupTChan a <*> dupTChan b
| MasseR/FreeIrc | src/Network/IRC/Runner.hs | bsd-3-clause | 3,243 | 0 | 23 | 701 | 1,119 | 579 | 540 | 83 | 3 |
-- | For updating XMonad.
module DevelMain where
import Control.Concurrent
import Foreign.Store
import Main
import System.Process
-- | Start or restart xmonad.
update =
do callCommand "killall xmonad"
forkIO (callCommand "dist/build/xmonad/xmonad")
| chrisdone/chrisdone-xmonad | src/DevelMain.hs | bsd-3-clause | 259 | 0 | 9 | 41 | 47 | 26 | 21 | 8 | 1 |
{-# LANGUAGE OverloadedStrings, PackageImports #-}
import Control.Applicative
import Control.Monad
import Data.IORef
import Data.List
import Data.Monoid
import Data.Vec.LinAlg.Transform3D
import Data.Vec.Nat
import FRP.Elerea.Param
import GPipeEffects
import GPipeUtils
import Utils as U
import Graphics.GPipe
import qualified Data.Map as Map
import qualified Data.Vec as Vec
import qualified Data.Vect.Float as V
import Graphics.Rendering.OpenGL ( Position(..) )
import Graphics.UI.GLUT( Window,
mainLoop,
postRedisplay,
idleCallback,
passiveMotionCallback,
getArgsAndInitialize,
($=),
KeyboardMouseCallback,
Key(..),
KeyState(..),
SpecialKey(..),
keyboardMouseCallback,
elapsedTime,
get)
main :: IO ()
main = do
getArgsAndInitialize
-- setup FRP environment
(winSize,winSizeSink) <- external (0,0)
(mousePosition,mousePositionSink) <- external (0,0)
(buttonPress,buttonPressSink) <- external False
(fblrPress,fblrPressSink) <- external (False,False,False,False,False)
obj1 <- loadGPipeMesh "Monkey.lcmesh"
obj2 <- loadGPipeMesh "Scene.lcmesh"
obj3 <- loadGPipeMesh "Plane.lcmesh"
obj4 <- loadGPipeMesh "Icosphere.lcmesh"
net <- start $ scene (take 4 $ cycle [obj1,obj2,obj3,obj4]) mousePosition fblrPress buttonPress winSize
keys <- newIORef $ Map.empty
tr <- newIORef =<< get elapsedTime
putStrLn "creating window..."
newWindow "Green Triangle"
(100:.100:.())
(800:.600:.())
(renderFrame tr keys fblrPressSink buttonPressSink winSizeSink net)
(initWindow keys mousePositionSink)
putStrLn "entering mainloop..."
mainLoop
--renderFrame :: Vec2 Int -> IO (FrameBuffer RGBFormat () ())
renderFrame tr keys fblrPress buttonPress winSize net (w:.h:.()) = do
km <- readIORef keys
let keyIsPressed c = case Map.lookup c km of
Nothing -> False
Just v -> v
winSize (w,h)
{-
t <- getTime
resetTime
(x,y) <- getMousePosition
mousePos (fromIntegral x,fromIntegral y)
-}
fblrPress (keyIsPressed $ SpecialKey KeyLeft, keyIsPressed $ SpecialKey KeyUp, keyIsPressed $ SpecialKey KeyDown, keyIsPressed $ SpecialKey KeyRight, False)
buttonPress $ keyIsPressed $ Char ' '
--tmp <- keyIsPressed KeySpace
--print (x,y,tmp)
--updateFPS s t
t <- get elapsedTime
t0 <- readIORef tr
let d = (fromIntegral $ t-t0) / 1000
writeIORef tr t
join $ net d
--initWindow :: Window -> IO ()
initWindow keys mousePositionSink win = do
keyboardMouseCallback $= Just (keyboard keys mousePositionSink)
passiveMotionCallback $= Just (\(Position x y) -> mousePositionSink (fromIntegral x,fromIntegral y))
idleCallback $= Just (postRedisplay (Just win))
{-
scene :: PrimitiveStream Triangle (Vec3 (Vertex Float))
-> Signal (Float, Float)
-> Signal (Bool, Bool, Bool, Bool, Bool)
-> Signal (Bool)
-> Signal (Int, Int)
-> SignalGen Float (Signal (IO (FrameBuffer RGBFormat () ())))
-}
scene objs mousePosition fblrPress buttonPress wh = do
time <- stateful 0 (+)
last2 <- transfer ((0,0),(0,0)) (\_ n (_,b) -> (b,n)) mousePosition
let mouseMove = (\((ox,oy),(nx,ny)) -> (nx-ox,ny-oy)) <$> last2
--let mouseMove = mousePosition
cam <- userCamera (V.Vec3 (-4) 0 0) mouseMove fblrPress
return $ drawGLScene objs <$> wh <*> cam <*> time <*> buttonPress
convMat :: V.Mat4 -> Vec.Mat44 (Vertex Float)
convMat m = toGPU $ (v a):.(v b):.(v c):.(v d):.()
where
V.Mat4 a b c d = V.transpose m
v (V.Vec4 x y z w) = x:.y:.z:.w:.()
{-
drawGLScene :: PrimitiveStream Triangle (Vec3 (Vertex Float))
-> (Int,Int)
-> (V.Vec3, V.Vec3, V.Vec3, t1)
-> Float
-> Bool
-> IO (FrameBuffer RGBFormat () ())
-}
drawGLScene objs (w,h) (cam,dir,up,_) time buttonPress = do
let cm = V.fromProjective (lookat cam (cam + dir) up)
pm = U.perspective 0.1 50 90 (fromIntegral w / fromIntegral h)
lpos = V.Vec3 0.1 2 0.1
lat = (V.Vec3 0 (-100) 0)
lup = V.Vec3 0 1 0
lmat = V.fromProjective (lookat lpos lat lup)
pmat = U.perspective 0.4 5 90 (fromIntegral w / fromIntegral h)
return $ vsm (convMat (cm V..*. pm)) (convMat (cm V..*. pm)) objs
--return $ moments (convMat (cm V..*. pmat)) objs
--return $ simple (convMat (cm V..*. pm)) objs
-- Key -> KeyState -> Modifiers -> Position -> IO ()
keyboard keys mousePos key keyState mods (Position x y) = do
mousePos (fromIntegral x,fromIntegral y)
modifyIORef keys $ \m -> case (key, keyState) of
(c, Down) -> Map.insert c True m
(c, Up) -> Map.insert c False m
| csabahruska/GFXDemo | gpipeDemo.hs | bsd-3-clause | 5,002 | 0 | 14 | 1,370 | 1,477 | 771 | 706 | 94 | 2 |
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, FunctionalDependencies, UnicodeSyntax, KindSignatures, OverlappingInstances, FlexibleInstances, ScopedTypeVariables, FlexibleContexts #-}
module Data.Protobuf (
protobuf
, protobuf'
, readProtobuf
, writeProtobuf
, Protobuf
, ProtobufValue(..)
, module Foreign.C
, module Control.Applicative
, Std__basic_string
, newPb
, derefPb
) where
import Data.Int
import Data.Word
import Data.Char
import Data.ByteString (ByteString)
import Control.Applicative
import Foreign.C
import Foreign.Ptr
import Foreign.ForeignPtr hiding (newForeignPtr, addForeignPtrFinalizer)
import Foreign.ForeignPtr.Unsafe
import Foreign.Concurrent
import Foreign.CPlusPlus
import Foreign.CPlusPlusStdLib
import Language.Haskell.TH
data TypeKind = Assign | Pointer | Vector | MaybeP TypeKind
deriving (Show, Eq)
newPb :: Protobuf a => IO (ForeignPtr a)
newPb = new >>= \p -> addForeignPtrFinalizer p (delete (unsafeForeignPtrToPtr p)) >> return p
derefPb :: ProtobufValue a b => ForeignPtr a -> IO b
derefPb p = withForeignPtr p load
class Protobuf a where
new :: IO (ForeignPtr a)
delete :: Ptr a -> IO ()
class Protobuf a => ProtobufValue a b | a -> b, b -> a where
load :: Ptr a -> IO b
assign :: ForeignPtr a -> b -> IO ()
-- "not really" an orphan
instance (ProtobufValue b a) => CPlusPlusLand (Maybe a) (Ptr b) where
to Nothing = return nullPtr
to (Just x) = to x
from x = if x == nullPtr then return Nothing else (Just `fmap` from x)
-- "not really" an orphan
instance (ProtobufValue b a) => CPlusPlusLand a (Ptr b) where
to x = new >>= \(p :: ForeignPtr b) -> assign p x >> withForeignPtr p (\p' -> return (p' :: Ptr b))
from = load
cplusplus "haskell::readProtobuf(char const*, google::protobuf::Message&)" "cbits/hsprotobuf.o" [t|CString -> Ptr () -> IO CInt|]
cplusplus "haskell::writeProtobuf(char const*, google::protobuf::Message&)" "cbits/hsprotobuf.o" [t|CString -> Ptr () -> IO CInt|]
readProtobuf :: Protobuf a => FilePath -> ForeignPtr a -> IO ()
readProtobuf f m = do
s <- newCString f
r <- withForeignPtr m $ haskell__readProtobuf s . castPtr
if r /= 0
then error "readProtobuf exception" -- TODO: error
else return ()
writeProtobuf :: Protobuf a => FilePath -> ForeignPtr a -> IO ()
writeProtobuf f m = do
s <- newCString f
r <- withForeignPtr m $ haskell__writeProtobuf s . castPtr
if r /= 0
then error "writeProtobuf exception" -- TODO: error
else return ()
-- use ("name", [t|String|])
protobuf' :: FilePath -> String -> [(String, Type)] -> Q [Dec]
protobuf' objfile tname fields = do
let dataDefn = DataD [] (mkName tname) [] [] []
let typeDefn = TySynD (mkName (tname ++ "Ptr")) [] (AppT (ConT ''ForeignPtr) (ConT (mkName tname)))
let lowCaseTname = toLower (head tname):(tail tname)
con <- cplusplus (tname ++ "::New() const") objfile
(appT (conT ''IO) (appT (conT ''Ptr) (conT (mkName tname))))
del <- cplusplus (tname ++ "::~" ++ tname ++ "()") objfile
(appT (appT arrowT (appT (conT ''Ptr) (conT (mkName tname)))) (appT (conT ''IO) (conT ''())))
instanceDef <- instanceD (cxt []) (appT (conT ''Protobuf) (conT (mkName tname)))
[valD (varP 'new) (normalB
(infixE
(Just (varE (mkName (lowCaseTname ++ "__New"))))
(varE '(>>=))
(Just (varE 'newForeignPtr_)))) []
,funD 'delete [clause [varP (mkName "p")]
(normalB (appE
(varE (mkName (lowCaseTname ++ "__~" ++ tname)))
(varE (mkName "p")))) []]]
xs <- fmap concat $ mapM (deHaskell objfile tname) fields
return $ dataDefn:typeDefn:instanceDef:[] ++ con ++ del ++ xs
protobuf :: FilePath -> Name -> Q [Dec]
protobuf objfile name = reify name >>= \val -> case val of
(TyConI (DataD [] _tyName [] [cx@(RecC _conName fields)] [])) -> do
pb <- protobuf' objfile (init (nameBase name)) $ map (\(n, _, t) -> (nameBase n, t)) fields
xs <- instanceD (cxt [])
(appT (appT (conT ''ProtobufValue) (conT (mkName (init (nameBase name))))) (conT name))
[
loadDef (nameBase name) cx
, assignDef (nameBase name) cx
]
return $ pb ++ [xs]
x -> error $ "can not handle decl of shape: " ++ show x
loadDef :: String -> Con -> DecQ
loadDef name (RecC conName fields) =
let
n' = let (x:xs) = init name in toLower x:xs
((fstField, _, fstType):_) = fields
apply y (Vector, _, _) =
-- optional_features_size >>= mapM optional_features . \x -> [0..(x-1)]
(InfixE
(Just (AppE (VarE (mkName (n' ++ "__" ++ nameBase y ++ "_size"))) (VarE (mkName "x"))))
(VarE '(>>=))
(Just
(InfixE
(Just
(AppE
(VarE 'mapM)
(LamE [VarP (mkName "y")]
(InfixE
(Just
(AppE
(AppE
(VarE (mkName (n' ++ "__" ++ nameBase y)))
(VarE (mkName "x")))
(VarE (mkName "y"))))
(VarE '(>>=))
(Just (VarE 'from))))))
(VarE '(.))
(Just
(LamE [VarP (mkName "y")]
(ArithSeqE
(FromToR (LitE (IntegerL 0))
(InfixE
(Just (VarE (mkName "y")))
(VarE '(-))
(Just (LitE (IntegerL 1)))))))))))
apply y (MaybeP typ', _, _) =
(InfixE
(Just
(AppE
(AppE
(case typ' of
Pointer -> (VarE 'getMaybePtr)
Assign -> (VarE 'getMaybeVal)
_ -> error "impossible data defn")
(AppE
(VarE
(mkName (n' ++ "__" ++ nameBase y)))
(VarE xv)))
(AppE
(VarE
(mkName (n' ++ "__has_" ++ nameBase y)))
(VarE xv))))
(VarE '(>>=))
(Just (VarE 'from)))
-- Assign and Pointer
apply y (_, _, _) =
(InfixE
(Just (AppE (VarE (mkName (n' ++ "__" ++ nameBase y))) (VarE xv)))
(VarE '(>>=))
(Just (VarE 'from)))
xv = mkName "x"
in funD 'load
-- TODO: todo for loading an array NEXT
[clause [varP xv]
(normalB
(return (foldl
(\x (y, _, t) -> InfixE (Just x) (VarE '(<*>))
(Just (apply y (typeinfo t)))
)
(InfixE (Just (ConE conName)) (VarE '(<$>))
(Just (apply fstField (typeinfo fstType))))
(tail fields)
)))
[] ]
loadDef _ _ = error "invalid constructor definition"
assignDef :: String -> Con -> DecQ
assignDef name (RecC _conName fields) =
let
n' = let (x:xs) = init name in toLower x:xs
((fstField, _, fstType):_) = fields
sety y (Vector, ftyp, _) =
(InfixE
(Just
(AppE (VarE 'to)
(AppE (VarE (mkName (show y))) (VarE xv))))
-- TODO: should clear the array first?
(VarE '(>>=))
(Just
(AppE
(VarE 'mapM_)
(setApply n' "__add_" ftyp pp pv y Nothing))))
sety y (Pointer, _, _) =
(InfixE
(Just
(AppE (VarE 'to)
(AppE (VarE (mkName (show y))) (VarE xv))))
(VarE '(>>=))
(Just
(AppE
(VarE (mkName (n' ++ "__set_allocated_" ++ (nameBase y))))
(VarE pv))))
sety y (Assign, ftyp, _) =
(InfixE
(Just
(AppE (VarE 'to)
(AppE (VarE (mkName (show y))) (VarE xv))))
(VarE '(>>=))
(Just
(setApply n' "__set_" ftyp pp pv y Nothing)))
sety y (MaybeP typ', ftyp, _) =
(InfixE
(Just
(AppE (VarE 'to)
(AppE (VarE (mkName (show y))) (VarE xv))))
(VarE '(>>=))
(Just
(AppE
(AppE
(case typ' of
Pointer -> (VarE 'setMaybePtr)
Assign -> (VarE 'setMaybeVal)
_ -> error "invalid data defn")
(setApply n' "__set_" ftyp pp pv y (Just typ')))
(AppE
(VarE (mkName (n' ++ "__clear_" ++ (nameBase y))))
(VarE pv)))))
pv = mkName "pv"
pp = mkName "pp"
xv = mkName "x"
in funD 'assign
[clause [varP pp, varP xv]
(normalB
(appE
(appE (varE 'withForeignPtr) (varE pp))
(lamE [varP pv]
(return
(foldl
(\x (y, _, t) ->
InfixE
(Just x)
(VarE '(>>))
(Just (sety y (typeinfo t))))
(sety fstField (typeinfo fstType))
(tail fields))))))
[]]
assignDef _ _ = error "invalid constructor definition"
setApply :: String -> String -> Type -> Name -> Name -> Name -> Maybe TypeKind -> Exp
setApply n' meth ftyp pp pv y typ' =
(AppE
(VarE (mkName (n' ++ meth
++ (if typ' == Just Pointer then "allocated_" else "")
++ (if ftyp == ConT ''Foreign.CPlusPlusStdLib.Std__basic_string
then "ret_"
else "")
++ (nameBase y))))
(if ftyp == ConT ''Foreign.CPlusPlusStdLib.Std__basic_string
then (VarE pp)
else (VarE pv))
)
deHaskell :: String -> String -> (String, Type) -> Q [Dec]
deHaskell objfile tname (name, typ) = do
let ptrTypName = appT (conT ''Ptr) (conT (mkName tname))
gets <- genGetter tname name ptrTypName objfile typ
sets <- genSetter tname name ptrTypName objfile typ
return $ gets ++ sets
genGetter :: String -> String -> TypeQ -> String -> Type -> Q [Dec]
genGetter tname name ptrTypName objfile typ = do
let (typeKind, ftype, _ctype) = typeinfo typ
case typeKind of
Vector -> do
x <- cplusplus
(tname ++ "::" ++ name ++ "(int) const") objfile
(appT (appT arrowT ptrTypName) (appT (appT arrowT (conT ''Int)) (appT (conT ''IO) (return ftype))))
y <- cplusplus
(tname ++ "::" ++ name ++ "_size() const") objfile
(appT (appT arrowT ptrTypName) (appT (conT ''IO) (conT ''Int)))
return (x ++ y)
MaybeP _typ -> do
g <- cplusplus
(tname ++ "::" ++ name ++ "() const") objfile
(appT (appT arrowT ptrTypName) (appT (conT ''IO) (return ftype)))
s <- cplusplus
(tname ++ "::has_" ++ name ++ "() const") objfile
(appT (appT arrowT ptrTypName) (appT (conT ''IO) (conT ''Bool)))
return (g ++ s)
-- Assign and Pointer
_ -> cplusplus
(tname ++ "::" ++ name ++ "() const") objfile
(appT (appT arrowT ptrTypName) (appT (conT ''IO) (return ftype)))
genSetter :: String -> String -> TypeQ -> String -> Type -> Q [Dec]
genSetter tname name ptrTypName objfile typ = do
let (typeKind, ftype, ctype) = typeinfo typ
isAllocated Pointer n = "allocated_" ++ n
isAllocated _ n = n
case typeKind of
Assign -> do
s <- cplusplus
(tname ++ "::set_" ++ name ++ "(" ++ ctype ++ ")") objfile
(appT (appT arrowT ptrTypName)
(appT (appT arrowT (return ftype)) (appT (conT ''IO) (conT ''()))))
al <- if ftype == ConT ''Foreign.CPlusPlusStdLib.Std__basic_string
then sequence [allocated_set tname name "set"]
else return []
return (s ++ al)
Vector -> do
s <- cplusplus
(tname ++ "::add_" ++ name ++ "(" ++ ctype ++ ")") objfile
(appT
(appT arrowT ptrTypName)
(appT (appT arrowT (return ftype)) (appT (conT ''IO) (conT ''()))))
al <- if ftype == ConT ''Foreign.CPlusPlusStdLib.Std__basic_string
then sequence [allocated_set tname name "add"]
else return []
return (s ++ al)
Pointer -> cplusplus
(tname ++ "::set_allocated_" ++ name ++ "(" ++ ctype ++ ")") objfile
(appT (appT arrowT ptrTypName) (appT (appT arrowT (return ftype)) (appT (conT ''IO) (conT ''()))))
MaybeP typ' -> do
set <- cplusplus
(tname ++ "::set_" ++ isAllocated typ' name ++ "(" ++ ctype ++ ")") objfile
(appT (appT arrowT ptrTypName) (appT (appT arrowT (return ftype)) (appT (conT ''IO) (conT ''()))))
al <- if ftype == ConT ''Foreign.CPlusPlusStdLib.Std__basic_string
then sequence [allocated_set tname name "set"]
else return []
clear <- cplusplus
(tname ++ "::clear_" ++ name ++ "()") objfile
(appT (appT arrowT ptrTypName) (appT (conT ''IO) (conT ''())))
return (set ++ al ++ clear)
allocated_set :: String -> String -> String -> DecQ
allocated_set tname name meth =
(funD (mkName (lower tname ++ "__" ++ meth ++ "_ret_" ++ name))
[clause [varP (mkName "p"), varP (mkName "v")]
(normalB
(appE
(appE (varE 'withForeignPtr) (varE (mkName "p")))
(lamE [varP (mkName "pv")]
(infixE
(Just
(appE
(appE
(varE (mkName (lower tname ++ "__" ++ meth ++ "_" ++ name)))
(varE (mkName "pv")))
(varE (mkName "v"))))
(varE '(>>))
(Just
(appE
(appE
(varE 'retainForeign)
(varE (mkName "p")))
(varE (mkName "v"))))
)))) []])
typeinfo :: Type -> (TypeKind, Type, String)
typeinfo t
| t == ConT ''String = (Assign, ConT ''Std__basic_string, "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&")
| t == ConT ''Bool = (Assign, ConT ''CChar, "bool")
| t == ConT ''Int = (Assign, ConT ''CInt, "int")
| t == ConT ''Int32 = (Assign, ConT ''CInt, "int")
| t == ConT ''Int64 = (Assign, ConT ''CLLong, "long long")
| t == ConT ''Word32 = (Assign, ConT ''CUInt, "unsigned int")
| t == ConT ''ByteString = (Assign, ConT ''Std__basic_string, "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&")
| otherwise =
case t of
ConT x ->
if last (nameBase x) == 'T'
then
-- TODO: reify x to check it is in Protobuf, that way it can be extended by client code, like enum
(Pointer, AppT (ConT ''Ptr) (ConT (mkName (init (nameBase x)))), init (nameBase x) ++ "*")
else
(Assign, t, nameBase x)
-- error $ "unknown type to typeinfo: " ++ nameBase x
AppT (ConT innerT) x -> typeinfo' innerT x
AppT ListT x -> typeinfoList x
_ -> error $ "type info not implemented for: " ++ show t
where
typeinfo' innerT x
| innerT == ''Maybe = let (i, y, z) = typeinfo x in (MaybeP i, y, z)
-- possible: | innerT == ''V.Vector = let (_, y, z) = typeinfo x in (Vector, y, z)
| otherwise = error $ "type info not implemented for: " ++ show innerT
typeinfoList x =
let (_, y, z) = typeinfo x in (Vector, y, z)
lower :: String -> String
lower (x:xs) = toLower x:xs
lower _ = error "NEL" | NICTA/protobuf-native | src/Data/Protobuf.hs | bsd-3-clause | 15,333 | 0 | 35 | 5,061 | 5,978 | 3,050 | 2,928 | 361 | 8 |
{-# LANGUAGE DataKinds,GADTs #-}
module Network.EasyBitcoin.Internal.Signatures
( detSignMsg
, Signature()
, checkSig
)where
import Network.EasyBitcoin.Keys
import Network.EasyBitcoin.Internal.Keys
import Network.EasyBitcoin.Internal.Words
import Network.EasyBitcoin.Internal.CurveConstants
import Network.EasyBitcoin.Internal.ByteString
import Network.EasyBitcoin.Internal.Words
import Network.EasyBitcoin.Internal.HashFunctions
import qualified Data.ByteString as BS
import Data.Binary (Binary, get, put, Word64,Word32,Word16)
import Data.Binary.Get ( getWord64be
, getWord32be
, getWord64le
, getWord8
, getWord16le
, getWord32le
, getByteString
, Get
)
import Data.Binary.Put( putWord64be
, putWord32be
, putWord32le
, putWord64le
, putWord16le
, putWord8
, putByteString
)
import Control.Monad
import GHC.Word
import Control.Applicative
import Data.Bits
import Control.DeepSeq (NFData, rnf)
import Control.Monad (unless, guard)
import Data.Maybe
-- | Sign a message using ECDSA deterministic signatures as defined by
-- RFC 6979 <http://tools.ietf.org/html/rfc6979>
detSignMsg :: Word256 -> Key Private net -> Signature
detSignMsg n (ExtendedPrv _ _ _ _ (PrvKey x)) = detSignMsg_ n x
detSignMsg_ :: Word256 -> FieldN -> Signature
detSignMsg_ h d = go $ hmacDRBGNew (enc d) (encode' h) BS.empty
where
enc::FieldN -> BS.ByteString
enc x = encode' (fromIntegral x ::Word256)
go ws = case hmacDRBGGen ws 32 BS.empty of
(ws', Just k) -> let kI = bsToInteger k
p = mulPoint (fromInteger kI) curveG
sigM = unsafeSignMsg h d (fromInteger kI,p)
in if (isIntegerValidKey kI)
then fromMaybe (go ws') sigM
else go ws'
(_ , Nothing) -> error "detSignMsg: No suitable K value found"
-- Signs a message by providing the nonce
unsafeSignMsg :: Word256 -> FieldN -> (FieldN, Point) -> Maybe Signature
unsafeSignMsg _ 0 _ = Nothing
unsafeSignMsg h d (k,p) = do let (x,_) = getAffine p
-- 4.1.3.3
r = (fromIntegral x :: FieldN)
--guard (r /= 0) -- is it necesary?
e = (fromIntegral h :: FieldN) -- double check this work!
s' = (e + r*d)/k
-- Canonicalize signatures: s <= order/2
-- maxBound/2 = (maxBound+1)/2 = order/2 (because order is odd)
s = if s' > (maxBound `div` 2) then (-s') else s'
-- 4.1.3.4 / 4.1.3.5
--guard (s /= 0)
-- 4.1.3.7
return $ Signature r s
-- Section 4.1.4 http://www.secg.org/download/aid-780/sec1-v2.pdf
-- | Verify an ECDSA signature
checkSig :: Word256 -> Signature -> Key Public net -> Bool
checkSig h sig ( ExtendedPub _ _ _ _ key) = checkSig_ h sig key
where
-- 4.1.4.1 (r and s can not be zero)
checkSig_ _ (Signature 0 _) _ = False
checkSig_ _ (Signature _ 0) _ = False
checkSig_ h (Signature r s) q = case Just $ getAffine p of
Nothing -> False
Just (x,_) -> (fromIntegral x :: FieldN) == r
where
-- 4.1.4.2 / 4.1.4.3
e = (fromIntegral h :: FieldN)
-- 4.1.4.4
s' = inverseN s
u1 = e*s'
u2 = r*s'
-- 4.1.4.5 (u1*G + u2*q)
p = shamirsTrick u1 curveG u2 (pubKeyPoint q)
data Signature = Signature { sigR :: !FieldN
, sigS :: !FieldN
} deriving (Read, Show, Eq)
--------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------
instance Binary Signature where
get = do t <- getWord8 -- 0x30 is DER sequence type
unless (t == 0x30) (fail $ "Bad DER identifier byte " ++ (show t) ++ ". Expecting 0x30")
l <- getWord8 -- Length = (33 + 1 identifier byte + 1 length byte) * 2
isolate (fromIntegral l) $ Signature <$> get <*> get
put (Signature 0 _) = error "0 is an invalid r value in a Signature"
put (Signature _ 0) = error "0 is an invalid s value in a Signature"
put (Signature r s) = do putWord8 0x30
let c = runPut' $ put r >> put s
putWord8 (fromIntegral $ BS.length c)
-- error .show $ (r,s)
putByteString c
shamirsTrick :: FieldN -> Point -> FieldN -> Point -> Point
shamirsTrick r1 p1 r2 p2 = addPoint (mulPoint r1 p1) (mulPoint r2 p2)
------------------------------------------------------------------------------------------------------------------------------
quadraticResidue :: FieldP -> [FieldP]
quadraticResidue x = guard (y^(2 :: Int) == x) >> [y, (-y)]
where
q = (curveP + 1) `div` 4
y = x^q
| vwwv/easy-bitcoin | Network/EasyBitcoin/Internal/Signatures.hs | bsd-3-clause | 5,794 | 0 | 16 | 2,228 | 1,265 | 689 | 576 | 97 | 4 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
module Startups.Interpreter where
import Startups.Base
import Startups.Cards
import Startups.GameTypes
import Control.Monad.Operational
import Control.Monad.State.Strict
import Data.List.NonEmpty
data Strategy p m = Strategy { _doPlayerDecision :: Age -> Turn -> PlayerId -> NonEmpty Card -> GameState -> m (p (PlayerAction, Exchange))
, _doAskCard :: Age -> PlayerId -> NonEmpty Card -> GameState -> Message -> m (p Card)
}
data OperationDict p m = OperationDict { _strat :: Strategy p m
, _doGetPromise :: forall a. p a -> m (Either Message a)
, _doMessage :: GameState -> CommunicationType -> m ()
}
runInterpreter :: Monad m
=> OperationDict p m
-> GameState
-> GameMonad p a
-> m (GameState, Either Message a)
runInterpreter dico gamestate m =
case runState (viewT m) gamestate of
(a, nextstate) -> evalInstrGen dico nextstate a
evalInstrGen :: Monad m
=> OperationDict p m
-> GameState
-> ProgramViewT (GameInstr p) (State GameState) a
-> m (GameState, Either Message a)
evalInstrGen _ gamestate (Return x) = return (gamestate, Right x)
evalInstrGen dico gamestate (a :>>= f) =
let runC a' = runInterpreter dico gamestate (f a')
in case a of
PlayerDecision age turn pid clist -> _doPlayerDecision (_strat dico) age turn pid clist gamestate >>= runC
GetPromise x -> do
o <- _doGetPromise dico x
case o of
Left rr -> return (gamestate, Left rr)
Right v -> runC v
AskCard age pid cards msg -> _doAskCard (_strat dico) age pid cards gamestate msg >>= runC
Message com -> _doMessage dico gamestate com >>= runC
ThrowError err -> return (gamestate, Left err)
CatchError n handler -> do
n' <- runInterpreter dico gamestate n
case n' of
(gs', Left rr) -> runInterpreter dico gs' (handler rr >>= f)
(gs', Right x) -> runInterpreter dico gs' (f x)
| bitemyapp/7startups | Startups/Interpreter.hs | bsd-3-clause | 2,352 | 0 | 18 | 853 | 711 | 356 | 355 | 45 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.