code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{----------------------------------------------------------------------------------------- Module name: WebSockets Made by: Tomas Möre 2015 Usage: This is a WebSockets module inteded to run over an instance of the standard Server IMPORTANT: If you start a websockets session DO NOT attempt to send any kind of HTTP request upon completion ------------------------------------------------------------------------------------------} --http://datatracker.ietf.org/doc/rfc6455/?include_text=1 {-# LANGUAGE OverloadedStrings #-} module WebSocket.Server.WebSocket where import qualified HTTP import qualified Headers as H import Smutt.Utility.Utility import Smutt.HTTP.ErrorResponses import qualified Data.ByteString as B import Data.ByteString.Internal (c2w) import qualified Data.ByteString.Lazy as BL import qualified Data.CaseInsensitive as CI import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified BufferedSocket as BS import qualified Data.Text.Lazy.Encoding as ENC import qualified Data.Text.Encoding as STRICTENC import qualified Data.Text.Encoding.Error as ENC import qualified Network.Socket as NS import Data.Maybe import Data.Either import Data.Monoid import Data.Bits import Data.List import qualified Data.ByteString.Base64 as B64 import qualified Crypto.Hash.SHA1 as SHA1 import qualified Data.Binary as BINARY type PayloadLength = Word64 type Mask = Maybe [Word8] -- Should be infinte list type Fin = Bool type FrameSize = Int -- Positive Int either 16 or 64 type Masked = Bool type CloseText = T.Text type PingPongData = ByteString type WebSocketThunk = (WebSocket -> Request -> IO Response) type CloseStatusCode = Word16 -- Websocket magic number, don't blame me!! :'( guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" data Message = TextMessage TL.Text | BinaryMessage BL.ByteString | CloseMessage StatusCode CloseReasonText data ControllFrame = Ping ByteString | Pong ByteString | Close StatusCode Text type ControllFrames = [ControllFrame] type CloseReasonText = TL.ByteString type Response = Message type Request = Message type MessageWriter = (Message -> IO ()) type MessageReader = Message data WebSocket = WebSocket { bufferedSocket :: BS.BufferedSocket -- reference to the underlying bufferedSocket , messageReader :: (MVar Message) -- When reading a message this will be read. The message is a lazy Text or bytestring. IF , messageWriter :: (MVar MessageWriter) -- , controllFrames :: (IORef ControllFrames) -- Should be treated with atomic operations , onPing :: (WebSocket -> PingPongData -> IO ()) , onPong :: (WebSocket -> PingPongData -> IO()) , onClose :: (WebSocket -> StatusCode -> CloseText -> IO ()) , closeStatus :: IORef (Maybe (StatusCode, CloseMessage)) -- When a close frame is recieved or sent This will be set } data AuthenticationError = InvalidVersion | InvalidMethod | MissingHeader H.HeaderName | InvalidHeader H.HeaderName data AuthenticationData = { , webSocketKey :: ByteString , origin :: Maybe ByteString , webSocketVersion :: Int , webSocketProtocol :: [ByteString] , socketExtensions :: [ByteString] } data FrameHeader = FrameHeader Fin OpCode Masked Mask PayloadLength isFin (FrameHeader fin _ _ _ _ ) = fin opCode (FrameHeader _ code _ _ _ ) = code isMasked (FrameHeader _ _ masked _ _ ) = masked getMask (FrameHeader _ _ _ mask _ ) = mask getPayLoadLength (FrameHeader _ _ _ _ len ) = len {- Opcode: 4 bits Defines the interpretation of the "Payload data". If an unknown opcode is received, the receiving endpoint MUST _Fail the WebSocket Connection_. The following values are defined. * %x0 denotes a continuation frame * %x1 denotes a text frame * %x2 denotes a binary frame * %x3-7 are reserved for further non-control frames * %x8 denotes a connection close * %x9 denotes a ping * %xA denotes a pong * %xB-F are reserved for further control frames -} data OpCode = ConinuationFrame | TextFrame | BinaryFrame | ConnectionClose | Ping | Pong | Reserved | Undefined data StatusCode = NormalClose | GoingAway | ProtocolError | NonAcceptableData | InvalidData | ViolatedPolicy | MessageTooBig | NeedsExtension | UnexpectedCondition | CusomCode Word16 {-- Util --} bufferedSocket :: WebSocket -> BS.BufferedSocket bufferedSocket (WebSocket bSocket _ _ ) = bSocket closeRead :: WebSocket -> IO () closeRead (WebSocket bSocket _ _ ) = BS.closeRead bSocket closeWrite :: WebSocket -> IO () closeWrite (WebSocket bSocket _ _ ) = BS.closeWrite bSocket isReadable :: WebSocket -> IO Bool isReadable (WebSocket bSocket _ _ ) = BS.isReadable bSocket isWriteable :: WebSocket -> IO Bool isWriteable WebSocket bSocket _ _ ) = BS.isWriteable bSocket {-- Utility --} -- When a controll frame should be sent this frame is added to the controll que. -- This function adds the specific frame to the end of the que -- The frame will be sent in between normal frame sending queControllFrame:: WebSocket -> ControllFrame -> IO () queControllFrame webSocket controllFrame = atomicModifyIORef' controllQue (\currentList -> (currentList ++ [controllFrame],())) where controllQue = controllFrames webSocket handOverRead :: WebSocket -> IO () handOverRead = (>>= putMVar (messageReader webSocket)) . unsafeInterLeaveIO . readMessage handOverWrite :: Websocket -> IO () handOverRead = (>>= putMVar (messageWriter webSocket)) . unsafeInterLeaveIO . writeMessage {-- Writing --} writeFreamHeader :: WebSocket -> FrameHeader -> IO () writeFreamHeader webSocket (FrameHeader fin opcode masked maskList messageLength) = let finBit = if fin then 128 else 0 payloadLength = if messageLength < 126 then messageLength else if messageLength <= 65535 then 126 else 127 maskBit = if mask then 128 else 0 extendedPayloadLength = if payloadLength >= 127 then case payloadLength of 126 -> numToWord8List (fromIntegral payloadLength :: Word32) 127 -> numToWord8List (fromIntegral payloadLength :: Word64) --- FIX THIS SHIT else [] firstByte = fromOpCode opcode .|. if fin then 128 else 0 -- Byte for fin and opcode secondByte = maskBit .|. payloadLength frameList = [firstByte, secondByte] ++ extendedPayloadLength ++ maskList in -- SEND SHIT HERE where nSocket = BS.nativeSocket $ bufferedSocket webSocket writeBinaryFrame :: WebSocket -> FrameHeader -> BL.ByteString -> IO () writeTextFrame :: WebSocket -> FrameHeader -> TL.Text -> IO () writeMessage :: WebSocket -> Message -> IO () writeMessage webSocket (CloseMessage statusCode statusText) = BS.send bSocket statusCodeData >> BS.sendText bSocket statusText >> where bSocket = bufferedSocket webSocket statusCodeData = statusCodeToByteString statusCode {- Table From http://datatracker.ietf.org/doc/rfc6455/?include_text=1 describing the bit table of a frame. This is used to make the functions under 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+d-+-+-------+-+-------------+-------------------------------+ |F|R|R|R| opcode|M| Payload len | Extended payload length | |I|S|S|S| (4) |A| (7) | (16/64) | |N|V|V|V| |S| | (if payload len==126/127) | | |1|2|3| |K| | | +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + | Extended payload length continued, if payload len == 127 | + - - - - - - - - - - - - - - - +-------------------------------+ | |Masking-key, if MASK set to 1 | +-------------------------------+-------------------------------+ | Masking-key (continued) | Payload Data | +-------------------------------- - - - - - - - - - - - - - - - + : Payload Data continued ... : + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Payload Data continued ... | +---------------------------------------------------------------+ -} {-- Reading --} readFrameHeader :: WebSocket -> IO FrameHeader readFrameHeader webSocket = do byte1 <- BS.readByte bSocket byte2 <- BS.readByte bSocket let fin = isFin byte1 opCode = toOpCode $ extractOpCode byte1 hasMask = extractIsMaksed byte2 eitherPayload = (payloadLength8 byte2) Right smallPayload = eitherPayload nExtendedBytes = if isRight eitherPayload then 0 else let Left a = eitherPayload in a extendedBytes <- B.unpack <$> BS.read bSocket nExtendedBytes let extendedPayloadLength = shiftWordTo extendedBytes realPayload = if nExtendedBytes == 0 then smallPayload else extendedPayloadLength maskString <- BS.read bSocket (if hasMask then 4 else 0) let maskList = case maskString of "" -> Nothing _ -> Just $ cycle $ B.unpack maskString return $ FrameHeader fin opcode masked maskList realPayload where bSocket = bufferedSocket webSocket -- readFrames :: WebSocket -> IO Bl.ByteString readFrames webSocket = do readable <- isReadable webSocket if readable then do fHead@(FrameHeader fin frameOpCode masked mask payloadLength) <- readFrameHeader bSocket if frameOpCode == ConinuationFrame -- If the frameOP is a continuation frame We will return a lazy bytestring -- if fin is set the "next" step is set to an empry bytestring. And will not continue reading then do next <- unsafeInterLeaveIO $ nextStep inBytes <- readBody return $ inBytes <> next -- If the frameOpCode isn't else controllFrameHandler webSocket fHead >> loop else handOverRead webSocket >> return "" where bSocket = bufferedSocket webSocket loop = readFrames webSocket nextStep = if if fin then return "" else unsafeInterLeaveIO loop outData bytes = if isMaked fHead then unmask mask a else a readBody = outData <$> BS.readLazy bSocket payloadLength readMessage :: WebSocket -> IO Request readMessage webSocket = do readable <- isReadable webSocket if readable -- if the socket is readable then read as normal then do fHead@(FrameHeader fin opCode masked mask payloadLength) <- readFrameHeader webSocket if elem opCode [TextFrame, BinaryFrame] then do firstFrame <- readLazy bSocket payloadLength >>= frameRest <- if fin then return "" else unsafeInterLeaveIO $ readFrames websocket let inData = firstFrame <> frameRest case opCode of TextFrame -> return $ TextMessage $ ENC.decodeUtf8With (ENC.replace '\xfffd') inData BinaryFrame -> return $ BinaryMessage inData else if payloadLength <= 125 then controllFrameHandler webSocket fHead >> loop else error "Controll frame data to big" -- If the socket isn't readable we will get the close status and message from the websockets IORef. -- We will then send the requesting function a "Closed" Frame else do (statusCode, message) <- readIORef (closeStatus webSocket) handOverRead webSocket return $ Closed statusCode message where bSocket = bufferedSocket webSocket loop = readMessage webSocket controllFrameHandler :: WebSocket -> FrameHeader -> IO () -- All controll frames MUST have a FIN set controllFrameHandler webSocket (FrameHeader False _ _ _ _) = error "Invalid ControllFrame Fin is not True" -- When we get a close frame we will close the read port. Set the status code and message to the websockets -- Status code IORef and run the onclose function controllFrameHandler webSocket (FrameHeader fin CloseFrame masked mask payloadLength) = do (statusCode, statusMessage) <- readCloseMessage webSocket fHead (onClose webSocket) webSocket statusCode statusMessage controllFrameHandler webSocket (FrameHeader fin opCode masked mask payloadLength) = do inBytes <- read bSocket payloadLength let pingPongData = if masked then unmaskStrict mask inBytes else inBytes case opCode of Ping -> (onPing webSocket) pingPongData fHead Pong -> (onPong webSocket) pingPongData fHead where bSocket = bufferedSocket webSocket case frameOpCode of Ping -> do inBytes <- readBody (onPing webSocket) respondToPing bSocket fHead loop Pong -> do inBytes <- readBody thunk $ PongRequest $ BL.fromChunks respondToPing bSocket fHead inBytes inBytes `seq` loop ConnectionClose -> do (statusCode, statusMessage) <- readCloseMessage (onClose webSocket) webSocket statusCode statusMessage return "" -- This reads the entire message of a close frame. -- Note that this function WILL close the readPort readCloseMessage :: WebSocket -> FrameHeader -> IO (StatusCode, CloseMessage) readCloseMessage webSocket (FrameHeader _ _ _ _ 0) = wsClose >> return (NormalClose, "") readCloseMessage webSocket (FrameHeader _ _ _ mask payloadLength) = if payloadLength <= 125 then do inData <- unmaskStrict mask $ read bSocket payloadLength let statusCode = bytestringToStatusCode $ B.take 2 inData message = (STRICTENC.decodeUtf8With (ENC.replace '\xfffd')) $ B.drop 2 inData closeData = (statusCode, message) writeIORef (closeStatus webSocket) $ Just closeData wsClose return closeData else wsClose >> error "Invalid payloadlength of socket" where bSocket = bufferedSocket webSocket wsClose = cloaseRead webSocket {-- Frame Header handeling --} {- Table From http://datatracker.ietf.org/doc/rfc6455/?include_text=1 describing the bit table of a frame. This is used to make the functions under 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+d-+-+-------+-+-------------+-------------------------------+ |F|R|R|R| opcode|M| Payload len | Extended payload length | |I|S|S|S| (4) |A| (7) | (16/64) | |N|V|V|V| |S| | (if payload len==126/127) | | |1|2|3| |K| | | +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + | Extended payload length continued, if payload len == 127 | + - - - - - - - - - - - - - - - +-------------------------------+ | |Masking-key, if MASK set to 1 | +-------------------------------+-------------------------------+ | Masking-key (continued) | Payload Data | +-------------------------------- - - - - - - - - - - - - - - - + : Payload Data continued ... : + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Payload Data continued ... | +---------------------------------------------------------------+ -} {- FIN: 1 bit Indicates that this is the final fragment in a message. The first fragment MAY also be the final fragment. -} isFin :: Word8 -> Fin isFin b = (shift b (-7)) == 1 toOpCode :: Word8 -> OpCode toOpCode 0x0 = ConinuationFrame toOpCode 0x1 =  TextFrame toOpCode 0x2 = BinaryFrame toOpCode 0x8 =  ConnectionClose toOpCode 0x9 = Ping toOpCode 0xA = Pong toOpCode n | isUndefined = Undefined | isReserved = Reserved where isUndefined = (0x3 >= n && 0x7 <= n) isReserved = n >= 0xB -- zeroes any FIN or RSV bits extractOpCode :: Word8 -> OpCode extractOpCode = toOpCode . (240 .&.) fromOpCode :: OpCode -> Word8 fromOpCode ConinuationFrame = 0x0 fromOpCode TextFrame = 0x1 fromOpCode BinaryFrame = 0x2 fromOpCode ConnectionClose = 0x8 fromOpCode Ping = 0x9 fromOpCode Pong = 0xA {- Mask: 1 bit Defines whether the "Payload data" is masked. If set to 1, a masking key is present in masking-key, and this is used to unmask the "Payload data" as per Section 5.3. All frames sent from client to server have this bit set to 1. -} -- Same function as isFin extractIsMaksed :: Word8 -> Bool extractIsMaksed = isFin -- Nulls the leftmost bit. IF the remaing is 126 then read extended payload of 16 bytes or if 127 read extended payload of payloadLength8 :: Word8 -> Either FrameSize PayloadLength payloadLength8 b | n < 126 = Right n | n == 126 = Left smallFrame | otherwise = Left bigFrame where n = 128 .&. b -- nulls the first bit smallFrame = 2 -- 16 bits bigFrame = 8 -- 8 bytes statusCodeToByteString :: StatusCode -> B.ByteString statusCodeToByteString NormalClose = "\ETX\232" -- 1000 statusCodeToByteString  GoingAway = "\ETX\233" -- 1001 statusCodeToByteString  ProtocolError = "\ETX\234" -- 1002 statusCodeToByteString  NonAcceptableData = "\ETX\235" -- 1003 statusCodeToByteString  InvalidData = "\ETX\239" -- 1007 statusCodeToByteString ViolatedPolicy = "\ETX\240" -- 1008 statusCodeToByteString  MessageTooBig = "\ETX\241" -- 1009 statusCodeToByteString  NeedsExtension = "\ETX\242" -- 1010 statusCodeToByteString  UnexpectedCondition = "\ETX\243" -- 1011 statusCodeToByteString CustomCode w16 = BINARY.encode w16 bytestringToStatusCode :: B.ByteString -> StatusCode bytestringToStatusCode "\ETX\232" = NormalClose bytestringToStatusCode  "\ETX\233" = GoingAway bytestringToStatusCode  "\ETX\234" = ProtocolError bytestringToStatusCode  "\ETX\235" = NonAcceptableData bytestringToStatusCode  "\ETX\239" = InvalidData bytestringToStatusCode "\ETX\240" = ViolatedPolicy bytestringToStatusCode  "\ETX\241" = MessageTooBig bytestringToStatusCode  "\ETX\242" = NeedsExtension bytestringToStatusCode  "\ETX\243" = UnexpectedCondition bytestringToStatusCode _ = CustomCode (BINARY.decode w16) -- First argument MUST be a cycled mask of bytes unmasker :: Mask -> Word8 -> (CycledMask, Word8) unmasker (maskByte:maskRest) byte = (maskRest, xor byte maskByte) unmask :: Mask -> [ByteString] -> [ByteString] unmask _ [] = [] unmask mask (currentString:unmakskedRest) = let (maskRest, unmasked) = B.mapAccumL (unmasker mask) currentString in (unmasked:unmask maskRest unmakskedRest) unmaskStrict :: Mask -> ByteString -> ByteString unmaskStrict mask string = let (_, unmasked) = B.mapAccumL (unmasker mask) currentString in unmasked {-- Opening handshake --} makeWebsocketExtensionList :: H.Headers -> [ByteString] makeWebsocketExtensionList [] = [] makeWebsocketExtensionList ((H.SecWebSocketExtensions, hdrValue):xs) = (hdrValue:makeWebsocketExtensionList xs) makeWebsocketExtensionList (_:xs) = makeWebsocketExtensionList xs makeWebsocketProtoclList :: ByteString -> [ByteString] makeWebsocketProtoclList = map stripWhitespace . B.split (c2w ',') authenticateHandshake :: HTTP.Request -> Either AuthenticationError AuthenticationData authenticateHandshake req = case lookup True conditions of Just a -> Left a Nothing -> Right authenticationData where headers = HTTP.requestHeaders req -- Lookups off diffrent header values and making just variables maybeHost = lookup H.Host $ headers Just host = maybeHost maybeUpgrade = lookup H.Upgrade $ headers Just upgrade = maybeUpgrade maybeConnection = lookup H.Host $connection Just connection = maybeConnection maybeOrigin = lookup H.Origin $ headers maybeWebSocketKey = lookup H.SecWebSocketKey $ headers Just webSocketKey = maybeWebSocketKey maybeWebSocketVersion = lookup H.SecWebSocketVersion $ headers Just webSocketVersion = maybeWebSocketVersion maybeWebSocketProtocol = lookup H.SecWebSocketProtocol $ headers Just webSocketProtocol = maybeWebSocketProtocol --maybeWebSocketExtensions@(Just webSocketExtensions) = lookup H.SecWebSocketExtensions $ headers keyDecoded = B64.decode webSocketKey Right keyBytestring = keyDecoded keyIsValid = and [isRight keyDecoded, (B.length keyBytestring) == 16] webSocketVersonInt = byteStringToInteger webSocketVersion conditions = [ ( not $ HTTP.reqIsGET req , InvalidMethod) , ( not $ HTTP.reqIsHTTP11 req , InvalidVersion) , ( isNothing maybeHost , MissingHeader H.Host) , ( isNothing maybeUpgrade , MissingHeader H.Upgrade) , ( isNothing maybeConnection , MissingHeader H.Connection) , ( isNothing maybeWebSocketKey , MissingHeader H.SecWebSocketKey) , ( isNothing maybeWebSocketVersion , MissingHeader H.SecWebSocketVersion) , ( quickQIEqual upgrade "websocket" , InvalidHeader H.Upgrade) , ( quickQIEqual connection "upgrade" , InvalidHeader H.Connection) , ( not keyIsValid , InvalidHeader H.SecWebSocketKey) , (webSocketVersion == "13" , InvalidHeader H.SecWebSocketVersion) ] authenticationData = AuthenticationData { webSocketKey = webSocketKey , origin = maybeOrigin , webSocketVersion = webSocketVersonInt , webSocketProtocol = maybe [] makeWebsocketProtoclList webSocketProtocol , socketExtensions = makeWebsocketExtensionList headers } acceptHandshake :: HTTP.Request -> AuthenticationData -> IO () acceptHandshake req authData = BS.send bSocket fullResponseString where statusLine = "HTTP/1.1 101 Switching Protocols\r\n" respondKey = (B64.encode (SHA1.hash ((webSocketKey req) <> guid))) respondHeaders = [(H.Connection, "Upgrade"),(H.Upgrade, "websocket"),(H.SecWebSocketAccept, respondKey)] fullResponseString = statusLine <> (H.headersToString respondHeaders) <> crlf bSocket = HTTP.bufSocket req withWebSockets :: HTTTP.Request -> WebSocketThunk -> IO HTTP.Response withWebSockets req thunk = if isRight eitherAuthentication then do let Right authData = eitherAuthentication acceptHandshake req authData return HTTP.Manual else return $ HTTP.HeadersResponse 400 [(H.Connection, "close")] where eitherAuthentication = authenticateHandshake request bSocket = HTTP.bufSocket req
black0range/Smutt
src/Smutt/WebSocket/Server/WebSocket.hs
Haskell
mit
25,956
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} module PrintC where -- pretty-printer generated by the BNF converter import AbsC import Data.Char -- the top-level printing method printTree :: Print a => a -> String printTree = render . prt 0 type Doc = [ShowS] -> [ShowS] doc :: ShowS -> Doc doc = (:) render :: Doc -> String render d = rend 0 (map ($ "") $ d []) "" where rend i ss = case ss of "[" :ts -> showChar '[' . rend i ts "(" :ts -> showChar '(' . rend i ts "{" :ts -> showChar '{' . new (i+1) . rend (i+1) ts "}" : ";":ts -> new (i-1) . space "}" . showChar ';' . new (i-1) . rend (i-1) ts "}" :ts -> new (i-1) . showChar '}' . new (i-1) . rend (i-1) ts ";" :ts -> showChar ';' . new i . rend i ts t : "," :ts -> showString t . space "," . rend i ts t : ")" :ts -> showString t . showChar ')' . rend i ts t : "]" :ts -> showString t . showChar ']' . rend i ts t :ts -> space t . rend i ts _ -> id new i = showChar '\n' . replicateS (2*i) (showChar ' ') . dropWhile isSpace space t = showString t . (\s -> if null s then "" else (' ':s)) parenth :: Doc -> Doc parenth ss = doc (showChar '(') . ss . doc (showChar ')') concatS :: [ShowS] -> ShowS concatS = foldr (.) id concatD :: [Doc] -> Doc concatD = foldr (.) id replicateS :: Int -> ShowS -> ShowS replicateS n f = concatS (replicate n f) -- the printer class does the job class Print a where prt :: Int -> a -> Doc prtList :: Int -> [a] -> Doc prtList i = concatD . map (prt i) instance Print a => Print [a] where prt = prtList instance Print Char where prt _ s = doc (showChar '\'' . mkEsc '\'' s . showChar '\'') prtList _ s = doc (showChar '"' . concatS (map (mkEsc '"') s) . showChar '"') mkEsc :: Char -> Char -> ShowS mkEsc q s = case s of _ | s == q -> showChar '\\' . showChar s '\\'-> showString "\\\\" '\n' -> showString "\\n" '\t' -> showString "\\t" _ -> showChar s prPrec :: Int -> Int -> Doc -> Doc prPrec i j = if j<i then parenth else id instance Print Integer where prt _ x = doc (shows x) instance Print Double where prt _ x = doc (shows x) instance Print Ident where prt _ (Ident i) = doc (showString ( i)) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Unsigned where prt _ (Unsigned i) = doc (showString ( i)) instance Print Long where prt _ (Long i) = doc (showString ( i)) instance Print UnsignedLong where prt _ (UnsignedLong i) = doc (showString ( i)) instance Print Hexadecimal where prt _ (Hexadecimal i) = doc (showString ( i)) instance Print HexUnsigned where prt _ (HexUnsigned i) = doc (showString ( i)) instance Print HexLong where prt _ (HexLong i) = doc (showString ( i)) instance Print HexUnsLong where prt _ (HexUnsLong i) = doc (showString ( i)) instance Print Octal where prt _ (Octal i) = doc (showString ( i)) instance Print OctalUnsigned where prt _ (OctalUnsigned i) = doc (showString ( i)) instance Print OctalLong where prt _ (OctalLong i) = doc (showString ( i)) instance Print OctalUnsLong where prt _ (OctalUnsLong i) = doc (showString ( i)) instance Print CDouble where prt _ (CDouble i) = doc (showString ( i)) instance Print CFloat where prt _ (CFloat i) = doc (showString ( i)) instance Print CLongDouble where prt _ (CLongDouble i) = doc (showString ( i)) instance Print Program where prt i e = case e of Progr externaldeclarations -> prPrec i 0 (concatD [prt 0 externaldeclarations]) instance Print External_declaration where prt i e = case e of Afunc functiondef -> prPrec i 0 (concatD [prt 0 functiondef]) Global dec -> prPrec i 0 (concatD [prt 0 dec]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Function_def where prt i e = case e of OldFunc declarationspecifiers declarator decs compoundstm -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 declarator, prt 0 decs, prt 0 compoundstm]) NewFunc declarationspecifiers declarator compoundstm -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 declarator, prt 0 compoundstm]) OldFuncInt declarator decs compoundstm -> prPrec i 0 (concatD [prt 0 declarator, prt 0 decs, prt 0 compoundstm]) NewFuncInt declarator compoundstm -> prPrec i 0 (concatD [prt 0 declarator, prt 0 compoundstm]) instance Print Dec where prt i e = case e of NoDeclarator declarationspecifiers -> prPrec i 0 (concatD [prt 0 declarationspecifiers, doc (showString ";")]) Declarators declarationspecifiers initdeclarators -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 initdeclarators, doc (showString ";")]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Declaration_specifier where prt i e = case e of Type typespecifier -> prPrec i 0 (concatD [prt 0 typespecifier]) Storage storageclassspecifier -> prPrec i 0 (concatD [prt 0 storageclassspecifier]) SpecProp typequalifier -> prPrec i 0 (concatD [prt 0 typequalifier]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Init_declarator where prt i e = case e of OnlyDecl declarator -> prPrec i 0 (concatD [prt 0 declarator]) InitDecl declarator initializer -> prPrec i 0 (concatD [prt 0 declarator, doc (showString "="), prt 0 initializer]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Type_specifier where prt i e = case e of Tvoid -> prPrec i 0 (concatD [doc (showString "void")]) Tchar -> prPrec i 0 (concatD [doc (showString "char")]) Tshort -> prPrec i 0 (concatD [doc (showString "short")]) Tint -> prPrec i 0 (concatD [doc (showString "int")]) Tlong -> prPrec i 0 (concatD [doc (showString "long")]) Tfloat -> prPrec i 0 (concatD [doc (showString "float")]) Tdouble -> prPrec i 0 (concatD [doc (showString "double")]) Tsigned -> prPrec i 0 (concatD [doc (showString "signed")]) Tunsigned -> prPrec i 0 (concatD [doc (showString "unsigned")]) Tstruct structorunionspec -> prPrec i 0 (concatD [prt 0 structorunionspec]) Tenum enumspecifier -> prPrec i 0 (concatD [prt 0 enumspecifier]) Tname -> prPrec i 0 (concatD [doc (showString "Typedef_name")]) instance Print Storage_class_specifier where prt i e = case e of MyType -> prPrec i 0 (concatD [doc (showString "typedef")]) GlobalPrograms -> prPrec i 0 (concatD [doc (showString "extern")]) LocalProgram -> prPrec i 0 (concatD [doc (showString "static")]) LocalBlock -> prPrec i 0 (concatD [doc (showString "auto")]) LocalReg -> prPrec i 0 (concatD [doc (showString "register")]) instance Print Type_qualifier where prt i e = case e of Const -> prPrec i 0 (concatD [doc (showString "const")]) NoOptim -> prPrec i 0 (concatD [doc (showString "volatile")]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Struct_or_union_spec where prt i e = case e of Tag structorunion id structdecs -> prPrec i 0 (concatD [prt 0 structorunion, prt 0 id, doc (showString "{"), prt 0 structdecs, doc (showString "}")]) Unique structorunion structdecs -> prPrec i 0 (concatD [prt 0 structorunion, doc (showString "{"), prt 0 structdecs, doc (showString "}")]) TagType structorunion id -> prPrec i 0 (concatD [prt 0 structorunion, prt 0 id]) instance Print Struct_or_union where prt i e = case e of Struct -> prPrec i 0 (concatD [doc (showString "struct")]) Union -> prPrec i 0 (concatD [doc (showString "union")]) instance Print Struct_dec where prt i e = case e of Structen specquals structdeclarators -> prPrec i 0 (concatD [prt 0 specquals, prt 0 structdeclarators, doc (showString ";")]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Spec_qual where prt i e = case e of TypeSpec typespecifier -> prPrec i 0 (concatD [prt 0 typespecifier]) QualSpec typequalifier -> prPrec i 0 (concatD [prt 0 typequalifier]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Struct_declarator where prt i e = case e of Decl declarator -> prPrec i 0 (concatD [prt 0 declarator]) Field constantexpression -> prPrec i 0 (concatD [doc (showString ":"), prt 0 constantexpression]) DecField declarator constantexpression -> prPrec i 0 (concatD [prt 0 declarator, doc (showString ":"), prt 0 constantexpression]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Enum_specifier where prt i e = case e of EnumDec enumerators -> prPrec i 0 (concatD [doc (showString "enum"), doc (showString "{"), prt 0 enumerators, doc (showString "}")]) EnumName id enumerators -> prPrec i 0 (concatD [doc (showString "enum"), prt 0 id, doc (showString "{"), prt 0 enumerators, doc (showString "}")]) EnumVar id -> prPrec i 0 (concatD [doc (showString "enum"), prt 0 id]) instance Print Enumerator where prt i e = case e of Plain id -> prPrec i 0 (concatD [prt 0 id]) EnumInit id constantexpression -> prPrec i 0 (concatD [prt 0 id, doc (showString "="), prt 0 constantexpression]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, doc (showString ","), prt 0 xs]) instance Print Declarator where prt i e = case e of BeginPointer pointer directdeclarator -> prPrec i 0 (concatD [prt 0 pointer, prt 0 directdeclarator]) NoPointer directdeclarator -> prPrec i 0 (concatD [prt 0 directdeclarator]) instance Print Direct_declarator where prt i e = case e of Name id -> prPrec i 0 (concatD [prt 0 id]) ParenDecl declarator -> prPrec i 0 (concatD [doc (showString "("), prt 0 declarator, doc (showString ")")]) InnitArray directdeclarator constantexpression -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "["), prt 0 constantexpression, doc (showString "]")]) Incomplete directdeclarator -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "["), doc (showString "]")]) NewFuncDec directdeclarator parametertype -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "("), prt 0 parametertype, doc (showString ")")]) OldFuncDef directdeclarator ids -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "("), prt 0 ids, doc (showString ")")]) OldFuncDec directdeclarator -> prPrec i 0 (concatD [prt 0 directdeclarator, doc (showString "("), doc (showString ")")]) instance Print Pointer where prt i e = case e of Point -> prPrec i 0 (concatD [doc (showString "*")]) PointQual typequalifiers -> prPrec i 0 (concatD [doc (showString "*"), prt 0 typequalifiers]) PointPoint pointer -> prPrec i 0 (concatD [doc (showString "*"), prt 0 pointer]) PointQualPoint typequalifiers pointer -> prPrec i 0 (concatD [doc (showString "*"), prt 0 typequalifiers, prt 0 pointer]) instance Print Parameter_type where prt i e = case e of AllSpec parameterdeclarations -> prPrec i 0 (concatD [prt 0 parameterdeclarations]) More parameterdeclarations -> prPrec i 0 (concatD [prt 0 parameterdeclarations, doc (showString ","), doc (showString "...")]) instance Print Parameter_declarations where prt i e = case e of ParamDec parameterdeclaration -> prPrec i 0 (concatD [prt 0 parameterdeclaration]) MoreParamDec parameterdeclarations parameterdeclaration -> prPrec i 0 (concatD [prt 0 parameterdeclarations, doc (showString ","), prt 0 parameterdeclaration]) instance Print Parameter_declaration where prt i e = case e of OnlyType declarationspecifiers -> prPrec i 0 (concatD [prt 0 declarationspecifiers]) TypeAndParam declarationspecifiers declarator -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 declarator]) Abstract declarationspecifiers abstractdeclarator -> prPrec i 0 (concatD [prt 0 declarationspecifiers, prt 0 abstractdeclarator]) instance Print Initializer where prt i e = case e of InitExpr exp -> prPrec i 0 (concatD [prt 2 exp]) InitListOne initializers -> prPrec i 0 (concatD [doc (showString "{"), prt 0 initializers, doc (showString "}")]) InitListTwo initializers -> prPrec i 0 (concatD [doc (showString "{"), prt 0 initializers, doc (showString ","), doc (showString "}")]) instance Print Initializers where prt i e = case e of AnInit initializer -> prPrec i 0 (concatD [prt 0 initializer]) MoreInit initializers initializer -> prPrec i 0 (concatD [prt 0 initializers, doc (showString ","), prt 0 initializer]) instance Print Type_name where prt i e = case e of PlainType specquals -> prPrec i 0 (concatD [prt 0 specquals]) ExtendedType specquals abstractdeclarator -> prPrec i 0 (concatD [prt 0 specquals, prt 0 abstractdeclarator]) instance Print Abstract_declarator where prt i e = case e of PointerStart pointer -> prPrec i 0 (concatD [prt 0 pointer]) Advanced dirabsdec -> prPrec i 0 (concatD [prt 0 dirabsdec]) PointAdvanced pointer dirabsdec -> prPrec i 0 (concatD [prt 0 pointer, prt 0 dirabsdec]) instance Print Dir_abs_dec where prt i e = case e of WithinParentes abstractdeclarator -> prPrec i 0 (concatD [doc (showString "("), prt 0 abstractdeclarator, doc (showString ")")]) Array -> prPrec i 0 (concatD [doc (showString "["), doc (showString "]")]) InitiatedArray constantexpression -> prPrec i 0 (concatD [doc (showString "["), prt 0 constantexpression, doc (showString "]")]) UnInitiated dirabsdec -> prPrec i 0 (concatD [prt 0 dirabsdec, doc (showString "["), doc (showString "]")]) Initiated dirabsdec constantexpression -> prPrec i 0 (concatD [prt 0 dirabsdec, doc (showString "["), prt 0 constantexpression, doc (showString "]")]) OldFunction -> prPrec i 0 (concatD [doc (showString "("), doc (showString ")")]) NewFunction parametertype -> prPrec i 0 (concatD [doc (showString "("), prt 0 parametertype, doc (showString ")")]) OldFuncExpr dirabsdec -> prPrec i 0 (concatD [prt 0 dirabsdec, doc (showString "("), doc (showString ")")]) NewFuncExpr dirabsdec parametertype -> prPrec i 0 (concatD [prt 0 dirabsdec, doc (showString "("), prt 0 parametertype, doc (showString ")")]) instance Print Stm where prt i e = case e of LabelS labeledstm -> prPrec i 0 (concatD [prt 0 labeledstm]) CompS compoundstm -> prPrec i 0 (concatD [prt 0 compoundstm]) ExprS expressionstm -> prPrec i 0 (concatD [prt 0 expressionstm]) SelS selectionstm -> prPrec i 0 (concatD [prt 0 selectionstm]) IterS iterstm -> prPrec i 0 (concatD [prt 0 iterstm]) JumpS jumpstm -> prPrec i 0 (concatD [prt 0 jumpstm]) prtList _ [x] = (concatD [prt 0 x]) prtList _ (x:xs) = (concatD [prt 0 x, prt 0 xs]) instance Print Labeled_stm where prt i e = case e of SlabelOne id stm -> prPrec i 0 (concatD [prt 0 id, doc (showString ":"), prt 0 stm]) SlabelTwo constantexpression stm -> prPrec i 0 (concatD [doc (showString "case"), prt 0 constantexpression, doc (showString ":"), prt 0 stm]) SlabelThree stm -> prPrec i 0 (concatD [doc (showString "default"), doc (showString ":"), prt 0 stm]) instance Print Compound_stm where prt i e = case e of ScompOne -> prPrec i 0 (concatD [doc (showString "{"), doc (showString "}")]) ScompTwo stms -> prPrec i 0 (concatD [doc (showString "{"), prt 0 stms, doc (showString "}")]) ScompThree decs -> prPrec i 0 (concatD [doc (showString "{"), prt 0 decs, doc (showString "}")]) ScompFour decs stms -> prPrec i 0 (concatD [doc (showString "{"), prt 0 decs, prt 0 stms, doc (showString "}")]) instance Print Expression_stm where prt i e = case e of SexprOne -> prPrec i 0 (concatD [doc (showString ";")]) SexprTwo exp -> prPrec i 0 (concatD [prt 0 exp, doc (showString ";")]) instance Print Selection_stm where prt i e = case e of SselOne exp stm -> prPrec i 0 (concatD [doc (showString "if"), doc (showString "("), prt 0 exp, doc (showString ")"), prt 0 stm]) SselTwo exp stm1 stm2 -> prPrec i 0 (concatD [doc (showString "if"), doc (showString "("), prt 0 exp, doc (showString ")"), prt 0 stm1, doc (showString "else"), prt 0 stm2]) SselThree exp stm -> prPrec i 0 (concatD [doc (showString "switch"), doc (showString "("), prt 0 exp, doc (showString ")"), prt 0 stm]) instance Print Iter_stm where prt i e = case e of SiterOne exp stm -> prPrec i 0 (concatD [doc (showString "while"), doc (showString "("), prt 0 exp, doc (showString ")"), prt 0 stm]) SiterTwo stm exp -> prPrec i 0 (concatD [doc (showString "do"), prt 0 stm, doc (showString "while"), doc (showString "("), prt 0 exp, doc (showString ")"), doc (showString ";")]) SiterThree expressionstm1 expressionstm2 stm -> prPrec i 0 (concatD [doc (showString "for"), doc (showString "("), prt 0 expressionstm1, prt 0 expressionstm2, doc (showString ")"), prt 0 stm]) SiterFour expressionstm1 expressionstm2 exp stm -> prPrec i 0 (concatD [doc (showString "for"), doc (showString "("), prt 0 expressionstm1, prt 0 expressionstm2, prt 0 exp, doc (showString ")"), prt 0 stm]) instance Print Jump_stm where prt i e = case e of SjumpOne id -> prPrec i 0 (concatD [doc (showString "goto"), prt 0 id, doc (showString ";")]) SjumpTwo -> prPrec i 0 (concatD [doc (showString "continue"), doc (showString ";")]) SjumpThree -> prPrec i 0 (concatD [doc (showString "break"), doc (showString ";")]) SjumpFour -> prPrec i 0 (concatD [doc (showString "return"), doc (showString ";")]) SjumpFive exp -> prPrec i 0 (concatD [doc (showString "return"), prt 0 exp, doc (showString ";")]) instance Print Exp where prt i e = case e of Ecomma exp1 exp2 -> prPrec i 0 (concatD [prt 0 exp1, doc (showString ","), prt 2 exp2]) Eassign exp1 assignmentop exp2 -> prPrec i 2 (concatD [prt 15 exp1, prt 0 assignmentop, prt 2 exp2]) Econdition exp1 exp2 exp3 -> prPrec i 3 (concatD [prt 4 exp1, doc (showString "?"), prt 0 exp2, doc (showString ":"), prt 3 exp3]) Elor exp1 exp2 -> prPrec i 4 (concatD [prt 4 exp1, doc (showString "||"), prt 5 exp2]) Eland exp1 exp2 -> prPrec i 5 (concatD [prt 5 exp1, doc (showString "&&"), prt 6 exp2]) Ebitor exp1 exp2 -> prPrec i 6 (concatD [prt 6 exp1, doc (showString "|"), prt 7 exp2]) Ebitexor exp1 exp2 -> prPrec i 7 (concatD [prt 7 exp1, doc (showString "^"), prt 8 exp2]) Ebitand exp1 exp2 -> prPrec i 8 (concatD [prt 8 exp1, doc (showString "&"), prt 9 exp2]) Eeq exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString "=="), prt 10 exp2]) Eneq exp1 exp2 -> prPrec i 9 (concatD [prt 9 exp1, doc (showString "!="), prt 10 exp2]) Elthen exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString "<"), prt 11 exp2]) Egrthen exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString ">"), prt 11 exp2]) Ele exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString "<="), prt 11 exp2]) Ege exp1 exp2 -> prPrec i 10 (concatD [prt 10 exp1, doc (showString ">="), prt 11 exp2]) Eleft exp1 exp2 -> prPrec i 11 (concatD [prt 11 exp1, doc (showString "<<"), prt 12 exp2]) Eright exp1 exp2 -> prPrec i 11 (concatD [prt 11 exp1, doc (showString ">>"), prt 12 exp2]) Eplus exp1 exp2 -> prPrec i 12 (concatD [prt 12 exp1, doc (showString "+"), prt 13 exp2]) Eminus exp1 exp2 -> prPrec i 12 (concatD [prt 12 exp1, doc (showString "-"), prt 13 exp2]) Etimes exp1 exp2 -> prPrec i 13 (concatD [prt 13 exp1, doc (showString "*"), prt 14 exp2]) Ediv exp1 exp2 -> prPrec i 13 (concatD [prt 13 exp1, doc (showString "/"), prt 14 exp2]) Emod exp1 exp2 -> prPrec i 13 (concatD [prt 13 exp1, doc (showString "%"), prt 14 exp2]) Etypeconv typename exp -> prPrec i 14 (concatD [doc (showString "("), prt 0 typename, doc (showString ")"), prt 14 exp]) Epreinc exp -> prPrec i 15 (concatD [doc (showString "++"), prt 15 exp]) Epredec exp -> prPrec i 15 (concatD [doc (showString "--"), prt 15 exp]) Epreop unaryoperator exp -> prPrec i 15 (concatD [prt 0 unaryoperator, prt 14 exp]) Ebytesexpr exp -> prPrec i 15 (concatD [doc (showString "sizeof"), prt 15 exp]) Ebytestype typename -> prPrec i 15 (concatD [doc (showString "sizeof"), doc (showString "("), prt 0 typename, doc (showString ")")]) Earray exp1 exp2 -> prPrec i 16 (concatD [prt 16 exp1, doc (showString "["), prt 0 exp2, doc (showString "]")]) Efunk exp -> prPrec i 16 (concatD [prt 16 exp, doc (showString "("), doc (showString ")")]) Efunkpar exp exps -> prPrec i 16 (concatD [prt 16 exp, doc (showString "("), prt 2 exps, doc (showString ")")]) Eselect exp id -> prPrec i 16 (concatD [prt 16 exp, doc (showString "."), prt 0 id]) Epoint exp id -> prPrec i 16 (concatD [prt 16 exp, doc (showString "->"), prt 0 id]) Epostinc exp -> prPrec i 16 (concatD [prt 16 exp, doc (showString "++")]) Epostdec exp -> prPrec i 16 (concatD [prt 16 exp, doc (showString "--")]) Evar id -> prPrec i 17 (concatD [prt 0 id]) Econst constant -> prPrec i 17 (concatD [prt 0 constant]) Estring str -> prPrec i 17 (concatD [prt 0 str]) prtList 2 [x] = (concatD [prt 2 x]) prtList 2 (x:xs) = (concatD [prt 2 x, doc (showString ","), prt 2 xs]) instance Print Constant where prt i e = case e of Efloat d -> prPrec i 0 (concatD [prt 0 d]) Echar c -> prPrec i 0 (concatD [prt 0 c]) Eunsigned unsigned -> prPrec i 0 (concatD [prt 0 unsigned]) Elong long -> prPrec i 0 (concatD [prt 0 long]) Eunsignlong unsignedlong -> prPrec i 0 (concatD [prt 0 unsignedlong]) Ehexadec hexadecimal -> prPrec i 0 (concatD [prt 0 hexadecimal]) Ehexaunsign hexunsigned -> prPrec i 0 (concatD [prt 0 hexunsigned]) Ehexalong hexlong -> prPrec i 0 (concatD [prt 0 hexlong]) Ehexaunslong hexunslong -> prPrec i 0 (concatD [prt 0 hexunslong]) Eoctal octal -> prPrec i 0 (concatD [prt 0 octal]) Eoctalunsign octalunsigned -> prPrec i 0 (concatD [prt 0 octalunsigned]) Eoctallong octallong -> prPrec i 0 (concatD [prt 0 octallong]) Eoctalunslong octalunslong -> prPrec i 0 (concatD [prt 0 octalunslong]) Ecdouble cdouble -> prPrec i 0 (concatD [prt 0 cdouble]) Ecfloat cfloat -> prPrec i 0 (concatD [prt 0 cfloat]) Eclongdouble clongdouble -> prPrec i 0 (concatD [prt 0 clongdouble]) Eint n -> prPrec i 0 (concatD [prt 0 n]) Elonger n -> prPrec i 0 (concatD [prt 0 n]) Edouble d -> prPrec i 0 (concatD [prt 0 d]) instance Print Constant_expression where prt i e = case e of Especial exp -> prPrec i 0 (concatD [prt 3 exp]) instance Print Unary_operator where prt i e = case e of Address -> prPrec i 0 (concatD [doc (showString "&")]) Indirection -> prPrec i 0 (concatD [doc (showString "*")]) Plus -> prPrec i 0 (concatD [doc (showString "+")]) Negative -> prPrec i 0 (concatD [doc (showString "-")]) Complement -> prPrec i 0 (concatD [doc (showString "~")]) Logicalneg -> prPrec i 0 (concatD [doc (showString "!")]) instance Print Assignment_op where prt i e = case e of Assign -> prPrec i 0 (concatD [doc (showString "=")]) AssignMul -> prPrec i 0 (concatD [doc (showString "*=")]) AssignDiv -> prPrec i 0 (concatD [doc (showString "/=")]) AssignMod -> prPrec i 0 (concatD [doc (showString "%=")]) AssignAdd -> prPrec i 0 (concatD [doc (showString "+=")]) AssignSub -> prPrec i 0 (concatD [doc (showString "-=")]) AssignLeft -> prPrec i 0 (concatD [doc (showString "<<=")]) AssignRight -> prPrec i 0 (concatD [doc (showString ">>=")]) AssignAnd -> prPrec i 0 (concatD [doc (showString "&=")]) AssignXor -> prPrec i 0 (concatD [doc (showString "^=")]) AssignOr -> prPrec i 0 (concatD [doc (showString "|=")])
aufheben/Y86
Compiler/lab/C/PrintC.hs
Haskell
mit
23,864
module Mortgage.Money ( Money ) where import Test.QuickCheck import Text.Printf import Data.Ratio data Money = Money {-# UNPACK #-} !Double instance Show Money where show (Money amt) = printf "%.2f" amt -- round to 0.01 instance Eq Money where (Money x) == (Money y) = round (100*x) == round (100*y) instance Ord Money where compare (Money x) (Money y) = compare (round (100*x)) (round (100*y)) instance Num Money where (+) (Money x) (Money y) = Money (x+y) (-) (Money x) (Money y) = Money (x-y) (*) (Money x) (Money y) = Money (x*y) negate (Money x) = Money (negate x) abs (Money x) = Money (abs x) signum (Money x) | x == 0 = 0 | x > 0 = 1 | x < 0 = -1 fromInteger i = Money (fromIntegral i) instance Fractional Money where (/) (Money x) (Money y) = Money (x / y) fromRational r = Money $ (fromIntegral . numerator $ r) / (fromIntegral . denominator $ r) instance Real Money where toRational (Money x) = toRational x instance RealFrac Money where properFraction (Money x) = (y, Money (x - fromIntegral y)) where y = floor x instance Arbitrary Money where arbitrary = fmap Money (choose (0, 1000000000))
wangbj/MortageCalc
src/Mortgage/Money.hs
Haskell
mit
1,247
{-**************************************************************************** * Hamster Balls * * Purpose: Common data types shared by other modules * * Author: David, Harley, Alex, Matt * * Copyright (c) Yale University, 2010 * ****************************************************************************-} module Common where import Vec3d import FRP.Yampa import Graphics.Rendering.OpenGL import Graphics.Rendering.OpenGL.GL.CoordTrans import System.IO import System.IO.Unsafe (unsafePerformIO) import Control.Concurrent ------------------------------------------------------------------------------ -- Debugging routines. Couldn't have made it without these ------------------------------------------------------------------------------ debug :: (Show a) => a -> t -> t debug s x = unsafePerformIO (print s) `seq` x debugShow, debugShow2 :: (Show a) => a -> a debugShow x = debug ("debug: " ++ show x) x -- only for SHOWable objects debugShow2 x = debug (show x) x -- only for SHOWable objects debugMaybe :: String -> t -> t debugMaybe s x = if s /= "" then debug s x else x -- The following is for debugging purposes only --instance Show a => Show (Event a) where -- show NoEvent = "NoEvent" -- show (Event a) = "Event " ++ (show a) ---------------------------------------------- ------------------------------------------------------------------------------ -- ReactChan: queue changes requested from different threads to apply sequentially ------------------------------------------------------------------------------ type ReactChan a = Chan (a -> a) addToReact :: ReactChan a -> (a -> a) -> IO () addToReact rch f = writeChan rch f getReactInput :: ReactChan a -> a -> IO a getReactInput rch old = do f <- readChan rch return $ f old data GameConfig = GameConfig { gcFullscreen :: Bool, gcPlayerName :: String, gcTracker :: String} -- width MUST be divisible by 4 -- height MUST be divisible by 3 width, height :: GLint (width,height) = (640, 480) --if fullscreen then (1600,1200) else (640,480) widthf, heightf :: GLdouble widthf = fromRational $ toRational width heightf = fromRational $ toRational height centerCoordX, centerCoordY :: Float centerCoordX = fromIntegral width / 2 centerCoordY = fromIntegral height / 2 sensitivity :: Float sensitivity = pi/(fromIntegral $ width `div` 4) initFrustum :: IO () initFrustum = do loadIdentity let near = 0.8 far = 1000 right = 0.4 top = 0.3 frustum (-right) right (-top) top near far -- TODO: explain this lookAt (Vertex3 0 0 0) (Vertex3 1 0 0) (Vector3 0 0 1) --bound lo hi a = max lo $ min hi a type ID = Int type Position3 = Vec3d type Velocity3 = Vec3d type Acceleration3 = Vec3d type Color3 = Vec3d data Player = Player { playerID :: !ID, playerPos :: !Position3, playerVel :: !Velocity3, playerAcc :: !Acceleration3, playerView :: !(Float,Float), -- theta, phi playerRadius :: !Float, playerLife :: !Float, playerEnergy :: !Float, playerColor :: !Common.Color3, playerName :: !String } deriving (Show, Eq) data Laser = Laser { laserID :: !ID, laserpID :: !ID, laserPos :: !Position3, laserVel :: !Velocity3, laserStr :: !Float, laserColor :: !Common.Color3 } deriving (Show, Eq) data Hit = Hit { player1ID :: !ID, player2ID :: !ID, hitLaserID :: !ID, hitStr :: !Float } deriving (Show, Eq) -- Particle Position Depth data Particle = Particle { particlePos :: !Position3, particleVel :: !Vec3d, particleEnergy :: !Float, particleDepth :: !Int } deriving (Show, Eq) -- Not in use now. Instead, model as a list of ObjectSFs (representing particles). Makes simpler data ParticleSystem = ParticleSystem { particlePV :: [(Vec3d,Vec3d)], particlesMax :: Float, particlesEnergy :: !Float } deriving (Show, Eq) -- TODO: keep track of previous location of display text data ScoreBoard = ScoreBoard { sbScores :: ![(Player, Int)] -- Player and Score } deriving (Show, Eq) data PowerUpType = StrengthenLaser !Float | XRayVision | DecreaseRadius !Float deriving Eq data PowerUp = PowerUp { powerupPos :: !Position3, powerupRadius :: !Float, powerupType :: !PowerUpType, powerupView :: !(Float,Float) -- theta, phi -- make it spin } deriving Eq instance Show PowerUp where show PowerUp{powerupType=t} = "^" ++ show t ++ "^" instance Show PowerUpType where show (StrengthenLaser f) = "Plus " ++ show f show XRayVision = "XRay" show (DecreaseRadius f) = "Smaller by " ++ show f data Obj = PlayerObj !Player | LaserObj !Laser deriving (Show, Eq) ------------------------------------------------------------------------------ -- Network messages between Server and Client ------------------------------------------------------------------------------ data SCMsg' = SCMsgInitialize !Player -- To initiatiate the joining player | SCMsgPlayer !Player -- For updating pos | SCMsgHit !Hit -- Announcing hits | SCMsgSpawn !Obj -- For creating new objects | SCMsgFrag !Player !Player -- For telling everyone player1 killed player2 | SCMsgRemove !Int -- Remove exiting player deriving (Show, Eq) data CSMsg' = CSMsgPlayer !Player -- Send when velocity changes | CSMsgUpdate !Player -- Send periodic updates | CSMsgLaser !Laser -- Send when a laser is shot by client | CSMsgKillLaser !ID | CSMsgDeath !Hit -- ID of killer and killed | CSMsgExit !String -- Name of player that exits, requires unique player names | CSMsgJoin !String -- Name of player that enters the game deriving (Show, Eq) type SCMsg = (ID, SCMsg') -- Server to Client, i.e. runs on Client type CSMsg = (ID, CSMsg') -- Client to Server, i.e. runs on Server dummySCMsg :: SCMsg dummySCMsg = (-1,SCMsgHit (Hit {player1ID= -1,player2ID= -1,hitLaserID= -1,hitStr= -1})) dummyCSMsg :: CSMsg dummyCSMsg = (-1,CSMsgExit "dummy") dummyPlayer :: Player dummyPlayer = Player {playerID = 0, playerPos = zeroVector, playerVel = zeroVector, playerAcc = zeroVector, playerView = (0,0), playerRadius = defRadius, playerLife = maxLife, playerEnergy = maxEnergy, playerColor = Vec3d(0.5, 0.2, 0.7), playerName = "Dummy"} -- Values for initializing objects defRadius :: Float defRadius = 1.5 maxLife :: Float maxLife = 100 maxEnergy :: Float maxEnergy = 100 defLaserStr :: Float defLaserStr = 10 printFlush :: String -> IO () printFlush s = do print s hFlush stdout hFlush stderr doIOevent :: Event (IO ()) -> IO () doIOevent (Event io) = io doIOevent NoEvent = return () vecToColor :: Vec3d -> Color4 GLfloat vecToColor (Vec3d (x,y,z)) = Color4 x y z 1 computeColor :: Player -> Color4 GLfloat computeColor (Player {playerColor = Vec3d (r,g,b), playerLife = life}) = vecToColor (Vec3d ((1 - life/maxLife) * (1-r) + r, g, b)) --deprecated in favor of edgeBy --detectChangeSF :: Eq a => SF (a, a) (Event a, a) --detectChangeSF = arr (\(new,old) -> (if new == old then NoEvent else Event new, new))
harley/hamball
src/Common.hs
Haskell
mit
7,661
f x = if x > 2 then do print "x" else do print "y"
itchyny/vim-haskell-indent
test/if/ifthendo.in.hs
Haskell
mit
51
module Test where import TambaraYamagami as TY import Stringnet as S import Data.Tree as T import Data.Matrix as M import Data.Maybe import Finite import Algebra obj = (toObject M) `TY.tensorO` (toObject M) `TY.tensorO` (toObject M) m = toObject M o = toObject one notOne = toObject $ AE $ AElement 1 -- a snake equation snake o = idMorphism o == ((ev o) `TY.tensorM` (idMorphism o)) `TY.compose` (alpha o o o) `TY.compose` ((idMorphism o) `TY.tensorM` (coev o)) -- ((ab)c)d) -> (ab)(cd) -> a(b(cd)) pentagonLHS a b c d = (alpha a b (c `TY.tensorO` d)) `TY.compose` (alpha (a `TY.tensorO` b) c d) -- ((ab)c)d -> (a(bc))d -> a((bc)d) -> a(b(cd)) pentagonRHS a b c d = ((idMorphism a) `tensorM` (alpha b c d)) `TY.compose` (alpha a (b `TY.tensorO` c) d) `TY.compose` ((alpha a b c) `tensorM` idMorphism d) --FIXME: pentagon m m m m pentagon a b c d = (pentagonLHS a b c d) == (pentagonRHS a b c d) -- 81 is interesting -- finalET = map (\ib -> map (substO (initialLabel ib)) $ map (S.objectLabel S.finalSN) $ S.flatten S.finalEdgeTree) (allElements :: [InitialBasisElement]) -- old (finalMorphism) testing tree = fmap (\x -> case x of Nothing -> "+" Just e -> show e ) $ toTree S.finalMorphism prin = (putStr. T.drawTree) tree cList = toCompositionList S.finalMorphism leaves = catMaybes $ T.flatten $ toTree S.finalMorphism leftT (TensorM a b) = a rightT (TensorM a b) = b -- leftC (Compose a b) = a -- rightC (Compose a b) = b -- bad = Compose (AlphaI (Star (OVar RightLoop)) (OVar RightLoop) (Star One)) (Compose (RhoI (OVar RightLoop)) (Coev (OVar RightLoop))) -- small = (Compose (TensorM (PivotalJI (Star (OVar RightLoop))) (LambdaI (OVar RightLoop))) (Coev (OVar RightLoop))) -- -- new testing -- -- TODO: Calculate a matrix for addCoev. What I need to do is figure -- -- out how to turn the monad actions into a list of actions.
PaulGustafson/stringnet
Test.hs
Haskell
mit
1,938
-- |Module for representing and manipulating complex numbers. module Cplx where -- |Basic data type for storing complex numbers. data Cplx = Cplx {re :: Double, im :: Double } deriving (Eq) -- re Cplx a b = a -- im Cplx a b = b -- |Function 'conj' returns a complex conjugate of a complex number. conj :: Cplx -> Cplx conj c = Cplx (re c) (-1*( im c)) -- |Funciton 'cabs' returns the absolute value of a complex number. In contrast -- to the 'abs' function overloaded from 'Num', this function returns 'Double'. cabs :: Cplx -> Double cabs c = (sqrt $ (re c)^2 + (im c)^2) -- |Operator for creating new complex number from two 'Double' numbers used as -- a real and as an imaginary part. (+:) :: Double -> Double -> Cplx a +: b = Cplx a b -- |Functions overloaded from Num class. In particular they implement the -- arithmetic on complex numbers. instance Num Cplx where a + b = (re a + re b) +: (im a + im b) a * b = (re a * re b - im a * im b) +: (im a * re b + re a * im b) abs a = Cplx (cabs a) 0 negate a = (negate $ re a) +: (negate $ im a) signum a = a fromInteger a = ((fromInteger a) :: Double) +: 0.0 -- |Function 'show' overloaded from 'Show' class. Complex numbers are displayed -- as pairs. instance Show Cplx where show (Cplx a b) = "(" ++ show a ++ "," ++ show b ++ ")"
jmiszczak/hoqus
alternative/Cplx.hs
Haskell
mit
1,306
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : Object.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:34 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Classes.Object ( Object(..), objectNull, objectIsNull, objectCast, objectFromPtr, objectFromPtr_nf, withObjectPtr, ptrFromObject, objectListFromPtrList, objectListFromPtrList_nf ) where import Control.Exception import System.IO.Unsafe( unsafePerformIO ) import Foreign.C import Foreign.Ptr import Foreign.ForeignPtr import Foreign.Storable import Foreign.Marshal.Alloc import Foreign.Marshal.Array data Object a = Object ! (ForeignPtr a) instance Eq (Object a) where fobj1 == fobj2 = unsafePerformIO $ withObjectPtr fobj1 $ \p1 -> withObjectPtr fobj2 $ \p2 -> return (p1 == p2) instance Ord (Object a) where compare fobj1 fobj2 = unsafePerformIO $ withObjectPtr fobj1 $ \p1 -> withObjectPtr fobj2 $ \p2 -> return (compare p1 p2) instance Show (Object a) where show fobj = unsafePerformIO $ withObjectPtr fobj $ \p -> return (show p) objectNull :: Object a objectNull = Object $ unsafePerformIO (newForeignPtr_ nullPtr) objectIsNull :: Object a -> Bool objectIsNull fobj = unsafePerformIO $ withObjectPtr fobj $ \p -> return (p == nullPtr) objectCast :: Object a -> Object b objectCast (Object fp) = Object (castForeignPtr fp) withObjectPtr :: Object a -> (Ptr a -> IO b) -> IO b withObjectPtr (Object fp) f = withForeignPtr fp f objectFromPtr :: FunPtr (Ptr a -> IO ()) -> Ptr a -> IO (Object a) objectFromPtr f p = do nfp <- newForeignPtr f p return $ Object nfp objectFromPtr_nf :: Ptr a -> IO (Object a) objectFromPtr_nf p = do nfp <- newForeignPtr_ p return $ Object nfp ptrFromObject :: Object a -> Ptr a ptrFromObject (Object fp) = unsafeForeignPtrToPtr fp objectListFromPtrList :: FunPtr (Ptr a -> IO ()) -> [Ptr a] -> IO [Object a] objectListFromPtrList f pl = objectListFromPtrList_r f [] pl objectListFromPtrList_r :: FunPtr (Ptr a -> IO ()) -> [Object a] -> [Ptr a] -> IO [Object a] objectListFromPtrList_r _ fol [] = return fol objectListFromPtrList_r f fol (x:xs) = do nfp <- newForeignPtr f x objectListFromPtrList_r f (fol ++ [Object nfp]) xs objectListFromPtrList_nf :: [Ptr a] -> IO [Object a] objectListFromPtrList_nf pl = objectListFromPtrList_nf_r [] pl objectListFromPtrList_nf_r :: [Object a] -> [Ptr a] -> IO [Object a] objectListFromPtrList_nf_r fol [] = return fol objectListFromPtrList_nf_r fol (x:xs) = do nfp <- newForeignPtr_ x objectListFromPtrList_nf_r (fol ++ [Object nfp]) xs
uduki/hsQt
Qtc/Classes/Object.hs
Haskell
bsd-2-clause
2,870
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module Mars.Command.Ls (Ls (..), LsResult (..), ansiColor) where import Data.Aeson import qualified Data.HashMap.Strict as Map import Data.Ix import Data.Maybe import Data.String import Data.String.Conv import Data.Text (Text) import qualified Data.Text as Text import Data.Text.IO (putStrLn) import Data.Typeable import qualified Data.Vector as Vector import GHC.Generics import Mars.Command import Mars.Query (Query (..)) import Mars.Renderable import Mars.Types import Test.QuickCheck import Prelude hiding (putStrLn) newtype Ls = Ls Query deriving (Generic, Show, Eq, Typeable) newtype LsResult = DirectoryEntries [DirectoryEntry] deriving (Generic, Show, Eq, Typeable) instance Command Ls LsResult where evalCommand s (Ls DefaultLocation) = DirectoryEntries . list (document s) $ path s evalCommand s (Ls q) = DirectoryEntries . list (document s) $ path s <> q instance Action LsResult where execCommand state (DirectoryEntries o) = do putStrLn . format $ o return state where format :: [DirectoryEntry] -> Text format l = Text.intercalate "\n" . zipWith ansiColor (colorMap <$> l) $ (\(DirectoryEntry (ItemName name) _) -> name) <$> l instance Renderable Ls where render (Ls a) = "ls " <> render a list :: Value -> Query -> [DirectoryEntry] list doc query = concatMap directoryEntries . queryDoc query $ doc directoryEntries :: Value -> [DirectoryEntry] directoryEntries (Object o) = let toDirectoryEntry :: (Text, Value) -> DirectoryEntry toDirectoryEntry (name, v) = DirectoryEntry (ItemName . toS $ name) (toItemType v) in toDirectoryEntry <$> catMaybes ( spreadMaybe <$> spread (o Map.!?) (Map.keys o) ) directoryEntries (Array o) = let toDirectoryEntry :: (Int, Value) -> DirectoryEntry toDirectoryEntry (name, v) = DirectoryEntry (ItemName . toS . show $ name) (toItemType v) in toDirectoryEntry <$> catMaybes ( spreadMaybe <$> spread (o Vector.!?) ((\x -> range (0, length x)) o) ) directoryEntries (String _) = [] directoryEntries (Number _) = [] directoryEntries (Bool _) = [] directoryEntries Null = [] colorMap :: DirectoryEntry -> ANSIColour colorMap (DirectoryEntry _ MarsObject) = Blue colorMap (DirectoryEntry _ MarsList) = Blue colorMap (DirectoryEntry _ MarsString) = Green colorMap (DirectoryEntry _ MarsNumber) = Green colorMap (DirectoryEntry _ MarsBool) = Green colorMap (DirectoryEntry _ MarsNull) = Green ansiColor :: ANSIColour -> Text -> Text ansiColor Grey = ansiWrap "30" ansiColor Red = ansiWrap "31" ansiColor Green = ansiWrap "32" ansiColor Yellow = ansiWrap "33" ansiColor Blue = ansiWrap "34" ansiColor Magenta = ansiWrap "35" ansiColor Cyan = ansiWrap "36" ansiColor White = ansiWrap "37" ansiWrap :: (Monoid m, Data.String.IsString m) => m -> m -> m ansiWrap colorID text = "\ESC[" <> colorID <> "m" <> text <> "\ESC[0m" spread :: (a -> b) -> [a] -> [(a, b)] spread f a = zip a (f <$> a) extractSpread :: Functor f => (a, f b) -> f (a, b) extractSpread (i, l) = (i,) <$> l spreadMaybe :: (a, Maybe b) -> Maybe (a, b) spreadMaybe = extractSpread toItemType :: Value -> ItemType toItemType (Object _) = MarsObject toItemType (Array _) = MarsList toItemType (String _) = MarsString toItemType (Number _) = MarsNumber toItemType (Bool _) = MarsBool toItemType Null = MarsNull instance Arbitrary Ls where arbitrary = Ls <$> arbitrary
lorcanmcdonald/mars
src/Mars/Command/Ls.hs
Haskell
bsd-3-clause
3,676
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} module River.X64.Color ( colorByRegister , RegisterError(..) ) where import Control.Monad.Trans.State.Strict (StateT, runStateT, get, put) import Data.Function (on) import qualified Data.List as List import Data.Map (Map) import qualified Data.Map as Map import River.Core.Color (ColorStrategy(..)) import River.Core.Syntax import River.Fresh import River.Map import River.X64.Primitive import River.X64.Syntax (Register64(..)) data RegisterError n = RegistersExhausted !n deriving (Eq, Ord, Show) colorByRegister :: Ord n => ColorStrategy (RegisterError n) Register64 k Prim n a colorByRegister = ColorStrategy { unusedColor = \n used -> case Map.toList (registers `mapDifferenceSet` used) of [] -> Left $ RegistersExhausted n regs -> pure . fst $ List.minimumBy (compare `on` snd) regs , precolored = precoloredOfProgram } precoloredOfProgram :: Ord n => FreshName n => Program k Prim n a -> Fresh (Map n Register64, Program k Prim n a) precoloredOfProgram = \case Program a tm0 -> do (tm, rs) <- runStateT (precoloredOfTerm tm0) Map.empty pure (rs, Program a tm) putsert :: (Ord k, Monad m) => k -> v -> StateT (Map k v) m () putsert k v = do kvs <- get put $ Map.insert k v kvs precoloredOfTerm :: Ord n => FreshName n => Term k Prim n a -> StateT (Map n Register64) Fresh (Term k Prim n a) precoloredOfTerm = \case -- TODO ensure in RAX Return at tl -> pure $ Return at tl If at k (Variable ai i) t0 e0 -> do t <- precoloredOfTerm t0 e <- precoloredOfTerm e0 i_ah <- freshen i i_flags <- freshen i putsert i_ah RAX putsert i_flags RFLAGS pure $ Let at [i_ah] (Copy at [Variable ai i]) $ Let at [i_flags] (Copy at [Variable ai i_ah]) $ -- implicit sahf instruction If at k (Variable ai i_flags) t e If at k i t0 e0 -> If at k i <$> precoloredOfTerm t0 <*> precoloredOfTerm e0 LetRec at bs tm -> do LetRec at <$> precoloredOfBindings bs <*> precoloredOfTerm tm Let at [lo, hi] (Prim ap Imul [Variable ax x, y]) tm0 -> do tm <- precoloredOfTerm tm0 x_rax <- freshen x lo_rax <- freshen lo hi_rdx <- freshen hi putsert x_rax RAX putsert lo_rax RAX putsert hi_rdx RDX pure $ Let ap [x_rax] (Copy ap [Variable ax x]) $ Let at [lo_rax, hi_rdx] (Prim ap Imul [Variable ax x_rax, y]) $ Let at [lo] (Copy at [Variable at lo_rax]) $ Let at [hi] (Copy at [Variable at hi_rdx]) $ tm Let at [dv, md] (Prim ap Idiv [Variable al lo, Variable ah hi, x]) tm0 -> do tm <- precoloredOfTerm tm0 lo_rax <- freshen lo hi_rdx <- freshen hi dv_rax <- freshen dv md_rdx <- freshen md putsert lo_rax RAX putsert hi_rdx RDX putsert dv_rax RAX putsert md_rdx RDX pure $ Let ap [lo_rax] (Copy ap [Variable al lo]) $ Let ap [hi_rdx] (Copy ap [Variable ah hi]) $ Let at [dv_rax, md_rdx] (Prim ap Idiv [Variable al lo_rax, Variable ah hi_rdx, x]) $ Let at [dv] (Copy at [Variable at dv_rax]) $ Let at [md] (Copy at [Variable at md_rdx]) $ tm Let at [hi] (Prim ap Cqto [Variable al lo]) tm0 -> do tm <- precoloredOfTerm tm0 lo_rax <- freshen lo hi_rdx <- freshen hi putsert lo_rax RAX putsert hi_rdx RDX pure $ Let ap [lo_rax] (Copy ap [Variable al lo]) $ Let at [hi_rdx] (Prim ap Cqto [Variable al lo_rax]) $ Let at [hi] (Copy at [Variable at hi_rdx]) $ tm Let at [r] (Prim ap Test [x, y]) tm0 -> do tm <- precoloredOfTerm tm0 r_flags <- freshen r r_ah <- freshen r putsert r_flags RFLAGS putsert r_ah RAX pure $ Let at [r_flags] (Prim ap Test [x, y]) $ Let at [r_ah] (Copy at [Variable at r_flags]) $ -- implicit lahf instruction Let at [r] (Copy at [Variable at r_ah]) $ tm Let at [r] (Prim ap Cmp [x, y]) tm0 -> do tm <- precoloredOfTerm tm0 r_flags <- freshen r r_ah <- freshen r putsert r_flags RFLAGS putsert r_ah RAX pure $ Let at [r_flags] (Prim ap Cmp [x, y]) $ Let at [r_ah] (Copy at [Variable at r_flags]) $ -- implicit lahf instruction Let at [r] (Copy at [Variable at r_ah]) $ tm Let at [b] (Prim ap (Set cc) [Variable ar r]) tm0 -> do tm <- precoloredOfTerm tm0 r_ah <- freshen r r_flags <- freshen r putsert r_ah RAX putsert r_flags RFLAGS pure $ Let at [r_ah] (Copy at [Variable ar r]) $ Let at [r_flags] (Copy at [Variable ar r_ah]) $ -- implicit sahf instruction Let at [b] (Prim ap (Set cc) [Variable ar r_flags]) $ tm Let at ns tl tm -> Let at ns tl <$> precoloredOfTerm tm precoloredOfBindings :: Ord n => FreshName n => Bindings k Prim n a -> StateT (Map n Register64) Fresh (Bindings k Prim n a) precoloredOfBindings = \case Bindings a nbs0 -> do let (ns, bs0) = unzip nbs0 bs <- traverse precoloredOfBinding bs0 pure $ Bindings a (zip ns bs) precoloredOfBinding :: Ord n => FreshName n => Binding k Prim n a -> StateT (Map n Register64) Fresh (Binding k Prim n a) precoloredOfBinding = \case Lambda a ns tm -> do Lambda a ns <$> precoloredOfTerm tm registers :: Map Register64 Int registers = Map.fromList $ flip zip [1..] -- -- Caller saved registers -- -- We can overwrite these at will. -- [ RAX , RCX , RDX , RSI , RDI , R8 , R9 , R10 -- -- Spill register -- -- We will use this to spill and restore from the stack. -- -- , R11 -- -- -- Stack pointer -- -- , RSP -- -- -- Callee saved registers -- -- If we use these, they must be saved to the stack and restored before -- returning. -- , R12 , R13 , R14 , R15 , RBX -- , RBP ]
jystic/river
src/River/X64/Color.hs
Haskell
bsd-3-clause
6,266
{-| Module : Idris.Output Description : Utilities to display Idris' internals and other informtation to the user. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Output where import Idris.Core.TT import Idris.Core.Evaluate (isDConName, isTConName, isFnName, normaliseAll) import Idris.AbsSyntax import Idris.Colours (hStartColourise, hEndColourise) import Idris.Delaborate import Idris.Docstrings import Idris.IdeMode import Util.Pretty import Util.ScreenSize (getScreenWidth) import Util.System (isATTY) import Control.Monad.Trans.Except (ExceptT (ExceptT), runExceptT) import System.Console.Haskeline.MonadException (MonadException (controlIO), RunIO (RunIO)) import System.IO (stdout, Handle, hPutStrLn, hPutStr) import System.FilePath (replaceExtension) import Prelude hiding ((<$>)) import Data.Char (isAlpha) import Data.List (nub, intersperse) import Data.Maybe (fromMaybe) instance MonadException m => MonadException (ExceptT Err m) where controlIO f = ExceptT $ controlIO $ \(RunIO run) -> let run' = RunIO (fmap ExceptT . run . runExceptT) in fmap runExceptT $ f run' pshow :: IState -> Err -> String pshow ist err = displayDecorated (consoleDecorate ist) . renderPretty 1.0 80 . fmap (fancifyAnnots ist True) $ pprintErr ist err iWarn :: FC -> Doc OutputAnnotation -> Idris () iWarn fc err = do i <- getIState case idris_outputmode i of RawOutput h -> do err' <- iRender . fmap (fancifyAnnots i True) $ case fc of FC fn _ _ | fn /= "" -> text (show fc) <> colon <//> err _ -> err hWriteDoc h i err' IdeMode n h -> do err' <- iRender . fmap (fancifyAnnots i True) $ err let (str, spans) = displaySpans err' runIO . hPutStrLn h $ convSExp "warning" (fc_fname fc, fc_start fc, fc_end fc, str, spans) n iRender :: Doc a -> Idris (SimpleDoc a) iRender d = do w <- getWidth ist <- getIState let ideMode = case idris_outputmode ist of IdeMode _ _ -> True _ -> False tty <- runIO isATTY case w of InfinitelyWide -> return $ renderPretty 1.0 1000000000 d ColsWide n -> return $ if n < 1 then renderPretty 1.0 1000000000 d else renderPretty 0.8 n d AutomaticWidth | ideMode || not tty -> return $ renderPretty 1.0 80 d | otherwise -> do width <- runIO getScreenWidth return $ renderPretty 0.8 width d hWriteDoc :: Handle -> IState -> SimpleDoc OutputAnnotation -> Idris () hWriteDoc h ist rendered = do runIO $ displayDecoratedA (hPutStr h) (maybe (return ()) (hStartColourise h)) (maybe (return ()) (hEndColourise h)) (fmap (annotationColour ist) rendered) runIO $ hPutStr h "\n" -- newline translation on the output -- stream should take care of this for -- Windows -- | Write a pretty-printed term to the console with semantic coloring consoleDisplayAnnotated :: Handle -> Doc OutputAnnotation -> Idris () consoleDisplayAnnotated h output = do ist <- getIState rendered <- iRender output hWriteDoc h ist rendered iPrintTermWithType :: Doc OutputAnnotation -> Doc OutputAnnotation -> Idris () iPrintTermWithType tm ty = iRenderResult (tm <+> colon <+> align ty) -- | Pretty-print a collection of overloadings to REPL or IDEMode - corresponds to :t name iPrintFunTypes :: [(Name, Bool)] -> Name -> [(Name, Doc OutputAnnotation)] -> Idris () iPrintFunTypes bnd n [] = iPrintError $ "No such variable " ++ show n iPrintFunTypes bnd n overloads = do ist <- getIState let ppo = ppOptionIst ist let infixes = idris_infixes ist let output = vsep (map (uncurry (ppOverload ppo infixes)) overloads) iRenderResult output where fullName ppo n | length overloads > 1 = prettyName True True bnd n | otherwise = prettyName True (ppopt_impl ppo) bnd n ppOverload ppo infixes n tm = fullName ppo n <+> colon <+> align tm iRenderOutput :: Doc OutputAnnotation -> Idris () iRenderOutput doc = do i <- getIState case idris_outputmode i of RawOutput h -> do out <- iRender doc hWriteDoc h i out IdeMode n h -> do (str, spans) <- fmap displaySpans . iRender . fmap (fancifyAnnots i True) $ doc let out = [toSExp str, toSExp spans] runIO . hPutStrLn h $ convSExp "write-decorated" out n iRenderResult :: Doc OutputAnnotation -> Idris () iRenderResult d = do ist <- getIState case idris_outputmode ist of RawOutput h -> consoleDisplayAnnotated h d IdeMode n h -> ideModeReturnAnnotated n h d ideModeReturnWithStatus :: String -> Integer -> Handle -> Doc OutputAnnotation -> Idris () ideModeReturnWithStatus status n h out = do ist <- getIState (str, spans) <- fmap displaySpans . iRender . fmap (fancifyAnnots ist True) $ out let good = [SymbolAtom status, toSExp str, toSExp spans] runIO . hPutStrLn h $ convSExp "return" good n -- | Write pretty-printed output to IDEMode with semantic annotations ideModeReturnAnnotated :: Integer -> Handle -> Doc OutputAnnotation -> Idris () ideModeReturnAnnotated = ideModeReturnWithStatus "ok" -- | Show an error with semantic highlighting iRenderError :: Doc OutputAnnotation -> Idris () iRenderError e = do ist <- getIState case idris_outputmode ist of RawOutput h -> consoleDisplayAnnotated h e IdeMode n h -> ideModeReturnWithStatus "error" n h e iPrintWithStatus :: String -> String -> Idris () iPrintWithStatus status s = do i <- getIState case idris_outputmode i of RawOutput h -> case s of "" -> return () s -> runIO $ hPutStrLn h s IdeMode n h -> let good = SexpList [SymbolAtom status, toSExp s] in runIO $ hPutStrLn h $ convSExp "return" good n iPrintResult :: String -> Idris () iPrintResult = iPrintWithStatus "ok" iPrintError :: String -> Idris () iPrintError = iPrintWithStatus "error" iputStrLn :: String -> Idris () iputStrLn s = do i <- getIState case idris_outputmode i of RawOutput h -> runIO $ hPutStrLn h s IdeMode n h -> runIO . hPutStrLn h $ convSExp "write-string" s n idemodePutSExp :: SExpable a => String -> a -> Idris () idemodePutSExp cmd info = do i <- getIState case idris_outputmode i of IdeMode n h -> runIO . hPutStrLn h $ convSExp cmd info n _ -> return () -- TODO: send structured output similar to the metavariable list iputGoal :: SimpleDoc OutputAnnotation -> Idris () iputGoal g = do i <- getIState case idris_outputmode i of RawOutput h -> hWriteDoc h i g IdeMode n h -> let (str, spans) = displaySpans . fmap (fancifyAnnots i True) $ g goal = [toSExp str, toSExp spans] in runIO . hPutStrLn h $ convSExp "write-goal" goal n -- | Warn about totality problems without failing to compile warnTotality :: Idris () warnTotality = do ist <- getIState mapM_ (warn ist) (nub (idris_totcheckfail ist)) where warn ist (fc, e) = iWarn fc (pprintErr ist (Msg e)) printUndefinedNames :: [Name] -> Doc OutputAnnotation printUndefinedNames ns = text "Undefined " <> names <> text "." where names = encloseSep empty empty (char ',') $ map ppName ns ppName = prettyName True True [] prettyDocumentedIst :: IState -> (Name, PTerm, Maybe (Docstring DocTerm)) -> Doc OutputAnnotation prettyDocumentedIst ist (name, ty, docs) = prettyName True True [] name <+> colon <+> align (prettyIst ist ty) <$> fromMaybe empty (fmap (\d -> renderDocstring (renderDocTerm ppTm norm) d <> line) docs) where ppTm = pprintDelab ist norm = normaliseAll (tt_ctxt ist) [] sendParserHighlighting :: Idris () sendParserHighlighting = do ist <- getIState let hs = map unwrap . nub . map wrap $ idris_parserHighlights ist sendHighlighting hs ist <- getIState putIState ist {idris_parserHighlights = []} where wrap (fc, a) = (FC' fc, a) unwrap (fc', a) = (unwrapFC fc', a) sendHighlighting :: [(FC, OutputAnnotation)] -> Idris () sendHighlighting highlights = do ist <- getIState case idris_outputmode ist of RawOutput _ -> updateIState $ \ist -> ist { idris_highlightedRegions = highlights ++ idris_highlightedRegions ist } IdeMode n h -> let fancier = [ toSExp (fc, fancifyAnnots ist False annot) | (fc, annot) <- highlights, fullFC fc ] in case fancier of [] -> return () _ -> runIO . hPutStrLn h $ convSExp "output" (SymbolAtom "ok", (SymbolAtom "highlight-source", fancier)) n where fullFC (FC _ _ _) = True fullFC _ = False -- | Write the highlighting information to a file, for use in external tools -- or in editors that don't support the IDE protocol writeHighlights :: FilePath -> Idris () writeHighlights f = do ist <- getIState let hs = reverse $ idris_highlightedRegions ist let hfile = replaceExtension f "idh" let annots = toSExp [ (fc, fancifyAnnots ist False annot) | (fc@(FC _ _ _), annot) <- hs ] runIO $ writeFile hfile $ sExpToString annots clearHighlights :: Idris () clearHighlights = updateIState $ \ist -> ist { idris_highlightedRegions = [] } renderExternal :: OutputFmt -> Int -> Doc OutputAnnotation -> Idris String renderExternal fmt width doc | width < 1 = throwError . Msg $ "There must be at least one column for the pretty-printer." | otherwise = do ist <- getIState return . wrap fmt . displayDecorated (decorate fmt) . renderPretty 1.0 width . fmap (fancifyAnnots ist True) $ doc where decorate _ (AnnFC _) = id decorate HTMLOutput (AnnName _ (Just TypeOutput) d _) = tag "idris-type" d decorate HTMLOutput (AnnName _ (Just FunOutput) d _) = tag "idris-function" d decorate HTMLOutput (AnnName _ (Just DataOutput) d _) = tag "idris-data" d decorate HTMLOutput (AnnName _ (Just MetavarOutput) d _) = tag "idris-metavar" d decorate HTMLOutput (AnnName _ (Just PostulateOutput) d _) = tag "idris-postulate" d decorate HTMLOutput (AnnName _ _ _ _) = id decorate HTMLOutput (AnnBoundName _ True) = tag "idris-bound idris-implicit" Nothing decorate HTMLOutput (AnnBoundName _ False) = tag "idris-bound" Nothing decorate HTMLOutput (AnnConst c) = tag (if constIsType c then "idris-type" else "idris-data") (Just $ constDocs c) decorate HTMLOutput (AnnData _ _) = tag "idris-data" Nothing decorate HTMLOutput (AnnType _ _) = tag "idris-type" Nothing decorate HTMLOutput AnnKeyword = tag "idris-keyword" Nothing decorate HTMLOutput (AnnTextFmt fmt) = case fmt of BoldText -> mkTag "strong" ItalicText -> mkTag "em" UnderlineText -> tag "idris-underlined" Nothing where mkTag t x = "<"++t++">"++x++"</"++t++">" decorate HTMLOutput (AnnTerm _ _) = id decorate HTMLOutput (AnnSearchResult _) = id decorate HTMLOutput (AnnErr _) = id decorate HTMLOutput (AnnNamespace _ _) = id decorate HTMLOutput (AnnLink url) = \txt -> "<a href=\"" ++ url ++ "\">" ++ txt ++ "</a>" decorate HTMLOutput AnnQuasiquote = id decorate HTMLOutput AnnAntiquote = id decorate LaTeXOutput (AnnName _ (Just TypeOutput) _ _) = latex "IdrisType" decorate LaTeXOutput (AnnName _ (Just FunOutput) _ _) = latex "IdrisFunction" decorate LaTeXOutput (AnnName _ (Just DataOutput) _ _) = latex "IdrisData" decorate LaTeXOutput (AnnName _ (Just MetavarOutput) _ _) = latex "IdrisMetavar" decorate LaTeXOutput (AnnName _ (Just PostulateOutput) _ _) = latex "IdrisPostulate" decorate LaTeXOutput (AnnName _ _ _ _) = id decorate LaTeXOutput (AnnBoundName _ True) = latex "IdrisImplicit" decorate LaTeXOutput (AnnBoundName _ False) = latex "IdrisBound" decorate LaTeXOutput (AnnConst c) = latex $ if constIsType c then "IdrisType" else "IdrisData" decorate LaTeXOutput (AnnData _ _) = latex "IdrisData" decorate LaTeXOutput (AnnType _ _) = latex "IdrisType" decorate LaTeXOutput AnnKeyword = latex "IdrisKeyword" decorate LaTeXOutput (AnnTextFmt fmt) = case fmt of BoldText -> latex "textbf" ItalicText -> latex "emph" UnderlineText -> latex "underline" decorate LaTeXOutput (AnnTerm _ _) = id decorate LaTeXOutput (AnnSearchResult _) = id decorate LaTeXOutput (AnnErr _) = id decorate LaTeXOutput (AnnNamespace _ _) = id decorate LaTeXOutput (AnnLink url) = (++ "(\\url{" ++ url ++ "})") decorate LaTeXOutput AnnQuasiquote = id decorate LaTeXOutput AnnAntiquote = id tag cls docs str = "<span class=\""++cls++"\""++title++">" ++ str ++ "</span>" where title = maybe "" (\d->" title=\"" ++ d ++ "\"") docs latex cmd str = "\\"++cmd++"{"++str++"}" wrap HTMLOutput str = "<!doctype html><html><head><style>" ++ css ++ "</style></head>" ++ "<body><!-- START CODE --><pre>" ++ str ++ "</pre><!-- END CODE --></body></html>" where css = concat . intersperse "\n" $ [".idris-data { color: red; } ", ".idris-type { color: blue; }", ".idris-function {color: green; }", ".idris-keyword { font-weight: bold; }", ".idris-bound { color: purple; }", ".idris-implicit { font-style: italic; }", ".idris-underlined { text-decoration: underline; }"] wrap LaTeXOutput str = concat . intersperse "\n" $ ["\\documentclass{article}", "\\usepackage{fancyvrb}", "\\usepackage[usenames]{xcolor}"] ++ map (\(cmd, color) -> "\\newcommand{\\"++ cmd ++ "}[1]{\\textcolor{"++ color ++"}{#1}}") [("IdrisData", "red"), ("IdrisType", "blue"), ("IdrisBound", "magenta"), ("IdrisFunction", "green")] ++ ["\\newcommand{\\IdrisKeyword}[1]{{\\underline{#1}}}", "\\newcommand{\\IdrisImplicit}[1]{{\\itshape \\IdrisBound{#1}}}", "\n", "\\begin{document}", "% START CODE", "\\begin{Verbatim}[commandchars=\\\\\\{\\}]", str, "\\end{Verbatim}", "% END CODE", "\\end{document}"]
enolan/Idris-dev
src/Idris/Output.hs
Haskell
bsd-3-clause
15,694
{-# OPTIONS_GHC -Wall #-} module Cis194.Hw.LogAnalysis where -- in ghci, you may need to specify an additional include path: -- Prelude> :set -isrc import Cis194.Hw.Log -- $setup -- >>> let foo = LogMessage Warning 10 "foo" -- >>> let baz = LogMessage Warning 5 "baz" -- >>> let bif = LogMessage Warning 15 "bif" -- >>> let zor = LogMessage (Error 2) 562 "zor" parseMessage :: String -> LogMessage parseMessage s = case s of [] -> Unknown "not good" 'E':_ -> do let _:y:z:zs = (words s) er = (read y)::Int ts = (read z)::Int str= unwords zs LogMessage (Error er) ts str 'I':_ -> do let _:z:zs = (words s) ts = (read z)::Int str= unwords zs LogMessage Info ts str 'W':_ -> do let _:z:zs = (words s) ts = (read z)::Int str= unwords zs LogMessage Warning ts str _ -> Unknown s parse :: String -> [LogMessage] parse s = case s of "" -> [] xs -> let dems = lines xs in map parseMessage dems -- | 1. test for getter: ts -- >>> let foo = LogMessage Warning 10 "foo" -- >>> tst foo -- 10 tst :: LogMessage -> Int tst (LogMessage _ t _) = t tst _ = 0 -- | find LogMessage type -- >>> let zor = LogMessage (Error 2) 562 "zor" -- >>> logMessage zor -- Error 2 -- logMessage :: LogMessage -> MessageType -- logMessage (LogMessage l _ _) = l -- logMessage _ = Info -- | insert for LogMessages -- >>> insert (Unknown "foo") Leaf -- Leaf -- >>> let a = Leaf -- >>> let b = LogMessage Warning 5 "baz" -- >>> insert b a -- Node Leaf b Leaf -- | insert maintains the sort order of messages in the tree -- >>> let foo = LogMessage Warning 10 "foo" -- >>> let baz = LogMessage Warning 5 "baz" -- >>> let bif = LogMessage Warning 15 "bif" -- >>> let zor = LogMessage (Error 2) 562 "zor" -- >>> let a = Node Leaf foo Leaf -- >>> insert baz a -- Node (Node Leaf baz Leaf) foo Leaf -- >>> insert bif b -- Node (Node Leaf baz Leaf) foo1 (Node Leaf bif Leaf) insert :: LogMessage -> MessageTree -> MessageTree insert (Unknown _) Leaf = Leaf insert lm Leaf = Node Leaf lm Leaf insert lm (Node l m r) | (tst lm) >= (tst m) = Node l m (insert lm r) | otherwise = Node (insert lm l) m r -- | Build: builds a MessageTree from a list of LogMessages ----- >>> let foo = LogMessage Warning 10 "foo" ---- >>> let baz = LogMessage Warning 5 "baz" ---- >>> let bif = LogMessage Warning 15 "bif" -- >>> let ans = Node (Node Leaf (LogMessage Warning 5 "baz") Leaf) (LogMessage Warning 10 "foo") (Node Leaf (LogMessage Warning 15 "bif") Leaf) -- >>> build [foo, baz, bif] -- ans ----- Node (Node Leaf (LogMessage Warning 5 "baz") Leaf) (LogMessage Warning 10 "foo") (Node Leaf (LogMessage Warning 15 "bif") Leaf) build :: [LogMessage] -> MessageTree build = foldl (flip insert) Leaf inOrder :: MessageTree -> [LogMessage] inOrder Leaf = [] inOrder (Node l m r) = inOrder l ++ [m] ++ inOrder r -- | build then order: buildThenOrder :: [LogMessage] -> [LogMessage] buildThenOrder = inOrder . build -- | function isError isError :: MessageType -> Bool isError x = case x of (Error _) -> True Warning -> False Info -> False -- | message type from log massage messType :: LogMessage -> MessageType messType (LogMessage mt _ _) = mt messType _ = Info -- | gets the message mess :: LogMessage -> String mess (LogMessage _ _ str) = str mess _ = "" -- | is this an error LogMessage? isLogMessageError :: LogMessage -> Bool isLogMessageError = isError . messType -- | does this error message exceed 50? exceedsThreshold50 :: MessageType -> Bool exceedsThreshold50 (Error x) | x >= 50 = True | otherwise = False exceedsThreshold50 Info = False exceedsThreshold50 Warning = False thresholdFor50 :: LogMessage -> Bool thresholdFor50 = exceedsThreshold50 . messType -- let yy = filter isLogMessageError (buildThenOrder messages) -- whatWentWrong takes an unsorted list of LogMessages, and returns a list of the -- messages corresponding to any errors with a severity of 50 or greater, -- sorted by timestamp. whatWentWrong :: [LogMessage] -> [String] whatWentWrong xs = map mess $ filter thresholdFor50 $ filter isLogMessageError $ buildThenOrder xs
halarnold2000/cis194
src/Cis194/Hw/LogAnalysis.hs
Haskell
bsd-3-clause
4,449
module Problem13 ( numbers100 , sum100numbers , columnarAddition ) where import Data.List as L import Lib (digits, number) numbers100 :: [Integer] numbers100 = [ 37107287533902102798797998220837590246510135740250 , 46376937677490009712648124896970078050417018260538 , 74324986199524741059474233309513058123726617309629 , 91942213363574161572522430563301811072406154908250 , 23067588207539346171171980310421047513778063246676 , 89261670696623633820136378418383684178734361726757 , 28112879812849979408065481931592621691275889832738 , 44274228917432520321923589422876796487670272189318 , 47451445736001306439091167216856844588711603153276 , 70386486105843025439939619828917593665686757934951 , 62176457141856560629502157223196586755079324193331 , 64906352462741904929101432445813822663347944758178 , 92575867718337217661963751590579239728245598838407 , 58203565325359399008402633568948830189458628227828 , 80181199384826282014278194139940567587151170094390 , 35398664372827112653829987240784473053190104293586 , 86515506006295864861532075273371959191420517255829 , 71693888707715466499115593487603532921714970056938 , 54370070576826684624621495650076471787294438377604 , 53282654108756828443191190634694037855217779295145 , 36123272525000296071075082563815656710885258350721 , 45876576172410976447339110607218265236877223636045 , 17423706905851860660448207621209813287860733969412 , 81142660418086830619328460811191061556940512689692 , 51934325451728388641918047049293215058642563049483 , 62467221648435076201727918039944693004732956340691 , 15732444386908125794514089057706229429197107928209 , 55037687525678773091862540744969844508330393682126 , 18336384825330154686196124348767681297534375946515 , 80386287592878490201521685554828717201219257766954 , 78182833757993103614740356856449095527097864797581 , 16726320100436897842553539920931837441497806860984 , 48403098129077791799088218795327364475675590848030 , 87086987551392711854517078544161852424320693150332 , 59959406895756536782107074926966537676326235447210 , 69793950679652694742597709739166693763042633987085 , 41052684708299085211399427365734116182760315001271 , 65378607361501080857009149939512557028198746004375 , 35829035317434717326932123578154982629742552737307 , 94953759765105305946966067683156574377167401875275 , 88902802571733229619176668713819931811048770190271 , 25267680276078003013678680992525463401061632866526 , 36270218540497705585629946580636237993140746255962 , 24074486908231174977792365466257246923322810917141 , 91430288197103288597806669760892938638285025333403 , 34413065578016127815921815005561868836468420090470 , 23053081172816430487623791969842487255036638784583 , 11487696932154902810424020138335124462181441773470 , 63783299490636259666498587618221225225512486764533 , 67720186971698544312419572409913959008952310058822 , 95548255300263520781532296796249481641953868218774 , 76085327132285723110424803456124867697064507995236 , 37774242535411291684276865538926205024910326572967 , 23701913275725675285653248258265463092207058596522 , 29798860272258331913126375147341994889534765745501 , 18495701454879288984856827726077713721403798879715 , 38298203783031473527721580348144513491373226651381 , 34829543829199918180278916522431027392251122869539 , 40957953066405232632538044100059654939159879593635 , 29746152185502371307642255121183693803580388584903 , 41698116222072977186158236678424689157993532961922 , 62467957194401269043877107275048102390895523597457 , 23189706772547915061505504953922979530901129967519 , 86188088225875314529584099251203829009407770775672 , 11306739708304724483816533873502340845647058077308 , 82959174767140363198008187129011875491310547126581 , 97623331044818386269515456334926366572897563400500 , 42846280183517070527831839425882145521227251250327 , 55121603546981200581762165212827652751691296897789 , 32238195734329339946437501907836945765883352399886 , 75506164965184775180738168837861091527357929701337 , 62177842752192623401942399639168044983993173312731 , 32924185707147349566916674687634660915035914677504 , 99518671430235219628894890102423325116913619626622 , 73267460800591547471830798392868535206946944540724 , 76841822524674417161514036427982273348055556214818 , 97142617910342598647204516893989422179826088076852 , 87783646182799346313767754307809363333018982642090 , 10848802521674670883215120185883543223812876952786 , 71329612474782464538636993009049310363619763878039 , 62184073572399794223406235393808339651327408011116 , 66627891981488087797941876876144230030984490851411 , 60661826293682836764744779239180335110989069790714 , 85786944089552990653640447425576083659976645795096 , 66024396409905389607120198219976047599490197230297 , 64913982680032973156037120041377903785566085089252 , 16730939319872750275468906903707539413042652315011 , 94809377245048795150954100921645863754710598436791 , 78639167021187492431995700641917969777599028300699 , 15368713711936614952811305876380278410754449733078 , 40789923115535562561142322423255033685442488917353 , 44889911501440648020369068063960672322193204149535 , 41503128880339536053299340368006977710650566631954 , 81234880673210146739058568557934581403627822703280 , 82616570773948327592232845941706525094512325230608 , 22918802058777319719839450180888072429661980811197 , 77158542502016545090413245809786882778948721859617 , 72107838435069186155435662884062257473692284509516 , 20849603980134001723930671666823555245252804609722 , 53503534226472524250874054075591789781264330331690 ] sum100numbers = columnarAddition numbers100 columnarAddition :: [Integer] -> Integer columnarAddition numbers = let numbersAsDigits = map digits numbers columns = L.transpose $ map L.reverse numbersAsDigits (sumDigits, carryOver) = foldl sumColumns ([], 0) columns in number $ digits carryOver ++ sumDigits where sumColumns :: ([Integer], Integer) -> [Integer] -> ([Integer], Integer) sumColumns (sumDigits,carryOver) nextDigits = let nextSum = (sum nextDigits) + carryOver nextDigit = nextSum `mod` 10 nextCarryOver = nextSum `div` 10 in (nextDigit:sumDigits, nextCarryOver)
candidtim/euler
src/Problem13.hs
Haskell
bsd-3-clause
7,418
{-# LANGUAGE RebindableSyntax #-} -- Copyright : (C) 2009 Corey O'Connor -- License : BSD-style (see the file LICENSE) {-# LANGUAGE MagicHash #-} module Bind.Marshal.Verify.Dynamic where import Bind.Marshal.Prelude import Bind.Marshal.Action.Base import Bind.Marshal.Action.Dynamic import Bind.Marshal.Action.Monad import Control.Applicative import Data.IORef import GHC.Exts import GHC.Prim import System.IO import Verify data NopDelegate = NopDelegate instance BufferDelegate NopDelegate where gen_region 0 NopDelegate = returnM $! BDIter 0 0 NopDelegate nullAddr# nullAddr# gen_region _size NopDelegate = fail "NopDelegate can only generate 0 sized buffers" finalize_region bd_iter | bytes_final bd_iter == 0 = returnM (buffer_delegate bd_iter) | otherwise = fail "NopDelegate can only finalize 0 sized buffers" data LoggingDelegate sub_delegate where LoggingDelegate :: BufferDelegate sub_delegate => [ProducerLogEntry] -> sub_delegate -> LoggingDelegate sub_delegate data ProducerLogEntry = GenBuffer Size Size -- Requested miminum size. Max bytes avail of generated buffer. | FinalizeBuffer Size -- Actual finalize size. deriving ( Show, Eq ) logging_buffer_delegate :: BufferDelegate bd => bd -> IO (LoggingDelegate bd) logging_buffer_delegate sub_delegate = returnM $! LoggingDelegate [] sub_delegate dump_request_log :: LoggingDelegate sub_delegate -> IO () dump_request_log (LoggingDelegate log _sub) = do mapM_ (\s -> log_out $ show s) log :: IO () instance BufferDelegate sub_delegate => BufferDelegate (LoggingDelegate sub_delegate) where gen_region size (LoggingDelegate log sub_p) = do bd_iter <- gen_region size sub_p let sub_p' = buffer_delegate bd_iter let log' = log ++ [GenBuffer size (max_bytes_avail bd_iter) ] returnM $! bd_iter { buffer_delegate = LoggingDelegate log' sub_p' } :: IO (BDIter (LoggingDelegate sub_delegate)) finalize_region bd_iter@(BDIter _ _ bd s p) = do let !(LoggingDelegate log sub_p) = bd log' = log ++ [FinalizeBuffer (I# (minusAddr# p s))] sub_p' <- finalize_region (bd_iter {buffer_delegate = sub_p}) returnM $! LoggingDelegate log' sub_p' :: IO (LoggingDelegate sub_delegate) verify_logged_requests :: LoggingDelegate sub_delegate -> [ProducerLogEntry] -> IO () verify_logged_requests p@(LoggingDelegate actual _sub_p) expected = do if actual == expected then returnM () else do fail $ "expected is:\n" ++ show expected :: IO ()
coreyoconnor/bind-marshal
src/Bind/Marshal/Verify/Dynamic.hs
Haskell
bsd-3-clause
2,661
-- | Simulates the @isUnicodeIdentifierPart@ Java method. <http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html#isUnicodeIdentifierPart%28int%29> module Language.Java.Character.IsUnicodeIdentifierPart ( IsUnicodeIdentifierPart(..) ) where import Data.Char import Data.Word import Data.Set.Diet(Diet) import qualified Data.Set.Diet as S -- | Instances simulate Java characters and provide a decision on simulating @isUnicodeIdentifierPart@. class Enum c => IsUnicodeIdentifierPart c where isUnicodeIdentifierPart :: c -> Bool isNotUnicodeIdentifierPart :: c -> Bool isNotUnicodeIdentifierPart = not . isUnicodeIdentifierPart instance IsUnicodeIdentifierPart Char where isUnicodeIdentifierPart c = ord c `S.member` isUnicodeIdentifierPartSet instance IsUnicodeIdentifierPart Int where isUnicodeIdentifierPart c = c `S.member` isUnicodeIdentifierPartSet instance IsUnicodeIdentifierPart Integer where isUnicodeIdentifierPart c = c `S.member` isUnicodeIdentifierPartSet instance IsUnicodeIdentifierPart Word8 where isUnicodeIdentifierPart c = c `S.member` isUnicodeIdentifierPartSet instance IsUnicodeIdentifierPart Word16 where isUnicodeIdentifierPart c = c `S.member` isUnicodeIdentifierPartSet instance IsUnicodeIdentifierPart Word32 where isUnicodeIdentifierPart c = c `S.member` isUnicodeIdentifierPartSet instance IsUnicodeIdentifierPart Word64 where isUnicodeIdentifierPart c = c `S.member` isUnicodeIdentifierPartSet isUnicodeIdentifierPartSet :: (Num a, Enum a, Ord a) => Diet a isUnicodeIdentifierPartSet = let r = [ [0..8] , [14..27] , [48..57] , [65..90] , [95] , [97..122] , [127..159] , [170] , [173] , [181] , [186] , [192..214] , [216..246] , [248..566] , [592..705] , [710..721] , [736..740] , [750] , [768..855] , [861..879] , [890] , [902] , [904..906] , [908] , [910..929] , [931..974] , [976..1013] , [1015..1019] , [1024..1153] , [1155..1158] , [1162..1230] , [1232..1269] , [1272..1273] , [1280..1295] , [1329..1366] , [1369] , [1377..1415] , [1425..1441] , [1443..1465] , [1467..1469] , [1471] , [1473..1474] , [1476] , [1488..1514] , [1520..1522] , [1536..1539] , [1552..1557] , [1569..1594] , [1600..1624] , [1632..1641] , [1646..1747] , [1749..1757] , [1759..1768] , [1770..1788] , [1791] , [1807..1866] , [1869..1871] , [1920..1969] , [2305..2361] , [2364..2381] , [2384..2388] , [2392..2403] , [2406..2415] , [2433..2435] , [2437..2444] , [2447..2448] , [2451..2472] , [2474..2480] , [2482] , [2486..2489] , [2492..2500] , [2503..2504] , [2507..2509] , [2519] , [2524..2525] , [2527..2531] , [2534..2545] , [2561..2563] , [2565..2570] , [2575..2576] , [2579..2600] , [2602..2608] , [2610..2611] , [2613..2614] , [2616..2617] , [2620] , [2622..2626] , [2631..2632] , [2635..2637] , [2649..2652] , [2654] , [2662..2676] , [2689..2691] , [2693..2701] , [2703..2705] , [2707..2728] , [2730..2736] , [2738..2739] , [2741..2745] , [2748..2757] , [2759..2761] , [2763..2765] , [2768] , [2784..2787] , [2790..2799] , [2817..2819] , [2821..2828] , [2831..2832] , [2835..2856] , [2858..2864] , [2866..2867] , [2869..2873] , [2876..2883] , [2887..2888] , [2891..2893] , [2902..2903] , [2908..2909] , [2911..2913] , [2918..2927] , [2929] , [2946..2947] , [2949..2954] , [2958..2960] , [2962..2965] , [2969..2970] , [2972] , [2974..2975] , [2979..2980] , [2984..2986] , [2990..2997] , [2999..3001] , [3006..3010] , [3014..3016] , [3018..3021] , [3031] , [3047..3055] , [3073..3075] , [3077..3084] , [3086..3088] , [3090..3112] , [3114..3123] , [3125..3129] , [3134..3140] , [3142..3144] , [3146..3149] , [3157..3158] , [3168..3169] , [3174..3183] , [3202..3203] , [3205..3212] , [3214..3216] , [3218..3240] , [3242..3251] , [3253..3257] , [3260..3268] , [3270..3272] , [3274..3277] , [3285..3286] , [3294] , [3296..3297] , [3302..3311] , [3330..3331] , [3333..3340] , [3342..3344] , [3346..3368] , [3370..3385] , [3390..3395] , [3398..3400] , [3402..3405] , [3415] , [3424..3425] , [3430..3439] , [3458..3459] , [3461..3478] , [3482..3505] , [3507..3515] , [3517] , [3520..3526] , [3530] , [3535..3540] , [3542] , [3544..3551] , [3570..3571] , [3585..3642] , [3648..3662] , [3664..3673] , [3713..3714] , [3716] , [3719..3720] , [3722] , [3725] , [3732..3735] , [3737..3743] , [3745..3747] , [3749] , [3751] , [3754..3755] , [3757..3769] , [3771..3773] , [3776..3780] , [3782] , [3784..3789] , [3792..3801] , [3804..3805] , [3840] , [3864..3865] , [3872..3881] , [3893] , [3895] , [3897] , [3902..3911] , [3913..3946] , [3953..3972] , [3974..3979] , [3984..3991] , [3993..4028] , [4038] , [4096..4129] , [4131..4135] , [4137..4138] , [4140..4146] , [4150..4153] , [4160..4169] , [4176..4185] , [4256..4293] , [4304..4344] , [4352..4441] , [4447..4514] , [4520..4601] , [4608..4614] , [4616..4678] , [4680] , [4682..4685] , [4688..4694] , [4696] , [4698..4701] , [4704..4742] , [4744] , [4746..4749] , [4752..4782] , [4784] , [4786..4789] , [4792..4798] , [4800] , [4802..4805] , [4808..4814] , [4816..4822] , [4824..4846] , [4848..4878] , [4880] , [4882..4885] , [4888..4894] , [4896..4934] , [4936..4954] , [4969..4977] , [5024..5108] , [5121..5740] , [5743..5750] , [5761..5786] , [5792..5866] , [5870..5872] , [5888..5900] , [5902..5908] , [5920..5940] , [5952..5971] , [5984..5996] , [5998..6000] , [6002..6003] , [6016..6099] , [6103] , [6108..6109] , [6112..6121] , [6155..6157] , [6160..6169] , [6176..6263] , [6272..6313] , [6400..6428] , [6432..6443] , [6448..6459] , [6470..6509] , [6512..6516] , [7424..7531] , [7680..7835] , [7840..7929] , [7936..7957] , [7960..7965] , [7968..8005] , [8008..8013] , [8016..8023] , [8025] , [8027] , [8029] , [8031..8061] , [8064..8116] , [8118..8124] , [8126] , [8130..8132] , [8134..8140] , [8144..8147] , [8150..8155] , [8160..8172] , [8178..8180] , [8182..8188] , [8204..8207] , [8234..8238] , [8255..8256] , [8276] , [8288..8291] , [8298..8303] , [8305] , [8319] , [8400..8412] , [8417] , [8421..8426] , [8450] , [8455] , [8458..8467] , [8469] , [8473..8477] , [8484] , [8486] , [8488] , [8490..8493] , [8495..8497] , [8499..8505] , [8509..8511] , [8517..8521] , [8544..8579] , [12293..12295] , [12321..12335] , [12337..12341] , [12344..12348] , [12353..12438] , [12441..12442] , [12445..12447] , [12449..12543] , [12549..12588] , [12593..12686] , [12704..12727] , [12784..12799] , [13312..19893] , [19968..40869] , [40960..42124] , [44032..55203] , [63744..64045] , [64048..64106] , [64256..64262] , [64275..64279] , [64285..64296] , [64298..64310] , [64312..64316] , [64318] , [64320..64321] , [64323..64324] , [64326..64433] , [64467..64829] , [64848..64911] , [64914..64967] , [65008..65019] , [65024..65039] , [65056..65059] , [65075..65076] , [65101..65103] , [65136..65140] , [65142..65276] , [65279] , [65296..65305] , [65313..65338] , [65343] , [65345..65370] , [65381..65470] , [65474..65479] , [65482..65487] , [65490..65495] , [65498..65500] , [65529..65531] , [65536..65547] , [65549..65574] , [65576..65594] , [65596..65597] , [65599..65613] , [65616..65629] , [65664..65786] , [66304..66334] , [66352..66378] , [66432..66461] , [66560..66717] , [66720..66729] , [67584..67589] , [67592] , [67594..67637] , [67639..67640] , [67644] , [67647] , [119141..119145] , [119149..119170] , [119173..119179] , [119210..119213] , [119808..119892] , [119894..119964] , [119966..119967] , [119970] , [119973..119974] , [119977..119980] , [119982..119993] , [119995] , [119997..120003] , [120005..120069] , [120071..120074] , [120077..120084] , [120086..120092] , [120094..120121] , [120123..120126] , [120128..120132] , [120134] , [120138..120144] , [120146..120483] , [120488..120512] , [120514..120538] , [120540..120570] , [120572..120596] , [120598..120628] , [120630..120654] , [120656..120686] , [120688..120712] , [120714..120744] , [120746..120770] , [120772..120777] , [120782..120831] , [131072..173782] , [194560..195101] ] in S.fromList . concat $ r
tonymorris/java-character
src/Language/Java/Character/IsUnicodeIdentifierPart.hs
Haskell
bsd-3-clause
12,247
{-# LANGUAGE TemplateHaskell #-} module NintetyNine.Problem16 where import Test.Hspec import Test.QuickCheck import Test.QuickCheck.All import Data.List -- dropEvery "abcdefghik" 3 "abdeghk" dropEvery :: [a] -> Int -> [a] dropEvery xs n | length xs < n = xs | otherwise = take (n - 1) xs ++ dropEvery (drop n xs) n dropEvery2 :: [a] -> Int -> [a] dropEvery2 [] _ = [] dropEvery2 xs n = take (n - 1) xs ++ dropEvery2 (drop n xs) n -- using flip, zip, map, first , snd, cycle dropEvery3 :: [a] -> Int -> [a] dropEvery3 = -- dropEvery x : drop + repeat for every n -- have a list and delete every element at position multiple of n -- how to delete an element from a list or create a new list without that element -- foldl untill find index = n * x -- scanl where it concatenates every x except if it has index m -- with splitAt -- dropEvery :: [a] -> Int -> [a] -- dropEvery xs n = y ++ (dropEvery ys) -- where (y:ys) = (splitAt n xs) -- dropEvery2 :: [a] -> Int -> [a] -- dropEvery2 xs n = let (y::ys) = (splitAt n xs) -- in y ++ (dropEvery2 ys) -- Test -- hspec dropEverySpec :: Spec dropEverySpec = do describe "Drop every N'th element from a list." $ do it "Drop every N'th element from a list." $ do dropEvery "abcdefghik" 3 `shouldBe` "abdeghk" describe "[With dropEvery2] Drop every N'th element from a list." $ do it "Drop every N'th element from a list." $ do dropEvery2 "abcdefghik" 3 `shouldBe` "abdeghk" -- QuickCheck return [] main = $quickCheckAll
chemouna/99Haskell
src/Problem16.hs
Haskell
bsd-3-clause
1,547
#!/usr/bin/runhaskell module Main where import Distribution.Simple main :: IO () main = defaultMain
colinhect/hsnoise
Setup.hs
Haskell
bsd-3-clause
104
------------------------------------------------------------ -- | -- Module : Data.NeuralNetwork.Backend.BLASHS -- Description : A backend for neural network on top of 'blas-hs' -- Copyright : (c) 2016 Jiasen Wu -- License : BSD-style (see the file LICENSE) -- Maintainer : Jiasen Wu <[email protected]> -- Stability : experimental -- Portability : portable -- -- -- This module supplies a backend for the neural-network-base -- package. This backend is implemented on top of the blas-hs -- package and optimised with SIMD. ------------------------------------------------------------ {-# LANGUAGE UndecidableInstances #-} module Data.NeuralNetwork.Backend.BLASHS ( -- module Data.NeuralNetwork.Backend.BLASHS.Layers, module Data.NeuralNetwork.Backend.BLASHS.Utils, module Data.NeuralNetwork.Backend.BLASHS.LSTM, module Data.NeuralNetwork.Backend.BLASHS.SIMD, ByBLASHS(..), byBLASHSf, byBLASHSd ) where import Data.NeuralNetwork import Data.NeuralNetwork.Stack import Data.NeuralNetwork.Common import Data.NeuralNetwork.Backend.BLASHS.Layers import Data.NeuralNetwork.Backend.BLASHS.LSTM import Data.NeuralNetwork.Backend.BLASHS.Utils import Data.NeuralNetwork.Backend.BLASHS.Eval import Data.NeuralNetwork.Backend.BLASHS.SIMD import Control.Monad.Except (ExceptT, throwError) import Control.Monad.State import Data.Constraint (Dict(..)) import Blas.Generic.Unsafe (Numeric) -- | Compilation of the specification of a neural network is carried out in -- the 'Err' monad, and the possible errors are characterized by 'ErrCode'. type Err = ExceptT ErrCode IO -- | The backend data type data ByBLASHS p = ByBLASHS byBLASHSf :: ByBLASHS Float byBLASHSf = ByBLASHS byBLASHSd :: ByBLASHS Double byBLASHSd = ByBLASHS type AbbrSpecToCom p s = SpecToCom (ByBLASHS p) s type AbbrSpecToEvl p s o = SpecToEvl (ByBLASHS p) (AbbrSpecToCom p s) o -- | Neural network specified to start with 1D / 2D input instance (InputLayer i, RealType p, BodyTrans Err (ByBLASHS p) s, EvalTrans Err (ByBLASHS p) (AbbrSpecToCom p s) o, BackendCst Err (AbbrSpecToCom p s) (AbbrSpecToEvl p s o)) => Backend (ByBLASHS p) (i,s,o) where type Env (ByBLASHS p) = Err type ComponentFromSpec (ByBLASHS p) (i,s,o) = AbbrSpecToCom p s type EvaluatorFromSpec (ByBLASHS p) (i,s,o) = AbbrSpecToEvl p s o compile b (i,s,o) = do c <- btrans b (isize i) s e <- etrans b c o return $ (c, e) witness _ _ = Dict instance RunInEnv IO Err where run = liftIO instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecFullConnect where -- 'SpecFullConnect' is translated to a two-layer component -- a full-connect, followed by a relu activation (1D, single channel) type SpecToCom (ByBLASHS p) SpecFullConnect = Stack (RunLayer p F) (RunLayer p (T SinglVec)) CE btrans _ (D1 s) (FullConnect n) = do u <- lift $ newFLayer s n return $ Stack u (Activation (relu, relu')) btrans _ _ _ = throwError ErrMismatch instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecConvolution where -- 'SpecConvolution' is translated to a two-layer component -- a convolution, following by a relu activation (2D, multiple channels) type SpecToCom (ByBLASHS p) SpecConvolution = Stack (RunLayer p C) (RunLayer p (T MultiMat)) CE btrans _ (D2 k s t) (Convolution n f p) = do u <- lift $ newCLayer k n f p return $ Stack u (Activation (relu, relu')) btrans _ _ _ = throwError ErrMismatch instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecMaxPooling where -- 'MaxPooling' is translated to a max-pooling component. type SpecToCom (ByBLASHS p) SpecMaxPooling = RunLayer p P btrans _ (D2 _ _ _) (MaxPooling n) = return (MaxP n) btrans _ _ _ = throwError ErrMismatch instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecReshape2DAs1D where -- 'SpecReshape2DAs1D' is translated to a reshaping component. type SpecToCom (ByBLASHS p) SpecReshape2DAs1D = Reshape2DAs1D p btrans _ (D2 _ _ _) _ = return as1D btrans _ _ _ = throwError ErrMismatch instance (Numeric p, RealType p, SIMDable p) => BodyTrans Err (ByBLASHS p) SpecLSTM where -- 'SpecLSTM' is translated to a LSTM component. type SpecToCom (ByBLASHS p) SpecLSTM = Stack (LSTM p) (RunLayer p (T SinglVec)) (LiftRun (Run (LSTM p)) (Run (RunLayer p (T SinglVec)))) btrans _ (D1 s) (LSTM n) = do u <- lift $ newLSTM s n return $ Stack u (Activation (relu, relu')) btrans _ _ _ = throwError ErrMismatch instance (BodyTrans Err (ByBLASHS p) a) => BodyTrans Err (ByBLASHS p) (SpecFlow a) where -- type SpecToCom (ByBLASHS p) (SpecFlow a) = Stream (SpecToCom (ByBLASHS p) a) btrans b (SV s) (Flow a) = do u <- btrans b s a return $ Stream u btrans _ _ _ = throwError ErrMismatch instance Component c => EvalTrans Err (ByBLASHS p) c SpecEvaluator where type SpecToEvl (ByBLASHS p) c SpecEvaluator = Eval (Run c) p etrans _ _ = return . Eval
pierric/neural-network
Backend-blashs/Data/NeuralNetwork/Backend/BLASHS.hs
Haskell
bsd-3-clause
5,167
-- -- Benchmark code: sample request using http-condiuit -- -- Copyright © 2012-2013 Operational Dynamics Consulting, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is made -- available to you by its authors as open source software: you can -- redistribute it and/or modify it under a BSD licence. -- {-# LANGUAGE OverloadedStrings #-} module ConduitSample (sampleViaHttpConduit) where import Control.Monad.Trans (liftIO) import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import Data.CaseInsensitive (CI, original) import Data.Conduit import Data.Conduit.Binary (sinkHandle, sourceLbs) import Network.HTTP.Conduit import Network.HTTP.Types import System.IO (IOMode (..), hClose, openFile) main :: IO () main = do withManager $ liftIO . sampleViaHttpConduit sampleViaHttpConduit :: Manager -> IO () sampleViaHttpConduit manager = do runResourceT $ do req <- parseUrl "http://localhost/" let req2 = req { checkStatus = \_ _ _ -> Nothing, requestHeaders = [(hAccept, "text/html")], responseTimeout = Nothing } res <- http req2 manager let sta = responseStatus res ver = responseVersion res hdr = responseHeaders res handle <- liftIO $ openFile "/tmp/http-conduit.out" WriteMode let src = do sourceLbs (joinStatus sta ver) sourceLbs (join hdr) src $$ sinkHandle handle responseBody res $$+- sinkHandle handle liftIO $ hClose handle joinStatus :: Status -> HttpVersion -> L.ByteString joinStatus sta ver = L.concat $ map L.pack [ show ver, " " , show $ statusCode sta, " " , S.unpack $ statusMessage sta , "\n" ] -- -- Process headers into a single string -- join :: ResponseHeaders -> L.ByteString join m = foldr combineHeaders "" m combineHeaders :: (CI S.ByteString, S.ByteString) -> L.ByteString -> L.ByteString combineHeaders (k,v) acc = L.append acc $ L.fromChunks [key, ": ", value, "\n"] where key = original k value = v
afcowie/pipes-http
tests/ConduitSample.hs
Haskell
bsd-3-clause
2,161
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-} module Tests.Test.HUnitPlus.Execution where import Control.Exception(Exception, throwIO) import Data.List import Data.HashMap.Strict(HashMap) import Data.Maybe import Data.Typeable import Distribution.TestSuite import Test.HUnitPlus.Base import Test.HUnitPlus.Execution import Test.HUnitPlus.Filter import Test.HUnitPlus.Reporting import qualified Data.HashSet as HashSet import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Strict data ReportEvent = EndEvent Counts | StartSuiteEvent State | EndSuiteEvent State | StartCaseEvent State | EndCaseEvent State | SkipEvent State | ProgressEvent Strict.Text State | FailureEvent Strict.Text State | ErrorEvent Strict.Text State | SystemErrEvent Strict.Text State | SystemOutEvent Strict.Text State deriving (Eq, Show) fullLoggingReporter :: Reporter [ReportEvent] fullLoggingReporter = defaultReporter { reporterStart = return [], reporterEnd = \_ ss events -> return $ (EndEvent ss :events), reporterStartSuite = \ss events -> return $ (StartSuiteEvent ss : events), reporterEndSuite = \_ ss events -> return $ (EndSuiteEvent ss : events), reporterStartCase = \ss events -> return $ (StartCaseEvent ss : events), reporterEndCase = \_ ss events -> return $ (EndCaseEvent ss : events), reporterSkipCase = \ss events -> return $ (SkipEvent ss : events), reporterCaseProgress = \msg ss events -> return $ (ProgressEvent msg ss : events), reporterFailure = \msg ss events -> return $ (FailureEvent msg ss : events), reporterError = \msg ss events -> return $ (ErrorEvent msg ss : events), reporterSystemErr = \msg ss events -> return $ (SystemErrEvent msg ss : events), reporterSystemOut = \msg ss events -> return $ (SystemOutEvent msg ss : events) } makeTagName False False = "no_tag" makeTagName True False = "tag1" makeTagName False True = "tag2" makeTagName True True = "tag12" makeTagSet (False, False) = HashSet.empty makeTagSet (True, False) = HashSet.singleton "tag1" makeTagSet (False, True) = HashSet.singleton "tag2" makeTagSet (True, True) = HashSet.fromList ["tag1", "tag2"] data TestException = TestException deriving (Show, Typeable) instance Exception TestException data Behavior = Normal Result | Exception makeResName (Normal Pass) = "pass" makeResName (Normal (Fail _)) = "fail" makeResName (Normal (Error _)) = "error" makeResName Exception = "exception" makeAssert (Normal Pass) = assertSuccess makeAssert (Normal (Fail msg)) = assertFailure (Strict.pack msg) makeAssert (Normal (Error msg)) = abortError (Strict.pack msg) makeAssert Exception = throwIO TestException updateCounts (Normal Pass) c @ Counts { cAsserts = asserts } = c { cAsserts = asserts + 1, cCaseAsserts = 1 } updateCounts (Normal (Fail _)) c @ Counts { cFailures = fails, cAsserts = asserts } = c { cFailures = fails + 1, cAsserts = asserts + 1, cCaseAsserts = 1 } updateCounts (Normal (Error _)) c @ Counts { cErrors = errors } = c { cErrors = errors + 1, cCaseAsserts = 0 } updateCounts Exception c @ Counts { cErrors = errors } = c { cErrors = errors + 1, cCaseAsserts = 0 } makeName :: (Bool, Bool, Behavior) -> Strict.Text makeName (tag1, tag2, res) = Strict.concat [makeTagName tag1 tag2, "_", makeResName res] makeTest :: String -> (Bool, Bool, Behavior) -> Test makeTest prefix tdata @ (tag1, tag2, res) = let inittags = if tag1 then ["tag1"] else [] tags = if tag2 then "tag2" : inittags else inittags testname = prefix ++ (Strict.unpack (makeName tdata)) in testNameTags testname tags (makeAssert res) {- testInstance = TestInstance { name = testname, tags = tags, setOption = (\_ _ -> Right testInstance), options = [], run = runTest } in Test testInstance -} makeTestData :: String -> ([Test], [ReportEvent], State) -> Either (Bool, Bool, Behavior) (Bool, Bool, Behavior) -> ([Test], [ReportEvent], State) makeTestData prefix (tests, events, ss @ State { stName = oldname, stCounts = counts @ Counts { cCases = cases, cTried = tried } }) (Right tdata @ (tag1, tag2, res)) = let startedCounts = counts { cCases = cases + 1, cTried = tried + 1 } finishedCounts = updateCounts res startedCounts ssWithName = ss { stName = Strict.concat [Strict.pack prefix, makeName tdata] } ssStarted = ssWithName { stCounts = startedCounts } ssFinished = ssWithName { stCounts = finishedCounts } -- Remember, the order is reversed for these, because we reverse -- the events list in the end. newevents = case res of Normal Pass -> EndCaseEvent ssFinished : StartCaseEvent ssStarted : events Normal (Fail msg) -> EndCaseEvent ssFinished : FailureEvent (Strict.pack msg) ssStarted : StartCaseEvent ssStarted : events Normal (Error msg) -> EndCaseEvent ssFinished : ErrorEvent (Strict.pack msg) ssStarted : StartCaseEvent ssStarted : events Exception -> EndCaseEvent ssFinished : ErrorEvent "Uncaught exception in test: TestException" ssStarted : StartCaseEvent ssStarted : events in (makeTest prefix tdata : tests, newevents, ssFinished { stName = oldname }) makeTestData prefix (tests, events, ss @ State { stCounts = c @ Counts { cSkipped = skipped, cCases = cases }, stName = oldname }) (Left tdata) = let newcounts = c { cCases = cases + 1, cSkipped = skipped + 1 } newstate = ss { stCounts = newcounts, stName = Strict.concat [Strict.pack prefix, makeName tdata] } in (makeTest prefix tdata : tests, SkipEvent newstate : events, newstate { stName = oldname }) resultVals :: [Behavior] resultVals = [Normal Pass, Normal (Fail "Fail Message"), Normal (Error "Error Message"), Exception] tagVals :: [Bool] tagVals = [True, False] testData :: [(Bool, Bool, Behavior)] testData = foldl (\accum tag1 -> foldl (\accum tag2 -> foldl (\accum res -> (tag1, tag2, res) : accum) accum resultVals) accum tagVals) [] tagVals tag1Filter tdata @ (True, _, _) = Right tdata tag1Filter tdata = Left tdata tag2Filter tdata @ (_, True, _) = Right tdata tag2Filter tdata = Left tdata tag12Filter tdata @ (True, _, _) = Right tdata tag12Filter tdata @ (_, True, _) = Right tdata tag12Filter tdata = Left tdata data ModFilter = All | WithTags (Bool, Bool) | None deriving Show getTests :: ModFilter -> [Either (Bool, Bool, Behavior) (Bool, Bool, Behavior)] getTests All = map Right testData getTests (WithTags (True, False)) = map tag1Filter testData getTests (WithTags (False, True)) = map tag2Filter testData getTests (WithTags (True, True)) = map tag12Filter testData getTests None = map Left testData -- Generate a list of all mod filters we can use for a sub-module, and -- the selectors we need for them getSuperSet :: (Selector -> Selector) -> ModFilter -> [(ModFilter, Selector, Bool)] -- If we're already running all tests, there's nothing else we can do getSuperSet wrapinner All = [(All, wrapinner (allSelector { selectorTags = Nothing }), False)] -- If we're running tests with both tags, we can do that, or we can -- run all tests in the submodule. getSuperSet wrapinner (WithTags (True, True)) = [(WithTags (True, True), wrapinner (allSelector { selectorTags = Nothing }), False), (All, wrapinner allSelector, True)] -- If we're running tests with one of the tags, we can do that, or we -- can run with both tags, or we can run all tests. getSuperSet wrapinner (WithTags (False, True)) = [(WithTags (False, True), wrapinner (allSelector { selectorTags = Nothing }), False), (WithTags (True, True), wrapinner (allSelector { selectorTags = Just $! HashSet.fromList ["tag1", "tag2" ] }), True), (All, wrapinner allSelector, True) ] getSuperSet wrapinner (WithTags (True, False)) = [(WithTags (True, False), wrapinner (allSelector { selectorTags = Nothing }), False), (WithTags (True, True), wrapinner (allSelector { selectorTags = Just $! HashSet.fromList ["tag1", "tag2" ] }), True), (All, wrapinner allSelector, True) ] -- If we're not running any tests, we can do anything getSuperSet wrapinner None = [(None, wrapinner (allSelector { selectorTags = Nothing }), False), (WithTags (True, False), wrapinner (allSelector { selectorTags = Just $! HashSet.singleton "tag1" }), True), (WithTags (False, True), wrapinner (allSelector { selectorTags = Just $! HashSet.singleton "tag2" }), True), (WithTags (True, True), wrapinner (allSelector { selectorTags = Just $! HashSet.fromList ["tag1", "tag2" ] }), True), (All, wrapinner allSelector, True) ] -- Make the tests for a group, with a starting modfilter makeLeafGroup :: String -> (Selector -> Selector) -> ModFilter -> ([Test], [ReportEvent], State, [Selector]) -> [([Test], [ReportEvent], State, [Selector])] makeLeafGroup gname wrapinner mfilter initialTests = let mapfun :: ([Test], [ReportEvent], State, [Selector]) -> (ModFilter, Selector, Bool) -> ([Test], [ReportEvent], State, [Selector]) mapfun (tests, events, ss @ State { stPath = oldpath }, selectors) (mfilter, selector, valid) = let ssWithPath = ss { stPath = Label (Strict.pack gname) : oldpath } (grouptests, events', ss') = foldl (makeTestData (gname ++ "_")) ([], events, ssWithPath) (getTests mfilter) tests' = Group { groupName = gname, groupTests = reverse grouptests, concurrently = True } : tests in if valid then (tests', events', ss' { stPath = oldpath }, selector : selectors) else (tests', events', ss' { stPath = oldpath }, selectors) in map (mapfun initialTests) (getSuperSet wrapinner mfilter) makeOuterGroup :: ModFilter -> ([Test], [ReportEvent], State, [Selector]) -> [([Test], [ReportEvent], State, [Selector])] makeOuterGroup mfilter initialTests = let wrapOuterPath inner = Selector { selectorInners = HashMap.singleton "Outer" inner, selectorTags = Nothing } mapfun :: ([Test], [ReportEvent], State, [Selector]) -> (ModFilter, Selector, Bool) -> [([Test], [ReportEvent], State, [Selector])] mapfun (tests, events, ss @ State { stPath = oldpath }, selectors) (mfilter, selector, valid) = let ssWithPath = ss { stPath = Label "Outer" : oldpath } mapfun :: ([Test], [ReportEvent], State, [Selector]) -> ([Test], [ReportEvent], State, [Selector]) mapfun (innergroup : tests, events, ss, selectors) = let (grouptests, events', ss') = foldl (makeTestData "Outer_") ([innergroup], events, ss) (getTests mfilter) tests' = Group { groupName = "Outer", groupTests = reverse grouptests, concurrently = True } : tests in if valid then (tests', events', ss' { stPath = oldpath }, selector : selectors) else (tests', events', ss' { stPath = oldpath }, selectors) wrapInnerPath inner = Selector { selectorInners = HashMap.singleton "Outer" Selector { selectorInners = HashMap.singleton "Inner" inner, selectorTags = Nothing }, selectorTags = Nothing } withInner :: [([Test], [ReportEvent], State, [Selector])] withInner = makeLeafGroup "Inner" wrapInnerPath mfilter (tests, events, ssWithPath, selectors) in map mapfun withInner in concatMap (mapfun initialTests) (getSuperSet wrapOuterPath mfilter) modfilters = [ All, WithTags (True, False), WithTags (False, True), WithTags (True, True), None ] genFilter :: Strict.Text -> [(TestSuite, [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector), Counts)] genFilter sname = let -- Take a root ModFilter and an initial (suite list, event list, -- selectors). We generate a stock suite, derive a selector from -- the root ModFilter, and produce a list of possible (suite list, -- event list, selectors)'s, one for each possibility. suiteTestInst :: ModFilter -> [(TestSuite, [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector), Counts)] suiteTestInst mfilter = let -- Initial state for a filter initState = State { stCounts = zeroCounts, stName = sname, stPath = [], stOptions = HashMap.empty, stOptionDescs = [] } -- The selectors for the root set rootSelectors :: [Selector] rootSelectors = case mfilter of All -> [allSelector] WithTags tags -> [allSelector { selectorTags = Just $! makeTagSet tags }] None -> [] -- Result after executing the root tests. (rootTests, rootEvents, rootState) = foldl (makeTestData "") ([], [StartSuiteEvent initState], initState) (getTests mfilter) wrapOtherPath inner = Selector { selectorInners = HashMap.singleton "Other" inner, selectorTags = Nothing } -- Results after executing tests in the Other module withOther :: [([Test], [ReportEvent], State, [Selector])] withOther = makeLeafGroup "Other" wrapOtherPath mfilter (rootTests, rootEvents, rootState, rootSelectors) finalData = concatMap (makeOuterGroup mfilter) withOther -- Wrap up a test list, end state, and selector list into a -- test suite and a filter. Also add the EndSuite event to -- the events list. buildSuite :: ([Test], [ReportEvent], State, [Selector]) -> (TestSuite, [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector), Counts) buildSuite (tests, _, _, []) = let suite = TestSuite { suiteName = sname, suiteTests = reverse tests, suiteConcurrently = True, suiteOptions = [] } in (suite, [], HashMap.empty, zeroCounts) buildSuite (tests, events, state @ State { stCounts = counts }, selectors) = let -- Build the test suite out of the name and test list, add -- it to the list of suites. suite = TestSuite { suiteName = sname, suiteTests = reverse tests, suiteConcurrently = True, suiteOptions = [] } -- Add an end suite event eventsWithEnd = EndSuiteEvent state : events -- Add an entry for this suite to the selector map selectormap :: HashMap Strict.Text (HashMap OptionMap Selector) selectormap = case selectors of [one] -> let optmap = HashMap.singleton HashMap.empty one in HashMap.singleton sname optmap _ -> let combined = foldl1 combineSelectors selectors optmap = HashMap.singleton HashMap.empty combined in HashMap.singleton sname optmap in (suite, reverse eventsWithEnd, selectormap, counts) in map buildSuite finalData in -- Create test data for this suite with all possible modfilters, -- and add it to the existing list of test instances. concatMap suiteTestInst modfilters suite1Data :: [(TestSuite, [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector), Counts)] suite1Data = genFilter "Suite1" suite2Data :: [(TestSuite, [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector), Counts)] suite2Data = genFilter "Suite2" combineSuites :: (TestSuite, [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector), Counts) -> (TestSuite, [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector), Counts) -> ([TestSuite], [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector)) combineSuites (suite1, events1, selectormap1, Counts { cAsserts = asserts1, cCases = cases1, cErrors = errors1, cFailures = failures1, cSkipped = skipped1, cTried = tried1 }) (suite2, events2, selectormap2, counts2) = let bumpCounts (EndEvent c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 }) = EndEvent c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } bumpCounts (StartSuiteEvent s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = StartSuiteEvent s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } bumpCounts (EndSuiteEvent s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = EndSuiteEvent s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } bumpCounts (StartCaseEvent s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = StartCaseEvent s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } bumpCounts (EndCaseEvent s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = EndCaseEvent s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } bumpCounts (SkipEvent s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = SkipEvent s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } bumpCounts (ProgressEvent msg s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = ProgressEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } bumpCounts (FailureEvent msg s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = FailureEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } bumpCounts (ErrorEvent msg s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = ErrorEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } bumpCounts (SystemErrEvent msg s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = SystemErrEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } bumpCounts (SystemOutEvent msg s @ State { stCounts = c @ Counts { cAsserts = asserts2, cCases = cases2, cErrors = errors2, cFailures = failures2, cSkipped = skipped2, cTried = tried2 } }) = SystemOutEvent msg s { stCounts = c { cAsserts = asserts1 + asserts2, cErrors = errors1 + errors2, cCases = cases1 + cases2, cFailures = failures1 + failures2, cSkipped = skipped1 + skipped2, cTried = tried1 + tried2 } } suites = [suite1, suite2] events = events1 ++ map bumpCounts events2 ++ [bumpCounts (EndEvent counts2 { cCaseAsserts = 0 })] selectormap = HashMap.union selectormap1 selectormap2 in (suites, events, selectormap) suiteData :: [([TestSuite], [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector))] suiteData = foldl (\accum suite1 -> foldl (\accum suite2 -> (combineSuites suite1 suite2) : accum) accum suite2Data) [] suite1Data makeExecutionTest :: ([TestSuite], [ReportEvent], HashMap Strict.Text (HashMap OptionMap Selector)) -> (Int, [Test]) -> (Int, [Test]) makeExecutionTest (suites, expected, selectors) (index, tests) = let format events = intercalate "\n" (map show events) selectorStrs = intercalate "\n" (map (\(suite, selector) -> "[" ++ Strict.unpack suite ++ "]" ++ show selector) (HashMap.toList selectors)) compstate State { stName = name1, stPath = path1, stCounts = counts1, stOptionDescs = descs1 } State { stName = name2, stPath = path2, stCounts = counts2, stOptionDescs = descs2 } = name1 == name2 && path1 == path2 && counts1 == counts2 && descs1 == descs2 comp (EndEvent counts1) (EndEvent counts2) = counts1 == counts2 comp (StartSuiteEvent st1) (StartSuiteEvent st2) = compstate st1 st2 comp (EndSuiteEvent st1) (EndSuiteEvent st2) = compstate st1 st2 comp (StartCaseEvent st1) (StartCaseEvent st2) = compstate st1 st2 comp (EndCaseEvent st1) (EndCaseEvent st2) = compstate st1 st2 comp (SkipEvent st1) (SkipEvent st2) = compstate st1 st2 comp (ProgressEvent msg1 st1) (ProgressEvent msg2 st2) = msg1 == msg2 && compstate st1 st2 comp (FailureEvent msg1 st1) (FailureEvent msg2 st2) = msg1 == msg2 && compstate st1 st2 comp (ErrorEvent msg1 st1) (ErrorEvent msg2 st2) = msg1 == msg2 && compstate st1 st2 comp (SystemErrEvent msg1 st1) (SystemErrEvent msg2 st2) = msg1 == msg2 && compstate st1 st2 comp (SystemOutEvent msg1 st1) (SystemOutEvent msg2 st2) = msg1 == msg2 && compstate st1 st2 comp _ _ = False check (e : expecteds) (a : actuals) | comp e a = check expecteds actuals | otherwise = return (Finished (Fail ("Selectors\n" ++ selectorStrs ++ "\nExpected\n************************\n" ++ show e ++ "\nbut got\n************************\n" ++ show a))) check [] [] = return (Finished Pass) check expected [] = return (Finished (Fail ("Missing output:\n" ++ format expected))) check [] actual = return (Finished (Fail ("Extra output:\n" ++ format actual))) runTest = do (_, actual) <- performTestSuites fullLoggingReporter selectors suites check expected (reverse actual) testInstance = TestInstance { name = "execution_test_" ++ show index, tags = [], options = [], run = runTest, setOption = (\_ _ -> Right testInstance) } in (index + 1, Test testInstance : tests) tests :: Test tests = testGroup "Execution" (snd (foldr makeExecutionTest (0, []) suiteData))
emc2/HUnit-Plus
test/Tests/Test/HUnitPlus/Execution.hs
Haskell
bsd-3-clause
31,830
-- | -- Module : -- License : BSD-Style -- Maintainer : Nicolas DI PRIMA <[email protected]> -- Stability : experimental -- Portability : unknown -- {-# LANGUAGE OverloadedStrings #-} module Main (main) where import Control.Monad (when) import Data.List (intercalate) import Network.SMTP import System.Environment main :: IO () main = do args <- getArgs case args of [] -> usage (Just "need at least sender and recipient email address") ["help"] -> usage Nothing "verify":fromStr:rcptStr:[] -> mainVerify fromStr rcptStr >>= putStrLn . prettyPrintResult " " _ -> usage (Just $ "unrecognized options: " ++ intercalate " " args) mainVerify :: String -> String -> IO (Result ()) mainVerify fromStr rcptStr = executeSMTP $ do mxs <- lookupMXs (domainpart rcpt) case mxs of [] -> fail "no MX server for the given recipient" (mx:_) -> do con <- openSMTPConnection (mxAddress mx) 25 (domainpart from) mailFrom con from bool <- rcptTo con rcpt when (not bool) $ fail $ "cannot send email to " ++ rcptStr closeSMTPConnection con where from :: EmailAddress from = either error id $ emailAddrFromString fromStr rcpt :: EmailAddress rcpt = either error id $ emailAddrFromString rcptStr usage :: Maybe String -> IO () usage mMsg = printUsage $ intercalate "\n" [ maybe "SMTP Client Command Line interface" ((++) "Error: ") mMsg , "" , "available options:" , " help: show this help message" ] where printUsage :: String -> IO () printUsage = case mMsg of Nothing -> putStrLn Just _ -> error
NicolasDP/hs-smtp
cli/Main.hs
Haskell
bsd-3-clause
1,713
{-# LANGUAGE MultiParamTypeClasses #-} module Lambda.Convertor.Expr where import DeepControl.Applicative import DeepControl.Monad hiding (forM, mapM) import Lambda.DataType (Lambda) import Lambda.DataType.Expr import Lambda.Action import Lambda.Convertor.PatternMatch import Util.Pseudo import Prelude hiding (forM, mapM) import Data.Monoid import Data.Foldable import Data.Traversable instance PseudoFunctor Expr where pdfmap f (LAM p x msp) = LAM p (f x) msp pdfmap f (LAMM p x msp) = LAMM p (f x) msp pdfmap f (FIX x msp) = FIX (f x) msp pdfmap f (APP x1 x2 msp) = APP (f x1) (f x2) msp pdfmap f (APPSeq xs msp) = APPSeq (f |$> xs) msp -- gadget pdfmap f (SYN g msp) = SYN (fmap f g) msp pdfmap f (SEN g msp) = SEN (fmap f g) msp pdfmap f (QUT g msp) = QUT (fmap f g) msp pdfmap f (LIST g msp) = LIST (fmap f g) msp pdfmap f (TPL g msp) = TPL (fmap f g) msp pdfmap f (TAG g msp) = TAG (fmap f g) msp -- pdfmap f (THUNK t) = THUNK (f t) pdfmap _ x = x instance PseudoFoldable Expr where pdfoldMap f (LAM p x _) = f x pdfoldMap f (LAMM p x _) = f x pdfoldMap f (FIX x _) = f x pdfoldMap f (APP x1 x2 _) = f x1 <> f x2 pdfoldMap f (APPSeq xs _) = fold $ f |$> xs -- gadget pdfoldMap f (SYN g _) = foldMap f g pdfoldMap f (SEN g _) = foldMap f g pdfoldMap f (QUT g _) = foldMap f g pdfoldMap f (LIST g _) = foldMap f g pdfoldMap f (TPL g _) = foldMap f g pdfoldMap f (TAG g _) = foldMap f g -- pdfoldMap f (THUNK t) = f t pdfoldMap f x = f x instance PseudoTraversable Lambda Expr where pdmapM f (LAM p x msp) = localMSPBy msp $ LAM p |$> localLAMPush p (f x) |* msp pdmapM f (LAMM p x msp) = localMSPBy msp $ LAMM p |$> localLAMPush p (f x) |* msp pdmapM f (FIX x msp) = localMSPBy msp $ FIX |$> f x |* msp pdmapM f (APP x1 x2 msp) = localMSPBy msp $ APP |$> f x1 |*> f x2 |* msp pdmapM f (APPSeq xs msp) = localMSPBy msp $ APPSeq |$> mapM f xs |* msp -- gadget pdmapM f (SYN g msp) = localMSPBy msp $ SYN |$> mapM f g |* msp pdmapM f (SEN g msp) = localMSPBy msp $ SEN |$> mapM f g |* msp pdmapM f (QUT g msp) = localMSPBy msp $ QUT |$> mapM f g |* msp pdmapM f (LIST g msp) = localMSPBy msp $ LIST |$> mapM f g |* msp pdmapM f (TPL g msp) = localMSPBy msp $ TPL |$> mapM f g |* msp pdmapM f (TAG g msp) = localMSPBy msp $ TAG |$> mapM f g |* msp -- pdmapM f (THUNK t) = THUNK |$> f t pdmapM _ x = (*:) x
ocean0yohsuke/Simply-Typed-Lambda
src/Lambda/Convertor/Expr.hs
Haskell
bsd-3-clause
2,635
module Parser.ParseModule (parseModule) where import Parser.Parse import Parser.Syntax import Parser.ParseSpace import Parser.ParseDec import Parser.ParseIdent parseImportSome :: Parse Char ImportTermination parseImportSome = fmap ImportSome $ ksingleOrParenthesized parseLocalIdent parseImportAll :: Parse Char ImportTermination parseImportAll = lit '*' >> return ImportAll parseImportTermination :: Parse Char ImportTermination parseImportTermination = parseEither parseImportSome parseImportAll parseImportPath :: Parse Char ImportPath parseImportPath = greedy $ do initPath <- many $ do name <- parseLocalIdent optional kspace lits "::" optional kspace return name term <- parseImportTermination return $ ImportPath initPath term parseImport :: Parse Char ImportPath parseImport = greedy $ do lits "import" kspace path <- parseImportPath ksemicolon return path parseModule :: Parse Char Module parseModule = greedy $ do optional kspace toImport <- many $ do -- not named "imports" because ST2 highlights that weirdly... path <- parseImport optional kspace return path decs <- many $ do dec <- parseDec optional kspace return dec return $ Module toImport decs
Kiwi-Labs/kwirc
kwick/parser/ParseModule.hs
Haskell
mit
1,205
{-# LANGUAGE DeriveGeneric #-} module Course where import qualified Data.Text as T import Data.Aeson import GHC.Generics data Course = Course !T.Text deriving (Show, Generic) instance FromJSON Course
ksaveljev/udemy-downloader
Course.hs
Haskell
mit
204
-- | -- Module : Example.Time.Compat -- License : BSD-style -- Maintainer : Nicolas DI PRIMA <[email protected]> -- -- This file is an example on how to use the Data.Hourglass.Compat -- module to transpose a ZonedTime (from time) into a LocalTime of DateTime -- (from hourglass). -- module Example.Time.Compat ( transpose ) where import Data.Hourglass as H import Data.Hourglass.Compat as C import Data.Time as T transpose :: T.ZonedTime -> H.LocalTime H.DateTime transpose oldTime = H.localTime offsetTime (H.DateTime newDate timeofday) where (T.ZonedTime (T.LocalTime day tod) (T.TimeZone tzmin _ _)) = oldTime newDate :: H.Date newDate = C.dateFromTAIEpoch $ T.toModifiedJulianDay day timeofday :: H.TimeOfDay timeofday = C.diffTimeToTimeOfDay $ toRational $ T.timeOfDayToTime tod offsetTime = H.TimezoneOffset $ fromIntegral tzmin
ppelleti/hs-hourglass
Example/Time/Compat.hs
Haskell
bsd-3-clause
935
{- ------------------------------------------------------------------------ (c) The GHC Team, 1992-2012 DeriveConstants is a program that extracts information from the C declarations in the header files (primarily struct field offsets) and generates various files, such as a header file that can be #included into non-C source containing this information. ------------------------------------------------------------------------ -} import Control.Monad import Data.Bits import Data.Char import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Numeric import System.Environment import System.Exit import System.FilePath import System.IO import System.Info import System.Process main :: IO () main = do opts <- parseArgs let getOption descr opt = case opt opts of Just x -> return x Nothing -> die ("No " ++ descr ++ " given") mode <- getOption "mode" o_mode fn <- getOption "output filename" o_outputFilename case mode of Gen_Haskell_Type -> writeHaskellType fn haskellWanteds Gen_Haskell_Wrappers -> writeHaskellWrappers fn haskellWanteds Gen_Haskell_Exports -> writeHaskellExports fn haskellWanteds Gen_Computed cm -> do tmpdir <- getOption "tmpdir" o_tmpdir gccProg <- getOption "gcc program" o_gccProg nmProg <- getOption "nm program" o_nmProg let verbose = o_verbose opts gccFlags = o_gccFlags opts rs <- getWanted verbose tmpdir gccProg gccFlags nmProg let haskellRs = [ what | (wh, what) <- rs , wh `elem` [Haskell, Both] ] cRs = [ what | (wh, what) <- rs , wh `elem` [C, Both] ] case cm of ComputeHaskell -> writeHaskellValue fn haskellRs ComputeHeader -> writeHeader fn cRs where haskellWanteds = [ what | (wh, what) <- wanteds, wh `elem` [Haskell, Both] ] data Options = Options { o_verbose :: Bool, o_mode :: Maybe Mode, o_tmpdir :: Maybe FilePath, o_outputFilename :: Maybe FilePath, o_gccProg :: Maybe FilePath, o_gccFlags :: [String], o_nmProg :: Maybe FilePath } parseArgs :: IO Options parseArgs = do args <- getArgs opts <- f emptyOptions args return (opts {o_gccFlags = reverse (o_gccFlags opts)}) where emptyOptions = Options { o_verbose = False, o_mode = Nothing, o_tmpdir = Nothing, o_outputFilename = Nothing, o_gccProg = Nothing, o_gccFlags = [], o_nmProg = Nothing } f opts [] = return opts f opts ("-v" : args') = f (opts {o_verbose = True}) args' f opts ("--gen-haskell-type" : args') = f (opts {o_mode = Just Gen_Haskell_Type}) args' f opts ("--gen-haskell-value" : args') = f (opts {o_mode = Just (Gen_Computed ComputeHaskell)}) args' f opts ("--gen-haskell-wrappers" : args') = f (opts {o_mode = Just Gen_Haskell_Wrappers}) args' f opts ("--gen-haskell-exports" : args') = f (opts {o_mode = Just Gen_Haskell_Exports}) args' f opts ("--gen-header" : args') = f (opts {o_mode = Just (Gen_Computed ComputeHeader)}) args' f opts ("--tmpdir" : dir : args') = f (opts {o_tmpdir = Just dir}) args' f opts ("-o" : fn : args') = f (opts {o_outputFilename = Just fn}) args' f opts ("--gcc-program" : prog : args') = f (opts {o_gccProg = Just prog}) args' f opts ("--gcc-flag" : flag : args') = f (opts {o_gccFlags = flag : o_gccFlags opts}) args' f opts ("--nm-program" : prog : args') = f (opts {o_nmProg = Just prog}) args' f _ (flag : _) = die ("Unrecognised flag: " ++ show flag) data Mode = Gen_Haskell_Type | Gen_Haskell_Wrappers | Gen_Haskell_Exports | Gen_Computed ComputeMode data ComputeMode = ComputeHaskell | ComputeHeader type Wanteds = [(Where, What Fst)] type Results = [(Where, What Snd)] type Name = String newtype CExpr = CExpr String newtype CPPExpr = CPPExpr String data What f = GetFieldType Name (f CExpr Integer) | GetClosureSize Name (f CExpr Integer) | GetWord Name (f CExpr Integer) | GetInt Name (f CExpr Integer) | GetNatural Name (f CExpr Integer) | GetBool Name (f CPPExpr Bool) | StructFieldMacro Name | ClosureFieldMacro Name | ClosurePayloadMacro Name | FieldTypeGcptrMacro Name data Fst a b = Fst a data Snd a b = Snd b data Where = C | Haskell | Both deriving Eq constantInt :: Where -> Name -> String -> Wanteds constantInt w name expr = [(w, GetInt name (Fst (CExpr expr)))] constantWord :: Where -> Name -> String -> Wanteds constantWord w name expr = [(w, GetWord name (Fst (CExpr expr)))] constantNatural :: Where -> Name -> String -> Wanteds constantNatural w name expr = [(w, GetNatural name (Fst (CExpr expr)))] constantBool :: Where -> Name -> String -> Wanteds constantBool w name expr = [(w, GetBool name (Fst (CPPExpr expr)))] fieldOffset :: Where -> String -> String -> Wanteds fieldOffset w theType theField = fieldOffset_ w nameBase theType theField where nameBase = theType ++ "_" ++ theField fieldOffset_ :: Where -> Name -> String -> String -> Wanteds fieldOffset_ w nameBase theType theField = [(w, GetWord name (Fst (CExpr expr)))] where name = "OFFSET_" ++ nameBase expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ")" -- FieldType is for defining REP_x to be b32 etc -- These are both the C-- types used in a load -- e.g. b32[addr] -- and the names of the CmmTypes in the compiler -- b32 :: CmmType fieldType' :: Where -> String -> String -> Wanteds fieldType' w theType theField = fieldType_' w nameBase theType theField where nameBase = theType ++ "_" ++ theField fieldType_' :: Where -> Name -> String -> String -> Wanteds fieldType_' w nameBase theType theField = [(w, GetFieldType name (Fst (CExpr expr)))] where name = "REP_" ++ nameBase expr = "FIELD_SIZE(" ++ theType ++ ", " ++ theField ++ ")" structField :: Where -> String -> String -> Wanteds structField = structFieldHelper C structFieldH :: Where -> String -> String -> Wanteds structFieldH w = structFieldHelper w w structField_ :: Where -> Name -> String -> String -> Wanteds structField_ w nameBase theType theField = fieldOffset_ w nameBase theType theField ++ fieldType_' C nameBase theType theField ++ structFieldMacro nameBase structFieldMacro :: Name -> Wanteds structFieldMacro nameBase = [(C, StructFieldMacro nameBase)] -- Outputs the byte offset and MachRep for a field structFieldHelper :: Where -> Where -> String -> String -> Wanteds structFieldHelper wFT w theType theField = fieldOffset w theType theField ++ fieldType' wFT theType theField ++ structFieldMacro nameBase where nameBase = theType ++ "_" ++ theField closureFieldMacro :: Name -> Wanteds closureFieldMacro nameBase = [(C, ClosureFieldMacro nameBase)] closurePayload :: Where -> String -> String -> Wanteds closurePayload w theType theField = closureFieldOffset_ w nameBase theType theField ++ closurePayloadMacro nameBase where nameBase = theType ++ "_" ++ theField closurePayloadMacro :: Name -> Wanteds closurePayloadMacro nameBase = [(C, ClosurePayloadMacro nameBase)] -- Byte offset and MachRep for a closure field, minus the header closureField_ :: Where -> Name -> String -> String -> Wanteds closureField_ w nameBase theType theField = closureFieldOffset_ w nameBase theType theField ++ fieldType_' C nameBase theType theField ++ closureFieldMacro nameBase closureField :: Where -> String -> String -> Wanteds closureField w theType theField = closureField_ w nameBase theType theField where nameBase = theType ++ "_" ++ theField closureFieldOffset_ :: Where -> Name -> String -> String -> Wanteds closureFieldOffset_ w nameBase theType theField = defOffset w nameBase (CExpr ("offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)")) -- Size of a closure type, minus the header, named SIZEOF_<type>_NoHdr -- Also, we #define SIZEOF_<type> to be the size of the whole closure for .cmm. closureSize :: Where -> String -> Wanteds closureSize w theType = defSize w (theType ++ "_NoHdr") (CExpr expr) ++ defClosureSize C theType (CExpr expr) where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgHeader)" -- Byte offset and MachRep for a closure field, minus the header closureFieldGcptr :: Where -> String -> String -> Wanteds closureFieldGcptr w theType theField = closureFieldOffset_ w nameBase theType theField ++ fieldTypeGcptr nameBase ++ closureFieldMacro nameBase where nameBase = theType ++ "_" ++ theField fieldTypeGcptr :: Name -> Wanteds fieldTypeGcptr nameBase = [(C, FieldTypeGcptrMacro nameBase)] closureFieldOffset :: Where -> String -> String -> Wanteds closureFieldOffset w theType theField = defOffset w nameBase (CExpr expr) where nameBase = theType ++ "_" ++ theField expr = "offsetof(" ++ theType ++ ", " ++ theField ++ ") - TYPE_SIZE(StgHeader)" thunkSize :: Where -> String -> Wanteds thunkSize w theType = defSize w (theType ++ "_NoThunkHdr") (CExpr expr) ++ closureSize w theType where expr = "TYPE_SIZE(" ++ theType ++ ") - TYPE_SIZE(StgThunkHeader)" defIntOffset :: Where -> Name -> String -> Wanteds defIntOffset w nameBase cExpr = [(w, GetInt ("OFFSET_" ++ nameBase) (Fst (CExpr cExpr)))] defOffset :: Where -> Name -> CExpr -> Wanteds defOffset w nameBase cExpr = [(w, GetWord ("OFFSET_" ++ nameBase) (Fst cExpr))] structSize :: Where -> String -> Wanteds structSize w theType = defSize w theType (CExpr ("TYPE_SIZE(" ++ theType ++ ")")) defSize :: Where -> Name -> CExpr -> Wanteds defSize w nameBase cExpr = [(w, GetWord ("SIZEOF_" ++ nameBase) (Fst cExpr))] defClosureSize :: Where -> Name -> CExpr -> Wanteds defClosureSize w nameBase cExpr = [(w, GetClosureSize ("SIZEOF_" ++ nameBase) (Fst cExpr))] haskellise :: Name -> Name haskellise (c : cs) = toLower c : cs haskellise "" = "" wanteds :: Wanteds wanteds = concat [-- Closure header sizes. constantWord Both "STD_HDR_SIZE" -- grrr.. PROFILING is on so we need to -- subtract sizeofW(StgProfHeader) "sizeofW(StgHeader) - sizeofW(StgProfHeader)" ,constantWord Both "PROF_HDR_SIZE" "sizeofW(StgProfHeader)" -- Size of a storage manager block (in bytes). ,constantWord Both "BLOCK_SIZE" "BLOCK_SIZE" ,constantWord C "MBLOCK_SIZE" "MBLOCK_SIZE" -- blocks that fit in an MBlock, leaving space for the block -- descriptors ,constantWord Both "BLOCKS_PER_MBLOCK" "BLOCKS_PER_MBLOCK" -- could be derived, but better to save doing the calculation twice ,fieldOffset Both "StgRegTable" "rR1" ,fieldOffset Both "StgRegTable" "rR2" ,fieldOffset Both "StgRegTable" "rR3" ,fieldOffset Both "StgRegTable" "rR4" ,fieldOffset Both "StgRegTable" "rR5" ,fieldOffset Both "StgRegTable" "rR6" ,fieldOffset Both "StgRegTable" "rR7" ,fieldOffset Both "StgRegTable" "rR8" ,fieldOffset Both "StgRegTable" "rR9" ,fieldOffset Both "StgRegTable" "rR10" ,fieldOffset Both "StgRegTable" "rF1" ,fieldOffset Both "StgRegTable" "rF2" ,fieldOffset Both "StgRegTable" "rF3" ,fieldOffset Both "StgRegTable" "rF4" ,fieldOffset Both "StgRegTable" "rF5" ,fieldOffset Both "StgRegTable" "rF6" ,fieldOffset Both "StgRegTable" "rD1" ,fieldOffset Both "StgRegTable" "rD2" ,fieldOffset Both "StgRegTable" "rD3" ,fieldOffset Both "StgRegTable" "rD4" ,fieldOffset Both "StgRegTable" "rD5" ,fieldOffset Both "StgRegTable" "rD6" ,fieldOffset Both "StgRegTable" "rXMM1" ,fieldOffset Both "StgRegTable" "rXMM2" ,fieldOffset Both "StgRegTable" "rXMM3" ,fieldOffset Both "StgRegTable" "rXMM4" ,fieldOffset Both "StgRegTable" "rXMM5" ,fieldOffset Both "StgRegTable" "rXMM6" ,fieldOffset Both "StgRegTable" "rYMM1" ,fieldOffset Both "StgRegTable" "rYMM2" ,fieldOffset Both "StgRegTable" "rYMM3" ,fieldOffset Both "StgRegTable" "rYMM4" ,fieldOffset Both "StgRegTable" "rYMM5" ,fieldOffset Both "StgRegTable" "rYMM6" ,fieldOffset Both "StgRegTable" "rZMM1" ,fieldOffset Both "StgRegTable" "rZMM2" ,fieldOffset Both "StgRegTable" "rZMM3" ,fieldOffset Both "StgRegTable" "rZMM4" ,fieldOffset Both "StgRegTable" "rZMM5" ,fieldOffset Both "StgRegTable" "rZMM6" ,fieldOffset Both "StgRegTable" "rL1" ,fieldOffset Both "StgRegTable" "rSp" ,fieldOffset Both "StgRegTable" "rSpLim" ,fieldOffset Both "StgRegTable" "rHp" ,fieldOffset Both "StgRegTable" "rHpLim" ,fieldOffset Both "StgRegTable" "rCCCS" ,fieldOffset Both "StgRegTable" "rCurrentTSO" ,fieldOffset Both "StgRegTable" "rCurrentNursery" ,fieldOffset Both "StgRegTable" "rHpAlloc" ,structField C "StgRegTable" "rRet" ,structField C "StgRegTable" "rNursery" ,defIntOffset Both "stgEagerBlackholeInfo" "FUN_OFFSET(stgEagerBlackholeInfo)" ,defIntOffset Both "stgGCEnter1" "FUN_OFFSET(stgGCEnter1)" ,defIntOffset Both "stgGCFun" "FUN_OFFSET(stgGCFun)" ,fieldOffset Both "Capability" "r" ,fieldOffset C "Capability" "lock" ,structField C "Capability" "no" ,structField C "Capability" "mut_lists" ,structField C "Capability" "context_switch" ,structField C "Capability" "interrupt" ,structField C "Capability" "sparks" ,structField Both "bdescr" "start" ,structField Both "bdescr" "free" ,structField Both "bdescr" "blocks" ,structField C "bdescr" "gen_no" ,structField C "bdescr" "link" ,structSize C "generation" ,structField C "generation" "n_new_large_words" ,structField C "generation" "weak_ptr_list" ,structSize Both "CostCentreStack" ,structField C "CostCentreStack" "ccsID" ,structFieldH Both "CostCentreStack" "mem_alloc" ,structFieldH Both "CostCentreStack" "scc_count" ,structField C "CostCentreStack" "prevStack" ,structField C "CostCentre" "ccID" ,structField C "CostCentre" "link" ,structField C "StgHeader" "info" ,structField_ Both "StgHeader_ccs" "StgHeader" "prof.ccs" ,structField_ Both "StgHeader_ldvw" "StgHeader" "prof.hp.ldvw" ,structSize Both "StgSMPThunkHeader" ,closurePayload C "StgClosure" "payload" ,structFieldH Both "StgEntCounter" "allocs" ,structFieldH Both "StgEntCounter" "allocd" ,structField Both "StgEntCounter" "registeredp" ,structField Both "StgEntCounter" "link" ,structField Both "StgEntCounter" "entry_count" ,closureSize Both "StgUpdateFrame" ,closureSize C "StgCatchFrame" ,closureSize C "StgStopFrame" ,closureSize Both "StgMutArrPtrs" ,closureField Both "StgMutArrPtrs" "ptrs" ,closureField Both "StgMutArrPtrs" "size" ,closureSize Both "StgArrWords" ,closureField C "StgArrWords" "bytes" ,closurePayload C "StgArrWords" "payload" ,closureField C "StgTSO" "_link" ,closureField C "StgTSO" "global_link" ,closureField C "StgTSO" "what_next" ,closureField C "StgTSO" "why_blocked" ,closureField C "StgTSO" "block_info" ,closureField C "StgTSO" "blocked_exceptions" ,closureField C "StgTSO" "id" ,closureField C "StgTSO" "cap" ,closureField C "StgTSO" "saved_errno" ,closureField C "StgTSO" "trec" ,closureField C "StgTSO" "flags" ,closureField C "StgTSO" "dirty" ,closureField C "StgTSO" "bq" ,closureField_ Both "StgTSO_cccs" "StgTSO" "prof.cccs" ,closureField Both "StgTSO" "stackobj" ,closureField Both "StgStack" "sp" ,closureFieldOffset Both "StgStack" "stack" ,closureField C "StgStack" "stack_size" ,closureField C "StgStack" "dirty" ,structSize C "StgTSOProfInfo" ,closureField Both "StgUpdateFrame" "updatee" ,closureField C "StgCatchFrame" "handler" ,closureField C "StgCatchFrame" "exceptions_blocked" ,closureSize C "StgPAP" ,closureField C "StgPAP" "n_args" ,closureFieldGcptr C "StgPAP" "fun" ,closureField C "StgPAP" "arity" ,closurePayload C "StgPAP" "payload" ,thunkSize C "StgAP" ,closureField C "StgAP" "n_args" ,closureFieldGcptr C "StgAP" "fun" ,closurePayload C "StgAP" "payload" ,thunkSize C "StgAP_STACK" ,closureField C "StgAP_STACK" "size" ,closureFieldGcptr C "StgAP_STACK" "fun" ,closurePayload C "StgAP_STACK" "payload" ,thunkSize C "StgSelector" ,closureFieldGcptr C "StgInd" "indirectee" ,closureSize C "StgMutVar" ,closureField C "StgMutVar" "var" ,closureSize C "StgAtomicallyFrame" ,closureField C "StgAtomicallyFrame" "code" ,closureField C "StgAtomicallyFrame" "next_invariant_to_check" ,closureField C "StgAtomicallyFrame" "result" ,closureField C "StgInvariantCheckQueue" "invariant" ,closureField C "StgInvariantCheckQueue" "my_execution" ,closureField C "StgInvariantCheckQueue" "next_queue_entry" ,closureField C "StgAtomicInvariant" "code" ,closureField C "StgTRecHeader" "enclosing_trec" ,closureSize C "StgCatchSTMFrame" ,closureField C "StgCatchSTMFrame" "handler" ,closureField C "StgCatchSTMFrame" "code" ,closureSize C "StgCatchRetryFrame" ,closureField C "StgCatchRetryFrame" "running_alt_code" ,closureField C "StgCatchRetryFrame" "first_code" ,closureField C "StgCatchRetryFrame" "alt_code" ,closureField C "StgTVarWatchQueue" "closure" ,closureField C "StgTVarWatchQueue" "next_queue_entry" ,closureField C "StgTVarWatchQueue" "prev_queue_entry" ,closureSize C "StgTVar" ,closureField C "StgTVar" "current_value" ,closureField C "StgTVar" "first_watch_queue_entry" ,closureField C "StgTVar" "num_updates" ,closureSize C "StgWeak" ,closureField C "StgWeak" "link" ,closureField C "StgWeak" "key" ,closureField C "StgWeak" "value" ,closureField C "StgWeak" "finalizer" ,closureField C "StgWeak" "cfinalizers" ,closureSize C "StgCFinalizerList" ,closureField C "StgCFinalizerList" "link" ,closureField C "StgCFinalizerList" "fptr" ,closureField C "StgCFinalizerList" "ptr" ,closureField C "StgCFinalizerList" "eptr" ,closureField C "StgCFinalizerList" "flag" ,closureSize C "StgMVar" ,closureField C "StgMVar" "head" ,closureField C "StgMVar" "tail" ,closureField C "StgMVar" "value" ,closureSize C "StgMVarTSOQueue" ,closureField C "StgMVarTSOQueue" "link" ,closureField C "StgMVarTSOQueue" "tso" ,closureSize C "StgBCO" ,closureField C "StgBCO" "instrs" ,closureField C "StgBCO" "literals" ,closureField C "StgBCO" "ptrs" ,closureField C "StgBCO" "arity" ,closureField C "StgBCO" "size" ,closurePayload C "StgBCO" "bitmap" ,closureSize C "StgStableName" ,closureField C "StgStableName" "sn" ,closureSize C "StgBlockingQueue" ,closureField C "StgBlockingQueue" "bh" ,closureField C "StgBlockingQueue" "owner" ,closureField C "StgBlockingQueue" "queue" ,closureField C "StgBlockingQueue" "link" ,closureSize C "MessageBlackHole" ,closureField C "MessageBlackHole" "link" ,closureField C "MessageBlackHole" "tso" ,closureField C "MessageBlackHole" "bh" ,structField_ C "RtsFlags_ProfFlags_showCCSOnException" "RTS_FLAGS" "ProfFlags.showCCSOnException" ,structField_ C "RtsFlags_DebugFlags_apply" "RTS_FLAGS" "DebugFlags.apply" ,structField_ C "RtsFlags_DebugFlags_sanity" "RTS_FLAGS" "DebugFlags.sanity" ,structField_ C "RtsFlags_DebugFlags_weak" "RTS_FLAGS" "DebugFlags.weak" ,structField_ C "RtsFlags_GcFlags_initialStkSize" "RTS_FLAGS" "GcFlags.initialStkSize" ,structField_ C "RtsFlags_MiscFlags_tickInterval" "RTS_FLAGS" "MiscFlags.tickInterval" ,structSize C "StgFunInfoExtraFwd" ,structField C "StgFunInfoExtraFwd" "slow_apply" ,structField C "StgFunInfoExtraFwd" "fun_type" ,structFieldH Both "StgFunInfoExtraFwd" "arity" ,structField_ C "StgFunInfoExtraFwd_bitmap" "StgFunInfoExtraFwd" "b.bitmap" ,structSize Both "StgFunInfoExtraRev" ,structField C "StgFunInfoExtraRev" "slow_apply_offset" ,structField C "StgFunInfoExtraRev" "fun_type" ,structFieldH Both "StgFunInfoExtraRev" "arity" ,structField_ C "StgFunInfoExtraRev_bitmap" "StgFunInfoExtraRev" "b.bitmap" ,structField C "StgLargeBitmap" "size" ,fieldOffset C "StgLargeBitmap" "bitmap" ,structSize C "snEntry" ,structField C "snEntry" "sn_obj" ,structField C "snEntry" "addr" ,structSize C "spEntry" ,structField C "spEntry" "addr" -- Note that this conditional part only affects the C headers. -- That's important, as it means we get the same PlatformConstants -- type on all platforms. ,if os == "mingw32" then concat [structSize C "StgAsyncIOResult" ,structField C "StgAsyncIOResult" "reqID" ,structField C "StgAsyncIOResult" "len" ,structField C "StgAsyncIOResult" "errCode"] else [] -- pre-compiled thunk types ,constantWord Haskell "MAX_SPEC_SELECTEE_SIZE" "MAX_SPEC_SELECTEE_SIZE" ,constantWord Haskell "MAX_SPEC_AP_SIZE" "MAX_SPEC_AP_SIZE" -- closure sizes: these do NOT include the header (see below for -- header sizes) ,constantWord Haskell "MIN_PAYLOAD_SIZE" "MIN_PAYLOAD_SIZE" ,constantInt Haskell "MIN_INTLIKE" "MIN_INTLIKE" ,constantWord Haskell "MAX_INTLIKE" "MAX_INTLIKE" ,constantWord Haskell "MIN_CHARLIKE" "MIN_CHARLIKE" ,constantWord Haskell "MAX_CHARLIKE" "MAX_CHARLIKE" ,constantWord Haskell "MUT_ARR_PTRS_CARD_BITS" "MUT_ARR_PTRS_CARD_BITS" -- A section of code-generator-related MAGIC CONSTANTS. ,constantWord Haskell "MAX_Vanilla_REG" "MAX_VANILLA_REG" ,constantWord Haskell "MAX_Float_REG" "MAX_FLOAT_REG" ,constantWord Haskell "MAX_Double_REG" "MAX_DOUBLE_REG" ,constantWord Haskell "MAX_Long_REG" "MAX_LONG_REG" ,constantWord Haskell "MAX_XMM_REG" "MAX_XMM_REG" ,constantWord Haskell "MAX_Real_Vanilla_REG" "MAX_REAL_VANILLA_REG" ,constantWord Haskell "MAX_Real_Float_REG" "MAX_REAL_FLOAT_REG" ,constantWord Haskell "MAX_Real_Double_REG" "MAX_REAL_DOUBLE_REG" ,constantWord Haskell "MAX_Real_XMM_REG" "MAX_REAL_XMM_REG" ,constantWord Haskell "MAX_Real_Long_REG" "MAX_REAL_LONG_REG" -- This tells the native code generator the size of the spill -- area is has available. ,constantWord Haskell "RESERVED_C_STACK_BYTES" "RESERVED_C_STACK_BYTES" -- The amount of (Haskell) stack to leave free for saving -- registers when returning to the scheduler. ,constantWord Haskell "RESERVED_STACK_WORDS" "RESERVED_STACK_WORDS" -- Continuations that need more than this amount of stack -- should do their own stack check (see bug #1466). ,constantWord Haskell "AP_STACK_SPLIM" "AP_STACK_SPLIM" -- Size of a word, in bytes ,constantWord Haskell "WORD_SIZE" "SIZEOF_HSWORD" -- Size of a double in StgWords. ,constantWord Haskell "DOUBLE_SIZE" "SIZEOF_DOUBLE" -- Size of a C int, in bytes. May be smaller than wORD_SIZE. ,constantWord Haskell "CINT_SIZE" "SIZEOF_INT" ,constantWord Haskell "CLONG_SIZE" "SIZEOF_LONG" ,constantWord Haskell "CLONG_LONG_SIZE" "SIZEOF_LONG_LONG" -- Number of bits to shift a bitfield left by in an info table. ,constantWord Haskell "BITMAP_BITS_SHIFT" "BITMAP_BITS_SHIFT" -- Amount of pointer bits used for semi-tagging constructor closures ,constantWord Haskell "TAG_BITS" "TAG_BITS" ,constantBool Haskell "WORDS_BIGENDIAN" "defined(WORDS_BIGENDIAN)" ,constantBool Haskell "DYNAMIC_BY_DEFAULT" "defined(DYNAMIC_BY_DEFAULT)" ,constantWord Haskell "LDV_SHIFT" "LDV_SHIFT" ,constantNatural Haskell "ILDV_CREATE_MASK" "LDV_CREATE_MASK" ,constantNatural Haskell "ILDV_STATE_CREATE" "LDV_STATE_CREATE" ,constantNatural Haskell "ILDV_STATE_USE" "LDV_STATE_USE" ] getWanted :: Bool -> FilePath -> FilePath -> [String] -> FilePath -> IO Results getWanted verbose tmpdir gccProgram gccFlags nmProgram = do let cStuff = unlines (headers ++ concatMap (doWanted . snd) wanteds) cFile = tmpdir </> "tmp.c" oFile = tmpdir </> "tmp.o" writeFile cFile cStuff execute verbose gccProgram (gccFlags ++ ["-c", cFile, "-o", oFile]) xs <- readProcess nmProgram ["-P", oFile] "" let ls = lines xs ms = map parseNmLine ls m = Map.fromList $ catMaybes ms rs <- mapM (lookupResult m) wanteds return rs where headers = ["#define IN_STG_CODE 0", "", "/*", " * We need offsets of profiled things...", " * better be careful that this doesn't", " * affect the offsets of anything else.", " */", "", "#define PROFILING", "#define THREADED_RTS", "", "#include \"PosixSource.h\"", "#include \"Rts.h\"", "#include \"Stable.h\"", "#include \"Capability.h\"", "", "#include <inttypes.h>", "#include <stddef.h>", "#include <stdio.h>", "#include <string.h>", "", "#define FIELD_SIZE(s_type, field) ((size_t)sizeof(((s_type*)0)->field))", "#define TYPE_SIZE(type) (sizeof(type))", "#define FUN_OFFSET(sym) (offsetof(Capability,f.sym) - offsetof(Capability,r))", "", "#pragma GCC poison sizeof" ] prefix = "derivedConstant" mkFullName name = prefix ++ name -- We add 1 to the value, as some platforms will make a symbol -- of size 1 when for -- char foo[0]; -- We then subtract 1 again when parsing. doWanted (GetFieldType name (Fst (CExpr cExpr))) = ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"] doWanted (GetClosureSize name (Fst (CExpr cExpr))) = ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"] doWanted (GetWord name (Fst (CExpr cExpr))) = ["char " ++ mkFullName name ++ "[1 + " ++ cExpr ++ "];"] doWanted (GetInt name (Fst (CExpr cExpr))) = ["char " ++ mkFullName name ++ "Mag[1 + ((intptr_t)(" ++ cExpr ++ ") >= 0 ? (" ++ cExpr ++ ") : -(" ++ cExpr ++ "))];", "char " ++ mkFullName name ++ "Sig[(intptr_t)(" ++ cExpr ++ ") >= 0 ? 3 : 1];"] doWanted (GetNatural name (Fst (CExpr cExpr))) = -- These casts fix "right shift count >= width of type" -- warnings let cExpr' = "(uint64_t)(size_t)(" ++ cExpr ++ ")" in ["char " ++ mkFullName name ++ "0[1 + ((" ++ cExpr' ++ ") & 0xFFFF)];", "char " ++ mkFullName name ++ "1[1 + (((" ++ cExpr' ++ ") >> 16) & 0xFFFF)];", "char " ++ mkFullName name ++ "2[1 + (((" ++ cExpr' ++ ") >> 32) & 0xFFFF)];", "char " ++ mkFullName name ++ "3[1 + (((" ++ cExpr' ++ ") >> 48) & 0xFFFF)];"] doWanted (GetBool name (Fst (CPPExpr cppExpr))) = ["#if " ++ cppExpr, "char " ++ mkFullName name ++ "[1];", "#else", "char " ++ mkFullName name ++ "[2];", "#endif"] doWanted (StructFieldMacro {}) = [] doWanted (ClosureFieldMacro {}) = [] doWanted (ClosurePayloadMacro {}) = [] doWanted (FieldTypeGcptrMacro {}) = [] -- parseNmLine parses "nm -P" output that looks like -- "derivedConstantMAX_Vanilla_REG C 0000000b 0000000b" (GNU nm) -- "_derivedConstantMAX_Vanilla_REG C b 0" (Mac OS X) -- "_derivedConstantMAX_Vanilla_REG C 000000b" (MinGW) -- "derivedConstantMAX_Vanilla_REG D 1 b" (Solaris) -- and returns ("MAX_Vanilla_REG", 11) parseNmLine line = case words line of ('_' : n) : "C" : s : _ -> mkP n s n : "C" : s : _ -> mkP n s [n, "D", _, s] -> mkP n s _ -> Nothing where mkP r s = case (stripPrefix prefix r, readHex s) of (Just name, [(size, "")]) -> Just (name, size) _ -> Nothing -- If an Int value is larger than 2^28 or smaller -- than -2^28, then fail. -- This test is a bit conservative, but if any -- constants are roughly maxBound or minBound then -- we probably need them to be Integer rather than -- Int so that -- cross-compiling between 32bit and -- 64bit platforms works. lookupSmall :: Map String Integer -> Name -> IO Integer lookupSmall m name = case Map.lookup name m of Just v | v > 2^(28 :: Int) || v < -(2^(28 :: Int)) -> die ("Value too large for GetWord: " ++ show v) | otherwise -> return v Nothing -> die ("Can't find " ++ show name) lookupResult :: Map String Integer -> (Where, What Fst) -> IO (Where, What Snd) lookupResult m (w, GetWord name _) = do v <- lookupSmall m name return (w, GetWord name (Snd (v - 1))) lookupResult m (w, GetInt name _) = do mag <- lookupSmall m (name ++ "Mag") sig <- lookupSmall m (name ++ "Sig") return (w, GetWord name (Snd ((mag - 1) * (sig - 2)))) lookupResult m (w, GetNatural name _) = do v0 <- lookupSmall m (name ++ "0") v1 <- lookupSmall m (name ++ "1") v2 <- lookupSmall m (name ++ "2") v3 <- lookupSmall m (name ++ "3") let v = (v0 - 1) + shiftL (v1 - 1) 16 + shiftL (v2 - 1) 32 + shiftL (v3 - 1) 48 return (w, GetWord name (Snd v)) lookupResult m (w, GetBool name _) = do v <- lookupSmall m name case v of 1 -> return (w, GetBool name (Snd True)) 2 -> return (w, GetBool name (Snd False)) _ -> die ("Bad boolean: " ++ show v) lookupResult m (w, GetFieldType name _) = do v <- lookupSmall m name return (w, GetFieldType name (Snd (v - 1))) lookupResult m (w, GetClosureSize name _) = do v <- lookupSmall m name return (w, GetClosureSize name (Snd (v - 1))) lookupResult _ (w, StructFieldMacro name) = return (w, StructFieldMacro name) lookupResult _ (w, ClosureFieldMacro name) = return (w, ClosureFieldMacro name) lookupResult _ (w, ClosurePayloadMacro name) = return (w, ClosurePayloadMacro name) lookupResult _ (w, FieldTypeGcptrMacro name) = return (w, FieldTypeGcptrMacro name) writeHaskellType :: FilePath -> [What Fst] -> IO () writeHaskellType fn ws = writeFile fn xs where xs = unlines (headers ++ body ++ footers) headers = ["data PlatformConstants = PlatformConstants {" -- Now a kludge that allows the real entries to -- all start with a comma, which makes life a -- little easier ," pc_platformConstants :: ()"] footers = [" } deriving Read"] body = concatMap doWhat ws doWhat (GetClosureSize name _) = [" , pc_" ++ name ++ " :: Int"] doWhat (GetFieldType name _) = [" , pc_" ++ name ++ " :: Int"] doWhat (GetWord name _) = [" , pc_" ++ name ++ " :: Int"] doWhat (GetInt name _) = [" , pc_" ++ name ++ " :: Int"] doWhat (GetNatural name _) = [" , pc_" ++ name ++ " :: Integer"] doWhat (GetBool name _) = [" , pc_" ++ name ++ " :: Bool"] doWhat (StructFieldMacro {}) = [] doWhat (ClosureFieldMacro {}) = [] doWhat (ClosurePayloadMacro {}) = [] doWhat (FieldTypeGcptrMacro {}) = [] writeHaskellValue :: FilePath -> [What Snd] -> IO () writeHaskellValue fn rs = writeFile fn xs where xs = unlines (headers ++ body ++ footers) headers = ["PlatformConstants {" ," pc_platformConstants = ()"] footers = [" }"] body = concatMap doWhat rs doWhat (GetClosureSize name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetFieldType name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetWord name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetInt name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetNatural name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (GetBool name (Snd v)) = [" , pc_" ++ name ++ " = " ++ show v] doWhat (StructFieldMacro {}) = [] doWhat (ClosureFieldMacro {}) = [] doWhat (ClosurePayloadMacro {}) = [] doWhat (FieldTypeGcptrMacro {}) = [] writeHaskellWrappers :: FilePath -> [What Fst] -> IO () writeHaskellWrappers fn ws = writeFile fn xs where xs = unlines body body = concatMap doWhat ws doWhat (GetFieldType {}) = [] doWhat (GetClosureSize {}) = [] doWhat (GetWord name _) = [haskellise name ++ " :: DynFlags -> Int", haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"] doWhat (GetInt name _) = [haskellise name ++ " :: DynFlags -> Int", haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"] doWhat (GetNatural name _) = [haskellise name ++ " :: DynFlags -> Integer", haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"] doWhat (GetBool name _) = [haskellise name ++ " :: DynFlags -> Bool", haskellise name ++ " dflags = pc_" ++ name ++ " (sPlatformConstants (settings dflags))"] doWhat (StructFieldMacro {}) = [] doWhat (ClosureFieldMacro {}) = [] doWhat (ClosurePayloadMacro {}) = [] doWhat (FieldTypeGcptrMacro {}) = [] writeHaskellExports :: FilePath -> [What Fst] -> IO () writeHaskellExports fn ws = writeFile fn xs where xs = unlines body body = concatMap doWhat ws doWhat (GetFieldType {}) = [] doWhat (GetClosureSize {}) = [] doWhat (GetWord name _) = [" " ++ haskellise name ++ ","] doWhat (GetInt name _) = [" " ++ haskellise name ++ ","] doWhat (GetNatural name _) = [" " ++ haskellise name ++ ","] doWhat (GetBool name _) = [" " ++ haskellise name ++ ","] doWhat (StructFieldMacro {}) = [] doWhat (ClosureFieldMacro {}) = [] doWhat (ClosurePayloadMacro {}) = [] doWhat (FieldTypeGcptrMacro {}) = [] writeHeader :: FilePath -> [What Snd] -> IO () writeHeader fn rs = writeFile fn xs where xs = unlines (headers ++ body) headers = ["/* This file is created automatically. Do not edit by hand.*/", ""] body = concatMap doWhat rs doWhat (GetFieldType name (Snd v)) = ["#define " ++ name ++ " b" ++ show (v * 8)] doWhat (GetClosureSize name (Snd v)) = ["#define " ++ name ++ " (SIZEOF_StgHeader+" ++ show v ++ ")"] doWhat (GetWord name (Snd v)) = ["#define " ++ name ++ " " ++ show v] doWhat (GetInt name (Snd v)) = ["#define " ++ name ++ " " ++ show v] doWhat (GetNatural name (Snd v)) = ["#define " ++ name ++ " " ++ show v] doWhat (GetBool name (Snd v)) = ["#define " ++ name ++ " " ++ show (fromEnum v)] doWhat (StructFieldMacro nameBase) = ["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+OFFSET_" ++ nameBase ++ "]"] doWhat (ClosureFieldMacro nameBase) = ["#define " ++ nameBase ++ "(__ptr__) REP_" ++ nameBase ++ "[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ "]"] doWhat (ClosurePayloadMacro nameBase) = ["#define " ++ nameBase ++ "(__ptr__,__ix__) W_[__ptr__+SIZEOF_StgHeader+OFFSET_" ++ nameBase ++ " + WDS(__ix__)]"] doWhat (FieldTypeGcptrMacro nameBase) = ["#define REP_" ++ nameBase ++ " gcptr"] die :: String -> IO a die err = do hPutStrLn stderr err exitFailure execute :: Bool -> FilePath -> [String] -> IO () execute verbose prog args = do when verbose $ putStrLn $ showCommandForUser prog args ec <- rawSystem prog args unless (ec == ExitSuccess) $ die ("Executing " ++ show prog ++ " failed")
lukexi/ghc-7.8-arm64
utils/deriveConstants/DeriveConstants.hs
Haskell
bsd-3-clause
40,857
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Main -- Copyright : (c) David Himmelstrup 2005 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Entry point to the default cabal-install front-end. ----------------------------------------------------------------------------- module Main (main) where import Distribution.Client.Setup ( GlobalFlags(..), globalCommand, globalRepos , ConfigFlags(..) , ConfigExFlags(..), defaultConfigExFlags, configureExCommand , BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..) , buildCommand, replCommand, testCommand, benchmarkCommand , InstallFlags(..), defaultInstallFlags , installCommand, upgradeCommand, uninstallCommand , FetchFlags(..), fetchCommand , FreezeFlags(..), freezeCommand , GetFlags(..), getCommand, unpackCommand , checkCommand , formatCommand , updateCommand , ListFlags(..), listCommand , InfoFlags(..), infoCommand , UploadFlags(..), uploadCommand , ReportFlags(..), reportCommand , runCommand , InitFlags(initVerbosity), initCommand , SDistFlags(..), SDistExFlags(..), sdistCommand , Win32SelfUpgradeFlags(..), win32SelfUpgradeCommand , ActAsSetupFlags(..), actAsSetupCommand , SandboxFlags(..), sandboxCommand , ExecFlags(..), execCommand , UserConfigFlags(..), userConfigCommand , reportCommand ) import Distribution.Simple.Setup ( HaddockFlags(..), haddockCommand, defaultHaddockFlags , HscolourFlags(..), hscolourCommand , ReplFlags(..) , CopyFlags(..), copyCommand , RegisterFlags(..), registerCommand , CleanFlags(..), cleanCommand , TestFlags(..), BenchmarkFlags(..) , Flag(..), fromFlag, fromFlagOrDefault, flagToMaybe, toFlag , configAbsolutePaths ) import Distribution.Client.SetupWrapper ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions ) import Distribution.Client.Config ( SavedConfig(..), loadConfig, defaultConfigFile, userConfigDiff , userConfigUpdate ) import Distribution.Client.Targets ( readUserTargets ) import qualified Distribution.Client.List as List ( list, info ) import Distribution.Client.Install (install) import Distribution.Client.Configure (configure) import Distribution.Client.Update (update) import Distribution.Client.Exec (exec) import Distribution.Client.Fetch (fetch) import Distribution.Client.Freeze (freeze) import Distribution.Client.Check as Check (check) --import Distribution.Client.Clean (clean) import Distribution.Client.Upload as Upload (upload, check, report) import Distribution.Client.Run (run, splitRunArgs) import Distribution.Client.HttpUtils (configureTransport) import Distribution.Client.SrcDist (sdist) import Distribution.Client.Get (get) import Distribution.Client.Sandbox (sandboxInit ,sandboxAddSource ,sandboxDelete ,sandboxDeleteSource ,sandboxListSources ,sandboxHcPkg ,dumpPackageEnvironment ,getSandboxConfigFilePath ,loadConfigOrSandboxConfig ,findSavedDistPref ,initPackageDBIfNeeded ,maybeWithSandboxDirOnSearchPath ,maybeWithSandboxPackageInfo ,WereDepsReinstalled(..) ,maybeReinstallAddSourceDeps ,tryGetIndexFilePath ,sandboxBuildDir ,updateSandboxConfigFileFlag ,updateInstallDirs ,configCompilerAux' ,getPersistOrConfigCompiler ,configPackageDB') import Distribution.Client.Sandbox.PackageEnvironment (setPackageDB ,userPackageEnvironmentFile) import Distribution.Client.Sandbox.Timestamp (maybeAddCompilerTimestampRecord) import Distribution.Client.Sandbox.Types (UseSandbox(..), whenUsingSandbox) import Distribution.Client.Types (Password (..)) import Distribution.Client.Init (initCabal) import qualified Distribution.Client.Win32SelfUpgrade as Win32SelfUpgrade import Distribution.Client.Utils (determineNumJobs #if defined(mingw32_HOST_OS) ,relaxEncodingErrors #endif ,existsAndIsMoreRecentThan) import Distribution.PackageDescription ( BuildType(..), Executable(..), benchmarkName, benchmarkBuildInfo , testName, testBuildInfo, buildable ) import Distribution.PackageDescription.Parse ( readPackageDescription ) import Distribution.PackageDescription.PrettyPrint ( writeGenericPackageDescription ) import qualified Distribution.Simple as Simple import qualified Distribution.Make as Make import Distribution.Simple.Build ( startInterpreter ) import Distribution.Simple.Command ( CommandParse(..), CommandUI(..), Command , commandsRun, commandAddAction, hiddenCommand ) import Distribution.Simple.Compiler ( Compiler(..) ) import Distribution.Simple.Configure ( checkPersistBuildConfigOutdated, configCompilerAuxEx , ConfigStateFileError(..), localBuildInfoFile , getPersistBuildConfig, tryGetPersistBuildConfig ) import qualified Distribution.Simple.LocalBuildInfo as LBI import Distribution.Simple.Program (defaultProgramConfiguration ,configureAllKnownPrograms ,simpleProgramInvocation ,getProgramInvocationOutput) import Distribution.Simple.Program.Db (reconfigurePrograms) import qualified Distribution.Simple.Setup as Cabal import Distribution.Simple.Utils ( cabalVersion, die, notice, info, topHandler , findPackageDesc, tryFindPackageDesc ) import Distribution.Text ( display ) import Distribution.Verbosity as Verbosity ( Verbosity, normal ) import Distribution.Version ( Version(..), orLaterVersion ) import qualified Paths_cabal_install (version) import System.Environment (getArgs, getProgName) import System.Exit (exitFailure) import System.FilePath (splitExtension, takeExtension) import System.IO ( BufferMode(LineBuffering), hSetBuffering #ifdef mingw32_HOST_OS , stderr #endif , stdout ) import System.Directory (doesFileExist, getCurrentDirectory) import Data.List (intercalate) import Data.Maybe (mapMaybe) #if !MIN_VERSION_base(4,8,0) import Data.Monoid (Monoid(..)) import Control.Applicative (pure, (<$>)) #endif import Control.Monad (when, unless) -- | Entry point -- main :: IO () main = do -- Enable line buffering so that we can get fast feedback even when piped. -- This is especially important for CI and build systems. hSetBuffering stdout LineBuffering -- The default locale encoding for Windows CLI is not UTF-8 and printing -- Unicode characters to it will fail unless we relax the handling of encoding -- errors when writing to stderr and stdout. #ifdef mingw32_HOST_OS relaxEncodingErrors stdout relaxEncodingErrors stderr #endif getArgs >>= mainWorker mainWorker :: [String] -> IO () mainWorker args = topHandler $ case commandsRun (globalCommand commands) commands args of CommandHelp help -> printGlobalHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo (globalFlags, commandParse) -> case commandParse of _ | fromFlagOrDefault False (globalVersion globalFlags) -> printVersion | fromFlagOrDefault False (globalNumericVersion globalFlags) -> printNumericVersion CommandHelp help -> printCommandHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo action -> do globalFlags' <- updateSandboxConfigFileFlag globalFlags action globalFlags' where printCommandHelp help = do pname <- getProgName putStr (help pname) printGlobalHelp help = do pname <- getProgName configFile <- defaultConfigFile putStr (help pname) putStr $ "\nYou can edit the cabal configuration file to set defaults:\n" ++ " " ++ configFile ++ "\n" exists <- doesFileExist configFile when (not exists) $ putStrLn $ "This file will be generated with sensible " ++ "defaults if you run 'cabal update'." printOptionsList = putStr . unlines printErrors errs = die $ intercalate "\n" errs printNumericVersion = putStrLn $ display Paths_cabal_install.version printVersion = putStrLn $ "cabal-install version " ++ display Paths_cabal_install.version ++ "\nusing version " ++ display cabalVersion ++ " of the Cabal library " commands = [installCommand `commandAddAction` installAction ,updateCommand `commandAddAction` updateAction ,listCommand `commandAddAction` listAction ,infoCommand `commandAddAction` infoAction ,fetchCommand `commandAddAction` fetchAction ,freezeCommand `commandAddAction` freezeAction ,getCommand `commandAddAction` getAction ,hiddenCommand $ unpackCommand `commandAddAction` unpackAction ,checkCommand `commandAddAction` checkAction ,sdistCommand `commandAddAction` sdistAction ,uploadCommand `commandAddAction` uploadAction ,reportCommand `commandAddAction` reportAction ,runCommand `commandAddAction` runAction ,initCommand `commandAddAction` initAction ,configureExCommand `commandAddAction` configureAction ,buildCommand `commandAddAction` buildAction ,replCommand `commandAddAction` replAction ,sandboxCommand `commandAddAction` sandboxAction ,haddockCommand `commandAddAction` haddockAction ,execCommand `commandAddAction` execAction ,userConfigCommand `commandAddAction` userConfigAction ,cleanCommand `commandAddAction` cleanAction ,wrapperAction copyCommand copyVerbosity copyDistPref ,wrapperAction hscolourCommand hscolourVerbosity hscolourDistPref ,wrapperAction registerCommand regVerbosity regDistPref ,testCommand `commandAddAction` testAction ,benchmarkCommand `commandAddAction` benchmarkAction ,hiddenCommand $ uninstallCommand `commandAddAction` uninstallAction ,hiddenCommand $ formatCommand `commandAddAction` formatAction ,hiddenCommand $ upgradeCommand `commandAddAction` upgradeAction ,hiddenCommand $ win32SelfUpgradeCommand`commandAddAction` win32SelfUpgradeAction ,hiddenCommand $ actAsSetupCommand`commandAddAction` actAsSetupAction ] wrapperAction :: Monoid flags => CommandUI flags -> (flags -> Flag Verbosity) -> (flags -> Flag String) -> Command (GlobalFlags -> IO ()) wrapperAction command verbosityFlag distPrefFlag = commandAddAction command { commandDefaultFlags = mempty } $ \flags extraArgs globalFlags -> do let verbosity = fromFlagOrDefault normal (verbosityFlag flags) (_, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config (distPrefFlag flags) let setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref } setupWrapper verbosity setupScriptOptions Nothing command (const flags) extraArgs configureAction :: (ConfigFlags, ConfigExFlags) -> [String] -> GlobalFlags -> IO () configureAction (configFlags, configExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (configVerbosity configFlags) (useSandbox, config) <- fmap (updateInstallDirs (configUserInstall configFlags)) (loadConfigOrSandboxConfig verbosity globalFlags) let configFlags' = savedConfigureFlags config `mappend` configFlags configExFlags' = savedConfigureExFlags config `mappend` configExFlags globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, platform, conf) <- configCompilerAuxEx configFlags' -- If we're working inside a sandbox and the user has set the -w option, we -- may need to create a sandbox-local package DB for this compiler and add a -- timestamp record for this compiler to the timestamp file. let configFlags'' = case useSandbox of NoSandbox -> configFlags' (UseSandbox sandboxDir) -> setPackageDB sandboxDir comp platform configFlags' whenUsingSandbox useSandbox $ \sandboxDir -> do initPackageDBIfNeeded verbosity configFlags'' comp conf -- NOTE: We do not write the new sandbox package DB location to -- 'cabal.sandbox.config' here because 'configure -w' must not affect -- subsequent 'install' (for UI compatibility with non-sandboxed mode). indexFile <- tryGetIndexFilePath config maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile (compilerId comp) platform maybeWithSandboxDirOnSearchPath useSandbox $ configure verbosity (configPackageDB' configFlags'') (globalRepos globalFlags') comp platform conf configFlags'' configExFlags' extraArgs buildAction :: (BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO () buildAction (buildFlags, buildExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags) noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) -- Calls 'configureAction' to do the real work, so nothing special has to be -- done to support sandboxes. (useSandbox, config, distPref) <- reconfigure verbosity (buildDistPref buildFlags) mempty [] globalFlags noAddSource (buildNumJobs buildFlags) (const Nothing) maybeWithSandboxDirOnSearchPath useSandbox $ build verbosity config distPref buildFlags extraArgs -- | Actually do the work of building the package. This is separate from -- 'buildAction' so that 'testAction' and 'benchmarkAction' do not invoke -- 'reconfigure' twice. build :: Verbosity -> SavedConfig -> FilePath -> BuildFlags -> [String] -> IO () build verbosity config distPref buildFlags extraArgs = setupWrapper verbosity setupOptions Nothing (Cabal.buildCommand progConf) mkBuildFlags extraArgs where progConf = defaultProgramConfiguration setupOptions = defaultSetupScriptOptions { useDistPref = distPref } mkBuildFlags version = filterBuildFlags version config buildFlags' buildFlags' = buildFlags { buildVerbosity = toFlag verbosity , buildDistPref = toFlag distPref } -- | Make sure that we don't pass new flags to setup scripts compiled against -- old versions of Cabal. filterBuildFlags :: Version -> SavedConfig -> BuildFlags -> BuildFlags filterBuildFlags version config buildFlags | version >= Version [1,19,1] [] = buildFlags_latest -- Cabal < 1.19.1 doesn't support 'build -j'. | otherwise = buildFlags_pre_1_19_1 where buildFlags_pre_1_19_1 = buildFlags { buildNumJobs = NoFlag } buildFlags_latest = buildFlags { -- Take the 'jobs' setting '~/.cabal/config' into account. buildNumJobs = Flag . Just . determineNumJobs $ (numJobsConfigFlag `mappend` numJobsCmdLineFlag) } numJobsConfigFlag = installNumJobs . savedInstallFlags $ config numJobsCmdLineFlag = buildNumJobs buildFlags replAction :: (ReplFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO () replAction (replFlags, buildExFlags) extraArgs globalFlags = do cwd <- getCurrentDirectory pkgDesc <- findPackageDesc cwd either (const onNoPkgDesc) (const onPkgDesc) pkgDesc where verbosity = fromFlagOrDefault normal (replVerbosity replFlags) -- There is a .cabal file in the current directory: start a REPL and load -- the project's modules. onPkgDesc = do let noAddSource = case replReload replFlags of Flag True -> SkipAddSourceDepsCheck _ -> fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) -- Calls 'configureAction' to do the real work, so nothing special has to -- be done to support sandboxes. (useSandbox, _config, distPref) <- reconfigure verbosity (replDistPref replFlags) mempty [] globalFlags noAddSource NoFlag (const Nothing) let progConf = defaultProgramConfiguration setupOptions = defaultSetupScriptOptions { useCabalVersion = orLaterVersion $ Version [1,18,0] [] , useDistPref = distPref } replFlags' = replFlags { replVerbosity = toFlag verbosity , replDistPref = toFlag distPref } maybeWithSandboxDirOnSearchPath useSandbox $ setupWrapper verbosity setupOptions Nothing (Cabal.replCommand progConf) (const replFlags') extraArgs -- No .cabal file in the current directory: just start the REPL (possibly -- using the sandbox package DB). onNoPkgDesc = do (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags let configFlags = savedConfigureFlags config (comp, _platform, programDb) <- configCompilerAux' configFlags programDb' <- reconfigurePrograms verbosity (replProgramPaths replFlags) (replProgramArgs replFlags) programDb startInterpreter verbosity programDb' comp (configPackageDB' configFlags) -- | Re-configure the package in the current directory if needed. Deciding -- when to reconfigure and with which options is convoluted: -- -- If we are reconfiguring, we must always run @configure@ with the -- verbosity option we are given; however, that a previous configuration -- uses a different verbosity setting is not reason enough to reconfigure. -- -- The package should be configured to use the same \"dist\" prefix as -- given to the @build@ command, otherwise the build will probably -- fail. Not only does this determine the \"dist\" prefix setting if we -- need to reconfigure anyway, but an existing configuration should be -- invalidated if its \"dist\" prefix differs. -- -- If the package has never been configured (i.e., there is no -- LocalBuildInfo), we must configure first, using the default options. -- -- If the package has been configured, there will be a 'LocalBuildInfo'. -- If there no package description file, we assume that the -- 'PackageDescription' is up to date, though the configuration may need -- to be updated for other reasons (see above). If there is a package -- description file, and it has been modified since the 'LocalBuildInfo' -- was generated, then we need to reconfigure. -- -- The caller of this function may also have specific requirements -- regarding the flags the last configuration used. For example, -- 'testAction' requires that the package be configured with test suites -- enabled. The caller may pass the required settings to this function -- along with a function to check the validity of the saved 'ConfigFlags'; -- these required settings will be checked first upon determining that -- a previous configuration exists. reconfigure :: Verbosity -- ^ Verbosity setting -> Flag FilePath -- ^ \"dist\" prefix -> ConfigFlags -- ^ Additional config flags to set. These flags -- will be 'mappend'ed to the last used or -- default 'ConfigFlags' as appropriate, so -- this value should be 'mempty' with only the -- required flags set. The required verbosity -- and \"dist\" prefix flags will be set -- automatically because they are always -- required; therefore, it is not necessary to -- set them here. -> [String] -- ^ Extra arguments -> GlobalFlags -- ^ Global flags -> SkipAddSourceDepsCheck -- ^ Should we skip the timestamp check for modified -- add-source dependencies? -> Flag (Maybe Int) -- ^ -j flag for reinstalling add-source deps. -> (ConfigFlags -> Maybe String) -- ^ Check that the required flags are set in -- the last used 'ConfigFlags'. If the required -- flags are not set, provide a message to the -- user explaining the reason for -- reconfiguration. Because the correct \"dist\" -- prefix setting is always required, it is checked -- automatically; this function need not check -- for it. -> IO (UseSandbox, SavedConfig, FilePath) reconfigure verbosity flagDistPref addConfigFlags extraArgs globalFlags skipAddSourceDepsCheck numJobsFlag checkFlags = do (useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config flagDistPref eLbi <- tryGetPersistBuildConfig distPref config' <- case eLbi of Left err -> onNoBuildConfig (useSandbox, config) distPref err Right lbi -> onBuildConfig (useSandbox, config) distPref lbi return (useSandbox, config', distPref) where -- We couldn't load the saved package config file. -- -- If we're in a sandbox: add-source deps don't have to be reinstalled -- (since we don't know the compiler & platform). onNoBuildConfig :: (UseSandbox, SavedConfig) -> FilePath -> ConfigStateFileError -> IO SavedConfig onNoBuildConfig (_, config) distPref err = do let msg = case err of ConfigStateFileMissing -> "Package has never been configured." ConfigStateFileNoParse -> "Saved package config file seems " ++ "to be corrupt." _ -> show err case err of ConfigStateFileBadVersion _ _ _ -> info verbosity msg _ -> do let distVerbFlags = mempty { configVerbosity = toFlag verbosity , configDistPref = toFlag distPref } defaultFlags = mappend addConfigFlags distVerbFlags notice verbosity $ msg ++ " Configuring with default flags." ++ configureManually configureAction (defaultFlags, defaultConfigExFlags) extraArgs globalFlags return config -- Package has been configured, but the configuration may be out of -- date or required flags may not be set. -- -- If we're in a sandbox: reinstall the modified add-source deps and -- force reconfigure if we did. onBuildConfig :: (UseSandbox, SavedConfig) -> FilePath -> LBI.LocalBuildInfo -> IO SavedConfig onBuildConfig (useSandbox, config) distPref lbi = do let configFlags = LBI.configFlags lbi distVerbFlags = mempty { configVerbosity = toFlag verbosity , configDistPref = toFlag distPref } flags = mconcat [configFlags, addConfigFlags, distVerbFlags] -- Was the sandbox created after the package was already configured? We -- may need to skip reinstallation of add-source deps and force -- reconfigure. let buildConfig = localBuildInfoFile distPref sandboxConfig <- getSandboxConfigFilePath globalFlags isSandboxConfigNewer <- sandboxConfig `existsAndIsMoreRecentThan` buildConfig let skipAddSourceDepsCheck' | isSandboxConfigNewer = SkipAddSourceDepsCheck | otherwise = skipAddSourceDepsCheck when (skipAddSourceDepsCheck' == SkipAddSourceDepsCheck) $ info verbosity "Skipping add-source deps check..." let (_, config') = updateInstallDirs (configUserInstall flags) (useSandbox, config) depsReinstalled <- case skipAddSourceDepsCheck' of DontSkipAddSourceDepsCheck -> maybeReinstallAddSourceDeps verbosity numJobsFlag flags globalFlags (useSandbox, config') SkipAddSourceDepsCheck -> do return NoDepsReinstalled -- Is the @cabal.config@ file newer than @dist/setup.config@? Then we need -- to force reconfigure. Note that it's possible to use @cabal.config@ -- even without sandboxes. isUserPackageEnvironmentFileNewer <- userPackageEnvironmentFile `existsAndIsMoreRecentThan` buildConfig -- Determine whether we need to reconfigure and which message to show to -- the user if that is the case. mMsg <- determineMessageToShow distPref lbi configFlags depsReinstalled isSandboxConfigNewer isUserPackageEnvironmentFileNewer case mMsg of -- No message for the user indicates that reconfiguration -- is not required. Nothing -> return config' -- Show the message and reconfigure. Just msg -> do notice verbosity msg configureAction (flags, defaultConfigExFlags) extraArgs globalFlags return config' -- Determine what message, if any, to display to the user if reconfiguration -- is required. determineMessageToShow :: FilePath -> LBI.LocalBuildInfo -> ConfigFlags -> WereDepsReinstalled -> Bool -> Bool -> IO (Maybe String) determineMessageToShow _ _ _ _ True _ = -- The sandbox was created after the package was already configured. return $! Just $! sandboxConfigNewerMessage determineMessageToShow _ _ _ _ False True = -- The user package environment file was modified. return $! Just $! userPackageEnvironmentFileModifiedMessage determineMessageToShow distPref lbi configFlags depsReinstalled False False = do let savedDistPref = fromFlagOrDefault (useDistPref defaultSetupScriptOptions) (configDistPref configFlags) case depsReinstalled of ReinstalledSomeDeps -> -- Some add-source deps were reinstalled. return $! Just $! reinstalledDepsMessage NoDepsReinstalled -> case checkFlags configFlags of -- Flag required by the caller is not set. Just msg -> return $! Just $! msg ++ configureManually Nothing -- Required "dist" prefix is not set. | savedDistPref /= distPref -> return $! Just distPrefMessage -- All required flags are set, but the configuration -- may be outdated. | otherwise -> case LBI.pkgDescrFile lbi of Nothing -> return Nothing Just pdFile -> do outdated <- checkPersistBuildConfigOutdated distPref pdFile return $! if outdated then Just $! outdatedMessage pdFile else Nothing reconfiguringMostRecent = " Re-configuring with most recently used options." configureManually = " If this fails, please run configure manually." sandboxConfigNewerMessage = "The sandbox was created after the package was already configured." ++ reconfiguringMostRecent ++ configureManually userPackageEnvironmentFileModifiedMessage = "The user package environment file ('" ++ userPackageEnvironmentFile ++ "') was modified." ++ reconfiguringMostRecent ++ configureManually distPrefMessage = "Package previously configured with different \"dist\" prefix." ++ reconfiguringMostRecent ++ configureManually outdatedMessage pdFile = pdFile ++ " has been changed." ++ reconfiguringMostRecent ++ configureManually reinstalledDepsMessage = "Some add-source dependencies have been reinstalled." ++ reconfiguringMostRecent ++ configureManually installAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags) -> [String] -> GlobalFlags -> IO () installAction (configFlags, _, installFlags, _) _ globalFlags | fromFlagOrDefault False (installOnly installFlags) = do let verbosity = fromFlagOrDefault normal (configVerbosity configFlags) (_, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config (configDistPref configFlags) let setupOpts = defaultSetupScriptOptions { useDistPref = distPref } setupWrapper verbosity setupOpts Nothing installCommand (const mempty) [] installAction (configFlags, configExFlags, installFlags, haddockFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (configVerbosity configFlags) (useSandbox, config) <- fmap (updateInstallDirs (configUserInstall configFlags)) (loadConfigOrSandboxConfig verbosity globalFlags) targets <- readUserTargets verbosity extraArgs -- TODO: It'd be nice if 'cabal install' picked up the '-w' flag passed to -- 'configure' when run inside a sandbox. Right now, running -- -- $ cabal sandbox init && cabal configure -w /path/to/ghc -- && cabal build && cabal install -- -- performs the compilation twice unless you also pass -w to 'install'. -- However, this is the same behaviour that 'cabal install' has in the normal -- mode of operation, so we stick to it for consistency. let sandboxDistPref = case useSandbox of NoSandbox -> NoFlag UseSandbox sandboxDir -> Flag $ sandboxBuildDir sandboxDir distPref <- findSavedDistPref config (configDistPref configFlags `mappend` sandboxDistPref) let configFlags' = maybeForceTests installFlags' $ savedConfigureFlags config `mappend` configFlags { configDistPref = toFlag distPref } configExFlags' = defaultConfigExFlags `mappend` savedConfigureExFlags config `mappend` configExFlags installFlags' = defaultInstallFlags `mappend` savedInstallFlags config `mappend` installFlags haddockFlags' = defaultHaddockFlags `mappend` savedHaddockFlags config `mappend` haddockFlags { haddockDistPref = toFlag distPref } globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, platform, conf) <- configCompilerAux' configFlags' -- TODO: Redesign ProgramDB API to prevent such problems as #2241 in the future. conf' <- configureAllKnownPrograms verbosity conf -- If we're working inside a sandbox and the user has set the -w option, we -- may need to create a sandbox-local package DB for this compiler and add a -- timestamp record for this compiler to the timestamp file. configFlags'' <- case useSandbox of NoSandbox -> configAbsolutePaths $ configFlags' (UseSandbox sandboxDir) -> return $ setPackageDB sandboxDir comp platform configFlags' whenUsingSandbox useSandbox $ \sandboxDir -> do initPackageDBIfNeeded verbosity configFlags'' comp conf' indexFile <- tryGetIndexFilePath config maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile (compilerId comp) platform -- FIXME: Passing 'SandboxPackageInfo' to install unconditionally here means -- that 'cabal install some-package' inside a sandbox will sometimes reinstall -- modified add-source deps, even if they are not among the dependencies of -- 'some-package'. This can also prevent packages that depend on older -- versions of add-source'd packages from building (see #1362). maybeWithSandboxPackageInfo verbosity configFlags'' globalFlags' comp platform conf useSandbox $ \mSandboxPkgInfo -> maybeWithSandboxDirOnSearchPath useSandbox $ install verbosity (configPackageDB' configFlags'') (globalRepos globalFlags') comp platform conf' useSandbox mSandboxPkgInfo globalFlags' configFlags'' configExFlags' installFlags' haddockFlags' targets where -- '--run-tests' implies '--enable-tests'. maybeForceTests installFlags' configFlags' = if fromFlagOrDefault False (installRunTests installFlags') then configFlags' { configTests = toFlag True } else configFlags' testAction :: (TestFlags, BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO () testAction (testFlags, buildFlags, buildExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (testVerbosity testFlags) addConfigFlags = mempty { configTests = toFlag True } noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) buildFlags' = buildFlags { buildVerbosity = testVerbosity testFlags } checkFlags flags | fromFlagOrDefault False (configTests flags) = Nothing | otherwise = Just "Re-configuring with test suites enabled." -- reconfigure also checks if we're in a sandbox and reinstalls add-source -- deps if needed. (useSandbox, config, distPref) <- reconfigure verbosity (testDistPref testFlags) addConfigFlags [] globalFlags noAddSource (buildNumJobs buildFlags') checkFlags let setupOptions = defaultSetupScriptOptions { useDistPref = distPref } testFlags' = testFlags { testDistPref = toFlag distPref } -- the package was just configured, so the LBI must be available lbi <- getPersistBuildConfig distPref let pkgDescr = LBI.localPkgDescr lbi nameTestsOnly = LBI.foldComponent (const Nothing) (const Nothing) (\t -> if buildable (testBuildInfo t) then Just (testName t) else Nothing) (const Nothing) tests = mapMaybe nameTestsOnly $ LBI.pkgComponents pkgDescr extraArgs' | null extraArgs = tests | otherwise = extraArgs if null tests then notice verbosity "Package has no buildable test suites." else do maybeWithSandboxDirOnSearchPath useSandbox $ build verbosity config distPref buildFlags' extraArgs' maybeWithSandboxDirOnSearchPath useSandbox $ setupWrapper verbosity setupOptions Nothing Cabal.testCommand (const testFlags') extraArgs' benchmarkAction :: (BenchmarkFlags, BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO () benchmarkAction (benchmarkFlags, buildFlags, buildExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (benchmarkVerbosity benchmarkFlags) addConfigFlags = mempty { configBenchmarks = toFlag True } buildFlags' = buildFlags { buildVerbosity = benchmarkVerbosity benchmarkFlags } checkFlags flags | fromFlagOrDefault False (configBenchmarks flags) = Nothing | otherwise = Just "Re-configuring with benchmarks enabled." noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) -- reconfigure also checks if we're in a sandbox and reinstalls add-source -- deps if needed. (useSandbox, config, distPref) <- reconfigure verbosity (benchmarkDistPref benchmarkFlags) addConfigFlags [] globalFlags noAddSource (buildNumJobs buildFlags') checkFlags let setupOptions = defaultSetupScriptOptions { useDistPref = distPref } benchmarkFlags'= benchmarkFlags { benchmarkDistPref = toFlag distPref } -- the package was just configured, so the LBI must be available lbi <- getPersistBuildConfig distPref let pkgDescr = LBI.localPkgDescr lbi nameBenchsOnly = LBI.foldComponent (const Nothing) (const Nothing) (const Nothing) (\b -> if buildable (benchmarkBuildInfo b) then Just (benchmarkName b) else Nothing) benchs = mapMaybe nameBenchsOnly $ LBI.pkgComponents pkgDescr extraArgs' | null extraArgs = benchs | otherwise = extraArgs if null benchs then notice verbosity "Package has no buildable benchmarks." else do maybeWithSandboxDirOnSearchPath useSandbox $ build verbosity config distPref buildFlags' extraArgs' maybeWithSandboxDirOnSearchPath useSandbox $ setupWrapper verbosity setupOptions Nothing Cabal.benchmarkCommand (const benchmarkFlags') extraArgs' haddockAction :: HaddockFlags -> [String] -> GlobalFlags -> IO () haddockAction haddockFlags extraArgs globalFlags = do let verbosity = fromFlag (haddockVerbosity haddockFlags) (_useSandbox, config, distPref) <- reconfigure verbosity (haddockDistPref haddockFlags) mempty [] globalFlags DontSkipAddSourceDepsCheck NoFlag (const Nothing) let haddockFlags' = defaultHaddockFlags `mappend` savedHaddockFlags config `mappend` haddockFlags { haddockDistPref = toFlag distPref } setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref } setupWrapper verbosity setupScriptOptions Nothing haddockCommand (const haddockFlags') extraArgs cleanAction :: CleanFlags -> [String] -> GlobalFlags -> IO () cleanAction cleanFlags extraArgs globalFlags = do (_, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config (cleanDistPref cleanFlags) let setupScriptOptions = defaultSetupScriptOptions { useDistPref = distPref , useWin32CleanHack = True } cleanFlags' = cleanFlags { cleanDistPref = toFlag distPref } setupWrapper verbosity setupScriptOptions Nothing cleanCommand (const cleanFlags') extraArgs where verbosity = fromFlagOrDefault normal (cleanVerbosity cleanFlags) listAction :: ListFlags -> [String] -> GlobalFlags -> IO () listAction listFlags extraArgs globalFlags = do let verbosity = fromFlag (listVerbosity listFlags) (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let configFlags' = savedConfigureFlags config configFlags = configFlags' { configPackageDBs = configPackageDBs configFlags' `mappend` listPackageDBs listFlags } globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, _, conf) <- configCompilerAux' configFlags List.list verbosity (configPackageDB' configFlags) (globalRepos globalFlags') comp conf listFlags extraArgs infoAction :: InfoFlags -> [String] -> GlobalFlags -> IO () infoAction infoFlags extraArgs globalFlags = do let verbosity = fromFlag (infoVerbosity infoFlags) targets <- readUserTargets verbosity extraArgs (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let configFlags' = savedConfigureFlags config configFlags = configFlags' { configPackageDBs = configPackageDBs configFlags' `mappend` infoPackageDBs infoFlags } globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, _, conf) <- configCompilerAuxEx configFlags List.info verbosity (configPackageDB' configFlags) (globalRepos globalFlags') comp conf globalFlags' infoFlags targets updateAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO () updateAction verbosityFlag extraArgs globalFlags = do unless (null extraArgs) $ die $ "'update' doesn't take any extra arguments: " ++ unwords extraArgs let verbosity = fromFlag verbosityFlag (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let globalFlags' = savedGlobalFlags config `mappend` globalFlags transport <- configureTransport verbosity (flagToMaybe (globalHttpTransport globalFlags')) update transport verbosity (globalRepos globalFlags') upgradeAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags) -> [String] -> GlobalFlags -> IO () upgradeAction _ _ _ = die $ "Use the 'cabal install' command instead of 'cabal upgrade'.\n" ++ "You can install the latest version of a package using 'cabal install'. " ++ "The 'cabal upgrade' command has been removed because people found it " ++ "confusing and it often led to broken packages.\n" ++ "If you want the old upgrade behaviour then use the install command " ++ "with the --upgrade-dependencies flag (but check first with --dry-run " ++ "to see what would happen). This will try to pick the latest versions " ++ "of all dependencies, rather than the usual behaviour of trying to pick " ++ "installed versions of all dependencies. If you do use " ++ "--upgrade-dependencies, it is recommended that you do not upgrade core " ++ "packages (e.g. by using appropriate --constraint= flags)." fetchAction :: FetchFlags -> [String] -> GlobalFlags -> IO () fetchAction fetchFlags extraArgs globalFlags = do let verbosity = fromFlag (fetchVerbosity fetchFlags) targets <- readUserTargets verbosity extraArgs config <- loadConfig verbosity (globalConfigFile globalFlags) let configFlags = savedConfigureFlags config globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, platform, conf) <- configCompilerAux' configFlags fetch verbosity (configPackageDB' configFlags) (globalRepos globalFlags') comp platform conf globalFlags' fetchFlags targets freezeAction :: FreezeFlags -> [String] -> GlobalFlags -> IO () freezeAction freezeFlags _extraArgs globalFlags = do let verbosity = fromFlag (freezeVerbosity freezeFlags) (useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags let configFlags = savedConfigureFlags config globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, platform, conf) <- configCompilerAux' configFlags maybeWithSandboxPackageInfo verbosity configFlags globalFlags' comp platform conf useSandbox $ \mSandboxPkgInfo -> maybeWithSandboxDirOnSearchPath useSandbox $ freeze verbosity (configPackageDB' configFlags) (globalRepos globalFlags') comp platform conf mSandboxPkgInfo globalFlags' freezeFlags uploadAction :: UploadFlags -> [String] -> GlobalFlags -> IO () uploadAction uploadFlags extraArgs globalFlags = do let verbosity = fromFlag (uploadVerbosity uploadFlags) config <- loadConfig verbosity (globalConfigFile globalFlags) let uploadFlags' = savedUploadFlags config `mappend` uploadFlags globalFlags' = savedGlobalFlags config `mappend` globalFlags tarfiles = extraArgs checkTarFiles extraArgs maybe_password <- case uploadPasswordCmd uploadFlags' of Flag (xs:xss) -> Just . Password <$> getProgramInvocationOutput verbosity (simpleProgramInvocation xs xss) _ -> pure $ flagToMaybe $ uploadPassword uploadFlags' transport <- configureTransport verbosity (flagToMaybe (globalHttpTransport globalFlags')) if fromFlag (uploadCheck uploadFlags') then Upload.check transport verbosity tarfiles else upload transport verbosity (globalRepos globalFlags') (flagToMaybe $ uploadUsername uploadFlags') maybe_password tarfiles where checkTarFiles tarfiles | null tarfiles = die "the 'upload' command expects one or more .tar.gz packages." | not (null otherFiles) = die $ "the 'upload' command expects only .tar.gz packages: " ++ intercalate ", " otherFiles | otherwise = sequence_ [ do exists <- doesFileExist tarfile unless exists $ die $ "file not found: " ++ tarfile | tarfile <- tarfiles ] where otherFiles = filter (not . isTarGzFile) tarfiles isTarGzFile file = case splitExtension file of (file', ".gz") -> takeExtension file' == ".tar" _ -> False checkAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO () checkAction verbosityFlag extraArgs _globalFlags = do unless (null extraArgs) $ die $ "'check' doesn't take any extra arguments: " ++ unwords extraArgs allOk <- Check.check (fromFlag verbosityFlag) unless allOk exitFailure formatAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO () formatAction verbosityFlag extraArgs _globalFlags = do let verbosity = fromFlag verbosityFlag path <- case extraArgs of [] -> do cwd <- getCurrentDirectory tryFindPackageDesc cwd (p:_) -> return p pkgDesc <- readPackageDescription verbosity path -- Uses 'writeFileAtomic' under the hood. writeGenericPackageDescription path pkgDesc uninstallAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO () uninstallAction _verbosityFlag extraArgs _globalFlags = do let package = case extraArgs of p:_ -> p _ -> "PACKAGE_NAME" die $ "This version of 'cabal-install' does not support the 'uninstall' operation. " ++ "It will likely be implemented at some point in the future; in the meantime " ++ "you're advised to use either 'ghc-pkg unregister " ++ package ++ "' or " ++ "'cabal sandbox hc-pkg -- unregister " ++ package ++ "'." sdistAction :: (SDistFlags, SDistExFlags) -> [String] -> GlobalFlags -> IO () sdistAction (sdistFlags, sdistExFlags) extraArgs globalFlags = do unless (null extraArgs) $ die $ "'sdist' doesn't take any extra arguments: " ++ unwords extraArgs let verbosity = fromFlag (sDistVerbosity sdistFlags) (_, config) <- loadConfigOrSandboxConfig verbosity globalFlags distPref <- findSavedDistPref config (sDistDistPref sdistFlags) let sdistFlags' = sdistFlags { sDistDistPref = toFlag distPref } sdist sdistFlags' sdistExFlags reportAction :: ReportFlags -> [String] -> GlobalFlags -> IO () reportAction reportFlags extraArgs globalFlags = do unless (null extraArgs) $ die $ "'report' doesn't take any extra arguments: " ++ unwords extraArgs let verbosity = fromFlag (reportVerbosity reportFlags) config <- loadConfig verbosity (globalConfigFile globalFlags) let globalFlags' = savedGlobalFlags config `mappend` globalFlags reportFlags' = savedReportFlags config `mappend` reportFlags Upload.report verbosity (globalRepos globalFlags') (flagToMaybe $ reportUsername reportFlags') (flagToMaybe $ reportPassword reportFlags') runAction :: (BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO () runAction (buildFlags, buildExFlags) extraArgs globalFlags = do let verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags) let noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck (buildOnly buildExFlags) -- reconfigure also checks if we're in a sandbox and reinstalls add-source -- deps if needed. (useSandbox, config, distPref) <- reconfigure verbosity (buildDistPref buildFlags) mempty [] globalFlags noAddSource (buildNumJobs buildFlags) (const Nothing) lbi <- getPersistBuildConfig distPref (exe, exeArgs) <- splitRunArgs verbosity lbi extraArgs maybeWithSandboxDirOnSearchPath useSandbox $ build verbosity config distPref buildFlags ["exe:" ++ exeName exe] maybeWithSandboxDirOnSearchPath useSandbox $ run verbosity lbi exe exeArgs getAction :: GetFlags -> [String] -> GlobalFlags -> IO () getAction getFlags extraArgs globalFlags = do let verbosity = fromFlag (getVerbosity getFlags) targets <- readUserTargets verbosity extraArgs (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let globalFlags' = savedGlobalFlags config `mappend` globalFlags get verbosity (globalRepos (savedGlobalFlags config)) globalFlags' getFlags targets unpackAction :: GetFlags -> [String] -> GlobalFlags -> IO () unpackAction getFlags extraArgs globalFlags = do getAction getFlags extraArgs globalFlags initAction :: InitFlags -> [String] -> GlobalFlags -> IO () initAction initFlags _extraArgs globalFlags = do let verbosity = fromFlag (initVerbosity initFlags) (_useSandbox, config) <- loadConfigOrSandboxConfig verbosity (globalFlags { globalRequireSandbox = Flag False }) let configFlags = savedConfigureFlags config let globalFlags' = savedGlobalFlags config `mappend` globalFlags (comp, _, conf) <- configCompilerAux' configFlags initCabal verbosity (configPackageDB' configFlags) (globalRepos globalFlags') comp conf initFlags sandboxAction :: SandboxFlags -> [String] -> GlobalFlags -> IO () sandboxAction sandboxFlags extraArgs globalFlags = do let verbosity = fromFlag (sandboxVerbosity sandboxFlags) case extraArgs of -- Basic sandbox commands. ["init"] -> sandboxInit verbosity sandboxFlags globalFlags ["delete"] -> sandboxDelete verbosity sandboxFlags globalFlags ("add-source":extra) -> do when (noExtraArgs extra) $ die "The 'sandbox add-source' command expects at least one argument" sandboxAddSource verbosity extra sandboxFlags globalFlags ("delete-source":extra) -> do when (noExtraArgs extra) $ die ("The 'sandbox delete-source' command expects " ++ "at least one argument") sandboxDeleteSource verbosity extra sandboxFlags globalFlags ["list-sources"] -> sandboxListSources verbosity sandboxFlags globalFlags -- More advanced commands. ("hc-pkg":extra) -> do when (noExtraArgs extra) $ die $ "The 'sandbox hc-pkg' command expects at least one argument" sandboxHcPkg verbosity sandboxFlags globalFlags extra ["buildopts"] -> die "Not implemented!" -- Hidden commands. ["dump-pkgenv"] -> dumpPackageEnvironment verbosity sandboxFlags globalFlags -- Error handling. [] -> die $ "Please specify a subcommand (see 'help sandbox')" _ -> die $ "Unknown 'sandbox' subcommand: " ++ unwords extraArgs where noExtraArgs = (<1) . length execAction :: ExecFlags -> [String] -> GlobalFlags -> IO () execAction execFlags extraArgs globalFlags = do let verbosity = fromFlag (execVerbosity execFlags) (useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags let configFlags = savedConfigureFlags config (comp, platform, conf) <- getPersistOrConfigCompiler configFlags exec verbosity useSandbox comp platform conf extraArgs userConfigAction :: UserConfigFlags -> [String] -> GlobalFlags -> IO () userConfigAction ucflags extraArgs globalFlags = do let verbosity = fromFlag (userConfigVerbosity ucflags) case extraArgs of ("diff":_) -> mapM_ putStrLn =<< userConfigDiff globalFlags ("update":_) -> userConfigUpdate verbosity globalFlags -- Error handling. [] -> die $ "Please specify a subcommand (see 'help user-config')" _ -> die $ "Unknown 'user-config' subcommand: " ++ unwords extraArgs -- | See 'Distribution.Client.Install.withWin32SelfUpgrade' for details. -- win32SelfUpgradeAction :: Win32SelfUpgradeFlags -> [String] -> GlobalFlags -> IO () win32SelfUpgradeAction selfUpgradeFlags (pid:path:_extraArgs) _globalFlags = do let verbosity = fromFlag (win32SelfUpgradeVerbosity selfUpgradeFlags) Win32SelfUpgrade.deleteOldExeFile verbosity (read pid) path win32SelfUpgradeAction _ _ _ = return () -- | Used as an entry point when cabal-install needs to invoke itself -- as a setup script. This can happen e.g. when doing parallel builds. -- actAsSetupAction :: ActAsSetupFlags -> [String] -> GlobalFlags -> IO () actAsSetupAction actAsSetupFlags args _globalFlags = let bt = fromFlag (actAsSetupBuildType actAsSetupFlags) in case bt of Simple -> Simple.defaultMainArgs args Configure -> Simple.defaultMainWithHooksArgs Simple.autoconfUserHooks args Make -> Make.defaultMainArgs args Custom -> error "actAsSetupAction Custom" (UnknownBuildType _) -> error "actAsSetupAction UnknownBuildType"
mmakowski/cabal
cabal-install/Main.hs
Haskell
bsd-3-clause
55,596
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Spacing -- Copyright : (c) Brent Yorgey -- License : BSD-style (see LICENSE) -- -- Maintainer : <[email protected]> -- Stability : unstable -- Portability : portable -- -- Add a configurable amount of space around windows. ----------------------------------------------------------------------------- module XMonad.Layout.Spacing ( -- * Usage -- $usage spacing, Spacing, smartSpacing, SmartSpacing, ) where import Graphics.X11 (Rectangle(..)) import Control.Arrow (second) import XMonad.Util.Font (fi) import XMonad.Layout.LayoutModifier -- $usage -- You can use this module by importing it into your @~\/.xmonad\/xmonad.hs@ file: -- -- > import XMonad.Layout.Spacing -- -- and modifying your layoutHook as follows (for example): -- -- > layoutHook = spacing 2 $ Tall 1 (3/100) (1/2) -- > -- put a 2px space around every window -- -- | Surround all windows by a certain number of pixels of blank space. spacing :: Int -> l a -> ModifiedLayout Spacing l a spacing p = ModifiedLayout (Spacing p) data Spacing a = Spacing Int deriving (Show, Read) instance LayoutModifier Spacing a where pureModifier (Spacing p) _ _ wrs = (map (second $ shrinkRect p) wrs, Nothing) modifierDescription (Spacing p) = "Spacing " ++ show p shrinkRect :: Int -> Rectangle -> Rectangle shrinkRect p (Rectangle x y w h) = Rectangle (x+fi p) (y+fi p) (w-2*fi p) (h-2*fi p) -- | Surrounds all windows with blank space, except when the window is the only -- visible window on the current workspace. smartSpacing :: Int -> l a -> ModifiedLayout SmartSpacing l a smartSpacing p = ModifiedLayout (SmartSpacing p) data SmartSpacing a = SmartSpacing Int deriving (Show, Read) instance LayoutModifier SmartSpacing a where pureModifier _ _ _ [x] = ([x], Nothing) pureModifier (SmartSpacing p) _ _ wrs = (map (second $ shrinkRect p) wrs, Nothing) modifierDescription (SmartSpacing p) = "SmartSpacing " ++ show p
markus1189/xmonad-contrib-710
XMonad/Layout/Spacing.hs
Haskell
bsd-3-clause
2,275
module C1 (Tree, leaf1, branch1, branch2, isLeaf, isBranch, mkLeaf, mkBranch, myFringe, SameOrNot(..)) where data Tree a = Leaf {leaf1 :: a} | Branch {branch1 :: Tree a, branch2 :: Tree a} mkLeaf :: a -> Tree a mkLeaf = Leaf mkBranch :: (Tree a) -> (Tree a) -> Tree a mkBranch = Branch isLeaf :: (Tree a) -> Bool isLeaf (Leaf _) = True isLeaf _ = False isBranch :: (Tree a) -> Bool isBranch (Branch _ _) = True isBranch _ = False sumTree :: Num a => (Tree a) -> a sumTree p | isLeaf p = (leaf1 p) sumTree p | isBranch p = (sumTree (branch1 p)) + (sumTree (branch2 p)) myFringe :: (Tree a) -> [a] myFringe p | isLeaf p = [(leaf1 p)] myFringe p | isBranch p = myFringe (branch1 p) class SameOrNot a where isSame :: a -> a -> Bool isNotSame :: a -> a -> Bool instance SameOrNot Int where isSame a b = a == b isNotSame a b = a /= b
SAdams601/HaRe
old/testing/fromConcreteToAbstract/C1_AstOut.hs
Haskell
bsd-3-clause
958
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.GHC.IPI641 -- Copyright : (c) The University of Glasgow 2004 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- module Distribution.Simple.GHC.IPI641 ( InstalledPackageInfo(..), toCurrent, ) where import qualified Distribution.InstalledPackageInfo as Current import qualified Distribution.Package as Current hiding (installedComponentId) import Distribution.Text (display) import Distribution.Simple.GHC.IPI642 ( PackageIdentifier, convertPackageId , License, convertLicense, convertModuleName ) -- | This is the InstalledPackageInfo type used by ghc-6.4 and 6.4.1. -- -- It's here purely for the 'Read' instance so that we can read the package -- database used by those ghc versions. It is a little hacky to read the -- package db directly, but we do need the info and until ghc-6.9 there was -- no better method. -- -- In ghc-6.4.2 the format changed a bit. See "Distribution.Simple.GHC.IPI642" -- data InstalledPackageInfo = InstalledPackageInfo { package :: PackageIdentifier, license :: License, copyright :: String, maintainer :: String, author :: String, stability :: String, homepage :: String, pkgUrl :: String, description :: String, category :: String, exposed :: Bool, exposedModules :: [String], hiddenModules :: [String], importDirs :: [FilePath], libraryDirs :: [FilePath], hsLibraries :: [String], extraLibraries :: [String], includeDirs :: [FilePath], includes :: [String], depends :: [PackageIdentifier], hugsOptions :: [String], ccOptions :: [String], ldOptions :: [String], frameworkDirs :: [FilePath], frameworks :: [String], haddockInterfaces :: [FilePath], haddockHTMLs :: [FilePath] } deriving Read mkComponentId :: Current.PackageIdentifier -> Current.ComponentId mkComponentId = Current.ComponentId . display toCurrent :: InstalledPackageInfo -> Current.InstalledPackageInfo toCurrent ipi@InstalledPackageInfo{} = let pid = convertPackageId (package ipi) mkExposedModule m = Current.ExposedModule m Nothing Nothing in Current.InstalledPackageInfo { Current.sourcePackageId = pid, Current.installedComponentId = mkComponentId pid, Current.compatPackageKey = mkComponentId pid, Current.license = convertLicense (license ipi), Current.copyright = copyright ipi, Current.maintainer = maintainer ipi, Current.author = author ipi, Current.stability = stability ipi, Current.homepage = homepage ipi, Current.pkgUrl = pkgUrl ipi, Current.synopsis = "", Current.description = description ipi, Current.category = category ipi, Current.abiHash = Current.AbiHash "", Current.exposed = exposed ipi, Current.exposedModules = map (mkExposedModule . convertModuleName) (exposedModules ipi), Current.instantiatedWith = [], Current.hiddenModules = map convertModuleName (hiddenModules ipi), Current.trusted = Current.trusted Current.emptyInstalledPackageInfo, Current.importDirs = importDirs ipi, Current.libraryDirs = libraryDirs ipi, Current.dataDir = "", Current.hsLibraries = hsLibraries ipi, Current.extraLibraries = extraLibraries ipi, Current.extraGHCiLibraries = [], Current.includeDirs = includeDirs ipi, Current.includes = includes ipi, Current.depends = map (mkComponentId.convertPackageId) (depends ipi), Current.ccOptions = ccOptions ipi, Current.ldOptions = ldOptions ipi, Current.frameworkDirs = frameworkDirs ipi, Current.frameworks = frameworks ipi, Current.haddockInterfaces = haddockInterfaces ipi, Current.haddockHTMLs = haddockHTMLs ipi, Current.pkgRoot = Nothing }
randen/cabal
Cabal/Distribution/Simple/GHC/IPI641.hs
Haskell
bsd-3-clause
4,324
module Foo1 where -- Variant: ill-kinded. class XClass a where xFun :: a -> XData data XData = XCon XClass
urbanslug/ghc
testsuite/tests/typecheck/should_fail/tcfail147.hs
Haskell
bsd-3-clause
119
{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE DataKinds #-} pattern PATTERN = () wrongLift :: PATTERN wrongLift = undefined
hferreiro/replay
testsuite/tests/patsyn/should_fail/T9161-1.hs
Haskell
bsd-3-clause
126
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Database ( module Generated , js_changeVersion , changeVersion' , changeVersion , js_transaction , transaction' , transaction , js_readTransaction , readTransaction' , readTransaction ) where import Data.Maybe (fromJust, maybe) import Control.Monad.IO.Class (MonadIO(..)) import Control.Exception (Exception, bracket) import GHCJS.Types (JSVal, JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (OnBlocked(..)) import GHCJS.Marshal (fromJSVal) import GHCJS.Marshal.Pure (pToJSVal) import GHCJS.Foreign.Callback (releaseCallback) import GHCJS.DOM.Types import GHCJS.DOM.JSFFI.SQLError (throwSQLException) import GHCJS.DOM.JSFFI.Generated.SQLTransactionCallback (newSQLTransactionCallbackSync) import GHCJS.DOM.JSFFI.Generated.Database as Generated hiding (js_changeVersion, changeVersion, js_transaction, transaction, js_readTransaction, readTransaction) withSQLTransactionCallback :: (SQLTransaction -> IO ()) -> (SQLTransactionCallback -> IO a) -> IO a withSQLTransactionCallback f = bracket (newSQLTransactionCallbackSync (f . fromJust)) (\(SQLTransactionCallback c) -> releaseCallback c) foreign import javascript interruptible "$1[\"changeVersion\"]($2, $3, $4, $c, function() { $c(null); });" js_changeVersion :: Database -> JSString -> JSString -> Nullable SQLTransactionCallback -> IO (Nullable SQLError) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.changeVersion Mozilla Database.changeVersion documentation> changeVersion' :: (MonadIO m, ToJSString oldVersion, ToJSString newVersion) => Database -> oldVersion -> newVersion -> Maybe (SQLTransaction -> IO ()) -> m (Maybe SQLError) changeVersion' self oldVersion newVersion Nothing = liftIO $ nullableToMaybe <$> js_changeVersion self (toJSString oldVersion) (toJSString newVersion) (Nullable jsNull) changeVersion' self oldVersion newVersion (Just callback) = liftIO $ nullableToMaybe <$> withSQLTransactionCallback callback (js_changeVersion self (toJSString oldVersion) (toJSString newVersion) . Nullable . pToJSVal) changeVersion :: (MonadIO m, ToJSString oldVersion, ToJSString newVersion) => Database -> oldVersion -> newVersion -> Maybe (SQLTransaction -> IO ()) -> m () changeVersion self oldVersion newVersion callback = changeVersion' self oldVersion newVersion callback >>= maybe (return ()) throwSQLException foreign import javascript interruptible "$1[\"transaction\"]($2, $c, function() { $c(null); });" js_transaction :: Database -> SQLTransactionCallback -> IO (Nullable SQLError) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.transaction Mozilla Database.transaction documentation> transaction' :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m (Maybe SQLError) transaction' self callback = liftIO $ nullableToMaybe <$> withSQLTransactionCallback callback (js_transaction self) transaction :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m () transaction self callback = transaction' self callback >>= maybe (return ()) throwSQLException foreign import javascript interruptible "$1[\"readTransaction\"]($2, $c, function() { $c(null); });" js_readTransaction :: Database -> SQLTransactionCallback -> IO (Nullable SQLError) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Database.readTransaction Mozilla Database.readTransaction documentation> readTransaction' :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m (Maybe SQLError) readTransaction' self callback = liftIO $ nullableToMaybe <$> withSQLTransactionCallback callback (js_readTransaction self) readTransaction :: (MonadIO m) => Database -> (SQLTransaction -> IO ()) -> m () readTransaction self callback = readTransaction' self callback >>= maybe (return ()) throwSQLException
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Database.hs
Haskell
mit
3,935
module Main where import Control.Applicative import Control.Concurrent.Suspend import Control.Exception import Control.Monad import Data.Int (Int64) import Data.List (intersperse) import Options import Text.Printf import Sound.ALUT import System.Console.ANSI import System.Console.Readline import System.Exit (exitFailure) import System.IO main = do -- Initialise ALUT and eat any ALUT-specific commandline flags. withProgNameAndArgs runALUT $ \progName args -> do runCommand $ \opts args -> runMenuLoop opts data MainOptions = MainOptions { optAlarm :: FilePath , optPomodoro :: Int64 , optShortBreak :: Int64 , optLongBreak :: Int64 } deriving (Show, Eq, Ord) instance Options MainOptions where defineOptions = pure MainOptions <*> simpleOption "alarm" "./audio/alarm.wav" "Path to alarm sound file" <*> simpleOption "pomodoro" 25 "Pomodoro length" <*> simpleOption "shortBreak" 5 "Short break length" <*> simpleOption "longBreak" 20 "Long break length" data UserChoice = StartPomodoro | StartShortBreak | StartLongBreak | Settings | Exit | UnknownChoice deriving (Show) ------------------------------------------------------------ -- Runs inifinite loop and waits for user input ------------------------------------------------------------ runMenuLoop :: MainOptions -> IO () runMenuLoop opts = runMenu where runMenu :: IO () runMenu = do clearScreen choice <- getMenuChoice case choice of StartPomodoro -> (startPomodoro (pomodoro * 60) fileName) >> runMenu StartShortBreak -> (startShortBreak (shortBreak * 60) fileName) >> runMenu StartLongBreak -> (startLongBreak (longBreak * 60) fileName) >> runMenu Exit -> return () otherwise -> runMenu fileName = optAlarm opts pomodoro = optPomodoro opts shortBreak = optShortBreak opts longBreak = optLongBreak opts ------------------------------------------------------------ -- Draws menu and waits for user input ------------------------------------------------------------ getMenuChoice :: IO UserChoice getMenuChoice = do putStrLn "##############################" putStrLn "####### Pomodoro Timer #######" putStrLn "##############################" putStrLn "# 1 - Start pomodoro timer #" putStrLn "# 2 - Start short break #" putStrLn "# 3 - Start long break #" putStrLn "# 4 - Exit #" putStrLn "##############################" maybeLine <- readline "λ> " case maybeLine of Nothing -> return Exit Just "exit" -> return Exit Just line -> parseChoice line ------------------------------------------------------------ -- Tries to match user input to the one of main menu item. -- Returns `UnknownChoice` if fails. ------------------------------------------------------------ parseChoice :: String -> IO UserChoice parseChoice s = handle handler (return $ (read s :: UserChoice)) where handler :: NonTermination -> IO UserChoice handler e = return UnknownChoice startPomodoro :: Int64 -> FilePath -> IO () startPomodoro s fileName = do putStrLn "Pomodoro started" startTimer s playFile fileName 5 putStrLn "Pomodoro finished!" startLongBreak :: Int64 -> FilePath -> IO () startLongBreak s fileName = do putStrLn "Long break started" startTimer s playFile fileName 5 putStrLn "Long break finished!" startShortBreak :: Int64 -> FilePath -> IO () startShortBreak s fileName = do putStrLn "Short break started" startTimer s playFile fileName 5 putStrLn "Short break finished!" startTimer :: Int64 -> IO () startTimer s = do runTimer $ s * 1000 where runTimer :: Int64 -> IO () runTimer ms = if ms > 0 then do clearLine putStrLn $ formatTime ms cursorUpLine 1 suspend $ msDelay tick runTimer $ ms - tick else do putStrLn "" return () tick = 1000 :: Int64 formatTime :: Int64 -> String formatTime ms = let ss = ms `div` 1000 mm = ss `div` 60 in printf "%02d:%02d" mm (ss - mm * 60) ------------------------------------------------------------ -- Plays sound from file during `s` seconds. ------------------------------------------------------------ playFile :: FilePath -> Float -> IO () playFile fileName s = do -- Create an AL buffer from the given sound file. buf <- createBuffer (File fileName) -- Generate a single source, attach the buffer to it and start playing. source <- genObjectName buffer source $= Just buf play [source] -- Normally nothing should go wrong above, but one never knows... errs <- get alErrors unless (null errs) $ do hPutStrLn stderr (concat (intersperse "," [ d | ALError _ d <- errs ])) exitFailure sleep s stop [source] instance Read UserChoice where readsPrec _ v = case v of '1':xs -> [(StartPomodoro, xs)] '2':xs -> [(StartShortBreak, xs)] '3':xs -> [(StartLongBreak, xs)] '4':xs -> [(Exit, xs)] otherwise -> [(UnknownChoice, "")]
AZaviruha/pomodoro-cli
src/Main.hs
Haskell
mit
5,818
import Data.List.Split import qualified Data.Map as Map data Direction = N | E | S | W deriving (Show, Ord, Eq) turnMap = Map.fromList $ [ ((dirs !! i, 'L'), dirs !! ((i - 1) `mod` 4)) | i <- [0 .. 3] ] ++ [ ((dirs !! i, 'R'), dirs !! ((i + 1) `mod` 4)) | i <- [0 .. 3] ] where dirs = [N, E, S, W] move facing x y [] = (x, y) move facing x y ((turn, numSteps):ss) | facing' == N = move facing' (x + numSteps) y ss | facing' == S = move facing' (x - numSteps) y ss | facing' == E = move facing' x (y + numSteps) ss | facing' == W = move facing' x (y - numSteps) ss where facing' = turnMap Map.! (facing, turn) parseStep :: String -> (Char, Integer) parseStep (turn:numSteps) = (turn, read numSteps) main = do line <- getLine let steps = map parseStep $ splitOn ", " line let (x, y) = move N 0 0 steps print $ abs x + abs y
lzlarryli/advent_of_code_2016
day1/part1.hs
Haskell
mit
875
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Persistence.DBConnection ( loadConnection ) where import Control.Applicative import Control.Monad import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as BSL import Database.PostgreSQL.Simple instance FromJSON ConnectInfo where parseJSON (Object v) = ConnectInfo <$> v .: "host" <*> v .: "port" <*> v .: "user" <*> v .: "password" <*> v .: "dbname" parseJSON _ = mzero loadConnection :: String -> IO (Either String ConnectInfo) loadConnection file = eitherDecode <$> BSL.readFile file
ostapneko/stld2
src/main/Persistence/DBConnection.hs
Haskell
mit
761
module Group where import Data.List import Data.Maybe import GroupUtils {- Types -} type BinOp a = (a -> a -> a) type MTable a = ([a], [[a]]) data Group a = Group { set :: [a], op :: (BinOp a) } data GAction a b = GAction (Group a) [b] (a -> b -> b) instance (Show a, Eq a) => Show (Group a) where show (Group s f) = "G = {\n" ++ tableToString (groupToTable (Group s f)) 6 ++ " }" instance (Show a, Show b, Eq a, Eq b) => Show (GAction a b) where show (GAction g xs p) = "Action = {\n\n " ++ show xs ++ "\n\n G = {\n" ++ tableToString (groupToTable g) 8 ++ " }\n}" {- Construction -} isValidGroup :: Eq a => Group a -> Bool isValidGroup (Group s f) = formsGroup s f constructGroup :: Eq a => [a] -> BinOp a -> Maybe (Group a) constructGroup s f | formsGroup s f = Just (Group s f) | otherwise = Nothing isValidAction :: (Eq a, Eq b) => GAction a b -> Bool isValidAction (GAction g xs p) = formsAction g xs p constructAction :: (Eq a, Eq b) => Group a -> [b] -> (a -> b -> b) -> Maybe (GAction a b) constructAction g xs p | formsAction g xs p = Just (GAction g xs p) | otherwise = Nothing {- Basics -} one :: Eq a => Group a -> a one (Group s f) = fromJust (one_ s f) inv :: Eq a => Group a -> a -> a inv (Group s f) x = fromJust $ inv_ s f x -- | b = xax^-1 conj :: Eq a => Group a -> a -> a -> a conj (Group s f) a x = f x (f a (inv (Group s f) x)) -- | Y = xAx^-1 conjs :: Eq a => Group a -> [a] -> a -> [a] conjs g as x = [conj g a x | a <- as] conjg :: Eq a => Group a -> a -> [a] conjg g x = conjs g (set g) x order :: Eq a => Group a -> Int order (Group s f) = length s elemOrder :: Eq a => Group a -> a -> Int elemOrder (Group s f) x = go (Group s f) x 1 where go (Group s f) y acc | y == e = acc | otherwise = go (Group s f) (f y x) (acc + 1) e = one (Group s f) isAbelian :: Eq a => Group a -> Bool isAbelian g = tab == tab' where tab = snd (groupToTable g) tab' = [[l !! i | l <- tab] | i <- [0..length (head tab) - 1]] isCyclic :: Eq a => Group a -> Bool isCyclic (Group s f) = go s f where go [] f = False go (x : xs) f | elemOrder (Group s f) x == o = True | otherwise = go xs f o = order (Group s f) {- Generating -} minimalGenerator :: Eq a => Group a -> [a] minimalGenerator g = head $ minimalGeneratingSets g minimalGeneratingSets :: Eq a => Group a -> [[a]] minimalGeneratingSets (Group s f) = go 1 where go l | not (null (gener l)) = gener l | otherwise = go (l + 1) gener l = [x | x <- lenSubSets l s, setEq s (generateFromSet (Group s f) x)] generateFromSet :: Eq a => Group a -> [a] -> [a] generateFromSet (Group s f) xs = go xs where go xs | setEq nextGen xs = xs | otherwise = go nextGen where nextGen = takeCrossProduct (Group s f) (generateFromSetOnce (Group s f) xs) -- | produces wrong result generateFromSet2 :: Eq a => Group a -> [a] -> [a] generateFromSet2 (Group s f) xs = go xs where go xs | setEq nextGen xs = xs | otherwise = go nextGen where nextGen = takeCrossProduct (Group s f) xs generateFromSetOnce :: Eq a => Group a -> [a] -> [a] generateFromSetOnce (Group s f) xs = nub (foldl (++) [] [generateFrom (Group s f) x | x <- xs]) takeCrossProduct :: Eq a => Group a -> [a] -> [a] takeCrossProduct (Group s f) xs = nub [f x y | x <- xs, y <- xs] generateFrom :: Eq a => Group a -> a -> [a] generateFrom (Group s f) x = go x x where go x y | y == e = [y] | otherwise = y : go x (f x y) e = one (Group s f) {- Subgroups -} subgroups :: Eq a => Group a -> [Group a] subgroups g = go atoms where atoms = cyclicSubgroups g go xs | length xs == length nextGen = nextGen | otherwise = go nextGen where nextGen = compoSubgroups g atoms xs -- | Takes atoms and previous composites and produces cross-product-gen compoSubgroups :: Eq a => Group a -> [Group a] -> [Group a] -> [Group a] compoSubgroups g ato comp = nubSubgroups r where o = order g unions = (nubSEq [union (set a) (set c) | a <- ato, c <- comp]) constr x | o `mod` length x /= 0 = Nothing | otherwise = constructGroup x (op g) r = catMaybes (map constr generated) where generated = nubSEq (map (generateFromSet g) unions) -- | Less efficient, generates from whole cross-prod including duplicates compoSubgroups2 :: Eq a => Group a -> [Group a] -> [Group a] -> [Group a] compoSubgroups2 g ato comp = catMaybes [subgrp a c | a <- ato, c <- comp] where subgrp a c | (order g) `mod` (length subg) /= 0 = Nothing | otherwise = constructGroup subg (op g) where subg = generateFromSet g (union (set a) (set c)) cyclicSubgroups :: Eq a => Group a -> [Group a] cyclicSubgroups (Group s f) = nubSubgroups subgrps where subgrps = map fromJust ( filter isJust [constructGroup (generateFrom (Group s f) x) f | x <- s]) nubSubgroups :: Eq a => [Group a] -> [Group a] nubSubgroups subgrps = nubBy (\a b -> setEq (set a) (set b)) subgrps nubSubgroups2 :: Eq a => [Group a] -> [Group a] nubSubgroups2 subgrps = go subgrps [] where go [] ys = ys go (x : xs) ys | null [z | z <- ys, setEq (set x) (set z)] = go xs (x : ys) | otherwise = go xs ys leftCoset :: Eq a => Group a -> a -> [a] leftCoset (Group s f) g = [f g x | x <- s] -- | Group -> Subgroup leftCosets :: Eq a => Group a -> Group a -> [[a]] leftCosets g h = nubBy setEq [leftCoset h x | x <- (set g)] rightCoset :: Eq a => Group a -> a -> [a] rightCoset (Group s f) g = [f x g | x <- s] rightCosets :: Eq a => Group a -> Group a -> [[a]] rightCosets g h = nubBy setEq [rightCoset h x | x <- (set g)] -- | Group -> Subgroup isNormalSubgroup :: Eq a => Group a -> Group a -> Bool isNormalSubgroup g h = null [x | x <- (set g), not $ setEq (leftCoset h x) (rightCoset h x)] normalSubgroups :: Eq a => Group a -> [Group a] normalSubgroups g = [h | h <- subgroups g, isNormalSubgroup g h] centralizer :: Eq a => Group a -> [a] -> Group a centralizer (Group s f) as = fromJust $ constructGroup [x | x <- s, null [a | a <- as, a /= conj (Group s f) a x]] f normalizer :: Eq a => Group a -> [a] -> Group a normalizer (Group s f) as = fromJust $ constructGroup [x | x <- s, setEq as (conjs (Group s f) as x)] f center :: Eq a => Group a -> Group a center g = centralizer g (set g) {- Group action stuff -} stabilizer :: (Eq a, Eq b) => GAction a b -> b -> Group a stabilizer (GAction g xs p) a = fromJust $ constructGroup [y | y <- (set g), p y a == a] (op g) kernel :: (Eq a, Eq b) => GAction a b -> Group a kernel (GAction g xs p) = fromJust $ constructGroup [y | y <- (set g), null [x | x <- xs, x /= p y x]] (op g) {- Isomorphism -} areIsomorphic :: (Eq a, Eq b) => Group a -> Group b -> Bool areIsomorphic g1 g2 | order g1 /= order g2 = False | not $ setEq (map (elemOrder g1) (set g1)) (map (elemOrder g2) (set g2)) = False | otherwise = True {- Helper for to-be groups -} formsGroup :: Eq a => [a] -> BinOp a -> Bool formsGroup s f = ckSet && ckOne && ckInv && ckClo && ckAssGen where ckSet = not $ null s && s == nub s ckOne = isJust (one_ s f) ckInv = length (filter isJust [inv_ s f x | x <- s]) == length s ckClo = null [x | x <- s, y <- s, not $ f x y `elem` s] ckAssGen = checkAss (minimalGenerator (Group s f)) f -- | runs in O(n^3) checkAss :: Eq a => [a] -> BinOp a -> Bool checkAss s f = null xs where xs = [a | a <- s, b <- s, c <- s, f (f a b) c /= f a (f b c)] formsAction :: (Eq a, Eq b) => Group a -> [b] -> (a -> b -> b) -> Bool formsAction (Group s f) xs p = ckCo && ckId && ckCl where ckCo = null [g | g <- s, h <- s, x <- xs, p (f g h) x /= p g (p h x)] ckId = null [x | x <- xs, p (one (Group s f)) x /= x ] ckCl = null [x | g <- s, x <- xs, not $ (p g x) `elem` xs] one_ :: Eq a => [a] -> BinOp a -> Maybe a one_ s f | null xs = Nothing | otherwise = Just $ head xs where xs = [x | x <- s, f x someE == someE] someE = head s -- | slower than above one_2 :: Eq a => [a] -> BinOp a -> Maybe a one_2 s f | isNothing ind = Nothing | otherwise = Just (s !! (fromJust ind)) where ind = elemIndex s (snd (groupToTable_ s f)) inv_ :: Eq a => [a] -> BinOp a -> a -> Maybe a inv_ s f x | isNothing e || not (x `elem` s) = Nothing | otherwise = find ((== fromJust e) . (f x)) s where e = one_ s f groupToTable_ :: Eq a => [a] -> BinOp a -> MTable a groupToTable_ s f = (s, [[f a b | a <- s] | b <- s]) tableToGroup :: Eq a => MTable a -> Maybe (Group a) tableToGroup (axis, tab) = constructGroup axis (tableToFunction (axis, tab)) tableToFunction :: Eq a => MTable a -> BinOp a tableToFunction (axis, tab) = \x y -> (tab !! pos x) !! pos y where pos x = fromJust $ elemIndex x axis groupToTable :: Eq a => Group a -> MTable a groupToTable (Group s f) = groupToTable_ s f
elfeck/grouphs
src/Group.hs
Haskell
mit
9,129
module ByteString.BuildersBenchmark.Inputs where import Prelude import qualified ByteString.BuildersBenchmark.Subjects as A import qualified ByteString.BuildersBenchmark.Actions as B sized :: Int -> [ByteString] sized factor = replicate factor "abcdefg"
nikita-volkov/bytestring-builders-benchmark
library/ByteString/BuildersBenchmark/Inputs.hs
Haskell
mit
259
-- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. {-# LANGUAGE QuasiQuotes, OverloadedStrings, RecordWildCards #-} module Language.Bond.Codegen.Cpp.Apply_h (apply_h) where import System.FilePath import Prelude import Data.Text.Lazy (Text) import Text.Shakespeare.Text import Language.Bond.Syntax.Types import Language.Bond.Util import Language.Bond.Codegen.Util import Language.Bond.Codegen.TypeMapping import Language.Bond.Codegen.Cpp.ApplyOverloads import qualified Language.Bond.Codegen.Cpp.Util as CPP -- | Codegen template for generating /base_name/_apply.h containing declarations of -- <https://microsoft.github.io/bond/manual/bond_cpp.html#optimizing-build-time Apply> -- function overloads for the specified protocols. apply_h :: [Protocol] -- ^ List of protocols for which @Apply@ overloads should be generated -> Maybe String -- ^ Optional attribute to decorate function declarations -> MappingContext -> String -> [Import] -> [Declaration] -> (String, Text) apply_h protocols attribute cpp file imports declarations = ("_apply.h", [lt| #pragma once #include "#{file}_types.h" #include <bond/core/bond.h> #include <bond/stream/output_buffer.h> #{newlineSep 0 includeImport imports} #{CPP.openNamespace cpp} #{newlineSepEnd 1 (applyOverloads protocols attr semi) declarations} #{CPP.closeNamespace cpp} |]) where includeImport (Import path) = [lt|#include "#{dropExtension path}_apply.h"|] attr = optional (\a -> [lt|#{a} |]) attribute semi = [lt|;|]
upsoft/bond
compiler/src/Language/Bond/Codegen/Cpp/Apply_h.hs
Haskell
mit
1,611
-- | -- Module : CmdLineParser -- Description : Parser for command line options. -- Copyright : (c) Maximilian Nitsch, 2015 -- -- License : MIT -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- This module enables to parse command line option and put them in a -- suitable data structure. module Spellchecker.CmdLineParser ( -- * Configuration type Configuration (..) -- * Run parser , parseConfig ) where import Options.Applicative hiding (empty, value) import Data.Maybe (fromMaybe) -- | Repository for all command line options data Configuration = Configuration { inFile :: FilePath , outFile :: FilePath , corpus :: FilePath , limit :: Int , quiet :: Bool } deriving (Show) -- | Parse command line options, use default on unset options cmdLine :: Parser Configuration cmdLine = Configuration <$> strOption (short 'i' <> long "input" <> metavar "FILE" <> help "Specifies the input file.") <*> (fromMaybe "out.txt" -- Default output file <$> optional (strOption $ short 'o' <> long "output" <> metavar "FILE" <> help "Specifies the output file.")) <*> (fromMaybe "data/corpus_de.dict" -- Default dictionary file <$> optional (strOption $ short 'c' <> long "corpus" <> metavar "FILE" <> help "Specifies the word corpus.")) <*> (fromMaybe 5 -- Default limit <$> optional (option auto $ short 'l' <> long "limit" <> metavar "NUMBER" <> help "Edit distance limit.")) <*> switch (short 'q' <> long "quite" <> help "Don't ask, take always the best match.") -- | Execute the command line parser and return the configuration of the -- spellchecker. parseConfig :: IO Configuration parseConfig = execParser $ info (helper <*> cmdLine) fullDesc
Ma-Ni/haspell
lib/Spellchecker/CmdLineParser.hs
Haskell
mit
2,455
module Text.XmlTv ( Channel(..) , Program(..) , xmlToChannel , xmlToProgram , parseChannels , parsePrograms , filterChans , updateChannel , findChan , sortChans , previous , current , later ) where import Control.Monad import Data.Maybe import Text.XML.Light import Data.Time import System.Locale data Channel = Channel { cid :: String , lang :: String , name :: String , base :: String , programs :: [Program] } deriving (Show, Eq) data Program = Program { start :: UTCTime , stop :: UTCTime , title :: String , description :: String } deriving (Show, Eq) toDate :: String -> Maybe UTCTime toDate str = parseTime defaultTimeLocale "%Y%m%d%H%M%S %z" str previous, current, later :: Program -> UTCTime -> Bool previous (Program start stop _ _) now = diffUTCTime start now < 0 && diffUTCTime stop now < 0 current (Program start stop _ _) now = diffUTCTime start now < 0 && diffUTCTime stop now > 0 later (Program start stop _ _) now = diffUTCTime start now > 0 && diffUTCTime stop now > 0 xmlToChannel :: Element -> Maybe Channel xmlToChannel e = do id <- findAttr (QName "id" Nothing Nothing) e d <- findChild (QName "display-name" Nothing Nothing) e lang <- findAttr (QName "lang" Nothing Nothing) d title <- listToMaybe . map cdData . onlyText . elContent $ d b <- findChild (QName "base-url" Nothing Nothing) e base <- listToMaybe . map cdData . onlyText . elContent $ b return $ Channel id lang title base [] -- A lot of optional fields that we should parse xmlToProgram :: Element -> Maybe Program xmlToProgram e = do start <- findAttr (QName "start" Nothing Nothing) e >>= toDate stop <- findAttr (QName "stop" Nothing Nothing) e >>= toDate t <- findChild (QName "title" Nothing Nothing) e --d <- findChild (QName "desc" Nothing Nothing) e title <- listToMaybe . map cdData . onlyText . elContent $ t --desc <- listToMaybe . map cdData . onlyText . elContent $ d return (Program start stop title "") parseChannels :: String -> [Maybe Channel] parseChannels str = do case parseXMLDoc str of Just p -> let f = findElements (QName "channel" Nothing Nothing) p in map xmlToChannel f Nothing -> [] parsePrograms :: String -> [Maybe Program] parsePrograms str = do case parseXMLDoc str of Just p -> let f = findElements (QName "programme" Nothing Nothing) p in map xmlToProgram f Nothing -> [] -- Starts of by filtering empty channels and then applies another filter. filterChans :: (Channel -> Bool) -> [Maybe Channel] -> [Channel] filterChans f chans = let pure = catMaybes chans in filter f pure sortChans :: [String] -> [Channel] -> [Channel] sortChans strs chans = map (findChan chans) strs findChan :: [Channel] -> String -> Channel findChan chans str = head . filter ((==) str . name) $ chans -- takes a channel, a prefix and a fetch method; -- then etches all programs for that channel using prefix -- (often date). updateChannel :: String -> (String -> IO String) -> Channel -> IO Channel updateChannel prefix fetch c = do let url = base c ++ cid c ++ prefix tv <- liftM (catMaybes . parsePrograms) . fetch $ url return c { programs = (programs c) ++ tv}
dagle/hs-xmltv
src/Text/XmlTv.hs
Haskell
mit
3,370
{-# LANGUAGE DeriveDataTypeable #-} module Main where import Data.Map.MultiKey import Data.Typeable import Prelude hiding (lookup, null) data Record = Record { rIntKey :: Int , rStringKey :: String , rData :: String } deriving (Show, Typeable) instance MultiKeyable Record where empty = MultiKey [key rIntKey, key rStringKey] records :: [Record] records = [ Record 1 "key 1" "data 1" , Record 20 "key 20" "data 20" , Record 3 "key 3" "data 3" ] mk :: MultiKey Record mk = fromList records
jhickner/data-map-multikey
example.hs
Haskell
mit
514
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.PositionCallback (newPositionCallback, newPositionCallbackSync, newPositionCallbackAsync, PositionCallback) 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 -- | <https://developer.mozilla.org/en-US/docs/Web/API/PositionCallback Mozilla PositionCallback documentation> newPositionCallback :: (MonadIO m) => (Maybe Geoposition -> IO ()) -> m PositionCallback newPositionCallback callback = liftIO (syncCallback1 ThrowWouldBlock (\ position -> fromJSRefUnchecked position >>= \ position' -> callback position')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/PositionCallback Mozilla PositionCallback documentation> newPositionCallbackSync :: (MonadIO m) => (Maybe Geoposition -> IO ()) -> m PositionCallback newPositionCallbackSync callback = liftIO (syncCallback1 ContinueAsync (\ position -> fromJSRefUnchecked position >>= \ position' -> callback position')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/PositionCallback Mozilla PositionCallback documentation> newPositionCallbackAsync :: (MonadIO m) => (Maybe Geoposition -> IO ()) -> m PositionCallback newPositionCallbackAsync callback = liftIO (asyncCallback1 (\ position -> fromJSRefUnchecked position >>= \ position' -> callback position'))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/PositionCallback.hs
Haskell
mit
2,205
module Main where import Control.Lens import Control.Monad ( unless, when ) import Data.IORef import System.Exit ( exitFailure, exitSuccess ) import System.IO ( hPutStrLn, stderr ) import qualified Graphics.UI.GLFW as W import Graphics.Rendering.OpenGL import Graphics.Event import Graphics.RenderableItem import Graphics.Types import Graphics.Utils errorCallBack :: W.ErrorCallback errorCallBack _ desc = hPutStrLn stderr desc keyCallback :: IORef ViewerState -> W.KeyCallback keyCallback ref window key _ action mods = when (action == W.KeyState'Pressed) $ do case lookup key keyEventFunctions of Nothing -> return () Just f -> f ref mods window mouseButtonCallback :: IORef ViewerState -> W.MouseButtonCallback mouseButtonCallback ref window button state _ = do when (state == W.MouseButtonState'Pressed) $ do case lookup button mouseEventFunctions of Nothing -> return () Just f -> f ref window initialize :: String -> IORef ViewerState -> IO W.Window initialize title stateRef = do W.setErrorCallback (Just errorCallBack) successfulInit <- W.init if not successfulInit then exitFailure else do W.windowHint $ W.WindowHint'ContextVersionMajor 2 W.windowHint $ W.WindowHint'ContextVersionMinor 1 W.windowHint $ W.WindowHint'Resizable False mw <- W.createWindow width height title Nothing Nothing case mw of Nothing -> W.terminate >> exitFailure Just window -> do W.makeContextCurrent mw W.setKeyCallback window (Just $ keyCallback stateRef) W.setMouseButtonCallback window (Just $ mouseButtonCallback stateRef) initGLParams return window main :: IO () main = do stateRef <- newIORef initialViewerState w <- initialize "cghs" stateRef mainLoop stateRef w cleanup w cleanup :: W.Window -> IO () cleanup w = do W.destroyWindow w W.terminate exitSuccess mainLoop :: IORef ViewerState -> W.Window -> IO () mainLoop ref window = do close <- W.windowShouldClose window unless close $ do clear [ColorBuffer] viewerState <- readIORef ref changeTitle viewerState window renderItemList $ viewerState ^. renderList W.swapBuffers window W.pollEvents mainLoop ref window changeTitle :: ViewerState -> W.Window -> IO () changeTitle state w = do let mode = state ^. selectionMode W.setWindowTitle w $ "cghs - " ++ show mode
nyorem/cghs
viewer/Main.hs
Haskell
mit
2,592
module List3 where -- 21 insertAt :: a -> [a] -> Int -> [a] insertAt _ _ 0 = error "0 is not a valid position" insertAt elem list pos = fst split ++ [elem] ++ snd split where split = splitAt (pos - 1) list range :: Int -> Int -> [Int] range from to = [from..to]
matteosister/haskell-exercises
List3.hs
Haskell
mit
272
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html module Stratosphere.Resources.GlueTrigger where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.GlueTriggerAction import Stratosphere.ResourceProperties.GlueTriggerPredicate -- | Full data type definition for GlueTrigger. See 'glueTrigger' for a more -- convenient constructor. data GlueTrigger = GlueTrigger { _glueTriggerActions :: [GlueTriggerAction] , _glueTriggerDescription :: Maybe (Val Text) , _glueTriggerName :: Maybe (Val Text) , _glueTriggerPredicate :: Maybe GlueTriggerPredicate , _glueTriggerSchedule :: Maybe (Val Text) , _glueTriggerType :: Val Text } deriving (Show, Eq) instance ToResourceProperties GlueTrigger where toResourceProperties GlueTrigger{..} = ResourceProperties { resourcePropertiesType = "AWS::Glue::Trigger" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ (Just . ("Actions",) . toJSON) _glueTriggerActions , fmap (("Description",) . toJSON) _glueTriggerDescription , fmap (("Name",) . toJSON) _glueTriggerName , fmap (("Predicate",) . toJSON) _glueTriggerPredicate , fmap (("Schedule",) . toJSON) _glueTriggerSchedule , (Just . ("Type",) . toJSON) _glueTriggerType ] } -- | Constructor for 'GlueTrigger' containing required fields as arguments. glueTrigger :: [GlueTriggerAction] -- ^ 'gtActions' -> Val Text -- ^ 'gtType' -> GlueTrigger glueTrigger actionsarg typearg = GlueTrigger { _glueTriggerActions = actionsarg , _glueTriggerDescription = Nothing , _glueTriggerName = Nothing , _glueTriggerPredicate = Nothing , _glueTriggerSchedule = Nothing , _glueTriggerType = typearg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-actions gtActions :: Lens' GlueTrigger [GlueTriggerAction] gtActions = lens _glueTriggerActions (\s a -> s { _glueTriggerActions = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-description gtDescription :: Lens' GlueTrigger (Maybe (Val Text)) gtDescription = lens _glueTriggerDescription (\s a -> s { _glueTriggerDescription = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-name gtName :: Lens' GlueTrigger (Maybe (Val Text)) gtName = lens _glueTriggerName (\s a -> s { _glueTriggerName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-predicate gtPredicate :: Lens' GlueTrigger (Maybe GlueTriggerPredicate) gtPredicate = lens _glueTriggerPredicate (\s a -> s { _glueTriggerPredicate = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-schedule gtSchedule :: Lens' GlueTrigger (Maybe (Val Text)) gtSchedule = lens _glueTriggerSchedule (\s a -> s { _glueTriggerSchedule = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-type gtType :: Lens' GlueTrigger (Val Text) gtType = lens _glueTriggerType (\s a -> s { _glueTriggerType = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/GlueTrigger.hs
Haskell
mit
3,424
{- MainTestSuite.hs Copyright 2014 Sebastien Soudan 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. -} module Main ( main ) where import qualified AVLTreeTest import qualified BSTreeTest import qualified BatchedQueueTest import qualified BatchedDequeueTest import qualified LeftistHeapTest import qualified BinomialHeapTest import qualified RDGTest import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.Framework.Options main :: IO () main = defaultMain tests tests :: [Test] tests = [ testGroup "AVLTree: simple" [ testProperty "insert" AVLTreeTest.prop_test --, testProperty "rotations" prop_rotations , testProperty "insert - Integer" AVLTreeTest.prop_insert_integer , testProperty "insert - Float" AVLTreeTest.prop_insert_float ] , testGroup "AVLTree: complex" [ testProperty "Height" AVLTreeTest.prop_height , testProperty "Balance factor" AVLTreeTest.prop_bf , testProperty "Sort" AVLTreeTest.prop_sort ] , testGroup "BSTree: simple" [ testProperty "insert" BSTreeTest.prop_test , testProperty "insert - Integer" BSTreeTest.prop_insert_integer , testProperty "insert - Float" BSTreeTest.prop_insert_float ] , testGroup "BSTree: complex" [ testProperty "Sort" BSTreeTest.prop_sort ] , testGroup "BatchedQueue: simple" [ testProperty "insert" BatchedQueueTest.prop_test , testProperty "build" BatchedQueueTest.prop_build , testProperty "empty isEmpty" BatchedQueueTest.prop_empty , testProperty "head - tail" BatchedQueueTest.prop_head_tail ] , testGroup "BatchedDequeue: simple" [ testProperty "insert" BatchedDequeueTest.prop_test , testProperty "build" BatchedDequeueTest.prop_build , testProperty "empty isEmpty" BatchedDequeueTest.prop_empty , testProperty "head - tail" BatchedDequeueTest.prop_head_tail ] , testGroup "LeftistHeap: simple" [ testProperty "empty isEmpty" LeftistHeapTest.prop_empty , testProperty "findMin" (LeftistHeapTest.prop_findMin :: [Int] -> Bool) , testProperty "merge - findMin" (LeftistHeapTest.prop_merge_findMin :: [Int] -> [Int] -> Bool) , testProperty "deleteMin" (LeftistHeapTest.prop_deleteMin :: [Int] -> Bool) , testProperty "insert" (LeftistHeapTest.prop_insert_not_empty :: [Int] -> Bool) , testProperty "P1" (LeftistHeapTest.prop_P1 :: [Int] -> Bool) ] , testGroup "SavedMinBinomialHeap: simple" [ testProperty "empty isEmpty" BinomialHeapTest.prop_empty , testProperty "findMin" (BinomialHeapTest.prop_findMin :: [Int] -> Bool) , testProperty "merge - findMin" (BinomialHeapTest.prop_merge_findMin :: [Int] -> [Int] -> Bool) , testProperty "deleteMin" (BinomialHeapTest.prop_deleteMin :: [Int] -> Bool) , testProperty "insert" (BinomialHeapTest.prop_insert_not_empty :: [Int] -> Bool) , testProperty "P1" (BinomialHeapTest.prop_P1 :: [Int] -> Bool) , testProperty "P2" (BinomialHeapTest.prop_P2 :: [Int] -> Bool) ] , testGroup "RDG: simple" [ testProperty "empty graph isEmpty" RDGTest.prop_empty , testProperty "connectedComp graph works" RDGTest.prop_cc , testProperty "connectedComp (2) graph works" RDGTest.prop_cc2 ] ]
ssoudan/hsStruct
test/MainTestSuite.hs
Haskell
apache-2.0
4,122
{-# LANGUAGE OverloadedStrings #-} module Salesforce.HTTP ( showRequest , showResponse ) where import Control.Monad (when, unless) import Control.Monad.Writer (MonadWriter(..), execWriter) import Data.ByteString.Lazy (ByteString) import Data.CaseInsensitive (original) import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy.Char8 as LB8 import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as LT import qualified Data.Text.Encoding as TE import qualified Data.Text.Lazy.Encoding as LTE import Network.HTTP.Client (getUri) import Network.HTTP.Conduit as HTTP ( Request(..), method, requestHeaders, requestBody , RequestBody(..) , Response(..), responseBody ) import Network.HTTP.Types.Header (Header) import Network.HTTP.Types.Status (Status(..)) showRequest :: Request -> Text showRequest x = T.concat . execWriter $ do tell [ "Request {", TE.decodeUtf8 $ method x, " ", T.pack $ show (getUri x) ] let headers = requestHeaders x when (headers /= []) $ tell [ " headers=[", T.intercalate ", " $ map showHeader headers, "]" ] let body = requestBody x unless (requestBodyIsEmpty body) $ tell [ " body=", showRequestBody body ] tell [ "}" ] where requestBodyIsEmpty :: RequestBody -> Bool requestBodyIsEmpty (RequestBodyLBS b) = LB8.length b == 0 requestBodyIsEmpty (RequestBodyBS b) = B8.length b == 0 requestBodyIsEmpty (RequestBodyBuilder b _) = b == 0 requestBodyIsEmpty (RequestBodyStream b _) = b == 0 requestBodyIsEmpty _ = False showRequestBody :: RequestBody -> Text showRequestBody (RequestBodyLBS b) = LT.toStrict $ LTE.decodeUtf8 b showRequestBody (RequestBodyBS b) = TE.decodeUtf8 b showRequestBody (RequestBodyBuilder _ _) = "<builder>" showRequestBody (RequestBodyStream _ _) = "<stream>" showRequestBody (RequestBodyStreamChunked _) = "<chunked>" showResponse :: Response ByteString -> Text showResponse x = T.concat . execWriter $ do tell [ "Response {", T.pack . show . statusCode $ responseStatus x ] let headers = responseHeaders x when (headers /= []) $ tell [ " headers=[", T.intercalate ", " $ map showHeader headers, "]" ] let body = responseBody x when (body /= "") $ tell [ " body=", LT.toStrict $ LTE.decodeUtf8 body ] tell [ "}" ] showHeader :: Header -> Text showHeader h = T.concat [ TE.decodeUtf8 $ original $ fst h, ": ", TE.decodeUtf8 $ snd h ]
VictorDenisov/salesforce
src/Salesforce/HTTP.hs
Haskell
apache-2.0
2,496
module Commands (commandMap) where import Control.Applicative import qualified Data.Map as Map import qualified Data.Set as Set import System.Exit import System.Directory import Types import CSVmail import Tools -- Map that list the commands key and the corresponding function. It is the -- public interface commandMap :: CommandMap commandMap = Map.fromList [("help", help) ,("exit", \_ _ -> putStrLn "goodbye" >> exitSuccess) ,("listtags", listtags) ,("load", load) ,("diff", diff) ,("printall", printall) ,("print", printtag) ] -- Help string. `unlines` add a trailing \n and `init` removes it help :: EStatus -> [String] -> IO EStatus help status _ = putStr helpStr >> return status where helpStr = unlines ["Welcome to `emails_compare`." ,"I guess that you want to know how I work, right?" ,"Available commands:" ," + help: print this help" ," + load tag filename: load all the email addresses from" ," file *name* and attach them to *tag* keyword." ," Existing tags will be silently overwritten." ," + diff tag1 tag2: show the emails that are in *tag1*" ," but not in *tag2*" ," + listtags: list the tags already present" ," + printall: print the full dictionary" ," + print tag: print the content of tag" ," + exit: exit the program" ] -- Lists the tags in the status dictionary listtags :: EStatus -> [String] -> IO EStatus listtags status _ = putStrLn (message keys) >> return status where keys = unlines $ map (\(n, k) -> (show n) ++ ": " ++ k) numKey numKey = zip [1 ..] $ Map.keys $ fromEStatus status message "" = "No tag found" message xs = "The available tags are:\n" ++ init xs -- read the input file and store its emails into the status load :: EStatus -> [String] -> IO EStatus load status (tag:filename:[]) = loadifFile status tag filename load status (tag:filename:_) = putStrLn msg >> load status (tag:filename:[]) where msg = unwords ["The command is 'load tag filename'." ,"Anything else is ignored" ] load status _ = putStrLn "The command is too short. The correct one is 'load tag filename'" >> return status -- if the file exists, read it and update the status. Otherwise print a warning -- and return the original status loadifFile :: EStatus -> Tag -> FilePath -> IO EStatus loadifFile s t fn = doesFileExist fn >>= loadIfExist where loadIfExist b = if b then loadFile s t fn else putStrLn ("'" ++ fn ++ "' does not exists") >> return s -- Now we are sure that the file exists: go ahead loadFile :: EStatus -> Tag -> FilePath -> IO EStatus loadFile s t fn = pure (esInsert t) <*> emails <*> (return s) where emails = readFile fn >>= (\s' -> return (csv2eMails s')) -- get the difference between the sets attached to two tags diff :: EStatus -> [String] -> IO EStatus diff status (tag1:tag2:[]) = putStrLn (pureDiff status tag1 tag2) >> return status diff status (tag1:tag2:_) = putStrLn msg >> diff status (tag1:tag2:[]) where msg = unwords ["The command is 'diff tag1 tag2'." ,"Anything else is ignored" ] diff status _ = putStrLn "The command is too short. The correct one is 'diff tag1 tag2'" >> return status pureDiff :: EStatus -> Tag -> Tag -> String pureDiff status tag1 tag2 = case doDiff status tag1 tag2 of Just set -> pplist (Set.toList set) "" Nothing -> "One of the tags does not exist" doDiff :: EStatus -> Tag -> Tag -> Maybe (Set.Set EMail) doDiff status t1 t2 = pure Set.difference <*> mapLookup t1 <*> mapLookup t2 where mapLookup k = Map.lookup k $ fromEStatus status -- print the whole dictionary printall :: EStatus -> [String] -> IO EStatus printall status [] = putStrLn msg >> return status where ppmsg = ppEStatus status msg = if null ppmsg then "No entries found" else ppmsg -- print the content of a single tag printtag :: EStatus -> [String] -> IO EStatus printtag status (tag:[]) = putStrLn ppstr >> return status where ppstr = case Map.lookup tag (fromEStatus status) of Just set -> pplist (Set.toList set) "" Nothing -> "The tag '" ++ tag ++ "' does not exist" printtag status (tag:_) = putStrLn msg >> printtag status (tag:[]) where msg = unwords ["The command is 'printtag tag'." ,"Anything else is ignored" ] printtag status _ = putStrLn "The command is too short. The correct one is 'printtag tag'" >> return status
montefra/email_compare
src/Commands.hs
Haskell
bsd-2-clause
5,924
-- http://www.codewars.com/kata/52f787eb172a8b4ae1000a34 module Zeros where zeros :: Int -> Int zeros 0 = 0 zeros n = sum . tail . takeWhile (>0) . iterate (`div`5) $ n
Bodigrim/katas
src/haskell/5-Number-of-trailing-zeros-of-N.hs
Haskell
bsd-2-clause
169
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module Database.Narc.AST.Pretty where import Database.Narc.AST import Database.Narc.Pretty import Database.Narc.Util (mapstrcat) -- Pretty-printing ------------------------------------------------===== instance Pretty (Term' a) where pretty (Unit) = "()" pretty (Bool b) = show b pretty (Num n) = show n pretty (String s) = show s pretty (PrimApp f args) = f ++ "(" ++ mapstrcat "," pretty args ++ ")" pretty (Var x) = x pretty (Abs x n) = "(fun " ++ x ++ " -> " ++ pretty n ++ ")" pretty (App l m) = pretty l ++ " " ++ pretty m pretty (Table tbl t) = "(table " ++ tbl ++ " : " ++ show t ++ ")" pretty (If c a b) = "(if " ++ pretty c ++ " then " ++ pretty a ++ " else " ++ pretty b ++ " )" pretty (Singleton m) = "[" ++ pretty m ++ "]" pretty (Nil) = "[]" pretty (Union m n) = "(" ++ pretty m ++ " ++ " ++ pretty n ++ ")" pretty (Record fields) = "{" ++ mapstrcat "," (\(l,m) -> l ++ "=" ++ pretty m) fields ++ "}" pretty (Project m l) = "(" ++ pretty m ++ "." ++ l ++ ")" pretty (Comp x m n) = "(for (" ++ x ++ " <- " ++ pretty m ++ ") " ++ pretty n ++ ")" instance Pretty (Term a) where pretty (m, _anno) = pretty m
ezrakilty/narc
Database/Narc/AST/Pretty.hs
Haskell
bsd-2-clause
1,241
module Evaluator.Deeds where import Data.List import StaticFlags import Utilities import Data.Ord (comparing) -- | Number of unclaimed deeds. Invariant: always greater than or equal to 0 type Unclaimed = Int -- | A deed supply shared amongst all expressions type Deeds = Int -- NB: it is OK if the number of deeds to claim is negative -- that just causes some deeds to be released claimDeeds :: Deeds -> Int -> Maybe Deeds claimDeeds deeds want = guard (not dEEDS || deeds >= want) >> return (deeds - want) -- | Splits up a number evenly across several partitions in proportions to weights given to those partitions. -- -- > sum (apportion n weights) == n -- -- Annoyingly, it is important that this works properly if n is negative as well -- these can occur -- when we have turned off deed checking. I don't care about handling negative weights. apportion :: Deeds -> [Deeds] -> [Deeds] apportion _ [] = error "apportion: empty list" apportion orig_n weighting | orig_n < 0 = map negate $ apportion (negate orig_n) weighting | otherwise = result where fracs :: [Rational] fracs = assertRender (text "apportion: must have at least one non-zero weight") (denominator /= 0) $ map (\numerator -> fromIntegral numerator / denominator) weighting where denominator = fromIntegral (sum weighting) -- Here is the idea: -- 1) Do one pass through the list of fractians -- 2) Start by allocating the floor of the number of "n" that we should allocate to this weight of the fraction -- 3) Accumulate the fractional pieces and the indexes that generated them -- 4) Use circular programming to feed the list of fractional pieces that we actually allowed the allocation -- of back in to the one pass we are doing over the list ((_, remaining, final_deserving), result) = mapAccumL go (0 :: Int, orig_n, []) fracs go (i, n, deserving) frac = ((i + 1, n - whole, (i, remainder) : deserving), whole + if i `elem` final_deserving_allowed then 1 else 0) where (whole, remainder) = properFraction (frac * fromIntegral orig_n) -- We should prefer to allocate pieces to those bits of the fraction where the error (i.e. the fractional part) is greatest. -- We cannot allocate more of these "fixup" pieces than we had "n" left at the end of the first pass. final_deserving_allowed = map fst (take remaining (sortBy (comparing (Down . snd)) final_deserving)) noChange, noGain :: Deeds -> Deeds -> Bool noChange = (==) noGain = (>=)
osa1/chsc
Evaluator/Deeds.hs
Haskell
bsd-3-clause
2,553
{-# LANGUAGE MultiParamTypeClasses #-} import Control.Monad.Chrono import Control.Monad.IO.Class newtype Pos = Pos (Int, Int, Int) deriving Show data DeltaPos = MoveX Int | MoveY Int | MoveZ Int instance Keystone Pos DeltaPos where redo (MoveX n) (Pos (x, y, z)) = Pos (x + n, y, z) redo (MoveY n) (Pos (x, y, z)) = Pos (x, y + n, z) redo (MoveZ n) (Pos (x, y, z)) = Pos (x, y, z + n) undo (MoveX n) = redo $ MoveX $ -n undo (MoveY n) = redo $ MoveY $ -n undo (MoveZ n) = redo $ MoveZ $ -n chronoExample :: ChronoT Pos DeltaPos IO () chronoExample = do step $ MoveX 10 step $ MoveY 9 step $ MoveZ 8 step $ MoveX 2 s1 <- get rewind 2 s2 <- get unwind 1 s3 <- get rewind 1 s4 <- get put $ Pos (1, 1, 1) s5 <- get unwind 2 s6 <- get liftIO $ print $ "Splices: " ++ show (s1, s2, s3, s4, s5, s6) main :: IO () main = do out <- execChronoT chronoExample $ Pos (0, 0, 0) print $ "Output: " ++ show out
kvanberendonck/monad-chrono
examples/Example.hs
Haskell
bsd-3-clause
997
-- |Load and unload MSF plugins. module MSF.Plugin ( module Types.Plugin , plugin_load , plugin_unload , plugin_loaded ) where import MSF.Monad import Types.Plugin import qualified RPC.Plugin as RPC -- | Silent operation. plugin_load :: (SilentCxt s) => PluginName -> PluginOptions -> MSF s Result plugin_load name opts = prim $ \ addr auth -> do RPC.plugin_load addr auth name opts -- | Unload a plugin, but names are not always compatible with plugin_load. Silent operation. plugin_unload :: (SilentCxt s) => PluginName -> MSF s Result plugin_unload name = prim $ \ addr auth -> do RPC.plugin_unload addr auth name -- | Enumerate loaded plugins. Silent operation. plugin_loaded :: (SilentCxt s) => MSF s Plugins plugin_loaded = prim $ \ addr auth -> do RPC.plugin_loaded addr auth
GaloisInc/msf-haskell
src/MSF/Plugin.hs
Haskell
bsd-3-clause
804
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies, MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude, OverloadedStrings, RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables, StandaloneDeriving, TemplateHaskell #-} {-# LANGUAGE TypeFamilies, QuasiQuotes #-} module FreeAgent.Core.Protocol.Schedule where import FreeAgent.AgentPrelude import FreeAgent.Core.Internal.Lenses import FreeAgent.Core.Protocol import FreeAgent.Orphans () import Control.Error (note) import Control.Monad.State (StateT) import Data.Aeson (Result (..), Value (..), fromJSON, (.:?)) import qualified Data.Aeson as A import Data.Aeson.TH (Options (..), defaultOptions, deriveJSON) import Data.Attoparsec.Text (parseOnly) import Data.Binary (Binary) import Data.Char as Char (toLower) import System.Cron import System.Cron.Parser (cronSchedule) -- ---------Types------------- -- Types -- --------------------------- data Event = Event { schedKey :: !Key , schedRecur :: !ScheduleRecurrence , schedRetry :: !RetryOption , schedModified :: !UTCTime , schedDisabled :: !Bool } deriving (Show, Eq, Typeable, Generic) data ScheduleRecurrence = RecurCron !CronSchedule !Text -- ^ execute when schedule matches | RecurInterval !Int -- ^ execute every n milliseconds | OnceAt !UTCTime deriving (Show, Eq, Typeable, Generic) cronEvent :: Text -> Either String ScheduleRecurrence cronEvent format = case parseOnly cronSchedule format of Right sched -> Right $ RecurCron sched format Left msg -> Left msg instance IsString ScheduleRecurrence where fromString format = case cronEvent (convert format) of Right cron' -> cron' _ -> error $ "Unable to parse cron formatted literal: " ++ format instance ToJSON ScheduleRecurrence where toJSON (RecurCron _ expr) = A.object ["recurCron" A..= expr] toJSON (RecurInterval num) = A.object ["recurInterval" A..= num] toJSON (OnceAt time') = A.object ["onceAt" A..= time'] instance FromJSON ScheduleRecurrence where parseJSON (Object value') = do cron <- value' .:? "recurCron" interval <- value' .:? "recurInterval" once <- value' .:? "onceAt" case cron of Just expr -> case cronEvent expr of Right recur -> return recur Left _ -> mzero Nothing -> case interval of Just i -> return (RecurInterval i) Nothing -> case once of Just jtime -> case fromJSON jtime of Error _ -> mzero Success time' -> return (OnceAt time') Nothing -> mzero parseJSON _ = mzero instance Stashable Event where key = schedKey instance Ord Event where compare ev1 ev2 = compare (key ev1) (key ev2) --TODO: implement retry logic data RetryOption = Never -- Retry N times at M interval | Fixed Int Int -- Retry N times at exponentially increasing interval -- starting from M | Exponential Int Int deriving (Show, Eq, Typeable, Generic) data ScheduleFail = SCallFailed CallFail | EventNotFound Key | SDBException !Text deriving (Show, Eq, Typeable, Generic) -- ---------API--------------- -- API -- --------------------------- -- | Helper for 'ScheduleAddEvent'; schedules an Event. Note -- that for a CronEvent, the event will run at the next matching time -- beginning one minute from now - e.g. you are scheduling something to run -- in the future, not right now. schedule :: MonadAgent agent => Key -> ScheduleRecurrence -> RetryOption -> agent (Either CallFail ()) schedule key' recur retry = callServ (ScheduleAddEvent key' recur retry) unschedule :: MonadAgent agent => Key -> agent (Either ScheduleFail ()) unschedule key' = do efail <- callServ (ScheduleRemoveEvent key') case efail of Right result' -> return result' Left failed -> return $ Left (SCallFailed failed) lookupEvent :: MonadAgent agent => Key -> agent (Either ScheduleFail Event) lookupEvent key' = do emevent <- callServ (ScheduleLookupEvent key') case emevent of Right mevent -> return $ note (EventNotFound key') mevent Left failed -> return $ Left (SCallFailed failed) type ScheduleImplM st rs = StateT st Agent rs type ScheduleImplE st rs = ScheduleImplM st (Either ScheduleFail rs) data ScheduleImpl st = ScheduleImpl { callScheduleAddEvent :: ScheduleAddEvent -> ProtoT ScheduleAddEvent st () , callScheduleEventControl :: ScheduleEventControl -> ProtoT ScheduleEventControl st () , callScheduleLookupEvent :: ScheduleLookupEvent -> ProtoT ScheduleLookupEvent st (Maybe Event) , callScheduleQueryEvents :: ScheduleQueryEvents -> ProtoT ScheduleQueryEvents st [Event] , callScheduleRemoveEvent :: ScheduleRemoveEvent -> ProtoT ScheduleRemoveEvent st (Either ScheduleFail ()) , castScheduleControl :: ScheduleControl -> ProtoT ScheduleControl st () } data ScheduleControl = ScheduleStart | ScheduleStop deriving (Show, Typeable, Generic) instance Binary ScheduleControl instance NFData ScheduleControl where rnf = genericRnf instance ServerCast ScheduleControl where type CastProtocol ScheduleControl = ScheduleImpl castName _ = serverName handle = castScheduleControl data ScheduleAddEvent = ScheduleAddEvent !Key !ScheduleRecurrence !RetryOption | ScheduleAddEvents [Event] | ScheduleAddNewerEvent !Key !ScheduleRecurrence !RetryOption !UTCTime deriving (Show, Typeable, Generic) instance Binary ScheduleAddEvent instance NFData ScheduleAddEvent where rnf = genericRnf instance ServerCall ScheduleAddEvent where type CallProtocol ScheduleAddEvent = ScheduleImpl type CallResponse ScheduleAddEvent = () callName _ = serverName respond = callScheduleAddEvent data ScheduleEventControl = ScheduleDisableEvents ![Key] | ScheduleEnableEvents ![Key] deriving (Show, Typeable, Generic) instance Binary ScheduleEventControl instance NFData ScheduleEventControl where rnf = genericRnf instance ServerCall ScheduleEventControl where type CallProtocol ScheduleEventControl = ScheduleImpl type CallResponse ScheduleEventControl = () callName _ = serverName respond = callScheduleEventControl data ScheduleQueryEvents = ScheduleQueryEvents deriving (Show, Typeable, Generic) instance Binary ScheduleQueryEvents instance NFData ScheduleQueryEvents where rnf = genericRnf instance ServerCall ScheduleQueryEvents where type CallProtocol ScheduleQueryEvents = ScheduleImpl type CallResponse ScheduleQueryEvents = [Event] callName _ = serverName respond = callScheduleQueryEvents data ScheduleLookupEvent = ScheduleLookupEvent Key deriving (Show, Typeable, Generic) instance NFData ScheduleLookupEvent where rnf = genericRnf instance Binary ScheduleLookupEvent instance ServerCall ScheduleLookupEvent where type CallProtocol ScheduleLookupEvent = ScheduleImpl type CallResponse ScheduleLookupEvent = Maybe Event callName _ = serverName respond = callScheduleLookupEvent data ScheduleRemoveEvent = ScheduleRemoveEvent Key deriving (Show, Typeable, Generic) instance Binary ScheduleRemoveEvent instance NFData ScheduleRemoveEvent where rnf = genericRnf instance ServerCall ScheduleRemoveEvent where type CallProtocol ScheduleRemoveEvent = ScheduleImpl type CallResponse ScheduleRemoveEvent = Either ScheduleFail () callName _ = serverName respond = callScheduleRemoveEvent serverName :: String serverName = "agent:schedule" deriveSerializers ''RetryOption instance Binary ScheduleFail instance NFData ScheduleFail where rnf = genericRnf instance Binary ScheduleRecurrence instance NFData ScheduleRecurrence where rnf = genericRnf deriveSafeStore ''ScheduleRecurrence instance Binary Event instance NFData Event where rnf = genericRnf -- we want to customize the JSON field names for ShellCommand -- so it looks nicer in Yaml, which may be very frequently used deriveJSON (defaultOptions {fieldLabelModifier = \field -> let (x:xs) = drop 5 field in Char.toLower x : xs }) ''Event deriveSafeStore ''Event
jeremyjh/free-agent
core/src/FreeAgent/Core/Protocol/Schedule.hs
Haskell
bsd-3-clause
9,410
{-# LANGUAGE CPP, BangPatterns #-} {-# OPTIONS_GHC -Wall -fno-warn-name-shadowing #-} module Main ( main, test {-, maxDistances -} ) where import Prelude import System.Environment import Data.Array.Accelerate as A import Data.Array.Accelerate.Interpreter -- <<Graph type Weight = Int32 type Graph = Array DIM2 Weight -- >> -- ----------------------------------------------------------------------------- -- shortestPaths -- <<shortestPaths shortestPaths :: Graph -> Graph shortestPaths g0 = run (shortestPathsAcc n (use g0)) where Z :. _ :. n = arrayShape g0 -- >> -- <<shortestPathsAcc shortestPathsAcc :: Int -> Acc Graph -> Acc Graph shortestPathsAcc n g0 = foldl1 (>->) steps g0 -- <3> where steps :: [ Acc Graph -> Acc Graph ] -- <1> steps = [ step (unit (constant k)) | k <- [0 .. n-1] ] -- <2> -- >> -- <<step step :: Acc (Scalar Int) -> Acc Graph -> Acc Graph step k g = generate (shape g) sp -- <1> where k' = the k -- <2> sp :: Exp DIM2 -> Exp Weight sp ix = let (Z :. i :. j) = unlift ix -- <3> in A.min (g ! (index2 i j)) -- <4> (g ! (index2 i k') + g ! (index2 k' j)) -- >> -- ----------------------------------------------------------------------------- -- Testing -- <<inf inf :: Weight inf = 999 -- >> testGraph :: Graph testGraph = toAdjMatrix $ [[ 0, inf, inf, 13, inf, inf], [inf, 0, inf, inf, 4, 9], [ 11, inf, 0, inf, inf, inf], [inf, 3, inf, 0, inf, 7], [ 15, 5, inf, 1, 0, inf], [ 11, inf, inf, 14, inf, 0]] -- correct result: expectedResult :: Graph expectedResult = toAdjMatrix $ [[0, 16, inf, 13, 20, 20], [19, 0, inf, 5, 4, 9], [11, 27, 0, 24, 31, 31], [18, 3, inf, 0, 7, 7], [15, 4, inf, 1, 0, 8], [11, 17, inf, 14, 21, 0] ] test :: Bool test = toList (shortestPaths testGraph) == toList expectedResult toAdjMatrix :: [[Weight]] -> Graph toAdjMatrix xs = A.fromList (Z :. k :. k) (concat xs) where k = length xs main :: IO () main = do (n:_) <- fmap (fmap read) getArgs print (run (let g :: Acc Graph g = generate (constant (Z:.n:.n) :: Exp DIM2) f f :: Exp DIM2 -> Exp Weight f ix = let i,j :: Exp Int Z:.i:.j = unlift ix in A.fromIntegral j + A.fromIntegral i * constant (Prelude.fromIntegral n) in A.foldAll (+) (constant 0) (shortestPathsAcc n g)))
mono0926/ParallelConcurrentHaskell
fwaccel.hs
Haskell
bsd-3-clause
2,783
module Applicatives where import Control.Applicative import Data.List (elemIndex) import Data.Monoid import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes added :: Maybe Integer added = (+3) <$> lookup 3 (zip [1, 2, 3] [4, 5, 6]) y' :: Maybe Integer y' = lookup 3 $ zip [1, 2, 3] [4, 5, 6] z :: Maybe Integer z = lookup 2 $ zip [1, 2, 3] [4, 5, 6] tupled :: Maybe (Integer, Integer) tupled = (,) <$> y' <*> z x :: Maybe Int x = elemIndex 3 [1..5] y :: Maybe Int y = elemIndex 4 [1..5] max' :: Int -> Int -> Int max' = max maxed :: Maybe Int maxed = max' <$> x <*> y xs = [1..3] ys = [4..6] x' :: Maybe Integer x' = lookup 3 $ zip xs ys y'' :: Maybe Integer y'' = lookup 2 $ zip xs ys summed :: Maybe Integer summed = sum <$> ((,) <$> x' <*> y'') newtype Identity a = Identity a deriving (Eq, Ord, Show) instance Functor Identity where fmap f (Identity a) = Identity $ f a instance Applicative Identity where pure = Identity (Identity f) <*> (Identity a) = Identity $ f a newtype Constant a b = Constant { getConstant :: a } deriving Show instance Functor (Constant a) where fmap _ (Constant a) = Constant a instance Monoid a => Applicative (Constant a) where pure _ = Constant mempty (Constant a) <*> (Constant b) = Constant $ a <> b validateLength :: Int -> String -> Maybe String validateLength maxLen s = if length s > maxLen then Nothing else Just s newtype Name = Name String deriving (Eq, Show) newtype Address = Address String deriving (Eq, Show) mkName :: String -> Maybe Name mkName s = Name <$> validateLength 25 s mkAddress :: String -> Maybe Address mkAddress a = Address <$> validateLength 100 a data Person = Person Name Address deriving (Eq, Show) mkPerson :: String -> String -> Maybe Person mkPerson n a = Person <$> mkName n <*> mkAddress a xx = const <$> Just "Hello" <*> pure "World" yy = (,,,) <$> Just 90 <*> Just 10 <*> Just "Tierness" <*> Just [1, 2, 3] -- Lows data Bull = Fools | Twoo deriving (Eq, Show) instance Arbitrary Bull where arbitrary = frequency [ (1, return Fools) , (1, return Twoo) ] instance Monoid Bull where mempty = Fools mappend _ _ = Fools instance EqProp Bull where (=-=) = eq -- ZipList instance Monoid a => Monoid (ZipList a) where mempty = pure mempty mappend = liftA2 mappend instance Arbitrary a => Arbitrary (ZipList a) where arbitrary = ZipList <$> arbitrary instance Arbitrary a => Arbitrary (Sum a) where arbitrary = Sum <$> arbitrary instance Eq a => EqProp (ZipList a) where (=-=) = eq -- List data List a = Nil | Cons a (List a) deriving (Eq, Show) instance Functor List where fmap _ Nil = Nil fmap f (Cons a l) = Cons (f a) (fmap f l) append :: List a -> List a -> List a append Nil ys = ys append (Cons x xs) ys = Cons x $ xs `append` ys fold :: (a -> b -> b) -> b -> List a -> b fold _ b Nil = b fold f b (Cons h t) = f h (fold f b t) concat' :: List (List a) -> List a concat' = fold append Nil flatMap :: (a -> List b) -> List a -> List b flatMap f as = concat' (fmap f as) zip' :: List a -> List b -> List (a, b) zip' Nil _ = Nil zip' _ Nil = Nil zip' (Cons x xs) (Cons y ys) = Cons (x, y) (zip' xs ys) instance Applicative List where pure a = Cons a Nil Nil <*> _ = Nil _ <*> Nil = Nil (<*>) fs as = flatMap (`fmap` as) fs instance Arbitrary a => Arbitrary (List a) where arbitrary = do a <- arbitrary elements [Nil, Cons a Nil] instance Eq a => EqProp (List a) where (=-=) = eq newtype ZipList' a = ZipList' (List a) deriving (Eq, Show) instance Functor ZipList' where fmap f (ZipList' xs) = ZipList' $ fmap f xs instance Applicative ZipList' where pure a = ZipList' $ Cons a Nil ZipList' l <*> ZipList' l' = ZipList' (fmap (\(f, x) -> f x) (zip' l l')) take' :: Int -> List a -> List a take' _ Nil = Nil take' 0 _ = Nil take' n (Cons x t) = Cons x (take' (n - 1) t) instance Eq a => EqProp (ZipList' a) where xs =-= ys = xs' `eq` ys' where xs' = let (ZipList' l) = xs in take' 3000 l ys' = let (ZipList' l) = ys in take' 3000 l instance Arbitrary a => Arbitrary (ZipList' a) where arbitrary = ZipList' <$> arbitrary -- Variations of Either data Sum' a b = First' a | Second' b deriving (Eq, Show) data Validation e a = Error' e | Success' a deriving (Eq, Show) instance Functor (Sum' a) where fmap _ (First' a) = First' a fmap f (Second' b) = Second' (f b) instance Applicative (Sum' a) where pure = Second' First' a <*> _ = First' a _ <*> First' a = First' a Second' f <*> Second' b = Second' $ f b instance (Eq a, Eq b) => EqProp (Sum' a b) where (=-=) = eq instance (Arbitrary a, Arbitrary b) => Arbitrary (Sum' a b) where arbitrary = do a <- arbitrary b <- arbitrary elements [First' a, Second' b] instance Functor (Validation e) where fmap _ (Error' e) = Error' e fmap f (Success' a) = Success' (f a) instance Monoid e => Applicative (Validation e) where pure = Success' Error' e <*> Error' e' = Error' $ e <> e' Error' e <*> _ = Error' e _ <*> Error' e = Error' e Success' f <*> Success' a = Success' $ f a instance (Eq a, Eq b) => EqProp (Validation a b) where (=-=) = eq instance (Arbitrary a, Arbitrary b) => Arbitrary (Validation a b) where arbitrary = do a <- arbitrary b <- arbitrary elements [Error' a, Success' b] ----- Chapter exercises instance (Eq a) => EqProp (Identity a) where (=-=) = eq instance Arbitrary a => Arbitrary (Identity a) where arbitrary = Identity <$> arbitrary -- Pair data Pair a = Pair a a deriving (Eq, Show) instance Functor Pair where fmap f (Pair x y) = Pair (f x) (f y) instance Applicative Pair where pure a = Pair a a (Pair f f') <*> (Pair a a') = Pair (f a) (f' a') instance Eq a => EqProp (Pair a) where (=-=) = eq instance Arbitrary a => Arbitrary (Pair a) where arbitrary = do a <- arbitrary a' <- arbitrary return $ Pair a a' -- Two data Two a b = Two a b deriving (Eq, Show) instance Functor (Two a) where fmap f (Two a b) = Two a (f b) instance (Arbitrary a, Arbitrary b) => Arbitrary (Two a b) where arbitrary = do a <- arbitrary b <- arbitrary return $ Two a b instance Monoid a => Applicative (Two a) where pure = Two mempty Two a f <*> Two a' x = Two (a <> a') (f x) instance (Eq a, Eq b) => EqProp (Two a b) where (=-=) = eq -- Four data Four a b c d = Four a b c d deriving (Eq, Show) instance Functor (Four a b c) where fmap f (Four a b c d) = Four a b c (f d) instance (Monoid a, Monoid b, Monoid c) => Applicative (Four a b c) where pure = Four mempty mempty mempty Four a b c f <*> Four a' b' c' x = Four (a <> a') (b <> b') (c <> c') (f x) instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => Arbitrary (Four a b c d) where arbitrary = do a <- arbitrary b <- arbitrary c <- arbitrary d <- arbitrary return $ Four a b c d instance (Eq a, Eq b, Eq c, Eq d) => EqProp (Four a b c d) where (=-=) = eq -- Four' data Four' a b = Four' a a a b deriving (Eq, Show) instance Functor (Four' a) where fmap f (Four' a a' a'' b) = Four' a a' a'' (f b) instance Monoid a => Applicative (Four' a) where pure = Four' mempty mempty mempty Four' a b c f <*> Four' a' b' c' x = Four' (a <> a') (b <> b') (c <> c') (f x) instance (Arbitrary a, Arbitrary b) => Arbitrary (Four' a b) where arbitrary = do a <- arbitrary a' <- arbitrary a'' <- arbitrary b <- arbitrary return $ Four' a a' a'' b instance (Eq a, Eq b) => EqProp (Four' a b) where (=-=) = eq -- Vowels stops :: String stops = "pbtdkg" vowels :: String vowels = "aeiou" combos :: [a] -> [b] -> [c] -> [(a, b, c)] combos = liftA3 (,,) main :: IO () main = do quickBatch $ monoid (ZipList [1 :: Sum Int]) quickBatch $ applicative (Cons (1 :: Int, 2 :: Int, 3 :: Int) Nil) quickBatch $ applicative (ZipList' (Cons (1 :: Int, 2 :: Int, 3 :: Int) Nil)) quickBatch $ applicative (First' (1, 2, 3) :: Sum' (Int, Int, Int) (Int, Int, Int)) quickBatch $ applicative (Error' ("a", "b", "c") :: Validation (String, String, String) (String, String, String)) quickBatch $ applicative (Identity (1 :: Int, 2 :: Int, 3 :: Int)) quickBatch $ applicative (Pair (1 :: Int, 1 :: Int, 1 :: Int) (2 :: Int, 2 :: Int, 2 :: Int)) quickBatch $ applicative (Two ("a", "b", "c") (2 :: Int, 2 :: Int, 2 :: Int)) quickBatch $ applicative (Four ("a", "b", "c") ("a", "b", "c") ("a", "b", "c") ("a", "b", "c")) quickBatch $ applicative (Four' ("a", "b", "c") ("a", "b", "c") ("a", "b", "c") ("a", "b", "c"))
vasily-kirichenko/haskell-book
src/Applicatives.hs
Haskell
bsd-3-clause
9,021
{-| Module : OpenLayersFunc Description : OpenLayers JavaScript and Haskell functions (using FFI) -} module OpenLayers.Func where import Prelude hiding (void) import JQuery import Fay.Text hiding (head, tail, map) import OpenLayers.Html import OpenLayers.Internal import OpenLayers.Types import Fay.FFI -- * NEW FUNCTION -- | new MapQuest layer newLayerMqt :: String -- ^ map type -> Object -- ^ new layer (Tile) newLayerMqt = ffi "new ol.layer.Tile({source: new ol.source.MapQuest({layer: %1})})" -- | new OpenStreetMap layer newLayerOSM :: Object -- ^ new layer (Tile) newLayerOSM = ffi "new ol.layer.Tile({source: new ol.source.OSM()})" -- | new Layer as vector newVector :: Object -- ^ vectorsource -> Opacity -- ^ opacity -> Fay Object -- ^ new layer (Vector) newVector = ffi "new ol.layer.Vector({source: %1, opacity: %2.slot1*0.01})" -- | new 'GeoFeature' ('GeoPoint' or 'GeoLine') newFeature :: GeoFeature -> Fay Object newFeature f = case f of GeoPoint p id s -> newFeaturePoint $ transformPoint p GeoLine pts id s -> newFeatureLine $ transformPoints pts _ -> error "newStyledFeature: the GeoFeature is not implemented yet" -- | new map source GeoJSON as LineString newFeatureLine :: [(Double, Double)] -- ^ input coordinates -> Fay Object newFeatureLine = ffi "new ol.source.GeoJSON({object:{'type':'Feature','geometry':{'type':'LineString','coordinates': %1}}})" -- | new map source GeoJSON as Point newFeaturePoint :: (Double, Double) -- ^ an input coordinate -> Fay Object newFeaturePoint = ffi "new ol.source.GeoJSON({object:{'type':'Feature','geometry':{'type':'Point','coordinates': %1}}})" -- | new styled 'GeoLine' newLineStyle :: GeoLineStyle -> Object newLineStyle = ffi "[new ol.style.Style({stroke: new ol.style.Stroke({color: %1.color, width: %1.width})})]" -- | new styled 'GeoPoint' newPointStyle :: GeoPointStyle -> Object newPointStyle = ffi "[new ol.style.Style({image: new ol.style.Circle({radius: %1.radius, fill: new ol.style.Fill({color:(%1.fillcolor == 'null' ? 'rgba(0,0,0,0)' : %1.fillcolor)}), stroke: %1.outcolor == 'null' ? null : new ol.style.Stroke({color: %1.outcolor, width: %1.outwidth})})})]" -- | new OpenLayers DOM binding newOlInput :: JQuery -- ^ element to bind to -> String -- ^ case (f.e. \"checked\" by Checkbox) -> Object -- ^ map object (f.e. 'getLayerByIndex 0') -> String -- ^ attribute of map object to change (f.e. \"visible\") -> Fay () -- ^ return type is void newOlInput = ffi "(new ol.dom.Input(%1[0])).bindTo(%2, %3, %4)" -- * ADD FUNCTION -- | add an event on \"singleclick\" to display pop-up with coordinates in mercator and custom projection addSingleClickEventAlertCoo :: String -- ^ EPSG-Code of custom projection (f.e. \"EPSG:4326\") -> Fay () -- ^ return type is void addSingleClickEventAlertCoo = ffi "olc.on('singleclick', function (evt) {alert(%1 + ': ' + ol.proj.transform([evt.coordinate[0], evt.coordinate[1]], 'EPSG:3857', %1) + '\\nEPSG:3857: ' + evt.coordinate)})" -- | add a layer to the map, and remove all layers before inserting (baselayer has now index 0) addBaseLayer :: MapSource -> Fay () addBaseLayer s = void $ do removeLayers addMapLayer s -- | add a MapSource to the map addMapLayer :: MapSource -> Fay () addMapLayer s | s == OSM = addLayer newLayerOSM | Prelude.any(s==)mapQuests = addLayer ( newLayerMqt $ showMapSource s) | otherwise = error ("wrong MapSource allowed is OSM and " ++ show mapQuests) -- | add a layer to the map addLayer :: Object -> Fay () addLayer = ffi "olc.addLayer(%1)" -- | add a 'GeoFeature' to a new layer to the map (first add coordinates to a new feature and then add the style and the id to this new feature, at least create a layer with the feature and add the layer to the map) addStyledFeature :: GeoFeature -- ^ input ('GeoPoint' or 'GeoLine') -> Opacity -- ^ opacity for the GeoFeature -> Fay () addStyledFeature f o = do feature <- newFeature f styleFeature feature f setFeatureId feature f vector <- newVector feature o addLayer vector -- | add more than one 'GeoFeature' to a new layer (similar to the 'addStyledFeature' function) addStyledFeatures :: [GeoFeature] -- ^ input ('GeoPoint' and/or 'GeoLine') -> Opacity -- ^ global opacity for the GeoFeatures -> Fay () addStyledFeatures f o = do features <- mapS newFeature f zipWithS styleFeature features f zipWithS setFeatureId features f vectors <- zipWithS newVector features [ o | x <- [0..(Prelude.length features)-1]] addLayer (head vectors) sources <- return $ zipWith getVectorFeatureAt ( vectors) [ 0 | x <- [0..(Prelude.length features)-1]] addFeatures (head vectors) (tail sources) -- | add an array with features to a layer addFeatures :: Object -- ^ layer -> [Object] -- ^ featurearray -> Fay () addFeatures = ffi "%1.getSource().addFeatures(%2)" -- | add a new point feature (and a new layer) by defining from HTML elements addPointFromLabels :: String -- ^ id of the HTML element for the first coordinate (element need value, must be a double, see 'Coordinate') -> String -- ^ id of the HTML element for the seconde coordinate (element need value, must be a double, see 'Coordinate') -> String -- ^ id of the HTML element for the opacity (element need value, must be an integer, see 'Opacity') -> String -- ^ id of the HTML element for the feature id (element need value, must be a positive integer, see 'OpenLayers.Types.id') -> GeoPointStyle -- ^ define the style of the feature -> Fay () -- ^ addPointFromLabels xId yId oId idId s = void $ do xinput <- selectId xId xcoor <- getVal xinput yinput <- selectId yId ycoor <- getVal yinput o <- getInputInt oId i <- getInputInt idId addStyledFeature (GeoPoint (Coordinate (toDouble xcoor) (toDouble ycoor) (Projection "EPSG:3857")) i s) (Opacity o) -- | add a map event listener (f.e. when zoom or pan) addMapWindowEvent :: String -- ^ the event trigger (f.e. \"moveend\") -> Fay JQuery -- ^ action on the event -> Fay () addMapWindowEvent = ffi "olc.on(%1, %2)" -- | add a connection between HTML and OpenLayers to manipulate layer attributes addOlDomInput :: String -- ^ id of the HTML element which triggers -> String -- ^ HTML value to trigger (f.e. \"checked\") -> String -- ^ layer attribute to manipulate (f.e. \"visible\") -> Object -- ^ layer to manipulate -> Fay () addOlDomInput id typehtml value method = void $ do element <- selectId id newOlInput element typehtml method value -- * REMOVE FUNCTION -- | remove all layers from the map removeLayers :: Fay () removeLayers = void $ do layers <- getLayers mapM removeLayer layers -- | remove a layer object (only use with layers) removeLayer :: a -- ^ layer to remove -> Fay () removeLayer = ffi "olc.removeLayer(%1)" -- * CHANGE FUNCTION -- | zoom IN and specify levels to change zoomIn :: Integer -- ^ number of zoomlevels to change -> Fay () zoomIn = ffi "olc.getView().setZoom(olc.getView().getZoom()+%1)" -- | zoom OUT and specify levels to change zoomOut :: Integer -- ^ number of zoomlevels to change -> Fay () zoomOut = ffi "olc.getView().setZoom(olc.getView().getZoom()-%1)" -- | style a feature @/after/@ creating a new feature and @/before/@ adding to a new layer (this is an internal function for 'addStyledFeature' and 'addStyledFeatures') styleFeature :: Object -- ^ the prevoiusly created new feature -> GeoFeature -- ^ the GeoFeature object of the prevoiusly created feature -> Fay () styleFeature object feature = case feature of GeoPoint p id s -> styleFeature' object $ newPointStyle s GeoLine pts id s -> styleFeature' object $ newLineStyle s _ -> error "styleFeature: the GeoFeature is not implemented" -- | style a feature FFI function styleFeature' :: Object -> Object -> Fay () styleFeature' = ffi "%1.getFeatures()[0].setStyle(%2)" -- | change the baselayer at layerindex 0 changeBaseLayer :: MapSource -- ^ new 'MapSource' for the baselayer -> Fay () changeBaseLayer s = void $ do layers <- getLayers addBaseLayer s mapS addLayer $ tail layers -- * SET FUNCTION -- | set the id of a feature, get the feature by layer and featureindex setId :: Object -- ^ layer with the requested feature -> Integer -- ^ new id for the feature ( > 0) -> Integer -- ^ index of the feature in the layer (Layer.getFeatures()[i] , i >= 0) -> Fay () setId = ffi "(%2 < 1 || %3 < 0) ? '' : %1.getSource().getFeatures()[%3].setId(%2)" -- | set the id of the first feature of the vector setFeatureId :: Object -- ^ vector -> GeoFeature -- ^ input for the id -> Fay () setFeatureId = ffi "%1.getFeatures()[0].setId(%2.id)" -- | set map center with a 'Coordinate' setCenter :: Coordinate -> Fay () setCenter c = setCenter' $ transformPoint c -- | set map center FFI function setCenter' :: (Double, Double) -> Fay () setCenter' = ffi "olc.getView().setCenter(%1)" -- | set the map center and the zoomlevel at the same time setCenterZoom :: Coordinate -- ^ center position -> Integer -- ^ zoomlevel -> Fay () -- ^ return type is void setCenterZoom c z = void $ do setCenter c setZoom z -- | set the zoomlevel of the map setZoom :: Integer -> Fay () setZoom = ffi "olc.getView().setZoom(%1)" -- * GET FUNCTION -- | get map center in requested projection with n decimal places getCenter :: Projectionlike -- ^ requested projection -> Integer -- ^ decimal places -> Fay Text getCenter proj fixed = do c <- getCenter' coordFixed (transformPointTo proj c) fixed -- | get map center FFI function getCenter' :: Fay (Double, Double) getCenter' = ffi "olc.getView().getCenter()" -- | get map zoom level getZoom :: Fay Text getZoom = ffi "olc.getView().getZoom()" -- | get an array of all layers in the map getLayers :: Fay [Object] getLayers = ffi "olc.getLayers().getArray()" -- | get a layer by index and return a object getLayerByIndex :: Integer -> Object getLayerByIndex = ffi "olc.getLayers().item(%1)" -- | get a layer by index and return a fay object getLayerByIndex' :: Integer -> Fay Object getLayerByIndex' = ffi "olc.getLayers().item(%1)" -- | get the id of a feature (<http://openlayers.org/en/v3.1.1/apidoc/ol.Feature.html OpenLayers Feature>) getFeatureId :: Object -> Integer getFeatureId = ffi "%1.getId()" -- | get a feature from a vector at index position getVectorFeatureAt :: Object -- ^ Vector -> Integer -- ^ index of vector features -> Object getVectorFeatureAt = ffi "%1.getSource().getFeatures()[%2]" -- | get the number of features in a vector getVectorFeatureLength :: Object -- ^ Vector -> Integer -- ^ number of features in vector getVectorFeatureLength = ffi "%1.getSource().getFeatures().length" -- * TRANSFORM FUNCTION -- | transform coordinates from mercator to requested projection transformPointTo :: Projectionlike -- ^ target projection -> (Double, Double) -- ^ input -> (Double, Double) -- ^ output transformPointTo = ffi "ol.proj.transform(%2, 'EPSG:3857', %1.slot1)" -- | transform 'Coordinate' to mercator (EPSG:3857) transformPoint :: Coordinate -- ^ input -> (Double, Double) -- ^ output transformPoint = ffi "ol.proj.transform([%1.x, %1.y], %1.from.slot1, 'EPSG:3857')" -- | transform 'Coordinate's to mercator (EPSG:3857) transformPoints :: [Coordinate] -> [(Double, Double)] transformPoints c = [transformPoint x | x <- c] -- * OTHER FUNCTION -- | create a Text from a tuple of doubles with fixed decimal places and seperator \",\" coordFixed :: (Double, Double) -> Integer -> Fay Text coordFixed = ffi "%1[0].toFixed(%2) + ',' + %1[1].toFixed(%2)" -- | change Text to Double toDouble :: Text -> Double toDouble = ffi "%1" -- | 'sequence' the 'map'-function mapS :: (a -> Fay b) -> [a] -> Fay [b] mapS f x = sequence (map f x) -- | 'sequence' the 'zipWith'-function zipWithS :: (a -> b -> Fay c) -> [a] -> [b] -> Fay [c] zipWithS f x y = sequence $ zipWith f x y -- zipWithS3 :: (a -> b -> c -> Fay d) -> [a] -> [b] -> [c] -> Fay [d] -- zipWithS3 f x y z = sequence $ zipWith3 f x y z
olwrapper/olwrapper
wrapper/OpenLayers/Func.hs
Haskell
bsd-3-clause
12,894
module Math.LinearRecursive.Internal.Polynomial ( Polynomial , polynomial , unPoly , fromList , toList , singleton , x , degree , evalPoly ) where import qualified Data.IntMap as IntMap import Math.LinearRecursive.Internal.Vector newtype Polynomial a = Polynomial { unPoly :: Vector a } polynomial :: Num a => Vector a -> Polynomial a polynomial = Polynomial toList :: (Eq a, Num a) => Polynomial a -> [(Int, a)] toList (Polynomial a) = IntMap.assocs (unVector a) fromList :: (Eq a, Num a) => [(Int, a)] -> Polynomial a fromList lst = polynomial (vector (IntMap.fromListWith (+) lst)) singleton :: (Eq a, Num a) => a -> Polynomial a singleton v = polynomial (vector (IntMap.singleton 0 v)) x :: (Eq a, Num a) => Polynomial a x = polynomial (vector (IntMap.singleton 1 1)) degree :: (Eq a, Num a) => Polynomial a -> Int degree p = maximum $ (-1) : map fst (toList p) evalPoly :: (Eq a, Num a) => Polynomial a -> a -> a evalPoly p v = sum [ci * v ^ i | (i, ci) <- toList p] instance (Show a, Eq a, Num a) => Show (Polynomial a) where show a = "Polynomial " ++ show (toList a) instance Eq a => Eq (Polynomial a) where Polynomial a == Polynomial b = a == b instance (Eq a, Num a) => Num (Polynomial a) where Polynomial a + Polynomial b = polynomial (a <+> b) Polynomial a - Polynomial b = polynomial (a <-> b) negate (Polynomial a) = polynomial (vmap negate a) a * b = fromList [(i + j, ai * bj) | (i, ai) <- toList a , (j, bj) <- toList b] abs = error "Polynomial : absolute value undefined" signum = error "Polynomial : signum undefined" fromInteger = singleton . fromInteger
bjin/monad-lrs
Math/LinearRecursive/Internal/Polynomial.hs
Haskell
bsd-3-clause
1,648
import System.Directory import PocParser import PocStrategy import StrategyTest -- Test GENERATE -- main :: IO () main = do --mapM_ (uncurry generateTest) genTests --plusTest --generateAllTest chooseStrategyTest -- PARSER AND PROGRAMS STUFF -- --main :: IO () --main = do -- files <- getDirectoryContents "test/basic_programs" -- mapM_ (progTest "test/basic_programs/") files -- --progTest :: FilePath -> FilePath -> IO () --progTest _ "." = return () --progTest _ ".." = return () --progTest p f = do -- program <- readFile (p++f) -- print ("Parsing " ++ (p++f)) -- let p = parseProg f program -- print p
NicolaiNebel/Bachelor-Poc
test/Spec.hs
Haskell
bsd-3-clause
624
module CallByReference.Data where import Control.Monad.Trans.State.Lazy import qualified Data.Map as M import Data.Maybe (fromMaybe) type Try = Either String type Environment = M.Map String DenotedValue empty :: Environment empty = M.empty initEnvironment :: [(String, DenotedValue)] -> Environment initEnvironment = M.fromList extend :: String -> DenotedValue -> Environment -> Environment extend = M.insert extendRec :: String -> [String] -> Expression -> Environment -> StatedTry Environment extendRec name params body = extendRecMany [(name, params, body)] extendRecMany :: [(String, [String], Expression)] -> Environment -> StatedTry Environment extendRecMany lst env = do refs <- allocMany (length lst) let denoVals = fmap DenoRef refs let names = fmap (\(n, _, _) -> n) lst let newEnv = extendMany (zip names denoVals) env extendRecMany' lst refs newEnv where extendRecMany' [] [] env = return env extendRecMany' ((name, params, body):triples) (ref:refs) env = do setRef ref (ExprProc $ Procedure params body env) extendRecMany' triples refs env allocMany 0 = return [] allocMany x = do ref <- newRef (ExprBool False) -- dummy value false for allocating space (ref:) <$> allocMany (x - 1) apply :: Environment -> String -> Maybe DenotedValue apply = flip M.lookup extendMany :: [(String, DenotedValue)] -> Environment -> Environment extendMany = flip (foldl func) where func env (var, val) = extend var val env applyForce :: Environment -> String -> DenotedValue applyForce env var = fromMaybe (error $ "Var " `mappend` var `mappend` " is not in environment!") (apply env var) newtype Ref = Ref { addr::Integer } deriving(Show, Eq) newtype Store = Store { refs::[ExpressedValue] } deriving(Show) type StatedTry = StateT Store (Either String) throwError :: String -> StatedTry a throwError msg = StateT (\s -> Left msg) initStore :: Store initStore = Store [] newRef :: ExpressedValue -> StatedTry Ref newRef val = do store <- get let refList = refs store put $ Store (val:refList) return . Ref . toInteger . length $ refList deRef :: Ref -> StatedTry ExpressedValue deRef (Ref r) = do store <- get let refList = refs store findVal r (reverse refList) where findVal 0 (x:_) = return x findVal 0 [] = throwError "Index out of bound when calling deref!" findVal i (_:xs) = findVal (i - 1) xs setRef :: Ref -> ExpressedValue -> StatedTry () setRef ref val = do store <- get let refList = refs store let i = addr ref newList <- reverse <$> setRefVal i (reverse refList) val put $ Store newList return () where setRefVal _ [] _ = throwError "Index out of bound when calling setref!" setRefVal 0 (_:xs) val = return (val:xs) setRefVal i (x:xs) val = (x:) <$> setRefVal (i - 1) xs val data Program = Prog Expression deriving (Show, Eq) data Expression = ConstExpr ExpressedValue | VarExpr String | LetExpr [(String, Expression)] Expression | BinOpExpr BinOp Expression Expression | UnaryOpExpr UnaryOp Expression | CondExpr [(Expression, Expression)] | ProcExpr [String] Expression | CallExpr Expression [Expression] | LetRecExpr [(String, [String], Expression)] Expression | BeginExpr [Expression] | AssignExpr String Expression | SetDynamicExpr String Expression Expression deriving(Show, Eq) data BinOp = Add | Sub | Mul | Div | Gt | Le | Eq deriving(Show, Eq) data UnaryOp = Minus | IsZero deriving(Show, Eq) data Procedure = Procedure [String] Expression Environment instance Show Procedure where show _ = "<procedure>" data ExpressedValue = ExprNum Integer | ExprBool Bool | ExprProc Procedure instance Show ExpressedValue where show (ExprNum i) = show i show (ExprBool b) = show b show (ExprProc p) = show p instance Eq ExpressedValue where (ExprNum i1) == (ExprNum i2) = i1 == i2 (ExprBool b1) == (ExprBool b2) = b1 == b2 _ == _ = False data DenotedValue = DenoRef Ref instance Show DenotedValue where show (DenoRef v) = show v instance Eq DenotedValue where DenoRef v1 == DenoRef v2 = v1 == v2
li-zhirui/EoplLangs
src/CallByReference/Data.hs
Haskell
bsd-3-clause
4,242
{-# LANGUAGE ExtendedDefaultRules, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, TypeFamilies, RankNTypes #-} module Web.ISO.HSX where import Data.Monoid ((<>)) import Data.Text (Text, pack, unpack) import GHCJS.Marshal.Pure (pFromJSVal) import GHCJS.Types (JSVal(..), JSString(..)) import Web.ISO.Types (Attr(Attr, Event), HTML(Element, CDATA), FormEvent(Change, Input), MouseEvent(Click), descendants) default (Text) {- HSX2HS -} genElement (d, t) a c = let c' = (concat c) in Element t {- [] -} a Nothing (descendants c') c' genEElement (d, t) a = genElement (d, t) a [] fromStringLit = pack class AsChild action c where asChild :: c -> [HTML action] instance AsChild action Text where asChild t = [CDATA True t] instance AsChild action String where asChild t = [CDATA True (pack t)] instance (parentAction ~ action) => AsChild parentAction (HTML action) where asChild t = [t] instance (parentAction ~ action) => AsChild parentAction [HTML action] where asChild t = t data KV k v = k := v class AsAttr action a where asAttr :: a -> Attr action instance AsAttr action (KV Text Text) where asAttr (k := v) = Attr k v instance AsAttr action (KV Text action) where asAttr (type' := action) = case type' of "onchange" -> Event Change (const $ pure action) "onclick" -> Event Click (const $ pure action) "oninput" -> Event Input (const $ pure action) -- "onblur" -> Event Blur (const $ pure action) _ -> error $ "unsupported event: " ++ (unpack type') {- instance AsAttr action (KV Text (JSVal -> action)) where asAttr (type' := action) = case type' of "onchange" -> Event Change (action . pFromJSVal) -- "onclick" -> Event Click action -- "oninput" -> Event Input action -- "onblur" -> Event Blur action _ -> error $ "unsupported event: " ++ (unpack type') -} {- instance AsAttr action (KV Text (IO String, (String -> action), action)) where asAttr (type' := action) = case type' of "onchange" -> Event (Change, action) "onclick" -> Event (Click, action) "oninput" -> Event (Input, action) _ -> error $ "unsupported event: " ++ (unpack type') -} instance (action' ~ action) => AsAttr action' (Attr action) where asAttr a = a
stepcut/isomaniac
Web/ISO/HSX.hs
Haskell
bsd-3-clause
2,383
{-# LANGUAGE FlexibleInstances, TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} import Control.Applicative import Data.IP import Data.Text import Data.Time import Test.Hspec import Test.HUnit import Test.Hspec.QuickCheck import Test.QuickCheck import Cloud.AWS.Lib.FromText import Cloud.AWS.Lib.ToText prop_class :: (Eq a, FromText a, ToText a) => a -> Bool prop_class a = fromText (toText a) == Just a instance Arbitrary Day where arbitrary = ModifiedJulianDay <$> arbitrary instance Arbitrary DiffTime where arbitrary = secondsToDiffTime <$> choose (0, 60*60*24-1) instance Arbitrary UTCTime where arbitrary = UTCTime <$> arbitrary <*> arbitrary instance Arbitrary IPv4 where arbitrary = toIPv4 <$> vectorOf 4 (choose (0,255)) instance Arbitrary (AddrRange IPv4) where arbitrary = makeAddrRange <$> arbitrary <*> choose (0, 32) instance Arbitrary Text where arbitrary = pack <$> arbitrary prop_mclass :: (Eq a, FromText a, ToText a) => a -> Bool prop_mclass a = fromText (toText a) == Just (Just a) testNothing :: IO () testNothing = (fromText "" :: Maybe Int) @=? Nothing testConvertNothingToUnit :: IO () testConvertNothingToUnit = fromNamedText "unit" Nothing @=? Just () data A = B | C deriving (Eq, Show) deriveToText "A" ["ab", "ac"] deriveFromText "A" ["ab", "ac"] instance Arbitrary A where arbitrary = elements [B, C] main :: IO () main = hspec $ do describe "Cloud.AWS.Lib.{FromText,ToText}" $ do prop "Int" (prop_class :: Int -> Bool) prop "Integer" (prop_class :: Integer -> Bool) prop "Double" (prop_class :: Double -> Bool) prop "Bool" (prop_class :: Bool -> Bool) prop "UTCTime" (prop_class :: UTCTime -> Bool) prop "IPv4" (prop_class :: IPv4 -> Bool) prop "AddrRange IPv4" (prop_class :: AddrRange IPv4 -> Bool) prop "Maybe Int" (prop_mclass :: Int -> Bool) it "convert Nothing" testNothing prop "deriveFromText/deriveToText" (prop_class :: A -> Bool) prop "Unit" (\t -> fromText t == Just ()) it "convert Nothing to Unit" testConvertNothingToUnit
worksap-ate/aws-sdk-text-converter
test/Spec.hs
Haskell
bsd-3-clause
2,120
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Generics.Regular.Functions -- Copyright : (c) 2010 Universiteit Utrecht -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable -- -- Summary: All of the generic functionality for regular dataypes: mapM, -- flatten, zip, equality, value generation, fold and unfold. -- Generic show ("Generics.Regular.Functions.Show"), generic read -- ("Generics.Regular.Functions.Read") and generic equality -- ("Generics.Regular.Functions.Eq") are not exported to prevent clashes -- with @Prelude@. ----------------------------------------------------------------------------- module Generics.Regular.Functions ( -- * Constructor names module Generics.Regular.Functions.ConNames, -- * Crush module Generics.Regular.Functions.Crush, -- * Generic folding module Generics.Regular.Functions.Fold, -- * Functorial map module Generics.Regular.Functions.GMap, -- * Generating values that are different on top-level module Generics.Regular.Functions.LR, -- * Zipping module Generics.Regular.Functions.Zip ) where import Generics.Regular.Functions.ConNames import Generics.Regular.Functions.Crush import Generics.Regular.Functions.Fold import Generics.Regular.Functions.GMap import Generics.Regular.Functions.LR import Generics.Regular.Functions.Zip
dreixel/regular
src/Generics/Regular/Functions.hs
Haskell
bsd-3-clause
1,626
module Jade.Jumper where import Jade.Common import qualified Jade.Decode.Coord as Coord getEnds :: Jumper -> ((Integer, Integer), (Integer, Integer)) getEnds (Jumper (Coord3 x y r)) = Coord.coord5ends (Coord5 x y r 8 0) points (Jumper (Coord3 x y r)) = [Point x y]
drhodes/jade2hdl
src/Jade/Jumper.hs
Haskell
bsd-3-clause
268
module DiceSpec ( main, spec ) where import System.Random import Test.Hspec import Test.QuickCheck import TestHelpers import Dice main :: IO () main = hspec spec spec :: Spec spec = do describe "d4" $ it "is within range" $ property $ \seed n -> let rolls = take n $ rollsOf (D4 $ mkStdGen seed) in all (`elem` [1..4]) rolls describe "d20" $ it "is within range" $ property $ \seed n -> let rolls = take n $ rollsOf (D20 $ mkStdGen seed) in all (`elem` [1..20]) rolls
camelpunch/rhascal
test/DiceSpec.hs
Haskell
bsd-3-clause
562
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Ordinal.DA.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Ordinal.DA.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "DA Tests" [ makeCorpusTest [Seal Ordinal] corpus ]
facebookincubator/duckling
tests/Duckling/Ordinal/DA/Tests.hs
Haskell
bsd-3-clause
504
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.NV.VertexProgram2Option -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.NV.VertexProgram2Option ( -- * Extension Support glGetNVVertexProgram2Option, gl_NV_vertex_program2_option, -- * Enums pattern GL_MAX_PROGRAM_CALL_DEPTH_NV, pattern GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
haskell-opengl/OpenGLRaw
src/Graphics/GL/NV/VertexProgram2Option.hs
Haskell
bsd-3-clause
731
{-# LANGUAGE OverloadedStrings #-} module HaskellStorm.Internal ( BoltIn (..) , EmitCommand (..) , Handshake (..) , PidOut (..) , SpoutIn , StormConfig (..) , StormOut (..) ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad (mzero) import Data.Aeson ((.:), (.:?), (.=), Array (..), decode, FromJSON (..), Object, object, ToJSON(..), Value(..)) import qualified Data.Aeson as A import Data.Aeson.Types (Parser) import Data.Maybe (catMaybes) import Data.Scientific (scientific) import Data.Text (Text) import Data.Vector (fromList) type StormConfig = Value type StormContext = Value type StormTuples = Array ----- data Handshake = Handshake { getConf :: StormConfig , getContext :: StormContext , getPidDir :: Text } deriving (Eq, Show) instance FromJSON Handshake where parseJSON (Object v) = Handshake <$> v .: "conf" <*> v .: "context" <*> v .: "pidDir" parseJSON _ = mzero instance ToJSON Handshake where toJSON (Handshake config context pidDir) = object [ "conf" .= toJSON config , "context" .= toJSON context , "pidDir" .= pidDir ] --- data PidOut = PidOut { getPid :: Integer } deriving (Show, Eq) instance FromJSON PidOut where parseJSON (Object v) = PidOut <$> v .: "pid" parseJSON _ = mzero instance ToJSON PidOut where toJSON (PidOut pid) = object [ "pid" .= pid ] --- data EmitCommand = EmitNext | EmitAck | EmitFail deriving (Show, Eq) instance FromJSON EmitCommand where parseJSON (A.String "next") = return EmitNext parseJSON (A.String "ack") = return EmitAck parseJSON (A.String "fail") = return EmitFail parseJSON _ = mzero instance ToJSON EmitCommand where toJSON EmitNext = A.String "next" toJSON EmitAck = A.String "ack" toJSON EmitFail = A.String "fail" --- data BoltIn = BoltIn { tupleId :: Text , boltComponent :: Text , boltStream :: Text , boltTask :: Integer , inputTuples :: StormTuples } deriving (Eq, Show) instance FromJSON BoltIn where parseJSON (Object v) = BoltIn <$> v .: "id" <*> v .: "comp" <*> v .: "stream" <*> v .: "task" <*> v .: "tuple" parseJSON _ = mzero instance ToJSON BoltIn where toJSON (BoltIn tupleId boltComponent boltStream boltTask inputTuples) = object [ "id" .= toJSON tupleId , "comp" .= toJSON boltComponent , "stream" .= toJSON boltStream , "task" .= toJSON boltTask , "tuple" .= toJSON inputTuples ] --- data StormOut = Emit { anchors :: [Text] , stream :: Maybe Text , task :: Maybe Integer , tuples :: StormTuples } | Ack { ackTupleId :: Text } | Fail { failTupleId :: Text } | Log { logMsg :: Text } deriving (Eq, Show) instance ToJSON StormOut where toJSON (Emit anchors stream task tuples) = object $ [ "anchors" .= fromList anchors , "command" .= A.String "emit" , "tuple" .= tuples ] ++ catMaybes [ ("stream" .=) . A.String <$> stream , ("task" .=) <$> (flip scientific 0) <$> task ] toJSON (Ack tupleId) = object $ [ "command" .= A.String "ack" , "id" .= A.String tupleId ] toJSON (Fail tupleId) = object $ [ "command" .= A.String "fail" , "id" .= A.String tupleId ] toJSON (Log msg) = object $ [ "command" .= A.String "log" , "msg" .= A.String msg ] --- data SpoutIn = SpoutNext | SpoutAck { spoutAckId :: Text } | SpoutFail { spoutFailId :: Text } deriving (Eq, Show) instance FromJSON SpoutIn where parseJSON (Object v) = (v .: "command") >>= (go v) where go :: Object -> Text -> Parser SpoutIn go o t = case t of "next" -> return SpoutNext "ack" -> SpoutAck <$> o .: "id" "fail" -> SpoutFail <$> o .: "id" _ -> mzero parseJSON _ = mzero
aaronlevin/pipes-storm
src/HaskellStorm/Internal.hs
Haskell
bsd-3-clause
4,546
module Interpreter (Program, run, verify, programFromText, testProgram, failingProgram ) where import Color import Evaluator import Program import qualified Data.Map as Map import Data.Maybe import qualified System.IO as System import System.Console.ANSI import System.Console.Regions import Control.Concurrent.STM import System.Console.Concurrent -- Monads we'll use import Data.Functor.Identity import Control.Monad.Trans.State import Control.Monad.Trans.Writer import Control.Monad.Trans import Control.Monad.Except type Run a = StateT ProgramState (ExceptT String IO) a runRun p = runExcept (runStateT p initialProgramState) set :: (Name, Val) -> Run () set (s,i) = state $ (\st -> let updatedCurrentEnv = Map.insert s i (currentEnv st) tailEnvs = tail $ envs st statements' = statements st outputs' = outputs st in ((), ProgramState{envs = updatedCurrentEnv : tailEnvs, statements = statements', outputs = outputs'})) exec :: Statement -> Run () exec (Assign s v) = do st <- get Right val <- return $ runEval (currentEnv st) (eval v) set (s,val) exec (Seq s0 s1) = do exec (Debug s0) >> exec (Debug s1) exec (Print e) = do st <- get Right val <- return $ runEval (currentEnv st) (eval e) put $ ProgramState{ envs = (envs st), statements = (statements st), outputs = val:(outputs st) } return () exec (If cond s0 s1) = do st <- get Right (B val) <- return $ runEval (currentEnv st) (eval cond) if val then do exec (Debug s0) else do exec (Debug s1) exec (While cond s) = do st <- get Right (B val) <- return $ runEval (currentEnv st) (eval cond) if val then do exec (Debug s) >> exec DebugTidyTree >> exec (Debug (While cond s)) else return() exec (Try s0 s1) = do catchError (exec s0) (\_ -> exec s1) exec Pass = return () exec (Debug (Seq s0 s1)) = exec (Seq s0 s1) -- Ignore this case as it's just chaining exec (Debug s) = do tick s printTree s printInstructions prompt s exec DebugTidyTree = do st <- get clearFromTree (lastStatement st) -- Executing a "program" means compiling it and then running the -- resulting Statement with an empty variable map. run :: Program -> IO () run p = do result <- runExceptT $ (runStateT (exec (compile p)) initialProgramState) case result of Right ((), _) -> return () Left exn -> System.print $ "Uncaught exception: " ++ exn -- ** Prompts ** -- Pattern match on input and first character so we can ensure the inspect command starts with a colon. -- Re-prompt if string is empty (this also prevents head input from failing because of lazy evaluation) prompt :: Statement -> Run () prompt s = do input <- liftIO $ getLine case (input, head input) of ("",_) -> prompt s ("next",_) -> exec s ("back",_) -> do stepback exec (Debug s) (_,':') -> do inspect $ tail input printHistoryInstructions historyprompt s (_,'|') -> do exec (read (tail input) :: Statement) prompt s (_,_) -> do liftIO $ putStrLn . red $ "Unknown command " ++ input printInstructions prompt s historyprompt :: Statement -> Run () historyprompt s = do input <- liftIO $ getLine case input of "done" -> do printTree s printInstructions prompt s _ -> return () -- ** Operations ** tick :: Statement -> Run () tick s = do st <- get put $ ProgramState{ envs = (currentEnv st):(envs st), statements = s:(statements st), outputs = (outputs st) } stepback :: Run () stepback = do st <- get let statement = lastStatement st put $ ProgramState{ envs = (tail $ (tail $ envs st)), statements = (tail $ (tail $ statements st)), outputs = (outputs st) } exec (Debug statement) inspect :: String -> Run () inspect v = printVarHistory v clearFromTree :: Statement -> Run () clearFromTree s = do st <- get put $ ProgramState{ envs = (envs st), statements = (tail $ statements st), outputs = (outputs st) } case s of (While _ _) -> return () _ -> clearFromTree $ lastStatement st -- ** Print operations ** printInstructions :: Run () printInstructions = liftIO $ putStrLn "Enter 'next' to proceed, 'back' to step back and ':<variablename>' to view a variable's value" printHistoryInstructions :: Run () printHistoryInstructions = liftIO $ putStrLn "Enter 'done' to return." -- Takes in next statement and prints it with the rest of the history tree printTree :: Statement -> Run () printTree s = do st <- get let statements' = tail $ statements st let list = zipWithPadding Pass ("", Null) Null (reverse statements') (Map.toList (currentEnv st)) (reverse (outputs st)) clearTerminal liftIO $ printTreeHeader liftIO $ mapM_ (putStrLn . printTreeLine) $ list liftIO $ putStrLn $ printCurrentStatement s printVarHistory :: Name -> Run() printVarHistory v = do st <- get let statements' = tail $ statements st let envs' = tail $ envs st let varhist = reverse $ map (variableFromEnv v) envs' let list = zipWithPadding Pass ("", Null) Null (reverse statements') varhist [] clearTerminal liftIO $ printTreeHeader' liftIO $ mapM_ (putStrLn . printTreeLine) $ list -- Tree header for normal tree printTreeHeader :: IO () printTreeHeader = do liftIO $ putStrLn $ "Statements" ++ (nspaces (60-10)) ++ "Variables" ++ (nspaces (60-9)) ++ "Output" liftIO $ putStrLn $ "==========" ++ (nspaces (60-10)) ++ "=========" ++ (nspaces (60-9)) ++ "======" -- Tree header for history tree printTreeHeader' :: IO () printTreeHeader' = do liftIO $ putStrLn $ "Statements" ++ (nspaces (60-10)) ++ "Value at Point of execution" liftIO $ putStrLn $ "==========" ++ (nspaces (60-10)) ++ "===========================" printTreeLine :: (Statement, (Name, Val), Val) -> String printTreeLine (s, var, val) = (cyan $ statementToString s) ++ spaces ++ (printVariable var) ++ spaces' ++ (printOutput val) where spaces = nspaces (60 - l) spaces' = nspaces (60 - l') l = length $ statementToString s l' = length $ printVariable var printCurrentStatement :: Statement -> String printCurrentStatement s = green $ "> " ++ statementToString s printVariable :: (Name, Val) -> String printVariable (_, Null) = "" printVariable (n, v) = "Variable: " ++ (blue n) ++ " Value: " ++ (blue (show v)) printOutput :: Val -> String printOutput Null = "" printOutput s = show s -- ** Utils ** variableFromEnv :: Name -> Env -> (Name, Val) variableFromEnv var env = case Map.lookup var env of Just val -> (var, val) Nothing -> ("", Null) statementToString :: Statement -> String statementToString (While cond _) = "While " ++ (show cond) ++ " do" statementToString (If cond _ _) = "If " ++ (show cond) ++ " do" statementToString Pass = "" -- Don't bother printing pass statements statementToString s = show s -- Clear screen twice ensures we are at the bottom of the screen. clearTerminal :: Run () clearTerminal = do liftIO $ clearScreen liftIO $ clearScreen -- Normalize's lengths of zipped lists (So will fill with standard defaults) zipWithPadding :: a -> b -> c -> [a] -> [b] -> [c] -> [(a,b,c)] zipWithPadding a b c (x:xs) (y:ys) (z:zs) = (x,y,z) : zipWithPadding a b c xs ys zs zipWithPadding _ _ _ [] [] [] = [] zipWithPadding a b c [] ys zs = zipWithPadding a b c [a] ys zs zipWithPadding a b c xs [] zs = zipWithPadding a b c xs [b] zs zipWithPadding a b c xs ys [] = zipWithPadding a b c xs ys [c] nspaces :: Int -> String nspaces n = take n (repeat ' ')
paterson/interpreter
src/Interpreter.hs
Haskell
bsd-3-clause
9,090
{-# LANGUAGE CPP, Rank2Types, ConstraintKinds, PatternGuards, ViewPatterns #-} {-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables, TupleSections #-} {-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable, TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UndecidableInstances #-} -- see below -- {-# LANGUAGE BangPatterns #-} {-# OPTIONS_GHC -Wall #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP -- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP ---------------------------------------------------------------------- -- | -- Module : HERMIT.Extras -- -- Maintainer : [email protected] -- Stability : experimental -- -- Some definitions useful with HERMIT. ---------------------------------------------------------------------- -- #define WatchFailures module HERMIT.Extras ( -- * Misc Unop, Binop -- * Core utilities , unsafeShowPpr , isType, exprType',exprTypeT, pairTy , tcFind0, tcFind, tcFind2 , tcApp0, tcApp1, tcApp2 , isPairTC, isPairTy, isEitherTy , isUnitTy, isBoolTy, isIntTy , onCaseAlts, onAltRhs, unliftedType , apps, apps', apps1', callSplitT, callNameSplitT, unCall, unCall1 , collectForalls, subst, isTyLam, setNominalRole_maybe , isVarT, isLitT , repr, varOccCount, oneOccT, castOccsSame , exprAsConApp -- * HERMIT utilities , moduledName , newIdT , liftedKind, unliftedKind , ReType, ReExpr, ReBind, ReAlt, ReProg, ReCore , FilterH, FilterE, FilterTy, OkCM, TransformU , findTyConT, tyConApp1T , isTypeE, isCastE, isDictE, isCoercionE , mkUnit, mkPair, mkLeft, mkRight, mkEither , InCoreTC , Observing, observeR', tries, triesL, scopeR, labeled , lintExprR -- , lintExprDieR , lintingExprR , varLitE, uqVarName, fqVarName, typeEtaLong, simplifyE , walkE , alltdE, anytdE, anybuE, onetdE, onebuE , inAppTys, isAppTy, inlineWorkerR , letFloatToProg , concatProgs , rejectR , rejectTypeR , simplifyExprR, changedSynR, changedArrR , showPprT, stashLabel, tweakLabel, saveDefT, findDefT , unJustT, tcViewT, unFunCo , lamFloatCastR, castFloatLamR, castCastR, unCastCastR, castTransitiveUnivR , castFloatAppR',castFloatAppUnivR, castFloatCaseR, caseFloatR' , caseWildR , bashExtendedWithE, bashUsingE, bashE , buildDictionaryT', buildTypeableT', simpleDict , TransformM, RewriteM , repeatN , saveDefNoFloatT, dumpStashR, dropStashedLetR , progRhsAnyR , ($*), pairT, listT, unPairR , externC , normaliseTypeT, normalizeTypeT, optimizeCoercionR, optimizeCastR , bindUnLetIntroR -- , letFloatCaseAltR , trivialExpr, letSubstTrivialR, betaReduceTrivialR -- , pruneAltsExpr, pruneAltsR -- might remove , extendTvSubstVars , retypeExprR , Tree(..), toTree, foldMapT, foldT , SyntaxEq(..) , regularizeType ) where import Prelude hiding (id,(.),foldr) import Data.Monoid (Monoid(..),(<>)) import Control.Category (Category(..),(>>>)) import Data.Functor ((<$>),(<$)) import Data.Foldable (Foldable(..)) import Control.Applicative (Applicative(..),liftA2,(<|>)) import Control.Monad ((<=<),unless) import Control.Arrow (Arrow(..)) import Data.Maybe (catMaybes,fromMaybe) import Data.List (intercalate,isPrefixOf) import Text.Printf (printf) import Data.Typeable (Typeable) import Control.Monad.IO.Class (MonadIO) import Data.Map (Map) import qualified Data.Map as Map import Data.Char (isUpper,isSpace) import Data.String (fromString) -- GHC import Unique(hasKey) import PrelNames ( liftedTypeKindTyConKey,unliftedTypeKindTyConKey,constraintKindTyConKey, eitherTyConName) import SimplCore (simplifyExpr) import FamInstEnv (normaliseType) import qualified Coercion import OptCoercion (optCoercion) import Type (substTy,substTyWith) import TcType (isUnitTy,isBoolTy,isIntTy) import Unify (tcUnifyTy) -- import Language.KURE.Transform (apply) import HERMIT.Core ( CoreProg(..),Crumb,bindsToProg,progToBinds,freeVarsExpr , progSyntaxEq,bindSyntaxEq,defSyntaxEq,exprSyntaxEq , altSyntaxEq,typeSyntaxEq,coercionSyntaxEq , CoreDef(..),defToIdExpr, coercionAlphaEq,localFreeVarsExpr) import HERMIT.Name (newIdH) import HERMIT.Monad (HermitM,HasHscEnv(..),HasHermitMEnv,getModGuts,RememberedName(..),saveDef,lookupDef,getStash) import HERMIT.Context ( BoundVars(..),AddBindings(..),ReadBindings(..) , HasEmptyContext(..), HasCoreRules(..) , HermitC ) -- Note that HERMIT.Dictionary re-exports HERMIT.Dictionary.* import HERMIT.Dictionary ( findIdT, findTyConT, callT, callNameT, simplifyR, letFloatTopR, letSubstR, betaReduceR , observeR, bracketR, bashExtendedWithR, bashUsingR, bashR, wrongExprForm , castFloatAppR , caseFloatCastR, caseFloatCaseR, caseFloatAppR, caseFloatLetR , unshadowR, lintExprT, inScope, inlineR, buildDictionaryT , buildTypeable , traceR ) -- import HERMIT.Dictionary (traceR) import HERMIT.GHC hiding (FastString(..),(<>),substTy) import HERMIT.Kure hiding (apply) import HERMIT.External (External,Extern(..),external,ExternalName) import HERMIT.Name (HermitName) {-------------------------------------------------------------------- Misc --------------------------------------------------------------------} -- | Unary transformation type Unop a = a -> a -- | Binary transformation type Binop a = a -> Unop a {-------------------------------------------------------------------- Core utilities --------------------------------------------------------------------} -- | 'showPpr' with global dynamic flags unsafeShowPpr :: Outputable a => a -> String unsafeShowPpr = showPpr unsafeGlobalDynFlags onCaseAlts :: (ExtendCrumb c, ReadCrumb c, AddBindings c, Monad m) => Rewrite c m CoreAlt -> Rewrite c m CoreExpr onCaseAlts r = caseAllR id id id (const r) -- | Rewrite a case alternative right-hand side. onAltRhs :: (Functor m, Monad m) => Rewrite c m CoreExpr -> Rewrite c m CoreAlt onAltRhs r = do (con,vs,rhs) <- id (con,vs,) <$> r $* rhs -- Form an application to type and value arguments. apps :: Id -> [Type] -> [CoreExpr] -> CoreExpr apps f ts es | tyArity f /= length ts = error $ printf "apps: Id %s wants %d type arguments but got %d." (fqVarName f) arity ntys | otherwise = mkApps (varToCoreExpr f) (map Type ts ++ es) where arity = tyArity f ntys = length ts -- Note: With unlifted types, mkCoreApps might make a case expression. -- If we don't want to, maybe use mkApps. -- Number of type arguments. tyArity :: Id -> Int tyArity = length . fst . splitForAllTys . varType -- exprType gives an obscure warning when given a Type expression. exprType' :: CoreExpr -> Type exprType' (Type {}) = error "exprType': given a Type" exprType' e = exprType e -- Like 'exprType', but fails if given a type. exprTypeT :: Monad m => Transform c m CoreExpr Type exprTypeT = do e <- idR guardMsg (not (isType e)) "exprTypeT: given a Type" return (exprType' e) isType :: CoreExpr -> Bool isType (Type {}) = True isType _ = False pairTy :: Binop Type pairTy a b = mkBoxedTupleTy [a,b] tcApp0 :: TyCon -> Type tcApp0 tc = TyConApp tc [] tcApp1 :: TyCon -> Unop Type tcApp1 tc a = TyConApp tc [a] tcApp2 :: TyCon -> Binop Type tcApp2 tc a b = TyConApp tc [a,b] isPairTC :: TyCon -> Bool isPairTC tc = isBoxedTupleTyCon tc && tupleTyConArity tc == 2 isPairTy :: Type -> Bool isPairTy (TyConApp tc [_,_]) = isBoxedTupleTyCon tc isPairTy _ = False isEitherTy :: Type -> Bool isEitherTy (TyConApp tc [_,_]) = tyConName tc == eitherTyConName isEitherTy _ = False -- Found in TcType #if 0 isUnitTy :: Type -> Bool isUnitTy (coreView -> Just t) = isUnitTy t -- experiment isUnitTy (TyConApp tc []) = tc == unitTyCon isUnitTy _ = False isBoolTy :: Type -> Bool isBoolTy (TyConApp tc []) = tc == boolTyCon isBoolTy _ = False #endif liftedKind :: Kind -> Bool liftedKind (TyConApp tc []) = any (tc `hasKey`) [liftedTypeKindTyConKey, constraintKindTyConKey] liftedKind _ = False unliftedKind :: Kind -> Bool unliftedKind (TyConApp tc []) = tc `hasKey` unliftedTypeKindTyConKey unliftedKind _ = False -- TODO: Switch to isLiftedTypeKind and isUnliftedTypeKind from Kind (in GHC). -- When I tried earlier, I lost my inlinings. Investigate! -- <https://github.com/conal/type-encode/issues/1> unliftedType :: Type -> Bool unliftedType = unliftedKind . typeKind splitTysVals :: [Expr b] -> ([Type], [Expr b]) splitTysVals (Type ty : rest) = first (ty :) (splitTysVals rest) splitTysVals rest = ([],rest) collectForalls :: Type -> ([Var], Type) collectForalls ty = go [] ty where go vs (ForAllTy v t') = go (v:vs) t' go vs t = (reverse vs, t) -- TODO: Rewrite collectTypeArgs and collectForalls as unfolds and refactor. -- | Substitute new subexpressions for variables in an expression subst :: [(Id,CoreExpr)] -> Unop CoreExpr subst ps = substExpr (error "subst: no SDoc") (foldr add emptySubst ps) where add (v,new) sub = extendIdSubst sub v new isTyLam :: CoreExpr -> Bool isTyLam (Lam v _) = isTyVar v isTyLam _ = False type ExtendCrumb c = ExtendPath c Crumb type ReadCrumb c = ReadPath c Crumb isVarT :: (Monad m, ExtendCrumb c) => Transform c m CoreExpr () isVarT = varT successT isLitT :: (Monad m, ExtendCrumb c) => Transform c m CoreExpr () isLitT = litT successT #if __GLASGOW_HASKELL__ < 709 -- | Abbreviation for the 'Representational' role repr :: Role repr = Representational -- | Number of occurrences of a non-type variable varOccCount :: Var -> CoreExpr -> Int varOccCount v = occs where occs :: CoreExpr -> Int occs (Var u) | u == v = 1 | otherwise = 0 occs (Lit _) = 0 occs (App p q) = occs p + occs q occs (Lam _ e) = occs e -- assumes no shadowning occs (Let b e) = bindOccs b + occs e occs (Case e _ _ alts) = occs e + sum (map altOccs alts) occs (Cast e _) = occs e occs (Tick _ e) = occs e occs (Type _) = 0 occs (Coercion _) = 0 altOccs (_,_,e) = occs e bindOccs (NonRec _ e) = occs e bindOccs (Rec bs) = sum (map (occs . snd) bs) -- TODO: stricter version #if 0 -- | Number of occurrences of a non-type variable varOccCount :: Var -> CoreExpr -> Int varOccCount v = occs 0 where occs !n (Var u) | u == v = n+1 occs !n (App p q) = occs (occs n p) q occs !n (Lam _ e) = occs n e -- assumes no shadowning occs !n (Cast e _) = occs n e occs !n (Tick _ e) = occs n e occs !n _ = n #endif -- | Matches a let binding with exactly one occurrence of the variable. oneOccT :: FilterE oneOccT = do Let (NonRec v _) body <- id guardMsg (varOccCount v body <= 1) "oneOccT: multiple occurrences" data VarCasts = NoCast | Casts Coercion | FailCast instance Monoid VarCasts where mempty = NoCast NoCast `mappend` c = c c `mappend` NoCast = c FailCast `mappend` _ = FailCast _ `mappend` FailCast = FailCast Casts co `mappend` Casts co' | co `coreEqCoercion` co' = Casts co | otherwise = FailCast -- | See if the given variable occurs only with casts having the same coercion. -- If so, yield that coercion. castOccsSame :: Var -> CoreExpr -> Maybe Coercion castOccsSame v e = case castOccsSame' v e of Casts co -> Just co _ -> Nothing castOccsSame' :: Var -> CoreExpr -> VarCasts castOccsSame' v = occs where occs :: CoreExpr -> VarCasts occs (Var _) = mempty occs (Lit _) = mempty occs (App p q) = occs p <> occs q occs (Lam _ e) = occs e -- assumes no shadowning occs (Let b e) = bindOccs b <> occs e occs (Case e _ _ alts) = occs e <> foldMap altOccs alts occs (Cast (Var u) co) | u == v = Casts co occs (Cast e _) = occs e occs (Tick _ e) = occs e occs (Type _) = mempty occs (Coercion _) = mempty altOccs (_,_,e) = occs e bindOccs (NonRec _ e) = occs e bindOccs (Rec bs) = foldMap (occs . snd) bs {-------------------------------------------------------------------- Borrowed from GHC HEAD >= 7.9 --------------------------------------------------------------------} -- Converts a coercion to be nominal, if possible. -- See also Note [Role twiddling functions] setNominalRole_maybe :: Coercion -> Maybe Coercion setNominalRole_maybe co | Nominal <- coercionRole co = Just co setNominalRole_maybe (SubCo co) = Just co setNominalRole_maybe (Refl _ ty) = Just $ Refl Nominal ty setNominalRole_maybe (TyConAppCo Representational tc coes) = do { cos' <- mapM setNominalRole_maybe coes ; return $ TyConAppCo Nominal tc cos' } setNominalRole_maybe (UnivCo Representational ty1 ty2) = Just $ UnivCo Nominal ty1 ty2 -- We do *not* promote UnivCo Phantom, as that's unsafe. -- UnivCo Nominal is no more unsafe than UnivCo Representational setNominalRole_maybe (TransCo co1 co2) = TransCo <$> setNominalRole_maybe co1 <*> setNominalRole_maybe co2 setNominalRole_maybe (AppCo co1 co2) = AppCo <$> setNominalRole_maybe co1 <*> pure co2 setNominalRole_maybe (ForAllCo tv co) = ForAllCo tv <$> setNominalRole_maybe co setNominalRole_maybe (NthCo n co) = NthCo n <$> setNominalRole_maybe co setNominalRole_maybe (InstCo co ty) = InstCo <$> setNominalRole_maybe co <*> pure ty setNominalRole_maybe _ = Nothing #else #endif -- | Succeeds if we are looking at an application of a data constructor. exprAsConApp :: CoreExpr -> Maybe (DataCon, [Type], [CoreExpr]) exprAsConApp e = exprIsConApp_maybe (in_scope, idUnfolding) e where in_scope =mkInScopeSet (mkVarEnv [ (v,v) | v <- varSetElems (localFreeVarsExpr e) ]) {-------------------------------------------------------------------- HERMIT utilities --------------------------------------------------------------------} newIdT :: String -> TransformM c Type Id newIdT nm = do ty <- id constT (newIdH nm ty) -- Common context & monad constraints -- type OkCM c m = -- ( HasDynFlags m, Functor m, MonadThings m, MonadCatch m -- , BoundVars c, HasModGuts m ) type OkCM c m = ( BoundVars c, HasDynFlags m, HasHscEnv m, HasHermitMEnv m , Functor m, MonadCatch m, MonadIO m, MonadThings m ) type TransformU b = forall c m a. OkCM c m => Transform c m a b type TransformM c a b = Transform c HermitM a b type RewriteM c a = TransformM c a a -- Apply a named id to type and value arguments. apps' :: HermitName -> [Type] -> [CoreExpr] -> TransformU CoreExpr apps' s ts es = (\ i -> apps i ts es) <$> findIdT s -- Apply a named id to type and value arguments. apps1' :: HermitName -> [Type] -> CoreExpr -> TransformU CoreExpr apps1' s ts = apps' s ts . (:[]) type ReType = RewriteH Type type ReProg = RewriteH CoreProg type ReBind = RewriteH CoreBind type ReExpr = RewriteH CoreExpr type ReAlt = RewriteH CoreAlt type ReCore = RewriteH Core #if 0 -- | Lookup the name in the context first, then, failing that, in GHC's global -- reader environment. findTyConT :: String -> TransformU TyCon findTyConT nm = prefixFailMsg ("Cannot resolve name " ++ nm ++ "; ") $ contextonlyT (findTyConMG nm) findTyConMG :: OkCM c m => String -> c -> m TyCon findTyConMG nm _ = do rdrEnv <- mg_rdr_env <$> getModGuts case filter isTyConName $ findNamesFromString rdrEnv nm of [n] -> lookupTyCon n ns -> do dynFlags <- getDynFlags fail $ show (length ns) ++ " matches found: " ++ intercalate ", " (showPpr dynFlags <$> ns) #endif -- TODO: remove context argument, simplify OkCM, etc. See where it leads. -- <https://github.com/conal/type-encode/issues/2> -- TODO: Use findTyConT in HERMIT.Dictionary.Name instead of above. tcFind :: (TyCon -> b) -> HermitName -> TransformU b tcFind h = fmap h . findTyConT tcFind0 :: HermitName -> TransformU Type tcFind0 = tcFind tcApp0 tcFind2 :: HermitName -> TransformU (Binop Type) tcFind2 = tcFind tcApp2 callSplitT :: MonadCatch m => Transform c m CoreExpr (CoreExpr, [Type], [CoreExpr]) callSplitT = do (f,args) <- callT let (tyArgs,valArgs) = splitTysVals args return (f,tyArgs,valArgs) callNameSplitT :: ( MonadCatch m, MonadIO m, MonadThings m, HasHscEnv m, HasHermitMEnv m , BoundVars c ) => HermitName -> Transform c m CoreExpr (CoreExpr, [Type], [Expr CoreBndr]) callNameSplitT name = do (f,args) <- callNameT name let (tyArgs,valArgs) = splitTysVals args return (f,tyArgs,valArgs) -- TODO: refactor with something like HERMIT's callPredT -- | Uncall a named function unCall :: ( MonadCatch m, MonadIO m, MonadThings m, HasHscEnv m, HasHermitMEnv m , BoundVars c ) => HermitName -> Transform c m CoreExpr [CoreExpr] unCall f = do (_f,_tys,args) <- callNameSplitT f return args -- | Uncall a named function of one value argument, dropping initial type args. unCall1 :: HermitName -> ReExpr unCall1 f = do [e] <- unCall f return e mkUnit :: TransformU CoreExpr mkUnit = return (mkCoreTup []) mkPair :: TransformU (Binop CoreExpr) mkPair = return $ \ u v -> mkCoreTup [u,v] moduledName :: String -> String -> HermitName moduledName modName = fromString . (modName ++) . ('.' :) eitherName :: String -> HermitName eitherName = moduledName "Data.Either" mkLR :: String -> TransformU (Type -> Type -> Unop CoreExpr) mkLR name = do f <- findIdT (eitherName name) return $ \ tu tv a -> apps f [tu,tv] [a] mkLeft :: TransformU (Type -> Type -> Unop CoreExpr) mkLeft = mkLR "Left" mkRight :: TransformU (Type -> Type -> Unop CoreExpr) mkRight = mkLR "Right" mkEither :: TransformU (Binop Type) mkEither = tcFind2 (eitherName "Either") type InCoreTC t = Injection t CoreTC -- Whether we're observing rewrites type Observing = Bool observeR' :: (ReadBindings c, ReadCrumb c) => Observing -> InCoreTC t => String -> RewriteM c t observeR' True = observeR observeR' False = const idR tries :: (MonadCatch m, InCoreTC t) => [Rewrite c m t] -> Rewrite c m t tries = foldr (<+) ({- observeR' "Unhandled" >>> -} fail "unhandled") triesL :: (ReadBindings c, ReadCrumb c, InCoreTC t) => Observing -> [(String,RewriteM c t)] -> RewriteM c t triesL observing = tries . map (labeled observing) -- scopeR :: InCoreTC a => String -> Unop (RewriteM c a) scopeR :: String -> Unop (TransformM c a b) scopeR label r = traceR ("Try " ++ label ) >>> -- r (r <+ (traceR (label ++ " failed") >>> fail "scopeR")) labeled :: (ReadBindings c, ReadCrumb c, InCoreTC a) => Observing -> (String, RewriteM c a) -> RewriteM c a labeled observing (label,r) = #ifdef WatchFailures scopeR label $ #endif (if observing then bracketR label else id) r lintExprR :: (Functor m, Monad m, HasDynFlags m, BoundVars c) => Rewrite c m CoreExpr -- lintExprR = (id &&& lintExprT) >>> arr fst lintExprR = lintExprT >> id #if 0 -- lintExprR = ifM (True <$ lintExprT) id (fail "lint failure") lintExprDieR :: (Functor m, MonadCatch m, HasDynFlags m, BoundVars c) => Rewrite c m CoreExpr lintExprDieR = lintExprR `catchM` error -- lintExprT :: (BoundVars c, Monad m, HasDynFlags m) => -- Transform c m CoreExpr String #endif -- | Apply a rewrite rule. If it succeeds but the result fails to pass -- core-lint, show the before and after (via 'bracketR') and die with the -- core-lint error message. lintingExprR :: ( ReadBindings c, ReadCrumb c , BoundVars c, AddBindings c, ExtendCrumb c, HasEmptyContext c -- for unshadowR ) => String -> Unop (Rewrite c HermitM CoreExpr) lintingExprR msg rr = do e <- idR e' <- rr' res <- attemptM (lintExprT $* e') either (\ lintMsg -> do _ <- bracketR ("Lint check " ++ msg) rr' $* e error ("Lint failure: " ++ lintMsg) -- traceR lintMsg ) (const $ do unless (isType e || isType e') ( do let t = exprType' e t' = exprType' e' unless ({- True || -} t `eqType` t') $ -- See 2015-11-27 notes do _ <- bracketR ("Type changed! " ++ msg) rr' $* e st <- showPprT $* t st' <- showPprT $* t' error (printf "OOPS! Type changed.\n Old: %s\n New: %s" (dropModules st) (dropModules st'))) return e') res where rr' = rr >>> extractR (tryR unshadowR) -- -- Lint both before and after -- lintingExprR2 :: ( ReadBindings c, ReadCrumb c -- , BoundVars c, AddBindings c, ExtendCrumb c, HasEmptyContext c -- for unshadowR -- ) => -- String -> Unop (Rewrite c HermitM CoreExpr) -- lintingExprR2 msg rr = -- lintingExprR ("Before " ++ msg) id >> lintingExprR ("After " ++ msg) rr -- TODO: Compare types before and after. -- TODO: Eliminate labeled. -- labeledR' :: InCoreTC a => Bool -> String -> Unop (RewriteH a) -- labeledR' debug label r = -- do c <- contextT -- labeled debug (label,r) -- mkVarName :: MonadThings m => Transform c m Var (CoreExpr,Type) -- mkVarName = contextfreeT (mkStringExpr . uqName . varName) &&& arr varType varLitE :: Var -> CoreExpr varLitE = Lit . mkMachString . uqVarName uqVarName :: Var -> String uqVarName = unqualifiedName . varName fqVarName :: Var -> String fqVarName = qualifiedName . varName -- Fully type-eta-expand, i.e., ensure that every leading forall has a matching -- (type) lambdas. typeEtaLong :: ReExpr typeEtaLong = readerT $ \ e -> if isTyLam e then lamAllR idR typeEtaLong else expand where -- Eta-expand enough for lambdas to match foralls. expand = do e@(collectForalls . exprType' -> (tvs,_)) <- idR return $ mkLams tvs (mkApps e ((Type . TyVarTy) <$> tvs)) simplifyE :: ReExpr simplifyE = extractR simplifyR walkE :: Unop ReCore -> Unop ReExpr walkE trav r = extractR (trav (promoteR r :: ReCore)) alltdE, anytdE, anybuE, onetdE, onebuE :: Unop ReExpr alltdE = walkE alltdR anytdE = walkE anytdR anybuE = walkE anybuR onetdE = walkE onetdR onebuE = walkE onebuR -- TODO: Try rewriting more gracefully, testing isForAllTy first and -- maybeEtaExpandR isWorkerT :: FilterE isWorkerT = do Var (isWorker -> True) <- id return () isWorker :: Id -> Bool isWorker = ("$W" `isPrefixOf`) . uqVarName inlineWorkerR :: ReExpr inlineWorkerR = isWorkerT >> inlineR -- Apply a rewriter inside type lambdas. inAppTys :: Unop ReExpr inAppTys r = r' where r' = readerT $ \ e -> if isAppTy e then appAllR r' idR else r isAppTy :: CoreExpr -> Bool isAppTy (App _ (Type _)) = True isAppTy _ = False letFloatToProg :: (BoundVars c, AddBindings c, ReadCrumb c, ExtendCrumb c) => TransformM c CoreBind CoreProg letFloatToProg = arr (flip ProgCons ProgNil) >>> tryR letFloatTopR -- TODO: alias for these c constraints. concatProgs :: [CoreProg] -> CoreProg concatProgs = bindsToProg . concatMap progToBinds -- | Reject if condition holds. Opposite of 'acceptR' rejectR :: Monad m => (a -> Bool) -> Rewrite c m a rejectR f = acceptR (not . f) -- | Reject if condition holds on an expression's type. rejectTypeR :: Monad m => (Type -> Bool) -> Rewrite c m CoreExpr rejectTypeR f = rejectR (f . exprType') -- | Succeed only if the given rewrite actually changes the term changedSynR :: (MonadCatch m, SyntaxEq a) => Unop (Rewrite c m a) changedSynR = changedByR (=~=) -- | Succeed only if the given rewrite actually changes the term changedArrR :: (MonadCatch m, SyntaxEq a) => Unop a -> Rewrite c m a changedArrR = changedSynR . arr -- | Use GHC expression simplifier and succeed if different. Sadly, the check -- gives false positives, which spoils its usefulness. simplifyExprR :: ReExpr simplifyExprR = changedSynR $ prefixFailMsg "simplify-expr failed: " $ contextfreeT $ \ e -> do dflags <- getDynFlags liftIO $ simplifyExpr dflags e -- | Get a GHC pretty-printing showPprT :: (HasDynFlags m, Outputable a, Monad m) => Transform c m a String showPprT = do a <- id dynFlags <- constT getDynFlags return (showPpr dynFlags a) -- | Make a stash label out of an outputtable stashLabel :: (Functor m, Monad m, HasDynFlags m, Outputable a) => Transform c m a String stashLabel = tweakLabel <$> showPprT -- Replace whitespace runs with underscores tweakLabel :: Unop String tweakLabel = intercalate "_" . words dropModules :: Unop String dropModules = unwords . map dropMods . words where dropMods (c:rest) | not (isUpper c) = c : dropMods rest dropMods (break (== '.') -> (_,'.':rest)) = dropMods rest dropMods s = s memoChat :: (ReadBindings c, ReadCrumb c, Injection a CoreTC) => Bool -> String -> String -> RewriteM c a memoChat brag pre lab = if brag then chat ("memo " ++ pre ++ ": " ++ lab) else id where chat = traceR -- observeR -- | Save a definition for future use. saveDefT :: (ReadBindings c, ReadCrumb c) => Observing -> String -> TransformM c CoreDef () saveDefT brag lab = do def@(Def _ e) <- id constT (saveDef (RememberedName lab) def) >>> (memoChat brag "save" lab $* e >> return ()) findDefT :: (ReadBindings c, ReadCrumb c) => Observing -> String -> TransformM c a CoreExpr findDefT brag lab = constT (defExpr <$> lookupDef (RememberedName lab)) >>> memoChat brag "hit" lab where defExpr (Def _ expr) = expr saveDefNoFloatT :: (ReadBindings c, ReadCrumb c) => Observing -> String -> TransformM c CoreExpr () saveDefNoFloatT brag lab = do e <- id v <- newIdT bogusDefName $* exprType' e saveDefT brag lab $* Def v e -- | unJust as transform. Fails on Nothing. -- Already in Kure? unJustT :: Monad m => Transform c m (Maybe a) a unJustT = do Just x <- idR return x -- | GHC's tcView as a rewrite tcViewT :: RewriteM c Type tcViewT = unJustT . arr tcView -- | Dissect a function coercion into role, domain, and range unFunCo :: Coercion -> Maybe (Role,Coercion,Coercion) unFunCo (TyConAppCo role tc [domCo,ranCo]) | isFunTyCon tc = Just (role,domCo,ranCo) unFunCo _ = Nothing -- | cast (\ v -> e) (domCo -> ranCo) -- ==> (\ v' -> cast (e[Var v <- cast (Var v') (SymCo domCo)]) ranCo) -- where v' :: a' if the whole expression had type a' -> b'. -- Warning, to avoid looping, don't combine with 'castFloatLamR'. lamFloatCastR :: ReExpr lamFloatCastR = -- labelR "lamFloatCastR" $ do Cast (Lam v e) (unFunCo -> Just (_,domCo,ranCo)) <- idR Just (domTy,_) <- arr (splitFunTy_maybe . exprType') v' <- constT $ newIdH (uqVarName v) domTy let e' = subst [(v, Cast (Var v') (SymCo domCo))] e return (Lam v' (Cast e' ranCo)) -- | (\ x :: a -> u `cast` co) ==> (\ x -> u) `cast` (<a> -> co) -- Warning, to avoid looping, don't combine with 'lamFloatCastR'. castFloatLamR :: ReExpr castFloatLamR = do Lam x (u `Cast` co) <- id return $ Lam x u `mkCast` (mkFunCo repr (mkReflCo repr (varType x)) co) -- TODO: Should I check the role? -- | cast (cast e co) co' ==> cast e (mkTransCo co co') castCastR :: ReExpr castCastR = -- labelR "castCastR" $ do Cast (Cast e co) co' <- idR return (Cast e (mkTransCo co co')) -- e `cast` (co1 ; co2) ==> (e `cast` co1) `cast` co2 -- Handle with care. Don't mix with its inverse, 'castCastR'. unCastCastR :: Monad m => Rewrite c m CoreExpr unCastCastR = do e `Cast` (co1 `TransCo` co2) <- idR return ((e `Cast` co1) `Cast` co2) -- Collapse transitive coercions when the latter is universal. -- TODO: Maybe re-associate. castTransitiveUnivR :: ReExpr castTransitiveUnivR = do Cast e (TransCo (coercionKind -> Pair t _) (UnivCo r _ t')) <- id return $ mkCast e (mkUnivCo r t t') -- Like 'castFloatAppR', but handles transitivy coercions. castFloatAppR' :: (MonadCatch m, ExtendCrumb c) => Rewrite c m CoreExpr castFloatAppR' = castFloatAppR <+ -- castFloatAppUnivR <+ (appAllR unCastCastR id >>> castFloatAppR') -- | Like castFloatApp but handles *all* coercions, and makes universal coercions. -- (f `cast` (co :: (a -> b) ~ (a' -> b'))) e ==> -- f (e `cast` (univ :: a' ~ a)) `cast` (univ :: b ~ b') -- or -- (f `cast` (co :: (forall a. b) ~ (forall a. b'))) (Type t) == -- f e `cast` (univ :: [a := t]b ~ [a := t]b') castFloatAppUnivR :: MonadCatch m => Rewrite c m CoreExpr castFloatAppUnivR = do App (Cast fun co) arg <- id let Pair ty ty' = coercionKind co role = coercionRole co (do Just (a ,b ) <- return $ splitFunTy_maybe ty Just (a',b') <- return $ splitFunTy_maybe ty' -- guardMsg (a =~= a') -- "castFloatAppUnivR: cast changes domain types" return $ mkCast (App fun (mkCast arg (mkUnivCo role a' a))) (mkUnivCo role b b')) <+ (do Just (a ,b ) <- return $ splitForAllTy_maybe ty Just (a',b') <- return $ splitForAllTy_maybe ty' Type tyArg <- return arg guardMsg (a =~= a') "castFloatAppUnivR: cast changes type argument" return $ let sub = substTyWith [a] [tyArg] in mkCast (App fun arg) (mkUnivCo role (sub b) (sub b'))) -- | case e of p -> (rhs `cast` co) ==> (case e of p -> rhs) `cast` co -- Inverse to 'caseFloatCastR', so don't use both rules! castFloatCaseR :: ReExpr castFloatCaseR = do Case scrut wild _ [(con,binds,rhs `Cast` co)] <- id return $ Case scrut wild (pFst (coercionKind co)) [(con,binds,rhs)] `Cast` co -- | Like caseFloatR, but excludes caseFloatCastR, so we can use castFloatCaseR -- Note: does NOT include caseFloatArg caseFloatR' :: (ExtendCrumb c, ReadCrumb c, AddBindings c, ReadBindings c) => Rewrite c HermitM CoreExpr caseFloatR' = setFailMsg "Unsuitable expression for Case floating." $ caseFloatAppR <+ caseFloatCaseR <+ caseFloatLetR -- | case scrut of wild t { _ -> body } -- ==> let wild = scrut in body -- May be followed by let-elimination. -- Warning: does not capture GHC's intent to reduce scrut to WHNF. caseWildR :: ReExpr caseWildR = -- labeledR "reifyCaseWild" $ do Case scrut wild _bodyTy [(DEFAULT,[],body)] <- idR return $ Let (NonRec wild scrut) body -- | Like bashExtendedWithR, but for expressions bashExtendedWithE :: [ReExpr] -> ReExpr bashExtendedWithE rs = extractR (bashExtendedWithR (promoteR <$> rs)) -- | Like bashUsingR, but for expressions bashUsingE :: [ReExpr] -> ReExpr bashUsingE rs = extractR (bashUsingR (promoteR <$> rs)) -- | bashE for expressions bashE :: ReExpr bashE = extractR bashR type FilterH a = TransformH a () type FilterE = FilterH CoreExpr type FilterTy = FilterH Type -- | Is the expression a type? isTypeE :: FilterE isTypeE = typeT successT -- | Is the expression a cast? isCastE :: FilterE isCastE = castT id id mempty -- | Is the expression a dictionary? isDictE :: FilterE isDictE = guardT . (isDictTy <$> exprTypeT) -- | Is the expression a coercion? isCoercionE :: FilterE isCoercionE = coercionT mempty -- | Like tyConAppT, but for single type argument. tyConApp1T :: (ExtendCrumb c, Monad m) => Transform c m TyCon a -> Transform c m KindOrType b -> (a -> b -> z) -> Transform c m Type z tyConApp1T ra rb h = do TyConApp _ [_] <- id tyConAppT ra (const rb) (\ a [b] -> h a b) modFailMsgM :: MonadCatch m => (String -> m String) -> m a -> m a modFailMsgM f ma = ma `catchM` (fail <=< f) setFailMsgM :: MonadCatch m => m String -> m a -> m a setFailMsgM msgM = modFailMsgM (const msgM) -- | Like 'buildDictionaryT' but simplifies with 'bashE'. buildDictionaryT' :: TransformH Type CoreExpr buildDictionaryT' = {- observeR "buildDictionaryT' (pre)" >>> -} ( setFailMsgM (("Couldn't build dictionary for "++) <$> showPprT ) $ tryR bashE . {- scopeR "buildDictionaryT" -} buildDictionaryT ) -- buildDictionaryT' = setFailMsg "Couldn't build dictionary" $ -- tryR bashE . buildDictionaryT -- Try again but with multiple type arguments. simpleDict :: HermitName -> TransformH [Type] CoreExpr simpleDict name = do tc <- findTyConT name buildDictionaryT' . arr (TyConApp tc) -- simpleDict1 :: HermitName -> TransformH Type CoreExpr -- simpleDict1 name = simpleDict name . arr (:[]) -- | Build and simplify a 'Typeable' instance buildTypeableT' :: TransformH Type CoreExpr #if 0 buildTypeableT' = do ty <- id tc <- findTyConT "Data.Typeable.Typeable" buildDictionaryT' $* TyConApp tc [typeKind ty, ty] -- The findTyConT is failing. Hm! #else -- Adapted from buildDictionaryT buildTypeableT' = tryR bashE . prefixFailMsg "buildTypeableT failed: " ( contextfreeT $ \ ty -> do (i,bnds) <- buildTypeable ty guardMsg (notNull bnds) "no dictionary bindings generated." return $ mkCoreLets bnds (varToCoreExpr i) ) #endif -- | Repeat a rewriter exactly @n@ times. repeatN :: Monad m => Int -> Unop (Rewrite c m a) repeatN n = serialise . replicate n -- | Use in a stashed 'Def' to say that we don't want to dump. bogusDefName :: String bogusDefName = "$bogus-def-name$" dropBogus :: Unop (Map Id CoreExpr) dropBogus = Map.filterWithKey (\ v _ -> uqVarName v /= bogusDefName) -- | Dump the stash of definitions. dumpStashR :: RewriteH CoreProg dumpStashR = do stashed <- stashIdMapT already <- arr progBound let new = dropBogus (Map.difference stashed already) -- Drop these let bindings from program before extending. progRhsAnyR (anybuE (dropLets new)) -- or anytdR (repeat (dropLets new)) >>> arr (\ prog -> foldr add prog (Map.toList new)) where add (v,rhs) = ProgCons (NonRec v rhs) -- We only remove let bindings from the top-level of a definition. -- They get floated there. -- TODO: Drop unused stashed bindings. dropStashedLetR :: ReExpr dropStashedLetR = stashIdMapT >>= dropLets -- Rewrite the right-hand sides of top-level definitions progRhsAnyR :: ReExpr -> RewriteH CoreProg progRhsAnyR r = progBindsAnyR (const (nonRecOrRecAllR id r)) where nonRecOrRecAllR p q = recAllR (const (defAllR p q)) <+ nonRecAllR p q -- (anybuE (dropLets new)) -- TODO: Handle recursive definition groups also. -- reifyProg = progBindsT (const (tryR reifyDef >>> letFloatToProg)) concatProgs -- progBindsAllR :: (ExtendPath c Crumb, ReadPath c Crumb, AddBindings c, MonadCatch m) => (Int -> Rewrite c m CoreBind) -> Rewrite c m CoreProg -- NOTE: I'm converting the stash from a map over RememberedName to a map over Id. -- Look for a better way. progBound :: CoreProg -> Map Id CoreExpr progBound = foldMap bindNames . progToBinds where bindNames (NonRec v e) = Map.singleton v e bindNames (Rec bs) = Map.fromList bs stashIdMapT :: TransformM c a (Map Id CoreExpr) stashIdMapT = (Map.fromList . Map.elems . fmap defToIdExpr) <$> constT getStash #if 1 dropLets :: Monad m => Map Id CoreExpr -> Rewrite c m CoreExpr dropLets defs = dropLetPred (flip Map.member defs) dropLetPred :: Monad m => (Id -> Bool) -> Rewrite c m CoreExpr dropLetPred f = do Let (NonRec v _) body <- id guardMsg (f v) "dropLets: doesn't satisfy predicate" return body #else -- | Drop a 'let' binding if the variable is already bound. Assumes that the -- outer matches the inner, but doesn't check. Useful with 'dumpStash'. dropRedundantLetR :: ReExpr dropRedundantLetR = do Let (NonRec v _) body <- id contextonlyT $ \ c -> guardMsg (inScope c v) "dropRedundantLet: out of scope" return body #endif -- Experimental utilities infixr 8 $* ($*) :: Monad m => Transform c m a b -> a -> Transform c m q b t $* x = t . return x pairT :: ReExpr -> ReExpr -> ReExpr pairT ra rb = do [_,_,a,b] <- snd <$> callNameT "GHC.Tuple.(,)" liftA2 pair (ra $* a) (rb $* b) where pair x y = mkCoreTup [x,y] listT :: Monad m => [Transform c m a b] -> Transform c m [a] [b] listT rs = do es <- id guardMsg (length rs == length es) "listT: length mismatch" sequence (zipWith ($*) rs es) unPairR :: ( Functor m, MonadCatch m, MonadThings m, MonadIO m , HasHermitMEnv m, HasHscEnv m, BoundVars c ) => Transform c m CoreExpr (CoreExpr,CoreExpr) unPairR = do [_,_,a,b] <- snd <$> callNameT "GHC.Tuple.(,)" return (a,b) externC :: Injection a Core => ExternalName -> RewriteH a -> String -> External externC name rew help = external name (promoteR rew :: ReCore) [help] -- | Normalize a type, giving coercion and result type. -- Fails if already normalized (rather than returning 'ReflCo'). normaliseTypeT :: (MonadIO m, HasHscEnv m, HasHermitMEnv m) => Role -> Transform c m Type (Coercion, Type) normaliseTypeT r = do envs <- constT $ do guts <- getModGuts eps <- getHscEnv >>= liftIO . hscEPS return (eps_fam_inst_env eps, mg_fam_inst_env guts) res@(co,_) <- arr (normaliseType envs r) guardMsg (not (isReflCo co)) "normaliseTypeT: already normal" return res -- Adapted from Andrew Farmer's code. -- | Alias for 'normalizeTypeT'. normalizeTypeT :: (MonadIO m, HasHscEnv m, HasHermitMEnv m) => Role -> Transform c m Type (Coercion, Type) normalizeTypeT = normaliseTypeT -- | Optimize a coercion. optimizeCoercionR :: RewriteM c Coercion optimizeCoercionR = changedArrR (optCoercion emptyCvSubst) -- | Optimize a cast. optimizeCastR :: ExtendCrumb c => RewriteM c CoreExpr optimizeCastR = castAllR id optimizeCoercionR -- | x = (let y = e in y) ==> x = e bindUnLetIntroR :: ReBind bindUnLetIntroR = do NonRec x (Let (NonRec y e) (Var ((== y) -> True))) <- id return (NonRec x e) -- Now in HERMIT #if 0 -- | Float a let out of a case alternative: -- -- case foo of { ... ; p -> let x = u in v ; ... } ==> -- let x = u in case foo of { ... ; p -> v ; ... } -- -- where no variable in `p` occurs freely in `u`, and where `x` is not one of -- the variables in `p`. letFloatCaseAltR :: ReExpr letFloatCaseAltR = do Case scrut w ty alts <- id (b,alts') <- letFloatOneAltR alts return $ Let b (Case scrut w ty alts') -- Perform the first safe let-floating out of a case alternative letFloatOneAltR :: [CoreAlt] -> TransformH x (CoreBind,[CoreAlt]) letFloatOneAltR [] = fail "no alternatives safe to let-float" letFloatOneAltR (alt:rest) = (do (bind,alt') <- letFloatAltR alt return (bind,alt':rest)) <+ (second (alt :) <$> letFloatOneAltR rest) -- (p -> let bind in e) ==> (bind, p -> e) letFloatAltR :: CoreAlt -> TransformH x (CoreBind,CoreAlt) letFloatAltR (con,vs,Let bind@(NonRec x a) body) | isEmptyVarSet (vset `intersectVarSet` freeVarsExpr a) && not (x `elemVarSet` vset) = return (bind,(con,vs,body)) where vset = mkVarSet vs letFloatAltR _ = fail "letFloatAltR: not applicable" -- TODO: consider variable occurrence conditions more carefully #endif {-------------------------------------------------------------------- Triviality --------------------------------------------------------------------} -- exprIsTrivial :: CoreExpr -> Bool -- exprIsTrivial (Var {}) = True -- exprIsTrivial (Lit {}) = True -- exprIsTrivial (App {}) = False -- exprIsTrivial (Lam _ e) = exprIsTrivial e -- exprIsTrivial (Case {}) = False -- exprIsTrivial (Cast e _) = exprIsTrivial e -- exprIsTrivial (Tick _ e) = exprIsTrivial e -- exprIsTrivial (Type {}) = True -- exprIsTrivial (Coercion _) = True -- Instead use exprIsTrivial from GHC's CoreUtils -- | Trivial expression: for now, literals, variables, casts of trivial. trivialExpr :: FilterE trivialExpr = setFailMsg "Non-trivial" $ isTypeE <+ isVarT <+ isCoercionE <+ isDictE <+ isLitT <+ trivialLam <+ castT trivialExpr id mempty -- TODO: Maybe use a guardM variant and GHC's exprIsTrivial trivialBind :: FilterH CoreBind trivialBind = nonRecT successT trivialExpr mempty trivialLet :: FilterE trivialLet = letT trivialBind successT mempty trivialLam :: FilterE trivialLam = lamT id trivialExpr mempty trivialBetaRedex :: FilterE trivialBetaRedex = appT trivialLam successT mempty -- These filters could instead be predicates. Then use acceptR. letSubstTrivialR :: ReExpr letSubstTrivialR = -- watchR "trivialLet" $ trivialLet >> letSubstR betaReduceTrivialR :: ReExpr betaReduceTrivialR = -- watchR "betaReduceTrivialR" $ trivialBetaRedex >> betaReduceR {-------------------------------------------------------------------- Case alternative pruning --------------------------------------------------------------------} type InTvM a = TvSubst -> a type ReTv a = a -> InTvM a pruneBound :: Var -> Unop TvSubst pruneBound v = fromMaybe (error "pruneBound: contradiction") . extendTvSubstVar v extendTvSubstVar :: Var -> InTvM (Maybe TvSubst) extendTvSubstVar v | isCoVar v && coVarRole v == Nominal = extendTvSubstTys (coVarKind v) | otherwise = pure extendTvSubstVars :: [Id] -> TvSubst -> Maybe TvSubst extendTvSubstVars = foldr (\ v q -> q <=< extendTvSubstVar v) pure extendTvSubstTys :: (Type,Type) -> TvSubst -> Maybe TvSubst extendTvSubstTys (a,b) sub = unionTvSubst sub <$> tcUnifyTy (substTy sub a) (substTy sub b) -- TODO: Can I really use unionTvSubst here? Note comment "Works when the ranges -- are disjoint" -- TODO: Maybe use normaliseType and check that the resulting coercion is -- nominal TODO: Handle Representational coercions? #if 0 pruneAltsR :: ReExpr pruneAltsR = changedArrR (flip pruneAltsExpr emptyTvSubst) pruneAltsExpr :: ReTv CoreExpr pruneAltsExpr e@(Var _) = pure e pruneAltsExpr e@(Lit _) = pure e pruneAltsExpr (App u v) = liftA2 App (pruneAltsExpr u) (pruneAltsExpr v) pruneAltsExpr (Lam x e) = Lam x <$> (pruneAltsExpr e . pruneBound x) pruneAltsExpr (Let b e) = liftA2 Let (pruneAltsBind b) (pruneAltsExpr e) pruneAltsExpr (Case e w ty alts) = Case <$> (pruneAltsExpr e) <*> pure w <*> pure ty <*> (catMaybes <$> mapM pruneAltsAlt alts) pruneAltsExpr (Cast e co) = Cast <$> pruneAltsExpr e <*> pure co pruneAltsExpr (Tick t e) = Tick t <$> pruneAltsExpr e pruneAltsExpr e@(Type _) = pure e pruneAltsExpr e@(Coercion _) = pure e pruneAltsBind :: ReTv CoreBind pruneAltsBind (NonRec x e) = NonRec x <$> (pruneAltsExpr e . pruneBound x) pruneAltsBind (Rec ves) = \ env -> Rec ((fmap.second) (flip pruneAltsExpr env) ves) -- For Rec, I'm not gathering any info about the variables, so some pruning may -- be missed. TODO: Reconsider. -- TODO: Use an applicative or monadic style for Rec. pruneAltsAlt :: CoreAlt -> InTvM (Maybe CoreAlt) pruneAltsAlt (con,vs0,e) = -- \ env -> case prune vs0 env of -- Nothing -> Nothing -- Just env' -> Just (con,vs0,pruneAltsExpr e env') (fmap.fmap) ((con,vs0,) . pruneAltsExpr e) (extendTvSubstVars vs0) -- I think I'll want to combine pruneBound and consistentVar, yielding a Maybe -- TvSubst. What do I do for pruneAltsExpr etc if a lambda binding proves -- impossible? What about a let binding? #else {-------------------------------------------------------------------- Type localization --------------------------------------------------------------------} -- Eliminate type variables determined by coercions, so that other -- transformations can use local information. -- Subsumes pruneAlt* -- TODO: Make retypeFoo into a class -- TODO: Still needed? retypeExprR :: ReExpr retypeExprR = changedArrR (flip retypeExpr emptyTvSubst) retypeType :: ReTv Type retypeType = flip substTy retypeVar :: ReTv Var retypeVar x = \ sub -> setVarType x (substTy sub (varType x)) retypeExpr :: ReTv CoreExpr -- retypeExpr (Var x) = Var . retypeVar x retypeExpr (Var x) = \ sub -> let ty = varType x ty' = substTy sub ty in mkCast (Var x) (mkUnivCo Representational ty ty') retypeExpr e@(Lit _) = pure e retypeExpr (App u v) = App <$> retypeExpr u <*> retypeExpr v -- retypeExpr (Lam x e) = Lam <$> retypeVar x <*> (retypeExpr e . pruneBound x) retypeExpr (Lam x e) = Lam x <$> retypeExpr e retypeExpr (Let b e) = Let <$> retypeBind b <*> retypeExpr e retypeExpr (Case e w ty alts) = Case <$> retypeExpr e <*> retypeVar w <*> retypeType ty <*> (catMaybes <$> mapM retypeAlt alts) retypeExpr (Cast e co) = mkCast <$> retypeExpr e <*> retypeCoercion co retypeExpr (Tick t e) = Tick t <$> retypeExpr e retypeExpr (Type t) = Type <$> retypeType t retypeExpr (Coercion co) = Coercion <$> retypeCoercion co retypeBind :: ReTv CoreBind retypeBind (NonRec x e) = NonRec <$> retypeVar x <*> (retypeExpr e . pruneBound x) retypeBind (Rec ves) = Rec <$> mapM (\ (x,e) -> (,) <$> retypeVar x <*> retypeExpr e) ves -- retypeAlt :: CoreAlt -> InTvM (Maybe CoreAlt) -- retypeAlt (con,vs0,e) = go vs0 [] -- where -- go :: [Var] -> [Var] -> TvSubst -> Maybe (CoreAlt) -- go [] acc sub = return (con, reverse acc, retypeExpr e sub) -- go (v:vs) acc sub | isCoVar v && coVarRole v == Nominal -- = extendTvSubstTys (coVarKind v) sub >>= go vs (v:acc) -- | otherwise -- = go vs (retypeVar v sub : acc) sub -- -- Gather substitutions for all of coercion variables. -- -- Then substitute in the parameters and the body. -- retypeAlt :: CoreAlt -> InTvM (Maybe CoreAlt) -- retypeAlt (con,vs,e) sub = -- do sub' <- extendTvSubstVars vs sub -- return (con, tyToPat (lookupTvSubst sub') <$> vs, retypeExpr e sub') -- Gather substitutions for all of coercion variables. -- Then substitute in the the body. retypeAlt :: CoreAlt -> InTvM (Maybe CoreAlt) retypeAlt (con,vs,e) sub = do sub' <- extendTvSubstVars vs sub return (con, vs, retypeExpr e sub') -- retypeAlt (con,vs,e) sub = -- extendTvSubstVars vs sub >>= -- (con,,) <$> mapM retypeVar vs <*> retypeExpr e -- TODO: Consider coercions in let and lambda. -- For now, convert coercions to universal. retypeCoercion :: ReTv Coercion retypeCoercion co = -- optCoercion emptyCvSubst <$> (mkUnivCo (coercionRole co) <$> retypeType ty <*> retypeType ty') where Pair ty ty' = coercionKind co #endif {-------------------------------------------------------------------- Balanced binary trees, for type constructions --------------------------------------------------------------------} -- Binary leaf tree. Used to construct balanced nested sum and product types. data Tree a = Empty | Leaf a | Branch (Tree a) (Tree a) deriving (Show,Functor,Foldable) toTree :: [a] -> Tree a toTree [] = Empty toTree [a] = Leaf a toTree xs = Branch (toTree l) (toTree r) where (l,r) = splitAt (length xs `div` 2) xs foldMapT :: b -> (a -> b) -> Binop b -> Tree a -> b foldMapT e l b = h where h Empty = e h (Leaf a) = l a h (Branch u v) = b (h u) (h v) foldT :: a -> Binop a -> Tree a -> a foldT e b = foldMapT e id b {-------------------------------------------------------------------- Syntactic equality --------------------------------------------------------------------} -- Syntactic equality tests, taking care to check var types for change. infix 4 =~= class SyntaxEq a where (=~=) :: a -> a -> Bool instance (SyntaxEq a, SyntaxEq b) => SyntaxEq (a,b) where (a,b) =~= (a',b') = a =~= a' && b =~= b' instance (SyntaxEq a, SyntaxEq b, SyntaxEq c) => SyntaxEq (a,b,c) where (a,b,c) =~= (a',b',c') = a =~= a' && b =~= b' && c =~= c' instance SyntaxEq a => SyntaxEq [a] where (=~=) = all2 (=~=) instance SyntaxEq Var where (=~=) = varSyntaxEq' varSyntaxEq' :: Var -> Var -> Bool varSyntaxEq' x y = x == y && varType x =~= varType y instance SyntaxEq CoreProg where ProgNil =~= ProgNil = True ProgCons bnd1 p1 =~= ProgCons bnd2 p2 = bnd1 =~= bnd2 && p1 =~= p2 _ =~= _ = False instance SyntaxEq CoreBind where NonRec v1 e1 =~= NonRec v2 e2 = v1 =~= v2 && e1 =~= e2 Rec ies1 =~= Rec ies2 = ies1 =~= ies2 _ =~= _ = False instance SyntaxEq CoreDef where Def i1 e1 =~= Def i2 e2 = i1 =~= i2 && e1 =~= e2 instance SyntaxEq CoreExpr where Var x =~= Var y = x =~= y Lit l1 =~= Lit l2 = l1 == l2 App f1 e1 =~= App f2 e2 = f1 =~= f2 && e1 =~= e2 Lam v1 e1 =~= Lam v2 e2 = v1 == v2 && e1 =~= e2 Let b1 e1 =~= Let b2 e2 = b1 =~= b2 && e1 =~= e2 Case s1 w1 ty1 as1 =~= Case s2 w2 ty2 as2 = w1 == w2 && s1 =~= s2 && all2 (=~=) as1 as2 && ty1 =~= ty2 Cast e1 co1 =~= Cast e2 co2 = e1 =~= e2 && co1 =~= co2 Tick t1 e1 =~= Tick t2 e2 = t1 == t2 && e1 =~= e2 Type ty1 =~= Type ty2 = ty1 =~= ty2 Coercion co1 =~= Coercion co2 = co1 =~= co2 _ =~= _ = False instance SyntaxEq AltCon where (=~=) = (==) instance SyntaxEq Type where (=~=) = typeSyntaxEq instance SyntaxEq Coercion where (=~=) = coercionSyntaxEq regularizeType :: Unop Type regularizeType (coreView -> Just ty) = regularizeType ty regularizeType ty@(TyVarTy _) = ty regularizeType (AppTy u v) = AppTy (regularizeType u) (regularizeType v) regularizeType (TyConApp tc tys) = TyConApp tc (regularizeType <$> tys) regularizeType (FunTy u v) = FunTy (regularizeType u) (regularizeType v) regularizeType (ForAllTy x ty) = ForAllTy x (regularizeType ty) regularizeType ty@(LitTy _) = ty
conal/hermit-extras
src/HERMIT/Extras.hs
Haskell
bsd-3-clause
50,562
{-# LANGUAGE OverloadedStrings #-} {- Created : 2015 Sep 05 (Sat) 11:05:00 by Harold Carr. Last Modified : 2015 Sep 13 (Sun) 16:52:43 by Harold Carr. -} module Client where import Control.Lens import Data.Aeson (toJSON) import Msg import Network.Wreq epAddr = "http://127.0.0.1:3000" mkMsg = Msg "H" msgs = [ mkMsg 0 "hello" , mkMsg 1 "Just \"application/json; charset=utf-8\"" , mkMsg 19 "Just \"Warp/3.0.13.1\"" -- wrong id, right answer , mkMsg 2 "WRONG ANSWER" -- right id, wrong answer , mkMsg 2 "Just \"Warp/3.0.13.1\"" , mkMsg 3 "Just (Number 3.0)" , mkMsg 4 "4" , mkMsg 5 "15" , mkMsg 6 "15" , mkMsg 7 "120" , mkMsg 8 "120" , mkMsg 9 "[1,2,3,4]" , mkMsg 10 "[1,2,3,4]" , mkMsg 11 "3" , mkMsg 12 "3" , mkMsg 13 "8" , mkMsg 14 "203" , mkMsg 15 "23" , mkMsg 16 "winner" , mkMsg 25 "whatever" ] test = do rs <- mapM (post epAddr . toJSON) msgs mapM_ (\(m, r) -> do putStrLn $ "--> " ++ show m putStrLn $ "<-- " ++ show (r ^? responseBody)) (zip msgs rs)
ryoia/utah-haskell
2015-09-17-solution/Client.hs
Haskell
apache-2.0
1,238
{-# LANGUAGE CPP, NondecreasingIndentation, TupleSections #-} {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-} ----------------------------------------------------------------------------- -- -- GHC Driver program -- -- (c) The University of Glasgow 2005 -- ----------------------------------------------------------------------------- module Main (main) where -- The official GHC API import qualified GHC import GHC ( -- DynFlags(..), HscTarget(..), -- GhcMode(..), GhcLink(..), Ghc, GhcMonad(..), LoadHowMuch(..) ) import CmdLineParser -- Implementations of the various modes (--show-iface, mkdependHS. etc.) import LoadIface ( showIface ) import HscMain ( newHscEnv ) import DriverPipeline ( oneShot, compileFile, mergeRequirement ) import DriverMkDepend ( doMkDependHS ) #ifdef GHCI import InteractiveUI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings ) #endif -- Various other random stuff that we need import Config import Constants import HscTypes import Packages ( pprPackages, pprPackagesSimple, pprModuleMap ) import DriverPhases import BasicTypes ( failed ) import StaticFlags import DynFlags import ErrUtils import FastString import Outputable import SrcLoc import Util import Panic import UniqSupply import MonadUtils ( liftIO ) -- Imports for --abi-hash import LoadIface ( loadUserInterface ) import Module ( mkModuleName ) import Finder ( findImportedModule, cannotFindInterface ) import TcRnMonad ( initIfaceCheck ) import Binary ( openBinMem, put_, fingerprintBinMem ) -- Standard Haskell libraries import System.IO import System.Environment import System.Exit import System.FilePath import Control.Monad import Data.Char import Data.List import Data.Maybe ----------------------------------------------------------------------------- -- ToDo: -- time commands when run with -v -- user ways -- Win32 support: proper signal handling -- reading the package configuration file is too slow -- -K<size> ----------------------------------------------------------------------------- -- GHC's command-line interface main :: IO () main = do initGCStatistics -- See Note [-Bsymbolic and hooks] hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering -- Handle GHC-specific character encoding flags, allowing us to control how -- GHC produces output regardless of OS. env <- getEnvironment case lookup "GHC_CHARENC" env of Just "UTF-8" -> do hSetEncoding stdout utf8 hSetEncoding stderr utf8 _ -> do -- Avoid GHC erroring out when trying to display unhandled characters hSetTranslit stdout hSetTranslit stderr GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do -- 1. extract the -B flag from the args argv0 <- getArgs let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0 mbMinusB | null minusB_args = Nothing | otherwise = Just (drop 2 (last minusB_args)) let argv1' = map (mkGeneralLocated "on the commandline") argv1 (argv2, staticFlagWarnings) <- parseStaticFlags argv1' -- 2. Parse the "mode" flags (--make, --interactive etc.) (mode, argv3, modeFlagWarnings) <- parseModeFlags argv2 let flagWarnings = staticFlagWarnings ++ modeFlagWarnings -- If all we want to do is something like showing the version number -- then do it now, before we start a GHC session etc. This makes -- getting basic information much more resilient. -- In particular, if we wait until later before giving the version -- number then bootstrapping gets confused, as it tries to find out -- what version of GHC it's using before package.conf exists, so -- starting the session fails. case mode of Left preStartupMode -> do case preStartupMode of ShowSupportedExtensions -> showSupportedExtensions ShowVersion -> showVersion ShowNumVersion -> putStrLn cProjectVersion ShowOptions isInteractive -> showOptions isInteractive Right postStartupMode -> -- start our GHC session GHC.runGhc mbMinusB $ do dflags <- GHC.getSessionDynFlags case postStartupMode of Left preLoadMode -> liftIO $ do case preLoadMode of ShowInfo -> showInfo dflags ShowGhcUsage -> showGhcUsage dflags ShowGhciUsage -> showGhciUsage dflags PrintWithDynFlags f -> putStrLn (f dflags) Right postLoadMode -> main' postLoadMode dflags argv3 flagWarnings main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String] -> Ghc () main' postLoadMode dflags0 args flagWarnings = do -- set the default GhcMode, HscTarget and GhcLink. The HscTarget -- can be further adjusted on a module by module basis, using only -- the -fvia-C and -fasm flags. If the default HscTarget is not -- HscC or HscAsm, -fvia-C and -fasm have no effect. let dflt_target = hscTarget dflags0 (mode, lang, link) = case postLoadMode of DoInteractive -> (CompManager, HscInterpreted, LinkInMemory) DoEval _ -> (CompManager, HscInterpreted, LinkInMemory) DoMake -> (CompManager, dflt_target, LinkBinary) DoMkDependHS -> (MkDepend, dflt_target, LinkBinary) DoAbiHash -> (OneShot, dflt_target, LinkBinary) DoMergeRequirements -> (OneShot, dflt_target, LinkBinary) _ -> (OneShot, dflt_target, LinkBinary) let dflags1 = case lang of HscInterpreted -> let platform = targetPlatform dflags0 dflags0a = updateWays $ dflags0 { ways = interpWays } dflags0b = foldl gopt_set dflags0a $ concatMap (wayGeneralFlags platform) interpWays dflags0c = foldl gopt_unset dflags0b $ concatMap (wayUnsetGeneralFlags platform) interpWays in dflags0c _ -> dflags0 dflags2 = dflags1{ ghcMode = mode, hscTarget = lang, ghcLink = link, verbosity = case postLoadMode of DoEval _ -> 0 _other -> 1 } -- turn on -fimplicit-import-qualified for GHCi now, so that it -- can be overriden from the command-line -- XXX: this should really be in the interactive DynFlags, but -- we don't set that until later in interactiveUI dflags3 | DoInteractive <- postLoadMode = imp_qual_enabled | DoEval _ <- postLoadMode = imp_qual_enabled | otherwise = dflags2 where imp_qual_enabled = dflags2 `gopt_set` Opt_ImplicitImportQualified -- The rest of the arguments are "dynamic" -- Leftover ones are presumably files (dflags4, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags3 args GHC.prettyPrintGhcErrors dflags4 $ do let flagWarnings' = flagWarnings ++ dynamicFlagWarnings handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do liftIO $ handleFlagWarnings dflags4 flagWarnings' -- make sure we clean up after ourselves GHC.defaultCleanupHandler dflags4 $ do liftIO $ showBanner postLoadMode dflags4 let -- To simplify the handling of filepaths, we normalise all filepaths right -- away - e.g., for win32 platforms, backslashes are converted -- into forward slashes. normal_fileish_paths = map (normalise . unLoc) fileish_args (srcs, objs) = partition_args normal_fileish_paths [] [] dflags5 = dflags4 { ldInputs = map (FileOption "") objs ++ ldInputs dflags4 } -- we've finished manipulating the DynFlags, update the session _ <- GHC.setSessionDynFlags dflags5 dflags6 <- GHC.getSessionDynFlags hsc_env <- GHC.getSession ---------------- Display configuration ----------- case verbosity dflags6 of v | v == 4 -> liftIO $ dumpPackagesSimple dflags6 | v >= 5 -> liftIO $ dumpPackages dflags6 | otherwise -> return () when (verbosity dflags6 >= 3) $ do liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags) when (dopt Opt_D_dump_mod_map dflags6) . liftIO $ printInfoForUser (dflags6 { pprCols = 200 }) (pkgQual dflags6) (pprModuleMap dflags6) liftIO $ initUniqSupply (initialUnique dflags6) (uniqueIncrement dflags6) ---------------- Final sanity checking ----------- liftIO $ checkOptions postLoadMode dflags6 srcs objs ---------------- Do the business ----------- handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do case postLoadMode of ShowInterface f -> liftIO $ doShowIface dflags6 f DoMake -> doMake srcs DoMkDependHS -> doMkDependHS (map fst srcs) StopBefore p -> liftIO (oneShot hsc_env p srcs) DoInteractive -> ghciUI srcs Nothing DoEval exprs -> ghciUI srcs $ Just $ reverse exprs DoAbiHash -> abiHash (map fst srcs) DoMergeRequirements -> doMergeRequirements (map fst srcs) ShowPackages -> liftIO $ showPackages dflags6 liftIO $ dumpFinalStats dflags6 ghciUI :: [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc () #ifndef GHCI ghciUI _ _ = throwGhcException (CmdLineError "not built for interactive use") #else ghciUI = interactiveUI defaultGhciSettings #endif -- ----------------------------------------------------------------------------- -- Splitting arguments into source files and object files. This is where we -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source -- file indicating the phase specified by the -x option in force, if any. partition_args :: [String] -> [(String, Maybe Phase)] -> [String] -> ([(String, Maybe Phase)], [String]) partition_args [] srcs objs = (reverse srcs, reverse objs) partition_args ("-x":suff:args) srcs objs | "none" <- suff = partition_args args srcs objs | StopLn <- phase = partition_args args srcs (slurp ++ objs) | otherwise = partition_args rest (these_srcs ++ srcs) objs where phase = startPhase suff (slurp,rest) = break (== "-x") args these_srcs = zip slurp (repeat (Just phase)) partition_args (arg:args) srcs objs | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs | otherwise = partition_args args srcs (arg:objs) {- We split out the object files (.o, .dll) and add them to ldInputs for use by the linker. The following things should be considered compilation manager inputs: - haskell source files (strings ending in .hs, .lhs or other haskellish extension), - module names (not forgetting hierarchical module names), - things beginning with '-' are flags that were not recognised by the flag parser, and we want them to generate errors later in checkOptions, so we class them as source files (#5921) - and finally we consider everything not containing a '.' to be a comp manager input, as shorthand for a .hs or .lhs filename. Everything else is considered to be a linker object, and passed straight through to the linker. -} looks_like_an_input :: String -> Bool looks_like_an_input m = isSourceFilename m || looksLikeModuleName m || "-" `isPrefixOf` m || '.' `notElem` m -- ----------------------------------------------------------------------------- -- Option sanity checks -- | Ensure sanity of options. -- -- Throws 'UsageError' or 'CmdLineError' if not. checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO () -- Final sanity checking before kicking off a compilation (pipeline). checkOptions mode dflags srcs objs = do -- Complain about any unknown flags let unknown_opts = [ f | (f@('-':_), _) <- srcs ] when (notNull unknown_opts) (unknownFlagsErr unknown_opts) when (notNull (filter wayRTSOnly (ways dflags)) && isInterpretiveMode mode) $ hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi") -- -prof and --interactive are not a good combination when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays) && isInterpretiveMode mode) $ do throwGhcException (UsageError "--interactive can't be used with -prof or -static.") -- -ohi sanity check if (isJust (outputHi dflags) && (isCompManagerMode mode || srcs `lengthExceeds` 1)) then throwGhcException (UsageError "-ohi can only be used when compiling a single source file") else do -- -o sanity checking if (srcs `lengthExceeds` 1 && isJust (outputFile dflags) && not (isLinkMode mode)) then throwGhcException (UsageError "can't apply -o to multiple source files") else do let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags) when (not_linking && not (null objs)) $ hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs) -- Check that there are some input files -- (except in the interactive case) if null srcs && (null objs || not_linking) && needsInputsMode mode then throwGhcException (UsageError "no input files") else do case mode of StopBefore HCc | hscTarget dflags /= HscC -> throwGhcException $ UsageError $ "the option -C is only available with an unregisterised GHC" _ -> return () -- Verify that output files point somewhere sensible. verifyOutputFiles dflags -- Compiler output options -- Called to verify that the output files point somewhere valid. -- -- The assumption is that the directory portion of these output -- options will have to exist by the time 'verifyOutputFiles' -- is invoked. -- -- We create the directories for -odir, -hidir, -outputdir etc. ourselves if -- they don't exist, so don't check for those here (#2278). verifyOutputFiles :: DynFlags -> IO () verifyOutputFiles dflags = do let ofile = outputFile dflags when (isJust ofile) $ do let fn = fromJust ofile flg <- doesDirNameExist fn when (not flg) (nonExistentDir "-o" fn) let ohi = outputHi dflags when (isJust ohi) $ do let hi = fromJust ohi flg <- doesDirNameExist hi when (not flg) (nonExistentDir "-ohi" hi) where nonExistentDir flg dir = throwGhcException (CmdLineError ("error: directory portion of " ++ show dir ++ " does not exist (used with " ++ show flg ++ " option.)")) ----------------------------------------------------------------------------- -- GHC modes of operation type Mode = Either PreStartupMode PostStartupMode type PostStartupMode = Either PreLoadMode PostLoadMode data PreStartupMode = ShowVersion -- ghc -V/--version | ShowNumVersion -- ghc --numeric-version | ShowSupportedExtensions -- ghc --supported-extensions | ShowOptions Bool {- isInteractive -} -- ghc --show-options showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode showVersionMode = mkPreStartupMode ShowVersion showNumVersionMode = mkPreStartupMode ShowNumVersion showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions showOptionsMode = mkPreStartupMode (ShowOptions False) mkPreStartupMode :: PreStartupMode -> Mode mkPreStartupMode = Left isShowVersionMode :: Mode -> Bool isShowVersionMode (Left ShowVersion) = True isShowVersionMode _ = False isShowNumVersionMode :: Mode -> Bool isShowNumVersionMode (Left ShowNumVersion) = True isShowNumVersionMode _ = False data PreLoadMode = ShowGhcUsage -- ghc -? | ShowGhciUsage -- ghci -? | ShowInfo -- ghc --info | PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode showGhcUsageMode = mkPreLoadMode ShowGhcUsage showGhciUsageMode = mkPreLoadMode ShowGhciUsage showInfoMode = mkPreLoadMode ShowInfo printSetting :: String -> Mode printSetting k = mkPreLoadMode (PrintWithDynFlags f) where f dflags = fromMaybe (panic ("Setting not found: " ++ show k)) $ lookup k (compilerInfo dflags) mkPreLoadMode :: PreLoadMode -> Mode mkPreLoadMode = Right . Left isShowGhcUsageMode :: Mode -> Bool isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True isShowGhcUsageMode _ = False isShowGhciUsageMode :: Mode -> Bool isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True isShowGhciUsageMode _ = False data PostLoadMode = ShowInterface FilePath -- ghc --show-iface | DoMkDependHS -- ghc -M | StopBefore Phase -- ghc -E | -C | -S -- StopBefore StopLn is the default | DoMake -- ghc --make | DoInteractive -- ghc --interactive | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"] | DoAbiHash -- ghc --abi-hash | ShowPackages -- ghc --show-packages | DoMergeRequirements -- ghc --merge-requirements doMkDependHSMode, doMakeMode, doInteractiveMode, doAbiHashMode, showPackagesMode, doMergeRequirementsMode :: Mode doMkDependHSMode = mkPostLoadMode DoMkDependHS doMakeMode = mkPostLoadMode DoMake doInteractiveMode = mkPostLoadMode DoInteractive doAbiHashMode = mkPostLoadMode DoAbiHash showPackagesMode = mkPostLoadMode ShowPackages doMergeRequirementsMode = mkPostLoadMode DoMergeRequirements showInterfaceMode :: FilePath -> Mode showInterfaceMode fp = mkPostLoadMode (ShowInterface fp) stopBeforeMode :: Phase -> Mode stopBeforeMode phase = mkPostLoadMode (StopBefore phase) doEvalMode :: String -> Mode doEvalMode str = mkPostLoadMode (DoEval [str]) mkPostLoadMode :: PostLoadMode -> Mode mkPostLoadMode = Right . Right isDoInteractiveMode :: Mode -> Bool isDoInteractiveMode (Right (Right DoInteractive)) = True isDoInteractiveMode _ = False isStopLnMode :: Mode -> Bool isStopLnMode (Right (Right (StopBefore StopLn))) = True isStopLnMode _ = False isDoMakeMode :: Mode -> Bool isDoMakeMode (Right (Right DoMake)) = True isDoMakeMode _ = False isDoEvalMode :: Mode -> Bool isDoEvalMode (Right (Right (DoEval _))) = True isDoEvalMode _ = False #ifdef GHCI isInteractiveMode :: PostLoadMode -> Bool isInteractiveMode DoInteractive = True isInteractiveMode _ = False #endif -- isInterpretiveMode: byte-code compiler involved isInterpretiveMode :: PostLoadMode -> Bool isInterpretiveMode DoInteractive = True isInterpretiveMode (DoEval _) = True isInterpretiveMode _ = False needsInputsMode :: PostLoadMode -> Bool needsInputsMode DoMkDependHS = True needsInputsMode (StopBefore _) = True needsInputsMode DoMake = True needsInputsMode _ = False -- True if we are going to attempt to link in this mode. -- (we might not actually link, depending on the GhcLink flag) isLinkMode :: PostLoadMode -> Bool isLinkMode (StopBefore StopLn) = True isLinkMode DoMake = True isLinkMode DoInteractive = True isLinkMode (DoEval _) = True isLinkMode _ = False isCompManagerMode :: PostLoadMode -> Bool isCompManagerMode DoMake = True isCompManagerMode DoInteractive = True isCompManagerMode (DoEval _) = True isCompManagerMode _ = False -- ----------------------------------------------------------------------------- -- Parsing the mode flag parseModeFlags :: [Located String] -> IO (Mode, [Located String], [Located String]) parseModeFlags args = do let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) = runCmdLine (processArgs mode_flags args) (Nothing, [], []) mode = case mModeFlag of Nothing -> doMakeMode Just (m, _) -> m -- See Note [Handling errors when parsing commandline flags] unless (null errs1 && null errs2) $ throwGhcException $ errorsToGhcException $ map (("on the commandline", )) $ map unLoc errs1 ++ errs2 return (mode, flags' ++ leftover, warns) type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String]) -- mode flags sometimes give rise to new DynFlags (eg. -C, see below) -- so we collect the new ones and return them. mode_flags :: [Flag ModeM] mode_flags = [ ------- help / version ---------------------------------------------- defFlag "?" (PassFlag (setMode showGhcUsageMode)) , defFlag "-help" (PassFlag (setMode showGhcUsageMode)) , defFlag "V" (PassFlag (setMode showVersionMode)) , defFlag "-version" (PassFlag (setMode showVersionMode)) , defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode)) , defFlag "-info" (PassFlag (setMode showInfoMode)) , defFlag "-show-options" (PassFlag (setMode showOptionsMode)) , defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-show-packages" (PassFlag (setMode showPackagesMode)) ] ++ [ defFlag k' (PassFlag (setMode (printSetting k))) | k <- ["Project version", "Project Git commit id", "Booter version", "Stage", "Build platform", "Host platform", "Target platform", "Have interpreter", "Object splitting supported", "Have native code generator", "Support SMP", "Unregisterised", "Tables next to code", "RTS ways", "Leading underscore", "Debug on", "LibDir", "Global Package DB", "C compiler flags", "Gcc Linker flags", "Ld Linker flags"], let k' = "-print-" ++ map (replaceSpace . toLower) k replaceSpace ' ' = '-' replaceSpace c = c ] ++ ------- interfaces ---------------------------------------------------- [ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f) "--show-iface")) ------- primary modes ------------------------------------------------ , defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f addFlag "-no-link" f)) , defFlag "M" (PassFlag (setMode doMkDependHSMode)) , defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc))) , defFlag "C" (PassFlag (setMode (stopBeforeMode HCc))) , defFlag "S" (PassFlag (setMode (stopBeforeMode (As False)))) , defFlag "-make" (PassFlag (setMode doMakeMode)) , defFlag "-merge-requirements" (PassFlag (setMode doMergeRequirementsMode)) , defFlag "-interactive" (PassFlag (setMode doInteractiveMode)) , defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode)) , defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e")) ] setMode :: Mode -> String -> EwM ModeM () setMode newMode newFlag = liftEwM $ do (mModeFlag, errs, flags') <- getCmdLineState let (modeFlag', errs') = case mModeFlag of Nothing -> ((newMode, newFlag), errs) Just (oldMode, oldFlag) -> case (oldMode, newMode) of -- -c/--make are allowed together, and mean --make -no-link _ | isStopLnMode oldMode && isDoMakeMode newMode || isStopLnMode newMode && isDoMakeMode oldMode -> ((doMakeMode, "--make"), []) -- If we have both --help and --interactive then we -- want showGhciUsage _ | isShowGhcUsageMode oldMode && isDoInteractiveMode newMode -> ((showGhciUsageMode, oldFlag), []) | isShowGhcUsageMode newMode && isDoInteractiveMode oldMode -> ((showGhciUsageMode, newFlag), []) -- If we have both -e and --interactive then -e always wins _ | isDoEvalMode oldMode && isDoInteractiveMode newMode -> ((oldMode, oldFlag), []) | isDoEvalMode newMode && isDoInteractiveMode oldMode -> ((newMode, newFlag), []) -- Otherwise, --help/--version/--numeric-version always win | isDominantFlag oldMode -> ((oldMode, oldFlag), []) | isDominantFlag newMode -> ((newMode, newFlag), []) -- We need to accumulate eval flags like "-e foo -e bar" (Right (Right (DoEval esOld)), Right (Right (DoEval [eNew]))) -> ((Right (Right (DoEval (eNew : esOld))), oldFlag), errs) -- Saying e.g. --interactive --interactive is OK _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs) -- --interactive and --show-options are used together (Right (Right DoInteractive), Left (ShowOptions _)) -> ((Left (ShowOptions True), "--interactive --show-options"), errs) (Left (ShowOptions _), (Right (Right DoInteractive))) -> ((Left (ShowOptions True), "--show-options --interactive"), errs) -- Otherwise, complain _ -> let err = flagMismatchErr oldFlag newFlag in ((oldMode, oldFlag), err : errs) putCmdLineState (Just modeFlag', errs', flags') where isDominantFlag f = isShowGhcUsageMode f || isShowGhciUsageMode f || isShowVersionMode f || isShowNumVersionMode f flagMismatchErr :: String -> String -> String flagMismatchErr oldFlag newFlag = "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'" addFlag :: String -> String -> EwM ModeM () addFlag s flag = liftEwM $ do (m, e, flags') <- getCmdLineState putCmdLineState (m, e, mkGeneralLocated loc s : flags') where loc = "addFlag by " ++ flag ++ " on the commandline" -- ---------------------------------------------------------------------------- -- Run --make mode doMake :: [(String,Maybe Phase)] -> Ghc () doMake srcs = do let (hs_srcs, non_hs_srcs) = partition haskellish srcs haskellish (f,Nothing) = looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f haskellish (_,Just phase) = phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcxx, CmmCpp, Cmm , StopLn] hsc_env <- GHC.getSession -- if we have no haskell sources from which to do a dependency -- analysis, then just do one-shot compilation and/or linking. -- This means that "ghc Foo.o Bar.o -o baz" links the program as -- we expect. if (null hs_srcs) then liftIO (oneShot hsc_env StopLn srcs) else do o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x) non_hs_srcs dflags <- GHC.getSessionDynFlags let dflags' = dflags { ldInputs = map (FileOption "") o_files ++ ldInputs dflags } _ <- GHC.setSessionDynFlags dflags' targets <- mapM (uncurry GHC.guessTarget) hs_srcs GHC.setTargets targets ok_flag <- GHC.load LoadAllTargets when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1)) return () -- ---------------------------------------------------------------------------- -- Run --merge-requirements mode doMergeRequirements :: [String] -> Ghc () doMergeRequirements srcs = mapM_ doMergeRequirement srcs doMergeRequirement :: String -> Ghc () doMergeRequirement src = do hsc_env <- getSession liftIO $ mergeRequirement hsc_env (mkModuleName src) -- --------------------------------------------------------------------------- -- --show-iface mode doShowIface :: DynFlags -> FilePath -> IO () doShowIface dflags file = do hsc_env <- newHscEnv dflags showIface hsc_env file -- --------------------------------------------------------------------------- -- Various banners and verbosity output. showBanner :: PostLoadMode -> DynFlags -> IO () showBanner _postLoadMode dflags = do let verb = verbosity dflags #ifdef GHCI -- Show the GHCi banner when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg #endif -- Display details of the configuration in verbose mode when (verb >= 2) $ do hPutStr stderr "Glasgow Haskell Compiler, Version " hPutStr stderr cProjectVersion hPutStr stderr ", stage " hPutStr stderr cStage hPutStr stderr " booted by GHC version " hPutStrLn stderr cBooterVersion -- We print out a Read-friendly string, but a prettier one than the -- Show instance gives us showInfo :: DynFlags -> IO () showInfo dflags = do let sq x = " [" ++ x ++ "\n ]" putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags showSupportedExtensions :: IO () showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions showVersion :: IO () showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion) showOptions :: Bool -> IO () showOptions isInteractive = putStr (unlines availableOptions) where availableOptions = concat [ flagsForCompletion isInteractive, map ('-':) (concat [ getFlagNames mode_flags , (filterUnwantedStatic . getFlagNames $ flagsStatic) , flagsStaticNames ]) ] getFlagNames opts = map flagName opts -- this is a hack to get rid of two unwanted entries that get listed -- as static flags. Hopefully this hack will disappear one day together -- with static flags filterUnwantedStatic = filter (`notElem`["f", "fno-"]) showGhcUsage :: DynFlags -> IO () showGhcUsage = showUsage False showGhciUsage :: DynFlags -> IO () showGhciUsage = showUsage True showUsage :: Bool -> DynFlags -> IO () showUsage ghci dflags = do let usage_path = if ghci then ghciUsagePath dflags else ghcUsagePath dflags usage <- readFile usage_path dump usage where dump "" = return () dump ('$':'$':s) = putStr progName >> dump s dump (c:s) = putChar c >> dump s dumpFinalStats :: DynFlags -> IO () dumpFinalStats dflags = when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags dumpFastStringStats :: DynFlags -> IO () dumpFastStringStats dflags = do buckets <- getFastStringTable let (entries, longest, has_z) = countFS 0 0 0 buckets msg = text "FastString stats:" $$ nest 4 (vcat [text "size: " <+> int (length buckets), text "entries: " <+> int entries, text "longest chain: " <+> int longest, text "has z-encoding: " <+> (has_z `pcntOf` entries) ]) -- we usually get more "has z-encoding" than "z-encoded", because -- when we z-encode a string it might hash to the exact same string, -- which will is not counted as "z-encoded". Only strings whose -- Z-encoding is different from the original string are counted in -- the "z-encoded" total. putMsg dflags msg where x `pcntOf` y = int ((x * 100) `quot` y) <> char '%' countFS :: Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int) countFS entries longest has_z [] = (entries, longest, has_z) countFS entries longest has_z (b:bs) = let len = length b longest' = max len longest entries' = entries + len has_zs = length (filter hasZEncoding b) in countFS entries' longest' (has_z + has_zs) bs showPackages, dumpPackages, dumpPackagesSimple :: DynFlags -> IO () showPackages dflags = putStrLn (showSDoc dflags (pprPackages dflags)) dumpPackages dflags = putMsg dflags (pprPackages dflags) dumpPackagesSimple dflags = putMsg dflags (pprPackagesSimple dflags) -- ----------------------------------------------------------------------------- -- ABI hash support {- ghc --abi-hash Data.Foo System.Bar Generates a combined hash of the ABI for modules Data.Foo and System.Bar. The modules must already be compiled, and appropriate -i options may be necessary in order to find the .hi files. This is used by Cabal for generating the ComponentId for a package. The ComponentId must change when the visible ABI of the package chagnes, so during registration Cabal calls ghc --abi-hash to get a hash of the package's ABI. -} -- | Print ABI hash of input modules. -- -- The resulting hash is the MD5 of the GHC version used (Trac #5328, -- see 'hiVersion') and of the existing ABI hash from each module (see -- 'mi_mod_hash'). abiHash :: [String] -- ^ List of module names -> Ghc () abiHash strs = do hsc_env <- getSession let dflags = hsc_dflags hsc_env liftIO $ do let find_it str = do let modname = mkModuleName str r <- findImportedModule hsc_env modname Nothing case r of Found _ m -> return m _error -> throwGhcException $ CmdLineError $ showSDoc dflags $ cannotFindInterface dflags modname r mods <- mapM find_it strs let get_iface modl = loadUserInterface False (text "abiHash") modl ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods bh <- openBinMem (3*1024) -- just less than a block put_ bh hiVersion -- package hashes change when the compiler version changes (for now) -- see #5328 mapM_ (put_ bh . mi_mod_hash) ifaces f <- fingerprintBinMem bh putStrLn (showPpr dflags f) -- ----------------------------------------------------------------------------- -- Util unknownFlagsErr :: [String] -> a unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs where oneError f = "unrecognised flag: " ++ f ++ "\n" ++ (case fuzzyMatch f (nub allFlags) of [] -> "" suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs)) {- Note [-Bsymbolic and hooks] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Bsymbolic is a flag that prevents the binding of references to global symbols to symbols outside the shared library being compiled (see `man ld`). When dynamically linking, we don't use -Bsymbolic on the RTS package: that is because we want hooks to be overridden by the user, we don't want to constrain them to the RTS package. Unfortunately this seems to have broken somehow on OS X: as a result, defaultHooks (in hschooks.c) is not called, which does not initialize the GC stats. As a result, this breaks things like `:set +s` in GHCi (#8754). As a hacky workaround, we instead call 'defaultHooks' directly to initalize the flags in the RTS. A byproduct of this, I believe, is that hooks are likely broken on OS X when dynamically linking. But this probably doesn't affect most people since we're linking GHC dynamically, but most things themselves link statically. -} foreign import ccall safe "initGCStatistics" initGCStatistics :: IO ()
AlexanderPankiv/ghc
ghc/Main.hs
Haskell
bsd-3-clause
36,717
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} -- | This module implements predicate pushdown on comprehensions. module Database.DSH.CL.Opt.PredPushdown ( predpushdownR ) where import Control.Arrow import qualified Data.List.NonEmpty as N import qualified Data.Set as S import Database.DSH.CL.Kure import Database.DSH.CL.Lang import Database.DSH.CL.Opt.Auxiliary import qualified Database.DSH.CL.Primitives as P import Database.DSH.Common.Lang import Database.DSH.Common.Nat import Database.DSH.Common.Kure {-# ANN module "HLint: ignore Reduce duplication" #-} -------------------------------------------------------------------------------- -- Auxiliary functions -- | Return path to occurence of variable x varPathT :: Ident -> TransformC CL PathC varPathT x = do Var _ x' <- promoteT idR guardM $ x == x' snocPathToPath <$> absPathT -- | Collect all paths to variable x in the current expression and -- turn them into relative paths. allVarPathsT :: Ident -> TransformC CL [PathC] allVarPathsT x = do varPaths <- collectT $ varPathT x guardM $ not $ null varPaths parentPathLen <- length . snocPathToPath <$> absPathT let localPaths = map (init . drop parentPathLen) varPaths return localPaths -------------------------------------------------------------------------- -- Push a guard into a branch of a join operator -- | Try to push predicate into the left input of a binary operator -- which produces tuples: equijoin, nestjoin pushLeftTupleR :: Ident -> Expr -> RewriteC CL pushLeftTupleR x p = do AppE2 t op xs ys <- promoteT idR let predTrans = constT $ return $ inject p localPaths <- predTrans >>> allVarPathsT x ExprCL p' <- predTrans >>> andR (map (unTuplifyPathR (== TupElem First)) localPaths) let xst = typeOf xs let filterComp = Comp xst (Var (elemT xst) x) (BindQ x xs :* S (GuardQ p')) return $ inject $ AppE2 t op filterComp ys -- | Try to push predicate into the right input of a binary operator -- which produces tuples: equijoin pushRightTupleR :: Ident -> Expr -> RewriteC CL pushRightTupleR x p = do AppE2 t op xs ys <- promoteT idR let predTrans = constT $ return $ inject p localPaths <- predTrans >>> allVarPathsT x ExprCL p' <- predTrans >>> andR (map (unTuplifyPathR (== TupElem (Next First))) localPaths) let yst = typeOf ys let filterComp = Comp yst (Var (elemT yst) x) (BindQ x ys :* S (GuardQ p')) return $ inject $ AppE2 t op xs filterComp pushLeftOrRightTupleR :: Ident -> Expr -> RewriteC CL pushLeftOrRightTupleR x p = pushLeftTupleR x p <+ pushRightTupleR x p -- | Try to push predicates into the left input of a binary operator -- which produces only the left input, i.e. semijoin, antijoin pushLeftR :: Ident -> Expr -> RewriteC CL pushLeftR x p = do AppE2 ty op xs ys <- promoteT idR let xst = typeOf xs let xs' = Comp xst (Var (elemT xst) x) (BindQ x xs :* (S $ GuardQ p)) return $ inject $ AppE2 ty op xs' ys -------------------------------------------------------------------------- -- Merging of join predicates into already established theta-join -- operators -- -- A predicate can be merged into a theta-join as an additional -- conjunct if it has the shape of a join predicate and if its left -- expression refers only to the fst component of the join pair and -- the right expression refers only to the snd component (or vice -- versa). mkMergeableJoinPredT :: Ident -> Expr -> BinRelOp -> Expr -> TransformC CL (JoinConjunct ScalarExpr) mkMergeableJoinPredT x leftExpr op rightExpr = do let constLeftExpr = constT $ return $ inject leftExpr constRightExpr = constT $ return $ inject rightExpr leftVarPaths <- constLeftExpr >>> allVarPathsT x rightVarPaths <- constRightExpr >>> allVarPathsT x leftExpr' <- constLeftExpr >>> andR (map (unTuplifyPathR (== TupElem First)) leftVarPaths) >>> projectT >>> toScalarExprT x rightExpr' <- constRightExpr >>> andR (map (unTuplifyPathR (== TupElem (Next First))) rightVarPaths) >>> projectT >>> toScalarExprT x return $ JoinConjunct leftExpr' op rightExpr' mirrorRelOp :: BinRelOp -> BinRelOp mirrorRelOp Eq = Eq mirrorRelOp Gt = Lt mirrorRelOp GtE = LtE mirrorRelOp Lt = Gt mirrorRelOp LtE = GtE mirrorRelOp NEq = NEq splitMergeablePredT :: Ident -> Expr -> TransformC CL (JoinConjunct ScalarExpr) splitMergeablePredT x p = do ExprCL (BinOp _ (SBRelOp op) leftExpr rightExpr) <- return $ inject p guardM $ freeVars p == [x] -- We might have e1(fst x) op e2(snd x) or e1(snd x) op e2(fst x) mkMergeableJoinPredT x leftExpr op rightExpr <+ mkMergeableJoinPredT x rightExpr (mirrorRelOp op) leftExpr -- | If a predicate can be turned into a join predicate, merge it into -- the current theta join. mergePredIntoJoinR :: Ident -> Expr -> RewriteC CL mergePredIntoJoinR x p = do AppE2 t (ThetaJoin (JoinPred ps)) xs ys <- promoteT idR joinConjunct <- splitMergeablePredT x p let extendedJoin = ThetaJoin (JoinPred $ joinConjunct N.<| ps) return $ inject $ AppE2 t extendedJoin xs ys -- | Push into the /first/ argument (input) of some operator that -- commutes with selection. -- This was nicer with a higher-order 'sortWith'. With first-order -- 'sort', we have to push the predicate into both arguments, which -- works only if the comprehension for the sorting criteria is still -- in its original form. pushSortInputR :: Ident -> Expr -> RewriteC CL pushSortInputR x p = do AppE1 t Sort xs <- promoteT idR let xst = typeOf xs xt = elemT xt genVar = Var xt x p' <- substM x (P.fst genVar) p let restrictedInput = Comp xst genVar (BindQ x xs :* S (GuardQ p')) return $ inject $ AppE1 t Sort restrictedInput -------------------------------------------------------------------------- -- Take remaining comprehension guards and try to push them into the -- generator. This might be accomplished by either merging it into a -- join, pushing it into a join input or pushing it through some other -- operator that commutes with selection (e.g. sorting). pushPredicateR :: Ident -> Expr -> RewriteC CL pushPredicateR x p = readerT $ \e -> case e of -- First, try to merge the predicate into the join. For -- regular joins and products, non-join predicates might apply -- to the left or right input. ExprCL (AppE2 _ (ThetaJoin _) _ _) -> mergePredIntoJoinR x p <+ pushLeftOrRightTupleR x p ExprCL (AppE2 _ CartProduct _ _) -> pushLeftOrRightTupleR x p -- For nesting operators, a guard can only refer to the left -- input, i.e. the original outer generator. ExprCL NestJoinP{} -> pushLeftTupleR x p ExprCL GroupJoinP{} -> pushLeftTupleR x p -- Semi- and Antijoin operators produce a subset of their left -- input. A filter can only apply to the left input, -- consequently. ExprCL (AppE2 _ (SemiJoin _) _ _) -> pushLeftR x p ExprCL (AppE2 _ (AntiJoin _) _ _) -> pushLeftR x p -- Sorting commutes with selection ExprCL (AppE1 _ Sort _) -> pushSortInputR x p _ -> fail "expression does not allow predicate pushing" pushQualsR :: RewriteC CL pushQualsR = do BindQ x _ :* GuardQ p :* qs <- promoteT idR [x'] <- return $ freeVars p guardM $ x == x' ExprCL gen' <- pathT [QualsHead, BindQualExpr] (pushPredicateR x p) return $ inject $ BindQ x gen' :* qs pushQualsEndR :: RewriteC CL pushQualsEndR = do BindQ x _ :* S (GuardQ p) <- promoteT idR [x'] <- return $ freeVars p guardM $ x == x' ExprCL gen' <- pathT [QualsHead, BindQualExpr] (pushPredicateR x p) return $ inject $ S $ BindQ x gen' pushDownSinglePredR :: RewriteC CL pushDownSinglePredR = do Comp{} <- promoteT idR childR CompQuals (promoteR $ pushQualsR <+ pushQualsEndR) pushDownPredsR :: MergeGuard pushDownPredsR comp guard guardsToTry leftOverGuards = do let C ty h qs = comp env <- S.fromList . inScopeNames <$> contextT let compExpr = ExprCL $ Comp ty h (insertGuard guard env qs) ExprCL (Comp _ _ qs') <- constT (return compExpr) >>> pushDownSinglePredR return (C ty h qs', guardsToTry, leftOverGuards) -- | Push down all guards in a qualifier list, if possible. predpushdownR :: RewriteC CL predpushdownR = logR "predpushdown" $ mergeGuardsIterR pushDownPredsR
ulricha/dsh
src/Database/DSH/CL/Opt/PredPushdown.hs
Haskell
bsd-3-clause
8,803
-- print information about the current package -- (reads the cached build info, so only works after 'cabal configure') import Prelude hiding (print) import Distribution.Simple import Distribution.Simple.LocalBuildInfo import Distribution.Text import System.Environment readLocalBuildInfo :: IO LocalBuildInfo readLocalBuildInfo = do text <- readFile "dist/setup-config" let body = dropWhile (/= '\n') text return (read body) print :: Text a => a -> IO () print x = putStrLn (display x) main = do arg <- getArgs lbi <- readLocalBuildInfo let lpc = localPkgDescr lbi let pid = packageId lpc case arg of ["--package"] -> print pid ["--package-name"] -> print (pkgName pid) ["--package-version"] -> print (pkgVersion pid)
Toxaris/pts
src-tools/package-info.hs
Haskell
bsd-3-clause
768
module Spotify.Error ( Error(..), spotifyError ) where import qualified Bindings.Spotify.Error as SP data Error = Ok | ClientTooOld | UnableToContactServer | BadUsernameOrPassword | UserBanned | UserNeedsPremium spotifyError :: SP.Error -> Error spotifyError err | err == SP.ok = Ok | err == SP.clientTooOld = ClientTooOld | err == SP.unableToContactServer = UnableToContactServer | err == SP.userBanned = UserBanned | err == SP.userNeedsPremium = UserNeedsPremium
mrehayden1/harmony
Spotify/Error.hs
Haskell
bsd-3-clause
639
-- | Immediate operand module Haskus.Arch.X86_64.ISA.Immediate ( X86ImmFamP , X86ImmFamT , X86ImmFam , X86Imm , Imm (..) , immFamFixedSize , immFamOpSize , immFamOpSizeSE , immFamConst ) where import Haskus.Arch.X86_64.ISA.Size import Haskus.Arch.X86_64.ISA.Solver import Haskus.Arch.Common.Immediate import Haskus.Utils.Solver import Haskus.Format.Binary.Word data ImmType = ImmGeneric deriving (Show,Eq,Ord) type X86ImmFamP = ImmFamP X86Pred X86Err ImmType OperandSize type X86ImmFamT = ImmFamT ImmType OperandSize type X86ImmFam t = ImmFam t ImmType OperandSize type X86Imm = Imm ImmType OperandSize -- | Fixed size immediate immFamFixedSize :: OperandSize -> X86ImmFamP immFamFixedSize s = ImmFam { immFamSize = Terminal s , immFamSignExtended = Terminal Nothing , immFamValue = Terminal Nothing , immFamType = Terminal Nothing } -- | Operand-sized immediate immFamOpSize :: X86ImmFamP immFamOpSize = ImmFam { immFamSize = pOpSize64 OpSize8 OpSize16 OpSize32 OpSize64 , immFamSignExtended = Terminal Nothing , immFamValue = Terminal Nothing , immFamType = Terminal (Just ImmGeneric) } -- | Operand-sized immediate (size-extendable if the bit is set or in 64-bit -- mode) immFamOpSizeSE :: X86ImmFamP immFamOpSizeSE = ImmFam { immFamSize = orderedNonTerminal [ (pForce8bit , Terminal OpSize8) , (pSignExtendBit , Terminal OpSize8) , (pOverriddenOperationSize64 OpSize16, Terminal OpSize16) , (pOverriddenOperationSize64 OpSize32, Terminal OpSize32) , (pOverriddenOperationSize64 OpSize64, Terminal OpSize32) -- sign-extend ] , immFamSignExtended = orderedNonTerminal [ (pOverriddenOperationSize64 OpSize64, Terminal $ Just OpSize64) , (pSignExtendBit , NonTerminal [ (pOverriddenOperationSize64 OpSize16, Terminal $ Just OpSize16) , (pOverriddenOperationSize64 OpSize32, Terminal $ Just OpSize32) ]) , (CBool True , Terminal Nothing) ] , immFamValue = Terminal Nothing , immFamType = Terminal (Just ImmGeneric) } -- | Constant immediate immFamConst :: OperandSize -> Word64 -> X86ImmFamP immFamConst s v = ImmFam { immFamSize = Terminal s , immFamSignExtended = Terminal Nothing , immFamValue = Terminal (Just v) , immFamType = Terminal Nothing }
hsyl20/ViperVM
haskus-system/src/lib/Haskus/Arch/X86_64/ISA/Immediate.hs
Haskell
bsd-3-clause
2,513
{-# OPTIONS -Wall -Werror #-} module Test.TestEaster where import Data.Time.Calendar.Easter import Data.Time.Calendar import Data.Time.Format import Test.TestUtil import Test.TestEasterRef -- days :: [Day] days = [ModifiedJulianDay 53000 .. ModifiedJulianDay 53014] showWithWDay :: Day -> String showWithWDay = formatTime defaultTimeLocale "%F %A" testEaster :: Test testEaster = pureTest "testEaster" $ let ds = unlines $ map (\day -> unwords [ showWithWDay day, "->" , showWithWDay (sundayAfter day)]) days f y = unwords [ show y ++ ", Gregorian: moon," , show (gregorianPaschalMoon y) ++ ": Easter," , showWithWDay (gregorianEaster y)] ++ "\n" g y = unwords [ show y ++ ", Orthodox : moon," , show (orthodoxPaschalMoon y) ++ ": Easter," , showWithWDay (orthodoxEaster y)] ++ "\n" in diff testEasterRef $ ds ++ concatMap (\y -> f y ++ g y) [2000..2020]
bergmark/time
test/Test/TestEaster.hs
Haskell
bsd-3-clause
1,068
{-# LANGUAGE BangPatterns, CPP, MagicHash #-} module Main ( main ) where import Data.Bits import GHC.Prim import GHC.Word #include "MachDeps.h" main = putStr (test_popCnt ++ "\n" ++ test_popCnt8 ++ "\n" ++ test_popCnt16 ++ "\n" ++ test_popCnt32 ++ "\n" ++ test_popCnt64 ++ "\n" ++ "\n" ) popcnt :: Word -> Word popcnt (W# w#) = W# (popCnt# w#) popcnt8 :: Word -> Word popcnt8 (W# w#) = W# (popCnt8# w#) popcnt16 :: Word -> Word popcnt16 (W# w#) = W# (popCnt16# w#) popcnt32 :: Word -> Word popcnt32 (W# w#) = W# (popCnt32# w#) popcnt64 :: Word64 -> Word popcnt64 (W64# w#) = #if SIZEOF_HSWORD == 4 W# (popCnt64# w#) #else W# (popCnt# w#) #endif -- Cribbed from https://gitlab.haskell.org/ghc/ghc/issues/3563 slowPopcnt :: Word -> Word slowPopcnt x = count' (bitSize x) x 0 where count' 0 _ !acc = acc count' n x acc = count' (n-1) (x `shiftR` 1) (acc + if x .&. 1 == 1 then 1 else 0) test_popCnt = test popcnt slowPopcnt test_popCnt8 = test popcnt8 (slowPopcnt . fromIntegral . (mask 8 .&.)) test_popCnt16 = test popcnt16 (slowPopcnt . fromIntegral . (mask 16 .&.)) test_popCnt32 = test popcnt32 (slowPopcnt . fromIntegral . (mask 32 .&.)) test_popCnt64 = test popcnt64 (slowPopcnt . fromIntegral . (mask 64 .&.)) mask n = (2 ^ n) - 1 test :: (Show a, Num a) => (a -> Word) -> (a -> Word) -> String test fast slow = case failing of [] -> "OK" ((_, e, a, i):xs) -> "FAIL\n" ++ " Input: " ++ show i ++ "\nExpected: " ++ show e ++ "\n Actual: " ++ show a where failing = dropWhile ( \(b,_,_,_) -> b) . map (\ x -> (slow x == fast x, slow x, fast x, x)) $ cases expected = map slow cases actual = map fast cases -- 10 random numbers #if SIZEOF_HSWORD == 4 cases = [1480294021,1626858410,2316287658,1246556957,3806579062,65945563, 1521588071,791321966,1355466914,2284998160] #elif SIZEOF_HSWORD == 8 cases = [11004539497957619752,5625461252166958202,1799960778872209546, 16979826074020750638,12789915432197771481,11680809699809094550, 13208678822802632247,13794454868797172383,13364728999716654549, 17516539991479925226] #else # error Unexpected word size #endif
sdiehl/ghc
testsuite/tests/codeGen/should_run/cgrun071.hs
Haskell
bsd-3-clause
2,285
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 ************************************************************************ * * \section[FloatIn]{Floating Inwards pass} * * ************************************************************************ The main purpose of @floatInwards@ is floating into branches of a case, so that we don't allocate things, save them on the stack, and then discover that they aren't needed in the chosen branch. -} {-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fprof-auto #-} module FloatIn ( floatInwards ) where #include "HsVersions.h" import GhcPrelude import CoreSyn import MkCore import HscTypes ( ModGuts(..) ) import CoreUtils import CoreFVs import CoreMonad ( CoreM ) import Id ( isOneShotBndr, idType, isJoinId, isJoinId_maybe ) import Var import Type import VarSet import Util import DynFlags import Outputable -- import Data.List ( mapAccumL ) import BasicTypes ( RecFlag(..), isRec ) {- Top-level interface function, @floatInwards@. Note that we do not actually float any bindings downwards from the top-level. -} floatInwards :: ModGuts -> CoreM ModGuts floatInwards pgm@(ModGuts { mg_binds = binds }) = do { dflags <- getDynFlags ; return (pgm { mg_binds = map (fi_top_bind dflags) binds }) } where fi_top_bind dflags (NonRec binder rhs) = NonRec binder (fiExpr dflags [] (freeVars rhs)) fi_top_bind dflags (Rec pairs) = Rec [ (b, fiExpr dflags [] (freeVars rhs)) | (b, rhs) <- pairs ] {- ************************************************************************ * * \subsection{Mail from Andr\'e [edited]} * * ************************************************************************ {\em Will wrote: What??? I thought the idea was to float as far inwards as possible, no matter what. This is dropping all bindings every time it sees a lambda of any kind. Help! } You are assuming we DO DO full laziness AFTER floating inwards! We have to [not float inside lambdas] if we don't. If we indeed do full laziness after the floating inwards (we could check the compilation flags for that) then I agree we could be more aggressive and do float inwards past lambdas. Actually we are not doing a proper full laziness (see below), which was another reason for not floating inwards past a lambda. This can easily be fixed. The problem is that we float lets outwards, but there are a few expressions which are not let bound, like case scrutinees and case alternatives. After floating inwards the simplifier could decide to inline the let and the laziness would be lost, e.g. \begin{verbatim} let a = expensive ==> \b -> case expensive of ... in \ b -> case a of ... \end{verbatim} The fix is \begin{enumerate} \item to let bind the algebraic case scrutinees (done, I think) and the case alternatives (except the ones with an unboxed type)(not done, I think). This is best done in the SetLevels.hs module, which tags things with their level numbers. \item do the full laziness pass (floating lets outwards). \item simplify. The simplifier inlines the (trivial) lets that were created but were not floated outwards. \end{enumerate} With the fix I think Will's suggestion that we can gain even more from strictness by floating inwards past lambdas makes sense. We still gain even without going past lambdas, as things may be strict in the (new) context of a branch (where it was floated to) or of a let rhs, e.g. \begin{verbatim} let a = something case x of in case x of alt1 -> case something of a -> a + a alt1 -> a + a ==> alt2 -> b alt2 -> b let a = something let b = case something of a -> a + a in let b = a + a ==> in (b,b) in (b,b) \end{verbatim} Also, even if a is not found to be strict in the new context and is still left as a let, if the branch is not taken (or b is not entered) the closure for a is not built. ************************************************************************ * * \subsection{Main floating-inwards code} * * ************************************************************************ -} type FreeVarSet = DIdSet type BoundVarSet = DIdSet data FloatInBind = FB BoundVarSet FreeVarSet FloatBind -- The FreeVarSet is the free variables of the binding. In the case -- of recursive bindings, the set doesn't include the bound -- variables. type FloatInBinds = [FloatInBind] -- In reverse dependency order (innermost binder first) fiExpr :: DynFlags -> FloatInBinds -- Binds we're trying to drop -- as far "inwards" as possible -> CoreExprWithFVs -- Input expr -> CoreExpr -- Result fiExpr _ to_drop (_, AnnLit lit) = ASSERT( null to_drop ) Lit lit fiExpr _ to_drop (_, AnnType ty) = ASSERT( null to_drop ) Type ty fiExpr _ to_drop (_, AnnVar v) = wrapFloats to_drop (Var v) fiExpr _ to_drop (_, AnnCoercion co) = wrapFloats to_drop (Coercion co) fiExpr dflags to_drop (_, AnnCast expr (co_ann, co)) = wrapFloats (drop_here ++ co_drop) $ Cast (fiExpr dflags e_drop expr) co where [drop_here, e_drop, co_drop] = sepBindsByDropPoint dflags False [freeVarsOf expr, freeVarsOfAnn co_ann] to_drop {- Applications: we do float inside applications, mainly because we need to get at all the arguments. The next simplifier run will pull out any silly ones. -} fiExpr dflags to_drop ann_expr@(_,AnnApp {}) = wrapFloats drop_here $ wrapFloats extra_drop $ mkTicks ticks $ mkApps (fiExpr dflags fun_drop ann_fun) (zipWith (fiExpr dflags) arg_drops ann_args) where (ann_fun, ann_args, ticks) = collectAnnArgsTicks tickishFloatable ann_expr fun_ty = exprType (deAnnotate ann_fun) fun_fvs = freeVarsOf ann_fun arg_fvs = map freeVarsOf ann_args (drop_here : extra_drop : fun_drop : arg_drops) = sepBindsByDropPoint dflags False (extra_fvs : fun_fvs : arg_fvs) to_drop -- Shortcut behaviour: if to_drop is empty, -- sepBindsByDropPoint returns a suitable bunch of empty -- lists without evaluating extra_fvs, and hence without -- peering into each argument (_, extra_fvs) = foldl add_arg (fun_ty, extra_fvs0) ann_args extra_fvs0 = case ann_fun of (_, AnnVar _) -> fun_fvs _ -> emptyDVarSet -- Don't float the binding for f into f x y z; see Note [Join points] -- for why we *can't* do it when f is a join point. (If f isn't a -- join point, floating it in isn't especially harmful but it's -- useless since the simplifier will immediately float it back out.) add_arg :: (Type,FreeVarSet) -> CoreExprWithFVs -> (Type,FreeVarSet) add_arg (fun_ty, extra_fvs) (_, AnnType ty) = (piResultTy fun_ty ty, extra_fvs) add_arg (fun_ty, extra_fvs) (arg_fvs, arg) | noFloatIntoArg arg arg_ty = (res_ty, extra_fvs `unionDVarSet` arg_fvs) | otherwise = (res_ty, extra_fvs) where (arg_ty, res_ty) = splitFunTy fun_ty {- Note [Do not destroy the let/app invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Watch out for f (x +# y) We don't want to float bindings into here f (case ... of { x -> x +# y }) because that might destroy the let/app invariant, which requires unlifted function arguments to be ok-for-speculation. Note [Join points] ~~~~~~~~~~~~~~~~~~ Generally, we don't need to worry about join points - there are places we're not allowed to float them, but since they can't have occurrences in those places, we're not tempted. We do need to be careful about jumps, however: joinrec j x y z = ... in jump j a b c Previous versions often floated the definition of a recursive function into its only non-recursive occurrence. But for a join point, this is a disaster: (joinrec j x y z = ... in jump j) a b c -- wrong! Every jump must be exact, so the jump to j must have three arguments. Hence we're careful not to float into the target of a jump (though we can float into the arguments just fine). Note [Floating in past a lambda group] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * We must be careful about floating inside a value lambda. That risks losing laziness. The float-out pass might rescue us, but then again it might not. * We must be careful about type lambdas too. At one time we did, and there is no risk of duplicating work thereby, but we do need to be careful. In particular, here is a bad case (it happened in the cichelli benchmark: let v = ... in let f = /\t -> \a -> ... ==> let f = /\t -> let v = ... in \a -> ... This is bad as now f is an updatable closure (update PAP) and has arity 0. * Hack alert! We only float in through one-shot lambdas, not (as you might guess) through lone big lambdas. Reason: we float *out* past big lambdas (see the test in the Lam case of FloatOut.floatExpr) and we don't want to float straight back in again. It *is* important to float into one-shot lambdas, however; see the remarks with noFloatIntoRhs. So we treat lambda in groups, using the following rule: Float in if (a) there is at least one Id, and (b) there are no non-one-shot Ids Otherwise drop all the bindings outside the group. This is what the 'go' function in the AnnLam case is doing. (Join points are handled similarly: a join point is considered one-shot iff it's non-recursive, so we float only into non-recursive join points.) Urk! if all are tyvars, and we don't float in, we may miss an opportunity to float inside a nested case branch Note [Floating coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~ We could, in principle, have a coercion binding like case f x of co { DEFAULT -> e1 e2 } It's not common to have a function that returns a coercion, but nothing in Core prohibits it. If so, 'co' might be mentioned in e1 or e2 /only in a type/. E.g. suppose e1 was let (x :: Int |> co) = blah in blah2 But, with coercions appearing in types, there is a complication: we might be floating in a "strict let" -- that is, a case. Case expressions mention their return type. We absolutely can't float a coercion binding inward to the point that the type of the expression it's about to wrap mentions the coercion. So we include the union of the sets of free variables of the types of all the drop points involved. If any of the floaters bind a coercion variable mentioned in any of the types, that binder must be dropped right away. -} fiExpr dflags to_drop lam@(_, AnnLam _ _) | noFloatIntoLam bndrs -- Dump it all here -- NB: Must line up with noFloatIntoRhs (AnnLam...); see Trac #7088 = wrapFloats to_drop (mkLams bndrs (fiExpr dflags [] body)) | otherwise -- Float inside = mkLams bndrs (fiExpr dflags to_drop body) where (bndrs, body) = collectAnnBndrs lam {- We don't float lets inwards past an SCC. ToDo: keep info on current cc, and when passing one, if it is not the same, annotate all lets in binds with current cc, change current cc to the new one and float binds into expr. -} fiExpr dflags to_drop (_, AnnTick tickish expr) | tickish `tickishScopesLike` SoftScope = Tick tickish (fiExpr dflags to_drop expr) | otherwise -- Wimp out for now - we could push values in = wrapFloats to_drop (Tick tickish (fiExpr dflags [] expr)) {- For @Lets@, the possible ``drop points'' for the \tr{to_drop} bindings are: (a)~in the body, (b1)~in the RHS of a NonRec binding, or~(b2), in each of the RHSs of the pairs of a @Rec@. Note that we do {\em weird things} with this let's binding. Consider: \begin{verbatim} let w = ... in { let v = ... w ... in ... v .. w ... } \end{verbatim} Look at the inner \tr{let}. As \tr{w} is used in both the bind and body of the inner let, we could panic and leave \tr{w}'s binding where it is. But \tr{v} is floatable further into the body of the inner let, and {\em then} \tr{w} will also be only in the body of that inner let. So: rather than drop \tr{w}'s binding here, we add it onto the list of things to drop in the outer let's body, and let nature take its course. Note [extra_fvs (1): avoid floating into RHS] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider let x=\y....t... in body. We do not necessarily want to float a binding for t into the RHS, because it'll immediately be floated out again. (It won't go inside the lambda else we risk losing work.) In letrec, we need to be more careful still. We don't want to transform let x# = y# +# 1# in letrec f = \z. ...x#...f... in ... into letrec f = let x# = y# +# 1# in \z. ...x#...f... in ... because now we can't float the let out again, because a letrec can't have unboxed bindings. So we make "extra_fvs" which is the rhs_fvs of such bindings, and arrange to dump bindings that bind extra_fvs before the entire let. Note [extra_fvs (2): free variables of rules] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider let x{rule mentioning y} = rhs in body Here y is not free in rhs or body; but we still want to dump bindings that bind y outside the let. So we augment extra_fvs with the idRuleAndUnfoldingVars of x. No need for type variables, hence not using idFreeVars. -} fiExpr dflags to_drop (_,AnnLet bind body) = fiExpr dflags (after ++ new_float : before) body -- to_drop is in reverse dependency order where (before, new_float, after) = fiBind dflags to_drop bind body_fvs body_fvs = freeVarsOf body {- Note [Floating primops] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We try to float-in a case expression over an unlifted type. The motivating example was Trac #5658: in particular, this change allows array indexing operations, which have a single DEFAULT alternative without any binders, to be floated inward. SIMD primops for unpacking SIMD vectors into an unboxed tuple of unboxed scalars also need to be floated inward, but unpacks have a single non-DEFAULT alternative that binds the elements of the tuple. We now therefore also support floating in cases with a single alternative that may bind values. But there are wrinkles * Which unlifted cases do we float? See PrimOp.hs Note [PrimOp can_fail and has_side_effects] which explains: - We can float-in can_fail primops, but we can't float them out. - But we can float a has_side_effects primop, but NOT inside a lambda, so for now we don't float them at all. Hence exprOkForSideEffects * Because we can float can-fail primops (array indexing, division) inwards but not outwards, we must be careful not to transform case a /# b of r -> f (F# r) ===> f (case a /# b of r -> F# r) because that creates a new thunk that wasn't there before. And because it can't be floated out (can_fail), the thunk will stay there. Disaster! (This happened in nofib 'simple' and 'scs'.) Solution: only float cases into the branches of other cases, and not into the arguments of an application, or the RHS of a let. This is somewhat conservative, but it's simple. And it still hits the cases like Trac #5658. This is implemented in sepBindsByJoinPoint; if is_case is False we dump all floating cases right here. * Trac #14511 is another example of why we want to restrict float-in of case-expressions. Consider case indexArray# a n of (# r #) -> writeArray# ma i (f r) Now, floating that indexing operation into the (f r) thunk will not create any new thunks, but it will keep the array 'a' alive for much longer than the programmer expected. So again, not floating a case into a let or argument seems like the Right Thing For @Case@, the possible drop points for the 'to_drop' bindings are: (a) inside the scrutinee (b) inside one of the alternatives/default (default FVs always /first/!). -} fiExpr dflags to_drop (_, AnnCase scrut case_bndr _ [(con,alt_bndrs,rhs)]) | isUnliftedType (idType case_bndr) , exprOkForSideEffects (deAnnotate scrut) -- See Note [Floating primops] = wrapFloats shared_binds $ fiExpr dflags (case_float : rhs_binds) rhs where case_float = FB (mkDVarSet (case_bndr : alt_bndrs)) scrut_fvs (FloatCase scrut' case_bndr con alt_bndrs) scrut' = fiExpr dflags scrut_binds scrut rhs_fvs = freeVarsOf rhs `delDVarSetList` (case_bndr : alt_bndrs) scrut_fvs = freeVarsOf scrut [shared_binds, scrut_binds, rhs_binds] = sepBindsByDropPoint dflags False [scrut_fvs, rhs_fvs] to_drop fiExpr dflags to_drop (_, AnnCase scrut case_bndr ty alts) = wrapFloats drop_here1 $ wrapFloats drop_here2 $ Case (fiExpr dflags scrut_drops scrut) case_bndr ty (zipWith fi_alt alts_drops_s alts) where -- Float into the scrut and alts-considered-together just like App [drop_here1, scrut_drops, alts_drops] = sepBindsByDropPoint dflags False [scrut_fvs, all_alts_fvs] to_drop -- Float into the alts with the is_case flag set (drop_here2 : alts_drops_s) | [ _ ] <- alts = [] : [alts_drops] | otherwise = sepBindsByDropPoint dflags True alts_fvs alts_drops scrut_fvs = freeVarsOf scrut alts_fvs = map alt_fvs alts all_alts_fvs = unionDVarSets alts_fvs alt_fvs (_con, args, rhs) = foldl delDVarSet (freeVarsOf rhs) (case_bndr:args) -- Delete case_bndr and args from free vars of rhs -- to get free vars of alt fi_alt to_drop (con, args, rhs) = (con, args, fiExpr dflags to_drop rhs) ------------------ fiBind :: DynFlags -> FloatInBinds -- Binds we're trying to drop -- as far "inwards" as possible -> CoreBindWithFVs -- Input binding -> DVarSet -- Free in scope of binding -> ( FloatInBinds -- Land these before , FloatInBind -- The binding itself , FloatInBinds) -- Land these after fiBind dflags to_drop (AnnNonRec id ann_rhs@(rhs_fvs, rhs)) body_fvs = ( extra_binds ++ shared_binds -- Land these before -- See Note [extra_fvs (1,2)] , FB (unitDVarSet id) rhs_fvs' -- The new binding itself (FloatLet (NonRec id rhs')) , body_binds ) -- Land these after where body_fvs2 = body_fvs `delDVarSet` id rule_fvs = bndrRuleAndUnfoldingVarsDSet id -- See Note [extra_fvs (2): free variables of rules] extra_fvs | noFloatIntoRhs NonRecursive id rhs = rule_fvs `unionDVarSet` rhs_fvs | otherwise = rule_fvs -- See Note [extra_fvs (1): avoid floating into RHS] -- No point in floating in only to float straight out again -- We *can't* float into ok-for-speculation unlifted RHSs -- But do float into join points [shared_binds, extra_binds, rhs_binds, body_binds] = sepBindsByDropPoint dflags False [extra_fvs, rhs_fvs, body_fvs2] to_drop -- Push rhs_binds into the right hand side of the binding rhs' = fiRhs dflags rhs_binds id ann_rhs rhs_fvs' = rhs_fvs `unionDVarSet` floatedBindsFVs rhs_binds `unionDVarSet` rule_fvs -- Don't forget the rule_fvs; the binding mentions them! fiBind dflags to_drop (AnnRec bindings) body_fvs = ( extra_binds ++ shared_binds , FB (mkDVarSet ids) rhs_fvs' (FloatLet (Rec (fi_bind rhss_binds bindings))) , body_binds ) where (ids, rhss) = unzip bindings rhss_fvs = map freeVarsOf rhss -- See Note [extra_fvs (1,2)] rule_fvs = mapUnionDVarSet bndrRuleAndUnfoldingVarsDSet ids extra_fvs = rule_fvs `unionDVarSet` unionDVarSets [ rhs_fvs | (bndr, (rhs_fvs, rhs)) <- bindings , noFloatIntoRhs Recursive bndr rhs ] (shared_binds:extra_binds:body_binds:rhss_binds) = sepBindsByDropPoint dflags False (extra_fvs:body_fvs:rhss_fvs) to_drop rhs_fvs' = unionDVarSets rhss_fvs `unionDVarSet` unionDVarSets (map floatedBindsFVs rhss_binds) `unionDVarSet` rule_fvs -- Don't forget the rule variables! -- Push rhs_binds into the right hand side of the binding fi_bind :: [FloatInBinds] -- one per "drop pt" conjured w/ fvs_of_rhss -> [(Id, CoreExprWithFVs)] -> [(Id, CoreExpr)] fi_bind to_drops pairs = [ (binder, fiRhs dflags to_drop binder rhs) | ((binder, rhs), to_drop) <- zipEqual "fi_bind" pairs to_drops ] ------------------ fiRhs :: DynFlags -> FloatInBinds -> CoreBndr -> CoreExprWithFVs -> CoreExpr fiRhs dflags to_drop bndr rhs | Just join_arity <- isJoinId_maybe bndr , let (bndrs, body) = collectNAnnBndrs join_arity rhs = mkLams bndrs (fiExpr dflags to_drop body) | otherwise = fiExpr dflags to_drop rhs ------------------ noFloatIntoLam :: [Var] -> Bool noFloatIntoLam bndrs = any bad bndrs where bad b = isId b && not (isOneShotBndr b) -- Don't float inside a non-one-shot lambda noFloatIntoRhs :: RecFlag -> Id -> CoreExprWithFVs' -> Bool -- ^ True if it's a bad idea to float bindings into this RHS noFloatIntoRhs is_rec bndr rhs | isJoinId bndr = isRec is_rec -- Joins are one-shot iff non-recursive | otherwise = noFloatIntoArg rhs (idType bndr) noFloatIntoArg :: CoreExprWithFVs' -> Type -> Bool noFloatIntoArg expr expr_ty | isUnliftedType expr_ty = True -- See Note [Do not destroy the let/app invariant] | AnnLam bndr e <- expr , (bndrs, _) <- collectAnnBndrs e = noFloatIntoLam (bndr:bndrs) -- Wrinkle 1 (a) || all isTyVar (bndr:bndrs) -- Wrinkle 1 (b) -- See Note [noFloatInto considerations] wrinkle 2 | otherwise -- Note [noFloatInto considerations] wrinkle 2 = exprIsTrivial deann_expr || exprIsHNF deann_expr where deann_expr = deAnnotate' expr {- Note [noFloatInto considerations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When do we want to float bindings into - noFloatIntoRHs: the RHS of a let-binding - noFloatIntoArg: the argument of a function application Definitely don't float in if it has unlifted type; that would destroy the let/app invariant. * Wrinkle 1: do not float in if (a) any non-one-shot value lambdas or (b) all type lambdas In both cases we'll float straight back out again NB: Must line up with fiExpr (AnnLam...); see Trac #7088 (a) is important: we /must/ float into a one-shot lambda group (which includes join points). This makes a big difference for things like f x# = let x = I# x# in let j = \() -> ...x... in if <condition> then normal-path else j () If x is used only in the error case join point, j, we must float the boxing constructor into it, else we box it every time which is very bad news indeed. * Wrinkle 2: for RHSs, do not float into a HNF; we'll just float right back out again... not tragic, but a waste of time. For function arguments we will still end up with this in-then-out stuff; consider letrec x = e in f x Here x is not a HNF, so we'll produce f (letrec x = e in x) which is OK... it's not that common, and we'll end up floating out again, in CorePrep if not earlier. Still, we use exprIsTrivial to catch this case (sigh) ************************************************************************ * * \subsection{@sepBindsByDropPoint@} * * ************************************************************************ This is the crucial function. The idea is: We have a wad of bindings that we'd like to distribute inside a collection of {\em drop points}; insides the alternatives of a \tr{case} would be one example of some drop points; the RHS and body of a non-recursive \tr{let} binding would be another (2-element) collection. So: We're given a list of sets-of-free-variables, one per drop point, and a list of floating-inwards bindings. If a binding can go into only one drop point (without suddenly making something out-of-scope), in it goes. If a binding is used inside {\em multiple} drop points, then it has to go in a you-must-drop-it-above-all-these-drop-points point. We have to maintain the order on these drop-point-related lists. -} -- pprFIB :: FloatInBinds -> SDoc -- pprFIB fibs = text "FIB:" <+> ppr [b | FB _ _ b <- fibs] sepBindsByDropPoint :: DynFlags -> Bool -- True <=> is case expression -> [FreeVarSet] -- One set of FVs per drop point -- Always at least two long! -> FloatInBinds -- Candidate floaters -> [FloatInBinds] -- FIRST one is bindings which must not be floated -- inside any drop point; the rest correspond -- one-to-one with the input list of FV sets -- Every input floater is returned somewhere in the result; -- none are dropped, not even ones which don't seem to be -- free in *any* of the drop-point fvs. Why? Because, for example, -- a binding (let x = E in B) might have a specialised version of -- x (say x') stored inside x, but x' isn't free in E or B. type DropBox = (FreeVarSet, FloatInBinds) sepBindsByDropPoint dflags is_case drop_pts floaters | null floaters -- Shortcut common case = [] : [[] | _ <- drop_pts] | otherwise = ASSERT( drop_pts `lengthAtLeast` 2 ) go floaters (map (\fvs -> (fvs, [])) (emptyDVarSet : drop_pts)) where n_alts = length drop_pts go :: FloatInBinds -> [DropBox] -> [FloatInBinds] -- The *first* one in the argument list is the drop_here set -- The FloatInBinds in the lists are in the reverse of -- the normal FloatInBinds order; that is, they are the right way round! go [] drop_boxes = map (reverse . snd) drop_boxes go (bind_w_fvs@(FB bndrs bind_fvs bind) : binds) drop_boxes@(here_box : fork_boxes) = go binds new_boxes where -- "here" means the group of bindings dropped at the top of the fork (used_here : used_in_flags) = [ fvs `intersectsDVarSet` bndrs | (fvs, _) <- drop_boxes] drop_here = used_here || cant_push n_used_alts = count id used_in_flags -- returns number of Trues in list. cant_push | is_case = n_used_alts == n_alts -- Used in all, don't push -- Remember n_alts > 1 || (n_used_alts > 1 && not (floatIsDupable dflags bind)) -- floatIsDupable: see Note [Duplicating floats] | otherwise = floatIsCase bind || n_used_alts > 1 -- floatIsCase: see Note [Floating primops] new_boxes | drop_here = (insert here_box : fork_boxes) | otherwise = (here_box : new_fork_boxes) new_fork_boxes = zipWithEqual "FloatIn.sepBinds" insert_maybe fork_boxes used_in_flags insert :: DropBox -> DropBox insert (fvs,drops) = (fvs `unionDVarSet` bind_fvs, bind_w_fvs:drops) insert_maybe box True = insert box insert_maybe box False = box go _ _ = panic "sepBindsByDropPoint/go" {- Note [Duplicating floats] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For case expressions we duplicate the binding if it is reasonably small, and if it is not used in all the RHSs This is good for situations like let x = I# y in case e of C -> error x D -> error x E -> ...not mentioning x... If the thing is used in all RHSs there is nothing gained, so we don't duplicate then. -} floatedBindsFVs :: FloatInBinds -> FreeVarSet floatedBindsFVs binds = mapUnionDVarSet fbFVs binds fbFVs :: FloatInBind -> DVarSet fbFVs (FB _ fvs _) = fvs wrapFloats :: FloatInBinds -> CoreExpr -> CoreExpr -- Remember FloatInBinds is in *reverse* dependency order wrapFloats [] e = e wrapFloats (FB _ _ fl : bs) e = wrapFloats bs (wrapFloat fl e) floatIsDupable :: DynFlags -> FloatBind -> Bool floatIsDupable dflags (FloatCase scrut _ _ _) = exprIsDupable dflags scrut floatIsDupable dflags (FloatLet (Rec prs)) = all (exprIsDupable dflags . snd) prs floatIsDupable dflags (FloatLet (NonRec _ r)) = exprIsDupable dflags r floatIsCase :: FloatBind -> Bool floatIsCase (FloatCase {}) = True floatIsCase (FloatLet {}) = False
ezyang/ghc
compiler/simplCore/FloatIn.hs
Haskell
bsd-3-clause
29,172
----------------------------------------------------------------------------- -- | -- Module : Control.Monad.RWS -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology, 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (multi-param classes, functional dependencies) -- -- Declaration of the MonadRWS class. -- -- Inspired by the paper -- /Functional Programming with Overloading and Higher-Order Polymorphism/, -- Mark P Jones (<http://web.cecs.pdx.edu/~mpj/>) -- Advanced School of Functional Programming, 1995. ----------------------------------------------------------------------------- module Control.Monad.RWS ( module Control.Monad.RWS.Lazy ) where import Control.Monad.RWS.Lazy
johanneshilden/principle
public/mtl-2.2.1/Control/Monad/RWS.hs
Haskell
bsd-3-clause
895
module Syntax where type Name = String data Expr = Var Name | Lit Ground | App Expr Expr | Lam Name Type Expr deriving (Eq, Show) data Ground = LInt Int | LBool Bool deriving (Show, Eq, Ord) data Type = TInt | TBool | TArr Type Type deriving (Eq, Read, Show)
yupferris/write-you-a-haskell
chapter5/stlc/Syntax.hs
Haskell
mit
287
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="si-LK"> <title>Passive Scan Rules | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/pscanrules/src/main/javahelp/org/zaproxy/zap/extension/pscanrules/resources/help_si_LK/helpset_si_LK.hs
Haskell
apache-2.0
979
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ro-RO"> <title>All In One Notes Add-On</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/allinonenotes/src/main/javahelp/org/zaproxy/zap/extension/allinonenotes/resources/help_ro_RO/helpset_ro_RO.hs
Haskell
apache-2.0
968
module HLearn.Optimization.StepSize ( -- * fancy step sizes -- ** Almeida Langlois lrAlmeidaLanglois -- * simple step sizes -- ** linear decrease , lrLinear , eta -- , gamma -- ** constant step size , lrConst -- , step ) where import HLearn.Optimization.StepSize.Linear import HLearn.Optimization.StepSize.Const import HLearn.Optimization.StepSize.AlmeidaLanglois
mikeizbicki/HLearn
src/HLearn/Optimization/StepSize.hs
Haskell
bsd-3-clause
427
module PatBindIn3 where --A definition can be lifted from a where or let to the top level binding group. --Lifting a definition widens the scope of the definition. --In this example, lift 'sq' defined in 'sumSquares' --This example aims to test changing a constant to a function. sumSquares x = (sq x pow) + (sq x pow) where pow =2 sq x pow = x^pow anotherFun 0 y = sq y where sq x = x^2
kmate/HaRe
old/testing/liftToToplevel/PatBindIn3_TokOut.hs
Haskell
bsd-3-clause
454
module HAD.Y2014.M04.D09.Exercise where -- $setup -- >>> import Data.List data Foo = Foo {x :: Int, y :: String, z :: String} deriving (Read, Show, Eq) {- | orderXYZ Order Foo by x then by y and then by z prop> sort xs == (map x . orderXYZ . map (\v -> Foo v "y" "z")) xs prop> sort xs == (map y . orderXYZ . map (\v -> Foo 42 v "z")) xs prop> sort xs == (map z . orderXYZ . map (\v -> Foo 42 "y" v )) xs -} orderXYZ :: [Foo] -> [Foo] orderXYZ = undefined
1HaskellADay/1HAD
exercises/HAD/Y2014/M04/D09/Exercise.hs
Haskell
mit
481
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash, UnboxedTuples #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Word -- Copyright : (c) The University of Glasgow, 1997-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- Sized unsigned integral types: 'Word', 'Word8', 'Word16', 'Word32', and -- 'Word64'. -- ----------------------------------------------------------------------------- #include "MachDeps.h" module GHC.Word ( Word(..), Word8(..), Word16(..), Word32(..), Word64(..), uncheckedShiftL64#, uncheckedShiftRL64#, byteSwap16, byteSwap32, byteSwap64 ) where import Data.Bits import Data.Maybe #if WORD_SIZE_IN_BITS < 64 import GHC.IntWord64 #endif -- import {-# SOURCE #-} GHC.Exception import GHC.Base import GHC.Enum import GHC.Num import GHC.Real import GHC.Read import GHC.Arr import GHC.Show import GHC.Float () -- for RealFrac methods ------------------------------------------------------------------------ -- type Word8 ------------------------------------------------------------------------ -- Word8 is represented in the same way as Word. Operations may assume -- and must ensure that it holds only values from its logical range. data {-# CTYPE "HsWord8" #-} Word8 = W8# Word# deriving (Eq, Ord) -- ^ 8-bit unsigned integer type instance Show Word8 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Num Word8 where (W8# x#) + (W8# y#) = W8# (narrow8Word# (x# `plusWord#` y#)) (W8# x#) - (W8# y#) = W8# (narrow8Word# (x# `minusWord#` y#)) (W8# x#) * (W8# y#) = W8# (narrow8Word# (x# `timesWord#` y#)) negate (W8# x#) = W8# (narrow8Word# (int2Word# (negateInt# (word2Int# x#)))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W8# (narrow8Word# (integerToWord i)) instance Real Word8 where toRational x = toInteger x % 1 instance Enum Word8 where succ x | x /= maxBound = x + 1 | otherwise = succError "Word8" pred x | x /= minBound = x - 1 | otherwise = predError "Word8" toEnum i@(I# i#) | i >= 0 && i <= fromIntegral (maxBound::Word8) = W8# (int2Word# i#) | otherwise = toEnumError "Word8" i (minBound::Word8, maxBound::Word8) fromEnum (W8# x#) = I# (word2Int# x#) enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen instance Integral Word8 where quot (W8# x#) y@(W8# y#) | y /= 0 = W8# (x# `quotWord#` y#) | otherwise = divZeroError rem (W8# x#) y@(W8# y#) | y /= 0 = W8# (x# `remWord#` y#) | otherwise = divZeroError div (W8# x#) y@(W8# y#) | y /= 0 = W8# (x# `quotWord#` y#) | otherwise = divZeroError mod (W8# x#) y@(W8# y#) | y /= 0 = W8# (x# `remWord#` y#) | otherwise = divZeroError quotRem (W8# x#) y@(W8# y#) | y /= 0 = case x# `quotRemWord#` y# of (# q, r #) -> (W8# q, W8# r) | otherwise = divZeroError divMod (W8# x#) y@(W8# y#) | y /= 0 = (W8# (x# `quotWord#` y#), W8# (x# `remWord#` y#)) | otherwise = divZeroError toInteger (W8# x#) = smallInteger (word2Int# x#) instance Bounded Word8 where minBound = 0 maxBound = 0xFF instance Ix Word8 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral (i - m) inRange (m,n) i = m <= i && i <= n instance Read Word8 where readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s] instance Bits Word8 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W8# x#) .&. (W8# y#) = W8# (x# `and#` y#) (W8# x#) .|. (W8# y#) = W8# (x# `or#` y#) (W8# x#) `xor` (W8# y#) = W8# (x# `xor#` y#) complement (W8# x#) = W8# (x# `xor#` mb#) where !(W8# mb#) = maxBound (W8# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W8# (narrow8Word# (x# `shiftL#` i#)) | otherwise = W8# (x# `shiftRL#` negateInt# i#) (W8# x#) `shiftL` (I# i#) = W8# (narrow8Word# (x# `shiftL#` i#)) (W8# x#) `unsafeShiftL` (I# i#) = W8# (narrow8Word# (x# `uncheckedShiftL#` i#)) (W8# x#) `shiftR` (I# i#) = W8# (x# `shiftRL#` i#) (W8# x#) `unsafeShiftR` (I# i#) = W8# (x# `uncheckedShiftRL#` i#) (W8# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W8# x# | otherwise = W8# (narrow8Word# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (8# -# i'#)))) where !i'# = word2Int# (int2Word# i# `and#` 7##) bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = False popCount (W8# x#) = I# (word2Int# (popCnt8# x#)) bit = bitDefault testBit = testBitDefault instance FiniteBits Word8 where finiteBitSize _ = 8 {-# RULES "fromIntegral/Word8->Word8" fromIntegral = id :: Word8 -> Word8 "fromIntegral/Word8->Integer" fromIntegral = toInteger :: Word8 -> Integer "fromIntegral/a->Word8" fromIntegral = \x -> case fromIntegral x of W# x# -> W8# (narrow8Word# x#) "fromIntegral/Word8->a" fromIntegral = \(W8# x#) -> fromIntegral (W# x#) #-} {-# RULES "properFraction/Float->(Word8,Float)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Float) } "truncate/Float->Word8" truncate = (fromIntegral :: Int -> Word8) . (truncate :: Float -> Int) "floor/Float->Word8" floor = (fromIntegral :: Int -> Word8) . (floor :: Float -> Int) "ceiling/Float->Word8" ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Float -> Int) "round/Float->Word8" round = (fromIntegral :: Int -> Word8) . (round :: Float -> Int) #-} {-# RULES "properFraction/Double->(Word8,Double)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word8) n, y :: Double) } "truncate/Double->Word8" truncate = (fromIntegral :: Int -> Word8) . (truncate :: Double -> Int) "floor/Double->Word8" floor = (fromIntegral :: Int -> Word8) . (floor :: Double -> Int) "ceiling/Double->Word8" ceiling = (fromIntegral :: Int -> Word8) . (ceiling :: Double -> Int) "round/Double->Word8" round = (fromIntegral :: Int -> Word8) . (round :: Double -> Int) #-} ------------------------------------------------------------------------ -- type Word16 ------------------------------------------------------------------------ -- Word16 is represented in the same way as Word. Operations may assume -- and must ensure that it holds only values from its logical range. data {-# CTYPE "HsWord16" #-} Word16 = W16# Word# deriving (Eq, Ord) -- ^ 16-bit unsigned integer type instance Show Word16 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Num Word16 where (W16# x#) + (W16# y#) = W16# (narrow16Word# (x# `plusWord#` y#)) (W16# x#) - (W16# y#) = W16# (narrow16Word# (x# `minusWord#` y#)) (W16# x#) * (W16# y#) = W16# (narrow16Word# (x# `timesWord#` y#)) negate (W16# x#) = W16# (narrow16Word# (int2Word# (negateInt# (word2Int# x#)))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W16# (narrow16Word# (integerToWord i)) instance Real Word16 where toRational x = toInteger x % 1 instance Enum Word16 where succ x | x /= maxBound = x + 1 | otherwise = succError "Word16" pred x | x /= minBound = x - 1 | otherwise = predError "Word16" toEnum i@(I# i#) | i >= 0 && i <= fromIntegral (maxBound::Word16) = W16# (int2Word# i#) | otherwise = toEnumError "Word16" i (minBound::Word16, maxBound::Word16) fromEnum (W16# x#) = I# (word2Int# x#) enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen instance Integral Word16 where quot (W16# x#) y@(W16# y#) | y /= 0 = W16# (x# `quotWord#` y#) | otherwise = divZeroError rem (W16# x#) y@(W16# y#) | y /= 0 = W16# (x# `remWord#` y#) | otherwise = divZeroError div (W16# x#) y@(W16# y#) | y /= 0 = W16# (x# `quotWord#` y#) | otherwise = divZeroError mod (W16# x#) y@(W16# y#) | y /= 0 = W16# (x# `remWord#` y#) | otherwise = divZeroError quotRem (W16# x#) y@(W16# y#) | y /= 0 = case x# `quotRemWord#` y# of (# q, r #) -> (W16# q, W16# r) | otherwise = divZeroError divMod (W16# x#) y@(W16# y#) | y /= 0 = (W16# (x# `quotWord#` y#), W16# (x# `remWord#` y#)) | otherwise = divZeroError toInteger (W16# x#) = smallInteger (word2Int# x#) instance Bounded Word16 where minBound = 0 maxBound = 0xFFFF instance Ix Word16 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral (i - m) inRange (m,n) i = m <= i && i <= n instance Read Word16 where readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s] instance Bits Word16 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W16# x#) .&. (W16# y#) = W16# (x# `and#` y#) (W16# x#) .|. (W16# y#) = W16# (x# `or#` y#) (W16# x#) `xor` (W16# y#) = W16# (x# `xor#` y#) complement (W16# x#) = W16# (x# `xor#` mb#) where !(W16# mb#) = maxBound (W16# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W16# (narrow16Word# (x# `shiftL#` i#)) | otherwise = W16# (x# `shiftRL#` negateInt# i#) (W16# x#) `shiftL` (I# i#) = W16# (narrow16Word# (x# `shiftL#` i#)) (W16# x#) `unsafeShiftL` (I# i#) = W16# (narrow16Word# (x# `uncheckedShiftL#` i#)) (W16# x#) `shiftR` (I# i#) = W16# (x# `shiftRL#` i#) (W16# x#) `unsafeShiftR` (I# i#) = W16# (x# `uncheckedShiftRL#` i#) (W16# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W16# x# | otherwise = W16# (narrow16Word# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (16# -# i'#)))) where !i'# = word2Int# (int2Word# i# `and#` 15##) bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = False popCount (W16# x#) = I# (word2Int# (popCnt16# x#)) bit = bitDefault testBit = testBitDefault instance FiniteBits Word16 where finiteBitSize _ = 16 -- | Swap bytes in 'Word16'. -- -- /Since: 4.7.0.0/ byteSwap16 :: Word16 -> Word16 byteSwap16 (W16# w#) = W16# (narrow16Word# (byteSwap16# w#)) {-# RULES "fromIntegral/Word8->Word16" fromIntegral = \(W8# x#) -> W16# x# "fromIntegral/Word16->Word16" fromIntegral = id :: Word16 -> Word16 "fromIntegral/Word16->Integer" fromIntegral = toInteger :: Word16 -> Integer "fromIntegral/a->Word16" fromIntegral = \x -> case fromIntegral x of W# x# -> W16# (narrow16Word# x#) "fromIntegral/Word16->a" fromIntegral = \(W16# x#) -> fromIntegral (W# x#) #-} {-# RULES "properFraction/Float->(Word16,Float)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Float) } "truncate/Float->Word16" truncate = (fromIntegral :: Int -> Word16) . (truncate :: Float -> Int) "floor/Float->Word16" floor = (fromIntegral :: Int -> Word16) . (floor :: Float -> Int) "ceiling/Float->Word16" ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Float -> Int) "round/Float->Word16" round = (fromIntegral :: Int -> Word16) . (round :: Float -> Int) #-} {-# RULES "properFraction/Double->(Word16,Double)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word16) n, y :: Double) } "truncate/Double->Word16" truncate = (fromIntegral :: Int -> Word16) . (truncate :: Double -> Int) "floor/Double->Word16" floor = (fromIntegral :: Int -> Word16) . (floor :: Double -> Int) "ceiling/Double->Word16" ceiling = (fromIntegral :: Int -> Word16) . (ceiling :: Double -> Int) "round/Double->Word16" round = (fromIntegral :: Int -> Word16) . (round :: Double -> Int) #-} ------------------------------------------------------------------------ -- type Word32 ------------------------------------------------------------------------ -- Word32 is represented in the same way as Word. #if WORD_SIZE_IN_BITS > 32 -- Operations may assume and must ensure that it holds only values -- from its logical range. -- We can use rewrite rules for the RealFrac methods {-# RULES "properFraction/Float->(Word32,Float)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Float) } "truncate/Float->Word32" truncate = (fromIntegral :: Int -> Word32) . (truncate :: Float -> Int) "floor/Float->Word32" floor = (fromIntegral :: Int -> Word32) . (floor :: Float -> Int) "ceiling/Float->Word32" ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Float -> Int) "round/Float->Word32" round = (fromIntegral :: Int -> Word32) . (round :: Float -> Int) #-} {-# RULES "properFraction/Double->(Word32,Double)" properFraction = \x -> case properFraction x of { (n, y) -> ((fromIntegral :: Int -> Word32) n, y :: Double) } "truncate/Double->Word32" truncate = (fromIntegral :: Int -> Word32) . (truncate :: Double -> Int) "floor/Double->Word32" floor = (fromIntegral :: Int -> Word32) . (floor :: Double -> Int) "ceiling/Double->Word32" ceiling = (fromIntegral :: Int -> Word32) . (ceiling :: Double -> Int) "round/Double->Word32" round = (fromIntegral :: Int -> Word32) . (round :: Double -> Int) #-} #endif data {-# CTYPE "HsWord32" #-} Word32 = W32# Word# deriving (Eq, Ord) -- ^ 32-bit unsigned integer type instance Num Word32 where (W32# x#) + (W32# y#) = W32# (narrow32Word# (x# `plusWord#` y#)) (W32# x#) - (W32# y#) = W32# (narrow32Word# (x# `minusWord#` y#)) (W32# x#) * (W32# y#) = W32# (narrow32Word# (x# `timesWord#` y#)) negate (W32# x#) = W32# (narrow32Word# (int2Word# (negateInt# (word2Int# x#)))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W32# (narrow32Word# (integerToWord i)) instance Enum Word32 where succ x | x /= maxBound = x + 1 | otherwise = succError "Word32" pred x | x /= minBound = x - 1 | otherwise = predError "Word32" toEnum i@(I# i#) | i >= 0 #if WORD_SIZE_IN_BITS > 32 && i <= fromIntegral (maxBound::Word32) #endif = W32# (int2Word# i#) | otherwise = toEnumError "Word32" i (minBound::Word32, maxBound::Word32) #if WORD_SIZE_IN_BITS == 32 fromEnum x@(W32# x#) | x <= fromIntegral (maxBound::Int) = I# (word2Int# x#) | otherwise = fromEnumError "Word32" x enumFrom = integralEnumFrom enumFromThen = integralEnumFromThen enumFromTo = integralEnumFromTo enumFromThenTo = integralEnumFromThenTo #else fromEnum (W32# x#) = I# (word2Int# x#) enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen #endif instance Integral Word32 where quot (W32# x#) y@(W32# y#) | y /= 0 = W32# (x# `quotWord#` y#) | otherwise = divZeroError rem (W32# x#) y@(W32# y#) | y /= 0 = W32# (x# `remWord#` y#) | otherwise = divZeroError div (W32# x#) y@(W32# y#) | y /= 0 = W32# (x# `quotWord#` y#) | otherwise = divZeroError mod (W32# x#) y@(W32# y#) | y /= 0 = W32# (x# `remWord#` y#) | otherwise = divZeroError quotRem (W32# x#) y@(W32# y#) | y /= 0 = case x# `quotRemWord#` y# of (# q, r #) -> (W32# q, W32# r) | otherwise = divZeroError divMod (W32# x#) y@(W32# y#) | y /= 0 = (W32# (x# `quotWord#` y#), W32# (x# `remWord#` y#)) | otherwise = divZeroError toInteger (W32# x#) #if WORD_SIZE_IN_BITS == 32 | isTrue# (i# >=# 0#) = smallInteger i# | otherwise = wordToInteger x# where !i# = word2Int# x# #else = smallInteger (word2Int# x#) #endif instance Bits Word32 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W32# x#) .&. (W32# y#) = W32# (x# `and#` y#) (W32# x#) .|. (W32# y#) = W32# (x# `or#` y#) (W32# x#) `xor` (W32# y#) = W32# (x# `xor#` y#) complement (W32# x#) = W32# (x# `xor#` mb#) where !(W32# mb#) = maxBound (W32# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W32# (narrow32Word# (x# `shiftL#` i#)) | otherwise = W32# (x# `shiftRL#` negateInt# i#) (W32# x#) `shiftL` (I# i#) = W32# (narrow32Word# (x# `shiftL#` i#)) (W32# x#) `unsafeShiftL` (I# i#) = W32# (narrow32Word# (x# `uncheckedShiftL#` i#)) (W32# x#) `shiftR` (I# i#) = W32# (x# `shiftRL#` i#) (W32# x#) `unsafeShiftR` (I# i#) = W32# (x# `uncheckedShiftRL#` i#) (W32# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W32# x# | otherwise = W32# (narrow32Word# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (32# -# i'#)))) where !i'# = word2Int# (int2Word# i# `and#` 31##) bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = False popCount (W32# x#) = I# (word2Int# (popCnt32# x#)) bit = bitDefault testBit = testBitDefault instance FiniteBits Word32 where finiteBitSize _ = 32 {-# RULES "fromIntegral/Word8->Word32" fromIntegral = \(W8# x#) -> W32# x# "fromIntegral/Word16->Word32" fromIntegral = \(W16# x#) -> W32# x# "fromIntegral/Word32->Word32" fromIntegral = id :: Word32 -> Word32 "fromIntegral/Word32->Integer" fromIntegral = toInteger :: Word32 -> Integer "fromIntegral/a->Word32" fromIntegral = \x -> case fromIntegral x of W# x# -> W32# (narrow32Word# x#) "fromIntegral/Word32->a" fromIntegral = \(W32# x#) -> fromIntegral (W# x#) #-} instance Show Word32 where #if WORD_SIZE_IN_BITS < 33 showsPrec p x = showsPrec p (toInteger x) #else showsPrec p x = showsPrec p (fromIntegral x :: Int) #endif instance Real Word32 where toRational x = toInteger x % 1 instance Bounded Word32 where minBound = 0 maxBound = 0xFFFFFFFF instance Ix Word32 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral (i - m) inRange (m,n) i = m <= i && i <= n instance Read Word32 where #if WORD_SIZE_IN_BITS < 33 readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s] #else readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s] #endif -- | Reverse order of bytes in 'Word32'. -- -- /Since: 4.7.0.0/ byteSwap32 :: Word32 -> Word32 byteSwap32 (W32# w#) = W32# (narrow32Word# (byteSwap32# w#)) ------------------------------------------------------------------------ -- type Word64 ------------------------------------------------------------------------ #if WORD_SIZE_IN_BITS < 64 data {-# CTYPE "HsWord64" #-} Word64 = W64# Word64# -- ^ 64-bit unsigned integer type instance Eq Word64 where (W64# x#) == (W64# y#) = isTrue# (x# `eqWord64#` y#) (W64# x#) /= (W64# y#) = isTrue# (x# `neWord64#` y#) instance Ord Word64 where (W64# x#) < (W64# y#) = isTrue# (x# `ltWord64#` y#) (W64# x#) <= (W64# y#) = isTrue# (x# `leWord64#` y#) (W64# x#) > (W64# y#) = isTrue# (x# `gtWord64#` y#) (W64# x#) >= (W64# y#) = isTrue# (x# `geWord64#` y#) instance Num Word64 where (W64# x#) + (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `plusInt64#` word64ToInt64# y#)) (W64# x#) - (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `minusInt64#` word64ToInt64# y#)) (W64# x#) * (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `timesInt64#` word64ToInt64# y#)) negate (W64# x#) = W64# (int64ToWord64# (negateInt64# (word64ToInt64# x#))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W64# (integerToWord64 i) instance Enum Word64 where succ x | x /= maxBound = x + 1 | otherwise = succError "Word64" pred x | x /= minBound = x - 1 | otherwise = predError "Word64" toEnum i@(I# i#) | i >= 0 = W64# (wordToWord64# (int2Word# i#)) | otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64) fromEnum x@(W64# x#) | x <= fromIntegral (maxBound::Int) = I# (word2Int# (word64ToWord# x#)) | otherwise = fromEnumError "Word64" x enumFrom = integralEnumFrom enumFromThen = integralEnumFromThen enumFromTo = integralEnumFromTo enumFromThenTo = integralEnumFromThenTo instance Integral Word64 where quot (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `quotWord64#` y#) | otherwise = divZeroError rem (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `remWord64#` y#) | otherwise = divZeroError div (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `quotWord64#` y#) | otherwise = divZeroError mod (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `remWord64#` y#) | otherwise = divZeroError quotRem (W64# x#) y@(W64# y#) | y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#)) | otherwise = divZeroError divMod (W64# x#) y@(W64# y#) | y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#)) | otherwise = divZeroError toInteger (W64# x#) = word64ToInteger x# instance Bits Word64 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W64# x#) .&. (W64# y#) = W64# (x# `and64#` y#) (W64# x#) .|. (W64# y#) = W64# (x# `or64#` y#) (W64# x#) `xor` (W64# y#) = W64# (x# `xor64#` y#) complement (W64# x#) = W64# (not64# x#) (W64# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W64# (x# `shiftL64#` i#) | otherwise = W64# (x# `shiftRL64#` negateInt# i#) (W64# x#) `shiftL` (I# i#) = W64# (x# `shiftL64#` i#) (W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL64#` i#) (W64# x#) `shiftR` (I# i#) = W64# (x# `shiftRL64#` i#) (W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL64#` i#) (W64# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W64# x# | otherwise = W64# ((x# `uncheckedShiftL64#` i'#) `or64#` (x# `uncheckedShiftRL64#` (64# -# i'#))) where !i'# = word2Int# (int2Word# i# `and#` 63##) bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = False popCount (W64# x#) = I# (word2Int# (popCnt64# x#)) bit = bitDefault testBit = testBitDefault -- give the 64-bit shift operations the same treatment as the 32-bit -- ones (see GHC.Base), namely we wrap them in tests to catch the -- cases when we're shifting more than 64 bits to avoid unspecified -- behaviour in the C shift operations. shiftL64#, shiftRL64# :: Word64# -> Int# -> Word64# a `shiftL64#` b | isTrue# (b >=# 64#) = wordToWord64# 0## | otherwise = a `uncheckedShiftL64#` b a `shiftRL64#` b | isTrue# (b >=# 64#) = wordToWord64# 0## | otherwise = a `uncheckedShiftRL64#` b {-# RULES "fromIntegral/Int->Word64" fromIntegral = \(I# x#) -> W64# (int64ToWord64# (intToInt64# x#)) "fromIntegral/Word->Word64" fromIntegral = \(W# x#) -> W64# (wordToWord64# x#) "fromIntegral/Word64->Int" fromIntegral = \(W64# x#) -> I# (word2Int# (word64ToWord# x#)) "fromIntegral/Word64->Word" fromIntegral = \(W64# x#) -> W# (word64ToWord# x#) "fromIntegral/Word64->Word64" fromIntegral = id :: Word64 -> Word64 #-} #else -- Word64 is represented in the same way as Word. -- Operations may assume and must ensure that it holds only values -- from its logical range. data {-# CTYPE "HsWord64" #-} Word64 = W64# Word# deriving (Eq, Ord) -- ^ 64-bit unsigned integer type instance Num Word64 where (W64# x#) + (W64# y#) = W64# (x# `plusWord#` y#) (W64# x#) - (W64# y#) = W64# (x# `minusWord#` y#) (W64# x#) * (W64# y#) = W64# (x# `timesWord#` y#) negate (W64# x#) = W64# (int2Word# (negateInt# (word2Int# x#))) abs x = x signum 0 = 0 signum _ = 1 fromInteger i = W64# (integerToWord i) instance Enum Word64 where succ x | x /= maxBound = x + 1 | otherwise = succError "Word64" pred x | x /= minBound = x - 1 | otherwise = predError "Word64" toEnum i@(I# i#) | i >= 0 = W64# (int2Word# i#) | otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64) fromEnum x@(W64# x#) | x <= fromIntegral (maxBound::Int) = I# (word2Int# x#) | otherwise = fromEnumError "Word64" x enumFrom = integralEnumFrom enumFromThen = integralEnumFromThen enumFromTo = integralEnumFromTo enumFromThenTo = integralEnumFromThenTo instance Integral Word64 where quot (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `quotWord#` y#) | otherwise = divZeroError rem (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `remWord#` y#) | otherwise = divZeroError div (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `quotWord#` y#) | otherwise = divZeroError mod (W64# x#) y@(W64# y#) | y /= 0 = W64# (x# `remWord#` y#) | otherwise = divZeroError quotRem (W64# x#) y@(W64# y#) | y /= 0 = case x# `quotRemWord#` y# of (# q, r #) -> (W64# q, W64# r) | otherwise = divZeroError divMod (W64# x#) y@(W64# y#) | y /= 0 = (W64# (x# `quotWord#` y#), W64# (x# `remWord#` y#)) | otherwise = divZeroError toInteger (W64# x#) | isTrue# (i# >=# 0#) = smallInteger i# | otherwise = wordToInteger x# where !i# = word2Int# x# instance Bits Word64 where {-# INLINE shift #-} {-# INLINE bit #-} {-# INLINE testBit #-} (W64# x#) .&. (W64# y#) = W64# (x# `and#` y#) (W64# x#) .|. (W64# y#) = W64# (x# `or#` y#) (W64# x#) `xor` (W64# y#) = W64# (x# `xor#` y#) complement (W64# x#) = W64# (x# `xor#` mb#) where !(W64# mb#) = maxBound (W64# x#) `shift` (I# i#) | isTrue# (i# >=# 0#) = W64# (x# `shiftL#` i#) | otherwise = W64# (x# `shiftRL#` negateInt# i#) (W64# x#) `shiftL` (I# i#) = W64# (x# `shiftL#` i#) (W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL#` i#) (W64# x#) `shiftR` (I# i#) = W64# (x# `shiftRL#` i#) (W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL#` i#) (W64# x#) `rotate` (I# i#) | isTrue# (i'# ==# 0#) = W64# x# | otherwise = W64# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (64# -# i'#))) where !i'# = word2Int# (int2Word# i# `and#` 63##) bitSizeMaybe i = Just (finiteBitSize i) bitSize i = finiteBitSize i isSigned _ = False popCount (W64# x#) = I# (word2Int# (popCnt64# x#)) bit = bitDefault testBit = testBitDefault {-# RULES "fromIntegral/a->Word64" fromIntegral = \x -> case fromIntegral x of W# x# -> W64# x# "fromIntegral/Word64->a" fromIntegral = \(W64# x#) -> fromIntegral (W# x#) #-} uncheckedShiftL64# :: Word# -> Int# -> Word# uncheckedShiftL64# = uncheckedShiftL# uncheckedShiftRL64# :: Word# -> Int# -> Word# uncheckedShiftRL64# = uncheckedShiftRL# #endif instance FiniteBits Word64 where finiteBitSize _ = 64 instance Show Word64 where showsPrec p x = showsPrec p (toInteger x) instance Real Word64 where toRational x = toInteger x % 1 instance Bounded Word64 where minBound = 0 maxBound = 0xFFFFFFFFFFFFFFFF instance Ix Word64 where range (m,n) = [m..n] unsafeIndex (m,_) i = fromIntegral (i - m) inRange (m,n) i = m <= i && i <= n instance Read Word64 where readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s] -- | Reverse order of bytes in 'Word64'. -- -- /Since: 4.7.0.0/ #if WORD_SIZE_IN_BITS < 64 byteSwap64 :: Word64 -> Word64 byteSwap64 (W64# w#) = W64# (byteSwap64# w#) #else byteSwap64 :: Word64 -> Word64 byteSwap64 (W64# w#) = W64# (byteSwap# w#) #endif
frantisekfarka/ghc-dsi
libraries/base/GHC/Word.hs
Haskell
bsd-3-clause
31,190
-- | Some helpers for interrogating a WAI 'Request'. module Network.Wai.Request ( appearsSecure , guessApproot ) where import Data.ByteString (ByteString) import Data.Maybe (fromMaybe) import Network.HTTP.Types (HeaderName) import Network.Wai (Request, isSecure, requestHeaders, requestHeaderHost) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as C -- | Does this request appear to have been made over an SSL connection? -- -- This function first checks @'isSecure'@, but also checks for headers that may -- indicate a secure connection even in the presence of reverse proxies. -- -- Note: these headers can be easily spoofed, so decisions which require a true -- SSL connection (i.e. sending sensitive information) should only use -- @'isSecure'@. This is not always the case though: for example, deciding to -- force a non-SSL request to SSL by redirect. One can safely choose not to -- redirect when the request /appears/ secure, even if it's actually not. -- -- Since 3.0.7 appearsSecure :: Request -> Bool appearsSecure request = isSecure request || any (uncurry matchHeader) [ ("HTTPS" , (== "on")) , ("HTTP_X_FORWARDED_SSL" , (== "on")) , ("HTTP_X_FORWARDED_SCHEME", (== "https")) , ("HTTP_X_FORWARDED_PROTO" , ((== ["https"]) . take 1 . C.split ',')) , ("X-Forwarded-Proto" , (== "https")) -- Used by Nginx and AWS ELB. ] where matchHeader :: HeaderName -> (ByteString -> Bool) -> Bool matchHeader h f = maybe False f $ lookup h $ requestHeaders request -- | Guess the \"application root\" based on the given request. -- -- The application root is the basis for forming URLs pointing at the current -- application. For more information and relevant caveats, please see -- "Network.Wai.Middleware.Approot". -- -- Since 3.0.7 guessApproot :: Request -> ByteString guessApproot req = (if appearsSecure req then "https://" else "http://") `S.append` (fromMaybe "localhost" $ requestHeaderHost req)
dylex/wai
wai-extra/Network/Wai/Request.hs
Haskell
mit
2,017
{-| A data structure for measuring how many of a number of available slots are taken. -} {- Copyright (C) 2014 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 Ganeti.SlotMap ( Slot(..) , SlotMap , CountMap , toCountMap , isOverfull , occupySlots , hasSlotsFor ) where import Data.Map (Map) import qualified Data.Map as Map {-# ANN module "HLint: ignore Avoid lambda" #-} -- to not suggest (`Slot` 0) -- | A resource with [limit] available units and [occupied] of them taken. data Slot = Slot { slotOccupied :: Int , slotLimit :: Int } deriving (Eq, Ord, Show) -- | A set of keys of type @a@ and how many slots are available and (to be) -- occupied per key. -- -- Some keys can be overfull (more slots occupied than available). type SlotMap a = Map a Slot -- | A set of keys of type @a@ and how many there are of each. type CountMap a = Map a Int -- | Turns a `SlotMap` into a `CountMap` by throwing away the limits. toCountMap :: SlotMap a -> CountMap a toCountMap = Map.map slotOccupied -- | Whether any more slots are occupied than available. isOverfull :: SlotMap a -> Bool isOverfull m = or [ occup > limit | Slot occup limit <- Map.elems m ] -- | Fill slots of a `SlotMap`s by adding the given counts. -- Keys with counts that don't appear in the `SlotMap` get a limit of 0. occupySlots :: (Ord a) => SlotMap a -> CountMap a -> SlotMap a occupySlots sm counts = Map.unionWith (\(Slot o l) (Slot n _) -> Slot (o + n) l) sm (Map.map (\n -> Slot n 0) counts) -- | Whether the `SlotMap` has enough slots free to accomodate the given -- counts. -- -- The `SlotMap` is allowed to be overfull in some keys; this function -- still returns True as long as as adding the counts to the `SlotMap` would -- not *create or increase* overfull keys. -- -- Adding counts > 0 for a key which is not in the `SlotMap` does create -- overfull keys. hasSlotsFor :: (Ord a) => SlotMap a -> CountMap a -> Bool slotMap `hasSlotsFor` counts = let relevantSlots = slotMap `Map.intersection` counts in not $ isOverfull (relevantSlots `occupySlots` counts)
grnet/snf-ganeti
src/Ganeti/SlotMap.hs
Haskell
bsd-2-clause
3,394
-- !!! Testing the Word Enum instances. {-# LANGUAGE CPP #-} module Main(main) where import Control.Exception import Data.Word import Data.Int main = do putStrLn "Testing Enum Word8:" testEnumWord8 putStrLn "Testing Enum Word16:" testEnumWord16 putStrLn "Testing Enum Word32:" testEnumWord32 putStrLn "Testing Enum Word64:" testEnumWord64 #define printTest(x) (do{ putStr ( " " ++ "x" ++ " = " ) ; print (x) }) testEnumWord8 :: IO () testEnumWord8 = do -- succ printTest ((succ (0::Word8))) printTest ((succ (minBound::Word8))) mayBomb (printTest ((succ (maxBound::Word8)))) -- pred printTest (pred (1::Word8)) printTest (pred (maxBound::Word8)) mayBomb (printTest (pred (minBound::Word8))) -- toEnum printTest ((map (toEnum::Int->Word8) [1, fromIntegral (minBound::Word8)::Int, fromIntegral (maxBound::Word8)::Int])) mayBomb (printTest ((toEnum (maxBound::Int))::Word8)) -- fromEnum printTest ((map fromEnum [(1::Word8),minBound,maxBound])) -- [x..] aka enumFrom printTest ((take 7 [(1::Word8)..])) printTest ((take 7 [((maxBound::Word8)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word8),2..])) printTest ((take 7 [(1::Word8),7..])) printTest ((take 7 [(1::Word8),1..])) printTest ((take 7 [(1::Word8),0..])) printTest ((take 7 [(5::Word8),2..])) let x = (minBound::Word8) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word8) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word8) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word8) .. 5]))) printTest ((take 4 ([(1::Word8) .. 1]))) printTest ((take 7 ([(1::Word8) .. 0]))) printTest ((take 7 ([(5::Word8) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word8)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word8)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word8),4..1])) printTest ((take 7 [(5::Word8),3..1])) printTest ((take 7 [(5::Word8),3..2])) printTest ((take 7 [(1::Word8),2..1])) printTest ((take 7 [(2::Word8),1..2])) printTest ((take 7 [(2::Word8),1..1])) printTest ((take 7 [(2::Word8),3..1])) let x = (maxBound::Word8) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word8) + 5 printTest ((take 7 [x,(x-1)..minBound])) testEnumWord16 :: IO () testEnumWord16 = do -- succ printTest ((succ (0::Word16))) printTest ((succ (minBound::Word16))) mayBomb (printTest ((succ (maxBound::Word16)))) -- pred printTest (pred (1::Word16)) printTest (pred (maxBound::Word16)) mayBomb (printTest (pred (minBound::Word16))) -- toEnum printTest ((map (toEnum::Int->Word16) [1, fromIntegral (minBound::Word16)::Int, fromIntegral (maxBound::Word16)::Int])) mayBomb (printTest ((toEnum (maxBound::Int))::Word16)) -- fromEnum printTest ((map fromEnum [(1::Word16),minBound,maxBound])) -- [x..] aka enumFrom printTest ((take 7 [(1::Word16)..])) printTest ((take 7 [((maxBound::Word16)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word16),2..])) printTest ((take 7 [(1::Word16),7..])) printTest ((take 7 [(1::Word16),1..])) printTest ((take 7 [(1::Word16),0..])) printTest ((take 7 [(5::Word16),2..])) let x = (minBound::Word16) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word16) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word16) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word16) .. 5]))) printTest ((take 4 ([(1::Word16) .. 1]))) printTest ((take 7 ([(1::Word16) .. 0]))) printTest ((take 7 ([(5::Word16) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word16)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word16)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word16),4..1])) printTest ((take 7 [(5::Word16),3..1])) printTest ((take 7 [(5::Word16),3..2])) printTest ((take 7 [(1::Word16),2..1])) printTest ((take 7 [(2::Word16),1..2])) printTest ((take 7 [(2::Word16),1..1])) printTest ((take 7 [(2::Word16),3..1])) let x = (maxBound::Word16) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word16) + 5 printTest ((take 7 [x,(x-1)..minBound])) testEnumWord32 :: IO () testEnumWord32 = do -- succ printTest ((succ (0::Word32))) printTest ((succ (minBound::Word32))) mayBomb (printTest ((succ (maxBound::Word32)))) -- pred printTest (pred (1::Word32)) printTest (pred (maxBound::Word32)) mayBomb (printTest (pred (minBound::Word32))) -- toEnum printTest ((map (toEnum::Int->Word32) [1, fromIntegral (minBound::Word32)::Int, fromIntegral (maxBound::Int32)::Int])) mayBomb (printTest ((toEnum (maxBound::Int))::Word32)) -- fromEnum printTest ((map fromEnum [(1::Word32),minBound,fromIntegral (maxBound::Int)])) mayBomb (printTest (fromEnum (maxBound::Word32))) -- [x..] aka enumFrom printTest ((take 7 [(1::Word32)..])) printTest ((take 7 [((maxBound::Word32)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word32),2..])) printTest ((take 7 [(1::Word32),7..])) printTest ((take 7 [(1::Word32),1..])) printTest ((take 7 [(1::Word32),0..])) printTest ((take 7 [(5::Word32),2..])) let x = (minBound::Word32) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word32) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word32) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word32) .. 5]))) printTest ((take 4 ([(1::Word32) .. 1]))) printTest ((take 7 ([(1::Word32) .. 0]))) printTest ((take 7 ([(5::Word32) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word32)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word32)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word32),4..1])) printTest ((take 7 [(5::Word32),3..1])) printTest ((take 7 [(5::Word32),3..2])) printTest ((take 7 [(1::Word32),2..1])) printTest ((take 7 [(2::Word32),1..2])) printTest ((take 7 [(2::Word32),1..1])) printTest ((take 7 [(2::Word32),3..1])) let x = (maxBound::Word32) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word32) + 5 printTest ((take 7 [x,(x-1)..minBound])) testEnumWord64 :: IO () testEnumWord64 = do -- succ printTest ((succ (0::Word64))) printTest ((succ (minBound::Word64))) mayBomb (printTest ((succ (maxBound::Word64)))) -- pred printTest (pred (1::Word64)) printTest (pred (maxBound::Word64)) mayBomb (printTest (pred (minBound::Word64))) -- toEnum mayBomb (printTest ((map (toEnum::Int->Word64) [1, fromIntegral (minBound::Word64)::Int, maxBound::Int]))) mayBomb (printTest ((toEnum (maxBound::Int))::Word64)) -- fromEnum printTest ((map fromEnum [(1::Word64),minBound,fromIntegral (maxBound::Int)])) mayBomb (printTest (fromEnum (maxBound::Word64))) -- [x..] aka enumFrom printTest ((take 7 [(1::Word64)..])) printTest ((take 7 [((maxBound::Word64)-5)..])) -- just in case it doesn't catch the upper bound.. -- [x,y..] aka enumFromThen printTest ((take 7 [(1::Word64),2..])) printTest ((take 7 [(1::Word64),7..])) printTest ((take 7 [(1::Word64),1..])) printTest ((take 7 [(1::Word64),0..])) printTest ((take 7 [(5::Word64),2..])) let x = (minBound::Word64) + 1 printTest ((take 7 [x, x-1 ..])) let x = (minBound::Word64) + 5 printTest ((take 7 [x, x-1 ..])) let x = (maxBound::Word64) - 5 printTest ((take 7 [x, (x+1) ..])) -- [x..y] aka enumFromTo printTest ((take 7 ([(1::Word64) .. 5]))) printTest ((take 4 ([(1::Word64) .. 1]))) printTest ((take 7 ([(1::Word64) .. 0]))) printTest ((take 7 ([(5::Word64) .. 0]))) printTest ((take 7 ([(maxBound-(5::Word64)) .. maxBound]))) printTest ((take 7 ([(minBound+(5::Word64)) .. minBound]))) -- [x,y..z] aka enumFromThenTo printTest ((take 7 [(5::Word64),4..1])) printTest ((take 7 [(5::Word64),3..1])) printTest ((take 7 [(5::Word64),3..2])) printTest ((take 7 [(1::Word64),2..1])) printTest ((take 7 [(2::Word64),1..2])) printTest ((take 7 [(2::Word64),1..1])) printTest ((take 7 [(2::Word64),3..1])) let x = (maxBound::Word64) - 4 printTest ((take 7 [x,(x+1)..maxBound])) let x = (minBound::Word64) + 5 printTest ((take 7 [x,(x-1)..minBound])) -- -- -- Utils -- -- mayBomb x = catch x (\(ErrorCall e) -> putStrLn ("error " ++ show e)) `catch` (\e -> putStrLn ("Fail: " ++ show (e :: SomeException)))
green-haskell/ghc
libraries/base/tests/enum03.hs
Haskell
bsd-3-clause
8,784
{-# LANGUAGE DeriveTraversable #-} import Data.Monoid (Endo (..)) import Control.Exception (evaluate) data Tree a = Bin !(Tree a) a !(Tree a) | Tip deriving (Functor, Foldable) t1, t2, t3, t4, t5 :: Tree () t1 = Bin Tip () Tip t2 = Bin t1 () t1 t3 = Bin t2 () t2 t4 = Bin t3 () t3 t5 = Bin t4 () t4 t6 = Bin t5 () t5 t7 = Bin t6 () t6 replaceManyTimes :: Functor f => f a -> f Int replaceManyTimes xs = appEndo (foldMap (\x -> Endo (x <$)) [1..20000]) (0 <$ xs) main :: IO () main = do evaluate $ sum $ replaceManyTimes t7 pure ()
ezyang/ghc
testsuite/tests/perf/should_run/T13218.hs
Haskell
bsd-3-clause
546
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.JHC -- Copyright : Isaac Jones 2003-2006 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- This module contains most of the JHC-specific code for configuring, building -- and installing packages. module Distribution.Simple.JHC ( configure, getInstalledPackages, buildLib, buildExe, installLib, installExe ) where import Distribution.PackageDescription as PD ( PackageDescription(..), BuildInfo(..), Executable(..) , Library(..), libModules, hcOptions, usedExtensions ) import Distribution.InstalledPackageInfo ( emptyInstalledPackageInfo, ) import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo import Distribution.Simple.PackageIndex (InstalledPackageIndex) import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), ComponentLocalBuildInfo(..) ) import Distribution.Simple.BuildPaths ( autogenModulesDir, exeExtension ) import Distribution.Simple.Compiler ( CompilerFlavor(..), CompilerId(..), Compiler(..), AbiTag(..) , PackageDBStack, Flag, languageToFlags, extensionsToFlags ) import Language.Haskell.Extension ( Language(Haskell98), Extension(..), KnownExtension(..)) import Distribution.Simple.Program ( ConfiguredProgram(..), jhcProgram, ProgramConfiguration , userMaybeSpecifyPath, requireProgramVersion, lookupProgram , rawSystemProgram, rawSystemProgramStdoutConf ) import Distribution.Version ( Version(..), orLaterVersion ) import Distribution.Package ( Package(..), InstalledPackageId(InstalledPackageId), pkgName, pkgVersion, ) import Distribution.Simple.Utils ( createDirectoryIfMissingVerbose, writeFileAtomic , installOrdinaryFile, installExecutableFile , intercalate ) import System.FilePath ( (</>) ) import Distribution.Verbosity import Distribution.Text ( Text(parse), display ) import Distribution.Compat.ReadP ( readP_to_S, string, skipSpaces ) import Distribution.System ( Platform ) import Data.List ( nub ) import Data.Char ( isSpace ) import qualified Data.Map as M ( empty ) import Data.Maybe ( fromMaybe ) import qualified Data.ByteString.Lazy.Char8 as BS.Char8 -- ----------------------------------------------------------------------------- -- Configuring configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration) configure verbosity hcPath _hcPkgPath conf = do (jhcProg, _, conf') <- requireProgramVersion verbosity jhcProgram (orLaterVersion (Version [0,7,2] [])) (userMaybeSpecifyPath "jhc" hcPath conf) let Just version = programVersion jhcProg comp = Compiler { compilerId = CompilerId JHC version, compilerAbiTag = NoAbiTag, compilerCompat = [], compilerLanguages = jhcLanguages, compilerExtensions = jhcLanguageExtensions, compilerProperties = M.empty } compPlatform = Nothing return (comp, compPlatform, conf') jhcLanguages :: [(Language, Flag)] jhcLanguages = [(Haskell98, "")] -- | The flags for the supported extensions jhcLanguageExtensions :: [(Extension, Flag)] jhcLanguageExtensions = [(EnableExtension TypeSynonymInstances , "") ,(DisableExtension TypeSynonymInstances , "") ,(EnableExtension ForeignFunctionInterface , "") ,(DisableExtension ForeignFunctionInterface , "") ,(EnableExtension ImplicitPrelude , "") -- Wrong ,(DisableExtension ImplicitPrelude , "--noprelude") ,(EnableExtension CPP , "-fcpp") ,(DisableExtension CPP , "-fno-cpp") ] getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration -> IO InstalledPackageIndex getInstalledPackages verbosity _packageDBs conf = do -- jhc --list-libraries lists all available libraries. -- How shall I find out, whether they are global or local -- without checking all files and locations? str <- rawSystemProgramStdoutConf verbosity jhcProgram conf ["--list-libraries"] let pCheck :: [(a, String)] -> [a] pCheck rs = [ r | (r,s) <- rs, all isSpace s ] let parseLine ln = pCheck (readP_to_S (skipSpaces >> string "Name:" >> skipSpaces >> parse) ln) return $ PackageIndex.fromList $ map (\p -> emptyInstalledPackageInfo { InstalledPackageInfo.installedPackageId = InstalledPackageId (display p), InstalledPackageInfo.sourcePackageId = p }) $ concatMap parseLine $ lines str -- ----------------------------------------------------------------------------- -- Building -- | Building a package for JHC. -- Currently C source files are not supported. buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO () buildLib verbosity pkg_descr lbi lib clbi = do let Just jhcProg = lookupProgram jhcProgram (withPrograms lbi) let libBi = libBuildInfo lib let args = constructJHCCmdLine lbi libBi clbi (buildDir lbi) verbosity let pkgid = display (packageId pkg_descr) pfile = buildDir lbi </> "jhc-pkg.conf" hlfile= buildDir lbi </> (pkgid ++ ".hl") writeFileAtomic pfile . BS.Char8.pack $ jhcPkgConf pkg_descr rawSystemProgram verbosity jhcProg $ ["--build-hl="++pfile, "-o", hlfile] ++ args ++ map display (libModules lib) -- | Building an executable for JHC. -- Currently C source files are not supported. buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO () buildExe verbosity _pkg_descr lbi exe clbi = do let Just jhcProg = lookupProgram jhcProgram (withPrograms lbi) let exeBi = buildInfo exe let out = buildDir lbi </> exeName exe let args = constructJHCCmdLine lbi exeBi clbi (buildDir lbi) verbosity rawSystemProgram verbosity jhcProg (["-o",out] ++ args ++ [modulePath exe]) constructJHCCmdLine :: LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo -> FilePath -> Verbosity -> [String] constructJHCCmdLine lbi bi clbi _odir verbosity = (if verbosity >= deafening then ["-v"] else []) ++ hcOptions JHC bi ++ languageToFlags (compiler lbi) (defaultLanguage bi) ++ extensionsToFlags (compiler lbi) (usedExtensions bi) ++ ["--noauto","-i-"] ++ concat [["-i", l] | l <- nub (hsSourceDirs bi)] ++ ["-i", autogenModulesDir lbi] ++ ["-optc" ++ opt | opt <- PD.ccOptions bi] -- It would be better if JHC would accept package names with versions, -- but JHC-0.7.2 doesn't accept this. -- Thus, we have to strip the version with 'pkgName'. ++ (concat [ ["-p", display (pkgName pkgid)] | (_, pkgid) <- componentPackageDeps clbi ]) jhcPkgConf :: PackageDescription -> String jhcPkgConf pd = let sline name sel = name ++ ": "++sel pd lib = fromMaybe (error "no library available") . library comma = intercalate "," . map display in unlines [sline "name" (display . pkgName . packageId) ,sline "version" (display . pkgVersion . packageId) ,sline "exposed-modules" (comma . PD.exposedModules . lib) ,sline "hidden-modules" (comma . otherModules . libBuildInfo . lib) ] installLib :: Verbosity -> FilePath -> FilePath -> PackageDescription -> Library -> IO () installLib verb dest build_dir pkg_descr _ = do let p = display (packageId pkg_descr)++".hl" createDirectoryIfMissingVerbose verb True dest installOrdinaryFile verb (build_dir </> p) (dest </> p) installExe :: Verbosity -> FilePath -> FilePath -> (FilePath,FilePath) -> PackageDescription -> Executable -> IO () installExe verb dest build_dir (progprefix,progsuffix) _ exe = do let exe_name = exeName exe src = exe_name </> exeExtension out = (progprefix ++ exe_name ++ progsuffix) </> exeExtension createDirectoryIfMissingVerbose verb True dest installExecutableFile verb (build_dir </> src) (dest </> out)
DavidAlphaFox/ghc
libraries/Cabal/Cabal/Distribution/Simple/JHC.hs
Haskell
bsd-3-clause
8,608
{-# LANGUAGE OverloadedStrings #-} import Github.Issues import Data.Either import Data.Maybe import Data.Time.Clock import Data.Time.Calendar (addDays) import Data.Aeson import Data.Monoid import Data.Configurator import qualified Data.Configurator.Types as DCTypes (Value) import Web.Scotty import Network.HTTP.Types.Status import Data.List (intersect) import Data.IORef import Control.Monad.IO.Class (liftIO) import Control.Concurrent data CrossThreadData = CrossThreadData { issues :: Either [(String, Error)] [Issue], prs :: Either [(String, Error)] [Issue], recentlyClosedIssues :: Either [(String, Error)] [Issue], recentlyClosedCount :: Int, recentlyOpenedCount :: Int } data TruncatedIssue = TruncatedIssue { whenOpened :: UTCTime, whenClosed :: Maybe UTCTime, priority :: String, issueURL :: Maybe String, title :: String, createdBy :: String, ownedBy :: String } deriving Show instance ToJSON TruncatedIssue where toJSON (TruncatedIssue whenOpened whenClosed priority issueURL title createdBy ownedBy) = object ["description" .= title, "when_opened" .= whenOpened, "when_closed" .= whenClosed, "url" .= issueURL, "raiser" .= createdBy, "owner" .= ownedBy, "priority" .= priority ] getFortnightAgo :: IO UTCTime getFortnightAgo = do now <- getCurrentTime return $ UTCTime (addDays (-14) (utctDay now)) (utctDayTime now) convertJSON :: Either a [Issue] -> Either a Value convertJSON (Left errs) = Left errs convertJSON (Right issues) = Right (toJSON (map summariseIssue issues)) summariseIssue :: Issue -> TruncatedIssue summariseIssue issue = TruncatedIssue (fromGithubDate $ issueCreatedAt issue) (fmap fromGithubDate $ issueClosedAt issue) (priorityFromLabels (map labelName $ issueLabels issue)) (issueHtmlUrl issue) (issueTitle issue) (githubOwnerLogin $ issueUser issue) (fromMaybe "nobody" $ fmap githubOwnerLogin $ issueAssignee issue) doToLeft :: (a -> c) -> (Either a b) -> (Either c b) doToLeft fn (Left a) = Left (fn a) doToLeft _ (Right a) = Right a getOpenIssues :: Maybe GithubAuth -> [IssueLimitation] -> String -> String -> IO (Either (String, Error) [Issue]) getOpenIssues auth limitations user name = fmap (doToLeft (\x -> (name, x))) (issuesForRepo' auth user name limitations) onlyPRs :: Either a [Issue] -> Either a [Issue] onlyPRs (Right issues) = Right (filter isPullRequest issues) onlyPRs (Left errs) = Left errs notPRs :: Either a [Issue] -> Either a [Issue] notPRs (Right issues) = Right (filter (not . isPullRequest) issues) notPRs (Left errs) = Left errs multiGetIssues :: String -> [String] -> Maybe GithubAuth -> [IssueLimitation] -> IO (Either [(String, Error)] [Issue]) multiGetIssues user names auth limitations = fmap issuesTransform $ sequence $ map (getOpenIssues auth limitations user) names issuesTransform :: [Either a [b]] -> Either [a] [b] issuesTransform input = if null $ lefts input then Right (concat $ rights input) else Left (lefts input) overlap list1 list2 = not $ null (intersect list1 list2) priorityFromLabels_base highPriorityLabels mediumPriorityLabels lowPriorityLabels labels = if (overlap labels highPriorityLabels) then "1 - high" else if (overlap labels mediumPriorityLabels) then "2 - medium" else if (overlap labels lowPriorityLabels) then "4 - low" else "3 - unknown" priorityFromLabels = priorityFromLabels_base ["high-priority", "priority:high"] ["medium-priority", "priority:medium"] ["low-priority", "priority:low"] isPullRequest :: Issue -> Bool isPullRequest issue = isJust $ issuePullRequest issue scottyPRs :: Either [(String, Error)] [Issue] -> Int -> Int -> ActionM () scottyPRs (Left a) _ _ = do status status503 Web.Scotty.json $ object ["errors" .= (show a)] scottyPRs (Right a) ro rc = do setHeader "Access-Control-Allow-Methods" "POST, GET, OPTIONS" setHeader "Access-Control-Allow-Headers" "X-PINGOTHER" setHeader "Access-Control-Max-Age" "1728000" setHeader "Access-Control-Allow-Origin" "*" Web.Scotty.json $ object ["issues" .= (map summariseIssue a), "recentlyOpened" .= toJSON ro, "recentlyClosed" .= toJSON rc ] openedSince :: UTCTime -> Issue -> Bool openedSince when issue = (fromGithubDate (issueCreatedAt issue)) > when closedSince :: UTCTime -> Issue -> Bool closedSince when issue = case (issueClosedAt issue) of Nothing -> False Just date -> (fromGithubDate date) > when updateIssues:: String -> [String] -> Maybe GithubAuth -> IORef (CrossThreadData) -> IO () updateIssues repoOwner repoNames auth resultRef = do putStrLn "Updating issues from Github" fortnightAgo <- getFortnightAgo everything <- multiGetIssues repoOwner repoNames auth [Open] closedIssues <- fmap notPRs $ multiGetIssues repoOwner repoNames auth [OnlyClosed, (Since fortnightAgo)] let openPRs = onlyPRs everything let openIssues = notPRs everything let openIssueCount = (either length (length . filter (openedSince fortnightAgo)) openIssues) + (either length (length . filter (openedSince fortnightAgo)) closedIssues) let recentlyClosedIssues = either Left (Right . (filter (closedSince fortnightAgo))) closedIssues let closedIssueCount = either length length recentlyClosedIssues writeIORef resultRef (CrossThreadData openIssues openPRs recentlyClosedIssues closedIssueCount openIssueCount) putStrLn "Updated issues from Github" updateIssuesLoop :: String -> [String] -> Maybe GithubAuth -> IORef (CrossThreadData) -> IO () updateIssuesLoop repoOwner repoNames auth resultRef = do updateIssues repoOwner repoNames auth resultRef threadDelay (1000 * 1000 * 60 * 30) updateIssuesLoop repoOwner repoNames auth resultRef main = do cfg <- load [Required "./githubissues.cfg"] lst <- require cfg "repoNames" user <- require cfg "repoOwner" oauthToken <- Data.Configurator.lookup cfg "oauthToken" let oauth = fmap GithubOAuth oauthToken ctd <- newIORef $ CrossThreadData (Right []) (Right []) (Right []) (-1) (-1) forkIO $ updateIssuesLoop user lst oauth ctd scotty 3005 $ do get "/prs" $ do openPRs <- liftIO $ fmap prs $ readIORef ctd scottyPRs openPRs (-1) (-1) get "/issues" $ do openIssues <- liftIO $ fmap issues $ readIORef ctd ro <- liftIO $ fmap recentlyOpenedCount $ readIORef ctd rc <- liftIO $ fmap recentlyClosedCount $ readIORef ctd scottyPRs openIssues ro rc get "/recentlyClosed" $ do issues <- liftIO $ fmap recentlyClosedIssues $ readIORef ctd scottyPRs issues 0 0 get "/dashboard" $ file "./dashboard.html" get "/dashboard.js" $ file "./dashboard.js"
rkday/github-dashboard
github-dashboard.hs
Haskell
mit
7,983
{-| Module : Utils.Tuple Description : Utilities for working with tuples Copyright : (c) Tessa Belder 2015-2016 This module contains useful functions for working with tuples. -} module Utils.Tuple ( unzipConcat, mapFst, mapSnd, tmap, tmap2, swap, fst3, snd3, thrd3, fst4, snd4, thrd4, frth4 ) where import qualified Data.Graph.Inductive.Query.Monad as T (mapFst, mapSnd) -- | Unzip a list of tuples of lists, and concatenate the resulting lists of lists unzipConcat :: [([a], [b])] -> ([a], [b]) unzipConcat = mapFst concat . mapSnd concat . unzip -- | Map a function to the first element in a tuple mapFst :: (a -> a') -> (a, b) -> (a', b) mapFst = T.mapFst -- | Map a function to the first element in a tuple mapSnd :: (b -> b') -> (a, b) -> (a, b') mapSnd = T.mapSnd -- | Map a function to both elements in a tuple tmap :: (a -> b) -> (a, a) -> (b, b) tmap f = mapFst f . mapSnd f -- | Map functions to both elements in a tuple tmap2 :: (a -> a') -> (b -> b') -> (a, b) -> (a', b') tmap2 f g = mapFst f . mapSnd g -- | Swap the elements of a tuple swap :: (a, b) -> (b, a) swap (a, b) = (b, a) -- | Obtain the first element of a 3-tuple fst3 :: (a, b, c) -> a fst3 (x, _, _) = x -- | Obtain the second element of 3-tuple snd3 :: (a, b, c) -> b snd3 (_, x, _) = x -- | Obtain the third element of a 3-tuple thrd3 :: (a, b, c) -> c thrd3 (_, _, x) = x -- | Obtain the first element of a 4-tuple fst4 :: (a, b, c, d) -> a fst4 (x, _, _, _) = x -- | Obtain the second element of a 4-tuple snd4 :: (a, b, c, d) -> b snd4 (_, x, _, _) = x -- | Obtain the third element of a 4-tuple thrd4 :: (a, b, c, d) -> c thrd4 (_, _, x, _) = x -- | Obtain the fourth element of a 4-tuple frth4 :: (a, b, c, d) -> d frth4 (_, _, _, x) = x
julienschmaltz/madl
src/Utils/Tuple.hs
Haskell
mit
1,805
----------------------------------------------------------------------------- -- | -- Module : Control.AFSM.CoreType -- Copyright : (c) Hanzhong Xu, Meng Meng 2016, -- License : MIT License -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- -- {-# LANGUAGE ExistentialQuantification #-} module Control.AFSM.CoreType where -- | 'TF' is a type representing a transition function. -- s: storage, a: input, b: output -- Let's explain more about 'TF'. When a state gets an input a, -- it should do three things base on the storage and input: -- find the next state, update storage and output b. -- That's why it looks like this: -- (storage -> a -> (SM newState newStorage, b)) -- type TF storage input output = (storage -> input -> (SM storage input output, output)) -- Also, it is an instance of Arrow, it represents a machine without initial storage. -- composing two TF represents that two SM shares the same storage newtype TF s a b = TF (s -> a -> (SM s a b, b)) -- | STF is the type of simple transition function. -- type STF s a b = (s -> a -> (s, b)) -- | 'SM' is a type representing a state machine. -- (TF s a b): initial state(transition function), s: initial storage -- SM storage input output = SM (TF storage input output) storage data SM s a b = SM (TF s a b) s tf :: SM s a b -> (s -> a -> (SM s a b, b)) {-# INLINE tf #-} tf (SM (TF f) _) = f st :: SM s a b -> s {-# INLINE st #-} st (SM _ s) = s -- Constructors -- | It is the same with the SM constructor. newSM :: (s -> a -> (SM s a b, b)) -> s -> SM s a b {-# INLINE newSM #-} newSM tf s = SM (TF tf) s -- | build a simple SM which have only one TF. simpleSM :: (s -> a -> (s, b)) -> s -> SM s a b {-# INLINE simpleSM #-} simpleSM f s = newSM f' s where f' s' a' = (newSM f' s'', b) where (s'', b) = f s' a' {- -- | build a SM which can choose STF based on the input simplChcSM :: (s -> a -> STF s a b) -> s -> SM s a b simplChcSM cf s = simpleSM f s where f s a = (s', b) where (s', b) = (cf s a) s a -} instance (Show s) => Show (SM s a b) where show (SM f s) = show s -- | 'SMH' is the type of the state machine with hidden or no storage. -- It is the same type with -- Circuit a b = Circuit (a -> Circuit a b, b) type SMH a b = SM () a b -- | 'Event' type, there are 4 different events: event a, no event, error event string and exit event. data Event a = Event a | NoEvent | ErrEvent String | ExitEvent deriving (Show, Eq, Ord)
PseudoPower/AFSM
src/Control/AFSM/CoreType.hs
Haskell
mit
2,652
{-# htermination max :: Int -> Int -> Int #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_max_5.hs
Haskell
mit
46
{-# LANGUAGE OverloadedStrings #-} module OptionsSpec(spec) where import Control.Lens import System.NotifySend import Test.Hspec import Test.QuickCheck import Data.Text spec :: Spec spec = do describe "Command line options to notify-send" $ do it "should encode correctly" $ do property $ \x -> (commandOptions x) `shouldBe` ["-u", (Data.Text.toLower . pack. show) $ x ^. urgency, "-t", (pack . show) $ max 0 (x ^. expireTime), "-i", pack $ x ^. icon] it "should default correctly" $ do (commandOptions defaultNotification) `shouldBe` ["-u", "low", "-t", "1000", "-i", " "]
bobjflong/notify-send
test/OptionsSpec.hs
Haskell
mit
640
import Data.List (intersect) import GHC.Exts (sortWith) type Value = Int type Board = [Value] type Col = Int type Row = Int type Index = Int type Block = Int easy, hard, evil :: String easy = "530070000600195000098000060800060003400803001700020006060000280000419005000080079" hard = "000003020200019000001008097600000070709601804030000006360800700000950003080100000" evil = "502000008000800030000407060700010600040206090006040001050701000080002000900000806" colValues :: Col -> Board -> [Value] colValues _ [] = [] colValues col board = board !! col : colValues col (drop 9 board) rowValues :: Row -> Board -> [Value] rowValues row board = take 9 $ drop (row * 9) board blockValues :: Block -> Board -> [Value] blockValues block board = let cells = [0, 1, 2, 9, 10, 11, 18, 19, 20] offset = block `quot` 3 * 27 + (block `mod` 3 * 3) offsetCells = map (+offset) cells in map (board !!) offsetCells blockNum :: Col -> Row -> Block blockNum col row = let x = col `quot` 3 y = row `quot` 3 in y * 3 + x freeByCol :: Col -> Board -> [Value] freeByCol col board = let vs = colValues col board in filter (`notElem` vs) [1..9] freeByRow :: Row -> Board -> [Value] freeByRow row board = let vs = rowValues row board in filter (`notElem` vs) [1..9] freeByBlock :: Block -> Board -> [Value] freeByBlock block board = let vs = blockValues block board in filter (`notElem` vs) [1..9] freeByIndex :: Index -> Board -> [Value] freeByIndex i board = let col = i `mod` 9 row = i `quot` 9 block = blockNum col row colFree = freeByCol col board rowFree = freeByRow row board blockFree = freeByBlock block board in intersect colFree $ intersect rowFree blockFree moveList :: Board -> [(Index, [Value])] moveList board = let freeIndexes = map fst $ filter ((==0) . snd) $ zip [0..] board movesAt i = (i, freeByIndex i board) moves = map movesAt freeIndexes in sortWith (length . snd) moves applyMove :: Index -> Value -> Board -> Board applyMove i value board = take i board ++ [value] ++ drop (i + 1) board solveWith :: [(Index, [Value])] -> Board -> [Board] solveWith [] board = [board] solveWith ((_, []):_) _ = [] solveWith ((i, [v]):_) board = let board' = applyMove i v board moves = moveList board' in solveWith moves board' solveWith ((i, v:vs):_) board = solveWith [(i, [v])] board ++ solveWith [(i, vs)] board solve :: Board -> [Board] solve board = solveWith (moveList board) board boardStr :: Board -> String boardStr [] = [] boardStr board = boardStr' 0 board where boardStr' _ [] = "|\n+---+---+---+" boardStr' i (v:vs) = decorationAt i ++ valueStr v ++ boardStr' (i + 1) vs valueStr 0 = " " valueStr v = show v decorationAt :: Index -> String decorationAt n | n == 0 = "+---+---+---+\n|" | n `mod` 27 == 0 = "|\n+---+---+---+\n|" | n `mod` 9 == 0 = "|\n|" | n `mod` 3 == 0 = "|" | otherwise = "" printBoard :: Board -> IO () printBoard board = putStrLn $ boardStr board readBoard :: String -> Board readBoard = map (\c -> read [c]) doSolve :: String -> IO () doSolve s = do let board = readBoard s putStrLn "Initial:" printBoard board putStrLn "Solutions:" mapM_ printBoard $ solve board putStrLn "" main :: IO () main = do doSolve easy doSolve hard doSolve evil
derkyjadex/sudoku-solver
Main.hs
Haskell
mit
3,651
--The MIT License (MIT) -- --Copyright (c) 2017 Steffen Michels ([email protected]) -- --Permission is hereby granted, free of charge, to any person obtaining a copy of --this software and associated documentation files (the "Software"), to deal in --the Software without restriction, including without limitation the rights to use, --copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the --Software, and to permit persons to whom the Software is furnished to do so, --subject to the following conditions: -- --The above copyright notice and this permission notice shall be included in all --copies or substantial portions of the Software. -- --THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR --IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS --FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR --COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER --IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN --CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. module AstPreprocessor ( substitutePfsWithPfArgs ) where import AST (AST) import qualified AST import IdNrMap (IdNrMap) import qualified IdNrMap import Data.HashMap (Map) import qualified Data.HashMap as Map import Data.HashSet (Set) import qualified Data.HashSet as Set import Data.Text (Text) import TextShow import Data.Monoid ((<>)) import qualified Data.List as List import Data.Traversable (mapAccumR) import Data.Foldable (foldl') substitutePfsWithPfArgs :: AST -> IdNrMap Text -> (AST, IdNrMap Text) substitutePfsWithPfArgs ast identIds = (ast', identIds') where (ast', identIds') = Map.foldWithKey addUsagePreds (ast2, identIds2) pfsWithPfArgsUsages where -- add predicates for each usage of predicates, of which at least one arg is a PF in at least one usage addUsagePreds :: (AST.PFuncLabel, Int) -> Map [AST.Expr] AST.PredicateLabel -> (AST, IdNrMap Text) -> (AST, IdNrMap Text) addUsagePreds (_, nArgs) uses ast'' = res where (res, _, _, _) = Map.foldWithKey addUsagePreds' (ast'', 0, [], []) uses addUsagePreds' :: [AST.Expr] -> AST.PredicateLabel -> ((AST, IdNrMap Text), Int, [(AST.PredicateLabel, [AST.Expr])], [[(AST.Expr, AST.Expr)]]) -> ((AST, IdNrMap Text), Int, [(AST.PredicateLabel, [AST.Expr])], [[(AST.Expr, AST.Expr)]]) addUsagePreds' args usagePred ((ast''', identIds''), n, prevUsages, conditions) = ((ast'''', identIds'''), succ n, prevUsages', conditions') where ast'''' = ast''' { AST.rules = foldl' (\x (head', bodies'') -> Map.insert (head', 0) (([],) <$> bodies'') x) (Map.insert (usagePred, nArgs) bodies' $ AST.rules ast''') auxRules } (bodies', auxRules, identIds''') = bodies prevUsages ([], []) identIds'' conditions' = conditions prevUsages' = (usagePred, args) : prevUsages bodies :: [(AST.PredicateLabel, [AST.Expr])] -> ([([AST.HeadArgument], AST.RuleBody)], [(AST.PredicateLabel, [AST.RuleBody])]) -> IdNrMap Text -> ([([AST.HeadArgument], AST.RuleBody)], [(AST.PredicateLabel, [AST.RuleBody])], IdNrMap Text) -- handle cases that usage actually equals one of previous usage bodies ((prevUsagePred, prevUsageArgs) : prevUsages'') (accBodies, accAuxRules) identIds'''' = bodies prevUsages'' (body : accBodies, unequalAuxRule : accAuxRules) identIds''''' where body = (usagePredArgsHead, AST.RuleBody (AST.UserPredicate prevUsagePred usagePredArgs : equalToPrev)) usagePredArgsHead = [AST.ArgVariable $ AST.TempVar $ -x | x <- [1..nArgs]] usagePredArgs = [AST.Variable $ AST.TempVar $ -x | x <- [1..nArgs]] equalToPrev = [ AST.BuildInPredicate $ AST.Equality True arg argPrev | arg <- args | argPrev <- prevUsageArgs ] -- add aux rule, which is negation of 'equalToPrev', used to restrict last body to cases no rules matches unequalAuxRule = ( unequalAuxRuleHead , [ AST.RuleBody [AST.BuildInPredicate $ AST.Equality False arg argPrev] | arg <- args | argPrev <- prevUsageArgs ] ) unequalAuxRuleHead = AST.PredicateLabel unequalAuxRuleLabel (unequalAuxRuleLabel, identIds''''') = IdNrMap.getIdNr usagePredAuxLabel identIds'''' where AST.PredicateLabel pfId = usagePred usagePredAuxLabel = toText $ fromText (Map.findWithDefault undefined pfId (IdNrMap.fromIdNrMap identIds'')) <> "_" <> showb (length accBodies) -- add last case: no previous usage equals current one bodies [] (accBodies, accAuxRules) identIds'''' = ( ([AST.ArgVariable $ AST.TempVar $ -x | x <- [1..nArgs]], AST.RuleBody body) : accBodies , accAuxRules , identIds'''' ) where body = argValueEqs ++ uneqPrevious argValueEqs = [ AST.BuildInPredicate $ AST.Equality True (AST.Variable $ AST.TempVar $ -v) (pfs2placeh arg) | v <- [1..nArgs] | arg <- args ] uneqPrevious = [AST.UserPredicate label [] | (label, _) <- accAuxRules] pfs2placeh (AST.PFunc (AST.PFuncLabel pf) []) = AST.ConstantExpr $ AST.Placeholder (Map.findWithDefault undefined pf (IdNrMap.fromIdNrMap identIds'')) pfs2placeh arg = arg -- predicates for which pfsWithPfArgs are used -> all usages with generated predicate label to compute arguments of that usage pfsWithPfArgsUsages :: Map (AST.PFuncLabel, Int) (Map [AST.Expr] AST.PredicateLabel) pfsWithPfArgsUsages = pfsWithPfArgsUsages' ((pfsWithPfArgsUsages', identIds2, _), ast2) = mapAccumAddRuleElemsPfs pfsWithPfArgsUsages'' (Map.empty, identIds, 1) ast where pfsWithPfArgsUsages'' :: (Map (AST.PFuncLabel, Int) (Map [AST.Expr] AST.PredicateLabel), IdNrMap Text, Int) -> ((AST.PFuncLabel, Int), [AST.Expr]) -> ([AST.Expr], (Map (AST.PFuncLabel, Int) (Map [AST.Expr] AST.PredicateLabel), IdNrMap Text, Int), [AST.RuleBodyElement]) pfsWithPfArgsUsages'' st@(pfUses, identIds'', tmpVarCounter) (sign@(AST.PFuncLabel pfId, _), args) | Set.member sign pfsWithPfArgs = let usesArgs = Map.findWithDefault Map.empty sign pfUses in case Map.lookup args usesArgs of Just prd -> (argsWithSubstPfs, (pfUses, identIds'', tmpVarCounter'), [AST.UserPredicate prd argsWithSubstPfs]) Nothing -> let (prdId, identIds''') = IdNrMap.getIdNr (predIdent $ Map.size usesArgs) identIds'' prdLabel = AST.PredicateLabel prdId in ( argsWithSubstPfs , (Map.insert sign (Map.insert args prdLabel usesArgs) pfUses, identIds''', tmpVarCounter') , [AST.UserPredicate prdLabel argsWithSubstPfs] ) | otherwise = (args, st, []) where -- substitute all Pfs used as args with fresh variables (tmpVarCounter', argsWithSubstPfs) = mapAccumR substPfs tmpVarCounter args where substPfs counter (AST.PFunc _ _) = (succ counter, AST.Variable $ AST.TempVar $ -counter) substPfs counter a = (counter, a) predIdent n = toText $ "~" <> fromText (Map.findWithDefault undefined pfId (IdNrMap.fromIdNrMap identIds)) <> "@" <> showb n -- all pfs which have pfs as args pfsWithPfArgs :: Set (AST.PFuncLabel, Int) pfsWithPfArgs = fst $ mapAccumAddRuleElemsPfs pfsWithPfArgs' Set.empty ast where pfsWithPfArgs' :: Set (AST.PFuncLabel, Int) -> ((AST.PFuncLabel, Int), [AST.Expr]) -> ([AST.Expr], Set (AST.PFuncLabel, Int), [a]) pfsWithPfArgs' pfs (sign, args) | any (AST.foldExpr (\b e -> b || AST.exprIsPFunc e) False) args = (args, Set.insert sign pfs, []) | otherwise = (args, pfs, []) mapAccumAddRuleElemsPfs :: (a -> ((AST.PFuncLabel, Int), [AST.Expr]) -> ([AST.Expr], a, [AST.RuleBodyElement])) -> a -> AST -> (a, AST) mapAccumAddRuleElemsPfs f acc ast = (acc', ast{AST.rules = rules}) where (acc', rules) = Map.mapAccumWithKey (\acc'' _ -> List.mapAccumL mapAccumAddRuleElemsPfs' acc'') acc (AST.rules ast) mapAccumAddRuleElemsPfs' acc'' (args, AST.RuleBody body) = (acc''', (args, AST.RuleBody $ concat body')) where (acc''', body') = List.mapAccumL mapAccumAddRuleElemsPfs'' acc'' body mapAccumAddRuleElemsPfs'' acc'' el@(AST.UserPredicate _ _) = (acc'', [el]) mapAccumAddRuleElemsPfs'' acc'' (AST.BuildInPredicate bip) = case bip of AST.Equality op exprX exprY -> mapAccumAddRuleElemsPfs''' (AST.Equality op) exprX exprY AST.Ineq op exprX exprY -> mapAccumAddRuleElemsPfs''' (AST.Ineq op) exprX exprY where mapAccumAddRuleElemsPfs''' constr exprX exprY = (acc'''', AST.BuildInPredicate (constr exprX' exprY') : toAdd) where (acc''', exprX') = AST.mapAccExpr mapAccumAddRuleElemsPfs'''' (acc'', []) exprX ((acc'''', toAdd), exprY') = AST.mapAccExpr mapAccumAddRuleElemsPfs'''' acc''' exprY mapAccumAddRuleElemsPfs'''' (acc'', toAdd) (AST.PFunc label args) = ((acc''', toAdd ++ toAdd'), AST.PFunc label args') where (args', acc''', toAdd') = f acc'' ((label, length args), args) mapAccumAddRuleElemsPfs'''' acc'' expr = (acc'', expr)
SteffenMichels/IHPMC
src/AstPreprocessor.hs
Haskell
mit
10,833