code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE PatternGuards #-} {-# OPTIONS_GHC -fno-warn-deprecations #-} --------------------------------------------------------- -- -- Module : Network.Wai.Handler.Warp -- Copyright : Michael Snoyman -- License : BSD3 -- -- Maintainer : Michael Snoyman <michael@snoyman.com> -- Stability : Stable -- Portability : portable -- -- A fast, light-weight HTTP server handler for WAI. -- --------------------------------------------------------- -- | A fast, light-weight HTTP server handler for WAI. -- -- HTTP\/1.0, HTTP\/1.1 and HTTP\/2 are supported. For HTTP\/2, -- Warp supports direct and ALPN (in TLS) but not upgrade. -- -- Note on slowloris timeouts: to prevent slowloris attacks, timeouts are used -- at various points in request receiving and response sending. One interesting -- corner case is partial request body consumption; in that case, Warp's -- timeout handling is still in effect, and the timeout will not be triggered -- again. Therefore, it is recommended that once you start consuming the -- request body, you either: -- -- * consume the entire body promptly -- -- * call the 'pauseTimeout' function -- -- For more information, see <https://github.com/yesodweb/wai/issues/351>. -- -- module Network.Wai.Handler.Warp ( -- * Run a Warp server -- | All of these automatically serve the same 'Application' over HTTP\/1, -- HTTP\/1.1, and HTTP\/2. run , runEnv , runSettings , runSettingsSocket -- * Settings , Settings , defaultSettings -- ** Setters , setPort , setHost , setOnException , setOnExceptionResponse , setOnOpen , setOnClose , setTimeout , setManager , setFdCacheDuration , setFileInfoCacheDuration , setBeforeMainLoop , setNoParsePath , setInstallShutdownHandler , setServerName , setMaximumBodyFlush , setFork , setProxyProtocolNone , setProxyProtocolRequired , setProxyProtocolOptional , setSlowlorisSize , setHTTP2Disabled , setLogger , setServerPushLogger , setGracefulShutdownTimeout , setGracefulCloseTimeout1 , setGracefulCloseTimeout2 , setMaxTotalHeaderLength , setAltSvc -- ** Getters , getPort , getHost , getOnOpen , getOnClose , getOnException , getGracefulShutdownTimeout , getGracefulCloseTimeout1 , getGracefulCloseTimeout2 -- ** Exception handler , defaultOnException , defaultShouldDisplayException -- ** Exception response handler , defaultOnExceptionResponse , exceptionResponseForDebug -- * Data types , HostPreference , Port , InvalidRequest (..) -- * Utilities , pauseTimeout , FileInfo(..) , getFileInfo , clientCertificate , withApplication , withApplicationSettings , testWithApplication , testWithApplicationSettings , openFreePort -- * Version , warpVersion -- * HTTP/2 -- ** HTTP2 data , HTTP2Data , http2dataPushPromise , http2dataTrailers , defaultHTTP2Data , getHTTP2Data , setHTTP2Data , modifyHTTP2Data -- ** Push promise , PushPromise , promisedPath , promisedFile , promisedResponseHeaders , promisedWeight , defaultPushPromise ) where import UnliftIO.Exception (SomeException, throwIO) import Data.Streaming.Network (HostPreference) import qualified Data.Vault.Lazy as Vault import Data.X509 import qualified Network.HTTP.Types as H import Network.Socket (SockAddr) import Network.Wai (Request, Response, vault) import System.TimeManager import Network.Wai.Handler.Warp.FileInfoCache import Network.Wai.Handler.Warp.HTTP2.Request (getHTTP2Data, setHTTP2Data, modifyHTTP2Data) import Network.Wai.Handler.Warp.HTTP2.Types import Network.Wai.Handler.Warp.Imports import Network.Wai.Handler.Warp.Request import Network.Wai.Handler.Warp.Response (warpVersion) import Network.Wai.Handler.Warp.Run import Network.Wai.Handler.Warp.Settings import Network.Wai.Handler.Warp.Types hiding (getFileInfo) import Network.Wai.Handler.Warp.WithApplication -- | Port to listen on. Default value: 3000 -- -- Since 2.1.0 setPort :: Port -> Settings -> Settings setPort x y = y { settingsPort = x } -- | Interface to bind to. Default value: HostIPv4 -- -- Since 2.1.0 setHost :: HostPreference -> Settings -> Settings setHost x y = y { settingsHost = x } -- | What to do with exceptions thrown by either the application or server. -- Default: 'defaultOnException' -- -- Since 2.1.0 setOnException :: (Maybe Request -> SomeException -> IO ()) -> Settings -> Settings setOnException x y = y { settingsOnException = x } -- | A function to create a `Response` when an exception occurs. -- Default: 'defaultOnExceptionResponse' -- -- Note that an application can handle its own exceptions without interfering with Warp: -- -- > myApp :: Application -- > myApp request respond = innerApp `catch` onError -- > where -- > onError = respond . response500 request -- > -- > response500 :: Request -> SomeException -> Response -- > response500 req someEx = responseLBS status500 -- ... -- -- Since 2.1.0 setOnExceptionResponse :: (SomeException -> Response) -> Settings -> Settings setOnExceptionResponse x y = y { settingsOnExceptionResponse = x } -- | What to do when a connection is opened. When 'False' is returned, the -- connection is closed immediately. Otherwise, the connection is going on. -- Default: always returns 'True'. -- -- Since 2.1.0 setOnOpen :: (SockAddr -> IO Bool) -> Settings -> Settings setOnOpen x y = y { settingsOnOpen = x } -- | What to do when a connection is closed. Default: do nothing. -- -- Since 2.1.0 setOnClose :: (SockAddr -> IO ()) -> Settings -> Settings setOnClose x y = y { settingsOnClose = x } -- | "Slow-loris" timeout lower-bound value in seconds. Connections where -- network progress is made less frequently than this may be closed. In -- practice many connections may be allowed to go without progress for up to -- twice this amount of time. Note that this timeout is not applied to -- application code, only network progress. -- -- Default value: 30 -- -- Since 2.1.0 setTimeout :: Int -> Settings -> Settings setTimeout x y = y { settingsTimeout = x } -- | Use an existing timeout manager instead of spawning a new one. If used, -- 'settingsTimeout' is ignored. -- -- Since 2.1.0 setManager :: Manager -> Settings -> Settings setManager x y = y { settingsManager = Just x } -- | Cache duration time of file descriptors in seconds. 0 means that the cache mechanism is not used. -- -- The FD cache is an optimization that is useful for servers dealing with -- static files. However, if files are being modified, it can cause incorrect -- results in some cases. Therefore, we disable it by default. If you know that -- your files will be static or you prefer performance to file consistency, -- it's recommended to turn this on; a reasonable value for those cases is 10. -- Enabling this cache results in drastic performance improvement for file -- transfers. -- -- Default value: 0, was previously 10 -- -- Since 3.0.13 setFdCacheDuration :: Int -> Settings -> Settings setFdCacheDuration x y = y { settingsFdCacheDuration = x } -- | Cache duration time of file information in seconds. 0 means that the cache mechanism is not used. -- -- The file information cache is an optimization that is useful for servers dealing with -- static files. However, if files are being modified, it can cause incorrect -- results in some cases. Therefore, we disable it by default. If you know that -- your files will be static or you prefer performance to file consistency, -- it's recommended to turn this on; a reasonable value for those cases is 10. -- Enabling this cache results in drastic performance improvement for file -- transfers. -- -- Default value: 0 setFileInfoCacheDuration :: Int -> Settings -> Settings setFileInfoCacheDuration x y = y { settingsFileInfoCacheDuration = x } -- | Code to run after the listening socket is ready but before entering -- the main event loop. Useful for signaling to tests that they can start -- running, or to drop permissions after binding to a restricted port. -- -- Default: do nothing. -- -- Since 2.1.0 setBeforeMainLoop :: IO () -> Settings -> Settings setBeforeMainLoop x y = y { settingsBeforeMainLoop = x } -- | Perform no parsing on the rawPathInfo. -- -- This is useful for writing HTTP proxies. -- -- Default: False -- -- Since 2.1.0 setNoParsePath :: Bool -> Settings -> Settings setNoParsePath x y = y { settingsNoParsePath = x } -- | Get the listening port. -- -- Since 2.1.1 getPort :: Settings -> Port getPort = settingsPort -- | Get the interface to bind to. -- -- Since 2.1.1 getHost :: Settings -> HostPreference getHost = settingsHost -- | Get the action on opening connection. getOnOpen :: Settings -> SockAddr -> IO Bool getOnOpen = settingsOnOpen -- | Get the action on closeing connection. getOnClose :: Settings -> SockAddr -> IO () getOnClose = settingsOnClose -- | Get the exception handler. getOnException :: Settings -> Maybe Request -> SomeException -> IO () getOnException = settingsOnException -- | Get the graceful shutdown timeout -- -- Since 3.2.8 getGracefulShutdownTimeout :: Settings -> Maybe Int getGracefulShutdownTimeout = settingsGracefulShutdownTimeout -- | A code to install shutdown handler. -- -- For instance, this code should set up a UNIX signal -- handler. The handler should call the first argument, -- which closes the listen socket, at shutdown. -- -- Example usage: -- -- @ -- settings :: IO () -> 'Settings' -- settings shutdownAction = 'setInstallShutdownHandler' shutdownHandler 'defaultSettings' -- __where__ -- shutdownHandler closeSocket = -- void $ 'System.Posix.Signals.installHandler' 'System.Posix.Signals.sigTERM' ('System.Posix.Signals.Catch' $ shutdownAction >> closeSocket) 'Nothing' -- @ -- -- Note that by default, the graceful shutdown mode lasts indefinitely -- (see 'setGracefulShutdownTimeout'). If you install a signal handler as above, -- upon receiving that signal, the custon shutdown action will run /and/ all -- outstanding requests will be handled. -- -- You may instead prefer to do one or both of the following: -- -- * Only wait a finite amount of time for outstanding requests to complete, -- using 'setGracefulShutdownTimeout'. -- * Only catch one signal, so the second hard-kills the Warp server, using -- 'System.Posix.Signals.CatchOnce'. -- -- Default: does not install any code. -- -- Since 3.0.1 setInstallShutdownHandler :: (IO () -> IO ()) -> Settings -> Settings setInstallShutdownHandler x y = y { settingsInstallShutdownHandler = x } -- | Default server name to be sent as the \"Server:\" header -- if an application does not set one. -- If an empty string is set, the \"Server:\" header is not sent. -- This is true even if an application set one. -- -- Since 3.0.2 setServerName :: ByteString -> Settings -> Settings setServerName x y = y { settingsServerName = x } -- | The maximum number of bytes to flush from an unconsumed request body. -- -- By default, Warp does not flush the request body so that, if a large body is -- present, the connection is simply terminated instead of wasting time and -- bandwidth on transmitting it. However, some clients do not deal with that -- situation well. You can either change this setting to @Nothing@ to flush the -- entire body in all cases, or in your application ensure that you always -- consume the entire request body. -- -- Default: 8192 bytes. -- -- Since 3.0.3 setMaximumBodyFlush :: Maybe Int -> Settings -> Settings setMaximumBodyFlush x y | Just x' <- x, x' < 0 = error "setMaximumBodyFlush: must be positive" | otherwise = y { settingsMaximumBodyFlush = x } -- | Code to fork a new thread to accept a connection. -- -- This may be useful if you need OS bound threads, or if -- you wish to develop an alternative threading model. -- -- Default: void . forkIOWithUnmask -- -- Since 3.0.4 setFork :: (((forall a. IO a -> IO a) -> IO ()) -> IO ()) -> Settings -> Settings setFork fork' s = s { settingsFork = fork' } -- | Do not use the PROXY protocol. -- -- Since 3.0.5 setProxyProtocolNone :: Settings -> Settings setProxyProtocolNone y = y { settingsProxyProtocol = ProxyProtocolNone } -- | Require PROXY header. -- -- This is for cases where a "dumb" TCP/SSL proxy is being used, which cannot -- add an @X-Forwarded-For@ HTTP header field but has enabled support for the -- PROXY protocol. -- -- See <http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt> and -- <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#proxy-protocol>. -- -- Only the human-readable header format (version 1) is supported. The binary -- header format (version 2) is /not/ supported. -- -- Since 3.0.5 setProxyProtocolRequired :: Settings -> Settings setProxyProtocolRequired y = y { settingsProxyProtocol = ProxyProtocolRequired } -- | Use the PROXY header if it exists, but also accept -- connections without the header. See 'setProxyProtocolRequired'. -- -- WARNING: This is contrary to the PROXY protocol specification and -- using it can indicate a security problem with your -- architecture if the web server is directly accessible -- to the public, since it would allow easy IP address -- spoofing. However, it can be useful in some cases, -- such as if a load balancer health check uses regular -- HTTP without the PROXY header, but proxied -- connections /do/ include the PROXY header. -- -- Since 3.0.5 setProxyProtocolOptional :: Settings -> Settings setProxyProtocolOptional y = y { settingsProxyProtocol = ProxyProtocolOptional } -- | Size in bytes read to prevent Slowloris attacks. Default value: 2048 -- -- Since 3.1.2 setSlowlorisSize :: Int -> Settings -> Settings setSlowlorisSize x y = y { settingsSlowlorisSize = x } -- | Disable HTTP2. -- -- Since 3.1.7 setHTTP2Disabled :: Settings -> Settings setHTTP2Disabled y = y { settingsHTTP2Enabled = False } -- | Setting a log function. -- -- Since 3.X.X setLogger :: (Request -> H.Status -> Maybe Integer -> IO ()) -- ^ request, status, maybe file-size -> Settings -> Settings setLogger lgr y = y { settingsLogger = lgr } -- | Setting a log function for HTTP/2 server push. -- -- Since: 3.2.7 setServerPushLogger :: (Request -> ByteString -> Integer -> IO ()) -- ^ request, path, file-size -> Settings -> Settings setServerPushLogger lgr y = y { settingsServerPushLogger = lgr } -- | Set the graceful shutdown timeout. A timeout of `Nothing' will -- wait indefinitely, and a number, if provided, will be treated as seconds -- to wait for requests to finish, before shutting down the server entirely. -- -- Graceful shutdown mode is entered when the server socket is closed; see -- 'setInstallShutdownHandler' for an example of how this could be done in -- response to a UNIX signal. -- -- Since 3.2.8 setGracefulShutdownTimeout :: Maybe Int -> Settings -> Settings setGracefulShutdownTimeout time y = y { settingsGracefulShutdownTimeout = time } -- | Set the maximum header size that Warp will tolerate when using HTTP/1.x. -- -- Since 3.3.8 setMaxTotalHeaderLength :: Int -> Settings -> Settings setMaxTotalHeaderLength maxTotalHeaderLength settings = settings { settingsMaxTotalHeaderLength = maxTotalHeaderLength } -- | Setting the header value of Alternative Services (AltSvc:). -- -- Since 3.3.11 setAltSvc :: ByteString -> Settings -> Settings setAltSvc altsvc settings = settings { settingsAltSvc = Just altsvc } -- | Explicitly pause the slowloris timeout. -- -- This is useful for cases where you partially consume a request body. For -- more information, see <https://github.com/yesodweb/wai/issues/351> -- -- Since 3.0.10 pauseTimeout :: Request -> IO () pauseTimeout = fromMaybe (return ()) . Vault.lookup pauseTimeoutKey . vault -- | Getting file information of the target file. -- -- This function first uses a stat(2) or similar system call -- to obtain information of the target file, then registers -- it into the internal cache. -- From the next time, the information is obtained -- from the cache. This reduces the overhead to call the system call. -- The internal cache is refreshed every duration specified by -- 'setFileInfoCacheDuration'. -- -- This function throws an 'IO' exception if the information is not -- available. For instance, the target file does not exist. -- If this function is used an a Request generated by a WAI -- backend besides Warp, it also throws an 'IO' exception. -- -- Since 3.1.10 getFileInfo :: Request -> FilePath -> IO FileInfo getFileInfo = fromMaybe (\_ -> throwIO (userError "getFileInfo")) . Vault.lookup getFileInfoKey . vault -- | A timeout to limit the time (in milliseconds) waiting for -- FIN for HTTP/1.x. 0 means uses immediate close. -- Default: 0. -- -- Since 3.3.5 setGracefulCloseTimeout1 :: Int -> Settings -> Settings setGracefulCloseTimeout1 x y = y { settingsGracefulCloseTimeout1 = x } -- | A timeout to limit the time (in milliseconds) waiting for -- FIN for HTTP/1.x. 0 means uses immediate close. -- -- Since 3.3.5 getGracefulCloseTimeout1 :: Settings -> Int getGracefulCloseTimeout1 = settingsGracefulCloseTimeout1 -- | A timeout to limit the time (in milliseconds) waiting for -- FIN for HTTP/2. 0 means uses immediate close. -- Default: 2000. -- -- Since 3.3.5 setGracefulCloseTimeout2 :: Int -> Settings -> Settings setGracefulCloseTimeout2 x y = y { settingsGracefulCloseTimeout2 = x } -- | A timeout to limit the time (in milliseconds) waiting for -- FIN for HTTP/2. 0 means uses immediate close. -- -- Since 3.3.5 getGracefulCloseTimeout2 :: Settings -> Int getGracefulCloseTimeout2 = settingsGracefulCloseTimeout2 -- | Getting information of client certificate. -- -- Since 3.3.5 clientCertificate :: Request -> Maybe CertificateChain clientCertificate = join . Vault.lookup getClientCertificateKey . vault
sordina/wai
warp/Network/Wai/Handler/Warp.hs
bsd-2-clause
17,950
0
13
3,154
2,039
1,288
751
181
1
-- Copyright (C) 2012 John Chee -- See LICENSE for more details -- TODO verify mode, cleanup mode -- TODO in verify mode, report _all_ failures (line + byte in line + total byte offset) import qualified Data.ByteString.Lazy.Char8 as L8 import Data.Text.Lazy (Text) import qualified Data.Text.Lazy.IO as TIO import qualified Data.Text.Lazy.Encoding as DTE import Data.Text.Encoding.Error (OnDecodeError) import qualified Data.Text.Encoding.Error as DTEE -- Copied from: http://hackage.haskell.org/packages/archive/text/0.11.2.3/doc/html/src/Data-Text-Lazy-IO.html#hGetContents getContentsDecodedWith :: OnDecodeError -> IO Text getContentsDecodedWith ode = fmap (DTE.decodeUtf8With ode) L8.getContents interactDecodeWith :: OnDecodeError -> (Text -> Text) -> IO () interactDecodeWith ode f = TIO.putStr . f =<< (getContentsDecodedWith ode) main :: IO () main = interactDecodeWith DTEE.lenientDecode id --main = interactDecodeWith DTEE.strictDecode id
cheecheeo/utf8clean
utf8clean.hs
bsd-2-clause
955
0
8
117
178
107
71
12
1
module Data.CRF.Chain1.Util ( partition ) where import Data.List (transpose) partition :: Int -> [a] -> [[a]] partition n = transpose . group n where group _ [] = [] group k xs = take k xs : (group k $ drop k xs)
kawu/crf-chain1
src/Data/CRF/Chain1/Util.hs
bsd-2-clause
229
0
10
59
110
59
51
8
2
-- -- Copyright (c) 2013, Carl Joachim Svenn -- 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 MEnv.System ( #ifdef GRID_PLATFORM_IOS module MEnv.System.IOS, #endif #ifdef GRID_PLATFORM_GLFW module MEnv.System.GLFW, #endif ) where #ifdef GRID_PLATFORM_IOS import MEnv.System.IOS #endif #ifdef GRID_PLATFORM_GLFW import MEnv.System.GLFW #endif
karamellpelle/MEnv
source/MEnv/System.hs
bsd-2-clause
1,727
0
5
350
67
56
11
2
0
module Scurry.Data.Packet ( module Scurry.Data.Packet.Ethernet, module Scurry.Data.Packet.IPv4, parsePkt, encodePkt, ) where import Scurry.Data.Packet.Ethernet import Scurry.Data.Packet.IPv4 import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.Binary import Data.Binary.Get import Data.Binary.Put data Frame = Frame { eth :: Ethernet, pl :: EthPayload } deriving (Show) data EthPayload = PL_IPv4 IPv4 | PL_Other B.ByteString deriving (Show) instance Binary Frame where get = do e <- get p <- case etype e of ET_IP -> get >>= (return . PL_IPv4) _ -> getRemainingStrict >>= (return . PL_Other) return $ Frame { eth = e, pl = p } put f = do put $ eth f case pl f of (PL_IPv4 i) -> put i (PL_Other o) -> putByteString o parsePkt :: B.ByteString -> Frame parsePkt b = decode $ L.fromChunks [b] encodePkt :: Frame -> B.ByteString encodePkt = B.concat . L.toChunks . encode getRemainingStrict :: Get B.ByteString getRemainingStrict = remaining >>= (getBytes . fromIntegral)
sw17ch/Scurry
src/Scurry/Data/Packet.hs
bsd-3-clause
1,177
0
14
323
363
204
159
37
1
module Main where import System.Environment (getArgs) import Brainfuck.Parser import Brainfuck.Interpreter main :: IO () main = fmap head getArgs >>= fmap parse . readFile >>= run
sivawashere/bf
src/Main.hs
bsd-3-clause
182
0
8
28
59
32
27
6
1
module Render.Basic.BasicRenderAPI where import Render.RenderAPI import Types basicRenderAPI :: RenderAPI basicRenderAPI = undefined -- TODO
ksaveljev/hake-2
src/Render/Basic/BasicRenderAPI.hs
bsd-3-clause
143
0
4
17
26
17
9
5
1
{-# LANGUAGE TypeFamilies, DataKinds, TypeOperators, MultiParamTypeClasses , FlexibleInstances, PolyKinds, UndecidableInstances, AllowAmbiguousTypes , RankNTypes, ScopedTypeVariables, FlexibleContexts, ConstraintKinds #-} module Control.Instances.Morph (GenMorph(..), DB, db, Morph, morph) where import Control.Instances.ShortestPath import Control.Monad.Identity import Control.Monad.Trans.Maybe import Control.Monad.Trans.List import Data.Maybe import Data.Proxy -- | States that 'm1' can be represented with 'm2'. -- That is because 'm2' contains more infromation than 'm1'. -- -- The 'MMorph' relation defines a natural transformation from 'm1' to 'm2' -- that keeps the following laws: -- -- > morph (return x) = return x -- > morph (m >>= f) = morph m >>= morph . f -- -- It is a reflexive and transitive relation. -- type Morph m1 m2 = GenMorph DB m1 m2 -- | Lifts the first monad into the second. morph :: Morph m1 m2 => m1 a -> m2 a morph = genMorph db -- instance GenMorph DB m1 m2 => Morph m1 m2 where -- morph = genMorph db -- | A generalized version of 'Morph'. Can work on different -- rulesets, so this should be used if the ruleset is to be extended. type GenMorph db m1 m2 = ( CorrectPath m1 m2 (Path db m1 m2) , GeneratableMorph db (Path db m1 m2) , Morph' (Path db m1 m2) m1 m2 ) type Path db m1 m2 = TransformPath (PathFromList (ShortestPath (ToMorphRepo db) m1 m2)) -- | Lifts the first monad into the second. genMorph :: forall db m1 m2 a . GenMorph db m1 m2 => db -> m1 a -> m2 a genMorph db = repr (generateMorph db :: (Path db m1 m2)) class Morph' fl x y where repr :: fl -> x a -> y a instance Morph' r y z => Morph' (ConnectMorph x y :+: r) x z where repr (ConnectMorph m :+: r) = repr r . m instance (Morph' r m x, Monad m) => Morph' (IdentityMorph m :+: r) Identity x where repr (IdentityMorph :+: r) = (repr r :: forall a . m a -> x a) . return . runIdentity instance Morph' (MUMorph m :+: r) m Proxy where repr (MUMorph :+: _) = const Proxy instance Morph' NoMorph x x where repr _ = id infixr 6 :+: data a :+: r = a :+: r data NoMorph = NoMorph type family ToMorphRepo db where ToMorphRepo (cm :+: r) = TranslateConn cm ': ToMorphRepo r ToMorphRepo NoMorph = '[] type DB = ConnectMorph_2m Maybe MaybeT :+: ConnectMorph_mt MaybeT :+: ConnectMorph Maybe [] :+: ConnectMorph_2m [] ListT :+: ConnectMorph (MaybeT IO) (ListT IO) :+: NoMorph db :: DB db = ConnectMorph_2m (MaybeT . return) :+: ConnectMorph_mt (MaybeT . liftM Just) :+: ConnectMorph (maybeToList) :+: ConnectMorph_2m (ListT . return) :+: ConnectMorph (ListT . liftM maybeToList . runMaybeT) :+: NoMorph -- | This class provides a way to construct the value-level transformations -- from the type-level path and a rulebase. class GeneratableMorph db ch where generateMorph :: db -> ch instance GeneratableMorph db NoMorph where generateMorph _ = NoMorph instance GeneratableMorph db r => GeneratableMorph db ((IdentityMorph m) :+: r) where generateMorph db = IdentityMorph :+: generateMorph db instance GeneratableMorph db r => GeneratableMorph db (MUMorph m :+: r) where generateMorph db = MUMorph :+: generateMorph db instance (HasMorph db (ConnectMorph a b), GeneratableMorph db r) => GeneratableMorph db (ConnectMorph a b :+: r) where generateMorph db = getMorph db :+: generateMorph db -- | This class extracts a given morph from the set of rules class HasMorph r m where getMorph :: r -> m instance {-# OVERLAPPING #-} Monad k => HasMorph (ConnectMorph_2m a b :+: r) (ConnectMorph a (b k)) where getMorph (ConnectMorph_2m f :+: _) = ConnectMorph f instance {-# OVERLAPPING #-} Monad k => HasMorph (ConnectMorph_mt t :+: r) (ConnectMorph k (t k)) where getMorph (ConnectMorph_mt f :+: _) = ConnectMorph f instance {-# OVERLAPS #-} HasMorph r m => HasMorph (c :+: r) m where getMorph (_ :+: r) = getMorph r instance {-# OVERLAPPABLE #-} HasMorph (m :+: r) m where getMorph (c :+: _) = c -- | Checks if the path is found to provide usable error messages class CorrectPath from to path instance CorrectPath from to (a :+: b) instance CorrectPath from to NoMorph data ConnectMorph m1 m2 = ConnectMorph (forall a . m1 a -> m2 a) data ConnectMorph_2m m1 m2 = ConnectMorph_2m (forall a k . Monad k => m1 a -> m2 k a) data ConnectMorph_mt mt = ConnectMorph_mt (forall a k . Monad k => k a -> mt k a) data IdentityMorph (m :: * -> *) = IdentityMorph data MUMorph m = MUMorph -- | Transforms a path element from the generic format to the specific one type family TranslateConn m where TranslateConn (ConnectMorph m1 m2) = Connect m1 m2 TranslateConn (ConnectMorph_2m m1 m2) = Connect_2m m1 m2 TranslateConn (ConnectMorph_mt mt) = Connect_mt mt -- | Transforms the path from the generic format to the specific one type family TransformPath m where TransformPath (Connect m1 m2 :+: r) = ConnectMorph m1 m2 :+: TransformPath r TransformPath (Connect_id m :+: r) = IdentityMorph m :+: TransformPath r TransformPath (Connect_MU m :+: r) = MUMorph m :+: TransformPath r TransformPath NoMorph = NoMorph TransformPath NoPathFound = NoPathFound type family PathFromList ls where PathFromList '[] = NoMorph PathFromList '[ NoPathFound ] = NoPathFound PathFromList (c ': ls) = c :+: PathFromList ls
nboldi/instance-control
Control/Instances/Morph.hs
bsd-3-clause
5,621
0
13
1,341
1,593
832
761
-1
-1
module RevealHs ( module X ) where import RevealHs.Internal as X import RevealHs.Options as X import RevealHs.QQ as X import RevealHs.TH as X
KenetJervet/reveal-hs
src/RevealHs.hs
bsd-3-clause
159
0
4
40
38
27
11
5
0
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} {-# OPTIONS_GHC -funbox-strict-fields #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.BufferedIO -- Copyright : (c) The University of Glasgow 2008 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- Class of buffered IO devices -- ----------------------------------------------------------------------------- module GHC.IO.BufferedIO ( BufferedIO(..), readBuf, readBufNonBlocking, writeBuf, writeBufNonBlocking ) where import GHC.Base import GHC.Ptr import Data.Word import GHC.Num import GHC.IO.Device as IODevice import GHC.IO.Device as RawIO import GHC.IO.Buffer -- | The purpose of 'BufferedIO' is to provide a common interface for I/O -- devices that can read and write data through a buffer. Devices that -- implement 'BufferedIO' include ordinary files, memory-mapped files, -- and bytestrings. The underlying device implementing a 'Handle' must -- provide 'BufferedIO'. -- class BufferedIO dev where -- | allocate a new buffer. The size of the buffer is at the -- discretion of the device; e.g. for a memory-mapped file the -- buffer will probably cover the entire file. newBuffer :: dev -> BufferState -> IO (Buffer Word8) -- | reads bytes into the buffer, blocking if there are no bytes -- available. Returns the number of bytes read (zero indicates -- end-of-file), and the new buffer. fillReadBuffer :: dev -> Buffer Word8 -> IO (Int, Buffer Word8) -- | reads bytes into the buffer without blocking. Returns the -- number of bytes read (Nothing indicates end-of-file), and the new -- buffer. fillReadBuffer0 :: dev -> Buffer Word8 -> IO (Maybe Int, Buffer Word8) -- | Prepares an empty write buffer. This lets the device decide -- how to set up a write buffer: the buffer may need to point to a -- specific location in memory, for example. This is typically used -- by the client when switching from reading to writing on a -- buffered read/write device. -- -- There is no corresponding operation for read buffers, because before -- reading the client will always call 'fillReadBuffer'. emptyWriteBuffer :: dev -> Buffer Word8 -> IO (Buffer Word8) emptyWriteBuffer _dev buf = return buf{ bufL=0, bufR=0, bufState = WriteBuffer } -- | Flush all the data from the supplied write buffer out to the device. -- The returned buffer should be empty, and ready for writing. flushWriteBuffer :: dev -> Buffer Word8 -> IO (Buffer Word8) -- | Flush data from the supplied write buffer out to the device -- without blocking. Returns the number of bytes written and the -- remaining buffer. flushWriteBuffer0 :: dev -> Buffer Word8 -> IO (Int, Buffer Word8) -- for an I/O device, these operations will perform reading/writing -- to/from the device. -- for a memory-mapped file, the buffer will be the whole file in -- memory. fillReadBuffer sets the pointers to encompass the whole -- file, and flushWriteBuffer needs to do no I/O. A memory-mapped -- file has to maintain its own file pointer. -- for a bytestring, again the buffer should match the bytestring in -- memory. -- --------------------------------------------------------------------------- -- Low-level read/write to/from buffers -- These operations make it easy to implement an instance of 'BufferedIO' -- for an object that supports 'RawIO'. readBuf :: RawIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8) readBuf dev bbuf = do let bytes = bufferAvailable bbuf res <- withBuffer bbuf $ \ptr -> RawIO.read dev (ptr `plusPtr` bufR bbuf) bytes return (res, bbuf{ bufR = bufR bbuf + res }) -- zero indicates end of file readBufNonBlocking :: RawIO dev => dev -> Buffer Word8 -> IO (Maybe Int, -- Nothing ==> end of file -- Just n ==> n bytes were read (n>=0) Buffer Word8) readBufNonBlocking dev bbuf = do let bytes = bufferAvailable bbuf res <- withBuffer bbuf $ \ptr -> IODevice.readNonBlocking dev (ptr `plusPtr` bufR bbuf) bytes case res of Nothing -> return (Nothing, bbuf) Just n -> return (Just n, bbuf{ bufR = bufR bbuf + n }) writeBuf :: RawIO dev => dev -> Buffer Word8 -> IO (Buffer Word8) writeBuf dev bbuf = do let bytes = bufferElems bbuf withBuffer bbuf $ \ptr -> IODevice.write dev (ptr `plusPtr` bufL bbuf) bytes return bbuf{ bufL=0, bufR=0 } -- XXX ToDo writeBufNonBlocking :: RawIO dev => dev -> Buffer Word8 -> IO (Int, Buffer Word8) writeBufNonBlocking dev bbuf = do let bytes = bufferElems bbuf res <- withBuffer bbuf $ \ptr -> IODevice.writeNonBlocking dev (ptr `plusPtr` bufL bbuf) bytes return (res, bufferAdjustL (bufL bbuf + res) bbuf)
spacekitteh/smcghc
libraries/base/GHC/IO/BufferedIO.hs
bsd-3-clause
4,982
0
15
1,070
847
460
387
50
2
-- Issue overload-div-int-real #579 module Div where {-@ type Valid = {v:Bool | ( (Prop v) <=> true ) } @-} {-@ mulAssoc :: (Eq a, Fractional a) => a -> a -> a -> Valid @-} mulAssoc :: (Eq a, Fractional a) => a -> a -> a -> Bool mulAssoc x y z = (x * y) * z == x * (y * z) {-@ mulCommut :: (Eq a, Fractional a) => a -> a -> Valid @-} mulCommut :: (Eq a, Fractional a) => a -> a -> Bool mulCommut x y = x * y == y * x {-@ mulId :: (Eq a, Fractional a) => a -> Valid @-} mulId :: (Eq a, Fractional a) => a -> Bool mulId x = x == 1 * x {-@ mulDistr :: Double -> Double -> Double -> Valid @-} mulDistr :: Double -> Double -> Double -> Bool mulDistr x y z = x * (y + z) == (x * y) + (x * z) {-@ divId :: Double -> Valid @-} divId :: Double -> Bool divId x = x / 1.0 == x {-@ inverse :: {v:Double | v != 0.0} -> Valid @-} inverse :: Double -> Bool inverse x = 1.0 == x * (1.0 / x)
ssaavedra/liquidhaskell
tests/pos/RealProps1.hs
bsd-3-clause
888
0
9
230
291
158
133
13
1
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-} {-# OPTIONS_GHC -fcontext-stack47 #-} module Games.Chaos2010.Database.Piece_sprite where import Games.Chaos2010.Database.Fields import Database.HaskellDB.DBLayout type Piece_sprite = Record (HCons (LVPair X (Expr (Maybe Int))) (HCons (LVPair Y (Expr (Maybe Int))) (HCons (LVPair Ptype (Expr (Maybe String))) (HCons (LVPair Sprite (Expr (Maybe String))) (HCons (LVPair Colour (Expr (Maybe String))) (HCons (LVPair Tag (Expr (Maybe Int))) (HCons (LVPair Allegiance (Expr (Maybe String))) HNil))))))) piece_sprite :: Table Piece_sprite piece_sprite = baseTable "piece_sprite"
JakeWheat/Chaos-2010
Games/Chaos2010/Database/Piece_sprite.hs
bsd-3-clause
748
0
25
192
244
128
116
16
1
-- | Augmented grammars. {-# LANGUAGE ScopedTypeVariables #-} module Data.Cfg.Augment ( -- * Augmenting grammars augmentCfg, -- * Augmenting symbols AugNT(..), AugT(..), -- * Type synonyms AugV, AugVs, AugProduction, AugFreeCfg ) where import Data.Cfg.Cfg(Cfg(..), Production, V(..), Vs) import Data.Cfg.FreeCfg(FreeCfg(..)) import qualified Data.Set as S -- | Nonterminal symbols augmented with a special 'StartSymbol' data AugNT nt = StartSymbol | AugNT nt deriving (Eq, Ord, Show) -- | Terminal symbols augmented with a special end-of-file symbol data AugT t = EOF | AugT t deriving (Eq, Ord, Show) -- | A convenience synonym for an augmented vocabulary symbol type AugV t nt = V (AugT t) (AugNT nt) -- | A convenience synonym for augmented vocabulary symbols type AugVs t nt = Vs (AugT t) (AugNT nt) -- | A convenience synonym for augmented productions type AugProduction t nt = Production (AugT t) (AugNT nt) -- | A convenience symbol for an augmented grammar type AugFreeCfg t nt = FreeCfg (AugT t) (AugNT nt) -- | Returns the /augmented/ grammar: a grammar for the same language -- but using explicit start and end-of-file symbols. augmentCfg :: forall cfg t nt . (Cfg cfg t nt, Ord nt, Ord t) => cfg t nt -> FreeCfg (AugT t) (AugNT nt) augmentCfg cfg = FreeCfg { nonterminals' = S.insert StartSymbol $ S.map AugNT $ nonterminals cfg, terminals' = S.insert EOF $ S.map AugT $ terminals cfg, productionRules' = pr, startSymbol' = StartSymbol } where pr :: AugNT nt -> S.Set (Vs (AugT t) (AugNT nt)) pr StartSymbol = S.singleton [NT $ AugNT $ startSymbol cfg, T EOF] pr (AugNT nt) = S.map augmentVs oldRhss where oldRhss :: S.Set (Vs t nt) oldRhss = productionRules cfg nt augmentVs :: Vs t nt -> Vs (AugT t) (AugNT nt) augmentVs = map augmentV augmentV :: V t nt -> V (AugT t) (AugNT nt) augmentV (NT nt') = NT $ AugNT nt' augmentV (T t') = T $ AugT t'
nedervold/context-free-grammar
src/Data/Cfg/Augment.hs
bsd-3-clause
2,033
0
12
499
632
348
284
37
3
-------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.DrawElementsBaseVertex -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.DrawElementsBaseVertex ( -- * Extension Support glGetARBDrawElementsBaseVertex, gl_ARB_draw_elements_base_vertex, -- * Functions glDrawElementsBaseVertex, glDrawElementsInstancedBaseVertex, glDrawRangeElementsBaseVertex, glMultiDrawElementsBaseVertex ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/DrawElementsBaseVertex.hs
bsd-3-clause
762
0
4
95
53
40
13
9
0
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, FunctionalDependencies, TypeSynonymInstances, UndecidableInstances #-} --{-# OPTIONS_GHC -ddump-splices #-} module Scratch where import Prelude hiding ((.)) import Data.Time.Calendar import Data.RecordAccess import Data.RecordAccess.TH $(record [d| data Person = Person { name :: String , dob :: Day } deriving Show |]) $(record [d| data Company = Company { name :: String , number :: String } deriving Show |]) $(subrecord [d| data Named = Named { name :: String } |]) printName :: (Named f) => f -> IO () printName = putStrLn . name bozo = Person "Bozo The Clown" (fromGregorian 1971 01 10) acme = Company "Acme Inc" "12345678" main = do printName bozo printName acme
petermarks/record-access
src/Scratch.hs
bsd-3-clause
797
0
8
184
155
87
68
26
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} import Text.LaTeX import Text.LaTeX.Base.Parser import Text.LaTeX.Base.Pretty import Text.LaTeX.Base.Syntax import Data.Text (unlines, pack, unpack) import qualified Data.Text as DT import qualified Data.Text.IO as T import System.Environment (getArgs) import System.Console.Docopt.NoTH import Control.Monad (when) import Usage (progUsage) _sp :: Int -> String _sp n = foldl1 (++) spaces where spaces = replicate n (" ") _er :: String -> String _er [] = "" _er (x:s) | (x == '\n') = '\n' : (_er s) | otherwise = ' ' : (_er s) _eraseTex :: LaTeX -> String _eraseTex p = _er ((unpack . render) p) _eraseEnvProlog :: String -> String _eraseEnvProlog s = (_er "\\begin{") ++ (_er s) ++ (_er "}") _eraseEnvEpilog :: String -> String _eraseEnvEpilog s = (_er "\\end{") ++ (_er s) ++ (_er "}") _eraseSimpleCommand :: String -> String -> String _eraseSimpleCommand name content = (_er "\\") ++ (_er name) ++ (_er "{") ++ content ++ (_er "}") removeTilde :: Char -> Char removeTilde '~' = ' ' removeTilde s = s detex :: LaTeX -> String detex (TeXSeq l1 l2) = (detex l1) ++ (detex l2) detex (TeXRaw t) = (unpack (DT.map removeTilde t)) detex p@(TeXComm "emph" [FixArg (TeXRaw content)]) = _eraseSimpleCommand "emph" (unpack content) detex p@(TeXComm "texttt" [FixArg (TeXRaw content)]) = _eraseSimpleCommand "texttt" (unpack content) detex p@(TeXComm "textit" [FixArg (TeXRaw content)]) = _eraseSimpleCommand "textit" (unpack content) detex p@(TeXComm "textbf" [FixArg (TeXRaw content)]) = _eraseSimpleCommand "textbf" (unpack content) detex p@(TeXComm _ _) = (_eraseTex p) detex p@(TeXComment _) = (_eraseTex p) detex p@(TeXEnv "thebibliography" args content) = (_eraseTex p) detex p@(TeXEnv "document" args content) = (_eraseEnvProlog "document") ++ (detex content) ++ (_eraseEnvEpilog "document") detex p@(TeXEnv "abstract" args content) = (_eraseEnvProlog "abstract") ++ (detex content) ++ (_eraseEnvEpilog "abstract") detex p@(TeXEnv "letter" args content) = (_eraseEnvProlog "letter") ++ (detex content) ++ (_eraseEnvEpilog "letter") detex p@(TeXEnv "reviewer" args content) = (_eraseEnvProlog "reviewer") ++ (detex content) ++ (_eraseEnvEpilog "reviewer") detex p@(TeXEnv "revcomment" args content) = (_eraseEnvProlog "revcomment") ++ (detex content) ++ (_eraseEnvEpilog "revcomment") detex p@(TeXEnv "aecomment" args content) = (_eraseEnvProlog "aecomment") ++ (detex content) ++ (_eraseEnvEpilog "aecomment") detex p@(TeXEnv _ _ _) = (_eraseTex p) detex p = (_eraseTex p) _rArg :: String -> Docopt -> Arguments -> (IO String) _rArg name doc opts = getArgOrExitWith doc opts (argument name) _lOpt :: String -> Arguments -> Bool _lOpt name opts = (isPresent opts (longOption name)) printAST :: String -> IO () printAST name = do example <- readFile name case parseLaTeX (pack example) of Left err -> print err Right l -> do (print l) detexFile :: String -> IO () detexFile name = do example <- readFile name case parseLaTeX (pack example) of Left err -> print err Right l -> do putStrLn (detex l) dispatchOptions :: Docopt -> Arguments -> IO () dispatchOptions doc opts = let options = (_lOpt "version" opts, _lOpt "help" opts, _lOpt "ast" opts) parseOptions = do case options of (True,_,_) -> putStrLn "V1.0" (_,_,True) -> do file <- _rArg "FILE" doc opts printAST file (_,True,_) -> exitWithUsage doc _ -> do file <- _rArg "FILE" doc opts detexFile file in parseOptions main :: IO () main = do opts <- parseArgsOrExit progUsage =<< getArgs dispatchOptions progUsage opts
vzaccaria/huntex
app/Main.hs
bsd-3-clause
3,874
0
17
870
1,509
770
739
102
4
-- Rect.hs {-# OPTIONS_GHC -Wall #-} module Lab2.Rect( Rect(..) , HRect(..) , CanIntersect(..) , fromRect , getMbr , getMbrs , intersect ) where import Lab2.Config(hilbertDim) import Lab2.HilbertCurve(xy2d) data HRect = HRect Int Rect deriving Show data Rect = Rect { rectMinX :: Int , rectMaxX :: Int , rectMinY :: Int , rectMaxY :: Int } instance Show Rect where show rect = "Rect("++ show (rectMinX rect)++","++ show (rectMaxX rect)++","++ show (rectMinY rect)++","++ show (rectMaxY rect)++")" -- calculate hiblert value of rect and return both as hrect fromRect :: Rect -> HRect fromRect rect = HRect (xy2d hilbertDim (hx, hy)) rect where hx = rectMinX rect + ((rectMaxX rect - rectMinX rect) `div` 2) hy = rectMinY rect + ((rectMaxY rect - rectMinY rect) `div` 2) -- find the minimum bounding box of two rectangles getMbr :: Rect -> Rect -> Rect getMbr a b = Rect { rectMinX = min (rectMinX a) (rectMinX b) , rectMinY = min (rectMinY a) (rectMinY b) , rectMaxX = max (rectMaxX a) (rectMaxX b) , rectMaxY = max (rectMaxY a) (rectMaxY b) } -- find the minimum bounding box of a list of rectangles getMbrs :: [Rect] -> Rect getMbrs [] = error "can't getMbrs on empty list" getMbrs [r] = r getMbrs (x:xs) = getMbr x (getMbrs xs) -- things which can intersect each other class CanIntersect a where mbr :: a -> Rect instance CanIntersect Rect where mbr x = x instance CanIntersect HRect where mbr (HRect _ r) = r -- return true if two rectangles intersect intersect :: (CanIntersect a, CanIntersect b) => a -> b -> Bool intersect a b = xIntersect && yIntersect where xIntersect = aMaxX > bMinX && bMaxX > aMinX yIntersect = aMaxY > bMinY && bMaxY > aMinY Rect { rectMinX = aMinX, rectMaxX = aMaxX, rectMinY = aMinY, rectMaxY = aMaxY } = mbr a Rect { rectMinX = bMinX, rectMaxX = bMaxX, rectMinY = bMinY, rectMaxY = bMaxY } = mbr b
ghorn/cs240h-class
Lab2/Rect.hs
bsd-3-clause
2,185
0
16
686
692
377
315
46
1
{-| Module : Data.Array.BitArray Copyright : (c) Claude Heiland-Allen 2012 License : BSD3 Maintainer : claude@mathr.co.uk Stability : unstable Portability : portable Immutable unboxed packed bit arrays using bitwise operations to manipulate large chunks at a time much more quickly than individually unpacking and repacking bits would allow. -} -- almost all is implemented with runST and the ST-based implementation module Data.Array.BitArray ( BitArray() -- * IArray-like interface. , bounds , array , listArray , accumArray , (!) , indices , elems , assocs , (//) , accum , amap , ixmap -- * Constant arrays. , fill , false , true -- * Short-circuiting reductions. , or , and , isUniform -- * Aggregate operations. , fold , map , zipWith -- * Bounds-checked indexing. , (!?) -- * Unsafe. , (!!!) ) where import Prelude hiding (and, or, map, zipWith) import qualified Prelude as P import Control.Monad (forM_) import Control.Monad.ST (runST) import Data.Ix (Ix, range, inRange) import Data.Array.BitArray.Internal (BitArray) import qualified Data.Array.BitArray.ST as ST -- | The bounds of an array. {-# INLINE bounds #-} bounds :: Ix i => BitArray i -> (i, i) bounds a = runST (ST.getBounds =<< ST.unsafeThaw a) -- | Create an array from a list of (index, element) pairs. {-# INLINE array #-} array :: Ix i => (i, i) {- ^ bounds -} -> [(i, Bool)] {- ^ assocs -} -> BitArray i array bs ies = false bs // ies -- | Create an array from a list of elements. {-# INLINE listArray #-} listArray :: Ix i => (i, i) {- ^ bounds -} -> [Bool] {- ^ elems -} -> BitArray i listArray bs es = runST (ST.unsafeFreeze =<< ST.newListArray bs es) -- | Create an array by accumulating a list of (index, operand) pairs -- from a default seed with an operation. {-# INLINE accumArray #-} accumArray :: Ix i => (Bool -> a -> Bool) {- ^ operation -} -> Bool {- ^ default -} -> (i, i) {- ^ bounds -} -> [(i, a)] {- ^ assocs -} -> BitArray i accumArray f d bs = accum f (fill bs d) -- | Bit array indexing. {-# INLINE (!) #-} (!) :: Ix i => BitArray i -> i -> Bool a ! i = runST (do a' <- ST.unsafeThaw a ST.readArray a' i) -- | Bit array indexing without bounds checking. Unsafe. {-# INLINE (!!!) #-} (!!!) :: Ix i => BitArray i -> i -> Bool a !!! i = runST (do a' <- ST.unsafeThaw a ST.unsafeReadArray a' i) -- | A list of all the valid indices for this array. {-# INLINE indices #-} indices :: Ix i => BitArray i -> [i] indices = range . bounds -- | A list of the elements in this array. {-# INLINE elems #-} elems :: Ix i => BitArray i -> [Bool] elems a = runST (ST.unsafeGetElems =<< ST.unsafeThaw a) -- P.map (a !!!) (indices a) -- very slow! -- | A list of the (index, element) pairs in this array. {-# INLINE assocs #-} assocs :: Ix i => BitArray i -> [(i, Bool)] assocs ba = P.map (\i -> (i, ba ! i)) (indices ba) -- | A new array with updated values at the supplied indices. {-# INLINE (//) #-} (//) :: Ix i => BitArray i -> [(i, Bool)] {- ^ new assocs -} -> BitArray i ba // ies = accum (\_ a -> a) ba ies -- | Accumulate with an operation and a list of (index, operand). {-# INLINE accum #-} accum :: Ix i => (Bool -> a -> Bool) {- ^ operation -} -> BitArray i {- ^ source -} -> [(i, a)] {- ^ assocs -} -> BitArray i accum f a ies = runST (do a' <- ST.thaw a forM_ ies $ \(i, x) -> do b <- ST.readArray a' i ST.writeArray a' i (f b x) ST.unsafeFreeze a') -- | Alias for 'map'. {-# INLINE amap #-} amap :: Ix i => (Bool -> Bool) -> BitArray i -> BitArray i amap = map -- | Create a new array by mapping indices into a source array.. {-# INLINE ixmap #-} ixmap :: (Ix i, Ix j) => (i, i) {- ^ new bounds -} -> (i -> j) {- ^ index transformation -} -> BitArray j {- ^ source array -} -> BitArray i ixmap bs h ba = array bs (P.map (\i -> (i, ba ! h i)) (range bs)) -- | A uniform array of bits. {-# INLINE fill #-} fill :: Ix i => (i, i) {- ^ bounds -} -> Bool -> BitArray i fill bs b = runST (ST.unsafeFreeze =<< ST.newArray bs b) -- | A uniform array of 'False'. {-# INLINE false #-} false :: Ix i => (i, i) {- ^ bounds -} -> BitArray i false bs = fill bs False -- | A uniform array of 'True'. {-# INLINE true #-} true :: Ix i => (i, i) {- ^ bounds -} -> BitArray i true bs = fill bs True -- | Bounds checking combined with array indexing. {-# INLINE (!?) #-} (!?) :: Ix i => BitArray i -> i -> Maybe Bool b !? i | inRange (bounds b) i = Just (b ! i) | otherwise = Nothing -- | Short-circuit bitwise reduction: True if any bit is True. {-# INLINE or #-} or :: Ix i => BitArray i -> Bool or a = runST (ST.or =<< ST.unsafeThaw a) -- | Short-circuit bitwise reduction: False if any bit is False. {-# INLINE and #-} and :: Ix i => BitArray i -> Bool and a = runST (ST.and =<< ST.unsafeThaw a) -- | Short-circuit bitwise reduction: Nothing if any bits differ. {-# INLINE isUniform #-} isUniform :: Ix i => BitArray i -> Maybe Bool isUniform a = runST (ST.isUniform =<< ST.unsafeThaw a) -- | Bitwise reduction with an associative commutative boolean operator. -- Implementation lifts from 'Bool' to 'Bits' and folds large chunks -- at a time. Each bit is used as a source exactly once. {-# INLINE fold #-} fold :: Ix i => (Bool -> Bool -> Bool) -> BitArray i -> Maybe Bool fold f a = runST (ST.fold f =<< ST.unsafeThaw a) -- | Bitwise map. Implementation lifts from 'Bool' to 'Bits' and maps -- large chunks at a time. {-# INLINE map #-} map :: Ix i => (Bool -> Bool) -> BitArray i -> BitArray i map f a = runST (ST.unsafeFreeze =<< ST.map f =<< ST.unsafeThaw a) -- | Bitwise zipWith. Implementation lifts from 'Bool' to 'Bits' and -- combines large chunks at a time. -- -- The bounds of the source arrays must be identical. {-# INLINE zipWith #-} zipWith :: Ix i => (Bool -> Bool -> Bool) -> BitArray i -> BitArray i -> BitArray i zipWith f a b | bounds a == bounds b = runST (do a' <- ST.unsafeThaw a b' <- ST.unsafeThaw b ST.unsafeFreeze =<< ST.zipWith f a' b') | otherwise = error "zipWith bounds mismatch"
ekmett/bitwise
src/Data/Array/BitArray.hs
bsd-3-clause
6,068
0
15
1,363
1,739
930
809
-1
-1
{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses, FlexibleInstances #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Hooks.UrgencyHook -- Description : Configure an action to occur when a window demands your attention. -- Copyright : Devin Mullins <me@twifkak.com> -- License : BSD3-style (see LICENSE) -- -- Maintainer : Devin Mullins <me@twifkak.com> -- Stability : unstable -- Portability : unportable -- -- UrgencyHook lets you configure an action to occur when a window demands -- your attention. (In traditional WMs, this takes the form of \"flashing\" -- on your \"taskbar.\" Blech.) -- ----------------------------------------------------------------------------- module XMonad.Hooks.UrgencyHook ( -- * Usage -- $usage -- ** Pop up a temporary dzen -- $temporary -- ** Highlight in existing dzen -- $existing -- ** Useful keybinding -- $keybinding -- * Troubleshooting -- $troubleshooting -- * Example: Setting up irssi + rxvt-unicode -- $example -- ** Configuring irssi -- $irssi -- ** Configuring screen -- $screen -- ** Configuring rxvt-unicode -- $urxvt -- ** Configuring xmonad -- $xmonad -- * Stuff for your config file: withUrgencyHook, withUrgencyHookC, UrgencyConfig(..), urgencyConfig, SuppressWhen(..), RemindWhen(..), focusUrgent, clearUrgents, dzenUrgencyHook, DzenUrgencyHook(..), NoUrgencyHook(..), BorderUrgencyHook(..), FocusHook(..), filterUrgencyHook, filterUrgencyHook', minutes, seconds, askUrgent, doAskUrgent, -- * Stuff for developers: readUrgents, withUrgents, clearUrgents', StdoutUrgencyHook(..), SpawnUrgencyHook(..), UrgencyHook(urgencyHook), Interval, borderUrgencyHook, focusHook, spawnUrgencyHook, stdoutUrgencyHook ) where import XMonad import XMonad.Prelude (fi, delete, fromMaybe, listToMaybe, maybeToList, when, (\\)) import qualified XMonad.StackSet as W import XMonad.Hooks.ManageHelpers (windowTag) import XMonad.Util.Dzen (dzenWithArgs, seconds) import qualified XMonad.Util.ExtensibleState as XS import XMonad.Util.NamedWindows (getName) import XMonad.Util.Timer (TimerId, startTimer, handleTimer) import XMonad.Util.WindowProperties (getProp32) import Data.Bits (testBit) import qualified Data.Set as S import System.IO (hPutStrLn, stderr) import Foreign.C.Types (CLong) -- $usage -- -- To wire this up, first add: -- -- > import XMonad.Hooks.UrgencyHook -- -- to your import list in your config file. Now, you have a decision to make: -- When a window deems itself urgent, do you want to pop up a temporary dzen -- bar telling you so, or do you have an existing dzen wherein you would like to -- highlight urgent workspaces? -- $temporary -- -- Enable your urgency hook by wrapping your config record in a call to -- 'withUrgencyHook'. For example: -- -- > main = xmonad $ withUrgencyHook dzenUrgencyHook { args = ["-bg", "darkgreen", "-xs", "1"] } -- > $ def -- -- This will pop up a dzen bar for five seconds telling you you've got an -- urgent window. -- $existing -- -- In order for xmonad to track urgent windows, you must install an urgency hook. -- You can use the above 'dzenUrgencyHook', or if you're not interested in the -- extra popup, install NoUrgencyHook, as so: -- -- > main = xmonad $ withUrgencyHook NoUrgencyHook -- > $ def -- -- Now, your "XMonad.Hooks.StatusBar.PP" must be set up to display the urgent -- windows. If you're using the 'dzen' (from "XMonad.Hooks.DynamicLog") or -- 'dzenPP' functions from that module, then you should be good. Otherwise, -- you want to figure out how to set 'ppUrgent'. -- $keybinding -- -- You can set up a keybinding to jump to the window that was recently marked -- urgent. See an example at 'focusUrgent'. -- $troubleshooting -- -- There are three steps to get right: -- -- 1. The X client must set the UrgencyHint flag. How to configure this -- depends on the application. If you're using a terminal app, this is in -- two parts: -- -- * The console app must send a ^G (bell). In bash, a helpful trick is -- @sleep 1; echo -e \'\\a\'@. -- -- * The terminal must convert the bell into UrgencyHint. -- -- 2. XMonad must be configured to notice UrgencyHints. If you've added -- withUrgencyHook, you may need to hit mod-shift-space to reset the layout. -- -- 3. The dzen must run when told. Run @dzen2 -help@ and make sure that it -- supports all of the arguments you told DzenUrgencyHook to pass it. Also, -- set up a keybinding to the 'dzen' action in "XMonad.Util.Dzen" to test -- if that works. -- -- As best you can, try to isolate which one(s) of those is failing. -- $example -- -- This is a commonly asked example. By default, the window doesn't get flagged -- urgent when somebody messages you in irssi. You will have to configure some -- things. If you're using different tools than this, your mileage will almost -- certainly vary. (For example, in Xchat2, it's just a simple checkbox.) -- $irssi -- @Irssi@ is not an X11 app, so it can't set the @UrgencyHint@ flag on @XWMHints@. -- However, on all console applications is bestown the greatest of all notification -- systems: the bell. That's right, Ctrl+G, ASCII code 7, @echo -e '\a'@, your -- friend, the bell. To configure @irssi@ to send a bell when you receive a message: -- -- > /set beep_msg_level MSGS NOTICES INVITES DCC DCCMSGS HILIGHT -- -- Consult your local @irssi@ documentation for more detail. -- $screen -- A common way to run @irssi@ is within the lovable giant, @screen@. Some distros -- (e.g. Ubuntu) like to configure @screen@ to trample on your poor console -- applications -- in particular, to turn bell characters into evil, smelly -- \"visual bells.\" To turn this off, add: -- -- > vbell off # or remove the existing 'vbell on' line -- -- to your .screenrc, or hit @C-a C-g@ within a running @screen@ session for an -- immediate but temporary fix. -- $urxvt -- Rubber, meet road. Urxvt is the gateway between console apps and X11. To tell -- urxvt to set an @UrgencyHint@ when it receives a bell character, first, have -- an urxvt version 8.3 or newer, and second, set the following in your -- @.Xdefaults@: -- -- > urxvt.urgentOnBell: true -- -- Depending on your setup, you may need to @xrdb@ that. -- $xmonad -- Hopefully you already read the section on how to configure xmonad. If not, -- hopefully you know where to find it. -- | This is the method to enable an urgency hook. It uses the default -- 'urgencyConfig' to control behavior. To change this, use 'withUrgencyHookC' -- instead. withUrgencyHook :: (LayoutClass l Window, UrgencyHook h) => h -> XConfig l -> XConfig l withUrgencyHook hook = withUrgencyHookC hook urgencyConfig -- | This lets you modify the defaults set in 'urgencyConfig'. An example: -- -- > withUrgencyHookC dzenUrgencyHook { ... } urgencyConfig { suppressWhen = Focused } -- -- (Don't type the @...@, you dolt.) See 'UrgencyConfig' for details on configuration. withUrgencyHookC :: (LayoutClass l Window, UrgencyHook h) => h -> UrgencyConfig -> XConfig l -> XConfig l withUrgencyHookC hook urgConf conf = conf { handleEventHook = \e -> handleEvent (WithUrgencyHook hook urgConf) e >> handleEventHook conf e, logHook = cleanupUrgents (suppressWhen urgConf) >> logHook conf, startupHook = cleanupStaleUrgents >> startupHook conf } newtype Urgents = Urgents { fromUrgents :: [Window] } deriving (Read,Show) onUrgents :: ([Window] -> [Window]) -> Urgents -> Urgents onUrgents f = Urgents . f . fromUrgents instance ExtensionClass Urgents where initialValue = Urgents [] extensionType = PersistentExtension -- | Global configuration, applied to all types of 'UrgencyHook'. See -- 'urgencyConfig' for the defaults. data UrgencyConfig = UrgencyConfig { suppressWhen :: SuppressWhen -- ^ when to trigger the urgency hook , remindWhen :: RemindWhen -- ^ when to re-trigger the urgency hook } deriving (Read, Show) -- | A set of choices as to /when/ you should (or rather, shouldn't) be notified of an urgent window. -- The default is 'Visible'. Prefix each of the following with \"don't bug me when\": data SuppressWhen = Visible -- ^ the window is currently visible | OnScreen -- ^ the window is on the currently focused physical screen | Focused -- ^ the window is currently focused | Never -- ^ ... aww, heck, go ahead and bug me, just in case. deriving (Read, Show) -- | A set of choices as to when you want to be re-notified of an urgent -- window. Perhaps you focused on something and you miss the dzen popup bar. Or -- you're AFK. Or you feel the need to be more distracted. I don't care. -- -- The interval arguments are in seconds. See the 'minutes' helper. data RemindWhen = Dont -- ^ triggering once is enough | Repeatedly Int Interval -- ^ repeat <arg1> times every <arg2> seconds | Every Interval -- ^ repeat every <arg1> until the urgency hint is cleared deriving (Read, Show) -- | A prettified way of multiplying by 60. Use like: @(5 `minutes`)@. minutes :: Rational -> Rational minutes secs = secs * 60 -- | The default 'UrgencyConfig'. suppressWhen = Visible, remindWhen = Dont. -- Use a variation of this in your config just as you use a variation of -- 'def' for your xmonad definition. urgencyConfig :: UrgencyConfig urgencyConfig = UrgencyConfig { suppressWhen = Visible, remindWhen = Dont } -- | Focuses the most recently urgent window. Good for what ails ya -- I mean, your keybindings. -- Example keybinding: -- -- > , ((modm , xK_BackSpace), focusUrgent) focusUrgent :: X () focusUrgent = withUrgents $ flip whenJust (windows . W.focusWindow) . listToMaybe -- | Just makes the urgents go away. -- Example keybinding: -- -- > , ((modm .|. shiftMask, xK_BackSpace), clearUrgents) clearUrgents :: X () clearUrgents = withUrgents clearUrgents' -- | X action that returns a list of currently urgent windows. You might use -- it, or 'withUrgents', in your custom logHook, to display the workspaces that -- contain urgent windows. readUrgents :: X [Window] readUrgents = XS.gets fromUrgents -- | An HOF version of 'readUrgents', for those who prefer that sort of thing. withUrgents :: ([Window] -> X a) -> X a withUrgents f = readUrgents >>= f -- | Cleanup urgency and reminders for windows that no longer exist. cleanupStaleUrgents :: X () cleanupStaleUrgents = withWindowSet $ \ws -> do adjustUrgents (filter (`W.member` ws)) adjustReminders (filter ((`W.member` ws) . window)) adjustUrgents :: ([Window] -> [Window]) -> X () adjustUrgents = XS.modify . onUrgents type Interval = Rational -- | An urgency reminder, as reified for 'RemindWhen'. -- The last value is the countdown number, for 'Repeatedly'. data Reminder = Reminder { timer :: TimerId , window :: Window , interval :: Interval , remaining :: Maybe Int } deriving (Show,Read,Eq) instance ExtensionClass [Reminder] where initialValue = [] extensionType = PersistentExtension -- | Stores the list of urgency reminders. readReminders :: X [Reminder] readReminders = XS.get adjustReminders :: ([Reminder] -> [Reminder]) -> X () adjustReminders = XS.modify data WithUrgencyHook h = WithUrgencyHook h UrgencyConfig deriving (Read, Show) -- | Change the _NET_WM_STATE property by applying a function to the list of atoms. changeNetWMState :: Display -> Window -> ([CLong] -> [CLong]) -> X () changeNetWMState dpy w f = do wmstate <- getAtom "_NET_WM_STATE" wstate <- fromMaybe [] <$> getProp32 wmstate w io $ changeProperty32 dpy w wmstate aTOM propModeReplace (f wstate) return () -- | Add an atom to the _NET_WM_STATE property. addNetWMState :: Display -> Window -> Atom -> X () addNetWMState dpy w atom = changeNetWMState dpy w (fromIntegral atom :) -- | Remove an atom from the _NET_WM_STATE property. removeNetWMState :: Display -> Window -> Atom -> X () removeNetWMState dpy w atom = changeNetWMState dpy w $ delete (fromIntegral atom) -- | Get the _NET_WM_STATE propertly as a [CLong] getNetWMState :: Window -> X [CLong] getNetWMState w = do a_wmstate <- getAtom "_NET_WM_STATE" fromMaybe [] <$> getProp32 a_wmstate w -- The Non-ICCCM Manifesto: -- Note: Some non-standard choices have been made in this implementation to -- account for the fact that things are different in a tiling window manager: -- 1. In normal window managers, windows may overlap, so clients wait for focus to -- be set before urgency is cleared. In a tiling WM, it's sufficient to be able -- see the window, since we know that means you can see it completely. -- 2. The urgentOnBell setting in rxvt-unicode sets urgency even when the window -- has focus, and won't clear until it loses and regains focus. This is stupid. -- In order to account for these quirks, we track the list of urgent windows -- ourselves, allowing us to clear urgency when a window is visible, and not to -- set urgency if a window is visible. If you have a better idea, please, let us -- know! handleEvent :: UrgencyHook h => WithUrgencyHook h -> Event -> X () handleEvent wuh event = case event of -- WM_HINTS urgency flag PropertyEvent { ev_event_type = t, ev_atom = a, ev_window = w } -> when (t == propertyNotify && a == wM_HINTS) $ withDisplay $ \dpy -> do WMHints { wmh_flags = flags } <- io $ getWMHints dpy w if testBit flags urgencyHintBit then markUrgent w else markNotUrgent w -- Window destroyed DestroyWindowEvent {ev_window = w} -> markNotUrgent w -- _NET_WM_STATE_DEMANDS_ATTENTION requested by client ClientMessageEvent {ev_event_display = dpy, ev_window = w, ev_message_type = t, ev_data = action:atoms} -> do a_wmstate <- getAtom "_NET_WM_STATE" a_da <- getAtom "_NET_WM_STATE_DEMANDS_ATTENTION" wstate <- getNetWMState w let demandsAttention = fromIntegral a_da `elem` wstate remove = 0 add = 1 toggle = 2 when (t == a_wmstate && fromIntegral a_da `elem` atoms) $ do when (action == add || (action == toggle && not demandsAttention)) $ do markUrgent w addNetWMState dpy w a_da when (action == remove || (action == toggle && demandsAttention)) $ do markNotUrgent w removeNetWMState dpy w a_da _ -> mapM_ handleReminder =<< readReminders where handleReminder reminder = handleTimer (timer reminder) event $ reminderHook wuh reminder markUrgent w = do adjustUrgents (\ws -> if w `elem` ws then ws else w : ws) callUrgencyHook wuh w userCodeDef () =<< asks (logHook . config) markNotUrgent w = do adjustUrgents (delete w) >> adjustReminders (filter $ (w /=) . window) userCodeDef () =<< asks (logHook . config) callUrgencyHook :: UrgencyHook h => WithUrgencyHook h -> Window -> X () callUrgencyHook (WithUrgencyHook hook UrgencyConfig { suppressWhen = sw, remindWhen = rw }) w = whenX (not <$> shouldSuppress sw w) $ do userCodeDef () $ urgencyHook hook w case rw of Repeatedly times int -> addReminder w int $ Just times Every int -> addReminder w int Nothing Dont -> return () addReminder :: Window -> Rational -> Maybe Int -> X () addReminder w int times = do timerId <- startTimer int let reminder = Reminder timerId w int times adjustReminders (\rs -> if w `elem` map window rs then rs else reminder : rs) reminderHook :: UrgencyHook h => WithUrgencyHook h -> Reminder -> X (Maybe a) reminderHook (WithUrgencyHook hook _) reminder = do case remaining reminder of Just x | x > 0 -> remind $ Just (x - 1) Just _ -> adjustReminders $ delete reminder Nothing -> remind Nothing return Nothing where remind remaining' = do userCode $ urgencyHook hook (window reminder) adjustReminders $ delete reminder addReminder (window reminder) (interval reminder) remaining' shouldSuppress :: SuppressWhen -> Window -> X Bool shouldSuppress sw w = elem w <$> suppressibleWindows sw cleanupUrgents :: SuppressWhen -> X () cleanupUrgents sw = clearUrgents' =<< suppressibleWindows sw -- | Clear urgency status of selected windows. clearUrgents' :: [Window] -> X () clearUrgents' ws = do a_da <- getAtom "_NET_WM_STATE_DEMANDS_ATTENTION" dpy <- withDisplay return mapM_ (\w -> removeNetWMState dpy w a_da) ws adjustUrgents (\\ ws) >> adjustReminders (filter ((`notElem` ws) . window)) suppressibleWindows :: SuppressWhen -> X [Window] suppressibleWindows Visible = gets $ S.toList . mapped suppressibleWindows OnScreen = gets $ W.index . windowset suppressibleWindows Focused = gets $ maybeToList . W.peek . windowset suppressibleWindows Never = return [] -------------------------------------------------------------------------------- -- Urgency Hooks -- | The class definition, and some pre-defined instances. class UrgencyHook h where urgencyHook :: h -> Window -> X () instance UrgencyHook (Window -> X ()) where urgencyHook = id data NoUrgencyHook = NoUrgencyHook deriving (Read, Show) instance UrgencyHook NoUrgencyHook where urgencyHook _ _ = return () -- | Your set of options for configuring a dzenUrgencyHook. data DzenUrgencyHook = DzenUrgencyHook { duration :: Int, -- ^ number of microseconds to display the dzen -- (hence, you'll probably want to use 'seconds') args :: [String] -- ^ list of extra args (as 'String's) to pass to dzen } deriving (Read, Show) instance UrgencyHook DzenUrgencyHook where urgencyHook DzenUrgencyHook { duration = d, args = a } w = do name <- getName w ws <- gets windowset whenJust (W.findTag w ws) (flash name) where flash name index = dzenWithArgs (show name ++ " requests your attention on workspace " ++ index) a d {- | A hook which will automatically send you to anything which sets the urgent flag (as opposed to printing some sort of message. You would use this as usual, eg. > withUrgencyHook FocusHook $ myconfig { ... -} focusHook :: Window -> X () focusHook = urgencyHook FocusHook data FocusHook = FocusHook deriving (Read, Show) instance UrgencyHook FocusHook where urgencyHook _ _ = focusUrgent -- | A hook that sets the border color of an urgent window. The color -- will remain until the next time the window gains or loses focus, at -- which point the standard border color from the XConfig will be applied. -- You may want to use suppressWhen = Never with this: -- -- > withUrgencyHookC BorderUrgencyHook { urgencyBorderColor = "#ff0000" } urgencyConfig { suppressWhen = Never } ... -- -- (This should be @urgentBorderColor@ but that breaks "XMonad.Layout.Decoration". -- @borderColor@ breaks anyone using 'XPConfig' from "XMonad.Prompt". We need to -- think a bit more about namespacing issues, maybe.) borderUrgencyHook :: String -> Window -> X () borderUrgencyHook = urgencyHook . BorderUrgencyHook newtype BorderUrgencyHook = BorderUrgencyHook { urgencyBorderColor :: String } deriving (Read, Show) instance UrgencyHook BorderUrgencyHook where urgencyHook BorderUrgencyHook { urgencyBorderColor = cs } w = withDisplay $ \dpy -> do c' <- io (initColor dpy cs) case c' of Just c -> setWindowBorderWithFallback dpy w cs c _ -> io $ hPutStrLn stderr $ concat ["Warning: bad urgentBorderColor " ,show cs ," in BorderUrgencyHook" ] -- | Flashes when a window requests your attention and you can't see it. -- Defaults to a duration of five seconds, and no extra args to dzen. -- See 'DzenUrgencyHook'. dzenUrgencyHook :: DzenUrgencyHook dzenUrgencyHook = DzenUrgencyHook { duration = seconds 5, args = [] } -- | Spawn a commandline thing, appending the window id to the prefix string -- you provide. (Make sure to add a space if you need it.) Do your crazy -- xcompmgr thing. spawnUrgencyHook :: String -> Window -> X () spawnUrgencyHook = urgencyHook . SpawnUrgencyHook newtype SpawnUrgencyHook = SpawnUrgencyHook String deriving (Read, Show) instance UrgencyHook SpawnUrgencyHook where urgencyHook (SpawnUrgencyHook prefix) w = spawn $ prefix ++ show w -- | For debugging purposes, really. stdoutUrgencyHook :: Window -> X () stdoutUrgencyHook = urgencyHook StdoutUrgencyHook data StdoutUrgencyHook = StdoutUrgencyHook deriving (Read, Show) instance UrgencyHook StdoutUrgencyHook where urgencyHook _ w = io $ putStrLn $ "Urgent: " ++ show w -- | urgencyhook such that windows on certain workspaces -- never get urgency set. -- -- Useful for scratchpad workspaces perhaps: -- -- > main = xmonad (withUrgencyHook (filterUrgencyHook ["NSP", "SP"]) def) filterUrgencyHook :: [WorkspaceId] -> Window -> X () filterUrgencyHook skips = filterUrgencyHook' $ maybe False (`elem` skips) <$> windowTag -- | 'filterUrgencyHook' that takes a generic 'Query' to select which windows -- should never be marked urgent. filterUrgencyHook' :: Query Bool -> Window -> X () filterUrgencyHook' q w = whenX (runQuery q w) (clearUrgents' [w]) -- | Mark the given window urgent. -- -- (The implementation is a bit hacky: send a _NET_WM_STATE ClientMessage to -- ourselves. This is so that we respect the 'SuppressWhen' of the configured -- urgency hooks. If this module if ever migrated to the ExtensibleConf -- infrastrcture, we'll then invoke markUrgent directly.) askUrgent :: Window -> X () askUrgent w = withDisplay $ \dpy -> do rw <- asks theRoot a_wmstate <- getAtom "_NET_WM_STATE" a_da <- getAtom "_NET_WM_STATE_DEMANDS_ATTENTION" let state_add = 1 let source_pager = 2 io $ allocaXEvent $ \e -> do setEventType e clientMessage setClientMessageEvent' e w a_wmstate 32 [state_add, fi a_da, 0, source_pager] sendEvent dpy rw False (substructureRedirectMask .|. substructureNotifyMask) e -- | Helper for 'ManageHook' that marks the window as urgent (unless -- suppressed, see 'SuppressWhen'). Useful in -- 'XMonad.Hooks.EwmhDesktops.setEwmhActivateHook' and also in combination -- with "XMonad.Hooks.InsertPosition", "XMonad.Hooks.Focus". doAskUrgent :: ManageHook doAskUrgent = ask >>= \w -> liftX (askUrgent w) >> mempty
xmonad/xmonad-contrib
XMonad/Hooks/UrgencyHook.hs
bsd-3-clause
24,331
0
19
6,434
3,768
2,074
1,694
248
6
module REPL.Util ( wrappedPick , string2int ) where import Data.List (intercalate) import qualified AlbanKnights as AK import Rating wrappedPick :: String -> String -> Int -> Lock -> String wrappedPick name s i l = toString name $ AK.unsafePick s (i-1) where toString name' keys = let locked = if l then " [固定]" else "\t" in "【" ++ name' ++ "】\t" ++ show i ++ locked ++ "\t" ++ intercalate " -> " keys string2int :: String -> Int string2int str = case reads str :: [(Int, String)] of [(i,_)] -> if i < 1 then 1 else i [] -> 1
sandmark/AlbanKnights
src/REPL/Util.hs
bsd-3-clause
611
0
14
180
223
121
102
17
3
-- | The data types for the UI→Haskell interface. Roughly corresponds to the -- specification in SPEC.md. module Types ( module Types , Var ) where import qualified Data.Map as M import qualified Data.Set as S import Data.Tagged import Propositions -- We might want to look into other implementation of key-value maps type Key k = Tagged k String type KMap v = M.Map (Key v) v type KSet v = S.Set (Key v) data Task = Task { tAssumptions :: [Term] , tConclusions :: [Term] } deriving Show -- This is different from the specification: -- - There, we have a list of rules with an id. -- - Here, we have a map from id to rule. -- The Logic does not worry about the order, so a map interface with efficient -- lookup is nicer. data Rule = Rule { localVars :: [Var] , freeVars :: [Var] -- Subset of the local vars! , ports :: KMap Port } deriving Show data PortType = PTAssumption | PTConclusion | PTLocalHyp (Key Port) deriving Show isPortTypeOut :: PortType -> Bool isPortTypeOut PTConclusion = True isPortTypeOut (PTLocalHyp _) = True isPortTypeOut PTAssumption = False isPortTypeIn :: PortType -> Bool isPortTypeIn PTConclusion = False isPortTypeIn (PTLocalHyp _) = False isPortTypeIn PTAssumption = True data Port = Port { portType :: PortType , portProp :: Proposition , portScopes :: [Var] } deriving Show data Context = Context { ctxtRules :: KMap Rule } deriving Show type BlockNum = Int data Block = AnnotationBlock BlockNum Proposition -- ^ A block with an annotation (no associated rule) | Block BlockNum (Key Rule) -- ^ A normal with block with a rule deriving Show data PortSpec = NoPort | AssumptionPort Int | ConclusionPort Int | BlockPort (Key Block) (Key Port) deriving (Eq, Ord, Show) data Connection = Connection { connSortKey :: Integer -- Put sort key first, for a convenient Ord instance , connFrom :: PortSpec , connTo :: PortSpec } deriving (Eq, Ord, Show) data Proof = Proof { blocks :: KMap Block , connections :: KMap Connection } deriving Show data ConnLabel = Unconnected | Ok Proposition | Mismatch Proposition Proposition | DunnoLabel Proposition Proposition deriving (Eq, Show) badLabel :: ConnLabel -> Bool badLabel (Mismatch {}) = True badLabel (DunnoLabel {}) = True badLabel (Ok {}) = False badLabel Unconnected = False data Analysis = Analysis { connectionLabels :: M.Map (Key Connection) ConnLabel , unconnectedGoals :: [PortSpec] , cycles :: [Cycle] , escapedHypotheses :: [Path] , qed :: Bool } deriving Show type Cycle = [Key Connection] type Path = [Key Connection] -- Various accessors blockNum :: Block -> BlockNum blockNum (AnnotationBlock n _) = n blockNum (Block n _) = n block2Rule :: Context -> Block -> Rule block2Rule ctxt (Block _ rule) = ctxtRules ctxt M.! rule block2Rule _ (AnnotationBlock _ prop) = annotationRule prop annotationRule :: Proposition -> Rule annotationRule prop = Rule { localVars = [] , freeVars = [] , ports = M.fromList [ (annotationPortIn, Port { portType = PTAssumption , portProp = prop , portScopes = [] }) , (annotationPortOut, Port { portType = PTConclusion , portProp = prop , portScopes = [] }) ] } annotationPortIn :: Key Port annotationPortIn = Tagged "in" annotationPortOut :: Key Port annotationPortOut = Tagged "out"
psibi/incredible
logic/Types.hs
mit
3,456
0
12
800
910
526
384
92
1
-- | This tests the new MINIMAL pragma present in GHC 7.8 module Minimal ( Foo(..) , Weird(..) , NoMins(..) , FullMin(..) , PartialMin(ccc) , EmptyMin(..) ) where class Foo a where -- | Any two of these are required... foo, bar, bat :: a -- | .. or just this fooBarBat :: (a,a,a) {-# MINIMAL (foo, bar) | (bar, bat) | (foo, bat) | fooBarBat #-} class Weird a where a,b,c,d,e,f,g :: a {-# MINIMAL ((a, b), c | (d | (e, (f | g)))) #-} class NoMins a where x,y,z :: a -- | Has a default implementation! z = x class FullMin a where aaa,bbb :: a class PartialMin a where ccc,ddd :: a class EmptyMin a where eee,fff :: a eee = fff fff = undefined
jwiegley/ghc-release
utils/haddock/html-test/src/Minimal.hs
gpl-3.0
695
0
7
184
193
126
67
27
0
{- Copyright 2015-2017 Markus Ongyerth, Stephan Guenther This file is part of Monky. Monky is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Monky is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Monky. If not, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE CPP #-} {-| Module : Monky.Utility Description : Provides utility functions Maintainer : ongy, moepi Stability : testing Portability : Linux This module provides utility functions used in monky modules -} module Monky.Utility ( readValue , readValueI , readValues , fopen , fclose , File , readLine , readContent , findLine , splitAtEvery , maybeOpenFile , sdivBound , sdivUBound , listDirectory , C.UName , getUname , getKernelVersion ) where import Data.Word (Word) import qualified Monky.CUtil as C import System.IO import System.IO.Unsafe (unsafePerformIO) import Data.List (isPrefixOf) import Data.Maybe (fromMaybe) import qualified Data.Text as T import qualified Data.Text.Read as T import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS #if MIN_VERSION_base(4,9,0) import System.Directory (listDirectory) #else import System.Directory (getDirectoryContents) listDirectory :: String -> IO [String] listDirectory = fmap (filter (not . ("." `isPrefixOf`))) . getDirectoryContents #endif class LineReadable a where hGetReadable :: Handle -> IO a instance LineReadable String where hGetReadable = hGetLine instance LineReadable ByteString where hGetReadable = BS.hGetLine class FileReadable a where hGetFile :: Handle -> IO [a] instance FileReadable String where hGetFile = readStringLines instance FileReadable ByteString where hGetFile = readBSLines -- |type alias to distinguish system functions from utility newtype File = File Handle deriving (Show, Eq) -- |Find a line in a list of Strings findLine :: Eq a => [a] -> [[a]] -> Maybe [a] findLine y (x:xs) = if y `isPrefixOf` x then Just x else findLine y xs findLine _ [] = Nothing -- |Read the first line of the file and convert it into an 'Int' readValue :: File -> IO Int readValue (File h) = do hSeek h AbsoluteSeek 0 line <- hGetReadable h let value = fmap fst $ BS.readInt line return . fromMaybe (error ("Failed to read value from file:" ++ show h)) $ value -- |Read the first line of the file and convert it into an 'Integer' readValueI :: File -> IO Integer readValueI (File h) = do hSeek h AbsoluteSeek 0 line <- hGetReadable h let value = fmap fst $ BS.readInteger line return . fromMaybe (error ("Failed to read value from file:" ++ show h)) $ value -- |Read the first line of the file and convert the words in it into 'Int's readValues :: File -> IO [Int] readValues (File h) = do hSeek h AbsoluteSeek 0 line <- hGetReadable h let value = mapM (fmap fst . BS.readInt) $ BS.words line return . fromMaybe (error ("Failed to read values from file:" ++ show h)) $ value -- |Read the first line of the file readLine :: LineReadable a => File -> IO a readLine (File h) = do hSeek h AbsoluteSeek 0 hGetReadable h -- |Read a File as String line by line readStringLines :: Handle -> IO [String] readStringLines h = do eof <- hIsEOF h if eof then return [] else do l <- hGetReadable h fmap (l:) $ readStringLines h -- |Read a File as ByteString line by line readBSLines :: Handle -> IO [ByteString] readBSLines h = fmap (BS.lines . BS.concat) $ readLines' [] where readLines' ls = do ret <- BS.hGet h 512 if ret == BS.empty then return $ reverse ls else readLines' (ret:ls) -- |Rewind the file descriptor and read the complete file as lines readContent :: FileReadable a => File -> IO [a] readContent (File h) = do hSeek h AbsoluteSeek 0 hGetFile h -- |open a file read only fopen :: String -> IO File fopen = fmap File . flip openFile ReadMode -- |Close a file opened by 'fopen' fclose :: File -> IO () fclose (File h) = hClose h -- |Split ys at every occurence of xs splitAtEvery :: String -> String -> [String] splitAtEvery s str = splitAtEvery' s str [] where splitAtEvery' _ [] zs = [zs] splitAtEvery' xs (y:ys) zs = if xs `isPrefixOf` (y:ys) then zs:splitAtEvery' xs (cut ys) [] else splitAtEvery' xs ys (zs ++ [y]) where cut = drop (length xs -1) -- |fmap fopen would give Maybe (IO File), this fixes that maybeOpenFile :: Maybe String -> IO (Maybe File) maybeOpenFile Nothing = return Nothing maybeOpenFile (Just x) = fmap Just . fopen $ x -- |0 save divide, uses maxbound for default value sdivBound :: (Integral a, Bounded a) => a -> a -> a sdivBound _ 0 = maxBound sdivBound x y = x `div` y -- |0 save divide, uses default value sdivUBound :: Integral a => a -> a -> a -> a sdivUBound _ 0 d = d sdivUBound x y _ = x `div` y infixl 7 `sdivBound`, `sdivUBound` -- This should never change while we are on the same kernel -- | Get the kernel name/version/release and so forth getUname :: C.UName getUname = unsafePerformIO C.uname -- | Get the kernel version as (major, minor) getKernelVersion :: (Word, Word) getKernelVersion = let txt = T.splitOn (T.pack ".") . C._uRelease $ getUname (Right major: Right minor:_) = fmap T.decimal txt in (fst major, fst minor)
Ongy/monky
Monky/Utility.hs
lgpl-3.0
5,832
0
14
1,273
1,473
768
705
120
3
module Handler.Book ( getBookHomeR , getChapterR , getBookImageR ) where import Import import qualified Data.Text as T import qualified Filesystem.Path.CurrentOS as F import Filesystem (isFile) import Book import qualified Data.Map as Map import Text.XML import Network.HTTP.Types (status301) import Data.IORef (readIORef) import Book.Routes import qualified Text.Blaze.Html5 as H import Text.Blaze.Html.Renderer.Utf8 (renderHtml) import qualified Text.HTML.DOM import Yesod.Form.Jquery (urlJqueryJs) getBookHomeR :: HandlerT BookSub Handler Html getBookHomeR = do bs <- getYesod let ibook = bsBook bs Book parts _ <- liftIO $ readIORef ibook toMaster <- getRouteToParent lift $ defaultLayout $ do setTitle $ bsTitle bs $(widgetFile "book") $(widgetFile "booklist") getChapterR :: Text -> HandlerT BookSub Handler Html getChapterR slug = do bs <- getYesod let ibook = bsBook bs Book parts m <- liftIO $ readIORef ibook chapter <- maybe notFound return $ Map.lookup slug m toMaster <- getRouteToParent mraw <- lookupGetParam "raw" case mraw of Nothing -> lift $ defaultLayout $ do setTitle $ mconcat [ toHtml $ chapterTitle chapter , " :: " , bsTitle bs ] getYesod >>= addScriptEither . urlJqueryJs $(widgetFile "chapter") $(widgetFile "booklist") Just raw -> return [shamlet| $doctype 5 <html> <head> <title>#{chapterTitle chapter} <body> <article>#{sohFixes raw $ chapterHtml chapter} |] where sohFixes "soh" x = mconcat $ map (toHtml . fixSOH) nodes where Document _ (Element _ _ nodes) _ = Text.HTML.DOM.parseLBS $ renderHtml $ H.div x sohFixes _ x = x fixSOH :: Node -> Node fixSOH (NodeElement (Element "code" attrs [NodeContent t])) = NodeElement $ Element "code" attrs [NodeContent $ T.intercalate "\n" $ map go $ T.splitOn "\n" t] where go = T.replace "warp 3000" "warpEnv" fixSOH (NodeElement (Element "img" attrs nodes)) = NodeElement $ Element "img" attrs' $ map fixSOH nodes where attrs' = Map.fromList $ map fix $ Map.toList attrs fix ("src", t) | "image/" `T.isPrefixOf` t = ("src", T.append "http://www.yesodweb.com/book/" t) fix x = x fixSOH (NodeElement (Element name attrs nodes)) = NodeElement $ Element name attrs $ map fixSOH nodes fixSOH n = n getBookImageR :: Text -> HandlerT BookSub Handler () getBookImageR name | name' == name'' = do bs <- getYesod let fp1 = bsRoot bs F.</> "images" F.</> name' F.<.> "png" fp2 = bsRoot bs F.</> "asciidoc" F.</> "images" F.</> name' F.<.> "png" fp <- do x <- liftIO $ isFile fp1 return $ if x then fp1 else fp2 sendFile "image/png" $ F.encodeString $ fp | otherwise = redirectWith status301 $ BookImageR $ either id id $ F.toText name' where name' = F.basename name'' name'' = F.fromText name
wolftune/yesodweb.com
Handler/Book.hs
bsd-2-clause
3,171
0
17
928
982
490
492
-1
-1
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} module Graphics.Vty.Input.Terminfo where import Graphics.Vty.Input.Events import qualified Graphics.Vty.Input.Terminfo.ANSIVT as ANSIVT import Control.Arrow import System.Console.Terminfo -- | Queries the terminal for all capability-based input sequences and -- then adds on a terminal-dependent input sequence mapping. -- -- For reference see: -- -- * http://vimdoc.sourceforge.net/htmldoc/term.html -- -- * vim74/src/term.c -- -- * http://invisible-island.net/vttest/ -- -- * http://aperiodic.net/phil/archives/Geekery/term-function-keys.html -- -- Terminfo is incomplete. The vim source implies that terminfo is also -- incorrect. Vty assumes that the internal terminfo table added to the -- system-provided terminfo table is correct. -- -- The procedure used here is: -- -- 1. Build terminfo table for all caps. Missing caps are not added. -- -- 2. Add tables for visible chars, esc, del, ctrl, and meta. -- -- 3. Add internally-defined table for given terminal type. -- -- Precedence is currently implicit in the 'compile' algorithm. classifyMapForTerm :: String -> Terminal -> ClassifyMap classifyMapForTerm termName term = concat $ capsClassifyMap term keysFromCapsTable : universalTable : termSpecificTables termName -- | The key table applicable to all terminals. -- -- Note that some of these entries are probably only applicable to -- ANSI/VT100 terminals. universalTable :: ClassifyMap universalTable = concat [visibleChars, ctrlChars, ctrlMetaChars, specialSupportKeys] capsClassifyMap :: Terminal -> [(String,Event)] -> ClassifyMap capsClassifyMap terminal table = [(x,y) | (Just x,y) <- map extractCap table] where extractCap = first (getCapability terminal . tiGetStr) -- | Tables specific to a given terminal that are not derivable from -- terminfo. -- -- Note that this adds the ANSI/VT100/VT50 tables regardless of term -- identifier. termSpecificTables :: String -> [ClassifyMap] termSpecificTables _termName = ANSIVT.classifyTable -- | Visible characters in the ISO-8859-1 and UTF-8 common set. -- -- We limit to < 0xC1. The UTF8 sequence detector will catch all values -- 0xC2 and above before this classify table is reached. visibleChars :: ClassifyMap visibleChars = [ ([x], EvKey (KChar x) []) | x <- [' ' .. toEnum 0xC1] ] -- | Non-printable characters in the ISO-8859-1 and UTF-8 common set -- translated to ctrl + char. -- -- This treats CTRL-i the same as tab. ctrlChars :: ClassifyMap ctrlChars = [ ([toEnum x],EvKey (KChar y) [MCtrl]) | (x,y) <- zip [0..31] ('@':['a'..'z']++['['..'_']) , y /= 'i' -- Resolve issue #3 where CTRL-i hides TAB. , y /= 'h' -- CTRL-h should not hide BS ] -- | Ctrl+Meta+Char ctrlMetaChars :: ClassifyMap ctrlMetaChars = map (\(s,EvKey c m) -> ('\ESC':s, EvKey c (MMeta:m))) ctrlChars -- | Esc, meta-esc, delete, meta-delete, enter, meta-enter. specialSupportKeys :: ClassifyMap specialSupportKeys = [ ("\ESC\ESC[5~",EvKey KPageUp [MMeta]) , ("\ESC\ESC[6~",EvKey KPageDown [MMeta]) -- special support for ESC , ("\ESC",EvKey KEsc []), ("\ESC\ESC",EvKey KEsc [MMeta]) -- Special support for backspace , ("\DEL",EvKey KBS []), ("\ESC\DEL",EvKey KBS [MMeta]) -- Special support for Enter , ("\ESC\^J",EvKey KEnter [MMeta]), ("\^J",EvKey KEnter []) -- explicit support for tab , ("\t", EvKey (KChar '\t') []) ] -- | A classification table directly generated from terminfo cap -- strings. These are: -- -- * ka1 - keypad up-left -- -- * ka3 - keypad up-right -- -- * kb2 - keypad center -- -- * kbs - keypad backspace -- -- * kbeg - begin -- -- * kcbt - back tab -- -- * kc1 - keypad left-down -- -- * kc3 - keypad right-down -- -- * kdch1 - delete -- -- * kcud1 - down -- -- * kend - end -- -- * kent - enter -- -- * kf0 - kf63 - function keys -- -- * khome - KHome -- -- * kich1 - insert -- -- * kcub1 - left -- -- * knp - next page (page down) -- -- * kpp - previous page (page up) -- -- * kcuf1 - right -- -- * kDC - shift delete -- -- * kEND - shift end -- -- * kHOM - shift home -- -- * kIC - shift insert -- -- * kLFT - shift left -- -- * kRIT - shift right -- -- * kcuu1 - up keysFromCapsTable :: ClassifyMap keysFromCapsTable = [ ("ka1", EvKey KUpLeft []) , ("ka3", EvKey KUpRight []) , ("kb2", EvKey KCenter []) , ("kbs", EvKey KBS []) , ("kbeg", EvKey KBegin []) , ("kcbt", EvKey KBackTab []) , ("kc1", EvKey KDownLeft []) , ("kc3", EvKey KDownRight []) , ("kdch1", EvKey KDel []) , ("kcud1", EvKey KDown []) , ("kend", EvKey KEnd []) , ("kent", EvKey KEnter []) , ("khome", EvKey KHome []) , ("kich1", EvKey KIns []) , ("kcub1", EvKey KLeft []) , ("knp", EvKey KPageDown []) , ("kpp", EvKey KPageUp []) , ("kcuf1", EvKey KRight []) , ("kDC", EvKey KDel [MShift]) , ("kEND", EvKey KEnd [MShift]) , ("kHOM", EvKey KHome [MShift]) , ("kIC", EvKey KIns [MShift]) , ("kLFT", EvKey KLeft [MShift]) , ("kRIT", EvKey KRight [MShift]) , ("kcuu1", EvKey KUp []) ] ++ functionKeyCapsTable -- | Cap names for function keys. functionKeyCapsTable :: ClassifyMap functionKeyCapsTable = flip map [0..63] $ \n -> ("kf" ++ show n, EvKey (KFun n) [])
jtdaugherty/vty
src/Graphics/Vty/Input/Terminfo.hs
bsd-3-clause
5,427
0
12
1,202
1,165
705
460
67
1
{-# LANGUAGE OverloadedStrings #-} -- | -- Copyright : Anders Claesson 2015 -- Maintainer : Anders Claesson <anders.claesson@gmail.com> -- License : BSD-3 -- -- Rational numbers extended with two elements representing a finite but -- indeterminate value and divison by zero, respectively. module HOPS.GF.Rat ( Rat (..) , maybeRational , maybeInteger , maybeInt , isRational , isInteger , isInt , factorial , binomial , choose , multinomial ) where import Data.Ratio import Data.Vector (Vector, (!)) import qualified Data.Vector as V import qualified Data.ByteString.Char8 as B import HOPS.Pretty -- | Rationals extended with two elements: data Rat -- | A known rational value. = Val {-# UNPACK #-} !Rational -- | An unknown value. | Indet -- | Division by zero. | DZ deriving (Eq, Ord, Show, Read) -- | Addition and multiplication tables: -- -- @ -- -- + | Val b | Indet | DZ -- ------+-----------+-------+---- -- Val a | Val (a+b) | Indet | DZ -- Indet | Indet | Indet | DZ -- DZ | DZ | DZ | DZ -- -- * | Val 0 | Val b | Indet | DZ -- ------+-------+-----------+-------+---- -- Val 0 | Val 0 | Val 0 | Val 0 | DZ -- Val a | Val 0 | Val (a*b) | Indet | DZ -- Indet | Val 0 | Indet | Indet | DZ -- DZ | DZ | DZ | DZ | DZ -- @ -- instance Num Rat where (Val x) + (Val y) = Val (x+y) DZ + _ = DZ _ + DZ = DZ Indet + _ = Indet _ + Indet = Indet {-# INLINE (+) #-} (Val x) - (Val y) = Val (x-y) DZ - _ = DZ _ - DZ = DZ Indet - _ = Indet _ - Indet = Indet {-# INLINE (-) #-} (Val x) * (Val y) = Val (x*y) (Val 0) * Indet = 0 (Val _) * Indet = Indet _ * DZ = DZ DZ * _ = DZ Indet * (Val 0) = 0 Indet * (Val _) = Indet Indet * Indet = Indet {-# INLINE (*) #-} negate (Val x) = Val (negate x) negate Indet = Indet negate DZ = DZ {-# INLINE negate #-} abs (Val x) = Val (abs x) abs Indet = Indet abs DZ = DZ {-# INLINE abs #-} signum (Val x) = Val (signum x) signum Indet = Indet signum DZ = DZ {-# INLINE signum #-} fromInteger i = Val (fromInteger i) {-# INLINE fromInteger #-} -- | Division table: -- -- @ -- -- / | Val 0 | Val b | Indet | DZ -- ------+-------+-----------+-------+---- -- Val 0 | DZ | Val 0 | Val 0 | DZ -- Val a | DZ | Val (a/b) | Indet | DZ -- Indet | DZ | Indet | Indet | DZ -- DZ | DZ | DZ | DZ | DZ -- @ -- instance Fractional Rat where _ / (Val 0) = DZ (Val 0) / Indet = Val 0 (Val x) / (Val y) = Val (x/y) (Val _) / Indet = Indet DZ / _ = DZ _ / DZ = DZ Indet / _ = Indet {-# INLINE (/) #-} fromRational = Val . fromRational {-# INLINE fromRational #-} instance Floating Rat where pi = Val (toRational (pi :: Double)) exp = lift exp log = lift log sin = lift sin cos = lift cos asin = lift asin acos = lift acos atan = lift atan sinh = lift sinh cosh = lift cosh asinh = lift asinh acosh = lift acosh atanh = lift atanh sqrt DZ = DZ sqrt Indet = Indet sqrt (Val r) = let p = toRational $ sqrt (fromInteger (numerator r) :: Double) q = toRational $ sqrt (fromInteger (denominator r) :: Double) in Val (p/q) instance Pretty Rat where pretty DZ = "DZ" pretty Indet = "Indet" pretty (Val r) = B.concat [pretty (numerator r), "/", pretty (denominator r)] lift :: (Double -> Double) -> Rat -> Rat lift f (Val r) = Val $ toRational $ f (fromRational r) lift _ Indet = Indet lift _ DZ = DZ {-# INLINE lift #-} -- | Is the given element a rational? isRational :: Rat -> Bool isRational (Val _) = True isRational _ = False {-# INLINE isRational #-} -- | Is the given element an Int? isInt :: Rat -> Bool isInt (Val r) | denominator r == 1 = let i = numerator r minInt = toInteger (minBound :: Int) maxInt = toInteger (maxBound :: Int) in minInt <= i && i <= maxInt isInt _ = False -- | Is the given element an Integer? isInteger :: Rat -> Bool isInteger (Val r) | denominator r == 1 = True isInteger _ = False -- | `maybeRational` of @Val x@ is @Just x@, otherwise it is `Nothing`. maybeRational :: Rat -> Maybe Rational maybeRational (Val x) = Just x maybeRational _ = Nothing -- | `maybeInteger` of @Val x@ is `Just` the numerator of @x@ if the -- denominator of @x@ is 1, otherwise it is `Nothing`. maybeInteger :: Rat -> Maybe Integer maybeInteger (Val r) | denominator r == 1 = Just (numerator r) maybeInteger _ = Nothing {-# INLINE maybeInteger #-} -- | Like `maybeInteger` but return `Nothing` when the integer is out of -- range for an `Int`. maybeInt :: Rat -> Maybe Int maybeInt x@(Val r) | isInt x = Just (fromInteger (numerator r)) maybeInt _ = Nothing {-# INLINE maybeInt #-} -- | If the given value represents a nonnegative integer, then the -- factorial of that integer is returned. If given `DZ`, return `DZ`. In -- all other cases return `Indet`. factorial :: Rat -> Rat factorial DZ = DZ factorial r = case maybeInteger r of Nothing -> Indet Just k | k < 0 -> Indet | otherwise -> Val $ toRational $ product [1 .. k] pascal :: [Vector Integer] pascal = [ V.fromList [ n `binomial` k | k <- [0 .. (n+1) `div` 2 ] ] | n <- [0..] ] binomial :: Int -> Int -> Integer n `binomial` k | n < k = 0 | k == 0 = 1 | n == k = 1 | k < n && 2*k > n = n `binomial` (n-k) | otherwise = pascal!!(n-1)!k + pascal!!(n-1)!(k-1) choose :: (Integral a, Num b) => a -> a -> b choose n k = fromInteger $ binomial (fromIntegral n) (fromIntegral k) multinomial :: (Integral b, Fractional a) => [b] -> a multinomial [] = 1 multinomial [_] = 1 multinomial [k0,k1] = (k0+k1) `choose` k0 multinomial [k0,k1,k2] = (k0+k1+k2) `choose` k0 * (k1+k2) `choose` k1 multinomial ks@(k:kt) = fromIntegral (sum ks) `choose` k * multinomial kt
akc/gfscript
HOPS/GF/Rat.hs
bsd-3-clause
6,232
0
15
1,950
1,980
1,039
941
148
2
{-# LANGUAGE Haskell98, CPP, DeriveDataTypeable, ForeignFunctionInterface, TypeSynonymInstances #-} {-# LINE 1 "dist/dist-sandbox-261cd265/build/Network/Socket/ByteString/MsgHdr.hs" #-} {-# LINE 1 "Network/Socket/ByteString/MsgHdr.hsc" #-} {-# LANGUAGE CPP #-} {-# LINE 2 "Network/Socket/ByteString/MsgHdr.hsc" #-} {-# OPTIONS_GHC -funbox-strict-fields #-} -- | Support module for the POSIX 'sendmsg' system call. module Network.Socket.ByteString.MsgHdr ( MsgHdr(..) ) where {-# LINE 10 "Network/Socket/ByteString/MsgHdr.hsc" #-} {-# LINE 11 "Network/Socket/ByteString/MsgHdr.hsc" #-} import Foreign.C.Types (CInt, CSize, CUInt) import Foreign.Ptr (Ptr) import Foreign.Storable (Storable(..)) import Network.Socket (SockAddr) import Network.Socket.Internal (zeroMemory) import Network.Socket.ByteString.IOVec (IOVec) -- We don't use msg_control, msg_controllen, and msg_flags as these -- don't exist on OpenSolaris. data MsgHdr = MsgHdr { msgName :: !(Ptr SockAddr) , msgNameLen :: !CUInt , msgIov :: !(Ptr IOVec) , msgIovLen :: !CSize } instance Storable MsgHdr where sizeOf _ = (56) {-# LINE 31 "Network/Socket/ByteString/MsgHdr.hsc" #-} alignment _ = alignment (undefined :: CInt) peek p = do name <- ((\hsc_ptr -> peekByteOff hsc_ptr 0)) p {-# LINE 35 "Network/Socket/ByteString/MsgHdr.hsc" #-} nameLen <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) p {-# LINE 36 "Network/Socket/ByteString/MsgHdr.hsc" #-} iov <- ((\hsc_ptr -> peekByteOff hsc_ptr 16)) p {-# LINE 37 "Network/Socket/ByteString/MsgHdr.hsc" #-} iovLen <- ((\hsc_ptr -> peekByteOff hsc_ptr 24)) p {-# LINE 38 "Network/Socket/ByteString/MsgHdr.hsc" #-} return $ MsgHdr name nameLen iov iovLen poke p mh = do -- We need to zero the msg_control, msg_controllen, and msg_flags -- fields, but they only exist on some platforms (e.g. not on -- Solaris). Instead of using CPP, we zero the entire struct. zeroMemory p (56) {-# LINE 45 "Network/Socket/ByteString/MsgHdr.hsc" #-} ((\hsc_ptr -> pokeByteOff hsc_ptr 0)) p (msgName mh) {-# LINE 46 "Network/Socket/ByteString/MsgHdr.hsc" #-} ((\hsc_ptr -> pokeByteOff hsc_ptr 8)) p (msgNameLen mh) {-# LINE 47 "Network/Socket/ByteString/MsgHdr.hsc" #-} ((\hsc_ptr -> pokeByteOff hsc_ptr 16)) p (msgIov mh) {-# LINE 48 "Network/Socket/ByteString/MsgHdr.hsc" #-} ((\hsc_ptr -> pokeByteOff hsc_ptr 24)) p (msgIovLen mh) {-# LINE 49 "Network/Socket/ByteString/MsgHdr.hsc" #-}
phischu/fragnix
tests/packages/scotty/Network.Socket.ByteString.MsgHdr.hs
bsd-3-clause
2,612
4
13
538
469
262
207
40
0
module Dotnet.System.Collections.DictionaryEntry where import Dotnet import qualified Dotnet.System.Object import qualified Dotnet.System.ValueType data DictionaryEntry_ a type DictionaryEntry a = Dotnet.System.ValueType.ValueType (DictionaryEntry_ a) foreign import dotnet "method System.Collections.DictionaryEntry.get_Key" get_Key :: DictionaryEntry obj -> IO (Dotnet.System.Object.Object a0) foreign import dotnet "method System.Collections.DictionaryEntry.set_Key" set_Key :: Dotnet.System.Object.Object a0 -> DictionaryEntry obj -> IO (()) foreign import dotnet "method System.Collections.DictionaryEntry.get_Value" get_Value :: DictionaryEntry obj -> IO (Dotnet.System.Object.Object a0) foreign import dotnet "method System.Collections.DictionaryEntry.set_Value" set_Value :: Dotnet.System.Object.Object a0 -> DictionaryEntry obj -> IO (())
alekar/hugs
dotnet/lib/Dotnet/System/Collections/DictionaryEntry.hs
bsd-3-clause
872
0
10
101
189
107
82
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[PatSyntax]{Abstract Haskell syntax---patterns} -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} module HsPat ( Pat(..), InPat, OutPat, LPat, HsConDetails(..), HsConPatDetails, hsConPatArgs, HsRecFields(..), HsRecField(..), LHsRecField, hsRecFields, mkPrefixConPat, mkCharLitPat, mkNilPat, isStrictHsBind, looksLazyPatBind, isStrictLPat, hsPatNeedsParens, isIrrefutableHsPat, pprParendLPat, pprConArgs ) where import {-# SOURCE #-} HsExpr (SyntaxExpr, LHsExpr, HsSplice, pprLExpr, pprSplice) -- friends: import HsBinds import HsLit import PlaceHolder ( PostTc,DataId ) import HsTypes import TcEvidence import BasicTypes -- others: import PprCore ( {- instance OutputableBndr TyVar -} ) import TysWiredIn import Var import ConLike import DataCon import TyCon import Outputable import Type import SrcLoc import FastString -- libraries: import Data.Data hiding (TyCon,Fixity) import Data.Maybe type InPat id = LPat id -- No 'Out' constructors type OutPat id = LPat id -- No 'In' constructors type LPat id = Located (Pat id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang' -- For details on above see note [Api annotations] in ApiAnnotation data Pat id = ------------ Simple patterns --------------- WildPat (PostTc id Type) -- Wild card -- The sole reason for a type on a WildPat is to -- support hsPatType :: Pat Id -> Type | VarPat id -- Variable | LazyPat (LPat id) -- Lazy pattern -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde' -- For details on above see note [Api annotations] in ApiAnnotation | AsPat (Located id) (LPat id) -- As pattern -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt' -- For details on above see note [Api annotations] in ApiAnnotation | ParPat (LPat id) -- Parenthesised pattern -- See Note [Parens in HsSyn] in HsExpr -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | BangPat (LPat id) -- Bang pattern -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang' -- For details on above see note [Api annotations] in ApiAnnotation ------------ Lists, tuples, arrays --------------- | ListPat [LPat id] -- Syntactic list (PostTc id Type) -- The type of the elements (Maybe (PostTc id Type, SyntaxExpr id)) -- For rebindable syntax -- For OverloadedLists a Just (ty,fn) gives -- overall type of the pattern, and the toList -- function to convert the scrutinee to a list value -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | TuplePat [LPat id] -- Tuple sub-patterns Boxity -- UnitPat is TuplePat [] [PostTc id Type] -- [] before typechecker, filled in afterwards -- with the types of the tuple components -- You might think that the PostTc id Type was redundant, because we can -- get the pattern type by getting the types of the sub-patterns. -- But it's essential -- data T a where -- T1 :: Int -> T Int -- f :: (T a, a) -> Int -- f (T1 x, z) = z -- When desugaring, we must generate -- f = /\a. \v::a. case v of (t::T a, w::a) -> -- case t of (T1 (x::Int)) -> -- Note the (w::a), NOT (w::Int), because we have not yet -- refined 'a' to Int. So we must know that the second component -- of the tuple is of type 'a' not Int. See selectMatchVar -- (June 14: I'm not sure this comment is right; the sub-patterns -- will be wrapped in CoPats, no?) -- ^ - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnOpen' @'('@ or @'(#'@, -- 'ApiAnnotation.AnnClose' @')'@ or @'#)'@ -- For details on above see note [Api annotations] in ApiAnnotation | PArrPat [LPat id] -- Syntactic parallel array (PostTc id Type) -- The type of the elements -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation ------------ Constructor patterns --------------- | ConPatIn (Located id) (HsConPatDetails id) | ConPatOut { pat_con :: Located ConLike, pat_arg_tys :: [Type], -- The univeral arg types, 1-1 with the universal -- tyvars of the constructor/pattern synonym -- Use (conLikeResTy pat_con pat_arg_tys) to get -- the type of the pattern pat_tvs :: [TyVar], -- Existentially bound type variables (tyvars only) pat_dicts :: [EvVar], -- Ditto *coercion variables* and *dictionaries* -- One reason for putting coercion variable here, I think, -- is to ensure their kinds are zonked pat_binds :: TcEvBinds, -- Bindings involving those dictionaries pat_args :: HsConPatDetails id, pat_wrap :: HsWrapper -- Extra wrapper to pass to the matcher } ------------ View patterns --------------- -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | ViewPat (LHsExpr id) (LPat id) (PostTc id Type) -- The overall type of the pattern -- (= the argument type of the view function) -- for hsPatType. ------------ Pattern splices --------------- -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@ -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | SplicePat (HsSplice id) -- Includes quasi-quotes ------------ Literal and n+k patterns --------------- | LitPat HsLit -- Used for *non-overloaded* literal patterns: -- Int#, Char#, Int, Char, String, etc. | NPat -- Used for all overloaded literals, -- including overloaded strings with -XOverloadedStrings (Located (HsOverLit id)) -- ALWAYS positive (Maybe (SyntaxExpr id)) -- Just (Name of 'negate') for negative -- patterns, Nothing otherwise (SyntaxExpr id) -- Equality checker, of type t->t->Bool -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVal' @'+'@ -- For details on above see note [Api annotations] in ApiAnnotation | NPlusKPat (Located id) -- n+k pattern (Located (HsOverLit id)) -- It'll always be an HsIntegral (SyntaxExpr id) -- (>=) function, of type t->t->Bool (SyntaxExpr id) -- Name of '-' (see RnEnv.lookupSyntaxName) ------------ Pattern type signatures --------------- -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | SigPatIn (LPat id) -- Pattern with a type signature (HsWithBndrs id (LHsType id)) -- Signature can bind both -- kind and type vars | SigPatOut (LPat id) -- Pattern with a type signature Type ------------ Pattern coercions (translation only) --------------- | CoPat HsWrapper -- If co :: t1 ~ t2, p :: t2, -- then (CoPat co p) :: t1 (Pat id) -- Why not LPat? Ans: existing locn will do Type -- Type of whole pattern, t1 -- During desugaring a (CoPat co pat) turns into a cast with 'co' on -- the scrutinee, followed by a match on 'pat' deriving (Typeable) deriving instance (DataId id) => Data (Pat id) -- HsConDetails is use for patterns/expressions *and* for data type declarations data HsConDetails arg rec = PrefixCon [arg] -- C p1 p2 p3 | RecCon rec -- C { x = p1, y = p2 } | InfixCon arg arg -- p1 `C` p2 deriving (Data, Typeable) type HsConPatDetails id = HsConDetails (LPat id) (HsRecFields id (LPat id)) hsConPatArgs :: HsConPatDetails id -> [LPat id] hsConPatArgs (PrefixCon ps) = ps hsConPatArgs (RecCon fs) = map (hsRecFieldArg . unLoc) (rec_flds fs) hsConPatArgs (InfixCon p1 p2) = [p1,p2] {- However HsRecFields is used only for patterns and expressions (not data type declarations) -} data HsRecFields id arg -- A bunch of record fields -- { x = 3, y = True } -- Used for both expressions and patterns = HsRecFields { rec_flds :: [LHsRecField id arg], rec_dotdot :: Maybe Int } -- Note [DotDot fields] deriving (Data, Typeable) -- Note [DotDot fields] -- ~~~~~~~~~~~~~~~~~~~~ -- The rec_dotdot field means this: -- Nothing => the normal case -- Just n => the group uses ".." notation, -- -- In the latter case: -- -- *before* renamer: rec_flds are exactly the n user-written fields -- -- *after* renamer: rec_flds includes *all* fields, with -- the first 'n' being the user-written ones -- and the remainder being 'filled in' implicitly type LHsRecField id arg = Located (HsRecField id arg) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual', -- For details on above see note [Api annotations] in ApiAnnotation data HsRecField id arg = HsRecField { hsRecFieldId :: Located id, hsRecFieldArg :: arg, -- Filled in by renamer hsRecPun :: Bool -- Note [Punning] } deriving (Data, Typeable) -- Note [Punning] -- ~~~~~~~~~~~~~~ -- If you write T { x, y = v+1 }, the HsRecFields will be -- HsRecField x x True ... -- HsRecField y (v+1) False ... -- That is, for "punned" field x is expanded (in the renamer) -- to x=x; but with a punning flag so we can detect it later -- (e.g. when pretty printing) -- -- If the original field was qualified, we un-qualify it, thus -- T { A.x } means T { A.x = x } hsRecFields :: HsRecFields id arg -> [id] hsRecFields rbinds = map (unLoc . hsRecFieldId . unLoc) (rec_flds rbinds) {- ************************************************************************ * * * Printing patterns * * ************************************************************************ -} instance (OutputableBndr name) => Outputable (Pat name) where ppr = pprPat pprPatBndr :: OutputableBndr name => name -> SDoc pprPatBndr var -- Print with type info if -dppr-debug is on = getPprStyle $ \ sty -> if debugStyle sty then parens (pprBndr LambdaBind var) -- Could pass the site to pprPat -- but is it worth it? else pprPrefixOcc var pprParendLPat :: (OutputableBndr name) => LPat name -> SDoc pprParendLPat (L _ p) = pprParendPat p pprParendPat :: (OutputableBndr name) => Pat name -> SDoc pprParendPat p | hsPatNeedsParens p = parens (pprPat p) | otherwise = pprPat p pprPat :: (OutputableBndr name) => Pat name -> SDoc pprPat (VarPat var) = pprPatBndr var pprPat (WildPat _) = char '_' pprPat (LazyPat pat) = char '~' <> pprParendLPat pat pprPat (BangPat pat) = char '!' <> pprParendLPat pat pprPat (AsPat name pat) = hcat [pprPrefixOcc (unLoc name), char '@', pprParendLPat pat] pprPat (ViewPat expr pat _) = hcat [pprLExpr expr, text " -> ", ppr pat] pprPat (ParPat pat) = parens (ppr pat) pprPat (LitPat s) = ppr s pprPat (NPat l Nothing _) = ppr l pprPat (NPat l (Just _) _) = char '-' <> ppr l pprPat (NPlusKPat n k _ _) = hcat [ppr n, char '+', ppr k] pprPat (SplicePat splice) = pprSplice splice pprPat (CoPat co pat _) = pprHsWrapper (ppr pat) co pprPat (SigPatIn pat ty) = ppr pat <+> dcolon <+> ppr ty pprPat (SigPatOut pat ty) = ppr pat <+> dcolon <+> ppr ty pprPat (ListPat pats _ _) = brackets (interpp'SP pats) pprPat (PArrPat pats _) = paBrackets (interpp'SP pats) pprPat (TuplePat pats bx _) = tupleParens (boxityTupleSort bx) (pprWithCommas ppr pats) pprPat (ConPatIn con details) = pprUserCon (unLoc con) details pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, pat_binds = binds, pat_args = details }) = getPprStyle $ \ sty -> -- Tiresome; in TcBinds.tcRhs we print out a if debugStyle sty then -- typechecked Pat in an error message, -- and we want to make sure it prints nicely ppr con <> braces (sep [ hsep (map pprPatBndr (tvs ++ dicts)) , ppr binds]) <+> pprConArgs details else pprUserCon (unLoc con) details pprUserCon :: (OutputableBndr con, OutputableBndr id) => con -> HsConPatDetails id -> SDoc pprUserCon c (InfixCon p1 p2) = ppr p1 <+> pprInfixOcc c <+> ppr p2 pprUserCon c details = pprPrefixOcc c <+> pprConArgs details pprConArgs :: OutputableBndr id => HsConPatDetails id -> SDoc pprConArgs (PrefixCon pats) = sep (map pprParendLPat pats) pprConArgs (InfixCon p1 p2) = sep [pprParendLPat p1, pprParendLPat p2] pprConArgs (RecCon rpats) = ppr rpats instance (OutputableBndr id, Outputable arg) => Outputable (HsRecFields id arg) where ppr (HsRecFields { rec_flds = flds, rec_dotdot = Nothing }) = braces (fsep (punctuate comma (map ppr flds))) ppr (HsRecFields { rec_flds = flds, rec_dotdot = Just n }) = braces (fsep (punctuate comma (map ppr (take n flds) ++ [dotdot]))) where dotdot = ptext (sLit "..") <+> ifPprDebug (ppr (drop n flds)) instance (OutputableBndr id, Outputable arg) => Outputable (HsRecField id arg) where ppr (HsRecField { hsRecFieldId = f, hsRecFieldArg = arg, hsRecPun = pun }) = ppr f <+> (ppUnless pun $ equals <+> ppr arg) {- ************************************************************************ * * * Building patterns * * ************************************************************************ -} mkPrefixConPat :: DataCon -> [OutPat id] -> [Type] -> OutPat id -- Make a vanilla Prefix constructor pattern mkPrefixConPat dc pats tys = noLoc $ ConPatOut { pat_con = noLoc (RealDataCon dc), pat_tvs = [], pat_dicts = [], pat_binds = emptyTcEvBinds, pat_args = PrefixCon pats, pat_arg_tys = tys, pat_wrap = idHsWrapper } mkNilPat :: Type -> OutPat id mkNilPat ty = mkPrefixConPat nilDataCon [] [ty] mkCharLitPat :: String -> Char -> OutPat id mkCharLitPat src c = mkPrefixConPat charDataCon [noLoc $ LitPat (HsCharPrim src c)] [] {- ************************************************************************ * * * Predicates for checking things about pattern-lists in EquationInfo * * * ************************************************************************ \subsection[Pat-list-predicates]{Look for interesting things in patterns} Unlike in the Wadler chapter, where patterns are either ``variables'' or ``constructors,'' here we distinguish between: \begin{description} \item[unfailable:] Patterns that cannot fail to match: variables, wildcards, and lazy patterns. These are the irrefutable patterns; the two other categories are refutable patterns. \item[constructor:] A non-literal constructor pattern (see next category). \item[literal patterns:] At least the numeric ones may be overloaded. \end{description} A pattern is in {\em exactly one} of the above three categories; `as' patterns are treated specially, of course. The 1.3 report defines what ``irrefutable'' and ``failure-free'' patterns are. -} isStrictLPat :: LPat id -> Bool isStrictLPat (L _ (ParPat p)) = isStrictLPat p isStrictLPat (L _ (BangPat {})) = True isStrictLPat (L _ (TuplePat _ Unboxed _)) = True isStrictLPat _ = False isStrictHsBind :: HsBind id -> Bool -- A pattern binding with an outermost bang or unboxed tuple must be matched strictly -- Defined in this module because HsPat is above HsBinds in the import graph isStrictHsBind (PatBind { pat_lhs = p }) = isStrictLPat p isStrictHsBind _ = False looksLazyPatBind :: HsBind id -> Bool -- Returns True of anything *except* -- a StrictHsBind (as above) or -- a VarPat -- In particular, returns True of a pattern binding with a compound pattern, like (I# x) looksLazyPatBind (PatBind { pat_lhs = p }) = looksLazyLPat p looksLazyPatBind _ = False looksLazyLPat :: LPat id -> Bool looksLazyLPat (L _ (ParPat p)) = looksLazyLPat p looksLazyLPat (L _ (AsPat _ p)) = looksLazyLPat p looksLazyLPat (L _ (BangPat {})) = False looksLazyLPat (L _ (TuplePat _ Unboxed _)) = False looksLazyLPat (L _ (VarPat {})) = False looksLazyLPat (L _ (WildPat {})) = False looksLazyLPat _ = True isIrrefutableHsPat :: OutputableBndr id => LPat id -> Bool -- (isIrrefutableHsPat p) is true if matching against p cannot fail, -- in the sense of falling through to the next pattern. -- (NB: this is not quite the same as the (silly) defn -- in 3.17.2 of the Haskell 98 report.) -- -- isIrrefutableHsPat returns False if it's in doubt; specifically -- on a ConPatIn it doesn't know the size of the constructor family -- But if it returns True, the pattern is definitely irrefutable isIrrefutableHsPat pat = go pat where go (L _ pat) = go1 pat go1 (WildPat {}) = True go1 (VarPat {}) = True go1 (LazyPat {}) = True go1 (BangPat pat) = go pat go1 (CoPat _ pat _) = go1 pat go1 (ParPat pat) = go pat go1 (AsPat _ pat) = go pat go1 (ViewPat _ pat _) = go pat go1 (SigPatIn pat _) = go pat go1 (SigPatOut pat _) = go pat go1 (TuplePat pats _ _) = all go pats go1 (ListPat {}) = False go1 (PArrPat {}) = False -- ? go1 (ConPatIn {}) = False -- Conservative go1 (ConPatOut{ pat_con = L _ (RealDataCon con), pat_args = details }) = isJust (tyConSingleDataCon_maybe (dataConTyCon con)) -- NB: tyConSingleDataCon_maybe, *not* isProductTyCon, because -- the latter is false of existentials. See Trac #4439 && all go (hsConPatArgs details) go1 (ConPatOut{ pat_con = L _ (PatSynCon _pat) }) = False -- Conservative go1 (LitPat {}) = False go1 (NPat {}) = False go1 (NPlusKPat {}) = False -- Both should be gotten rid of by renamer before -- isIrrefutablePat is called go1 (SplicePat {}) = urk pat urk pat = pprPanic "isIrrefutableHsPat:" (ppr pat) hsPatNeedsParens :: Pat a -> Bool hsPatNeedsParens (NPlusKPat {}) = True hsPatNeedsParens (SplicePat {}) = False hsPatNeedsParens (ConPatIn _ ds) = conPatNeedsParens ds hsPatNeedsParens p@(ConPatOut {}) = conPatNeedsParens (pat_args p) hsPatNeedsParens (SigPatIn {}) = True hsPatNeedsParens (SigPatOut {}) = True hsPatNeedsParens (ViewPat {}) = True hsPatNeedsParens (CoPat {}) = True hsPatNeedsParens (WildPat {}) = False hsPatNeedsParens (VarPat {}) = False hsPatNeedsParens (LazyPat {}) = False hsPatNeedsParens (BangPat {}) = False hsPatNeedsParens (ParPat {}) = False hsPatNeedsParens (AsPat {}) = False hsPatNeedsParens (TuplePat {}) = False hsPatNeedsParens (ListPat {}) = False hsPatNeedsParens (PArrPat {}) = False hsPatNeedsParens (LitPat {}) = False hsPatNeedsParens (NPat {}) = False conPatNeedsParens :: HsConDetails a b -> Bool conPatNeedsParens (PrefixCon args) = not (null args) conPatNeedsParens (InfixCon {}) = True conPatNeedsParens (RecCon {}) = True
fmthoma/ghc
compiler/hsSyn/HsPat.hs
bsd-3-clause
21,886
0
18
6,828
3,875
2,111
1,764
249
20
module System.Uname ( getRelease ) where getRelease :: IO String getRelease = error "getRelease not supported on Windows"
juhp/stack
src/windows/System/Uname.hs
bsd-3-clause
127
0
5
23
27
15
12
4
1
<?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="sr-CS"> <title>SAML Support</title> <maps> <homeID>saml</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/saml/src/main/javahelp/help_sr_CS/helpset_sr_CS.hs
apache-2.0
958
77
66
156
407
206
201
-1
-1
{-# LANGUAGE OverloadedStrings, CPP #-} #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif -- | -- Module : Data.Text.Lazy.Read -- Copyright : (c) 2010, 2011 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : GHC -- -- Functions used frequently when reading textual data. module Data.Text.Lazy.Read ( Reader , decimal , hexadecimal , signed , rational , double ) where import Control.Monad (liftM) import Data.Char (isDigit, isHexDigit) import Data.Int (Int8, Int16, Int32, Int64) import Data.Ratio ((%)) import Data.Text.Internal.Read import Data.Text.Lazy as T import Data.Word (Word, Word8, Word16, Word32, Word64) -- | Read some text. If the read succeeds, return its value and the -- remaining text, otherwise an error message. type Reader a = IReader Text a type Parser = IParser Text -- | Read a decimal integer. The input must begin with at least one -- decimal digit, and is consumed until a non-digit or end of string -- is reached. -- -- This function does not handle leading sign characters. If you need -- to handle signed input, use @'signed' 'decimal'@. -- -- /Note/: For fixed-width integer types, this function does not -- attempt to detect overflow, so a sufficiently long input may give -- incorrect results. If you are worried about overflow, use -- 'Integer' for your result type. decimal :: Integral a => Reader a {-# SPECIALIZE decimal :: Reader Int #-} {-# SPECIALIZE decimal :: Reader Int8 #-} {-# SPECIALIZE decimal :: Reader Int16 #-} {-# SPECIALIZE decimal :: Reader Int32 #-} {-# SPECIALIZE decimal :: Reader Int64 #-} {-# SPECIALIZE decimal :: Reader Integer #-} {-# SPECIALIZE decimal :: Reader Word #-} {-# SPECIALIZE decimal :: Reader Word8 #-} {-# SPECIALIZE decimal :: Reader Word16 #-} {-# SPECIALIZE decimal :: Reader Word32 #-} {-# SPECIALIZE decimal :: Reader Word64 #-} decimal txt | T.null h = Left "input does not start with a digit" | otherwise = Right (T.foldl' go 0 h, t) where (h,t) = T.span isDigit txt go n d = (n * 10 + fromIntegral (digitToInt d)) -- | Read a hexadecimal integer, consisting of an optional leading -- @\"0x\"@ followed by at least one decimal digit. Input is consumed -- until a non-hex-digit or end of string is reached. This function -- is case insensitive. -- -- This function does not handle leading sign characters. If you need -- to handle signed input, use @'signed' 'hexadecimal'@. -- -- /Note/: For fixed-width integer types, this function does not -- attempt to detect overflow, so a sufficiently long input may give -- incorrect results. If you are worried about overflow, use -- 'Integer' for your result type. hexadecimal :: Integral a => Reader a {-# SPECIALIZE hexadecimal :: Reader Int #-} {-# SPECIALIZE hexadecimal :: Reader Integer #-} hexadecimal txt | h == "0x" || h == "0X" = hex t | otherwise = hex txt where (h,t) = T.splitAt 2 txt hex :: Integral a => Reader a {-# SPECIALIZE hexadecimal :: Reader Int #-} {-# SPECIALIZE hexadecimal :: Reader Int8 #-} {-# SPECIALIZE hexadecimal :: Reader Int16 #-} {-# SPECIALIZE hexadecimal :: Reader Int32 #-} {-# SPECIALIZE hexadecimal :: Reader Int64 #-} {-# SPECIALIZE hexadecimal :: Reader Integer #-} {-# SPECIALIZE hexadecimal :: Reader Word #-} {-# SPECIALIZE hexadecimal :: Reader Word8 #-} {-# SPECIALIZE hexadecimal :: Reader Word16 #-} {-# SPECIALIZE hexadecimal :: Reader Word32 #-} {-# SPECIALIZE hexadecimal :: Reader Word64 #-} hex txt | T.null h = Left "input does not start with a hexadecimal digit" | otherwise = Right (T.foldl' go 0 h, t) where (h,t) = T.span isHexDigit txt go n d = (n * 16 + fromIntegral (hexDigitToInt d)) -- | Read an optional leading sign character (@\'-\'@ or @\'+\'@) and -- apply it to the result of applying the given reader. signed :: Num a => Reader a -> Reader a {-# INLINE signed #-} signed f = runP (signa (P f)) -- | Read a rational number. -- -- This function accepts an optional leading sign character, followed -- by at least one decimal digit. The syntax similar to that accepted -- by the 'read' function, with the exception that a trailing @\'.\'@ -- or @\'e\'@ /not/ followed by a number is not consumed. -- -- Examples: -- -- >rational "3" == Right (3.0, "") -- >rational "3.1" == Right (3.1, "") -- >rational "3e4" == Right (30000.0, "") -- >rational "3.1e4" == Right (31000.0, "") -- >rational ".3" == Left "input does not start with a digit" -- >rational "e3" == Left "input does not start with a digit" -- -- Examples of differences from 'read': -- -- >rational "3.foo" == Right (3.0, ".foo") -- >rational "3e" == Right (3.0, "e") rational :: Fractional a => Reader a {-# SPECIALIZE rational :: Reader Double #-} rational = floaty $ \real frac fracDenom -> fromRational $ real % 1 + frac % fracDenom -- | Read a rational number. -- -- The syntax accepted by this function is the same as for 'rational'. -- -- /Note/: This function is almost ten times faster than 'rational', -- but is slightly less accurate. -- -- The 'Double' type supports about 16 decimal places of accuracy. -- For 94.2% of numbers, this function and 'rational' give identical -- results, but for the remaining 5.8%, this function loses precision -- around the 15th decimal place. For 0.001% of numbers, this -- function will lose precision at the 13th or 14th decimal place. double :: Reader Double double = floaty $ \real frac fracDenom -> fromIntegral real + fromIntegral frac / fromIntegral fracDenom signa :: Num a => Parser a -> Parser a {-# SPECIALIZE signa :: Parser Int -> Parser Int #-} {-# SPECIALIZE signa :: Parser Int8 -> Parser Int8 #-} {-# SPECIALIZE signa :: Parser Int16 -> Parser Int16 #-} {-# SPECIALIZE signa :: Parser Int32 -> Parser Int32 #-} {-# SPECIALIZE signa :: Parser Int64 -> Parser Int64 #-} {-# SPECIALIZE signa :: Parser Integer -> Parser Integer #-} signa p = do sign <- perhaps '+' $ char (\c -> c == '-' || c == '+') if sign == '+' then p else negate `liftM` p char :: (Char -> Bool) -> Parser Char char p = P $ \t -> case T.uncons t of Just (c,t') | p c -> Right (c,t') _ -> Left "character does not match" floaty :: Fractional a => (Integer -> Integer -> Integer -> a) -> Reader a {-# INLINE floaty #-} floaty f = runP $ do sign <- perhaps '+' $ char (\c -> c == '-' || c == '+') real <- P decimal T fraction fracDigits <- perhaps (T 0 0) $ do _ <- char (=='.') digits <- P $ \t -> Right (fromIntegral . T.length $ T.takeWhile isDigit t, t) n <- P decimal return $ T n digits let e c = c == 'e' || c == 'E' power <- perhaps 0 (char e >> signa (P decimal) :: Parser Int) let n = if fracDigits == 0 then if power == 0 then fromIntegral real else fromIntegral real * (10 ^^ power) else if power == 0 then f real fraction (10 ^ fracDigits) else f real fraction (10 ^ fracDigits) * (10 ^^ power) return $! if sign == '+' then n else -n
beni55/text
Data/Text/Lazy/Read.hs
bsd-2-clause
7,222
0
19
1,633
1,246
682
564
106
5
module Test5 where f = \x y z -> x + y + l +j where l = 56 j = 92
kmate/HaRe
old/testing/refacSlicing/Test5.hs
bsd-3-clause
97
0
8
53
42
24
18
4
1
-- |Binary iteratee-style serialization helpers for working with ROS -- message types. This module is used by the automatically-generated -- code for ROS .msg types. module Ros.Node.BinaryIter (streamIn, getServiceResult) where import Control.Applicative import Control.Concurrent (myThreadId, killThread) import Control.Monad.IO.Class import Control.Monad.Trans.Maybe import Data.Binary.Get import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import System.IO (Handle) import Ros.Topic import Ros.Internal.RosBinary (RosBinary(get)) import Ros.Service.ServiceTypes(ServiceResponseExcept(..)) import Data.ByteString.Lazy.Char8 (unpack) import Control.Monad.Except (ExceptT(..), throwError) -- Get the specified number of bytes from a 'Handle'. Returns a -- wrapped-up 'Nothing' if the client shutdown (indicated by receiving -- a message of zero length). hGetAll :: Handle -> Int -> MaybeT IO BL.ByteString hGetAll h n = go n [] where go 0 acc = return . BL.fromChunks $ reverse acc go n' acc = do bs <- liftIO $ BS.hGet h n' case BS.length bs of 0 -> MaybeT $ return Nothing x -> go (n' - x) (bs:acc) -- |The function that does the work of streaming members of the -- 'RosBinary' class in from a 'Handle'. streamIn :: RosBinary a => Handle -> Topic IO a streamIn h = Topic go where go = do item <- runMaybeT $ do len <- runGet getInt <$> hGetAll h 4 runGet get <$> hGetAll h len case item of Nothing -> putStrLn "Publisher stopped" >> myThreadId >>= killThread >> return undefined Just item' -> return (item', Topic go) getInt :: Get Int getInt = fromIntegral <$> getWord32le -- | Get the result back from a service call (called by the service client) -- (see http://wiki.ros.org/ROS/TCPROS) getServiceResult :: RosBinary a => Handle -> ExceptT ServiceResponseExcept IO a getServiceResult h = do okByte <- runGet getWord8 <$> hGetAllET h 1 (ResponseReadExcept "Could not read okByte") case okByte of 0 -> do len <- runGet getInt <$> hGetAllET h 4 (ResponseReadExcept "Could not read length for notOk message") message <- hGetAllET h len (ResponseReadExcept "Could not read notOk message") throwError . NotOkExcept $ unpack message _ -> do len <- runGet getInt <$> hGetAllET h 4 (ResponseReadExcept "Could not read length") runGet get <$> hGetAllET h len (ResponseReadExcept "Could not read response message") hGetAllET :: Handle -> Int -> ServiceResponseExcept -> ExceptT ServiceResponseExcept IO BL.ByteString hGetAllET h n exceptMessage = do maybeData <- liftIO . runMaybeT $ hGetAll h n case maybeData of Nothing -> throwError exceptMessage Just b -> ExceptT . return $ Right b
bitemyapp/roshask
src/Ros/Node/BinaryIter.hs
bsd-3-clause
2,921
0
16
705
730
374
356
49
3
{-# LANGUAGE Safe #-} {-# LANGUAGE CPP #-} #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 700 {-# LANGUAGE GADTs #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Text.Printf -- Copyright : (c) Lennart Augustsson and Bart Massey 2013 -- License : BSD-style (see the file LICENSE in this distribution) -- -- Maintainer : Bart Massey <bart@cs.pdx.edu> -- Stability : provisional -- Portability : portable -- -- A C @printf(3)@-like formatter. This version has been -- extended by Bart Massey as per the recommendations of -- John Meacham and Simon Marlow -- \<<http://comments.gmane.org/gmane.comp.lang.haskell.libraries/4726>\> -- to support extensible formatting for new datatypes. It -- has also been extended to support almost all C -- @printf(3)@ syntax. ----------------------------------------------------------------------------- module Text.Printf( -- * Printing Functions printf, hPrintf, -- * Extending To New Types -- -- | This 'printf' can be extended to format types -- other than those provided for by default. This -- is done by instancing 'PrintfArg' and providing -- a 'formatArg' for the type. It is possible to -- provide a 'parseFormat' to process type-specific -- modifiers, but the default instance is usually -- the best choice. -- -- For example: -- -- > instance PrintfArg () where -- > formatArg x fmt | fmtChar (vFmt 'U' fmt) == 'U' = -- > formatString "()" (fmt { fmtChar = 's', fmtPrecision = Nothing }) -- > formatArg _ fmt = errorBadFormat $ fmtChar fmt -- > -- > main :: IO () -- > main = printf "[%-3.1U]\n" () -- -- prints \"@[() ]@\". Note the use of 'formatString' to -- take care of field formatting specifications in a convenient -- way. PrintfArg(..), FieldFormatter, FieldFormat(..), FormatAdjustment(..), FormatSign(..), vFmt, -- ** Handling Type-specific Modifiers -- -- | In the unlikely case that modifier characters of -- some kind are desirable for a user-provided type, -- a 'ModifierParser' can be provided to process these -- characters. The resulting modifiers will appear in -- the 'FieldFormat' for use by the type-specific formatter. ModifierParser, FormatParse(..), -- ** Standard Formatters -- -- | These formatters for standard types are provided for -- convenience in writting new type-specific formatters: -- a common pattern is to throw to 'formatString' or -- 'formatInteger' to do most of the format handling for -- a new type. formatString, formatChar, formatInt, formatInteger, formatRealFloat, -- ** Raising Errors -- -- | These functions are used internally to raise various -- errors, and are exported for use by new type-specific -- formatters. errorBadFormat, errorShortFormat, errorMissingArgument, errorBadArgument, perror, -- * Implementation Internals -- | These types are needed for implementing processing -- variable numbers of arguments to 'printf' and 'hPrintf'. -- Their implementation is intentionally not visible from -- this module. If you attempt to pass an argument of a type -- which is not an instance of the appropriate class to -- 'printf' or 'hPrintf', then the compiler will report it -- as a missing instance of 'PrintfArg'. (All 'PrintfArg' -- instances are 'PrintfType' instances.) PrintfType, HPrintfType, -- | This class is needed as a Haskell98 compatibility -- workaround for the lack of FlexibleInstances. IsChar(..) ) where import Prelude import Data.Char import Data.Int import Data.List import Data.Word import Numeric import System.IO ------------------- -- | Format a variable number of arguments with the C-style formatting string. -- The return value is either 'String' or @('IO' a)@ (which -- should be @('IO' '()')@, but Haskell's type system -- makes this hard). -- -- The format string consists of ordinary characters and -- /conversion specifications/, which specify how to format -- one of the arguments to 'printf' in the output string. A -- format specification is introduced by the @%@ character; -- this character can be self-escaped into the format string -- using @%%@. A format specification ends with a /format -- character/ that provides the primary information about -- how to format the value. The rest of the conversion -- specification is optional. In order, one may have flag -- characters, a width specifier, a precision specifier, and -- type-specific modifier characters. -- -- Unlike C @printf(3)@, the formatting of this 'printf' -- is driven by the argument type; formatting is type specific. The -- types formatted by 'printf' \"out of the box\" are: -- -- * 'Integral' types, including 'Char' -- -- * 'String' -- -- * 'RealFloat' types -- -- 'printf' is also extensible to support other types: see below. -- -- A conversion specification begins with the -- character @%@, followed by zero or more of the following flags: -- -- > - left adjust (default is right adjust) -- > + always use a sign (+ or -) for signed conversions -- > space leading space for positive numbers in signed conversions -- > 0 pad with zeros rather than spaces -- > # use an \"alternate form\": see below -- -- When both flags are given, @-@ overrides @0@ and @+@ overrides space. -- A negative width specifier in a @*@ conversion is treated as -- positive but implies the left adjust flag. -- -- The \"alternate form\" for unsigned radix conversions is -- as in C @printf(3)@: -- -- > %o prefix with a leading 0 if needed -- > %x prefix with a leading 0x if nonzero -- > %X prefix with a leading 0X if nonzero -- > %b prefix with a leading 0b if nonzero -- > %[eEfFgG] ensure that the number contains a decimal point -- -- Any flags are followed optionally by a field width: -- -- > num field width -- > * as num, but taken from argument list -- -- The field width is a minimum, not a maximum: it will be -- expanded as needed to avoid mutilating a value. -- -- Any field width is followed optionally by a precision: -- -- > .num precision -- > . same as .0 -- > .* as num, but taken from argument list -- -- Negative precision is taken as 0. The meaning of the -- precision depends on the conversion type. -- -- > Integral minimum number of digits to show -- > RealFloat number of digits after the decimal point -- > String maximum number of characters -- -- The precision for Integral types is accomplished by zero-padding. -- If both precision and zero-pad are given for an Integral field, -- the zero-pad is ignored. -- -- Any precision is followed optionally for Integral types -- by a width modifier; the only use of this modifier being -- to set the implicit size of the operand for conversion of -- a negative operand to unsigned: -- -- > hh Int8 -- > h Int16 -- > l Int32 -- > ll Int64 -- > L Int64 -- -- The specification ends with a format character: -- -- > c character Integral -- > d decimal Integral -- > o octal Integral -- > x hexadecimal Integral -- > X hexadecimal Integral -- > b binary Integral -- > u unsigned decimal Integral -- > f floating point RealFloat -- > F floating point RealFloat -- > g general format float RealFloat -- > G general format float RealFloat -- > e exponent format float RealFloat -- > E exponent format float RealFloat -- > s string String -- > v default format any type -- -- The \"%v\" specifier is provided for all built-in types, -- and should be provided for user-defined type formatters -- as well. It picks a \"best\" representation for the given -- type. For the built-in types the \"%v\" specifier is -- converted as follows: -- -- > c Char -- > u other unsigned Integral -- > d other signed Integral -- > g RealFloat -- > s String -- -- Mismatch between the argument types and the format -- string, as well as any other syntactic or semantic errors -- in the format string, will cause an exception to be -- thrown at runtime. -- -- Note that the formatting for 'RealFloat' types is -- currently a bit different from that of C @printf(3)@, -- conforming instead to 'Numeric.showEFloat', -- 'Numeric.showFFloat' and 'Numeric.showGFloat' (and their -- alternate versions 'Numeric.showFFloatAlt' and -- 'Numeric.showGFloatAlt'). This is hard to fix: the fixed -- versions would format in a backward-incompatible way. -- In any case the Haskell behavior is generally more -- sensible than the C behavior. A brief summary of some -- key differences: -- -- * Haskell 'printf' never uses the default \"6-digit\" precision -- used by C printf. -- -- * Haskell 'printf' treats the \"precision\" specifier as -- indicating the number of digits after the decimal point. -- -- * Haskell 'printf' prints the exponent of e-format -- numbers without a gratuitous plus sign, and with the -- minimum possible number of digits. -- -- * Haskell 'printf' will place a zero after a decimal point when -- possible. -- -- Examples: -- -- > > printf "%d\n" (23::Int) -- > 23 -- > > printf "%s %s\n" "Hello" "World" -- > Hello World -- > > printf "%.2f\n" pi -- > 3.14 -- printf :: (PrintfType r) => String -> r printf fmts = spr fmts [] -- | Similar to 'printf', except that output is via the specified -- 'Handle'. The return type is restricted to @('IO' a)@. hPrintf :: (HPrintfType r) => Handle -> String -> r hPrintf hdl fmts = hspr hdl fmts [] -- |The 'PrintfType' class provides the variable argument magic for -- 'printf'. Its implementation is intentionally not visible from -- this module. If you attempt to pass an argument of a type which -- is not an instance of this class to 'printf' or 'hPrintf', then -- the compiler will report it as a missing instance of 'PrintfArg'. class PrintfType t where spr :: String -> [UPrintf] -> t -- | The 'HPrintfType' class provides the variable argument magic for -- 'hPrintf'. Its implementation is intentionally not visible from -- this module. class HPrintfType t where hspr :: Handle -> String -> [UPrintf] -> t {- not allowed in Haskell 2010 instance PrintfType String where spr fmt args = uprintf fmt (reverse args) -} instance (IsChar c) => PrintfType [c] where spr fmts args = map fromChar (uprintf fmts (reverse args)) -- Note that this should really be (IO ()), but GHC's -- type system won't readily let us say that without -- bringing the GADTs. So we go conditional for these defs. #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 700 instance (a ~ ()) => PrintfType (IO a) where spr fmts args = putStr $ map fromChar $ uprintf fmts $ reverse args instance (a ~ ()) => HPrintfType (IO a) where hspr hdl fmts args = do hPutStr hdl (uprintf fmts (reverse args)) #else instance PrintfType (IO a) where spr fmts args = do putStr $ map fromChar $ uprintf fmts $ reverse args return (error "PrintfType (IO a): result should not be used.") instance HPrintfType (IO a) where hspr hdl fmts args = do hPutStr hdl (uprintf fmts (reverse args)) return (error "HPrintfType (IO a): result should not be used.") #endif instance (PrintfArg a, PrintfType r) => PrintfType (a -> r) where spr fmts args = \ a -> spr fmts ((parseFormat a, formatArg a) : args) instance (PrintfArg a, HPrintfType r) => HPrintfType (a -> r) where hspr hdl fmts args = \ a -> hspr hdl fmts ((parseFormat a, formatArg a) : args) -- | Typeclass of 'printf'-formattable values. The 'formatArg' method -- takes a value and a field format descriptor and either fails due -- to a bad descriptor or produces a 'ShowS' as the result. The -- default 'parseFormat' expects no modifiers: this is the normal -- case. Minimal instance: 'formatArg'. class PrintfArg a where -- | /Since: 4.7.0.0/ formatArg :: a -> FieldFormatter -- | /Since: 4.7.0.0/ parseFormat :: a -> ModifierParser parseFormat _ (c : cs) = FormatParse "" c cs parseFormat _ "" = errorShortFormat instance PrintfArg Char where formatArg = formatChar parseFormat _ cf = parseIntFormat (undefined :: Int) cf instance (IsChar c) => PrintfArg [c] where formatArg = formatString instance PrintfArg Int where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Int8 where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Int16 where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Int32 where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Int64 where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Word where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Word8 where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Word16 where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Word32 where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Word64 where formatArg = formatInt parseFormat = parseIntFormat instance PrintfArg Integer where formatArg = formatInteger parseFormat = parseIntFormat instance PrintfArg Float where formatArg = formatRealFloat instance PrintfArg Double where formatArg = formatRealFloat -- | This class, with only the one instance, is used as -- a workaround for the fact that 'String', as a concrete -- type, is not allowable as a typeclass instance. 'IsChar' -- is exported for backward-compatibility. class IsChar c where -- | /Since: 4.7.0.0/ toChar :: c -> Char -- | /Since: 4.7.0.0/ fromChar :: Char -> c instance IsChar Char where toChar c = c fromChar c = c ------------------- -- | Whether to left-adjust or zero-pad a field. These are -- mutually exclusive, with 'LeftAdjust' taking precedence. -- -- /Since: 4.7.0.0/ data FormatAdjustment = LeftAdjust | ZeroPad -- | How to handle the sign of a numeric field. These are -- mutually exclusive, with 'SignPlus' taking precedence. -- -- /Since: 4.7.0.0/ data FormatSign = SignPlus | SignSpace -- | Description of field formatting for 'formatArg'. See UNIX `printf`(3) -- for a description of how field formatting works. -- -- /Since: 4.7.0.0/ data FieldFormat = FieldFormat { fmtWidth :: Maybe Int, -- ^ Total width of the field. fmtPrecision :: Maybe Int, -- ^ Secondary field width specifier. fmtAdjust :: Maybe FormatAdjustment, -- ^ Kind of filling or padding -- to be done. fmtSign :: Maybe FormatSign, -- ^ Whether to insist on a -- plus sign for positive -- numbers. fmtAlternate :: Bool, -- ^ Indicates an "alternate -- format". See printf(3) -- for the details, which -- vary by argument spec. fmtModifiers :: String, -- ^ Characters that appeared -- immediately to the left of -- 'fmtChar' in the format -- and were accepted by the -- type's 'parseFormat'. -- Normally the empty string. fmtChar :: Char -- ^ The format character -- 'printf' was invoked -- with. 'formatArg' should -- fail unless this character -- matches the type. It is -- normal to handle many -- different format -- characters for a single -- type. } -- | The \"format parser\" walks over argument-type-specific -- modifier characters to find the primary format character. -- This is the type of its result. -- -- /Since: 4.7.0.0/ data FormatParse = FormatParse { fpModifiers :: String, -- ^ Any modifiers found. fpChar :: Char, -- ^ Primary format character. fpRest :: String -- ^ Rest of the format string. } -- Contains the "modifier letters" that can precede an -- integer type. intModifierMap :: [(String, Integer)] intModifierMap = [ ("hh", toInteger (minBound :: Int8)), ("h", toInteger (minBound :: Int16)), ("l", toInteger (minBound :: Int32)), ("ll", toInteger (minBound :: Int64)), ("L", toInteger (minBound :: Int64)) ] parseIntFormat :: Integral a => a -> String -> FormatParse parseIntFormat _ s = case foldr matchPrefix Nothing intModifierMap of Just m -> m Nothing -> case s of c : cs -> FormatParse "" c cs "" -> errorShortFormat where matchPrefix (p, _) m@(Just (FormatParse p0 _ _)) | length p0 >= length p = m | otherwise = case getFormat p of Nothing -> m Just fp -> Just fp matchPrefix (p, _) Nothing = getFormat p getFormat p = stripPrefix p s >>= fp where fp (c : cs) = Just $ FormatParse p c cs fp "" = errorShortFormat -- | This is the type of a field formatter reified over its -- argument. -- -- /Since: 4.7.0.0/ type FieldFormatter = FieldFormat -> ShowS -- | Type of a function that will parse modifier characters -- from the format string. -- -- /Since: 4.7.0.0/ type ModifierParser = String -> FormatParse -- | Substitute a \'v\' format character with the given -- default format character in the 'FieldFormat'. A -- convenience for user-implemented types, which should -- support \"%v\". -- -- /Since: 4.7.0.0/ vFmt :: Char -> FieldFormat -> FieldFormat vFmt c ufmt@(FieldFormat {fmtChar = 'v'}) = ufmt {fmtChar = c} vFmt _ ufmt = ufmt -- | Formatter for 'Char' values. -- -- /Since: 4.7.0.0/ formatChar :: Char -> FieldFormatter formatChar x ufmt = formatIntegral (Just 0) (toInteger $ ord x) $ vFmt 'c' ufmt -- | Formatter for 'String' values. -- -- /Since: 4.7.0.0/ formatString :: IsChar a => [a] -> FieldFormatter formatString x ufmt = case fmtChar $ vFmt 's' ufmt of 's' -> map toChar . (adjust ufmt ("", ts) ++) where ts = map toChar $ trunc $ fmtPrecision ufmt where trunc Nothing = x trunc (Just n) = take n x c -> errorBadFormat c -- Possibly apply the int modifiers to get a new -- int width for conversion. fixupMods :: FieldFormat -> Maybe Integer -> Maybe Integer fixupMods ufmt m = let mods = fmtModifiers ufmt in case mods of "" -> m _ -> case lookup mods intModifierMap of Just m0 -> Just m0 Nothing -> perror "unknown format modifier" -- | Formatter for 'Int' values. -- -- /Since: 4.7.0.0/ formatInt :: (Integral a, Bounded a) => a -> FieldFormatter formatInt x ufmt = let lb = toInteger $ minBound `asTypeOf` x m = fixupMods ufmt (Just lb) ufmt' = case lb of 0 -> vFmt 'u' ufmt _ -> ufmt in formatIntegral m (toInteger x) ufmt' -- | Formatter for 'Integer' values. -- -- /Since: 4.7.0.0/ formatInteger :: Integer -> FieldFormatter formatInteger x ufmt = let m = fixupMods ufmt Nothing in formatIntegral m x ufmt -- All formatting for integral types is handled -- consistently. The only difference is between Integer and -- bounded types; this difference is handled by the 'm' -- argument containing the lower bound. formatIntegral :: Maybe Integer -> Integer -> FieldFormatter formatIntegral m x ufmt0 = let prec = fmtPrecision ufmt0 in case fmtChar ufmt of 'd' -> (adjustSigned ufmt (fmti prec x) ++) 'i' -> (adjustSigned ufmt (fmti prec x) ++) 'x' -> (adjust ufmt (fmtu 16 (alt "0x" x) prec m x) ++) 'X' -> (adjust ufmt (upcase $ fmtu 16 (alt "0X" x) prec m x) ++) 'b' -> (adjust ufmt (fmtu 2 (alt "0b" x) prec m x) ++) 'o' -> (adjust ufmt (fmtu 8 (alt "0" x) prec m x) ++) 'u' -> (adjust ufmt (fmtu 10 Nothing prec m x) ++) 'c' | x >= fromIntegral (ord (minBound :: Char)) && x <= fromIntegral (ord (maxBound :: Char)) && fmtPrecision ufmt == Nothing && fmtModifiers ufmt == "" -> formatString [chr $ fromIntegral x] (ufmt { fmtChar = 's' }) 'c' -> perror "illegal char conversion" c -> errorBadFormat c where ufmt = vFmt 'd' $ case ufmt0 of FieldFormat { fmtPrecision = Just _, fmtAdjust = Just ZeroPad } -> ufmt0 { fmtAdjust = Nothing } _ -> ufmt0 alt _ 0 = Nothing alt p _ = case fmtAlternate ufmt of True -> Just p False -> Nothing upcase (s1, s2) = (s1, map toUpper s2) -- | Formatter for 'RealFloat' values. -- -- /Since: 4.7.0.0/ formatRealFloat :: RealFloat a => a -> FieldFormatter formatRealFloat x ufmt = let c = fmtChar $ vFmt 'g' ufmt prec = fmtPrecision ufmt alt = fmtAlternate ufmt in case c of 'e' -> (adjustSigned ufmt (dfmt c prec alt x) ++) 'E' -> (adjustSigned ufmt (dfmt c prec alt x) ++) 'f' -> (adjustSigned ufmt (dfmt c prec alt x) ++) 'F' -> (adjustSigned ufmt (dfmt c prec alt x) ++) 'g' -> (adjustSigned ufmt (dfmt c prec alt x) ++) 'G' -> (adjustSigned ufmt (dfmt c prec alt x) ++) _ -> errorBadFormat c -- This is the type carried around for arguments in -- the varargs code. type UPrintf = (ModifierParser, FieldFormatter) -- Given a format string and a list of formatting functions -- (the actual argument value having already been baked into -- each of these functions before delivery), return the -- actual formatted text string. uprintf :: String -> [UPrintf] -> String uprintf s us = uprintfs s us "" -- This function does the actual work, producing a ShowS -- instead of a string, for future expansion and for -- misguided efficiency. uprintfs :: String -> [UPrintf] -> ShowS uprintfs "" [] = id uprintfs "" (_:_) = errorShortFormat uprintfs ('%':'%':cs) us = ('%' :) . uprintfs cs us uprintfs ('%':_) [] = errorMissingArgument uprintfs ('%':cs) us@(_:_) = fmt cs us uprintfs (c:cs) us = (c :) . uprintfs cs us -- Given a suffix of the format string starting just after -- the percent sign, and the list of remaining unprocessed -- arguments in the form described above, format the portion -- of the output described by this field description, and -- then continue with 'uprintfs'. fmt :: String -> [UPrintf] -> ShowS fmt cs0 us0 = case getSpecs False False Nothing False cs0 us0 of (_, _, []) -> errorMissingArgument (ufmt, cs, (_, u) : us) -> u ufmt . uprintfs cs us -- Given field formatting information, and a tuple -- consisting of a prefix (for example, a minus sign) that -- is supposed to go before the argument value and a string -- representing the value, return the properly padded and -- formatted result. adjust :: FieldFormat -> (String, String) -> String adjust ufmt (pre, str) = let naturalWidth = length pre + length str zero = case fmtAdjust ufmt of Just ZeroPad -> True _ -> False left = case fmtAdjust ufmt of Just LeftAdjust -> True _ -> False fill = case fmtWidth ufmt of Just width | naturalWidth < width -> let fillchar = if zero then '0' else ' ' in replicate (width - naturalWidth) fillchar _ -> "" in if left then pre ++ str ++ fill else if zero then pre ++ fill ++ str else fill ++ pre ++ str -- For positive numbers with an explicit sign field ("+" or -- " "), adjust accordingly. adjustSigned :: FieldFormat -> (String, String) -> String adjustSigned ufmt@(FieldFormat {fmtSign = Just SignPlus}) ("", str) = adjust ufmt ("+", str) adjustSigned ufmt@(FieldFormat {fmtSign = Just SignSpace}) ("", str) = adjust ufmt (" ", str) adjustSigned ufmt ps = adjust ufmt ps -- Format a signed integer in the "default" fashion. -- This will be subjected to adjust subsequently. fmti :: Maybe Int -> Integer -> (String, String) fmti prec i | i < 0 = ("-", integral_prec prec (show (-i))) | otherwise = ("", integral_prec prec (show i)) -- Format an unsigned integer in the "default" fashion. -- This will be subjected to adjust subsequently. The 'b' -- argument is the base, the 'pre' argument is the prefix, -- and the '(Just m)' argument is the implicit lower-bound -- size of the operand for conversion from signed to -- unsigned. Thus, this function will refuse to convert an -- unbounded negative integer to an unsigned string. fmtu :: Integer -> Maybe String -> Maybe Int -> Maybe Integer -> Integer -> (String, String) fmtu b (Just pre) prec m i = let ("", s) = fmtu b Nothing prec m i in case pre of "0" -> case s of '0' : _ -> ("", s) _ -> (pre, s) _ -> (pre, s) fmtu b Nothing prec0 m0 i0 = case fmtu' prec0 m0 i0 of Just s -> ("", s) Nothing -> errorBadArgument where fmtu' :: Maybe Int -> Maybe Integer -> Integer -> Maybe String fmtu' prec (Just m) i | i < 0 = fmtu' prec Nothing (-2 * m + i) fmtu' (Just prec) _ i | i >= 0 = fmap (integral_prec (Just prec)) $ fmtu' Nothing Nothing i fmtu' Nothing _ i | i >= 0 = Just $ showIntAtBase b intToDigit i "" fmtu' _ _ _ = Nothing -- This is used by 'fmtu' and 'fmti' to zero-pad an -- int-string to a required precision. integral_prec :: Maybe Int -> String -> String integral_prec Nothing integral = integral integral_prec (Just 0) "0" = "" integral_prec (Just prec) integral = replicate (prec - length integral) '0' ++ integral stoi :: String -> (Int, String) stoi cs = let (as, cs') = span isDigit cs in case as of "" -> (0, cs') _ -> (read as, cs') -- Figure out the FormatAdjustment, given: -- width, precision, left-adjust, zero-fill adjustment :: Maybe Int -> Maybe a -> Bool -> Bool -> Maybe FormatAdjustment adjustment w p l z = case w of Just n | n < 0 -> adjl p True z _ -> adjl p l z where adjl _ True _ = Just LeftAdjust adjl _ False True = Just ZeroPad adjl _ _ _ = Nothing -- Parse the various format controls to get a format specification. getSpecs :: Bool -> Bool -> Maybe FormatSign -> Bool -> String -> [UPrintf] -> (FieldFormat, String, [UPrintf]) getSpecs _ z s a ('-' : cs0) us = getSpecs True z s a cs0 us getSpecs l z _ a ('+' : cs0) us = getSpecs l z (Just SignPlus) a cs0 us getSpecs l z s a (' ' : cs0) us = getSpecs l z ss a cs0 us where ss = case s of Just SignPlus -> Just SignPlus _ -> Just SignSpace getSpecs l _ s a ('0' : cs0) us = getSpecs l True s a cs0 us getSpecs l z s _ ('#' : cs0) us = getSpecs l z s True cs0 us getSpecs l z s a ('*' : cs0) us = let (us', n) = getStar us ((p, cs''), us'') = case cs0 of '.':'*':r -> let (us''', p') = getStar us' in ((Just p', r), us''') '.':r -> let (p', r') = stoi r in ((Just p', r'), us') _ -> ((Nothing, cs0), us') FormatParse ms c cs = case us'' of (ufmt, _) : _ -> ufmt cs'' [] -> errorMissingArgument in (FieldFormat { fmtWidth = Just (abs n), fmtPrecision = p, fmtAdjust = adjustment (Just n) p l z, fmtSign = s, fmtAlternate = a, fmtModifiers = ms, fmtChar = c}, cs, us'') getSpecs l z s a ('.' : cs0) us = let ((p, cs'), us') = case cs0 of '*':cs'' -> let (us'', p') = getStar us in ((p', cs''), us'') _ -> (stoi cs0, us) FormatParse ms c cs = case us' of (ufmt, _) : _ -> ufmt cs' [] -> errorMissingArgument in (FieldFormat { fmtWidth = Nothing, fmtPrecision = Just p, fmtAdjust = adjustment Nothing (Just p) l z, fmtSign = s, fmtAlternate = a, fmtModifiers = ms, fmtChar = c}, cs, us') getSpecs l z s a cs0@(c0 : _) us | isDigit c0 = let (n, cs') = stoi cs0 ((p, cs''), us') = case cs' of '.' : '*' : r -> let (us'', p') = getStar us in ((Just p', r), us'') '.' : r -> let (p', r') = stoi r in ((Just p', r'), us) _ -> ((Nothing, cs'), us) FormatParse ms c cs = case us' of (ufmt, _) : _ -> ufmt cs'' [] -> errorMissingArgument in (FieldFormat { fmtWidth = Just (abs n), fmtPrecision = p, fmtAdjust = adjustment (Just n) p l z, fmtSign = s, fmtAlternate = a, fmtModifiers = ms, fmtChar = c}, cs, us') getSpecs l z s a cs0@(_ : _) us = let FormatParse ms c cs = case us of (ufmt, _) : _ -> ufmt cs0 [] -> errorMissingArgument in (FieldFormat { fmtWidth = Nothing, fmtPrecision = Nothing, fmtAdjust = adjustment Nothing Nothing l z, fmtSign = s, fmtAlternate = a, fmtModifiers = ms, fmtChar = c}, cs, us) getSpecs _ _ _ _ "" _ = errorShortFormat -- Process a star argument in a format specification. getStar :: [UPrintf] -> ([UPrintf], Int) getStar us = let ufmt = FieldFormat { fmtWidth = Nothing, fmtPrecision = Nothing, fmtAdjust = Nothing, fmtSign = Nothing, fmtAlternate = False, fmtModifiers = "", fmtChar = 'd' } in case us of [] -> errorMissingArgument (_, nu) : us' -> (us', read (nu ufmt "")) -- Format a RealFloat value. dfmt :: (RealFloat a) => Char -> Maybe Int -> Bool -> a -> (String, String) dfmt c p a d = let caseConvert = if isUpper c then map toUpper else id showFunction = case toLower c of 'e' -> showEFloat 'f' -> if a then showFFloatAlt else showFFloat 'g' -> if a then showGFloatAlt else showGFloat _ -> perror "internal error: impossible dfmt" result = caseConvert $ showFunction p d "" in case result of '-' : cs -> ("-", cs) cs -> ("" , cs) -- | Raises an 'error' with a printf-specific prefix on the -- message string. -- -- /Since: 4.7.0.0/ perror :: String -> a perror s = error $ "printf: " ++ s -- | Calls 'perror' to indicate an unknown format letter for -- a given type. -- -- /Since: 4.7.0.0/ errorBadFormat :: Char -> a errorBadFormat c = perror $ "bad formatting char " ++ show c errorShortFormat, errorMissingArgument, errorBadArgument :: a -- | Calls 'perror' to indicate that the format string ended -- early. -- -- /Since: 4.7.0.0/ errorShortFormat = perror "formatting string ended prematurely" -- | Calls 'perror' to indicate that there is a missing -- argument in the argument list. -- -- /Since: 4.7.0.0/ errorMissingArgument = perror "argument list ended prematurely" -- | Calls 'perror' to indicate that there is a type -- error or similar in the given argument. -- -- /Since: 4.7.0.0/ errorBadArgument = perror "bad argument"
frantisekfarka/ghc-dsi
libraries/base/Text/Printf.hs
bsd-3-clause
31,174
0
23
8,107
6,146
3,419
2,727
420
13
{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes, TypeFamilies, MultiParamTypeClasses, ViewPatterns #-} module YesodCoreTest.Reps (specs, Widget) where import Yesod.Core import Test.Hspec import Network.Wai import Network.Wai.Test import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.String (IsString) import Data.Text (Text) import Data.Maybe (fromJust) import Data.Monoid (Endo (..)) import qualified Control.Monad.Trans.Writer as Writer import qualified Data.Set as Set data App = App mkYesod "App" [parseRoutes| / HomeR GET !home /json JsonR GET /parent/#Int ParentR: /#Text/child ChildR !child |] instance Yesod App specialHtml :: IsString a => a specialHtml = "text/html; charset=special" getHomeR :: Handler TypedContent getHomeR = selectRep $ do rep typeHtml "HTML" rep specialHtml "HTMLSPECIAL" rep typeXml "XML" rep typeJson "JSON" rep :: Monad m => ContentType -> Text -> Writer.Writer (Data.Monoid.Endo [ProvidedRep m]) () rep ct t = provideRepType ct $ return (t :: Text) getJsonR :: Handler TypedContent getJsonR = selectRep $ do rep typeHtml "HTML" provideRep $ return $ object ["message" .= ("Invalid Login" :: Text)] handleChildR :: Int -> Text -> Handler () handleChildR _ _ = return () testRequest :: Int -- ^ http status code -> Request -> ByteString -- ^ expected body -> Spec testRequest status req expected = it (S8.unpack $ fromJust $ lookup "Accept" $ requestHeaders req) $ do app <- toWaiApp App flip runSession app $ do sres <- request req assertStatus status sres assertBody expected sres test :: String -- ^ accept header -> ByteString -- ^ expected body -> Spec test accept expected = testRequest 200 (acceptRequest accept) expected acceptRequest :: String -> Request acceptRequest accept = defaultRequest { requestHeaders = [("Accept", S8.pack accept)] } specs :: Spec specs = do describe "selectRep" $ do test "application/json" "JSON" test (S8.unpack typeJson) "JSON" test "text/xml" "XML" test (S8.unpack typeXml) "XML" test "text/xml,application/json" "XML" test "text/xml;q=0.9,application/json;q=1.0" "JSON" test (S8.unpack typeHtml) "HTML" test "text/html" "HTML" test specialHtml "HTMLSPECIAL" testRequest 200 (acceptRequest "application/json") { pathInfo = ["json"] } "{\"message\":\"Invalid Login\"}" testRequest 406 (acceptRequest "text/foo") "no match found for accept header" test "text/*" "HTML" test "*/*" "HTML" describe "routeAttrs" $ do it "HomeR" $ routeAttrs HomeR `shouldBe` Set.singleton "home" it "JsonR" $ routeAttrs JsonR `shouldBe` Set.empty it "ChildR" $ routeAttrs (ParentR 5 $ ChildR "ignored") `shouldBe` Set.singleton "child"
ygale/yesod
yesod-core/test/YesodCoreTest/Reps.hs
mit
2,863
0
15
579
818
409
409
71
1
{-# LANGUAGE MagicHash, UnboxedTuples #-} import GHC.Prim import GHC.Types main = do let local = () let null = 0## :: Word# let triple = (# local, null, null #) IO (\s -> case mkWeakNoFinalizer# triple () s of (# s, r #) -> (# s, () #))
ezyang/ghc
testsuite/tests/typecheck/should_fail/T13611.hs
bsd-3-clause
254
0
14
65
102
53
49
8
1
-- !!! ds002 -- overlapping equations and guards -- -- this tests "overlapping" variables and guards module ShouldCompile where f x = x f y = y f z = z g x y z | True = f z | True = f z | True = f z g x y z | True = f z | True = f z | True = f z
urbanslug/ghc
testsuite/tests/deSugar/should_compile/ds002.hs
bsd-3-clause
269
0
7
92
121
56
65
10
1
module Main where import qualified Events import qualified Example import Data.BitVector main = do Example.main Events.main
sboosali/Haskell-DragonNaturallySpeaking
Main.hs
mit
129
0
7
21
32
19
13
7
1
{-# LANGUAGE BlockArguments #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE ViewPatterns #-} module U.Codebase.Term where import qualified Control.Monad.Writer as Writer import qualified Data.Foldable as Foldable import Data.Int (Int64) import Data.Sequence (Seq) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import Data.Word (Word64) import GHC.Generics (Generic, Generic1) import U.Codebase.Reference (Reference, Reference' (ReferenceBuiltin, ReferenceDerived)) import qualified U.Codebase.Reference as Reference import U.Codebase.Referent (Referent') import U.Codebase.Type (TypeR) import qualified U.Codebase.Type as Type import qualified U.Core.ABT as ABT import U.Util.Hash (Hash) import qualified U.Util.Hash as Hash import qualified U.Util.Hashable as H type ConstructorId = Word64 type Term v = ABT.Term (F v) v () type Type v = TypeR TypeRef v type TermRef = Reference' Text (Maybe Hash) type TypeRef = Reference type TermLink = Referent' (Reference' Text (Maybe Hash)) (Reference' Text Hash) type TypeLink = Reference -- | Base functor for terms in the Unison codebase type F vt = F' Text TermRef TypeRef TermLink TypeLink vt -- | Generalized version. We could generalize further to allow sharing within -- terms. data F' text termRef typeRef termLink typeLink vt a = Int Int64 | Nat Word64 | Float Double | Boolean Bool | Text text | Char Char | Ref termRef | -- First argument identifies the data type, -- second argument identifies the constructor Constructor typeRef ConstructorId | Request typeRef ConstructorId | Handle a a | App a a | Ann a (TypeR typeRef vt) | List (Seq a) | If a a a | And a a | Or a a | Lam a | -- Note: let rec blocks have an outer ABT.Cycle which introduces as many -- variables as there are bindings LetRec [a] a | -- Note: first parameter is the binding, second is the expression which may refer -- to this let bound variable. Constructed as `Let b (abs v e)` Let a a | -- Pattern matching / eliminating data types, example: -- case x of -- Just n -> rhs1 -- Nothing -> rhs2 -- -- translates to -- -- Match x -- [ (Constructor 0 [Var], ABT.abs n rhs1) -- , (Constructor 1 [], rhs2) ] Match a [MatchCase text typeRef a] | TermLink termLink | TypeLink typeLink deriving (Foldable, Functor, Traversable, Show) data MatchCase t r a = MatchCase (Pattern t r) (Maybe a) a deriving (Foldable, Functor, Generic, Generic1, Traversable, Show) data Pattern t r = PUnbound | PVar | PBoolean !Bool | PInt !Int64 | PNat !Word64 | PFloat !Double | PText !t | PChar !Char | PConstructor !r !Int [Pattern t r] | PAs (Pattern t r) | PEffectPure (Pattern t r) | PEffectBind !r !Int [Pattern t r] (Pattern t r) | PSequenceLiteral [Pattern t r] | PSequenceOp (Pattern t r) !SeqOp (Pattern t r) deriving (Generic, Functor, Foldable, Traversable, Show) data SeqOp = PCons | PSnoc | PConcat deriving (Eq, Show) extraMap :: forall text termRef typeRef termLink typeLink vt text' termRef' typeRef' termLink' typeLink' vt' v a. (Ord v, Ord vt') => (text -> text') -> (termRef -> termRef') -> (typeRef -> typeRef') -> (termLink -> termLink') -> (typeLink -> typeLink') -> (vt -> vt') -> ABT.Term (F' text termRef typeRef termLink typeLink vt) v a -> ABT.Term (F' text' termRef' typeRef' termLink' typeLink' vt') v a extraMap ftext ftermRef ftypeRef ftermLink ftypeLink fvt = go' where go' = ABT.transform go go :: forall x. F' text termRef typeRef termLink typeLink vt x -> F' text' termRef' typeRef' termLink' typeLink' vt' x go = \case Int i -> Int i Nat n -> Nat n Float d -> Float d Boolean b -> Boolean b Text t -> Text (ftext t) Char c -> Char c Ref r -> Ref (ftermRef r) Constructor r cid -> Constructor (ftypeRef r) cid Request r cid -> Request (ftypeRef r) cid Handle e h -> Handle e h App f a -> App f a Ann a typ -> Ann a (Type.rmap ftypeRef $ ABT.vmap fvt typ) List s -> List s If c t f -> If c t f And p q -> And p q Or p q -> Or p q Lam b -> Lam b LetRec bs b -> LetRec bs b Let a b -> Let a b Match s cs -> Match s (goCase <$> cs) TermLink r -> TermLink (ftermLink r) TypeLink r -> TypeLink (ftypeLink r) goCase :: MatchCase text typeRef x -> MatchCase text' typeRef' x goCase (MatchCase p g b) = MatchCase (goPat p) g b goPat = rmapPattern ftext ftypeRef rmapPattern :: (t -> t') -> (r -> r') -> Pattern t r -> Pattern t' r' rmapPattern ft fr = go where go = \case PUnbound -> PUnbound PVar -> PVar PBoolean b -> PBoolean b PInt i -> PInt i PNat n -> PNat n PFloat d -> PFloat d PText t -> PText (ft t) PChar c -> PChar c PConstructor r i ps -> PConstructor (fr r) i (go <$> ps) PAs p -> PAs (go p) PEffectPure p -> PEffectPure (go p) PEffectBind r i ps p -> PEffectBind (fr r) i (go <$> ps) (go p) PSequenceLiteral ps -> PSequenceLiteral (go <$> ps) PSequenceOp p1 op p2 -> PSequenceOp (go p1) op (go p2) dependencies :: (Ord termRef, Ord typeRef, Ord termLink, Ord typeLink, Ord v) => ABT.Term (F' text termRef typeRef termLink typeLink vt) v a -> (Set termRef, Set typeRef, Set termLink, Set typeLink) dependencies = Writer.execWriter . ABT.visit_ \case Ref r -> termRef r Constructor r _ -> typeRef r Request r _ -> typeRef r Match _ cases -> Foldable.for_ cases \case MatchCase pat _guard _body -> go pat where go = \case PConstructor r _i args -> typeRef r *> Foldable.traverse_ go args PAs pat -> go pat PEffectPure pat -> go pat PEffectBind r _i args k -> typeRef r *> Foldable.traverse_ go args *> go k PSequenceLiteral pats -> Foldable.traverse_ go pats PSequenceOp l _op r -> go l *> go r _ -> pure () TermLink r -> termLink r TypeLink r -> typeLink r _ -> pure () where termRef r = Writer.tell (Set.singleton r, mempty, mempty, mempty) typeRef r = Writer.tell (mempty, Set.singleton r, mempty, mempty) termLink r = Writer.tell (mempty, mempty, Set.singleton r, mempty) typeLink r = Writer.tell (mempty, mempty, mempty, Set.singleton r) -- * Instances instance H.Hashable SeqOp where tokens PCons = [H.Tag 0] tokens PSnoc = [H.Tag 1] tokens PConcat = [H.Tag 2] instance H.Hashable (Pattern Text Reference) where tokens (PUnbound) = [H.Tag 0] tokens (PVar) = [H.Tag 1] tokens (PBoolean b) = H.Tag 2 : [H.Tag $ if b then 1 else 0] tokens (PInt n) = H.Tag 3 : [H.Int n] tokens (PNat n) = H.Tag 4 : [H.Nat n] tokens (PFloat f) = H.Tag 5 : H.tokens f tokens (PConstructor r n args) = [H.Tag 6, H.accumulateToken r, H.Nat $ fromIntegral n, H.accumulateToken args] tokens (PEffectPure p) = H.Tag 7 : H.tokens p tokens (PEffectBind r n args k) = [H.Tag 8, H.accumulateToken r, H.Nat $ fromIntegral n, H.accumulateToken args, H.accumulateToken k] tokens (PAs p) = H.Tag 9 : H.tokens p tokens (PText t) = H.Tag 10 : H.tokens t tokens (PSequenceLiteral ps) = H.Tag 11 : concatMap H.tokens ps tokens (PSequenceOp l op r) = H.Tag 12 : H.tokens op ++ H.tokens l ++ H.tokens r tokens (PChar c) = H.Tag 13 : H.tokens c instance (Eq v, Show v) => H.Hashable1 (F v) where hash1 hashCycle hash e = let (tag, hashed, varint) = (H.Tag, H.Hashed, H.Nat . fromIntegral) in case e of -- So long as `Reference.Derived` ctors are created using the same -- hashing function as is used here, this case ensures that references -- are 'transparent' wrt hash and hashing is unaffected by whether -- expressions are linked. So for example `x = 1 + 1` and `y = x` hash -- the same. Ref (Reference.Derived (Just h) 0) -> H.fromBytes (Hash.toBytes h) Ref (Reference.Derived h i) -> H.accumulate [ tag 1, -- it's a term tag 1, -- it's a derived reference H.accumulateToken (Hash.toBytes <$> h), H.Nat i ] -- Note: start each layer with leading `1` byte, to avoid collisions -- with types, which start each layer with leading `0`. -- See `Hashable1 Type.F` _ -> H.accumulate $ tag 1 : -- it's a term case e of Nat n -> tag 64 : H.tokens n Int i -> tag 65 : H.tokens i Float d -> tag 66 : H.tokens d Boolean b -> tag 67 : H.tokens b Text t -> tag 68 : H.tokens t Char c -> tag 69 : H.tokens c Ref (ReferenceBuiltin name) -> [tag 2, H.accumulateToken name] Ref ReferenceDerived {} -> error "handled above, but GHC can't figure this out" App a a2 -> [tag 3, hashed (hash a), hashed (hash a2)] Ann a t -> [tag 4, hashed (hash a), hashed (ABT.hash t)] List as -> tag 5 : varint (fromIntegral (length as)) : map (hashed . hash) (Foldable.toList as) Lam a -> [tag 6, hashed (hash a)] -- note: we use `hashCycle` to ensure result is independent of -- let binding order LetRec as a -> case hashCycle as of (hs, hash) -> tag 7 : hashed (hash a) : map hashed hs -- here, order is significant, so don't use hashCycle Let b a -> [tag 8, hashed $ hash b, hashed $ hash a] If b t f -> [tag 9, hashed $ hash b, hashed $ hash t, hashed $ hash f] Request r n -> [tag 10, H.accumulateToken r, varint n] Constructor r n -> [tag 12, H.accumulateToken r, varint n] Match e branches -> tag 13 : hashed (hash e) : concatMap h branches where h (MatchCase pat guard branch) = concat [ [H.accumulateToken pat], Foldable.toList @Maybe (hashed . hash <$> guard), [hashed (hash branch)] ] Handle h b -> [tag 15, hashed $ hash h, hashed $ hash b] And x y -> [tag 16, hashed $ hash x, hashed $ hash y] Or x y -> [tag 17, hashed $ hash x, hashed $ hash y] TermLink r -> [tag 18, H.accumulateToken r] TypeLink r -> [tag 19, H.accumulateToken r]
unisonweb/platform
codebase2/codebase/U/Codebase/Term.hs
mit
11,256
0
22
3,488
3,867
1,963
1,904
-1
-1
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, DoAndIfThenElse #-} {- | Description: Generates tab completion options. This has a limited amount of context sensitivity. It distinguishes between four contexts at the moment: - import statements (completed using modules) - identifiers (completed using in scope values) - extensions via :ext (completed using GHC extensions) - qualified identifiers (completed using in-scope values) -} module IHaskell.Eval.Completion (complete, completionTarget, completionType, CompletionType(..)) where import ClassyPrelude hiding (init, last, head, liftIO) --import Prelude import Control.Applicative ((<$>)) import Data.ByteString.UTF8 hiding (drop, take) import Data.Char import Data.List (nub, init, last, head, elemIndex) import Data.List.Split import Data.List.Split.Internals import Data.Maybe import Data.String.Utils (strip, startswith, endswith, replace) import qualified Data.String.Utils as StringUtils import System.Environment (getEnv) import GHC import DynFlags import GhcMonad import PackageConfig import Outputable (showPpr) import System.Directory import System.FilePath import MonadUtils (MonadIO) import System.Console.Haskeline.Completion import IHaskell.Types import IHaskell.Eval.Evaluate (Interpreter) import IHaskell.Eval.ParseShell (parseShell) data CompletionType = Empty | Identifier String | DynFlag String | Qualified String String | ModuleName String String | HsFilePath String String | FilePath String String | KernelOption String | Extension String deriving (Show, Eq) complete :: String -> Int -> Interpreter (String, [String]) complete line pos = do flags <- getSessionDynFlags rdrNames <- map (showPpr flags) <$> getRdrNamesInScope scopeNames <- nub <$> map (showPpr flags) <$> getNamesInScope let isQualified = ('.' `elem`) unqualNames = nub $ filter (not . isQualified) rdrNames qualNames = nub $ scopeNames ++ filter isQualified rdrNames let Just db = pkgDatabase flags getNames = map moduleNameString . exposedModules moduleNames = nub $ concatMap getNames db let target = completionTarget line pos completion = completionType line pos target let matchedText = case completion of HsFilePath _ match -> match FilePath _ match -> match otherwise -> intercalate "." target options <- case completion of Empty -> return [] Identifier candidate -> return $ filter (candidate `isPrefixOf`) unqualNames Qualified moduleName candidate -> do trueName <- getTrueModuleName moduleName let prefix = intercalate "." [trueName, candidate] completions = filter (prefix `isPrefixOf`) qualNames falsifyName = replace trueName moduleName return $ map falsifyName completions ModuleName previous candidate -> do let prefix = if null previous then candidate else intercalate "." [previous, candidate] return $ filter (prefix `isPrefixOf`) moduleNames DynFlag ext -> do -- Possibly leave out the fLangFlags? The -- -XUndecidableInstances vs. obsolete -- -fallow-undecidable-instances. let extName (name, _, _) = name kernelOptNames = concatMap getSetName kernelOpts otherNames = ["-package","-Wall","-w"] fNames = map extName fFlags ++ map extName fWarningFlags ++ map extName fLangFlags fNoNames = map ("no"++) fNames fAllNames = map ("-f"++) (fNames ++ fNoNames) xNames = map extName xFlags xNoNames = map ("No" ++) xNames xAllNames = map ("-X"++) (xNames ++ xNoNames) allNames = xAllNames ++ otherNames ++ fAllNames return $ filter (ext `isPrefixOf`) allNames Extension ext -> do let extName (name, _, _) = name xNames = map extName xFlags xNoNames = map ("No" ++) xNames return $ filter (ext `isPrefixOf`) $ xNames ++ xNoNames HsFilePath lineUpToCursor match -> completePathWithExtensions [".hs", ".lhs"] lineUpToCursor FilePath lineUpToCursor match -> completePath lineUpToCursor KernelOption str -> return $ filter (str `isPrefixOf`) (concatMap getOptionName kernelOpts) return (matchedText, options) getTrueModuleName :: String -> Interpreter String getTrueModuleName name = do -- Only use the things that were actually imported let onlyImportDecl (IIDecl decl) = Just decl onlyImportDecl _ = Nothing -- Get all imports that we use. imports <- catMaybes <$> map onlyImportDecl <$> getContext -- Find the ones that have a qualified name attached. -- If this name isn't one of them, it already is the true name. flags <- getSessionDynFlags let qualifiedImports = filter (isJust . ideclAs) imports hasName imp = name == (showPpr flags . fromJust . ideclAs) imp case find hasName qualifiedImports of Nothing -> return name Just trueImp -> return $ showPpr flags $ unLoc $ ideclName trueImp -- | Get which type of completion this is from the surrounding context. completionType :: String -- ^ The line on which the completion is being done. -> Int -- ^ Location of the cursor in the line. -> [String] -- ^ The identifier being completed (pieces separated by dots). -> CompletionType completionType line loc target -- File and directory completions are special | startswith ":!" stripped = fileComplete FilePath | startswith ":l" stripped = fileComplete HsFilePath -- Complete :set, :opt, and :ext | startswith ":s" stripped = DynFlag candidate | startswith ":o" stripped = KernelOption candidate | startswith ":e" stripped = Extension candidate -- Use target for other completions. -- If it's empty, no completion. | null target = Empty -- When in a string, complete filenames. | cursorInString line loc = FilePath (getStringTarget lineUpToCursor) (getStringTarget lineUpToCursor) -- Complete module names in imports and elsewhere. | startswith "import" stripped && isModName = ModuleName dotted candidate | isModName && (not . null . init) target = Qualified dotted candidate -- Default to completing identifiers. | otherwise = Identifier candidate where stripped = strip line dotted = dots target candidate | null target = "" | otherwise = last target dots = intercalate "." . init isModName = all isCapitalized (init target) isCapitalized = isUpper . head lineUpToCursor = take loc line fileComplete filePath = case parseShell lineUpToCursor of Right xs -> filePath lineUpToCursor $ if endswith (last xs) lineUpToCursor then last xs else [] Left _ -> Empty cursorInString str loc = nquotes (take loc str) `mod` 2 /= 0 nquotes ('\\':'"':xs) = nquotes xs nquotes ('"':xs) = 1 + nquotes xs nquotes (_:xs) = nquotes xs nquotes [] = 0 -- Get the bit of a string that might be a filename completion. -- Logic is a bit convoluted, but basically go backwards from the -- end, stopping at any quote or space, unless they are escaped. getStringTarget :: String -> String getStringTarget = go "" . reverse where go acc rest = case rest of '"':'\\':rem -> go ('"':acc) rem '"':rem -> acc ' ':'\\':rem -> go (' ':acc) rem ' ':rem -> acc x:rem -> go (x:acc) rem [] -> acc -- | Get the word under a given cursor location. completionTarget :: String -> Int -> [String] completionTarget code cursor = expandCompletionPiece pieceToComplete where pieceToComplete = map fst <$> find (elem cursor . map snd) pieces pieces = splitAlongCursor $ split splitter $ zip code [1 .. ] splitter = defaultSplitter { -- Split using only the characters, which are the first elements of -- the (char, index) tuple delimiter = Delimiter [uncurry isDelim], -- Condense multiple delimiters into one and then drop them. condensePolicy = Condense, delimPolicy = Drop } isDelim :: Char -> Int -> Bool isDelim char idx = char `elem` neverIdent || isSymbol char splitAlongCursor :: [[(Char, Int)]] -> [[(Char, Int)]] splitAlongCursor [] = [] splitAlongCursor (x:xs) = case elemIndex cursor $ map snd x of Nothing -> x:splitAlongCursor xs Just idx -> take (idx + 1) x:drop (idx + 1) x:splitAlongCursor xs -- These are never part of an identifier. neverIdent :: String neverIdent = " \n\t(),{}[]\\'\"`" expandCompletionPiece Nothing = [] expandCompletionPiece (Just str) = splitOn "." str getHome :: IO String getHome = do homeEither <- try $ getEnv "HOME" :: IO (Either SomeException String) return $ case homeEither of Left _ -> "~" Right home -> home dirExpand :: String -> IO String dirExpand str = do home <- getHome return $ replace "~" home str unDirExpand :: String -> IO String unDirExpand str = do home <- getHome return $ replace home "~" str completePath :: String -> Interpreter [String] completePath line = completePathFilter acceptAll acceptAll line "" where acceptAll = const True completePathWithExtensions :: [String] -> String -> Interpreter [String] completePathWithExtensions extensions line = completePathFilter (extensionIsOneOf extensions) acceptAll line "" where acceptAll = const True extensionIsOneOf exts str = any correctEnding exts where correctEnding ext = endswith ext str completePathFilter :: (String -> Bool) -- ^ File filter: test whether to include this file. -> (String -> Bool) -- ^ Directory filter: test whether to include this directory. -> String -- ^ Line contents to the left of the cursor. -> String -- ^ Line contents to the right of the cursor. -> Interpreter [String] completePathFilter includeFile includeDirectory left right = liftIO $ do -- Get the completions from Haskeline. It has a bit of a strange API. expanded <- dirExpand left completions <- map replacement <$> snd <$> completeFilename (reverse expanded, right) -- Split up into files and directories. -- Filter out ones we don't want. areDirs <- mapM doesDirectoryExist completions let dirs = filter includeDirectory $ map fst $ filter snd $ zip completions areDirs files = filter includeFile $ map fst $ filter (not . snd) $ zip completions areDirs -- Return directories before files. However, stick everything that starts -- with a dot after everything else. If we wanted to keep original -- order, we could instead use -- filter (`elem` (dirs ++ files)) completions suggestions <- mapM unDirExpand $ dirs ++ files let isHidden str = startswith "." . last . StringUtils.split "/" $ if endswith "/" str then init str else str visible = filter (not . isHidden) suggestions hidden = filter isHidden suggestions return $ visible ++ hidden
aostiles/LiveHaskell
src/IHaskell/Eval/Completion.hs
mit
11,655
0
18
3,193
2,808
1,441
1,367
219
12
import Utmp import Control.Monad import Data.List (group, sort) import Data.Time import System.Environment import Text.Printf -- Reads input from utmp files main :: IO () main = do logins <- concat <$> (mapM decodeFile =<< getArgs) days <- mapM (utcToLocalDay . utTime) logins forM_ (group . sort $ days) $ \d -> do let n = length d putStrLn $ printf "%s %d" (show $ head d) n putStrLn $ printf "%10s %d" "" $ length days utcToLocalDay :: UTCTime -> IO Day utcToLocalDay t = do z <- getTimeZone t -- current location +/- DST at the time return . localDay . utcToLocalTime z $ t
neilmayhew/Utmp
CountsByDay.hs
mit
624
0
15
152
223
110
113
18
1
import Control.Monad import Data.List.Extra import Data.Maybe import qualified Data.Char import qualified Data.Map as Map splitOn1 a b = fromJust $ stripInfix a b type Data = Map.Map String Int input = "Sue 0: children: 3, cats: 7, samoyeds: 2, pomeranians: 3, akitas: 0, vizslas: 0, goldfish: 5, trees: 3, cars: 2, perfumes: 1" target = snd $ readSue input readSue :: String -> (Int, Data) readSue s = let (prefix, body) = splitOn1 ": " s fragments = splitOn ", " body parsePart frag = let (key, count) = splitOn1 ": " frag in (key, read count) ["Sue", num] = words prefix in (read num, Map.fromList $ map parsePart fragments) matches :: (Int, Data) -> Bool matches (i, d) = all present $ Map.toList d where present (k, v) = Map.lookup k target == Just v solve :: String -> Int solve = fst . head . filter matches . map readSue . lines answer f = interact $ (++"\n") . show . f main = answer solve
msullivan/advent-of-code
2015/A16a.hs
mit
947
0
13
216
350
184
166
25
1
module Lint (lintTipToi, warnTipToi) where import Text.Printf import Data.Maybe import Control.Monad import qualified Data.Map as M import Types import PrettyPrint lintTipToi :: TipToiFile -> Segments -> IO () lintTipToi tt segments = do let hyps = [ (hyp1, "play indicies are correct") , (hyp2 (fromIntegral (length (ttAudioFiles tt))), "media indicies are correct") ] forM_ hyps $ \(hyp, desc) -> do let wrong = filter (not . hyp) (concat (mapMaybe snd (ttScripts tt))) if null wrong then printf "All lines do satisfy hypothesis \"%s\"!\n" desc else do printf "These lines do not satisfy hypothesis \"%s\":\n" desc forM_ wrong $ \line -> do printf " %s\n" (ppLine M.empty line) let overlapping_segments = filter (\((o1,l1,_),(o2,l2,_)) -> o1+l1 > o2) $ zip segments (tail segments) unless (null overlapping_segments) $ do printf "Overlapping segments: %d\n" (length overlapping_segments) mapM_ (uncurry report) overlapping_segments where hyp1 :: Line ResReg -> Bool hyp1 (Line _ _ as mi) = all ok as where ok (Play n) = 0 <= n && n < fromIntegral (length mi) ok (Random a b) = 0 <= a && a < fromIntegral (length mi) && 0 <= b && b < fromIntegral (length mi) ok _ = True hyp2 :: Word16 -> Line ResReg -> Bool hyp2 n (Line _ _ _ mi) = all (<= n) mi report :: Segment -> Segment -> IO () report (o1,l1,d1) (o2,l2,d2) | l1 == l2 && o1 == o2 = printf " Offset %08X Size %d referenced by %s and %s\n" o1 l1 (ppDesc d1) (ppDesc d2) | otherwise = printf " Offset %08X Size %d (%s) overlaps Offset %08X Size %d (%s) by %d\n" o1 l1 (ppDesc d1) o2 l2 (ppDesc d2) overlap where overlap = o1 + l1 - o2 warnTipToi :: TipToiFile -> IO () warnTipToi tt = do sequence_ [ printf "[Script %d line %d] Warning: More than 8 commands per line may cause problems\n" c n | (c, Just lines) <- ttScripts tt , (n,Line _ _ cmds _) <- zip [(1::Int)..] lines , length cmds > 8 ]
colinba/tip-toi-reveng
src/Lint.hs
mit
2,244
0
21
732
789
400
389
52
4
{-# LANGUAGE OverloadedStrings #-} module Popeye.Users ( User(..) , UserName(..) , UserPublicKey(..) , Group(..) , getUsers , getUser ) where import Control.Lens (set, view) import Control.Monad (mfilter) import Data.Maybe (catMaybes) import Data.Text (Text) import Network.AWS import Network.AWS.IAM.GetGroup import Network.AWS.IAM.GetSSHPublicKey import Network.AWS.IAM.ListSSHPublicKeys import Network.AWS.IAM.Types hiding (User, Group) newtype Group = Group { unGroup :: Text } newtype PublicKeyId = PublicKeyId { unPublicKeyId :: Text } newtype UserName = UserName { unUserName :: Text } newtype UserPublicKey = UserPublicKey { unUserPublicKey :: Text } data User = User { userName :: UserName , userPublicKeys :: [UserPublicKey] } getUsers :: [Group] -> AWS [User] getUsers gs = mapM getUser =<< concat <$> mapM getUserNames gs getUser :: UserName -> AWS User getUser un = do pks <- mapM (getPublicKeyContent un) =<< getPublicKeyIds un return User { userName = un , userPublicKeys = catMaybes pks } getUserNames :: Group -> AWS [UserName] getUserNames g = do rsp <- send $ getGroup $ unGroup g return $ (UserName . view uUserName) <$> view ggrsUsers rsp getPublicKeyIds :: UserName -> AWS [PublicKeyId] getPublicKeyIds un = do rsp <- send $ set lspkUserName (Just $ unUserName un) listSSHPublicKeys return $ (PublicKeyId . view spkmSSHPublicKeyId) <$> view lspkrsSSHPublicKeys rsp getPublicKeyContent :: UserName -> PublicKeyId -> AWS (Maybe UserPublicKey) getPublicKeyContent un pk = do rsp <- send $ getSSHPublicKey (unUserName un) (unPublicKeyId pk) SSH return $ (UserPublicKey . view spkSSHPublicKeyBody) <$> (mfilter ((== Active) . view spkStatus) $ view gspkrsSSHPublicKey rsp)
codeclimate/popeye
src/Popeye/Users.hs
mit
1,804
0
13
356
568
313
255
45
1
module GHCJS.DOM.SVGZoomEvent ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGZoomEvent.hs
mit
42
0
3
7
10
7
3
1
0
module ANUQRNG ( randomWords, -- :: Integer -> MaybeT IO [Word8] randomWord -- :: MaybeT IO Word8 ) where import Network (withSocketsDo) import Network.Connection import Network.HTTP.Conduit import Data.Aeson import Data.Word import Control.Applicative import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.Maybe import Control.Monad.Trans.Resource import qualified Data.Text as T -- Models the response from the QRNG API. data QRNGResponse = QRNGResponse { qrngType :: String, qrngLength :: Integer, qrngData :: [Word8], qrngSuccess :: Bool } deriving (Show) instance FromJSON QRNGResponse where parseJSON (Object v) = QRNGResponse <$> v .: T.pack "type" <*> v .: T.pack "length" <*> v .: T.pack "data" <*> v .: T.pack "success" parseJSON _ = mzero -- Base URL of the QRNG API. apiUrl :: String apiUrl = "https://qrng.anu.edu.au/API/jsonI.php" -- Settings for the network Manager. managerSettings :: ManagerSettings managerSettings = mkManagerSettings tlsSettings sockSettings where tlsSettings = TLSSettingsSimple True False False sockSettings = Nothing -- Form a request for n random words from the QRNG. apiRequest :: Integer -> Maybe Request apiRequest n = parseUrl $ apiUrl ++ "?length=" ++ show n ++ "&type=uint8" -- Request n random words from the QRNG and return the parsed response. sendApiRequest :: Integer -> MaybeT IO QRNGResponse sendApiRequest n = (mapMaybeT withSocketsDo) . runResourceT $ do manager <- liftIO $ newManager managerSettings request <- liftMaybe $ apiRequest n response <- httpLbs request manager liftMaybe . decode . responseBody $ response where liftMaybe = lift . MaybeT . return -- Fetch a list of random words from the QRNG. randomWords :: Integer -> MaybeT IO [Word8] randomWords n = fmap qrngData $ sendApiRequest n -- Fetch a single random word from the QRNG. randomWord :: MaybeT IO Word8 randomWord = fmap head $ randomWords 1
MatthewJA/haskell-anu-qrng
requesttime.hs
mit
2,055
0
14
445
462
249
213
46
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -- + Complete the 10 exercises below by filling out the function bodies. -- Replace the function bodies (error "todo: ...") with an appropriate -- solution. -- + These exercises may be done in any order, however: -- Exercises are generally increasing in difficulty, though some people may find later exercise easier. -- + Bonus for using the provided functions or for using one exercise solution to help solve another. -- + Approach with your best available intuition; just dive in and do what you can! module Course.List where import qualified Control.Applicative as A import qualified Control.Monad as M import Course.Core import Course.Optional import qualified Numeric as N import qualified Prelude as P import qualified System.Environment as E -- $setup -- >>> import Test.QuickCheck -- >>> import Course.Core(even, id, const) -- >>> import qualified Prelude as P(fmap, foldr) -- >>> instance Arbitrary a => Arbitrary (List a) where arbitrary = P.fmap ((P.foldr (:.) Nil) :: ([a] -> List a)) arbitrary -- BEGIN Helper functions and data types -- The custom list type data List t = Nil | t :. List t deriving (Eq, Ord) -- Right-associative infixr 5 :. instance Show t => Show (List t) where show = show . foldRight (:) [] -- The list of integers from zero to infinity. infinity :: List Integer infinity = let inf x = x :. inf (x+1) in inf 0 -- functions over List that you may consider using foldRight :: (a -> b -> b) -> b -> List a -> b foldRight _ b Nil = b foldRight f b (h :. t) = f h (foldRight f b t) foldLeft :: (b -> a -> b) -> b -> List a -> b foldLeft _ b Nil = b foldLeft f b (h :. t) = let b' = f b h in b' `seq` foldLeft f b' t -- END Helper functions and data types -- | Returns the head of the list or the given default. -- -- >>> headOr 3 (1 :. 2 :. Nil) -- 1 -- -- >>> headOr 3 Nil -- 3 -- -- prop> x `headOr` infinity == 0 -- -- prop> x `headOr` Nil == x headOr :: a -> List a -> a headOr d Nil = d headOr _ (h :. _) = h -- | The product of the elements of a list. -- -- >>> product (1 :. 2 :. 3 :. Nil) -- 6 -- -- >>> product (1 :. 2 :. 3 :. 4 :. Nil) -- 24 product :: List Int -> Int product Nil = 1 product (h :. t) = h * product t product' :: List Int -> Int product' = foldRight (*) 1 -- | Sum the elements of the list. -- -- >>> sum (1 :. 2 :. 3 :. Nil) -- 6 -- -- >>> sum (1 :. 2 :. 3 :. 4 :. Nil) -- 10 -- -- prop> foldLeft (-) (sum x) x == 0 sum :: List Int -> Int sum Nil = 0 sum (h :. t) = h + sum t sum' :: List Int -> Int sum' = foldRight (+) 0 -- | Return the length of the list. -- -- >>> length (1 :. 2 :. 3 :. Nil) -- 3 -- -- prop> sum (map (const 1) x) == length x length :: List a -> Int length Nil = 0 length (_ :. t) = 1 + length t length' :: List a -> Int length' = foldRight (\_ -> (+1)) 0 -- | Map the given function on each element of the list. -- -- >>> map (+10) (1 :. 2 :. 3 :. Nil) -- [11,12,13] -- -- prop> headOr x (map (+1) infinity) == 1 -- -- prop> map id x == x map :: (a -> b) -> List a -> List b map _ Nil = Nil map f (h :. t) = f h :. map f t map' :: (a -> b) -> List a -> List b map' f = foldRight (\x xs -> f x :. xs) Nil -- | Return elements satisfying the given predicate. -- -- >>> filter even (1 :. 2 :. 3 :. 4 :. 5 :. Nil) -- [2,4] -- -- prop> headOr x (filter (const True) infinity) == 0 -- -- prop> filter (const True) x == x -- -- prop> filter (const False) x == Nil filter :: (a -> Bool) -> List a -> List a filter _ Nil = Nil filter f (h :. t) | f h == True = h :. filter f t | otherwise = filter f t -- I can't figure out the type issues based on x :. xs -- filter' :: (a -> Bool) -> List a -> List b -- filter' f = foldRight (\x xs -> if f x then x :. xs else xs) Nil -- | Append two lists to a new list. -- -- >>> (1 :. 2 :. 3 :. Nil) ++ (4 :. 5 :. 6 :. Nil) -- [1,2,3,4,5,6] -- -- prop> headOr x (Nil ++ infinity) == 0 -- -- prop> headOr x (y ++ infinity) == headOr 0 y -- -- prop> (x ++ y) ++ z == x ++ (y ++ z) -- -- prop> x ++ Nil == x (++) :: List a -> List a -> List a (++) Nil ts = ts (++) (h :. t) ts = h :. t ++ ts infixr 5 ++ -- | Flatten a list of lists to a list. -- -- >>> flatten ((1 :. 2 :. 3 :. Nil) :. (4 :. 5 :. 6 :. Nil) :. (7 :. 8 :. 9 :. Nil) :. Nil) -- [1,2,3,4,5,6,7,8,9] -- -- prop> headOr x (flatten (infinity :. y :. Nil)) == 0 -- -- prop> headOr x (flatten (y :. infinity :. Nil)) == headOr 0 y -- -- prop> sum (map length x) == length (flatten x) flatten :: List (List a) -> List a flatten Nil = Nil flatten (h :. t) = h ++ flatten t -- | Map a function then flatten to a list. -- -- >>> flatMap (\x -> x :. x + 1 :. x + 2 :. Nil) (1 :. 2 :. 3 :. Nil) -- [1,2,3,2,3,4,3,4,5] -- -- prop> headOr x (flatMap id (infinity :. y :. Nil)) == 0 -- -- prop> headOr x (flatMap id (y :. infinity :. Nil)) == headOr 0 y -- -- prop> flatMap id (x :: List (List Int)) == flatten x flatMap :: (a -> List b) -> List a -> List b flatMap _ Nil = Nil flatMap f (x :. xs) = f x ++ flatMap f xs -- | Flatten a list of lists to a list (again). -- HOWEVER, this time use the /flatMap/ function that you just wrote. -- -- prop> let types = x :: List (List Int) in flatten x == flattenAgain x flattenAgain :: List (List a) -> List a flattenAgain = flatMap id -- | Convert a list of optional values to an optional list of values. -- -- * If the list contains all `Full` values, -- then return `Full` list of values. -- -- * If the list contains one or more `Empty` values, -- then return `Empty`. -- -- * The only time `Empty` is returned is -- when the list contains one or more `Empty` values. -- -- >>> seqOptional (Full 1 :. Full 10 :. Nil) -- Full [1,10] -- -- >>> seqOptional Nil -- Full [] -- -- >>> seqOptional (Full 1 :. Full 10 :. Empty :. Nil) -- Empty -- -- >>> seqOptional (Empty :. map Full infinity) -- Empty seqOptional :: Eq (a) => List (Optional a) -> Optional (List a) seqOptional l | any (== Empty) l = Empty | otherwise = Full $ toFullL l where toFullL Nil = Nil toFullL ((Full x) :. xs) = x :. toFullL xs toFullL _ = error "unreachable!!" -- | Find the first element in the list matching the predicate. -- -- >>> find even (1 :. 3 :. 5 :. Nil) -- Empty -- -- >>> find even Nil -- Empty -- -- >>> find even (1 :. 2 :. 3 :. 5 :. Nil) -- Full 2 -- -- >>> find even (1 :. 2 :. 3 :. 4 :. 5 :. Nil) -- Full 2 -- -- >>> find (const True) infinity -- Full 0 find :: (a -> Bool) -> List a -> Optional a find f l = headOr Empty $ filter (\(Full a) -> f a) $ map Full l -- | Determine if the length of the given list is greater than 4. -- -- >>> lengthGT4 (1 :. 3 :. 5 :. Nil) -- False -- -- >>> lengthGT4 Nil -- False -- -- >>> lengthGT4 (1 :. 2 :. 3 :. 4 :. 5 :. Nil) -- True -- -- >>> lengthGT4 infinity -- True lengthGT4 :: List a -> Bool lengthGT4 = getLengthTo 4 where getLengthTo _ Nil = False getLengthTo n (_ :. t) | n <= 0 = True | otherwise = getLengthTo (n - 1) t -- | Reverse a list. -- -- >>> reverse Nil -- [] -- -- >>> take 1 (reverse (reverse largeList)) -- [1] -- -- prop> let types = x :: List Int in reverse x ++ reverse y == reverse (y ++ x) -- -- prop> let types = x :: Int in reverse (x :. Nil) == x :. Nil reverse :: List a -> List a reverse l = rev l Nil where rev Nil a = a rev (h :. t) a = rev t (h :. a) -- | Produce an infinite `List` that seeds with the given value at its head, -- then runs the given function for subsequent elements -- -- >>> let (x:.y:.z:.w:._) = produce (+1) 0 in [x,y,z,w] -- [0,1,2,3] -- -- >>> let (x:.y:.z:.w:._) = produce (*2) 1 in [x,y,z,w] -- [1,2,4,8] produce :: (a -> a) -> a -> List a produce f a = a :. produce f (f a) -- | Do anything other than reverse a list. -- Is it even possible? -- -- >>> notReverse Nil -- [] -- -- prop> let types = x :: List Int in notReverse x ++ notReverse y == notReverse (y ++ x) -- -- prop> let types = x :: Int in notReverse (x :. Nil) == x :. Nil notReverse :: List a -> List a notReverse = reverse ---- End of list exercises largeList :: List Int largeList = listh [1..50000] hlist :: List a -> [a] hlist = foldRight (:) [] listh :: [a] -> List a listh = P.foldr (:.) Nil putStr :: Chars -> IO () putStr = P.putStr . hlist putStrLn :: Chars -> IO () putStrLn = P.putStrLn . hlist readFile :: Filename -> IO Chars readFile = P.fmap listh . P.readFile . hlist writeFile :: Filename -> Chars -> IO () writeFile n s = P.writeFile (hlist n) (hlist s) getLine :: IO Chars getLine = P.fmap listh P.getLine getArgs :: IO (List Chars) getArgs = P.fmap (listh . P.fmap listh) E.getArgs isPrefixOf :: Eq a => List a -> List a -> Bool isPrefixOf Nil _ = True isPrefixOf _ Nil = False isPrefixOf (x:.xs) (y:.ys) = x == y && isPrefixOf xs ys isEmpty :: List a -> Bool isEmpty Nil = True isEmpty (_:._) = False span :: (a -> Bool) -> List a -> (List a, List a) span p x = (takeWhile p x, dropWhile p x) break :: (a -> Bool) -> List a -> (List a, List a) break p = span (not . p) dropWhile :: (a -> Bool) -> List a -> List a dropWhile _ Nil = Nil dropWhile p xs@(x:.xs') = if p x then dropWhile p xs' else xs takeWhile :: (a -> Bool) -> List a -> List a takeWhile _ Nil = Nil takeWhile p (x:.xs) = if p x then x :. takeWhile p xs else Nil zip :: List a -> List b -> List (a, b) zip = zipWith (,) zipWith :: (a -> b -> c) -> List a -> List b -> List c zipWith f (a:.as) (b:.bs) = f a b :. zipWith f as bs zipWith _ _ _ = Nil unfoldr :: (a -> Optional (b, a)) -> a -> List b unfoldr f b = case f b of Full (a, z) -> a :. unfoldr f z Empty -> Nil lines :: Chars -> List Chars lines = listh . P.fmap listh . P.lines . hlist unlines :: List Chars -> Chars unlines = listh . P.unlines . hlist . map hlist words :: Chars -> List Chars words = listh . P.fmap listh . P.words . hlist unwords :: List Chars -> Chars unwords = listh . P.unwords . hlist . map hlist listOptional :: (a -> Optional b) -> List a -> List b listOptional _ Nil = Nil listOptional f (h:.t) = let r = listOptional f t in case f h of Empty -> r Full q -> q :. r any :: (a -> Bool) -> List a -> Bool any p = foldRight ((||) . p) False all :: (a -> Bool) -> List a -> Bool all p = foldRight ((&&) . p) True or :: List Bool -> Bool or = any id and :: List Bool -> Bool and = all id elem :: Eq a => a -> List a -> Bool elem x = any (== x) notElem :: Eq a => a -> List a -> Bool notElem x = all (/= x) permutations :: List a -> List (List a) permutations xs0 = let perms Nil _ = Nil perms (t:.ts) is = let interleave' _ Nil r = (ts, r) interleave' f (y:.ys) r = let (us,zs) = interleave' (f . (y:.)) ys r in (y:.us, f (t:.y:.us):.zs) in foldRight (\xs -> snd . interleave' id xs) (perms ts (t:.is)) (permutations is) in xs0 :. perms xs0 Nil intersectBy :: (a -> b -> Bool) -> List a -> List b -> List a intersectBy e xs ys = filter (\x -> any (e x) ys) xs take :: (Num n, Ord n) => n -> List a -> List a take n _ | n <= 0 = Nil take _ Nil = Nil take n (x:.xs) = x :. take (n - 1) xs drop :: (Num n, Ord n) => n -> List a -> List a drop n xs | n <= 0 = xs drop _ Nil = Nil drop n (_:.xs) = drop (n-1) xs repeat :: a -> List a repeat x = x :. repeat x replicate :: (Num n, Ord n) => n -> a -> List a replicate n x = take n (repeat x) reads :: P.Read a => Chars -> Optional (a, Chars) reads s = case P.reads (hlist s) of [] -> Empty ((a, q):_) -> Full (a, listh q) read :: P.Read a => Chars -> Optional a read = mapOptional fst . reads readHexs :: (Eq a, Num a) => Chars -> Optional (a, Chars) readHexs s = case N.readHex (hlist s) of [] -> Empty ((a, q):_) -> Full (a, listh q) readHex :: (Eq a, Num a) => Chars -> Optional a readHex = mapOptional fst . readHexs readFloats :: (RealFrac a) => Chars -> Optional (a, Chars) readFloats s = case N.readSigned N.readFloat (hlist s) of [] -> Empty ((a, q):_) -> Full (a, listh q) readFloat :: (RealFrac a) => Chars -> Optional a readFloat = mapOptional fst . readFloats instance IsString (List Char) where fromString = listh type Chars = List Char type Filename = Chars strconcat :: [Chars] -> P.String strconcat = P.concatMap hlist stringconcat :: [P.String] -> P.String stringconcat = P.concat show' :: Show a => a -> List Char show' = listh . show instance P.Functor List where fmap = M.liftM instance A.Applicative List where (<*>) = M.ap pure = (:. Nil) instance P.Monad List where (>>=) = flip flatMap return = (:. Nil)
harrisi/on-being-better
list-expansion/Haskell/course/src/Course/List.hs
cc0-1.0
13,121
0
20
3,637
4,049
2,158
1,891
447
3
{- This module was generated from data in the Kate syntax highlighting file verilog.xml, version 1.09, by Yevgen Voronenko (ysv22@drexel.edu), Ryan Dalzell (ryan@tullyroan.com) -} module Text.Highlighting.Kate.Syntax.Verilog (highlight, parseExpression, syntaxName, syntaxExtensions) where import Text.Highlighting.Kate.Types import Text.Highlighting.Kate.Common import qualified Text.Highlighting.Kate.Syntax.Alert import Text.ParserCombinators.Parsec hiding (State) import Control.Monad.State import Data.Char (isSpace) import qualified Data.Set as Set -- | Full name of language. syntaxName :: String syntaxName = "Verilog" -- | Filename extensions for this language. syntaxExtensions :: String syntaxExtensions = "*.v;*.V;*.vl" -- | Highlight source code using this syntax definition. highlight :: String -> [SourceLine] highlight input = evalState (mapM parseSourceLine $ lines input) startingState parseSourceLine :: String -> State SyntaxState SourceLine parseSourceLine = mkParseSourceLine (parseExpression Nothing) -- | Parse an expression using appropriate local context. parseExpression :: Maybe (String,String) -> KateParser Token parseExpression mbcontext = do (lang,cont) <- maybe currentContext return mbcontext result <- parseRules (lang,cont) optional $ do eof updateState $ \st -> st{ synStPrevChar = '\n' } pEndLine return result startingState = SyntaxState {synStContexts = [("Verilog","Normal")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []} pEndLine = do updateState $ \st -> st{ synStPrevNonspace = False } context <- currentContext contexts <- synStContexts `fmap` getState st <- getState if length contexts >= 2 then case context of _ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False } ("Verilog","Normal") -> return () ("Verilog","String") -> (popContext) >> pEndLine ("Verilog","Commentar 1") -> (popContext) >> pEndLine ("Verilog","Commentar 2") -> return () ("Verilog","Preprocessor") -> (popContext) >> pEndLine ("Verilog","Commentar/Preprocessor") -> return () ("Verilog","Some Context") -> (popContext) >> pEndLine ("Verilog","Some Context2") -> return () ("Verilog","Block name") -> (popContext) >> pEndLine ("Verilog","Port") -> return () _ -> return () else return () withAttribute attr txt = do when (null txt) $ fail "Parser matched no text" updateState $ \st -> st { synStPrevChar = last txt , synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) } return (attr, txt) list_keywords = Set.fromList $ words $ "macromodule table endtable specify specparam endspecify defparam default if ifnone else forever while for wait repeat disable assign deassign force release always initial edge posedge negedge config endconfig library design liblist cell use instance" list_beginwords = Set.fromList $ words $ "begin fork module case casex casez task function generate" list_endwords = Set.fromList $ words $ "end join endmodule endcase endtask endfunction endgenerate" list_strength = Set.fromList $ words $ "strong0 strong1 pull0 pull1 weak0 weak1 highz0 highz1 small medium large" list_gates = Set.fromList $ words $ "pullup pulldown cmos rcmos nmos pmos rnmos rpmos and nand or nor xor xnor not buf tran rtran tranif0 tranif1 rtranif0 rtranif1 bufif0 bufif1 notif0 notif1" list_types = Set.fromList $ words $ "input output inout wire tri tri0 tri1 wand wor triand trior supply0 supply1 reg integer real realtime time vectored scalared trireg parameter event signed automatic genvar localparam" regex_begin'5c_'2a'3a = compileRegex True "begin\\ *:" regex_fork'5c_'2a'3a = compileRegex True "fork\\ *:" regex_'5b'5cd'5f'5d'2a'27d'5b'5cd'5f'5d'2b = compileRegex True "[\\d_]*'d[\\d_]+" regex_'5b'5cd'5f'5d'2a'27o'5b0'2d7xXzZ'5f'5d'2b = compileRegex True "[\\d_]*'o[0-7xXzZ_]+" regex_'5b'5cd'5f'5d'2a'27h'5b'5cda'2dfA'2dFxXzZ'5f'5d'2b = compileRegex True "[\\d_]*'h[\\da-fA-FxXzZ_]+" regex_'5b'5cd'5f'5d'2a'27b'5b01'5fzZxX'5d'2b = compileRegex True "[\\d_]*'b[01_zZxX]+" regex_'5ba'2dzA'2dZ0'2d9'5f'2c_'5ct'5d'2b'5cs'2a'3a = compileRegex True "[a-zA-Z0-9_, \\t]+\\s*:" regex_'5c'60'5ba'2dzA'2dZ'5f'5d'2b'5cw'2a = compileRegex True "\\`[a-zA-Z_]+\\w*" regex_'5c'24'5ba'2dzA'2dZ'5f'5d'2b'5cw'2a = compileRegex True "\\$[a-zA-Z_]+\\w*" regex_'23'5b'5cd'5f'5d'2b = compileRegex True "#[\\d_]+" parseRules ("Verilog","Normal") = (((pDetectSpaces >>= withAttribute NormalTok)) <|> ((pRegExpr regex_begin'5c_'2a'3a >>= withAttribute KeywordTok) >>~ pushContext ("Verilog","Block name")) <|> ((pRegExpr regex_fork'5c_'2a'3a >>= withAttribute KeywordTok) >>~ pushContext ("Verilog","Block name")) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_beginwords >>= withAttribute KeywordTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_endwords >>= withAttribute KeywordTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywords >>= withAttribute KeywordTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_types >>= withAttribute DataTypeTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_strength >>= withAttribute BaseNTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_gates >>= withAttribute DataTypeTok)) <|> ((pRegExpr regex_'5b'5cd'5f'5d'2a'27d'5b'5cd'5f'5d'2b >>= withAttribute BaseNTok)) <|> ((pRegExpr regex_'5b'5cd'5f'5d'2a'27o'5b0'2d7xXzZ'5f'5d'2b >>= withAttribute BaseNTok)) <|> ((pRegExpr regex_'5b'5cd'5f'5d'2a'27h'5b'5cda'2dfA'2dFxXzZ'5f'5d'2b >>= withAttribute BaseNTok)) <|> ((pRegExpr regex_'5b'5cd'5f'5d'2a'27b'5b01'5fzZxX'5d'2b >>= withAttribute BaseNTok)) <|> ((pFloat >>= withAttribute FloatTok)) <|> ((pInt >>= withAttribute DecValTok)) <|> ((pFirstNonSpace >> pRegExpr regex_'5ba'2dzA'2dZ0'2d9'5f'2c_'5ct'5d'2b'5cs'2a'3a >>= withAttribute DecValTok)) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("Verilog","String")) <|> ((pDetect2Chars False '/' '/' >>= withAttribute CommentTok) >>~ pushContext ("Verilog","Commentar 1")) <|> ((pDetect2Chars False '/' '*' >>= withAttribute CommentTok) >>~ pushContext ("Verilog","Commentar 2")) <|> ((pAnyChar "!%&()+,-<=+/:;>?[]^{|}~@" >>= withAttribute NormalTok)) <|> ((pColumn 0 >> pDetectChar False '`' >>= withAttribute OtherTok) >>~ pushContext ("Verilog","Preprocessor")) <|> ((pRegExpr regex_'5c'60'5ba'2dzA'2dZ'5f'5d'2b'5cw'2a >>= withAttribute OtherTok)) <|> ((pRegExpr regex_'5c'24'5ba'2dzA'2dZ'5f'5d'2b'5cw'2a >>= withAttribute DataTypeTok)) <|> ((pRegExpr regex_'23'5b'5cd'5f'5d'2b >>= withAttribute BaseNTok)) <|> (currentContext >>= \x -> guard (x == ("Verilog","Normal")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Verilog","String") = (((pLineContinue >>= withAttribute StringTok) >>~ pushContext ("Verilog","Some Context")) <|> ((pHlCStringChar >>= withAttribute CharTok)) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Verilog","String")) >> pDefault >>= withAttribute StringTok)) parseRules ("Verilog","Commentar 1") = (((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd))) <|> (currentContext >>= \x -> guard (x == ("Verilog","Commentar 1")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Verilog","Commentar 2") = (((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd))) <|> ((pDetect2Chars False '*' '/' >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Verilog","Commentar 2")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Verilog","Preprocessor") = (((pLineContinue >>= withAttribute OtherTok) >>~ pushContext ("Verilog","Some Context")) <|> ((pRangeDetect '"' '"' >>= withAttribute FloatTok)) <|> ((pRangeDetect '<' '>' >>= withAttribute FloatTok)) <|> ((pDetect2Chars False '/' '/' >>= withAttribute CommentTok) >>~ pushContext ("Verilog","Commentar 1")) <|> ((pDetect2Chars False '/' '*' >>= withAttribute CommentTok) >>~ pushContext ("Verilog","Commentar/Preprocessor")) <|> (currentContext >>= \x -> guard (x == ("Verilog","Preprocessor")) >> pDefault >>= withAttribute OtherTok)) parseRules ("Verilog","Commentar/Preprocessor") = (((pDetect2Chars False '*' '/' >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Verilog","Commentar/Preprocessor")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Verilog","Some Context") = (currentContext >>= \x -> guard (x == ("Verilog","Some Context")) >> pDefault >>= withAttribute NormalTok) parseRules ("Verilog","Some Context2") = (((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd))) <|> ((pFirstNonSpace >> pString False "#endif" >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Verilog","Some Context2")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Verilog","Block name") = (((pDetectIdentifier >>= withAttribute DataTypeTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Verilog","Block name")) >> pDefault >>= withAttribute DataTypeTok)) parseRules ("Verilog","Port") = (((pDetectIdentifier >>= withAttribute NormalTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Verilog","Port")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Alerts", _) = Text.Highlighting.Kate.Syntax.Alert.parseExpression Nothing parseRules x = parseRules ("Verilog","Normal") <|> fail ("Unknown context" ++ show x)
ambiata/highlighting-kate
Text/Highlighting/Kate/Syntax/Verilog.hs
gpl-2.0
10,049
0
34
1,519
2,632
1,413
1,219
170
13
{- | Module : $Header$ Description : Utils for the abstract syntax of EnCL Copyright : (c) Dominik Dietrich, Ewaryst Schulz, DFKI Bremen 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : Ewaryst.Schulz@dfki.de Stability : experimental Portability : portable Utils to create and access abstract syntax data -} module CSL.ASUtils ( getDefiniens -- accessor function for AssDefinition , getArguments -- accessor function for AssDefinition , isFunDef -- predicate for AssDefinition , isInterval -- predicate for EXPRESSION , mkDefinition -- constructor for AssDefinition , updateDefinition -- updates the definiens , mapExpr -- maps function over EXPRESSION arguments , varDeclName , varDeclToVar , opDeclToOp , mkVar -- Variable constructor , mkOp -- Simple Operator constructor , mkPredefOp -- Simple Operator constructor for predefined ops , mkUserdefOp , mkAndAnalyzeOp , mkAndAnalyzeOp' , toElimConst -- Constant naming for elim constants, see Analysis.hs , simpleName , setOfUserDefined , setOfConstsAndEPSpecs ) where import Common.Id as Id import qualified Data.Set as Set import Data.List (sort, mapAccumL) import CSL.AS_BASIC_CSL import CSL.Fold -- --------------------------------------------------------------------------- -- * Preliminaries and Utilities -- --------------------------------------------------------------------------- -- | A simple operator constructor from given operator name and arguments mkOp :: String -> [EXPRESSION] -> EXPRESSION mkOp s el = Op (OpUser $ SimpleConstant s) [] el nullRange -- | A variable constructor mkVar :: String -> EXPRESSION mkVar = Var . mkSimpleId -- | A simple operator constructor from given operator id and arguments mkPredefOp :: OPNAME -> [EXPRESSION] -> EXPRESSION mkPredefOp n el = Op (OpId n) [] el nullRange -- | A simple operator constructor from given operator id and arguments mkUserdefOp :: String -> [EXTPARAM] -> [EXPRESSION] -> Range -> EXPRESSION mkUserdefOp n epl el rg = Op (OpUser $ SimpleConstant n) epl el rg foldNaryToBinary :: OPID -> Range -> [EXPRESSION] -> EXPRESSION foldNaryToBinary op rg exps = foldl f (f (exps!!0) (exps!!1)) $ drop 2 exps where f e' e'' = Op op [] [e', e''] rg mkAndAnalyzeOp :: OperatorState st => st -> String -> [EXTPARAM] -> [EXPRESSION] -> Range -> EXPRESSION mkAndAnalyzeOp st s eps exps rg = either f g $ mkAndAnalyzeOp' False st s eps exps rg where f = error g e = e -- | Lookup the string in the given 'OperatorState' mkAndAnalyzeOp' :: OperatorState st => Bool -- ^ process binders -> st -> String -> [EXTPARAM] -> [EXPRESSION] -> Range -> Either String EXPRESSION mkAndAnalyzeOp' b st s eps exps rg = case lookupOperator st s (length exps) of Left False | isVar st s -> if null exps && null eps then Right $ Var $ Token { tokStr = s, tokPos = rg } else Left "Variable requires no (extended) parameters" | otherwise -> f exps $ OpUser $ SimpleConstant s -- if registered it must be registered with the given arity or -- as flex-op, otherwise we don't accept it Left True -> Left "Wrong arity" Right oi | null eps -> if foldNAry oi && length exps > 2 then Right $ foldNaryToBinary (OpId $ opname oi) rg exps else let exps' = case bind oi of Just x -> if b then processBinderArgs x exps else exps _ -> exps in f exps' $ OpId $ opname oi | otherwise -> Left "No extended parameters allowed" where f exps' op = Right $ Op op eps exps' rg -- | For given binder arguments we replace the constant-expressions at the -- bound variable positions by variable-expressions and also all constants with -- the name of a variable in the arguments at binder body positions. processBinderArgs :: BindInfo -> [EXPRESSION] -> [EXPRESSION] processBinderArgs (BindInfo {bindingVarPos = bvl, boundBodyPos = bbl}) exps = let bvl' = sort bvl (vs, vl) = varSet $ map (exps!!) bvl' g l'@((j,ve):l) (i, e) | j == i -- at bound variable position = (l, ve) | otherwise = (l', g' (i, e)) g l x = (l, g' x) g' (i, e) | elem i bbl -- at binder body position = constsToVars vs e | otherwise = e in snd $ mapAccumL g (zip bvl' vl) $ zip [0..] exps mapExpr :: (EXPRESSION -> EXPRESSION) -> EXPRESSION -> EXPRESSION mapExpr f e = case e of Op oi epl args rg -> Op oi epl (map f args) rg List exps rg -> List (map f exps) rg _ -> e -- | Transforms Op-Expressions to a set of op-names and a Var-list varSet :: [EXPRESSION] -> (Set.Set String, [EXPRESSION]) varSet l = let opToVar' s (Op v _ _ rg') = ( Set.insert (simpleName v) s , Var Token{ tokStr = simpleName v, tokPos = rg' } ) opToVar' s v@(Var tok) = (Set.insert (tokStr tok) s, v) opToVar' _ x = error $ "varSet: not supported varexpression at " ++ show x in mapAccumL opToVar' Set.empty l -- | Replaces Op occurrences to Var if the op is in the given set constsToVars :: Set.Set String -> EXPRESSION -> EXPRESSION constsToVars env e = let substRec = idRecord { foldOp = \ _ s epl' args rg' -> if Set.member (simpleName s) env then if null args then Var (Token { tokStr = simpleName s, tokPos = rg' }) else error $ "constsToVars: variable must not have" ++ " arguments:" ++ show args else Op s epl' args rg' , foldList = \ _ l rg' -> List l rg' } in foldTerm substRec e updateDefinition :: EXPRESSION -> AssDefinition -> AssDefinition updateDefinition e' (ConstDef _) = ConstDef e' updateDefinition e' (FunDef l _) = FunDef l e' mkDefinition :: [String] -> EXPRESSION -> AssDefinition mkDefinition l e = if null l then ConstDef e else FunDef l e getDefiniens :: AssDefinition -> EXPRESSION getDefiniens (ConstDef e) = e getDefiniens (FunDef _ e) = e getArguments :: AssDefinition -> [String] getArguments (FunDef l _) = l getArguments _ = [] isFunDef :: AssDefinition -> Bool isFunDef (FunDef _ _) = True isFunDef _ = False isInterval :: EXPRESSION -> Bool isInterval (Interval _ _ _) = True isInterval _ = False simpleName :: OPID -> String simpleName (OpId n) = showOPNAME n simpleName (OpUser (SimpleConstant s)) = s simpleName (OpUser x) = error "simpleName: ElimConstant not supported: " ++ show x toElimConst :: ConstantName -> Int -> ConstantName toElimConst (SimpleConstant s) i = ElimConstant s i toElimConst ec _ = error $ "toElimConst: already an elim const " ++ show ec varDeclName :: VarDecl -> String varDeclName (VarDecl n _) = Id.tokStr n varDeclToVar :: VarDecl -> EXPRESSION varDeclToVar (VarDecl n _) = Var n opDeclToOp :: OpDecl -> EXPRESSION opDeclToOp (OpDecl n epl vdl rg ) = Op (OpUser n) epl (map varDeclToVar vdl) rg -- | Returns a set of user defined constants ignoring 'EXTPARAM' instantiation. setOfUserDefined :: EXPRESSION -> Set.Set String setOfUserDefined e = g Set.empty e where g s x = case x of Op oi@(OpUser _) _ al _ -> foldl g (Set.insert (simpleName oi) s) al -- handle also non-userdefined ops. Op _ _ al _ -> foldl g s al -- ignoring lists (TODO: they should be removed soon anyway) _ -> s -- | Returns a set of user defined constants and 'EXTPARAM' specifications. setOfConstsAndEPSpecs :: EXPRESSION -> (Set.Set String, Set.Set EXTPARAM) setOfConstsAndEPSpecs e = g (Set.empty, Set.empty) e where g s@(s1, s2) x = case x of Op oi@(OpUser _) epl al _ -> foldl g ( Set.insert (simpleName oi) s1 , foldr Set.insert s2 epl) al -- handle also non-userdefined ops. Op _ _ al _ -> foldl g s al -- ignoring lists (TODO: they should be removed soon anyway) _ -> s
nevrenato/Hets_Fork
CSL/ASUtils.hs
gpl-2.0
8,369
0
18
2,391
2,270
1,177
1,093
154
7
module Type where import Test.QuickCheck import Control.Applicative import Data.List (union) import Exp data Type = BasicType Id | FunType Type Type | TypeVariable Id deriving (Show, Eq) showType :: Type -> String showType (BasicType t) = t showType (FunType a b) = showType a ++ " -> (" ++ showType b ++ ")" showType (TypeVariable a) = a typeVariables :: Type -> [Id] typeVariables (BasicType _) = [] typeVariables (TypeVariable a) = [a] typeVariables (FunType a b) = typeVariables a `union` typeVariables b instance Arbitrary Type where arbitrary = sized arbType arbType :: Int -> Gen Type arbType 0 = oneof [ BasicType <$> elements ["Bool", "Int", "String", "Float"], TypeVariable <$> elements ["a", "b", "c"] ] arbType n = do k <- choose (0, n-1) FunType <$> resize k arbitrary <*> resize (n-1-k) arbitrary
pbevin/milner-type-poly
src/Type.hs
gpl-2.0
843
0
11
166
343
180
163
22
1
-- -*-haskell-*- -- Vision (for the Voice): an XMMS2 client. -- -- Author: Oleg Belozeorov -- Created: 20 Jun. 2010 -- -- Copyright (C) 2010, 2011, 2012 Oleg Belozeorov -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License as -- published by the Free Software Foundation; either version 3 of -- the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- General Public License for more details. -- {-# LANGUAGE DeriveDataTypeable, Rank2Types #-} module Playback ( initPlayback , WithPlayback , withPlayback , currentTrack , getPlaybackStatus , playbackStatus , getCurrentTrack , startPlayback , pausePlayback , stopPlayback , restartPlayback , prevTrack , nextTrack , requestCurrentTrack ) where import Control.Concurrent import Control.Concurrent.STM import Control.Concurrent.STM.TGVar import Control.Arrow import Control.Monad import Control.Monad.Trans import Data.Typeable import Data.Env import XMMS2.Client hiding (playbackStatus) import qualified XMMS2.Client as XC import XMMS import Registry import Utils data Ix = Ix deriving (Typeable) data Playback = Playback { _playbackStatus :: TVar (Maybe PlaybackStatus) , _currentTrack :: TVar (Maybe (Int, String)) } deriving (Typeable) type WithPlayback = ?_Playback :: Playback playbackStatus :: WithPlayback => TVar (Maybe PlaybackStatus) playbackStatus = _playbackStatus ?_Playback currentTrack :: WithPlayback => TVar (Maybe (Int, String)) currentTrack = _currentTrack ?_Playback getPlaybackStatus :: WithPlayback => IO (Maybe PlaybackStatus) getPlaybackStatus = atomically $ readTVar playbackStatus getCurrentTrack :: WithPlayback => IO (Maybe (Int, String)) getCurrentTrack = atomically $ readTVar currentTrack initPlayback :: WithRegistry => IO () initPlayback = withXMMS $ do playback <- mkPlayback addEnv Ix playback let ?_Playback = playback xcW <- atomically $ newTGWatch connectedV forkIO $ forever $ do conn <- atomically $ watch xcW resetState when conn $ do broadcastPlaybackStatus xmms >>* do liftIO requestStatus return True requestStatus broadcastPlaylistCurrentPos xmms >>* do liftIO requestCurrentTrack return True requestCurrentTrack return () withPlayback :: WithRegistry => (WithPlayback => IO a) -> IO a withPlayback func = do Just (Env playback) <- getEnv (Extract :: Extract Ix Playback) let ?_Playback = playback func mkPlayback :: IO Playback mkPlayback = do playbackStatus <- atomically $ newTVar Nothing currentTrack <- atomically $ newTVar Nothing return Playback { _playbackStatus = playbackStatus , _currentTrack = currentTrack } resetState :: WithPlayback => IO () resetState = atomically $ do writeTVar playbackStatus Nothing writeTVar currentTrack Nothing setStatus :: WithPlayback => Maybe PlaybackStatus -> IO () setStatus s = atomically $ writeTVar playbackStatus s requestStatus :: (WithPlayback, WithXMMS) => IO () requestStatus = XC.playbackStatus xmms >>* do status <- result liftIO . setStatus $ Just status requestCurrentTrack :: (WithPlayback, WithXMMS) => IO () requestCurrentTrack = playlistCurrentPos xmms Nothing >>* do new <- catchResult Nothing (Just . first fromIntegral) liftIO $ atomically $ writeTVar currentTrack new startPlayback :: (WithPlayback, WithXMMS) => Bool -> IO () startPlayback False = do playbackStart xmms return () startPlayback True = do ps <- getPlaybackStatus case ps of Just StatusPlay -> playbackTickle xmms Just StatusPause -> do playbackTickle xmms playbackStart xmms playbackTickle xmms _ -> playbackStart xmms return () pausePlayback :: WithXMMS => IO () pausePlayback = do playbackPause xmms return () stopPlayback :: WithXMMS => IO () stopPlayback = do playbackStop xmms return () nextTrack :: WithXMMS => IO () nextTrack = do playlistSetNextRel xmms 1 playbackTickle xmms return () prevTrack :: WithXMMS => IO () prevTrack = do playlistSetNextRel xmms (-1) playbackTickle xmms return () restartPlayback :: WithXMMS => IO () restartPlayback = do playbackTickle xmms return ()
upwawet/vision
src/Playback.hs
gpl-3.0
4,529
0
17
935
1,163
572
591
-1
-1
module Math where import Control.DeepSeq --import Data.Vector.Unboxed -- scalar type type Scalar = Double epsilon :: Scalar epsilon = 0.000001 ----------------------------------------------------------------------------------------------------- -- A 3D vector data Vec3 = Vec3 { vecX :: Scalar, vecY :: Scalar, vecZ :: Scalar } deriving (Eq) instance Show Vec3 where show (Vec3 x y z) = "(" ++ show x ++ "," ++ show y ++ "," ++ show z ++ ")" instance Num Vec3 where (Vec3 x y z) + (Vec3 x' y' z') = Vec3 (x+x') (y+y') (z+z') (Vec3 x y z) * (Vec3 x' y' z') = Vec3 (x*x') (y*y') (z*z') negate (Vec3 x y z) = Vec3 (-x) (-y) (-z) abs (Vec3 x y z) = Vec3 (abs x) (abs y) (abs z) signum (Vec3 x y z) = Vec3 (signum x) (signum y) (signum z) fromInteger n = let x = fromInteger n in Vec3 x x x instance NFData Vec3 where rnf (Vec3 x y z) = rnf x `seq` rnf y `seq` rnf z `seq` () -- the zero vector zerov :: Vec3 zerov = Vec3 0 0 0 -- map f to each coordinate vmap :: (Scalar -> Scalar) -> Vec3 -> Vec3 vmap f (Vec3 x y z) = Vec3 (f x) (f y) (f z) vzip :: Vec3 -> Vec3 -> [(Scalar, Scalar)] vzip (Vec3 x y z) (Vec3 x' y' z') = [(x,x'), (y,y'), (z,z')] liftV2 :: (Scalar -> Scalar -> Scalar) -> Vec3 -> Vec3 -> Vec3 liftV2 f (Vec3 x y z) (Vec3 x' y' z') = Vec3 (f x x') (f y y') (f z z') allCoordsCompare :: (Scalar -> Scalar -> Bool) -> Vec3 -> Vec3 -> Bool allCoordsCompare f (Vec3 x y z) (Vec3 x' y' z') = x `f` x' && y `f` y' && z `f` z' allCoordsLE, allCoordsLT :: Vec3 -> Vec3 -> Bool allCoordsLE = allCoordsCompare (<=) allCoordsLT = allCoordsCompare (<) -- scalar product infixl 7 |* (|*) :: Scalar -> Vec3 -> Vec3 (|*) a = vmap (a*) infixl 7 *| (*|) :: Vec3 -> Scalar -> Vec3 (*|) = flip (|*) -- dot product infixl 7 |.| (|.|) :: Vec3 -> Vec3 -> Scalar (Vec3 x y z) |.| (Vec3 x' y' z') = x*x' + y*y' + z*z' -- cross product infixl 7 |*| (|*|) :: Vec3 -> Vec3 -> Vec3 (Vec3 x y z) |*| (Vec3 x' y' z') = Vec3 (y*z'-y'*z) (x'*z-x*z') (x*y'-x'*y) -- component-wise exp infixr 8 |**| (|**|) :: Vec3 -> Scalar -> Vec3 (Vec3 x y z) |**| e = Vec3 (x**e) (y**e) (z**e) -- vector norm norm :: Vec3 -> Scalar norm v = sqrt $ v |.| v -- distance between two vectors distance :: Vec3 -> Vec3 -> Scalar distance v w = norm $ v-w -- normalize vector normalize :: Vec3 -> Vec3 normalize v | n < epsilon = zerov | otherwise = vmap (/n) v where n = norm v -- Vec3 with identical entries idv :: Scalar -> Vec3 idv x = Vec3 x x x -- |Standard basis vectors basis :: [Vec3] basis = [Vec3 1 0 0, Vec3 0 1 0, Vec3 0 0 1] -- 3D ray data Ray = Ray { origin :: Vec3, direction :: Vec3 } deriving (Eq, Show) type Velocity = Vec3 type Time = Scalar -- lorentz boost a vector with velocity. Note c = 1, so |velocity| < 1. lorentzBoost :: Velocity -> Time -> Vec3 -> Vec3 lorentzBoost velocity t r | v >= 1 = error "Superluminal motion forbidden" | v < 0.01 = r -- don't bother for v << c | otherwise = r + (gamma - 1) * (r |.| n) |* n - gamma * t |* velocity where v = norm velocity n = vmap (/v) velocity gamma = 1 / sqrt (1 - v^2) -- compute the smallest real root(s) to ax^2 + bx + c = 0 roots2 :: Scalar -> Scalar -> Scalar -> [Scalar] roots2 a b c | disc < (-epsilon) = [] | abs disc < epsilon = [-b/(2*a)] | otherwise = let sd = sqrt disc in [(-b-sd)/(2*a), (-b+sd)/(2*a)] where disc = b*b - 4*a*c -- reflection of a vector against a unit normal reflection :: Vec3 -> Vec3 -> Vec3 reflection d n = d - (2*(d |.| n) |* n) -- types type Point = Vec3 type Normal = Vec3 type Axis = Vec3 type Angle = Double -- Homogeneous 4d vector and 4x4 matrix data Vec4 = Vec4 Scalar Scalar Scalar Scalar deriving (Eq) instance Show Vec4 where show (Vec4 x y z w) = "(" ++ show x ++ "," ++ show y ++ "," ++ show z ++ "," ++ show w ++ ")" instance Num Vec4 where (Vec4 x y z w) + (Vec4 x' y' z' w') = Vec4 (x+x') (y+y') (z+z') (w+w') (Vec4 x y z w) * (Vec4 x' y' z' w') = Vec4 (x*x') (y*y') (z*z') (w*w') negate (Vec4 x y z w) = Vec4 (-x) (-y) (-z) (-w) abs (Vec4 x y z w) = Vec4 (abs x) (abs y) (abs z) (abs w) signum (Vec4 x y z w) = Vec4 (signum x) (signum y) (signum z) (signum w) fromInteger n = let x = fromInteger n in Vec4 x x x x v4dot :: Vec4 -> Vec4 -> Scalar v4dot (Vec4 x y z w) (Vec4 x' y' z' w') = x*x' + y*y' + z*z' + w*w' -- combine a Vec3 with a scalar infixr 5 |: (|:) :: Vec3 -> Scalar -> Vec4 (Vec3 x y z) |: w = Vec4 x y z w -- transform homogenous coordinates (x,y,z,w) -> (x',y',z') fromHVec4 :: Vec4 -> Vec3 fromHVec4 (Vec4 x y z w) | w < epsilon || abs (w-1) < epsilon = Vec3 x y z | otherwise = Vec3 (x/w) (y/w) (z/w) data Mat4 = Mat4 Vec4 Vec4 Vec4 Vec4 deriving (Eq) instance Show Mat4 where show (Mat4 a b c d) = "(" ++ show a ++ "\n " ++ show b ++ "\n " ++ show c ++ "\n " ++ show d ++ ")" instance Num Mat4 where (Mat4 x y z w) + (Mat4 x' y' z' w') = Mat4 (x+x') (y+y') (z+z') (w+w') (Mat4 a1 a2 a3 a4) * (Mat4 (Vec4 b11 b12 b13 b14) (Vec4 b21 b22 b23 b24) (Vec4 b31 b32 b33 b34) (Vec4 b41 b42 b43 b44)) = Mat4 (Vec4 (a1 `v4dot` b1) (a1 `v4dot` b2) (a1 `v4dot` b3) (a1 `v4dot` b4)) (Vec4 (a2 `v4dot` b1) (a2 `v4dot` b2) (a2 `v4dot` b3) (a2 `v4dot` b4)) (Vec4 (a3 `v4dot` b1) (a3 `v4dot` b2) (a3 `v4dot` b3) (a3 `v4dot` b4)) (Vec4 (a4 `v4dot` b1) (a4 `v4dot` b2) (a4 `v4dot` b3) (a4 `v4dot` b4)) where b1 = Vec4 b11 b21 b31 b41 b2 = Vec4 b12 b22 b32 b42 b3 = Vec4 b13 b23 b33 b43 b4 = Vec4 b14 b24 b34 b44 negate (Mat4 x y z w) = Mat4 (-x) (-y) (-z) (-w) abs (Mat4 x y z w) = Mat4 (abs x) (abs y) (abs z) (abs w) signum (Mat4 x y z w) = Mat4 (signum x) (signum y) (signum z) (signum w) fromInteger = diagMat . fromInteger diagMat :: Vec4 -> Mat4 diagMat (Vec4 a b c d) = Mat4 (Vec4 a 0 0 0) (Vec4 0 b 0 0) (Vec4 0 0 c 0) (Vec4 0 0 0 d) idMat :: Mat4 idMat = diagMat 1 invMat :: Mat4 -> Maybe Mat4 invMat (Mat4 (Vec4 m0 m1 m2 m3) (Vec4 m4 m5 m6 m7) (Vec4 m8 m9 m10 m11) (Vec4 m12 m13 m14 m15)) | abs det < epsilon = Nothing | otherwise = Just $ Mat4 (Vec4 (i0/det) (i1/det) (i2/det) (i3/det)) (Vec4 (i4/det) (i5/det) (i6/det) (i7/det)) (Vec4 (i8/det) (i9/det) (i10/det) (i11/det)) (Vec4 (i12/det) (i13/det) (i14/det) (i15/det)) where i0 = m5 * m10 * m15 - m5 * m11 * m14 - m9 * m6 * m15 + m9 * m7 * m14 + m13 * m6 * m11 - m13 * m7 * m10 i4 = -m4 * m10 * m15 + m4 * m11 * m14 + m8 * m6 * m15 - m8 * m7 * m14 - m12 * m6 * m11 + m12 * m7 * m10 i8 = m4 * m9 * m15 - m4 * m11 * m13 - m8 * m5 * m15 + m8 * m7 * m13 + m12 * m5 * m11 - m12 * m7 * m9 i12 = -m4 * m9 * m14 + m4 * m10 * m13 + m8 * m5 * m14 - m8 * m6 * m13 - m12 * m5 * m10 + m12 * m6 * m9 i1 = -m1 * m10 * m15 + m1 * m11 * m14 + m9 * m2 * m15 - m9 * m3 * m14 - m13 * m2 * m11 + m13 * m3 * m10 i5 = m0 * m10 * m15 - m0 * m11 * m14 - m8 * m2 * m15 + m8 * m3 * m14 + m12 * m2 * m11 - m12 * m3 * m10 i9 = -m0 * m9 * m15 + m0 * m11 * m13 + m8 * m1 * m15 - m8 * m3 * m13 - m12 * m1 * m11 + m12 * m3 * m9 i13 = m0 * m9 * m14 - m0 * m10 * m13 - m8 * m1 * m14 + m8 * m2 * m13 + m12 * m1 * m10 - m12 * m2 * m9 i2 = m1 * m6 * m15 - m1 * m7 * m14 - m5 * m2 * m15 + m5 * m3 * m14 + m13 * m2 * m7 - m13 * m3 * m6 i6 = -m0 * m6 * m15 + m0 * m7 * m14 + m4 * m2 * m15 - m4 * m3 * m14 - m12 * m2 * m7 + m12 * m3 * m6 i10 = m0 * m5 * m15 - m0 * m7 * m13 - m4 * m1 * m15 + m4 * m3 * m13 + m12 * m1 * m7 - m12 * m3 * m5 i14 = -m0 * m5 * m14 + m0 * m6 * m13 + m4 * m1 * m14 - m4 * m2 * m13 - m12 * m1 * m6 + m12 * m2 * m5 i3 = -m1 * m6 * m11 + m1 * m7 * m10 + m5 * m2 * m11 - m5 * m3 * m10 - m9 * m2 * m7 + m9 * m3 * m6; i7 = m0 * m6 * m11 - m0 * m7 * m10 - m4 * m2 * m11 + m4 * m3 * m10 + m8 * m2 * m7 - m8 * m3 * m6; i11 = -m0 * m5 * m11 + m0 * m7 * m9 + m4 * m1 * m11 - m4 * m3 * m9 - m8 * m1 * m7 + m8 * m3 * m5; i15 = m0 * m5 * m10 - m0 * m6 * m9 - m4 * m1 * m10 + m4 * m2 * m9 + m8 * m1 * m6 - m8 * m2 * m5 det = m0 * i0 + m1 * i4 + m2 * i8 + m3 * i12 transformVec4 :: Mat4 -> Vec4 -> Vec4 transformVec4 (Mat4 a1 a2 a3 a4) v = Vec4 (a1 `v4dot` v) (a2 `v4dot` v) (a3 `v4dot` v) (a4 `v4dot` v) -- standard transformation matricies scaleMat :: Vec3 -> Mat4 scaleMat v = diagMat $ v |: 1 translateMat :: Vec3 -> Mat4 translateMat (Vec3 x y z) = Mat4 (Vec4 1 0 0 x) (Vec4 0 1 0 y) (Vec4 0 0 1 z) (Vec4 0 0 0 1) -- rotate CCW along axis rotateMat :: Angle -> Axis -> Mat4 rotateMat angle axis = Mat4 (Vec4 (x*x + (1-x*x)*c) (x*y*(1-c) - z*s) (x*z*(1-c) + y*s) 0) (Vec4 (x*y*(1-c) + z*s) (y*y + (1-y*y)*c) (y*z*(1-c) - x*s) 0) (Vec4 (x*z*(1-c) - y*s) (y*z*(1-c) + x*s) (z*z + (1-z*z)*c) 0) (Vec4 0 0 0 1) where (Vec3 x y z) = normalize axis s = sin angle c = cos angle
shaunren/htracer
src/Math.hs
gpl-3.0
10,505
0
24
4,181
5,252
2,747
2,505
255
1
#!/usr/bin/env runhaskell -- {-# LANGUAGE CPP #-} {-| hledger-rewrite [PATTERNS] --add-posting "ACCT AMTEXPR" ... A start at a generic rewriter of journal entries. Reads the default journal and prints the entries, like print, but adds the specified postings to any entries matching PATTERNS. Examples: hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33' --add-posting '(reserve:gifts) $100' hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"' Note the single quotes to protect the dollar sign from bash, and the two spaces between account and amount. See the command-line help for more details. Currently does not work when invoked via "hledger rewrite". Tested-with: hledger HEAD ~ 2014/2/4 |-} -- hledger lib, cli and cmdargs utils import Hledger.Cli -- more utils for parsing -- #if !MIN_VERSION_base(4,8,0) -- import Control.Applicative.Compat ((<*)) -- #endif import Text.Parsec cmdmode :: Mode RawOpts cmdmode = (defCommandMode ["hledger-rewrite"]) { modeArgs = ([], Just $ argsFlag "[PATTERNS] --add-posting \"ACCT AMTEXPR\" ...") ,modeHelp = "print all journal entries, with custom postings added to the matched ones" ,modeGroupFlags = Group { groupNamed = [("Input", inputflags) ,("Reporting", reportflags) ,("Misc", helpflags) ] ,groupUnnamed = [flagReq ["add-posting"] (\s opts -> Right $ setopt "add-posting" s opts) "'ACCT AMTEXPR'" "add a posting to ACCT, which may be parenthesised. AMTEXPR is either a literal amount, or *N which means the transaction's first matched amount multiplied by N (a decimal number). Two spaces separate ACCT and AMTEXPR."] ,groupHidden = [] } } type PostingExpr = (AccountName, AmountExpr) data AmountExpr = AmountLiteral String | AmountMultiplier Quantity deriving (Show) addPostingExprsFromOpts :: RawOpts -> [PostingExpr] addPostingExprsFromOpts = map (either parseerror id . runParser (postingexprp <* eof) nullctx "") . map stripquotes . listofstringopt "add-posting" postingexprp = do a <- accountnamep spacenonewline >> many1 spacenonewline aex <- amountexprp many spacenonewline return (a,aex) amountexprp = choice [ AmountMultiplier <$> (do char '*' many spacenonewline (q,_,_,_) <- numberp return q) ,AmountLiteral <$> many anyChar ] amountExprRenderer :: Query -> AmountExpr -> (Transaction -> MixedAmount) amountExprRenderer q aex = case aex of AmountLiteral s -> mamountp' s -- either parseerror (const . mixed) $ runParser (amountp <* eof) nullctx "" s AmountMultiplier n -> (`divideMixedAmount` (1 / n)) . (`firstAmountMatching` q) where firstAmountMatching :: Transaction -> Query -> MixedAmount firstAmountMatching t q = pamount $ head $ filter (q `matchesPosting`) $ tpostings t rewriteTransaction :: Transaction -> [(AccountName, Transaction -> MixedAmount)] -> Transaction rewriteTransaction t addps = t{tpostings=tpostings t ++ map (uncurry (generatePosting t)) addps} where generatePosting :: Transaction -> AccountName -> (Transaction -> MixedAmount) -> Posting generatePosting t acct amtfn = nullposting{paccount = accountNameWithoutPostingType acct ,ptype = accountNamePostingType acct ,pamount = amtfn t ,ptransaction = Just t } main = do opts@CliOpts{rawopts_=rawopts,reportopts_=ropts} <- getCliOpts cmdmode d <- getCurrentDay let q = queryFromOpts d ropts addps = [(a, amountExprRenderer q aex) | (a, aex) <- addPostingExprsFromOpts rawopts] withJournalDo opts $ \opts j@Journal{jtxns=ts} -> do -- rewrite matched transactions let j' = j{jtxns=map (\t -> if q `matchesTransaction` t then rewriteTransaction t addps else t) ts} -- run the print command, showing all transactions print' opts{reportopts_=ropts{query_=""}} j'
kmels/hledger
extra/hledger-rewrite.hs
gpl-3.0
4,140
0
20
1,004
832
452
380
52
2
module System.DevUtils.Redis ( ) where
adarqui/DevUtils-Redis
src/System/DevUtils/Redis.hs
gpl-3.0
39
0
3
5
10
7
3
1
0
{-# LANGUAGE DerivingStrategies #-} -- | -- Module : Aura.Settings.External -- Copyright : (c) Colin Woodbury, 2012 - 2020 -- License : GPL3 -- Maintainer: Colin Woodbury <colin@fosskers.ca> -- -- A simple parser for .conf files, along with types for aura-specific config -- files. module Aura.Settings.External ( -- * Aura Config AuraConfig(..) , getAuraConf , auraConfig , defaultAuraConf -- * Parsing , Config(..) , config ) where import Aura.Languages (langFromLocale) import Aura.Settings import Aura.Types import RIO hiding (first, some, try) import qualified RIO.ByteString as BS import RIO.Directory import qualified RIO.Map as M import qualified RIO.Text as T import Text.Megaparsec hiding (single) import Text.Megaparsec.Char import qualified Text.Megaparsec.Char.Lexer as L -------------------------------------------------------------------------------- -- Aura-specific Configuration data AuraConfig = AuraConfig { acLang :: Maybe Language , acEditor :: Maybe FilePath , acUser :: Maybe User , acBuildPath :: Maybe FilePath , acASPath :: Maybe FilePath , acVCSPath :: Maybe FilePath , acAnalyse :: Maybe BuildSwitch } deriving stock (Show) defaultAuraConf :: FilePath defaultAuraConf = "/etc/aura.conf" getAuraConf :: FilePath -> IO Config getAuraConf fp = do exists <- doesFileExist fp if not exists then pure $ Config mempty else do file <- decodeUtf8Lenient <$> BS.readFile fp pure . either (const $ Config M.empty) id $ parse config "aura config" file auraConfig :: Config -> AuraConfig auraConfig (Config m) = AuraConfig { acLang = one "language" >>= langFromLocale , acEditor = T.unpack <$> one "editor" , acUser = User <$> one "user" , acBuildPath = T.unpack <$> one "buildpath" , acASPath = T.unpack <$> one "allsourcepath" , acVCSPath = T.unpack <$> one "vcspath" , acAnalyse = one "analyse" >>= readMaybe . T.unpack >>= bool (Just NoPkgbuildCheck) Nothing } where one x = M.lookup x m >>= listToMaybe -------------------------------------------------------------------------------- -- Parsing -- | The (meaningful) contents of a .conf file. newtype Config = Config (Map Text [Text]) deriving (Show) -- | Parse a `Config`. config :: Parsec Void Text Config config = do garbage cs <- some $ fmap Right (try pair) <|> fmap Left single eof pure . Config . M.fromList $ rights cs single :: Parsec Void Text () single = L.lexeme garbage . void $ manyTill letterChar newline pair :: Parsec Void Text (Text, [Text]) pair = L.lexeme garbage $ do n <- takeWhile1P Nothing (/= ' ') space void $ char '=' space rest <- T.words <$> takeWhile1P Nothing (/= '\n') pure (n, rest) -- Thu 23 Apr 2020 06:57:59 PM PDT -- Thank you me-from-the-past for documenting this. -- | All skippable content. Using `[]` as block comment markers is a trick to -- skip conf file "section" lines. garbage :: Parsec Void Text () garbage = L.space space1 (L.skipLineComment "#") (L.skipBlockComment "[" "]")
bb010g/aura
aura/lib/Aura/Settings/External.hs
gpl-3.0
3,109
0
16
655
790
431
359
68
2
----------------------------------------------------------------------------------------- {-| Module : CompileClassTypes Copyright : (c) Daan Leijen 2003, 2004 License : BSD-style Maintainer : wxhaskell-devel@lists.sourceforge.net Stability : provisional Portability : portable Module that compiles classes to class type definitions to Haskell. -} ----------------------------------------------------------------------------------------- module CompileClassTypes( compileClassTypes ) where import qualified Data.Map as Map import Data.Time( getCurrentTime) import Types import HaskellNames import Classes( isClassName, haskellClassDefs ) import DeriveTypes( ClassName ) import IOExtra {----------------------------------------------------------------------------------------- Compile -----------------------------------------------------------------------------------------} compileClassTypes :: Bool -> String -> String -> FilePath -> [FilePath] -> IO () compileClassTypes showIgnore moduleRoot moduleName outputFile inputFiles = do time <- getCurrentTime let (exportsClass,classDecls) = haskellClassDefs exportsClassClasses = exportDefs exportsClass classCount = length exportsClass export = concat [ ["module " ++ moduleRoot ++ moduleName , " ( -- * Version" , " classTypesVersion" , " -- * Classes" ] , exportsClassClasses , [ " ) where" , "" , "import " ++ moduleRoot ++ "WxcObject" , "" , "classTypesVersion :: String" , "classTypesVersion = \"" ++ show time ++ "\"" , "" ] ] prologue <- getPrologue moduleName "class" (show classCount ++ " class definitions.") inputFiles let output = unlines (prologue ++ export ++ classDecls) putStrLn ("generating: " ++ outputFile) writeFileLazy outputFile output putStrLn ("generated " ++ show classCount ++ " class definitions.") putStrLn ("ok.") {----------------------------------------------------------------------------------------- Create export definitions -----------------------------------------------------------------------------------------} exportDefs :: [(ClassName,[String])] -> [String] exportDefs classExports = let classMap = Map.fromListWith (++) classExports in concatMap exportDef (Map.toAscList classMap) where exportDef (className,exports) = [heading 2 className] ++ commaSep exports commaSep xs = map (exportComma++) xs heading i name = exportSpaces ++ "-- " ++ replicate i '*' ++ " " ++ name exportComma = exportSpaces ++ "," exportSpaces = " "
thielema/wxhaskell
wxdirect/src/CompileClassTypes.hs
lgpl-2.1
3,110
0
15
965
482
258
224
46
1
---------------------------------------------------------------------- -- | -- Module : Graphics.UI.Awesomium.UploadElement -- Copyright : (c) 2012 Maksymilian Owsianny -- License : LGPL-3 (see the file LICENSE) -- -- Maintainer : Maksymilian.Owsianny+Awesomium@gmail.com -- Stability : Experimental -- Portability : Portable? (needs FFI) -- ---------------------------------------------------------------------- module Graphics.UI.Awesomium.UploadElement ( UploadElement , isFilePath , isBytes , getBytes , getFilePath ) where import Graphics.UI.Awesomium.Raw -- | Whether or not this 'UploadElement' is a file. isFilePath :: UploadElement -> IO Bool isFilePath = awe_upload_element_is_file_path -- | Whether or not this 'UploadElement' is a string of bytes. isBytes :: UploadElement -> IO Bool isBytes = awe_upload_element_is_bytes -- | Get the string of bytes associated with this 'UploadElement'. getBytes :: UploadElement -> IO String getBytes = awe_upload_element_get_bytes -- | Get the file path associated with this 'UploadElement'. getFilePath :: UploadElement -> IO String getFilePath = awe_upload_element_get_file_path
MaxOw/awesomium
src/Graphics/UI/Awesomium/UploadElement.hs
lgpl-3.0
1,178
0
6
182
115
73
42
15
1
{-| Module : HackerRank Description : Wrapper for submodules in HackerRank License : CC BY-NC-SA 3.0 Stability : experimental Portability : POSIX Just imports & exposes all submodules. -} module HackerRank ( -- * Modules module HackerRank.Utilities ) where import HackerRank.Utilities
oopsno/hrank
src/HackerRank.hs
unlicense
303
0
5
59
19
13
6
3
0
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE JavaScriptFFI #-} {- Copyright 2019 The CodeWorld Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Blockly.DesignBlock (Type(..) ,FieldType(..) ,BlockType(..) ,Input(..) ,Field(..) ,Inline(..) ,Connection(..) ,DesignBlock(..) ,Color(..) ,Tooltip(..) ,setBlockType) where import GHCJS.Types import Data.JSString.Text import GHCJS.Marshal import GHCJS.Foreign hiding (Number, String, Function) import GHCJS.Foreign.Callback import Data.Monoid import Control.Monad import Data.Ord (comparing) import Data.List (maximumBy) import qualified Data.Text as T import Data.Maybe (fromJust) import Data.List (intercalate) import qualified Blockly.TypeExpr as TE import qualified JavaScript.Array as JA import Blockly.Block as B pack = textToJSString unpack = textFromJSString -- Low level bindings to construction of various different type of Blockly -- blocks data ADT = Product String [Type] | Sum [ADT] data User = User String ADT instance Show User where show (User name adt) = name data Type = Arrow [Type] | Number | Str -- Actually Text | Truth | Picture | Col -- Actually Color | List Type -- Have to define kinded types | Custom User | Poly T.Text | Program -- For top level blocks | Comment instance Show Type where show Number = "Number" show Picture = "Picture" show (Custom (User name adt)) = name show (Poly c) = T.unpack c show (Str) = "Text" show (Truth) = "Truth" show (Col) = "Color" show (Comment) = "" show (Program) = "Program" show (Arrow tps) = intercalate " -> " $ map show tps data FieldType = LeftField | RightField | CentreField data Input = Value T.Text [Field] -- | Statement T.Text [Field] Type | Dummy [Field] data Field = Text T.Text | TextE T.Text -- Emphasized Text, for titles | TextInput T.Text T.Text -- displayname, value | FieldImage T.Text Int Int -- src, width, height data Connection = TopCon | BotCon | TopBotCon | LeftCon newtype Inline = Inline Bool -- Name functionName inputs connectiontype color outputType tooltip -- name funcName data BlockType = Literal T.Text | Function T.Text [Type] | Top T.Text [Type] | None -- do nothing ! -- DesignBlock name type inputs isInline Color Tooltip data DesignBlock = DesignBlock T.Text BlockType [Input] Inline Color Tooltip newtype Color = Color Int newtype Tooltip = Tooltip T.Text fieldCode :: FieldInput -> Field -> IO FieldInput fieldCode field (Text str) = js_appendTextField field (pack str) fieldCode field (TextE str) = js_appendTextFieldEmph field (pack str) fieldCode field (TextInput text name) = js_appendTextInputField field (pack text) (pack name) fieldCode field (FieldImage src width height) = js_appendFieldImage field (pack src) width height inputCode :: Bool -> Block -> Input -> IO () inputCode rightAlign block (Dummy fields) = do fieldInput <- js_appendDummyInput block when rightAlign $ js_setAlignRight fieldInput foldr (\ field fi -> do fi_ <- fi fieldCode fi_ field) (return fieldInput) fields return () inputCode rightAlign block (Value name fields) = do fieldInput <- js_appendValueInput block (pack name) when rightAlign $ js_setAlignRight fieldInput foldr (\ field fi -> do fi_ <- fi fieldCode fi_ field) (return fieldInput) fields return () typeToTypeExpr :: Type -> TE.Type_ typeToTypeExpr (Poly a) = TE.createType $ TE.TypeVar a typeToTypeExpr t = TE.createType $ TE.Lit (T.pack $ show t ) [] -- Currently still a hack -- set block setBlockType :: DesignBlock -> IO () setBlockType (DesignBlock name blockType inputs (Inline inline) (Color color) (Tooltip tooltip) ) = do cb <- syncCallback1 ContinueAsync (\this -> do let block = B.Block this js_setColor block color forM_ (zip inputs (False : repeat True)) $ \(inp, rightAlign) -> do inputCode rightAlign block inp case blockType of None -> js_disableOutput block Top _ _ -> js_disableOutput block _ -> js_enableOutput block assignBlockType block blockType when inline $ js_setInputsInline block True return () ) js_setGenFunction (pack name) cb typeToType :: Type -> TE.Type typeToType (Poly a) = TE.TypeVar a typeToType lit = TE.Lit (T.pack $ show lit) [] assignBlockType :: Block -> BlockType -> IO () assignBlockType block (Literal name) = B.setAsLiteral block name assignBlockType block (Function name tps) = do js_defineFunction (pack name) (TE.fromList tp) B.setAsFunction block name where tp = map typeToType tps assignBlockType block (Top name tps) = assignBlockType block (Function name tps) assignBlockType _ _ = return () newtype FieldInput = FieldInput JSVal -- setArrows :: Block -> [Type] -> IO () -- setArrows block tps = js_setArrows block typeExprs -- where -- typeExprs = TE.toJSArray $ map typeToTypeExpr tps foreign import javascript unsafe "Blockly.Blocks[$1] = { init: function() { $2(this); }}" js_setGenFunction :: JSString -> Callback a -> IO () foreign import javascript unsafe "$1.setColour($2)" js_setColor :: Block -> Int -> IO () foreign import javascript unsafe "$1.setOutput(true)" js_enableOutput :: Block -> IO () foreign import javascript unsafe "$1.setOutput(false)" js_disableOutput:: Block -> IO () foreign import javascript unsafe "$1.setTooltip($2)" js_setTooltip :: Block -> JSString -> IO () foreign import javascript unsafe "$1.appendDummyInput()" js_appendDummyInput :: Block -> IO FieldInput foreign import javascript unsafe "Blockly.TypeInf.defineFunction($1, $2)" js_defineFunction :: JSString -> TE.Type_ -> IO () foreign import javascript unsafe "$1.appendValueInput($2)" js_appendValueInput :: Block -> JSString -> IO FieldInput foreign import javascript unsafe "$1.appendField($2)" js_appendTextField :: FieldInput -> JSString -> IO FieldInput foreign import javascript unsafe "$1.appendField(new Blockly.FieldLabel($2, 'blocklyTextEmph'))" js_appendTextFieldEmph :: FieldInput -> JSString -> IO FieldInput foreign import javascript unsafe "$1.appendField(new Blockly.FieldImage($2, $3, $4))" js_appendFieldImage:: FieldInput -> JSString -> Int -> Int -> IO FieldInput foreign import javascript unsafe "$1.appendField(new Blockly.FieldTextInput($2), $3)" js_appendTextInputField :: FieldInput -> JSString -> JSString -> IO FieldInput foreign import javascript unsafe "$1.setCheck($2)" js_setCheck :: FieldInput -> JSString -> IO () foreign import javascript unsafe "$1.setAlign(Blockly.ALIGN_RIGHT)" js_setAlignRight :: FieldInput -> IO () foreign import javascript unsafe "$1.setInputsInline($2)" js_setInputsInline :: Block -> Bool -> IO ()
pranjaltale16/codeworld
funblocks-client/src/Blockly/DesignBlock.hs
apache-2.0
8,059
46
20
2,129
1,948
1,020
928
153
3
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-} module Mdb.Database.Album ( Album(..) ) where import Database.SQLite.Simple ( FromRow(..), field ) import Data.Aeson import Data.JSON.Schema ( JSONSchema(..), gSchema ) import qualified Data.Text as T import Generics.Generic.Aeson import GHC.Generics import Mdb.Types data Album = Album { albumId :: ! AlbumId , albumName :: ! T.Text , albumPoster :: Maybe FileId , fileCount :: ! Int } deriving ( Generic, Show ) instance FromRow Album where fromRow = Album <$> field <*> field <*> field <*> field instance ToJSON Album where toJSON = gtoJson instance FromJSON Album where parseJSON = gparseJson instance JSONSchema Album where schema = gSchema
waldheinz/mdb
src/lib/Mdb/Database/Album.hs
apache-2.0
819
6
9
225
205
123
82
30
0
-- | Simple abstraction for message digests {-# LANGUAGE TypeSynonymInstances, CPP #-} module Digest ( Digest , digest , digestBS ) where import Control.DeepSeq () import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Crypto.Hash.SHA1 as SHA1 -- Consider newtyping this type Digest = B.ByteString #if ! MIN_VERSION_bytestring(0,10,0) -- instance was introduced instance NFData Digest #endif digest :: L.ByteString -> B.ByteString digest bs = {-# SCC "sha1_digest" #-} SHA1.hashlazy bs digestBS :: B.ByteString -> B.ByteString digestBS bs = digest . L.fromChunks $ [bs]
rethab/combinatorrent
src/Digest.hs
bsd-2-clause
628
0
7
101
131
81
50
15
1
-- | This module deals with git operations on an application's repository. module Handler.TApplication.Git( pullChanges , clone ) where import Control.Monad (when) import qualified Data.Conduit as C import qualified Data.Conduit.Binary as CB import Data.Conduit.Process import qualified Data.Text as T import Import import Prelude import System.Directory (doesDirectoryExist) import System.IO --os filesystem import Database.Redis import Tersus.DataTypes.TApplication import Tersus.DataTypes.TFile(mkTFileFromPath) import Tersus.Database import Tersus.Debug import Tersus.Filesystem import Tersus.HandlerMachinery tApplicationDirectory :: TApplication -> String tApplicationDirectory tapp = fullStrPath $ [apps_dir,identifier tapp] -- TODO: implement repositoryExists :: TApplication -> IO Bool repositoryExists tapp = do -- $(logDebug) "Checking if repository exists.." exists <- doesDirectoryExist . tApplicationDirectory $ tapp -- $(logDebug) "Repository exists:" ++ show exists return exists -- TODO: implemento pullChanges :: Connection -> TApplication -> IO () pullChanges conn tapp = do debugM $ "Pulling changes.." repoExists <- repositoryExists tapp when (not repoExists) $ do verboseM "Repository doesn't exist, cloning.." clone conn tapp when (repoExists) $ do verboseM "Repository exists, pulling.." pull tapp return () -- TODO: implement clone :: Connection -> TApplication -> IO () clone conn tapp = do C.runResourceT $ do -- liftIO $(logDebug) "Cloning repository.." let repoUrl' = T.unpack . repositoryUrl $ tapp cloneCmd = "git clone --quiet " ++ repoUrl' ++ " " ++ tApplicationDirectory tapp -- $(logDebug) "Spawning: " ++ cloneCmd sourceCmd cloneCmd C.$$ CB.sinkHandle stdout fid <- mkTFileFromPath conn (apps_dir:[identifier tapp]) debugM $ " Created file id " ++ show fid return () pull :: TApplication -> IO () pull tapp = do debugM $ pullCmd C.runResourceT $ sourceCmd pullCmd C.$$ CB.sinkHandle stdout where repoName = T.unpack . identifier $ tapp pullCmd = "cd "++ tApplicationDirectory tapp ++ "; git pull"
kmels/tersus
Handler/TApplication/Git.hs
bsd-2-clause
2,293
0
15
533
532
274
258
52
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Controller ( withMySite , withDevelApp ) where import MySite import Settings import Yesod.Helpers.Static import Yesod.Helpers.Auth import Database.Persist.GenericSql import Data.ByteString (ByteString) import Data.Dynamic (Dynamic, toDyn) -- Import all relevant handler modules here. import Handler.Root -- This line actually creates our YesodSite instance. It is the second half -- of the call to mkYesodData which occurs in MySite.hs. Please see -- the comments there for more details. mkYesodDispatch "MySite" resourcesMySite -- Some default handlers that ship with the Yesod site template. You will -- very rarely need to modify this. getFaviconR :: Handler () getFaviconR = sendFile "image/x-icon" "config/favicon.ico" getRobotsR :: Handler RepPlain getRobotsR = return $ RepPlain $ toContent ("User-agent: *" :: ByteString) -- This function allocates resources (such as a database connection pool), -- performs initialization and creates a WAI application. This is also the -- place to put your migrate statements to have automatic database -- migrations handled by Yesod. withMySite :: (Application -> IO a) -> IO a withMySite f = Settings.withConnectionPool $ \p -> do runConnectionPool (runMigration migrateAll) p let h = MySite s p toWaiApp h >>= f where s = static Settings.staticdir withDevelApp :: Dynamic withDevelApp = toDyn (withMySite :: (Application -> IO ()) -> IO ())
Tarrasch/Recipe-Site
Controller.hs
bsd-2-clause
1,577
0
12
256
267
148
119
28
1
module Language.Brainfuck.Syntax where data Stmt = IncPtr | DecPtr | IncData | DecData | Output | Input | While Program deriving Show type Program = [Stmt]
gergoerdi/brainfuck
language-brainfuck/src/Language/Brainfuck/Syntax.hs
bsd-3-clause
252
0
6
122
46
30
16
10
0
-- | Source file location annotations for reporting module SrcLoc ( SrcLoc, srcFile, srcLine, srcCol , beforeLoc , rangeLoc , startLoc , incrLoc , sameLine , noLoc , hasLoc , Loc(..) , srcLoc, unLoc , HasLoc(..) ) where import Data.Maybe import Data.Monoid import Pretty -- Pull in definition of SrcLoc import Gen.SrcLoc -- !See definition of Loc in srcLoc.duck srcLoc :: Loc a -> SrcLoc srcLoc (L l _) = l unLoc (L _ x) = x instance Functor Loc where fmap f (L l x) = L l (f x) showOff :: Int -> String -> String showOff 0 = ('$':) showOff n | n < 0 = ('$':) . shows (negate n) | otherwise = shows n instance Show SrcLoc where showsPrec _ (SrcNone "") = showString "<unknown>" showsPrec _ (SrcNone s) = showString s showsPrec _ (SrcLoc file line col) = (file++) . (':':) . showOff line . (':':) . showOff col showsPrec _ (SrcRng file line col line' col') | line == line' = (file++) . (':':) . showOff line . (':':) . showOff col . ('-':) . showOff col' | otherwise = (file++) . (':':) . showOff line . (':':) . showOff col . ('-':) . showOff line' . (':':) . showOff col' -- By default, locations drop away when printing instance Show t => Show (Loc t) where show (L _ x) = show x instance Pretty t => Pretty (Loc t) where pretty' (L _ x) = pretty' x class HasLoc a where loc :: a -> SrcLoc maybeLoc :: a -> Maybe SrcLoc loc = fromMaybe noLoc . maybeLoc maybeLoc a = if hasLoc l then Just l else Nothing where l = loc a instance HasLoc SrcLoc where loc = id instance HasLoc (Loc a) where loc = srcLoc instance HasLoc a => HasLoc [a] where loc = mconcat . map loc instance Pretty SrcLoc where pretty l | hasLoc l = pretty (show l) | otherwise = pretty () -- |The location immediately before another beforeLoc :: SrcLoc -> SrcLoc beforeLoc l@(SrcNone _) = l beforeLoc (SrcLoc f l 1) = SrcLoc f (pred l) 0 beforeLoc (SrcLoc f l c) = SrcLoc f l (pred c) beforeLoc (SrcRng f l c _ _) = beforeLoc (SrcLoc f l c) startLoc :: String -> SrcLoc startLoc file = SrcLoc file 1 1 incrLoc :: SrcLoc -> Char -> SrcLoc incrLoc (SrcLoc f l _) '\n' = SrcLoc f (l+1) 1 incrLoc (SrcLoc f l c) '\t' = SrcLoc f l (1 + 8 * div (c+7) 8) incrLoc (SrcLoc f l c) _ = SrcLoc f l (c+1) incrLoc _ _ = error "incrLoc works only on SrcLoc, not SrcNone or SrcRng" sameLine :: SrcLoc -> SrcLoc -> Bool sameLine s t = srcLine s == srcLine t joinFile :: String -> String -> String joinFile "" s = s joinFile s _ = s {- this is probably too slow to be worth it: joinFile s "" = s joinFile s1 s2 = s1 | s1 == s2 = s1 | otherwise = s1 ++ ';' : s2 -} joinLocs :: SrcLoc -> String -> Int -> Int -> SrcLoc joinLocs (SrcNone s1) s2 r2 c2 = SrcLoc (joinFile s1 s2) r2 c2 joinLocs l s2 r2 c2 | srcLine l == r2 && srcCol l == c2 = SrcLoc s r2 c2 | otherwise = SrcRng s (srcLine l) (srcCol l) r2 c2 where s = joinFile (srcFile l) s2 setFile :: SrcLoc -> String -> SrcLoc setFile (SrcNone _) f = SrcNone f setFile (SrcLoc _ r c) f = SrcLoc f r c setFile (SrcRng _ r c r2 c2) f = SrcRng f r c r2 c2 instance Monoid SrcLoc where mempty = SrcNone "" mappend (SrcNone s) l = setFile l (joinFile s (srcFile l)) mappend l (SrcNone s) = setFile l (joinFile (srcFile l) s) mappend l (SrcLoc s2 r2 c2) = joinLocs l s2 r2 c2 mappend l (SrcRng s2 _ _ r2 c2) = joinLocs l s2 r2 c2 rangeLoc :: SrcLoc -> SrcLoc -> SrcLoc rangeLoc l = mappend l . beforeLoc noLoc :: SrcLoc noLoc = mempty hasLoc :: SrcLoc -> Bool hasLoc (SrcNone "") = False hasLoc _ = True {- srcRng :: SrcLoc -> SrcLoc -> SrcLoc srcRng = mappend srcLocStart :: SrcLoc -> SrcLoc srcLocStart (SrcRng s r c _ _) = SrcLoc s r c srcLocStart l = l srcLocEnd :: SrcLoc -> SrcLoc srcLocEnd (SrcRng s _ _ r c) = SrcLoc s r c srcLocEnd l = l -}
girving/duck
duck/SrcLoc.hs
bsd-3-clause
3,766
0
15
890
1,576
799
777
90
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE OverloadedStrings #-} import Data.Maybe (fromJust) import Test.Tasty import Test.Tasty.HUnit import qualified Test.Tasty.QuickCheck as QC import Network.Multiaddr instance QC.Arbitrary IPv4Addr where arbitrary = fromBytes <$> QC.arbitrary instance QC.Arbitrary IPv6Addr where arbitrary = do (a, b, c, d) <- QC.arbitrary (e, f, g, h) <- QC.arbitrary pure (fromPieces (a, b, c, d, e, f, g, h)) ipv4Tests :: TestTree ipv4Tests = testGroup "IPv4" [ QC.testProperty "round trips" $ \ipv4 -> readIPv4Addr (toText (ipv4 :: IPv4Addr)) == Just ipv4 , testCase "parses and formats sample IPs" $ mapM_ (\t -> toText (fromJust (readIPv4Addr t)) @?= t) [ "0.0.0.0" , "0.0.0.1" , "1.1.1.1" , "127.0.0.1" , "192.168.1.1" , "255.255.255.0" , "255.255.255.255" ] , testCase "fails to parse bad IPs" $ mapM_ (\t -> readIPv4Addr t @?= Nothing) [ "" , "foo" , "..." , "127 0 0 1" , "1 27.0.0.1" , "256.0.0.0" , "-1.0.0.0" , "1.2.3.4.5" , "1.2.3.ff" ] , testCase "Bounded instance" $ do (minBound :: IPv4Addr) @?= IPv4Addr 0 (maxBound :: IPv4Addr) @?= IPv4Addr 0xFFFFFFFF ] ipv6Tests :: TestTree ipv6Tests = testGroup "IPv6" [ testCase "parses sample IPs" $ do readIPv6Addr "::" @?= Just (IPv6Addr 0 0 0 0) readIPv6Addr "::1" @?= Just (IPv6Addr 0 0 0 1) readIPv6Addr "::2" @?= Just (IPv6Addr 0 0 0 2) readIPv6Addr "::ffff" @?= Just (IPv6Addr 0 0 0 0xFFFF) readIPv6Addr "::ff:ffff" @?= Just (IPv6Addr 0 0 0 0xFFFFFF) readIPv6Addr "::ffff:ffff" @?= Just (IPv6Addr 0 0 0 0xFFFFFFFF) readIPv6Addr "2001:0DB8:AC10:FE01:0000:0000:0000:0000" @?= Just (IPv6Addr 0x20010DB8 0xAC10FE01 0 0) readIPv6Addr "2001:0DB8:AC10:FE01:0:0:0:0" @?= Just (IPv6Addr 0x20010DB8 0xAC10FE01 0 0) readIPv6Addr "2001:db8:ac10:fe01::" @?= Just (IPv6Addr 0x20010DB8 0xAC10FE01 0 0) , testCase "round trips RFC 5952 IPs" $ mapM_ (\t -> toText (fromJust (readIPv6Addr t)) @?= t) [ "::" , "::1" , "::1:1" , "1::" , "1::1" , "1::1:1" , "2001:db8:85a3:8d3:1319:8a2e:370:7348" ] , QC.testProperty "round trips arbitrary IPs" $ \ip -> readIPv6Addr (toText (ip :: IPv6Addr)) == Just ip , testCase "Bounded instance" $ do (minBound :: IPv6Addr) @?= IPv6Addr 0 0 0 0 (maxBound :: IPv6Addr) @?= IPv6Addr 0xFFFFFFFF 0xFFFFFFFF 0xFFFFFFFF 0xFFFFFFFF ] multiaddrTests :: TestTree multiaddrTests = testGroup "multiaddr" [ testCase "round trips sample multiaddrs via text" $ mapM_ (\t -> toText (fromJust (readMultiaddr t)) @?= t) [ "" , "/ip4/127.0.0.1" , "/ip4/127.0.0.1/tcp/80" , "/ip4/127.0.0.1/http" , "/ip4/127.0.0.1/dccp/49" , "/ip4/127.0.0.1/sctp/49" , "/ip4/127.0.0.1/tcp/80/ip6/::1" , "/ip4/127.0.0.1/tcp/80/ip6/::1/udp/1234" , "/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC" , "/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234" , "/ip4/8.4.203.49/udp/40/udt" , "/ip4/8.4.203.49/udp/40/utp" ] , testCase "round trips sample multiaddrs via binary" $ mapM_ (\t -> let ma = fromJust (readMultiaddr t) in fromJust (decode (encode ma)) @?= ma) [ "" , "/ip4/127.0.0.1" , "/ip4/127.0.0.1/http" , "/ip4/127.0.0.1/dccp/49" , "/ip4/127.0.0.1/sctp/49" , "/ip4/127.0.0.1/tcp/80" , "/ip4/127.0.0.1/tcp/80/ip6/::1" , "/ip4/127.0.0.1/tcp/80/ip6/::1/udp/1234" , "/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC" , "/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234" , "/ip4/8.4.203.49/udp/40/udt" , "/ip4/8.4.203.49/udp/40/utp" ] , testCase "protocolNames" $ mapM_ (\(ma, ps) -> protocolNames (fromJust (readMultiaddr ma)) @?= ps) [ ("", []) , ("/ip4/127.0.0.1", ["ip4"]) , ("/ip4/127.0.0.1/dccp/49", ["ip4", "dccp"]) , ("/ip4/127.0.0.1/sctp/49", ["ip4", "sctp"]) , ("/ip4/127.0.0.1/tcp/80", ["ip4", "tcp"]) , ("/ip4/127.0.0.1/http", ["ip4", "http"]) , ("/ip4/127.0.0.1/tcp/80/ip6/::1", ["ip4", "tcp", "ip6"]) , ("/ip4/127.0.0.1/tcp/80/ip6/::1/udp/1234", ["ip4", "tcp", "ip6", "udp"]) , ("/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", ["ipfs"]) , ("/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234", ["ipfs", "tcp"]) , ("/ip4/8.4.203.49/udp/40/udt", ["ip4", "udp", "udt"]) , ("/ip4/8.4.203.49/udp/40/utp", ["ip4", "udp", "utp"]) ] ] tests :: TestTree tests = testGroup "Network.Multiaddr" [ipv4Tests, ipv6Tests, multiaddrTests] main :: IO () main = defaultMain tests
micxjo/hs-multiaddr
test/test.hs
bsd-3-clause
4,727
0
18
1,047
1,240
678
562
120
1
module Text.MPretty ( module Text.MPretty.IsPretty , module Text.MPretty.MonadPretty , module Text.MPretty.Pretty , module Text.MPretty.StateSpace ) where import Text.MPretty.IsPretty import Text.MPretty.MonadPretty import Text.MPretty.Pretty import Text.MPretty.StateSpace
davdar/mpretty
Text/MPretty.hs
bsd-3-clause
285
0
5
35
60
41
19
9
0
module Sexy.Instances.Eq.Maybe () where import Sexy.Classes (Eq(..), BoolC(..)) import Sexy.Data (Maybe(..)) import Sexy.Instances.BoolC.Bool () instance (Eq a) => Eq (Maybe a) where Nothing == Nothing = true Just x == Just y = x == y _ == _ = false
DanBurton/sexy
src/Sexy/Instances/Eq/Maybe.hs
bsd-3-clause
273
0
7
64
122
69
53
8
0
{-# LANGUAGE TemplateHaskell #-} module EFA.Test.Utility where import EFA.Utility (pairs, yazf) import Test.QuickCheck (Property, (==>)) import Test.QuickCheck.All (quickCheckAll) prop_dmap :: Eq a => [a] -> Property prop_dmap xs = length xs > 0 ==> yazf (,) xs xs == pairs xs runTests :: IO Bool runTests = $quickCheckAll
energyflowanalysis/efa-2.1
test/EFA/Test/Utility.hs
bsd-3-clause
329
0
8
54
116
65
51
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Distributed.Process.Platform.Internal.Primitives -- Copyright : (c) Tim Watson 2013, Parallel Scientific (Jeff Epstein) 2012 -- License : BSD3 (see the file LICENSE) -- -- Maintainers : Jeff Epstein, Tim Watson -- Stability : experimental -- Portability : non-portable (requires concurrency) -- -- This module provides a set of additional primitives that add functionality -- to the basic Cloud Haskell APIs. ----------------------------------------------------------------------------- module Control.Distributed.Process.Platform.Internal.Primitives ( -- * General Purpose Process Addressing Addressable , Routable(..) , Resolvable(..) , Linkable(..) , Killable(..) -- * Spawning and Linking , spawnSignalled , spawnLinkLocal , spawnMonitorLocal , linkOnFailure -- * Registered Processes , whereisRemote , whereisOrStart , whereisOrStartRemote -- * Selective Receive/Matching , matchCond , awaitResponse -- * General Utilities , times , monitor , awaitExit , isProcessAlive , forever' , deliver -- * Remote Table , __remoteTable ) where import Control.Concurrent (myThreadId, throwTo) import Control.Distributed.Process hiding (monitor) import qualified Control.Distributed.Process as P (monitor) import Control.Distributed.Process.Closure (seqCP, remotable, mkClosure) import Control.Distributed.Process.Serializable (Serializable) import Control.Distributed.Process.Platform.Internal.Types ( Addressable , Linkable(..) , Killable(..) , Resolvable(..) , Routable(..) , RegisterSelf(..) , ExitReason(ExitOther) , whereisRemote ) import Control.Monad (void) import Data.Maybe (isJust, fromJust) -- utility -- | Monitor any @Resolvable@ object. -- monitor :: Resolvable a => a -> Process (Maybe MonitorRef) monitor addr = do mPid <- resolve addr case mPid of Nothing -> return Nothing Just p -> return . Just =<< P.monitor p awaitExit :: Resolvable a => a -> Process () awaitExit addr = do mPid <- resolve addr case mPid of Nothing -> return () Just p -> do mRef <- P.monitor p receiveWait [ matchIf (\(ProcessMonitorNotification r p' _) -> r == mRef && p == p') (\_ -> return ()) ] deliver :: (Addressable a, Serializable m) => m -> a -> Process () deliver = flip sendTo isProcessAlive :: ProcessId -> Process Bool isProcessAlive pid = getProcessInfo pid >>= \info -> return $ info /= Nothing -- | Apply the supplied expression /n/ times times :: Int -> Process () -> Process () n `times` proc = runP proc n where runP :: Process () -> Int -> Process () runP _ 0 = return () runP p n' = p >> runP p (n' - 1) -- | Like 'Control.Monad.forever' but sans space leak forever' :: Monad m => m a -> m b forever' a = let a' = a >> a' in a' {-# INLINE forever' #-} -- spawning, linking and generic server startup -- | Spawn a new (local) process. This variant takes an initialisation -- action and a secondary expression from the result of the initialisation -- to @Process ()@. The spawn operation synchronises on the completion of the -- @before@ action, such that the calling process is guaranteed to only see -- the newly spawned @ProcessId@ once the initialisation has successfully -- completed. spawnSignalled :: Process a -> (a -> Process ()) -> Process ProcessId spawnSignalled before after = do (sigStart, recvStart) <- newChan (pid, mRef) <- spawnMonitorLocal $ do initProc <- before sendChan sigStart () after initProc receiveWait [ matchIf (\(ProcessMonitorNotification ref _ _) -> ref == mRef) (\(ProcessMonitorNotification _ _ dr) -> die $ ExitOther (show dr)) , matchChan recvStart (\() -> return pid) ] -- | Node local version of 'Control.Distributed.Process.spawnLink'. -- Note that this is just the sequential composition of 'spawn' and 'link'. -- (The "Unified" semantics that underlies Cloud Haskell does not even support -- a synchronous link operation) spawnLinkLocal :: Process () -> Process ProcessId spawnLinkLocal p = do pid <- spawnLocal p link pid return pid -- | Like 'spawnLinkLocal', but monitors the spawned process. -- spawnMonitorLocal :: Process () -> Process (ProcessId, MonitorRef) spawnMonitorLocal p = do pid <- spawnLocal p ref <- P.monitor pid return (pid, ref) -- | CH's 'link' primitive, unlike Erlang's, will trigger when the target -- process dies for any reason. This function has semantics like Erlang's: -- it will trigger 'ProcessLinkException' only when the target dies abnormally. -- linkOnFailure :: ProcessId -> Process () linkOnFailure them = do us <- getSelfPid tid <- liftIO $ myThreadId void $ spawnLocal $ do callerRef <- P.monitor us calleeRef <- P.monitor them reason <- receiveWait [ matchIf (\(ProcessMonitorNotification mRef _ _) -> mRef == callerRef) -- nothing left to do (\_ -> return DiedNormal) , matchIf (\(ProcessMonitorNotification mRef' _ _) -> mRef' == calleeRef) (\(ProcessMonitorNotification _ _ r') -> return r') ] case reason of DiedNormal -> return () _ -> liftIO $ throwTo tid (ProcessLinkException us reason) -- | Returns the pid of the process that has been registered -- under the given name. This refers to a local, per-node registration, -- not @global@ registration. If that name is unregistered, a process -- is started. This is a handy way to start per-node named servers. -- whereisOrStart :: String -> Process () -> Process ProcessId whereisOrStart name proc = do mpid <- whereis name case mpid of Just pid -> return pid Nothing -> do caller <- getSelfPid pid <- spawnLocal $ do self <- getSelfPid register name self send caller (RegisterSelf,self) () <- expect proc ref <- P.monitor pid ret <- receiveWait [ matchIf (\(ProcessMonitorNotification aref _ _) -> ref == aref) (\(ProcessMonitorNotification _ _ _) -> return Nothing), matchIf (\(RegisterSelf,apid) -> apid == pid) (\(RegisterSelf,_) -> return $ Just pid) ] case ret of Nothing -> whereisOrStart name proc Just somepid -> do unmonitor ref send somepid () return somepid registerSelf :: (String, ProcessId) -> Process () registerSelf (name,target) = do self <- getSelfPid register name self send target (RegisterSelf, self) () <- expect return () $(remotable ['registerSelf]) -- | A remote equivalent of 'whereisOrStart'. It deals with the -- node registry on the given node, and the process, if it needs to be started, -- will run on that node. If the node is inaccessible, Nothing will be returned. -- whereisOrStartRemote :: NodeId -> String -> Closure (Process ()) -> Process (Maybe ProcessId) whereisOrStartRemote nid name proc = do mRef <- monitorNode nid whereisRemoteAsync nid name res <- receiveWait [ matchIf (\(WhereIsReply label _) -> label == name) (\(WhereIsReply _ mPid) -> return (Just mPid)), matchIf (\(NodeMonitorNotification aref _ _) -> aref == mRef) (\(NodeMonitorNotification _ _ _) -> return Nothing) ] case res of Nothing -> return Nothing Just (Just pid) -> unmonitor mRef >> return (Just pid) Just Nothing -> do self <- getSelfPid sRef <- spawnAsync nid ($(mkClosure 'registerSelf) (name,self) `seqCP` proc) ret <- receiveWait [ matchIf (\(NodeMonitorNotification ref _ _) -> ref == mRef) (\(NodeMonitorNotification _ _ _) -> return Nothing), matchIf (\(DidSpawn ref _) -> ref==sRef ) (\(DidSpawn _ pid) -> do pRef <- P.monitor pid receiveWait [ matchIf (\(RegisterSelf, apid) -> apid == pid) (\(RegisterSelf, _) -> do unmonitor pRef send pid () return $ Just pid), matchIf (\(NodeMonitorNotification aref _ _) -> aref == mRef) (\(NodeMonitorNotification _aref _ _) -> return Nothing), matchIf (\(ProcessMonitorNotification ref _ _) -> ref==pRef) (\(ProcessMonitorNotification _ _ _) -> return Nothing) ] ) ] unmonitor mRef case ret of Nothing -> whereisOrStartRemote nid name proc Just pid -> return $ Just pid -- advanced messaging/matching -- | An alternative to 'matchIf' that allows both predicate and action -- to be expressed in one parameter. matchCond :: (Serializable a) => (a -> Maybe (Process b)) -> Match b matchCond cond = let v n = (isJust n, fromJust n) res = v . cond in matchIf (fst . res) (snd . res) -- | Safe (i.e., monitored) waiting on an expected response/message. awaitResponse :: Addressable a => a -> [Match (Either ExitReason b)] -> Process (Either ExitReason b) awaitResponse addr matches = do mPid <- resolve addr case mPid of Nothing -> return $ Left $ ExitOther "UnresolvedAddress" Just p -> do mRef <- P.monitor p receiveWait ((matchRef mRef):matches) where matchRef :: MonitorRef -> Match (Either ExitReason b) matchRef r = matchIf (\(ProcessMonitorNotification r' _ _) -> r == r') (\(ProcessMonitorNotification _ _ d) -> do return (Left (ExitOther (show d))))
haskell-distributed/distributed-process-platform
src/Control/Distributed/Process/Platform/Internal/Primitives.hs
bsd-3-clause
10,705
0
28
3,246
2,596
1,341
1,255
199
4
module Data.HashPSQ.Tests ( tests ) where import Prelude hiding (lookup) import Test.Framework (Test) import Test.Framework.Providers.HUnit (testCase) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck (Property, arbitrary, forAll, NonNegative(NonNegative)) import Test.HUnit (Assertion, assert) import Data.HashPSQ.Internal import qualified Data.OrdPSQ as OrdPSQ import Data.PSQ.Class.Gen import Data.PSQ.Class.Util -------------------------------------------------------------------------------- -- Index of tests -------------------------------------------------------------------------------- tests :: [Test] tests = [ testCase "showBucket" test_showBucket , testCase "toBucket" test_toBucket , testProperty "unsafeLookupIncreasePriority" prop_unsafeLookupIncreasePriority , testProperty "unsafeInsertIncreasePriority" prop_unsafeInsertIncreasePriority , testProperty "unsafeInsertIncreasePriorityView" prop_unsafeInsertIncreasePriorityView , testProperty "takeMin_length" prop_takeMin_length , testProperty "takeMin_increasing" prop_takeMin_increasing , testProperty "insertWith_const" prop_insertWith_const , testProperty "insertWith_flipconst" prop_insertWith_flipconst ] -------------------------------------------------------------------------------- -- Unit tests -------------------------------------------------------------------------------- test_showBucket :: Assertion test_showBucket = assert $ length (coverShowInstance bucket) > 0 where bucket :: Bucket Int Int Char bucket = B 1 'a' OrdPSQ.empty test_toBucket :: Assertion test_toBucket = assert True -- TODO (jaspervdj) -- assert $ mkBucket (OrdPSQ.empty :: OrdPSQ.OrdPSQ Int Int Char) -------------------------------------------------------------------------------- -- Properties -------------------------------------------------------------------------------- prop_unsafeLookupIncreasePriority :: Property prop_unsafeLookupIncreasePriority = forAll arbitraryPSQ $ \t -> forAll arbitrary $ \k -> let newP = maybe 0 ((+ 1) . fst) (lookup k t) (mbPx, t') = unsafeLookupIncreasePriority k newP t expect = case mbPx of Nothing -> Nothing Just (p, x) -> Just (p + 1, x) in valid (t' :: HashPSQ LousyHashedInt Int Char) && lookup k t' == expect && lookup k t == mbPx prop_unsafeInsertIncreasePriority :: Property prop_unsafeInsertIncreasePriority = forAll arbitraryPSQ $ \t -> forAll arbitrary $ \k -> forAll arbitrary $ \x -> let prio = largerThanMaxPrio t t' = unsafeInsertIncreasePriority k prio x t in valid (t' :: HashPSQ LousyHashedInt Int Char) && lookup k t' == Just (prio, x) prop_unsafeInsertIncreasePriorityView :: Property prop_unsafeInsertIncreasePriorityView = forAll arbitraryPSQ $ \t -> forAll arbitrary $ \k -> forAll arbitrary $ \x -> let prio = largerThanMaxPrio t (mbPx, t') = unsafeInsertIncreasePriorityView k prio x t in valid (t' :: HashPSQ LousyHashedInt Int Char) && lookup k t' == Just (prio, x) && lookup k t == mbPx prop_takeMin_length :: NonNegative Int -> HashPSQ Int Int Char -> Bool prop_takeMin_length (NonNegative n) t = length (takeMin n t) <= n prop_takeMin_increasing :: NonNegative Int -> HashPSQ Int Int Char -> Bool prop_takeMin_increasing (NonNegative n) t = isSorted [p | (_, p, _) <- takeMin n t] where isSorted (x : y : zs) = x <= y && isSorted (y : zs) isSorted [_] = True isSorted [] = True prop_insertWith_const :: (Int,Int,Char) -> HashPSQ Int Int Char -> Bool prop_insertWith_const (k,p,v) t = lookup k (i1 . i2 $ t) == Just (p + 1,succ v) where i1 = insertWith (const const) k (p + 1) (succ v) i2 = insert k p v prop_insertWith_flipconst :: (Int,Int,Char) -> HashPSQ Int Int Char -> Bool prop_insertWith_flipconst (k,p,v) t = lookup k (i1 . i2 $ t) == Just (p,v) where i1 = insertWith (const $ flip const) k (p + 1) (succ v) i2 = insert k p v
ariep/psqueues
tests/Data/HashPSQ/Tests.hs
bsd-3-clause
4,669
0
19
1,356
1,142
609
533
82
3
{-| Module : Numeric.CatchingExceptions Description : Wrapper type tracking numerical exceptions Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable A wrapper type CatchingNumExceptions that tracks errors such as DivByZero instead of throwing an exception. For example, using Prelude arithmetic: @ > 1 / 1 :: CatchingNumExceptions Rational 1 % 1 > 1 / 0 :: CatchingNumExceptions Rational <no value>{![DivByZero]} @ It is currently impossible to catch exceptions for Prelude ^ and ^^ in Prelude arithmetic. The mixed-types-num power operator is correctly handled by CatchingNumExceptions: @ > let x = catchingNumExceptions 1 in 1 / x 1 % 1 > let x = catchingNumExceptions 1 in 1 / (1 - x) <no value>{![DivByZero]} > let pi100 = piBallP (prec 100) -- using aern2-mp > let x = catchingNumExceptions (pi100 - pi100) in 1 / x <no value>{?[DivByZero]} > 0 ^ (catchingNumExceptions (-1)) <no value>{![NumericalException "0^n for n < 0"]} > (-1) ^ (catchingNumExceptions (double $ -1/2)) <no value>{![NumericalException "a^b for negative a and non-integer b (a=-1, b=-0.5)"]} @ -} module Numeric.CatchingExceptions ( -- * Representation of numerical errors NumericalException(..) -- * Numerical wrapper type , CatchingNumExceptions(..), catchingNumExceptions , numEXC_maybeValue , numEXC_certainExceptions , numEXC_potentialExceptions , addCertainException, addPotentialException -- ** auxiliary functions , hasCertainException, ifCertainExceptionDie , filterNoException , gunzip, zipCatchingNumExceptionsWith -- * validity checking (eg to avoid Infinity, NaN) , CanTestValid(..), testValidity ) where -- import Prelude -- import Numeric.MixedTypes import Numeric.CatchingExceptions.Type -- import Numeric.CatchingExceptions.Lifts import Numeric.CatchingExceptions.Num () import Numeric.CatchingExceptions.MixedTypes.Conversions () import Numeric.CatchingExceptions.MixedTypes.Comparisons () import Numeric.CatchingExceptions.MixedTypes.Ring () import Numeric.CatchingExceptions.MixedTypes.Power () import Numeric.CatchingExceptions.MixedTypes.Field () import Numeric.CatchingExceptions.MixedTypes.Elementary ()
michalkonecny/num-exceptions
src/Numeric/CatchingExceptions.hs
bsd-3-clause
2,432
0
5
514
148
104
44
20
0
module Main where import Model import Tabular import Varying import Parser import System.Environment import System.IO parseArgs :: IO (FilePath, FilePath) parseArgs = do margs <- getArgs case margs of [] -> return ("input.txt", "output.txt") [input] -> return (input, "output.txt") (input:output:_) -> return (input, output) main :: IO () main = do (inputPath, outputPath) <- parseArgs minputs <- parseFile inputPath case minputs of Left err -> print err Right inputs -> do outputs <- simulateMany inputs simulate let str = prettyPrintOutputs outputs putStrLn str withFile outputPath WriteMode $ \h -> do hSetEncoding h utf8_bom hPutStr h str putStrLn $ "Results were written to " ++ outputPath
NCrashed/bmstu-aivika-tutorial-01
src/Main.hs
bsd-3-clause
775
0
16
185
260
129
131
28
3
{-# LANGUAGE TupleSections #-} module LaTeXGrapher.Plot ( plot , Plot(..) , EndMark(..) , Segments(..) , LineStyle(..) , light , dark , clip , isEmpty ) where import Data.Maybe(maybeToList) import Data.List(find,span) import Control.Applicative import Control.Arrow import Control.Monad.Instances import Data.VectorSpace import LaTeXGrapher.Math import LaTeXGrapher.Data.Context import LaTeXGrapher.Data.Markup import LaTeXGrapher.Data.Function import LaTeXGrapher.Parser.Expression data LineStyle = Light | Dark deriving (Show) data EndMark = Arrow | Closed | Open | None deriving (Show) data Plot = Plot { segments :: Segments , startMark :: EndMark , endMark :: EndMark , lineStyle :: LineStyle } | PlotPoint Point | Tick Point Point deriving (Show) data Segments = PolyLine [Point] deriving (Show) plot :: Context -> Either EvalError [Plot] plot c = plot' c <$> (fmap concat . sequence $ (apMap c plotFunction plotFunctions ++ apMap c plotMarkup markups)) plot' c ms = (axis $ minMax c) ++ ms apMap c f g = map (f c) (g c) isEmpty :: Plot -> Bool isEmpty (Plot (PolyLine []) _ _ _) = True isEmpty _ = False light :: Plot -> Plot light p = p { lineStyle = Light } dark :: Plot -> Plot dark p = p { lineStyle = Dark } axis :: MinMax -> [Plot] axis mm = concat $ f <$> [(0,0)] <*> [(1,0),(0,1)] where f a = g . clip mm . (a:) . (:[]) g ps = (light . arrows . PolyLine $ ps) : ticks ps ticks :: [Point] -> [Plot] ticks (a@(ax,ay):b@(bx,by):_) = [ Tick v p | p <- ps ] where v = perp . normalized $ b ^-^ a ps = map (fromIntegral *** fromIntegral) . filter (/= (0,0)) $ is is | abs (ax - bx) < abs (ay - by) = zip (cycle [floor ax]) (ay...by) | otherwise = zip (ax...bx) (cycle [floor ay]) a ... b = [ceiling (0.1 + min a b)..floor (max a b - 0.1)] ticks _ = [] perp (x,y) = (-y,x) totalSteps = 100 plotFunction :: Context -> Function -> Either EvalError [Plot] plotFunction c f = maybe (Left . EvalError $ "undefined function") (Right . uncurry (plotFunction' c)) (evaluatePlotFunction c f) plotFunction' :: Context -> [Double] -> (Double -> Double) -> [Plot] plotFunction' c ss f = (map dark plots) ++ ss' where plots = concatMap (clipPlot mm) pss pss = ranges Arrow xs qs xs = [(x, f x) | n <- [l..u], x <- [n / step]] step = totalSteps / (mmWidth mm) mm = minMax c l = step * (fst $ mmMin mm) u = step * (fst $ mmMax mm) qs = map (id &&& querySpecial (mmWidth mm / (1000*totalSteps)) f) $ ss ss' = map PlotPoint . filter (mm `mmContains`) . map ((,) <*> f) . map fst $ qs data SpecialEnd = SOpen | SClosed deriving (Eq, Show) data SpecialMark = SLine | SPoint deriving (Eq, Show) data Special = Special Double SpecialEnd SpecialMark SpecialEnd Double deriving (Eq, Show) querySpecial :: Double -> (Double -> Double) -> Double -> Special querySpecial e f x = Special m a mark b p where a = diff m y b = diff y p m = f (x - e) y = f x p = f (x + e) mark | abs (m - p) > 4 * e = SPoint | otherwise = SLine diff a b | abs (a - b) < 2 * e = SClosed | otherwise = SOpen ranges :: EndMark -> [Point] -> [(Double,Special)] -> [Plot] ranges _ [] _ = [] ranges em ps [] = [Plot (PolyLine ps) em Arrow Dark] ranges em ps ((a,m):ss) = as : ranges em' bs ss where (as,(em',bs)) = f m f (Special sy s _ e ey) = second ((mark e,) . h ey e) . first (p s . reverse . h sy s . reverse) . span ((< a) . fst) $ ps h y SOpen = replace (a,y) h y SClosed = replace (a,y) p sy ps = Plot (PolyLine ps) em (mark sy) Dark mark SOpen = Open mark SClosed = Closed replace :: Eq a => (a,b) -> [(a,b)] -> [(a,b)] replace p [] = [p] replace p@(a,_) ts@((b,_):ps) | a == b = p:ps | otherwise = p:ts clipPlot :: MinMax -> Plot -> [Plot] clipPlot mm (Plot (PolyLine ps) s e l) = f . split (mm `mmContains`) $ ps where f [] = [] f (ps:[]) = [Plot (PolyLine ps) s e l] f (ps:pss) = Plot (PolyLine ps) s Arrow l : h pss h [] = [] h (ps:[]) = [Plot (PolyLine ps) Arrow e l] h (ps:pps) = Plot (PolyLine ps) Arrow Arrow l : h pps clipPlot mm a@(PlotPoint p) | mm `mmContains` p = [a] | otherwise = [] split :: (a -> Bool) -> [a] -> [[a]] split f as = step as where step [] = [] step vs = let (hs,ts) = span f vs in hs : (step $ dropWhile (not . f) ts) plotMarkup :: Context -> Markup -> Either EvalError [Plot] plotMarkup c m = f <$> points c ps where (f, ps) = plotMarkup' c m points c = maybe (Left . EvalError $ "unbound markup") Right . sequence . map (evaluateEPoint c) plotMarkup' c (Points ps) = (map PlotPoint, ps) plotMarkup' c (Segment ps) = ((:[]) . nones . PolyLine, ps) plotMarkup' c (Line ps) = ((:[]) . nones . PolyLine . clip (minMax c), ps) plotMarkup' c (Secant f a b) = (const [], []) plotMarkup' c (Tangent f x) = (const [], []) plotMarkup' c (Shade f a b) = (const [], []) plotMarkup' _ _ = (const [], []) clip :: MinMax -> [Point] -> [Point] clip mm (a:b:[]) = concat $ map snd $ maybeToList $ find fst options where options = [(horz, horzLn), (vert, vertLn), (onTwo, ln)] l = mmMin mm u = mmMax mm v = b ^-^ a mm' = mm `mmSub` a l' = l ^-^ a u' = u ^-^ a horz = snd v == 0 horzLn = spany l u (snd a) vert = fst v == 0 vertLn = spanx l u (fst a) onTwo = len == 2 || len == 4 ln = head crossings' : [head $ tail crossings'] len = length crossings crossings = filter (mm' `mmContains`) [fx' (fst l'), fx' (fst u'), fy' (snd l'), fy' (snd u')] crossings' = map (^+^ a) $ take 2 crossings m = (snd v) / (fst v) fx x = m * x fy y = y / m fx' x = (x, fx x) fy' y = (fy y, y) spany (lx,ly) (ux,uy) y | inOpenInterval y ly uy = [(lx,y),(ux,y)] | otherwise = [] spanx (lx,ly) (ux,uy) x | inOpenInterval x lx ux = [(x,ly),(x,uy)] | otherwise = [] arrows :: Segments -> Plot arrows s = Plot s Arrow Arrow Light nones :: Segments -> Plot nones s = Plot s None None Light
fryguybob/LaTeXGrapher
src/LaTeXGrapher/Plot.hs
bsd-3-clause
6,489
0
15
2,011
3,246
1,726
1,520
165
5
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- A Parser monad with access to the 'DynFlags'. -- -- The 'P' monad only has access to the subset of of 'DynFlags' -- required for parsing Haskell. -- The parser for C-- requires access to a lot more of the 'DynFlags', -- so 'PD' provides access to 'DynFlags' via a 'HasDynFlags' instance. ----------------------------------------------------------------------------- module GHC.Cmm.Monad ( PD(..) , liftP ) where import GhcPrelude import Control.Monad import qualified Control.Monad.Fail as MonadFail import DynFlags import Lexer newtype PD a = PD { unPD :: DynFlags -> PState -> ParseResult a } instance Functor PD where fmap = liftM instance Applicative PD where pure = returnPD (<*>) = ap instance Monad PD where (>>=) = thenPD #if !MIN_VERSION_base(4,13,0) fail = MonadFail.fail #endif instance MonadFail.MonadFail PD where fail = failPD liftP :: P a -> PD a liftP (P f) = PD $ \_ s -> f s returnPD :: a -> PD a returnPD = liftP . return thenPD :: PD a -> (a -> PD b) -> PD b (PD m) `thenPD` k = PD $ \d s -> case m d s of POk s1 a -> unPD (k a) d s1 PFailed s1 -> PFailed s1 failPD :: String -> PD a failPD = liftP . fail instance HasDynFlags PD where getDynFlags = PD $ \d s -> POk s d
sdiehl/ghc
compiler/GHC/Cmm/Monad.hs
bsd-3-clause
1,380
0
12
314
366
203
163
33
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_HADDOCK hide #-} module Dalvik.SSA.Types ( DexFile(..), dexFileClass, dexFields, dexMethodRefs, dexConstants, dexTypes, dexClasses, dexClassAnnotation, dexMethodAnnotation, Type(..), Class(..), classStaticField, classInstanceField, classMethods, classVirtualMethods, classDirectMethods, classInstanceFields, classStaticFields, classInterfaces, Field(..), Method(..), MethodSignature, methodSignature, methodIsVirtual, methodParameters, methodBody, Parameter(..), BasicBlock(..), basicBlockSuccessors, basicBlockPredecessors, basicBlockInstructions, basicBlockTerminator, basicBlockSplitPhis, MethodRef(..), UniqueId, Value(..), IsValue(..), FromValue(..), CastException(..), Constant(..), constantId, constantType, Instruction(..), instructionOperands, InvokeDirectKind(..), InvokeVirtualKind(..), VisibleAnnotation(..), Annotation(..), AnnotationValue(..), DT.AnnotationVisibility(..), LL.CmpOp(..), LL.IfOp(..), LL.Binop(..), LL.Unop(..), LL.CType(..), module Dalvik.AccessFlags, module Dalvik.ClassName ) where import GHC.Generics ( Generic ) import Control.DeepSeq import qualified Control.Monad.Catch as E import qualified Data.ByteString.Char8 as BS import qualified Data.Foldable as F import Data.Function ( on ) import Data.Hashable import Data.HashMap.Strict ( HashMap ) import qualified Data.HashMap.Strict as HM import Data.Int ( Int64 ) import Data.List.NonEmpty ( NonEmpty ) import Data.Maybe ( fromMaybe, maybeToList ) import qualified Data.Serialize as S import qualified Data.Set as Set import Data.Typeable ( Typeable ) import Data.Vector ( Vector ) import qualified Data.Vector as V import Dalvik.AccessFlags import Dalvik.ClassName -- Low-level instructions import qualified Dalvik.Instruction as LL import qualified Dalvik.Types as DT -- | A Dalvik Dex file represented in SSA form. data DexFile = DexFile { _dexClasses :: !(Vector Class) , _dexConstants :: !(Vector Constant) , _dexTypes :: !(Vector Type) , dexIdSrc :: !Int , _dexClassesByType :: !(HashMap Type Class) , _dexClassesByName :: !(HashMap BS.ByteString Class) -- ^ An index by Class.className to the class. These are -- dotted fully-qualified names , _dexClassAnnotations :: !(HashMap Class [VisibleAnnotation]) , _dexMethodAnnotations :: !(HashMap MethodAnnotationKey (MethodRef, [VisibleAnnotation])) -- ^ See Note [Annotations] } deriving (Typeable) type MethodAnnotationKey = (Type, BS.ByteString, [Type]) -- | Look up the annotations on a 'Class' dexClassAnnotation :: DexFile -> Class -> [VisibleAnnotation] dexClassAnnotation df k = fromMaybe [] $ HM.lookup k (_dexClassAnnotations df) -- | Look up the annotations on a 'Method' dexMethodAnnotation :: DexFile -> Method -> [VisibleAnnotation] dexMethodAnnotation df m = maybe [] snd $ HM.lookup key (_dexMethodAnnotations df) where (ptypes, _) = methodSignature m key = (classType (methodClass m), methodName m, ptypes) dexFileClass :: DexFile -> Type -> Maybe Class dexFileClass df t = HM.lookup t (_dexClassesByType df) dexClasses :: DexFile -> [Class] dexClasses = V.toList . _dexClasses dexConstants :: DexFile -> [Constant] dexConstants = V.toList . _dexConstants dexTypes :: DexFile -> [Type] dexTypes = V.toList . _dexTypes data Value = InstructionV Instruction | ConstantV Constant | ParameterV Parameter instance Eq Value where (==) = (==) `on` valueId instance Ord Value where compare = compare `on` valueId instance Hashable Value where hashWithSalt s = hashWithSalt s . valueId instance NFData Value where rnf v = case v of InstructionV i -> i `deepseq` () ConstantV c -> c `deepseq` () ParameterV p -> p `deepseq` () -- | A common interface to the three 'Value'-like types. class IsValue a where valueType :: a -> Type valueId :: a -> UniqueId toValue :: a -> Value instance IsValue Value where valueId (InstructionV i) = instructionId i valueId (ConstantV c) = constantId c valueId (ParameterV p) = parameterId p valueType (InstructionV i) = instructionType i valueType (ConstantV c) = constantType c valueType (ParameterV p) = parameterType p toValue = id -- | Convenient and safe casting from 'Value' to a concrete type -- (either 'Constant', 'Instruction', or 'Parameter'). class FromValue a where fromValue :: (E.MonadThrow m) => Value -> m a data CastException = CastException String deriving (Eq, Ord, Show, Typeable) instance E.Exception CastException -- | The 'VisibleAnnotation' is a wrapper around a Java 'Annotation' -- that records the visibility of the annotation. Some annotations -- can be discarded at build time, while others are available at run -- time to the application. data VisibleAnnotation = VisibleAnnotation { annotationVisibility :: DT.AnnotationVisibility , annotationValue :: Annotation } -- | An annotation has a type (which is always a class type) and -- compile-time constant arguments. The argument language available -- is separate from the constants used in the rest of the IR. data Annotation = Annotation { annotationType :: Type -- ^ This must be a class (i.e., -- reference type); should this just be -- a ClassName? , annotationArguments :: [(BS.ByteString, AnnotationValue)] } deriving (Eq, Ord, Typeable) data AnnotationValue = AVInt !Integer | AVChar !Char | AVFloat !Float | AVDouble !Double | AVString BS.ByteString | AVType Type | AVField Field | AVMethod MethodRef | AVEnum Field | AVArray [AnnotationValue] | AVAnnotation Annotation | AVNull | AVBool !Bool deriving (Eq, Ord, Typeable) -- FIXME: For now, all numeric constants are integer types because we -- can't tell (without a type inference pass) what type a constant -- really is. Dalvik is untyped. data Constant = ConstantInt {-# UNPACK #-} !UniqueId {-# UNPACK #-} !Int64 | ConstantString {-# UNPACK #-} !UniqueId BS.ByteString | ConstantClass {-# UNPACK #-} !UniqueId Type deriving (Typeable) instance Eq Constant where (==) = (==) `on` constantId instance Ord Constant where compare = compare `on` constantId instance Hashable Constant where hashWithSalt s = hashWithSalt s . constantId instance NFData Constant where rnf c = c `seq` () constantId :: Constant -> Int constantId (ConstantInt i _) = i constantId (ConstantString i _) = i constantId (ConstantClass i _) = i constantType :: Constant -> Type constantType (ConstantString _ _) = ReferenceType (qualifiedClassName ["java", "lang"] "String") constantType (ConstantClass _ _) = ReferenceType (qualifiedClassName ["java", "lang"] "Class") constantType _ = UnknownType instance IsValue Constant where valueId = constantId valueType = constantType toValue = ConstantV instance FromValue Constant where fromValue (ConstantV c) = return c fromValue _ = E.throwM $ CastException "Not a Constant" data Type = VoidType | ByteType | ShortType | IntType | LongType | FloatType | DoubleType | CharType | BooleanType | ArrayType Type | ReferenceType ClassName | UnknownType -- ^ We use this in cases where we can't deduce a type -- during the SSA translation deriving (Eq, Ord, Read, Show, Generic) instance S.Serialize Type instance NFData Type where rnf t = case t of ReferenceType cn -> cn `seq` () _ -> () instance Hashable Type where hashWithSalt s VoidType = hashWithSalt s (1 :: Int) hashWithSalt s ByteType = hashWithSalt s (2 :: Int) hashWithSalt s ShortType = hashWithSalt s (3 :: Int) hashWithSalt s IntType = hashWithSalt s (4 :: Int) hashWithSalt s LongType = hashWithSalt s (5 :: Int) hashWithSalt s FloatType = hashWithSalt s (6 :: Int) hashWithSalt s DoubleType = hashWithSalt s (7 :: Int) hashWithSalt s CharType = hashWithSalt s (8 :: Int) hashWithSalt s BooleanType = hashWithSalt s (9 :: Int) hashWithSalt s (ArrayType t) = s `hashWithSalt` (10 :: Int) `hashWithSalt` t hashWithSalt s (ReferenceType cname) = s `hashWithSalt` (11 :: Int) `hashWithSalt` cname hashWithSalt s UnknownType = hashWithSalt s (12 :: Int) -- | A basic block containing 'Instruction's. We maintain a count of -- the phi nodes in the block so that we can efficiently slice out -- either instructions or phi nodes for separate processing. -- -- The 'basicBlockNumber' is the local identifier (within a method) of -- a 'BasicBlock'. The unique ID is unique among all 'BasicBlock's in -- the 'DexFile'. data BasicBlock = BasicBlock { basicBlockId :: {-# UNPACK #-} !UniqueId , basicBlockNumber :: {-# UNPACK #-} !Int , basicBlockPhiCount :: {-# UNPACK #-} !Int , _basicBlockInstructions :: Vector Instruction , _basicBlockSuccessors :: Vector BasicBlock , _basicBlockPredecessors :: Vector BasicBlock , basicBlockMethod :: Method } -- | The instructions in the 'BasicBlock' basicBlockInstructions :: BasicBlock -> [Instruction] basicBlockInstructions = V.toList . _basicBlockInstructions basicBlockSuccessors :: BasicBlock -> [BasicBlock] basicBlockSuccessors = V.toList . _basicBlockSuccessors basicBlockPredecessors :: BasicBlock -> [BasicBlock] basicBlockPredecessors = V.toList . _basicBlockPredecessors -- | The last non-phi instruction in the block. -- -- There is always a final non-phi instruction because we insert -- explicit control flow transfers as necessary. However, the -- returned instruction may not be a typical terminator instruction in -- some cases. See Note [Non-Empty Blocks] in Dalvik.SSA for details. basicBlockTerminator :: BasicBlock -> Instruction basicBlockTerminator bb = insns V.! (len - 1) where insns = _basicBlockInstructions bb len = V.length insns -- | Split the instructions in the 'BasicBlock' into phi nodes and the -- rest. basicBlockSplitPhis :: BasicBlock -> ([Instruction], [Instruction]) basicBlockSplitPhis bb = (V.toList v1, V.toList v2) where (v1, v2) = V.splitAt (basicBlockPhiCount bb) (_basicBlockInstructions bb) instance Eq BasicBlock where (==) = (==) `on` basicBlockId instance Ord BasicBlock where compare = compare `on` basicBlockId instance Hashable BasicBlock where hashWithSalt s = hashWithSalt s . basicBlockId instance NFData BasicBlock where rnf b = b `seq` () type UniqueId = Int data Instruction = Return { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , returnValue :: Maybe Value } | MoveException { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock } | MonitorEnter { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , monitorReference :: Value } | MonitorExit { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , monitorReference :: Value } | CheckCast { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , castReference :: Value , castType :: Type } | InstanceOf { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , instanceOfReference :: Value , instanceOfType :: Type } | ArrayLength { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , arrayReference :: Value } | NewInstance { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock } | NewArray { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , newArrayLength :: Value , newArrayContents :: Maybe [Value] } | FillArray { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , fillArrayReference :: Value , fillArrayContents :: [Int64] } | Throw { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , throwReference :: Value } | ConditionalBranch { instructionId :: {-# UNPACK #-} !UniqueId , branchTestType :: !LL.IfOp , instructionType :: Type , instructionBasicBlock :: BasicBlock , branchOperand1 :: Value , branchOperand2 :: Value , branchTarget :: BasicBlock , branchFallthrough :: BasicBlock } | UnconditionalBranch { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , branchTarget :: BasicBlock } | Switch { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , switchValue :: Value , switchTargets :: [(Int64, BasicBlock)] , switchFallthrough :: BasicBlock } | Compare { instructionId :: {-# UNPACK #-} !UniqueId , compareOperation :: !LL.CmpOp , instructionType :: Type , instructionBasicBlock :: BasicBlock , compareOperand1 :: Value , compareOperand2 :: Value } | UnaryOp { instructionId :: {-# UNPACK #-} !UniqueId , unaryOperation :: !LL.Unop , instructionType :: Type , instructionBasicBlock :: BasicBlock , unaryOperand :: Value } | BinaryOp { instructionId :: {-# UNPACK #-} !UniqueId , binaryOperation :: !LL.Binop , instructionType :: Type , instructionBasicBlock :: BasicBlock , binaryOperand1 :: Value , binaryOperand2 :: Value } | ArrayGet { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , arrayReference :: Value , arrayIndex :: Value } | ArrayPut { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , arrayReference :: Value , arrayIndex :: Value , arrayPutValue :: Value } | StaticGet { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , staticOpField :: Field } | StaticPut { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , staticOpField :: Field , staticOpPutValue :: Value } | InstanceGet { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , instanceOpReference :: Value , instanceOpField :: Field } | InstancePut { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , instanceOpReference :: Value , instanceOpField :: Field , instanceOpPutValue :: Value } | InvokeVirtual { instructionId :: {-# UNPACK #-} !UniqueId , invokeVirtualKind :: !InvokeVirtualKind , instructionType :: Type , instructionBasicBlock :: BasicBlock , invokeVirtualMethod :: MethodRef , invokeVirtualArguments :: NonEmpty Value } | InvokeDirect { instructionId :: {-# UNPACK #-} !UniqueId , invokeDirectKind :: !InvokeDirectKind , instructionType :: Type , instructionBasicBlock :: BasicBlock , invokeDirectMethod :: MethodRef , invokeDirectMethodDef :: Maybe Method , invokeDirectArguments :: [Value] } -- ^ We have to refer to the invoked method in this -- case by a Ref because it might not have a -- definition in this dex file. However, we do -- include the definition of the invoked method if -- it is available. | Phi { instructionId :: {-# UNPACK #-} !UniqueId , instructionType :: Type , instructionBasicBlock :: BasicBlock , phiValues :: [(BasicBlock, Value)] } instance Eq Instruction where (==) = (==) `on` instructionId instance Ord Instruction where compare = compare `on` instructionId instance Hashable Instruction where hashWithSalt s = hashWithSalt s . instructionId instance NFData Instruction where rnf i = i `seq` () instance IsValue Instruction where valueId = instructionId valueType = instructionType toValue = InstructionV instance FromValue Instruction where fromValue (InstructionV i) = return i fromValue _ = E.throwM $ CastException "Not an Instruction" data Parameter = Parameter { parameterId :: {-# UNPACK #-} !UniqueId , parameterIndex :: {-# UNPACK #-} !Int , parameterType :: Type , parameterName :: BS.ByteString , parameterMethod :: Method } instance Eq Parameter where (==) = (==) `on` parameterId instance Ord Parameter where compare = compare `on` parameterId instance Hashable Parameter where hashWithSalt s = hashWithSalt s . parameterId instance NFData Parameter where rnf p = parameterType p `seq` parameterName p `seq` parameterMethod p `seq` () instance IsValue Parameter where valueId = parameterId valueType = parameterType toValue = ParameterV instance FromValue Parameter where fromValue (ParameterV p) = return p fromValue _ = E.throwM $ CastException "Not a Parameter" data Method = Method { methodId :: {-# UNPACK #-} !UniqueId , methodAccessFlags :: {-# UNPACK #-} !AccessFlags , methodName :: BS.ByteString , methodReturnType :: Type , _methodParameters :: Vector Parameter , _methodBody :: Maybe (Vector BasicBlock) , methodClass :: Class } methodIsVirtual :: Method -> Bool methodIsVirtual = not . hasAccessFlag ACC_STATIC . methodAccessFlags methodParameters :: Method -> [Parameter] methodParameters = V.toList . _methodParameters methodBody :: Method -> Maybe [BasicBlock] methodBody = fmap V.toList . _methodBody type MethodSignature = ([Type], Type) methodSignature :: Method -> MethodSignature methodSignature m = (map parameterType ps, methodReturnType m) where ps = case methodIsVirtual m of False -> methodParameters m True -> case methodParameters m of [] -> error "methodSignature: No parameters in a virtual function" _:rest -> rest instance Eq Method where (==) = (==) `on` methodId instance Ord Method where compare = compare `on` methodId instance Hashable Method where hashWithSalt s = hashWithSalt s . methodId instance NFData Method where rnf m = methodName m `seq` methodReturnType m `deepseq` _methodParameters m `deepseq` _methodBody m `deepseq` methodClass m `deepseq` () data Class = Class { classId :: {-# UNPACK #-} !UniqueId , classAccessFlags :: {-# UNPACK #-} !AccessFlags , classType :: Type , className :: BS.ByteString , classSourceName :: BS.ByteString , classParent :: Maybe Type , classParentReference :: Maybe Class , _classInterfaces :: Vector Type , _classDirectMethods :: Vector Method , _classVirtualMethods :: Vector Method , _classStaticFields :: Vector (AccessFlags, Field) , _classInstanceFields :: Vector (AccessFlags, Field) , _classStaticFieldMap :: HashMap BS.ByteString Field , _classInstanceFieldMap :: HashMap BS.ByteString Field , _classMethodMap :: HashMap (BS.ByteString, MethodSignature) Method -- ^ A map of method name + signature to methods } classInterfaces :: Class -> [Type] classInterfaces = V.toList . _classInterfaces classDirectMethods :: Class -> [Method] classDirectMethods = V.toList . _classDirectMethods classVirtualMethods :: Class -> [Method] classVirtualMethods = V.toList . _classVirtualMethods classMethods :: Class -> [Method] classMethods klass = classDirectMethods klass ++ classVirtualMethods klass classStaticFields :: Class -> [(AccessFlags, Field)] classStaticFields = V.toList . _classStaticFields classInstanceFields :: Class -> [(AccessFlags, Field)] classInstanceFields = V.toList . _classInstanceFields classStaticField :: Class -> BS.ByteString -> Maybe Field classStaticField k s = HM.lookup s (_classStaticFieldMap k) classInstanceField :: Class -> BS.ByteString -> Maybe Field classInstanceField k s = HM.lookup s (_classInstanceFieldMap k) instance Eq Class where (==) = (==) `on` classId instance Ord Class where compare = compare `on` classId instance Hashable Class where hashWithSalt s = hashWithSalt s . classId instance NFData Class where rnf c = classType c `seq` className c `seq` classSourceName c `seq` classParent c `deepseq` classParentReference c `deepseq` _classInterfaces c `deepseq` _classDirectMethods c `deepseq` _classVirtualMethods c `deepseq` _classStaticFields c `deepseq` _classInstanceFields c `deepseq` _classStaticFieldMap c `deepseq` _classInstanceFieldMap c `deepseq` _classMethodMap c `deepseq` () data Field = Field { fieldId :: {-# UNPACK #-} !UniqueId , fieldName :: BS.ByteString , fieldType :: Type , fieldClass :: Type } instance Eq Field where (==) = (==) `on` fieldId instance Ord Field where compare = compare `on` fieldId instance Hashable Field where hashWithSalt s = hashWithSalt s . fieldId instance NFData Field where rnf f = fieldName f `seq` fieldType f `seq` fieldClass f `seq` () data MethodRef = MethodRef { methodRefId :: {-# UNPACK #-} !UniqueId , methodRefClass :: Type , methodRefReturnType :: Type , methodRefParameterTypes :: [Type] , methodRefName :: BS.ByteString } instance Eq MethodRef where (==) = (==) `on` methodRefId instance Ord MethodRef where compare = compare `on` methodRefId instance Hashable MethodRef where hashWithSalt s = hashWithSalt s . methodRefId instance NFData MethodRef where rnf mr = methodRefClass mr `seq` methodRefReturnType mr `deepseq` methodRefParameterTypes mr `seq` methodRefName mr `seq` () data InvokeDirectKind = MethodInvokeStatic | MethodInvokeDirect deriving (Eq, Ord, Show, Generic) instance S.Serialize InvokeDirectKind instance NFData InvokeDirectKind where rnf k = k `seq` () instance Hashable InvokeDirectKind where hashWithSalt s MethodInvokeStatic = hashWithSalt s (1 :: Int) hashWithSalt s MethodInvokeDirect = hashWithSalt s (2 :: Int) data InvokeVirtualKind = MethodInvokeInterface | MethodInvokeSuper | MethodInvokeVirtual deriving (Eq, Ord, Show, Generic) instance S.Serialize InvokeVirtualKind instance NFData InvokeVirtualKind where rnf k = k `seq` () instance Hashable InvokeVirtualKind where hashWithSalt s MethodInvokeInterface = hashWithSalt s (1 :: Int) hashWithSalt s MethodInvokeSuper = hashWithSalt s (2 :: Int) hashWithSalt s MethodInvokeVirtual = hashWithSalt s (3 :: Int) -- | Returns a view of the operands of an instruction -- -- Only 'Value' operands are included. Constant Ints are not, nor are -- Types. instructionOperands :: Instruction -> [Value] instructionOperands i = case i of Return { returnValue = rv } -> maybe [] (:[]) rv MoveException {} -> [] MonitorEnter { monitorReference = v } -> [v] MonitorExit { monitorReference = v } -> [v] CheckCast { castReference = r } -> [r] InstanceOf { instanceOfReference = r } -> [r] ArrayLength { arrayReference = r } -> [r] NewInstance {} -> [] NewArray { newArrayLength = l , newArrayContents = vs } -> l : fromMaybe [] vs FillArray { fillArrayReference = r } -> [r] Throw { throwReference = r } -> [r] ConditionalBranch { branchOperand1 = o1 , branchOperand2 = o2 } -> [o1, o2] UnconditionalBranch {} -> [] Switch { switchValue = v } -> [v] Compare { compareOperand1 = op1 , compareOperand2 = op2 } -> [op1, op2] UnaryOp { unaryOperand = op } -> [op] BinaryOp { binaryOperand1 = op1 , binaryOperand2 = op2 } -> [op1, op2] ArrayGet { arrayReference = r , arrayIndex = ix } -> [r, ix] ArrayPut { arrayReference = r , arrayIndex = ix , arrayPutValue = v } -> [r, ix, v] StaticGet {} -> [] StaticPut { staticOpPutValue = v } -> [v] InstanceGet { instanceOpReference = r } -> [r] InstancePut { instanceOpReference = r , instanceOpPutValue = v } -> [r, v] InvokeVirtual { invokeVirtualArguments = args } -> F.toList args InvokeDirect { invokeDirectArguments = args } -> args Phi { phiValues = ivs } -> map snd ivs -- | All of the fields referenced in a dex file. -- -- This is a superset of the fields contained by all classes. In the -- case where an instruction references a field not defined in the dex -- file, 'dexFields' will return it while just inspecting the fields -- of all available classes will not find it. dexFields :: DexFile -> [Field] dexFields df = Set.toList $ Set.fromList $ concat [ifields, cfields, afields] where cfields = [ f | klass <- dexClasses df , (_, f) <- classStaticFields klass ++ classInstanceFields klass ] ifields = [ f | k <- dexClasses df , m <- classDirectMethods k ++ classVirtualMethods k , body <- maybeToList (methodBody m) , block <- body , i <- basicBlockInstructions block , f <- referencedField i ] afields = [ f | va <- allAnnotations df , (_, val) <- annotationArguments (annotationValue va) , f <- annotationValueFieldRefs val ] referencedField i = case i of StaticGet { staticOpField = f } -> [f] StaticPut { staticOpField = f } -> [f] InstanceGet { instanceOpField = f } -> [f] InstancePut { instanceOpField = f } -> [f] _ -> [] dexMethodRefs :: DexFile -> [MethodRef] dexMethodRefs df = Set.toList $ Set.fromList $ concat [ irefs, arefs, amrefs ] where irefs = [ mref | k <- dexClasses df , m <- classDirectMethods k ++ classVirtualMethods k , body <- maybeToList (methodBody m) , block <- body , i <- basicBlockInstructions block , mref <- maybeMethodRef i ] arefs = [ mref | va <- allAnnotations df , (_, val) <- annotationArguments (annotationValue va) , mref <- annotationValueMethodRefs val ] amrefs = [ mref | (mref, _) <- HM.elems (_dexMethodAnnotations df) ] maybeMethodRef i = case i of InvokeVirtual { invokeVirtualMethod = mref } -> [mref] InvokeDirect { invokeDirectMethod = mref } -> [mref] _ -> [] allAnnotations :: DexFile -> [VisibleAnnotation] allAnnotations df = concat $ map snd (HM.toList (_dexClassAnnotations df)) ++ map (snd . snd) (HM.toList (_dexMethodAnnotations df)) annotationValueFieldRefs :: AnnotationValue -> [Field] annotationValueFieldRefs = go [] where go acc v = case v of AVField f -> f : acc AVEnum f -> f : acc AVArray vs -> F.foldl' go acc vs AVAnnotation a -> F.foldl' go acc [ val | (_, val) <- annotationArguments a ] _ -> acc annotationValueMethodRefs :: AnnotationValue -> [MethodRef] annotationValueMethodRefs = go [] where go acc v = case v of AVMethod m -> m : acc AVArray vs -> F.foldl' go acc vs AVAnnotation a -> F.foldl' go acc [ val | (_, val) <- annotationArguments a ] _ -> acc {- Note [Annotations] All of classes, methods, fields, and individual parameters can have annotations. Instead of putting annotations directly on those objects in the IR, we store them in side tables (held by the top-level DexFile). This is mostly a matter of implementation convenience, excused by the fact that annotations are accessed only infrequently. -}
travitch/dalvik
src/Dalvik/SSA/Types.hs
bsd-3-clause
33,554
0
19
11,723
6,974
3,967
3,007
691
26
{-# LANGUAGE StandaloneDeriving, DeriveDataTypeable, PatternGuards #-} module LogicDB.JavascriptFreeVars (Vars(..), vars) where import Prelude () import PreludePlus import qualified Data.Set as Set import Data.Generics import Data.Typeable import Language.JavaScript.Parser import Language.JavaScript.Parser.AST data Vars = Vars { freeVars :: Set.Set String, definedVars :: Set.Set String } deriving Show instance Monoid Vars where mempty = Vars Set.empty Set.empty mappend (Vars f d) (Vars f' d') = Vars (f `Set.union` f') (d `Set.union` d') vars :: String -> Either String Vars vars i = right gvars $ parse i "<input>" gvars :: (Data a) => a -> Vars gvars x = case cast x of Just n | Just vs <- query n -> vs y -> fold (gmapQ gvars x) getIdentifier :: JSNode -> [String] getIdentifier (NN (JSIdentifier s)) = [s] getIdentifier (NT (JSIdentifier s) _ _) = [s] getIdentifier _ = [] query :: Node -> Maybe Vars query (JSFunction _ nameS _ paramsS _ body) = Just $ Vars { freeVars = freeVars vbody `Set.difference` Set.fromList (concatMap getIdentifier paramsS) `Set.difference` definedVars vbody, definedVars = Set.fromList (getIdentifier nameS) } where vbody = gvars body query (JSFunctionExpression _ namesS _ paramsS _ body) = Just $ Vars { freeVars = freeVars vbody `Set.difference` Set.fromList (concatMap getIdentifier paramsS) `Set.difference` definedVars vbody, definedVars = Set.fromList (concatMap getIdentifier namesS) } where vbody = gvars body query (JSVarDecl name init) = Just $ Vars { freeVars = freeVars (gvars init), definedVars = Set.fromList (getIdentifier name) } query (JSWith _ _ e _ block) = Just $ Vars { -- ignore free variables in body of with freeVars = freeVars ve, definedVars = definedVars ve `Set.union` definedVars (gvars block) } where ve = gvars e query (JSIdentifier ident) = Just $ Vars { freeVars = Set.singleton ident, definedVars = Set.empty } query (JSMemberDot pre _ _) = Just $ gvars pre -- ignore identifiers after a dot query (JSCallExpression "." _ _ _) = Just mempty -- same query (JSPropertyNameandValue _ _ value) = Just $ gvars value query x = Nothing
luqui/logic-db
LogicDB/JavascriptFreeVars.hs
bsd-3-clause
2,350
0
12
582
809
426
383
53
2
-- 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. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.TimeGrain.IT.Rules ( rules ) where import Data.Text (Text) import Prelude import Data.String import Duckling.Dimensions.Types import qualified Duckling.TimeGrain.Types as TG import Duckling.Types grains :: [(Text, String, TG.Grain)] grains = [ ("seconde (grain)", "second[oi]", TG.Second) , ("minute (grain)", "minut[oi]", TG.Minute) , ("heure (grain)", "or[ae]", TG.Hour) , ("jour (grain)", "giorn[oi]", TG.Day) , ("semaine (grain)", "settiman[ae]", TG.Week) , ("mois (grain)", "mes[ei]", TG.Month) , ("trimestre (grain)", "trimestr[ei]", TG.Quarter) , ("année (grain)", "ann?[oi]", TG.Year) ] rules :: [Rule] rules = map go grains where go (name, regexPattern, grain) = Rule { name = name , pattern = [regex regexPattern] , prod = \_ -> Just $ Token TimeGrain grain }
facebookincubator/duckling
Duckling/TimeGrain/IT/Rules.hs
bsd-3-clause
1,161
0
11
259
271
172
99
25
1
module Types.Internal where import Data.Array.IArray (Array) type Vector = (Double, Double, Double) type Normal = (Double, Double, Double) type Colour = (Double, Double, Double) type Matrix = Array Int Vector
leohaskell/parseVRS
src/Types/Internal.hs
bsd-3-clause
212
0
5
33
73
47
26
6
0
----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <dimitri.sabadie@gmail.com> -- Stability : experimental -- Portability : portable -- ---------------------------------------------------------------------------- module Quaazar.Control ( module X ) where import Quaazar.Control.Constraint as X import Quaazar.Control.Monad as X import Quaazar.Control.Trans as X
phaazon/quaazar
src/Quaazar/Control.hs
bsd-3-clause
504
0
4
67
46
36
10
5
0
{-# LANGUAGE FlexibleInstances #-} module Jira2Sheet.Types.HTTP where import Control.Exception (SomeException (..)) import Control.Monad (join, unless, (<=<)) import Control.Monad.Except (ExceptT (..)) import Control.Monad.Log (LoggingT (..)) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Maybe (MaybeT (..)) import Data.Aeson (FromJSON (..)) import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LBS import Data.Either.Combinators (mapLeft) import Data.Monoid ((<>)) import Network.HTTP.Conduit (Manager, ManagerSettings, newManager) import Network.OAuth.OAuth2 (AccessToken (..), OAuth2 (..), QueryParams, appendQueryParam, authorizationUrl, fetchAccessToken) import qualified Network.OAuth.OAuth2 as OAuth2 import Network.Wreq (asJSON) import qualified Network.Wreq as Wreq import Network.Wreq.Types (Postable) import UnexceptionalIO (UIO, fromIO, unsafeFromIO) import Web.Browser (openBrowser) import Jira2Sheet.Common (Error (..), decode, encode, lazyDecode) import Jira2Sheet.Types.Input (MonadInput (..)) class (Monad m ) => MonadHTTPGet m where -- TODO add back MonadThrow, change to MonadError getWith :: (FromJSON a) => Wreq.Options -> String -> m (Wreq.Response a) class (MonadHTTPGet m) => MonadHTTP m where postWith :: (Postable a, FromJSON b) => Wreq.Options -> String -> a -> m (Wreq.Response b) class (Monad m) => MonadOAuth m where newTls :: ManagerSettings -> m Manager oauthAuthorize :: Manager -> OAuth2 -> QueryParams -> m AccessToken fetchRefreshToken :: Manager -> OAuth2 -> ByteString -> m AccessToken instance MonadHTTPGet UIO where getWith options = unsafeFromIO . (asJSON <=< Wreq.getWith options) instance MonadHTTP UIO where postWith options body = unsafeFromIO . (asJSON <=< Wreq.postWith options body) oauthToExcept :: IO (Either LBS.ByteString a) -> ExceptT SomeException (MaybeT UIO) a oauthToExcept = ExceptT . lift . fmap join . fromIO . fmap ( mapLeft (SomeException . Error . lazyDecode)) instance MonadOAuth (ExceptT SomeException (MaybeT UIO)) where newTls = ExceptT . lift . fromIO . newManager oauthAuthorize mgr oauth params = do let url = decode $ authorizationUrl oauth `appendQueryParam` params opened <- lift $ lift $ unsafeFromIO $ openBrowser url unless opened $ lift $ lift $ unsafeFromIO $ putStrLn $ "Unable to open the browser for you, please visit: " <> url code <- lift $ getInputLine "Paste here the code obtained from the browser>" --code <- maybeToExceptT (SomeException $ Error "No code from user") $ getInputLine "Paste here the code obtained from the browser" oauthToExcept $ fetchAccessToken mgr oauth $ encode code fetchRefreshToken mgr oauth = oauthToExcept . OAuth2.fetchRefreshToken mgr oauth instance (MonadHTTPGet m) => MonadHTTPGet (LoggingT message m) where getWith options = lift . getWith options instance (MonadHTTP m) => MonadHTTP (LoggingT message m) where postWith options body = lift . postWith options body instance (MonadHTTPGet m) => MonadHTTPGet (ExceptT e m) where getWith options = lift . getWith options instance (MonadHTTP m) => MonadHTTP (ExceptT e m) where postWith options body = lift . postWith options body instance (MonadOAuth m) => MonadOAuth (LoggingT message m) where newTls = lift . newTls oauthAuthorize mgr oauth = lift . oauthAuthorize mgr oauth fetchRefreshToken mgr oauth = lift . fetchRefreshToken mgr oauth instance (MonadOAuth m) => MonadOAuth (MaybeT m) where newTls = lift . newTls oauthAuthorize mgr oauth = lift . oauthAuthorize mgr oauth fetchRefreshToken mgr oauth = lift . fetchRefreshToken mgr oauth instance (MonadHTTPGet m) => MonadHTTPGet (MaybeT m) where getWith options = lift . getWith options instance (MonadHTTP m) => MonadHTTP (MaybeT m) where postWith options body = lift . postWith options body
berdario/jira2sheet
src/Jira2Sheet/Types/HTTP.hs
bsd-3-clause
4,438
0
14
1,197
1,209
652
557
70
1
{-# OPTIONS_GHC -Wall #-} module Main where import ElmVersion import qualified ElmFormat main :: IO () main = ElmFormat.main Elm_0_18
nukisman/elm-format-short
src-cli/Main0_18.hs
bsd-3-clause
141
0
6
27
32
19
13
7
1
{-# OPTIONS -fno-warn-name-shadowing #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} module Language.Haskell.Names.Recursive ( computeInterfaces , getInterfaces , annotateModule ) where import Fay.Compiler.ModuleT import Language.Haskell.Names.Annotated import Language.Haskell.Names.Exports import Language.Haskell.Names.Imports import Language.Haskell.Names.ModuleSymbols import Language.Haskell.Names.Open.Base import Language.Haskell.Names.ScopeUtils import Language.Haskell.Names.SyntaxUtils import Language.Haskell.Names.Types import Control.Monad hiding (forM_) import Data.Data (Data) import Data.Foldable import Data.Graph (flattenSCC, stronglyConnComp) import Data.Maybe import Data.Monoid import qualified Data.Set as Set import Language.Haskell.Exts.Annotated -- | Take a set of modules and return a list of sets, where each sets for -- a strongly connected component in the import graph. -- The boolean determines if imports using @SOURCE@ are taken into account. groupModules :: forall l . [Module l] -> [[Module l]] groupModules modules = map flattenSCC $ stronglyConnComp $ map mkNode modules where mkNode :: Module l -> (Module l, ModuleName (), [ModuleName ()]) mkNode m = ( m , dropAnn $ getModuleName m , map (dropAnn . importModule) $ getImports m ) -- | Annotate a module with scoping information. This assumes that all -- module dependencies have been resolved and cached — usually you need -- to run 'computeInterfaces' first, unless you have one module in -- isolation. annotateModule :: (MonadModule m, ModuleInfo m ~ Symbols, Data l, SrcInfo l, Eq l) => Language -- ^ base language -> [Extension] -- ^ global extensions (e.g. specified on the command line) -> Module l -- ^ input module -> m (Module (Scoped l)) -- ^ output (annotated) module annotateModule lang exts mod@(Module lm mh os is ds) = do let extSet = moduleExtensions lang exts mod (imp, impTbl) <- processImports extSet is let tbl = moduleTable impTbl mod (exp, _syms) <- processExports tbl mod let lm' = none lm os' = fmap noScope os is' = imp ds' = annotate (initialScope tbl) `map` ds mh' = flip fmap mh $ \(ModuleHead lh n mw _me) -> let lh' = none lh n' = noScope n mw' = fmap noScope mw me' = exp in ModuleHead lh' n' mw' me' return $ Module lm' mh' os' is' ds' annotateModule _ _ _ = error "annotateModule: non-standard modules are not supported" -- | Compute interfaces for a set of mutually recursive modules and write -- the results to the cache. Return the set of import/export errors. findFixPoint :: (Ord l, Data l, MonadModule m, ModuleInfo m ~ Symbols) => [(Module l, ExtensionSet)] -- ^ module and all extensions with which it is to be compiled. -- Use 'moduleExtensions' to build this list. -> m (Set.Set (Error l)) findFixPoint mods = go mods (map (const mempty) mods) where go mods syms = do forM_ (zip syms mods) $ \(s,(m, _)) -> insertInCache (getModuleName m) s (syms', errors) <- liftM unzip $ forM mods $ \(m, extSet) -> do (imp, impTbl) <- processImports extSet $ getImports m let tbl = moduleTable impTbl m (exp, syms) <- processExports tbl m return (syms, foldMap getErrors imp <> foldMap getErrors exp) if syms' == syms then return $ mconcat errors else go mods syms' -- | 'computeInterfaces' takes a list of possibly recursive modules and -- computes the interface of each module. The computed interfaces are -- written into the @m@'s cache and are available to further computations -- in this monad. -- -- Returns the set of import/export errors. Note that the interfaces are -- registered in the cache regardless of whether there are any errors, but -- if there are errors, the interfaces may be incomplete. computeInterfaces :: (MonadModule m, ModuleInfo m ~ Symbols, Data l, SrcInfo l, Ord l) => Language -- ^ base language -> [Extension] -- ^ global extensions (e.g. specified on the command line) -> [Module l] -- ^ input modules -> m (Set.Set (Error l)) -- ^ errors in export or import lists computeInterfaces lang exts = liftM fold . mapM findFixPoint . map supplyExtensions . groupModules where supplyExtensions = map $ \m -> (m, moduleExtensions lang exts m) -- | Like 'computeInterfaces', but also returns a list of interfaces, one -- per module and in the same order getInterfaces :: (MonadModule m, ModuleInfo m ~ Symbols, Data l, SrcInfo l, Ord l) => Language -- ^ base language -> [Extension] -- ^ global extensions (e.g. specified on the command line) -> [Module l] -- ^ input modules -> m ([Symbols], Set.Set (Error l)) -- ^ output modules, and errors in export or import lists getInterfaces lang exts mods = do errs <- computeInterfaces lang exts mods ifaces <- forM mods $ \mod -> let modName = getModuleName mod in fromMaybe (error $ msg modName) `liftM` lookupInCache modName return (ifaces, errs) where msg modName = "getInterfaces: module " ++ modToString modName ++ " is not in the cache"
beni55/fay
src/haskell-names/Language/Haskell/Names/Recursive.hs
bsd-3-clause
5,390
0
17
1,312
1,286
684
602
94
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE QuasiQuotes #-} {- | Various HTML utils, Mustache utils, etc. -} module Guide.Views.Utils ( -- * Script utils onPageLoad, onEnter, onCtrlEnter, onEscape, onFormSubmit, inputValue, clearInput, -- * HTML utils emptySpan, mkLink, selectedIf, checkedIf, hiddenIf, categoryLink, itemLink, -- * HTML components button, textButton, imgButton, textInput, markdownEditor, smallMarkdownEditor, -- * Node identifiers thisNode, itemNodeId, categoryNodeId, -- * Sections system shown, noScriptShown, section, sectionSpan, -- * Widget system & templates mustache, readWidgets, getJS, getCSS, protectForm, getCsrfHeader, module Guide.Views.Utils.Input ) where import Imports hiding (some) -- Web import Web.Spock import Web.Spock.Config -- Lists import Data.List.Split -- Containers import qualified Data.Map as M -- import Data.Tree -- Text import qualified Data.Text.All as T -- digestive-functors import Text.Digestive (View) -- import NeatInterpolation -- Web import Lucid hiding (for_) -- Files import qualified System.FilePath.Find as F -- -- Network -- import Data.IP -- -- Time -- import Data.Time.Format.Human -- -- Markdown -- import qualified CMark as MD -- Mustache (templates) import Text.Mustache.Plus import qualified Data.Aeson as A import qualified Data.ByteString.Lazy.Char8 as BS import qualified Data.Semigroup as Semigroup import qualified Data.List.NonEmpty as NonEmpty import Text.Megaparsec import Text.Megaparsec.Char import Guide.App -- import Guide.Config -- import Guide.State import Guide.Types import Guide.Utils import Guide.JS (JS(..), JQuerySelector) import qualified Guide.JS as JS import Guide.Markdown -- import Guide.Cache import Guide.Views.Utils.Input -- | Add a script that does something on page load. onPageLoad :: Monad m => JS -> HtmlT m () onPageLoad js = script_ $ "$(document).ready(function(){"+|js|+"});" -- | Add some empty space. emptySpan :: Monad m => Text -> HtmlT m () emptySpan w = span_ [style_ ("margin-left:" <> w)] mempty -- Use inputValue to get the value (works with input_ and textarea_) onEnter :: JS -> Attribute onEnter handler = onkeydown_ $ "if (event.keyCode == 13 || event.keyCode == 10) {" +|handler|+" return false;}\n" onCtrlEnter :: JS -> Attribute onCtrlEnter handler = onkeydown_ $ "if ((event.keyCode == 13 || event.keyCode == 10) && " <> "(event.metaKey || event.ctrlKey)) {" +|handler|+" return false;}\n" onEscape :: JS -> Attribute onEscape handler = onkeydown_ $ "if (event.keyCode == 27) {" +|handler|+" return false;}\n" textInput :: Monad m => [Attribute] -> HtmlT m () textInput attrs = input_ (type_ "text" : attrs) inputValue :: JS inputValue = JS "this.value" clearInput :: JS clearInput = JS "this.value = '';" onFormSubmit :: (JS -> JS) -> Attribute onFormSubmit f = onsubmit_ $ format "{} return false;" (f (JS "this")) button :: Monad m => Text -> [Attribute] -> JS -> HtmlT m () button value attrs handler = input_ (type_ "button" : value_ value : onclick_ handler' : attrs) where handler' = fromJS handler -- A text button looks like “[cancel]” textButton :: Monad m => Text -- ^ Button text -> JS -- ^ Onclick handler -> HtmlT m () textButton caption (JS handler) = span_ [class_ "text-button"] $ -- “#” is used instead of javascript:void(0) because the latter is slow -- in Firefox (at least for me – tested with Firefox 43 on Arch Linux) a_ [href_ "#", onclick_ (handler <> "return false;")] (toHtml caption) -- So far all icons used here have been from <https://useiconic.com/open/> imgButton :: Monad m => Text -> Url -> [Attribute] -> JS -> HtmlT m () imgButton alt src attrs (JS handler) = a_ [href_ "#", onclick_ (handler <> "return false;")] (img_ (src_ src : alt_ alt : title_ alt : attrs)) mkLink :: Monad m => HtmlT m a -> Url -> HtmlT m a mkLink x src = a_ [href_ src] x selectedIf :: With w => Bool -> w -> w selectedIf p x = if p then with x [selected_ "selected"] else x checkedIf :: With w => Bool -> w -> w checkedIf p x = if p then with x [checked_] else x hiddenIf :: With w => Bool -> w -> w hiddenIf p x = if p then with x [style_ "display:none;"] else x markdownEditor :: MonadIO m => [Attribute] -> MarkdownBlock -- ^ Default text -> (JS -> JS) -- ^ “Submit” handler, receiving the contents of the editor -> JS -- ^ “Cancel” handler -> Text -- ^ Instruction (e.g. “press Ctrl+Enter to save”) -> HtmlT m () markdownEditor attr (view mdSource -> s) submit cancel instr = do textareaUid <- randomLongUid let val = JS $ "document.getElementById(\""+|textareaUid|+"\").value" -- Autocomplete has to be turned off thanks to -- <http://stackoverflow.com/q/8311455>. textarea_ ([uid_ textareaUid, autocomplete_ "off", class_ "big fullwidth", onCtrlEnter (submit val), onEscape (JS.assign val s <> cancel) ] ++ attr) $ toHtml s button "Save" [class_ " save "] $ submit val emptySpan "6px" button "Cancel" [class_ " cancel "] $ JS.assign val s <> cancel emptySpan "6px" span_ [class_ "edit-field-instruction"] (toHtml instr) a_ [href_ "/markdown", target_ "_blank"] $ img_ [src_ "/markdown.svg", alt_ "markdown supported", class_ " markdown-supported "] smallMarkdownEditor :: MonadIO m => [Attribute] -> MarkdownInline -- ^ Default text -> (JS -> JS) -- ^ “Submit” handler, receiving the contents of the editor -> Maybe JS -- ^ “Cancel” handler (if “Cancel” is needed) -> Text -- ^ Instruction (e.g. “press Enter to add”) -> HtmlT m () smallMarkdownEditor attr (view mdSource -> s) submit mbCancel instr = do textareaId <- randomLongUid let val = JS $ "document.getElementById(\""+|textareaId|+"\").value" textarea_ ([class_ "fullwidth", uid_ textareaId, autocomplete_ "off"] ++ [onEnter (submit val)] ++ [onEscape cancel | Just cancel <- [mbCancel]] ++ attr) $ toHtml s br_ [] for_ mbCancel $ \cancel -> do textButton "cancel" $ JS.assign val s <> cancel span_ [style_ "float:right"] $ do span_ [class_ "edit-field-instruction"] (toHtml instr) a_ [href_ "/markdown", target_ "_blank"] $ img_ [src_ "/markdown.svg", alt_ "markdown supported", class_ " markdown-supported "] thisNode :: MonadIO m => HtmlT m JQuerySelector thisNode = do uid' <- randomLongUid -- If the class name ever changes, fix 'JS.moveNodeUp' and -- 'JS.moveNodeDown'. span_ [uid_ uid', class_ "dummy"] mempty return (JS.selectParent (JS.selectUid uid')) itemNodeId :: Item -> Text itemNodeId item = format "item-{}" (item^.uid) categoryNodeId :: Category -> Text categoryNodeId category = format "category-{}" (category^.uid) -- TODO: another absolute link to get rid of [absolute-links] categoryLink :: Category -> Url categoryLink category = format "/haskell/{}" (categorySlug category) itemLink :: Category -> Item -> Url itemLink category item = format "/haskell/{}#{}" (categorySlug category) (itemNodeId item) -- See Note [show-hide]; wheh changing these, also look at 'JS.switchSection'. shown, noScriptShown :: Attribute shown = class_ " shown " noScriptShown = class_ " noscript-shown " -- See Note [show-hide] section :: Monad m => Text -- ^ Section name (or names) -> [Attribute] -- ^ Additional attributes -> HtmlT m () -- ^ Content of the section -> HtmlT m () section t attrs = div_ (class_ (t <> " section ") : attrs) -- See Note [show-hide] sectionSpan :: Monad m => Text -- ^ Section name (or names) -> [Attribute] -- ^ Additional attributes -> HtmlT m () -- ^ Content of the section -> HtmlT m () sectionSpan t attrs = span_ (class_ (t <> " section ") : attrs) {- TODO: warn about how one shouldn't write @foo("{{bar}}")@ in templates, because a newline in 'bar' directly after the quote will mess things up. Write @foo({{{%js bar}}})@ instead. -} mustache :: MonadIO m => PName -> A.Value -> HtmlT m () mustache f v = do let functions = M.fromList [ ("selectIf", \[x] -> if x == A.Bool True then return (A.String "selected") else return A.Null), ("js", \[x] -> return $ A.String (toJson x)), ("trace", \xs -> do mapM_ (BS.putStrLn . toJsonPretty) xs return A.Null) ] widgets <- readWidgets let templates = [(tname, t) | (HTML_ tname, t) <- widgets] when (null templates) $ error "View.mustache: no HTML templates found in templates/" parsed <- for templates $ \(tname, t) -> do let pname = fromString (T.unpack tname) case compileMustacheText pname t of Left e -> error $ printf "View.mustache: when parsing %s: %s" tname (parseErrorPretty e) Right template -> return template let combined = (Semigroup.sconcat (NonEmpty.fromList parsed)) { templateActual = f } (rendered, warnings) <- liftIO $ renderMustacheM functions combined v when (not (null warnings)) $ error $ printf "View.mustache: warnings when rendering %s:\n%s" (unPName f) (unlines warnings) toHtmlRaw rendered data SectionType = HTML_ Text | JS_ | CSS_ | Description_ | Note_ Text -- | Used to turn collected section lines back into a section. -- -- * Trims surrounding blank lines -- * Doesn't append a newline when there's only one line -- (useful for inline partials) unlinesSection :: [Text] -> Text unlinesSection = unlines' . dropWhile T.null . dropWhileEnd T.null where unlines' [] = "" unlines' [x] = x unlines' xs = T.unlines xs readWidget :: MonadIO m => FilePath -> m [(SectionType, Text)] readWidget fp = liftIO $ do s <- T.readFile fp let isDivide line = (T.all (== '=') line || T.all (== '-') line) && T.length line >= 20 let go (x:y:[]) = [(T.strip (last x), unlinesSection y)] go (x:y:xs) = (T.strip (last x), unlinesSection (init y)) : go (y : xs) go _ = error $ "View.readWidget: couldn't read " ++ fp let sections = go (splitWhen isDivide (T.lines s)) let sectionTypeP :: Parsec Void Text SectionType sectionTypeP = choice [ do string "HTML" HTML_ <$> choice [ string ": " >> (T.pack <$> some anyChar), return (T.pack (takeBaseName fp)) ], string "JS" $> JS_, string "CSS" $> CSS_, string "Description" $> Description_, do string "Note [" Note_ . T.pack <$> someTill anyChar (char ']') ] let parseSectionType t = case parse (sectionTypeP <* eof) fp t of Right x -> x Left e -> error $ printf "invalid section name: '%s'\n%s" t (parseErrorPretty e) return $ over (each._1) parseSectionType sections readWidgets :: MonadIO m => m [(SectionType, Text)] readWidgets = liftIO $ do let isWidget = F.extension F.==? ".widget" files' <- F.find F.always isWidget "templates/" concat <$> mapM readWidget files' getJS :: MonadIO m => m Text getJS = do widgets <- readWidgets let js = [t | (JS_, t) <- widgets] return (T.concat js) getCSS :: MonadIO m => m Text getCSS = do widgets <- readWidgets let css = [t | (CSS_, t) <- widgets] return (T.concat css) -- | 'protectForm' renders a set of input fields within a CSRF-protected form. -- -- This sets the method (POST) of submission and includes a server-generated -- token to help prevent cross-site request forgery (CSRF) attacks. -- -- Briefly: this is necessary to prevent third party sites from impersonating -- logged in users, because a POST to the right URL is not sufficient to -- submit the form and perform an action. The CSRF token is only displayed -- when viewing the page. protectForm :: MonadIO m => (View (HtmlT m ()) -> HtmlT m ()) -> View (HtmlT m ()) -> GuideAction ctx (HtmlT m ()) protectForm render formView = do (name', value) <- getCsrfTokenPair return $ form formView "" [id_ "login-form"] $ do input_ [ type_ "hidden", name_ name', value_ value ] render formView getCsrfTokenPair :: GuideAction ctx (Text, Text) getCsrfTokenPair = do csrfTokenName <- spc_csrfPostName <$> getSpockCfg csrfTokenValue <- getCsrfToken return (csrfTokenName, csrfTokenValue) getCsrfHeader :: GuideAction ctx (Text, Text) getCsrfHeader = do csrfTokenName <- spc_csrfHeaderName <$> getSpockCfg csrfTokenValue <- getCsrfToken return (csrfTokenName, csrfTokenValue)
aelve/hslibs
src/Guide/Views/Utils.hs
bsd-3-clause
12,726
0
22
2,883
3,601
1,859
1,742
-1
-1
{-# LANGUAGE Rank2Types #-} module Learn.ConjugateGradient where import Control.Monad import Data.Maybe import Data.Array.Repa as R hiding ((++)) import Learn.MonadLogger import Learn.Types import Learn.Optimization -- Underscores like in x_ means roughly "x value from previous iteration" whenever new x is calculated -- TODO: maybe reduce parallelism somewhere? benchmark sumAllP vs. sumAllS, or decide in runtime depending on size -- Constants: -- ^ procedure to chose next step length. TODO: tune it chose :: Double -> Double -> Double chose low high = low + (high - low) / 100 -- ^ maximum step length, TODO: tune it aMax :: Double aMax = 50.0 -- ^ constants for strong Wolfe conditions recommended by Nocedal: c₁ :: Double c₁ = 0.0001 c₂ :: Double c₂ = 0.1 -- Cubic Hermite spline based on values of function and its first derivatives -- If there is no extremum in the interval or if it is not minimum, just bisect -- Also if it is too close to the boundary, it is also rejected to prevent slow convergence. interpolateMinNorm :: Double -> Double -> Double -> Double -> Maybe Double interpolateMinNorm p₀ p₁ m₀ m₁ = let a = 2*p₀ + m₀ -2*p₁ + m₁ b = -3*p₀ - 2*m₀ + 3*p₁ - m₁ c = m₀ d = p₁ spline x = a*x*x*x + b*x*x + c*x + d in do x <- cubicMin a b c guard $ x * (1 - x) >= 0.05 -- if it is less then zero, minimum is outside [0;1] -- if it is just small, we are too close to the border guard $ spline x < min p₀ p₁ -- if value at the boundary is less than value at extremum return x -- normalize values as if we have values of function and tangent at 0 and 1, then find minimum cubicOrBisect :: Double -> Double -> Double -> Double -> Double -> Double -> Double cubicOrBisect a₀ a₁ p₀ p₁ m₀ m₁ = a₀ + x * len where len = a₁ - a₀ x = fromMaybe 0.5 $ interpolateMinNorm p₀ p₁ (m₀ * len) (m₁ * len) -- find minimum of cubic polynomial (last coefficient is omitted) -- to avoid endless loops somewhere in the calling code (zoom) cubicMin :: Double -> Double -> Double -> Maybe Double cubicMin a b c = if det > 0 then Just $ (-b + sqrt det) / (3 * a) -- determinant is taken with pLowus for minimum else Nothing where det = b*b-3*a*c -- ^ Strong Wolfe conditions check, for testing line search algorithms strongWolfe :: Double -> Double -> Double -> UVec -> UVec -> UVec -> Bool strongWolfe a f₀ f δf₀ δf p = f <= f₀ + c₁ * a * sumAllS (δf₀ *^ p) && -- sufficient decrease abs (sumAllS (δf *^ p)) <= abs (c₂ * sumAllS (δf₀ *^ p)) -- curvature {- FIXME: add some checks if we approach machine precision limit. And do something about it. -} hasNaNs :: UVec -> Bool hasNaNs = isNaN . sumAllS -- ^ line search algorithm form the book: -- Jorge Nocedal, Stephen J. Wright, Numerical Optimization, Second Edition, Algorithm 3.5 lineSearch :: MonadLogger m => Function m -> UVec -> Double -> UVec -> UVec -> m (UVec, Double, UVec) lineSearch fn x₀ f₀ δf₀ dir = do let f₀' = sumAllS $ δf₀ *^ dir step a₁ a₂ f₁ f₁' first = do yell $ "line search step with a1 = " ++ show a₁ ++ "; a2 = " ++ show a₂ (x₂, f₂, f₂', δf₂) <- φ a₂ case () of _ | f₂ > f₀ + c₁ * a₂ * f₀' || (f₂ > f₁ && not first) -> zoom a₁ a₂ f₁ f₂ f₁' f₂' | abs f₂' <= -c₂ * f₀' -> return (x₂, f₂, δf₂) | f₂' > 0 -> zoom a₂ a₁ f₂ f₁ f₂' f₁' | otherwise -> step a₂ (chose a₂ aMax) f₂ f₂' True zoom aLow aHigh fLow fHigh fLow' fHigh' = do yell $ "line search zoom with al = " ++ show aLow ++ "; ah = " ++ show aHigh let aⱼ = if aLow < aHigh then cubicOrBisect aLow aHigh fLow fHigh fLow' fHigh' else cubicOrBisect aHigh aLow fHigh fLow fHigh' fLow' (xⱼ, fⱼ, fⱼ', δfⱼ) <- φ aⱼ case () of _ | fⱼ > f₀ + c₁ * aLow * f₀' || fⱼ >= fLow -> zoom aLow aⱼ fLow fⱼ fLow' fⱼ' -- move upper bound | abs fⱼ' <= - c₂ * f₀' -> return (xⱼ, fⱼ, δfⱼ) | fⱼ' * (aHigh - aLow) >= 0 -> zoom aLow aⱼ fLow fⱼ fLow' fⱼ' -- move upper bound | otherwise -> zoom aⱼ aHigh fⱼ fHigh fⱼ' fHigh' -- move lower bound yell $ "initial gradient: " ++ show f₀' step 0 (chose 0 aMax) f₀ f₀' False where φ a = do -- φ(a) = fn(x₀ + a * dir), univariate representation of step length selection problem let x = computeS $ x₀ +^ R.map (* a) dir (p, δp) <- fn x let p' = sumAllS $ δp *^ dir -- projection of gradient on search direction return (x, p, p', δp) -- Polack-Ribiere conjugate gradient method with restarts conjugateGradient :: MonadLogger m => StopCondition -> Function m -> UVec -> m (UVec, Double) conjugateGradient sc fn x₀ = do (f₀, δf₀) <- fn x₀ -- get value and gradient at start let p₀ = computeS $ R.map negate δf₀ -- initial search direction is the steepest descent direction loop x₀ f₀ δf₀ p₀ 0 0 where (Z :. n) = extent x₀ loop x_ f_ δf_ p_ i ir = do yell $ "conjugate gradient starting iteration " ++ show i (x, f, δf) <- lineSearch fn x_ f_ δf_ p_ let beta = betaPR δf_ δf (betaPlus, restart) = if beta > 0 && ir < n -- if beta went below zero or at least every n'th iteration then (beta, False) -- we restart using steepest descent direction else (0, True) let p = computeS $ R.map (* betaPlus) p_ -^ δf if checkIter sc i || checkTol sc f_ f then return (x, f) else loop x f δf p (i+1) (if restart then 0 else ir+1) betaPR prev cur = sumAllS (cur *^ cur) / sumAllS (prev *^ (prev -^ cur))
ratatosk/learn
Learn/ConjugateGradient.hs
bsd-3-clause
6,015
274
20
1,674
2,005
1,034
971
92
4
----------------------------------------------------------------------------- -- | -- Module : ForSyDe.Shallow.Model -- Copyright : (c) ForSyDe Group, KTH 2007-2008 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : forsyde-dev@ict.kth.se -- Stability : experimental -- Portability : portable -- -- This module contains the data structure and access -- functions for the memory model. ----------------------------------------------------------------------------- module ForSyDe.Shallow.Utility.Memory ( Memory (..), Access (..), MemSize, Adr, newMem, memState, memOutput ) where import ForSyDe.Shallow.Core.Vector import ForSyDe.Shallow.Core.AbsentExt type Adr = Int type MemSize = Int -- | The data type 'Memory' is modeled as a vector. data Memory a = Mem Adr (Vector (AbstExt a)) deriving (Eq, Show) -- | The data type 'Access' defines two access patterns. data Access a = Read Adr -- ^ 'Read adr' reads an address from the memory. | Write Adr a -- ^ 'Write Adr a' writes a value into an address. deriving (Eq, Show) -- | The function 'newMem' creates a new memory, where the number of -- entries is given by a parameter. newMem :: MemSize -> Memory a -- | The function 'memState' gives the new state of the memory, after -- an access to a memory. A 'Read' operation leaves the memory -- unchanged. memState :: Memory a -> Access a -> Memory a -- | The function 'memOutput' gives the output of the memory after an -- access to the memory. A 'Write' operation gives an absent value as -- output. memOutput :: Memory a -> Access a -> AbstExt a -- Implementation newMem size = Mem size (copyV size Abst) writeMem :: Memory a -> (Int, a) -> Memory a writeMem (Mem size vs) (i, x) | i < size && i >= 0 = Mem size (replaceV vs i (abstExt x)) | otherwise = Mem size vs readMem :: Memory a -> Int -> (AbstExt a) readMem (Mem size vs) i | i < size && i >= 0 = vs `atV` i | otherwise = Abst memState mem (Read _) = mem memState mem (Write i x) = writeMem mem (i, x) memOutput mem (Read i) = readMem mem i memOutput _ (Write _ _) = Abst
forsyde/forsyde-shallow
src/ForSyDe/Shallow/Utility/Memory.hs
bsd-3-clause
2,199
0
10
512
490
270
220
28
1
import Arbre.Load import Arbre.Expressions import Arbre.Print import Arbre.View main = do views <- loadViews "views.json" case views of Just v -> do printViews v putStrLn $ show $ getView v "==" printProgramWithViews v Nothing -> do putStrLn "No views" printProgramWithViews (Views []) printProgramWithViews :: Views -> IO() printProgramWithViews views = do prog <- loadProgram "test.json" case prog of Just lp -> do printProg views lp Nothing -> do return()
blanu/arbre-go
bin/print.hs
gpl-2.0
569
0
15
179
176
79
97
20
2
{-# LANGUAGE OverloadedStrings #-} {- Module: TestMaker Copyright: (c) Chris Godbout License: GPLv3 Maintainer: Chris Godbout <chris@mathologist.net> Stability: experimental Portability: portable -} module TestMaker ( fileToDB , shuffleQList , getQuestions , getDatabase , getQuestionsByTag , renumber , freeze , genExamsFromYaml , writeExamsFromYaml , writeExamsFromConfig) where import qualified Data.ByteString as B import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import qualified Data.Text.IO import Data.Yaml (FromJSON (..), (.!=), (.:), (.:?)) import qualified Data.Yaml as Y import System.FilePath import System.Random.Shuffle import TestMaker.Database import TestMaker.Problems import TestMaker.SageTex import TestMaker.Test import TestMaker.Types -- Generate exams from yaml files data QGroup = QGroup { qgSA :: Bool , qgIntro :: T.Text , qgList :: [Int] , qgShuffle :: Bool , qgPerPage :: Int , qgDB :: Maybe FilePath} deriving (Eq, Show) instance FromJSON QGroup where parseJSON (Y.Object v) = QGroup <$> v .:? "short-answer" .!= False <*> v .:? "intro" .!= "" <*> v .:? "ids" .!= [] <*> v .:? "shuffle" .!= False <*> v .:? "per-page" .!= 0 <*> v .:? "database" data Exam = Exam { eDBname :: FilePath , eGroups :: [QGroup] , eNameSpace :: Bool , eTitle :: T.Text , eKey :: Bool , eOutFile :: Maybe [FilePath]} deriving (Eq, Show) instance FromJSON Exam where parseJSON (Y.Object v) = Exam <$> v .: "database" <*> v .:? "questions" .!= [] <*> v .:? "name-space" .!= False <*> v .:? "title" .!= "" <*> v .:? "answer-key" .!= True <*> v .:? "output-file" writeExams :: Maybe [FilePath] -> [T.Text] -> IO () writeExams (Just []) _ = pure () writeExams _ [] = pure () writeExams Nothing (exam:_) = Data.Text.IO.putStrLn exam writeExams (Just (fp:fps)) (exam:exams) = (B.writeFile fp $ encodeUtf8 exam) >> writeExams (Just fps) exams unrelative :: FilePath -> FilePath -> FilePath unrelative dir fp = if isRelative fp then dir </> fp else fp qgroupToQuestionGroup :: FilePath -> QuestionDB -> QGroup -> IO QuestionGroup qgroupToQuestionGroup dir _ (QGroup sa intro ids shuffle n (Just db)) = do db' <- fileToDB $ unrelative dir db qgroupToQuestionGroup dir db' (QGroup sa intro ids shuffle n Nothing) qgroupToQuestionGroup _ db (QGroup sa intro ids shuffle n Nothing ) = do qs' <- if shuffle then (shuffleQList $ getQuestions db ids) >>= shuffleM else shuffleQList $ getQuestions db ids pure $ QG qs' sa intro n groupsToBody ::FilePath -> QuestionDB -> [QGroup] -> IO (T.Text, T.Text) groupsToBody dir db qgs = fmap makeGroups $ sequence $ map (qgroupToQuestionGroup dir db) qgs decodeYaml :: B.ByteString -> Either String Exam decodeYaml = Y.decodeEither genExamsFromYaml' :: FilePath -> Exam -> IO [T.Text] genExamsFromYaml' dir (Exam dbfp qgs ns title key output) = do db <- fileToDB $ unrelative dir dbfp (bdy, answerKey) <- groupsToBody dir db qgs let answerKey' = if key then T.concat ["\\pagebreak \n \\begin{center}\n \\textbf{Answer Key}\n\\end{center}\n\\begin{enumerate}\n" , answerKey , "\n\\end{enumerate}\n"] else "" preamble = "\\documentclass{article}\n\\usepackage{testmaker}\n" sageInit = "\\begin{sagesilent}\n import random\n x,y,z = var('x','y','z')\n\\end{sagesilent}" header = if ns then T.concat [ "\\hfill Name:\\underline{\\hspace{2in}}\n\\begin{center}\n " , title , "\n\\end{center}"] else T.concat [ "\\begin{center}\n " , title , "\n\\end{center}"] exam =T.intercalate "\n" [ preamble , "\\begin{document}" , header , sageInit , bdy , answerKey' , "\\end{document}"] case output of Nothing -> pure [exam] Just [] -> pure [] Just (fp:fps) -> (exam:) <$> genExamsFromYaml' dir (Exam dbfp qgs ns title key (Just fps)) -- pure $ exam : rest genExamsFromYaml :: Maybe FilePath -> FilePath -> B.ByteString -> IO [T.Text] genExamsFromYaml db dir yaml = do case decodeYaml yaml of Left s -> pure [T.pack s] Right exam -> genExamsFromYaml' dir $ changeDB db exam splitYaml :: B.ByteString -> [B.ByteString] splitYaml y = h : if B.null t then [] else splitYaml (B.drop 5 t) where (h,t) = B.breakSubstring "\n---\n" y changeDB :: Maybe FilePath -> Exam -> Exam changeDB fp e@(Exam _ g n t k o) = case fp of Nothing -> e Just fp' -> Exam fp' g n t k o writeExamsFromYaml :: Maybe FilePath -> FilePath -> [B.ByteString] -> IO () writeExamsFromYaml db dir [] = pure () writeExamsFromYaml db dir (yaml:yamls) = do exams <- genExamsFromYaml db dir yaml f (decodeYaml yaml) exams writeExamsFromYaml db dir yamls where f (Left _) _ = pure () f (Right x) y = writeExams (eOutFile x) y -- examFromYaml = undefined writeExamsFromConfig :: Maybe FilePath -> FilePath -> IO () writeExamsFromConfig db yamlFile = do config <- B.readFile yamlFile writeExamsFromYaml db (takeDirectory yamlFile) $ filter (not . B.null) $ splitYaml config
mathologist/hTestMaker
testmaker/src/TestMaker.hs
gpl-3.0
5,974
0
22
1,941
1,693
887
806
131
5
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FunctionalDependencies #-} module Server where import System.IO import Control.Monad import Control.Applicative import Data.List import Control.Monad.Trans.Maybe import Control.Monad import GHC.Word -- "Server" class for all server objects (Gmail, Disk, etc.) class (SHandle handle, Show handle) => Server server handle | server -> handle, handle -> server where type KeyFor server :: * type QueryFor server :: * type ActionFor server :: * type ResultFor server :: * lookup :: [QueryFor server] -> [ActionFor server] -> server -> MaybeT IO [handle] open :: KeyFor server -> server -> MaybeT IO server close :: server -> IO () actions :: server -> [ActionFor server] perform :: (ActionFor server) -> handle -> MaybeT IO (ResultFor server) -- "Wire" class deals with handle interactions between servers class (Server s1 h1, Server s2 h2) => Wire s1 h1 s2 h2 where transfer :: h1 -> s2 -> IO h2 trace :: h1 -> s2 -> IO h2 --} -- "SHandle" class used to handle files on different servers class SHandle h where uid :: h -> Word64 -- this is a hack, MUST be fixed name :: h -> String author :: h -> String split :: h -> IO (h, h) withHandle :: (Handle -> IO a) -> h -> IO a properties :: h -> IO [(String, String)] set :: String -> a -> h -> IO h command :: String -> h -> IO h class Similar a b where similar :: a -> b -> Bool instance (SHandle a, SHandle b) => Similar a b where similar h1 h2 = (uid h1) == (uid h2) -- Abstract from sources to pools data Source k q a r where Source :: forall s h. (Server s h, Show s) => s -> Source (KeyFor s) (QueryFor s) (ActionFor s) (ResultFor s) data SourceHandle = forall h. (SHandle h, Show h) => SourceHandle h data PoolHandle = forall h. (SHandle h, Show h) => PoolHandle h instance SHandle SourceHandle where uid (SourceHandle h) = uid h name (SourceHandle h) = name h author (SourceHandle h) = author h split (SourceHandle h) = (\(h1, h2) -> (SourceHandle h1, SourceHandle h2)) <$> split h withHandle f (SourceHandle h) = withHandle f h properties (SourceHandle h) = properties h set prop value (SourceHandle h) = SourceHandle <$> set prop value h command cmd (SourceHandle h) = SourceHandle <$> command cmd h instance SHandle PoolHandle where uid (PoolHandle h) = uid h name (PoolHandle h) = name h author (PoolHandle h) = author h split (PoolHandle h) = (\(h1, h2) -> (PoolHandle h1, PoolHandle h2)) <$> split h withHandle f (PoolHandle h) = withHandle f h properties (PoolHandle h) = properties h set prop value (PoolHandle h) = PoolHandle <$> set prop value h command cmd (PoolHandle h) = PoolHandle <$> command cmd h instance Show SourceHandle where show (SourceHandle h) = "SourceHandle " ++ (show h) instance Show PoolHandle where show (PoolHandle h) = "PoolHandle " ++ (show h) instance Show (Source k q a r) where show (Source s) = "Source " ++ (show s) --Both Source and Pool are instances of Server instance Server (Source k q a r) SourceHandle where type KeyFor (Source k q a r) = [k] type QueryFor (Source k q a r) = q --type HandleFor (Source k q a r) = SourceHandle type ActionFor (Source k q a r) = a type ResultFor (Source k q a r) = r open [] (Source s) = MaybeT $ return Nothing open (k:keys) (Source s) = (Source <$> open k s) `mplus` (open keys (Source s)) close (Source s) = Server.close s actions (Source s) = actions s lookup queries actions (Source s) = map SourceHandle <$> Server.lookup queries actions s instance Server [Source k q a r] PoolHandle where type KeyFor [Source k q a r] = [k] type QueryFor [Source k q a r] = q --type HandleFor [Source k q a r] = SourceHandle type ActionFor [Source k q a r] = a type ResultFor [Source k q a r] = r -- all or none behavior when using keys (can these be rewritten more elegantly?) open key [] = return [] open key (s:ss) = (:) <$> open key s <*> open key ss close ss = forM_ ss Server.close lookup queries actions [] = return [] lookup q a pool = nubb <$> map PoolHandle <$> lookup' q a pool where lookup' queries actions [] = return [] lookup' queries actions (s:ss) = (++) <$> Server.lookup queries actions s <*> lookup' queries actions ss actions pool = undefined --TODO nubb [] = [] nubb (x:xs) = iff (present x xs) (nubb xs) (nubb (x:xs)) present a [] = False present (PoolHandle h) ((PoolHandle h') : shs) = (similar h h') || (present (PoolHandle h) shs) iff True x y = x iff False x y = y
trehansiddharth/mlsciencebowl
hs/server.hs
gpl-3.0
4,866
314
8
1,095
1,915
1,043
872
101
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.SNS.ListSubscriptions -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a list of the requester\'s subscriptions. Each call returns a -- limited list of subscriptions, up to 100. If there are more -- subscriptions, a 'NextToken' is also returned. Use the 'NextToken' -- parameter in a new 'ListSubscriptions' call to get further results. -- -- /See:/ <http://docs.aws.amazon.com/sns/latest/api/API_ListSubscriptions.html AWS API Reference> for ListSubscriptions. -- -- This operation returns paginated results. module Network.AWS.SNS.ListSubscriptions ( -- * Creating a Request listSubscriptions , ListSubscriptions -- * Request Lenses , lsNextToken -- * Destructuring the Response , listSubscriptionsResponse , ListSubscriptionsResponse -- * Response Lenses , lsrsNextToken , lsrsSubscriptions , lsrsResponseStatus ) where import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.SNS.Types import Network.AWS.SNS.Types.Product -- | Input for ListSubscriptions action. -- -- /See:/ 'listSubscriptions' smart constructor. newtype ListSubscriptions = ListSubscriptions' { _lsNextToken :: Maybe Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListSubscriptions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lsNextToken' listSubscriptions :: ListSubscriptions listSubscriptions = ListSubscriptions' { _lsNextToken = Nothing } -- | Token returned by the previous 'ListSubscriptions' request. lsNextToken :: Lens' ListSubscriptions (Maybe Text) lsNextToken = lens _lsNextToken (\ s a -> s{_lsNextToken = a}); instance AWSPager ListSubscriptions where page rq rs | stop (rs ^. lsrsNextToken) = Nothing | stop (rs ^. lsrsSubscriptions) = Nothing | otherwise = Just $ rq & lsNextToken .~ rs ^. lsrsNextToken instance AWSRequest ListSubscriptions where type Rs ListSubscriptions = ListSubscriptionsResponse request = postQuery sNS response = receiveXMLWrapper "ListSubscriptionsResult" (\ s h x -> ListSubscriptionsResponse' <$> (x .@? "NextToken") <*> (x .@? "Subscriptions" .!@ mempty >>= may (parseXMLList "member")) <*> (pure (fromEnum s))) instance ToHeaders ListSubscriptions where toHeaders = const mempty instance ToPath ListSubscriptions where toPath = const "/" instance ToQuery ListSubscriptions where toQuery ListSubscriptions'{..} = mconcat ["Action" =: ("ListSubscriptions" :: ByteString), "Version" =: ("2010-03-31" :: ByteString), "NextToken" =: _lsNextToken] -- | Response for ListSubscriptions action -- -- /See:/ 'listSubscriptionsResponse' smart constructor. data ListSubscriptionsResponse = ListSubscriptionsResponse' { _lsrsNextToken :: !(Maybe Text) , _lsrsSubscriptions :: !(Maybe [Subscription]) , _lsrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListSubscriptionsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lsrsNextToken' -- -- * 'lsrsSubscriptions' -- -- * 'lsrsResponseStatus' listSubscriptionsResponse :: Int -- ^ 'lsrsResponseStatus' -> ListSubscriptionsResponse listSubscriptionsResponse pResponseStatus_ = ListSubscriptionsResponse' { _lsrsNextToken = Nothing , _lsrsSubscriptions = Nothing , _lsrsResponseStatus = pResponseStatus_ } -- | Token to pass along to the next 'ListSubscriptions' request. This -- element is returned if there are more subscriptions to retrieve. lsrsNextToken :: Lens' ListSubscriptionsResponse (Maybe Text) lsrsNextToken = lens _lsrsNextToken (\ s a -> s{_lsrsNextToken = a}); -- | A list of subscriptions. lsrsSubscriptions :: Lens' ListSubscriptionsResponse [Subscription] lsrsSubscriptions = lens _lsrsSubscriptions (\ s a -> s{_lsrsSubscriptions = a}) . _Default . _Coerce; -- | The response status code. lsrsResponseStatus :: Lens' ListSubscriptionsResponse Int lsrsResponseStatus = lens _lsrsResponseStatus (\ s a -> s{_lsrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-sns/gen/Network/AWS/SNS/ListSubscriptions.hs
mpl-2.0
5,138
0
15
1,104
747
439
308
86
1
----------------------------------------------------------------------------- -- | -- Module : Control.Comonad.Indexed -- Copyright : (C) 2008 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : portable -- ---------------------------------------------------------------------------- module Control.Comonad.Indexed ( IxFunctor(..) , IxCopointed(..) , IxComonad(..) , iduplicate ) where import Control.Functor.Indexed class IxCopointed w => IxComonad w where iextend :: (w j k a -> b) -> w i k a -> w i j b iduplicate :: IxComonad w => w i k a -> w i j (w j k a) iduplicate = iextend id
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
Control/Comonad/Indexed.hs
apache-2.0
721
4
10
131
159
90
69
10
1
{-# LANGUAGE CPP #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | The monad used for the command-line executable @stack@. module Stack.Types.StackT (StackT ,StackLoggingT ,runStackT ,runStackTGlobal ,runStackLoggingT ,runStackLoggingTGlobal ,runInnerStackT ,runInnerStackLoggingT ,newTLSManager ,logSticky ,logStickyDone) where import Control.Applicative import Control.Concurrent.MVar import Control.Monad import Control.Monad.Base import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader hiding (lift) import Control.Monad.Trans.Control import qualified Data.ByteString.Char8 as S8 import Data.Char import Data.List (stripPrefix) import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T import qualified Data.Text.IO as T import Data.Time import GHC.Foreign (withCString, peekCString) import Language.Haskell.TH import Language.Haskell.TH.Syntax (lift) import Network.HTTP.Client.Conduit (HasHttpManager(..)) import Network.HTTP.Conduit import Prelude -- Fix AMP warning import System.FilePath import Stack.Types.Config (GlobalOpts (..)) import Stack.Types.Internal import System.Console.ANSI import System.IO import System.Log.FastLogger #ifndef MIN_VERSION_time #define MIN_VERSION_time(x, y, z) 0 #endif #if !MIN_VERSION_time(1, 5, 0) import System.Locale #endif -------------------------------------------------------------------------------- -- Main StackT monad transformer -- | The monad used for the executable @stack@. newtype StackT config m a = StackT {unStackT :: ReaderT (Env config) m a} deriving (Functor,Applicative,Monad,MonadIO,MonadReader (Env config),MonadThrow,MonadCatch,MonadMask,MonadTrans) deriving instance (MonadBase b m) => MonadBase b (StackT config m) instance MonadBaseControl b m => MonadBaseControl b (StackT config m) where type StM (StackT config m) a = ComposeSt (StackT config) m a liftBaseWith = defaultLiftBaseWith restoreM = defaultRestoreM instance MonadTransControl (StackT config) where type StT (StackT config) a = StT (ReaderT (Env config)) a liftWith = defaultLiftWith StackT unStackT restoreT = defaultRestoreT StackT -- | Takes the configured log level into account. instance MonadIO m => MonadLogger (StackT config m) where monadLoggerLog = stickyLoggerFunc instance MonadIO m => MonadLoggerIO (StackT config m) where askLoggerIO = getStickyLoggerFunc -- | Run a Stack action, using global options. runStackTGlobal :: (MonadIO m) => Manager -> config -> GlobalOpts -> StackT config m a -> m a runStackTGlobal manager config GlobalOpts{..} = runStackT manager globalLogLevel config globalTerminal (isJust globalReExecVersion) -- | Run a Stack action. runStackT :: (MonadIO m) => Manager -> LogLevel -> config -> Bool -> Bool -> StackT config m a -> m a runStackT manager logLevel config terminal reExec m = do ansiTerminal <- liftIO $ hSupportsANSI stderr canUseUnicode <- liftIO getCanUseUnicode withSticky terminal (\sticky -> runReaderT (unStackT m) (Env config logLevel terminal ansiTerminal reExec manager sticky canUseUnicode)) -- | Taken from GHC: determine if we should use Unicode syntax getCanUseUnicode :: IO Bool getCanUseUnicode = do let enc = localeEncoding str = "\x2018\x2019" test = withCString enc str $ \cstr -> do str' <- peekCString enc cstr return (str == str') test `catchIOError` \_ -> return False -------------------------------------------------------------------------------- -- Logging only StackLoggingT monad transformer -- | Monadic environment for 'StackLoggingT'. data LoggingEnv = LoggingEnv { lenvLogLevel :: !LogLevel , lenvTerminal :: !Bool , lenvAnsiTerminal :: !Bool , lenvReExec :: !Bool , lenvManager :: !Manager , lenvSticky :: !Sticky , lenvSupportsUnicode :: !Bool } -- | The monad used for logging in the executable @stack@ before -- anything has been initialized. newtype StackLoggingT m a = StackLoggingT { unStackLoggingT :: ReaderT LoggingEnv m a } deriving (Functor,Applicative,Monad,MonadIO,MonadThrow,MonadReader LoggingEnv,MonadCatch,MonadMask,MonadTrans) deriving instance (MonadBase b m) => MonadBase b (StackLoggingT m) instance MonadBaseControl b m => MonadBaseControl b (StackLoggingT m) where type StM (StackLoggingT m) a = ComposeSt StackLoggingT m a liftBaseWith = defaultLiftBaseWith restoreM = defaultRestoreM instance MonadTransControl StackLoggingT where type StT StackLoggingT a = StT (ReaderT LoggingEnv) a liftWith = defaultLiftWith StackLoggingT unStackLoggingT restoreT = defaultRestoreT StackLoggingT -- | Takes the configured log level into account. instance (MonadIO m) => MonadLogger (StackLoggingT m) where monadLoggerLog = stickyLoggerFunc instance HasSticky LoggingEnv where getSticky = lenvSticky instance HasLogLevel LoggingEnv where getLogLevel = lenvLogLevel instance HasHttpManager LoggingEnv where getHttpManager = lenvManager instance HasTerminal LoggingEnv where getTerminal = lenvTerminal getAnsiTerminal = lenvAnsiTerminal instance HasReExec LoggingEnv where getReExec = lenvReExec instance HasSupportsUnicode LoggingEnv where getSupportsUnicode = lenvSupportsUnicode runInnerStackT :: (HasHttpManager r, HasLogLevel r, HasTerminal r, HasReExec r, MonadReader r m, MonadIO m) => config -> StackT config IO a -> m a runInnerStackT config inner = do manager <- asks getHttpManager logLevel <- asks getLogLevel terminal <- asks getTerminal reExec <- asks getReExec liftIO $ runStackT manager logLevel config terminal reExec inner runInnerStackLoggingT :: (HasHttpManager r, HasLogLevel r, HasTerminal r, HasReExec r, MonadReader r m, MonadIO m) => StackLoggingT IO a -> m a runInnerStackLoggingT inner = do manager <- asks getHttpManager logLevel <- asks getLogLevel terminal <- asks getTerminal reExec <- asks getReExec liftIO $ runStackLoggingT manager logLevel terminal reExec inner -- | Run the logging monad, using global options. runStackLoggingTGlobal :: MonadIO m => Manager -> GlobalOpts -> StackLoggingT m a -> m a runStackLoggingTGlobal manager GlobalOpts{..} = runStackLoggingT manager globalLogLevel globalTerminal (isJust globalReExecVersion) -- | Run the logging monad. runStackLoggingT :: MonadIO m => Manager -> LogLevel -> Bool -> Bool -> StackLoggingT m a -> m a runStackLoggingT manager logLevel terminal reExec m = do ansiTerminal <- liftIO $ hSupportsANSI stderr canUseUnicode <- liftIO getCanUseUnicode withSticky terminal (\sticky -> runReaderT (unStackLoggingT m) LoggingEnv { lenvLogLevel = logLevel , lenvManager = manager , lenvSticky = sticky , lenvTerminal = terminal , lenvAnsiTerminal = ansiTerminal , lenvReExec = reExec , lenvSupportsUnicode = canUseUnicode }) -- | Convenience for getting a 'Manager' newTLSManager :: MonadIO m => m Manager newTLSManager = liftIO $ newManager tlsManagerSettings -------------------------------------------------------------------------------- -- Logging functionality stickyLoggerFunc :: (HasSticky r, HasLogLevel r, HasSupportsUnicode r, HasTerminal r, ToLogStr msg, MonadReader r m, MonadIO m) => Loc -> LogSource -> LogLevel -> msg -> m () stickyLoggerFunc loc src level msg = do func <- getStickyLoggerFunc liftIO $ func loc src level msg getStickyLoggerFunc :: (HasSticky r, HasLogLevel r, HasSupportsUnicode r, HasTerminal r, ToLogStr msg, MonadReader r m) => m (Loc -> LogSource -> LogLevel -> msg -> IO ()) getStickyLoggerFunc = do sticky <- asks getSticky logLevel <- asks getLogLevel supportsUnicode <- asks getSupportsUnicode supportsAnsi <- asks getAnsiTerminal return $ stickyLoggerFuncImpl sticky logLevel supportsUnicode supportsAnsi stickyLoggerFuncImpl :: ToLogStr msg => Sticky -> LogLevel -> Bool -> Bool -> (Loc -> LogSource -> LogLevel -> msg -> IO ()) stickyLoggerFuncImpl (Sticky mref) maxLogLevel supportsUnicode supportsAnsi loc src level msg = case mref of Nothing -> loggerFunc supportsAnsi maxLogLevel out loc src (case level of LevelOther "sticky-done" -> LevelInfo LevelOther "sticky" -> LevelInfo _ -> level) msg Just ref -> do sticky <- takeMVar ref let backSpaceChar = '\8' repeating = S8.replicate (maybe 0 T.length sticky) clear = S8.hPutStr out (repeating backSpaceChar <> repeating ' ' <> repeating backSpaceChar) -- Convert some GHC-generated Unicode characters as necessary let msgText | supportsUnicode = msgTextRaw | otherwise = T.map replaceUnicode msgTextRaw newState <- case level of LevelOther "sticky-done" -> do clear T.hPutStrLn out msgText hFlush out return Nothing LevelOther "sticky" -> do clear T.hPutStr out msgText hFlush out return (Just msgText) _ | level >= maxLogLevel -> do clear loggerFunc supportsAnsi maxLogLevel out loc src level $ toLogStr msgText case sticky of Nothing -> return Nothing Just line -> do T.hPutStr out line >> hFlush out return sticky | otherwise -> return sticky putMVar ref newState where out = stderr msgTextRaw = T.decodeUtf8With T.lenientDecode msgBytes msgBytes = fromLogStr (toLogStr msg) -- | Replace Unicode characters with non-Unicode equivalents replaceUnicode :: Char -> Char replaceUnicode '\x2018' = '`' replaceUnicode '\x2019' = '\'' replaceUnicode c = c -- | Logging function takes the log level into account. loggerFunc :: ToLogStr msg => Bool -> LogLevel -> Handle -> Loc -> Text -> LogLevel -> msg -> IO () loggerFunc supportsAnsi maxLogLevel outputChannel loc _src level msg = when (level >= maxLogLevel) (liftIO (do out <- getOutput T.hPutStrLn outputChannel out)) where getOutput = do timestamp <- getTimestamp l <- getLevel lc <- getLoc return $ T.concat [ T.pack timestamp , T.pack l , T.pack (ansi [Reset]) , T.decodeUtf8 (fromLogStr (toLogStr msg)) , T.pack lc , T.pack (ansi [Reset]) ] where ansi xs | supportsAnsi = setSGRCode xs | otherwise = "" getTimestamp | maxLogLevel <= LevelDebug = do now <- getZonedTime return $ ansi [SetColor Foreground Vivid Black] ++ formatTime' now ++ ": " | otherwise = return "" where formatTime' = take timestampLength . formatTime defaultTimeLocale "%F %T.%q" getLevel | maxLogLevel <= LevelDebug = return ((case level of LevelDebug -> ansi [SetColor Foreground Dull Green] LevelInfo -> ansi [SetColor Foreground Dull Blue] LevelWarn -> ansi [SetColor Foreground Dull Yellow] LevelError -> ansi [SetColor Foreground Dull Red] LevelOther _ -> ansi [SetColor Foreground Dull Magenta]) ++ "[" ++ map toLower (drop 5 (show level)) ++ "] ") | otherwise = return "" getLoc | maxLogLevel <= LevelDebug = return $ ansi [SetColor Foreground Vivid Black] ++ "\n@(" ++ fileLocStr ++ ")" | otherwise = return "" fileLocStr = fromMaybe file (stripPrefix dirRoot file) ++ ':' : line loc ++ ':' : char loc where file = loc_filename loc line = show . fst . loc_start char = show . snd . loc_start dirRoot = $(lift . T.unpack . fromJust . T.stripSuffix (T.pack $ "Stack" </> "Types" </> "StackT.hs") . T.pack . loc_filename =<< location) -- | The length of a timestamp in the format "YYYY-MM-DD hh:mm:ss.μμμμμμ". -- This definition is top-level in order to avoid multiple reevaluation at runtime. timestampLength :: Int timestampLength = length (formatTime defaultTimeLocale "%F %T.000000" (UTCTime (ModifiedJulianDay 0) 0)) -- | With a sticky state, do the thing. withSticky :: (MonadIO m) => Bool -> (Sticky -> m b) -> m b withSticky terminal m = if terminal then do state <- liftIO (newMVar Nothing) originalMode <- liftIO (hGetBuffering stdout) liftIO (hSetBuffering stdout NoBuffering) a <- m (Sticky (Just state)) state' <- liftIO (takeMVar state) liftIO (when (isJust state') (S8.putStr "\n")) liftIO (hSetBuffering stdout originalMode) return a else m (Sticky Nothing) -- | Write a "sticky" line to the terminal. Any subsequent lines will -- overwrite this one, and that same line will be repeated below -- again. In other words, the line sticks at the bottom of the output -- forever. Running this function again will replace the sticky line -- with a new sticky line. When you want to get rid of the sticky -- line, run 'logStickyDone'. -- logSticky :: Q Exp logSticky = logOther "sticky" -- | This will print out the given message with a newline and disable -- any further stickiness of the line until a new call to 'logSticky' -- happens. -- -- It might be better at some point to have a 'runSticky' function -- that encompasses the logSticky->logStickyDone pairing. logStickyDone :: Q Exp logStickyDone = logOther "sticky-done"
AndrewRademacher/stack
src/Stack/Types/StackT.hs
bsd-3-clause
15,566
0
24
4,618
3,520
1,795
1,725
339
7
module Geometry.Point ( Rect, Polar , Point , magPoint , argPoint , normaliseAngle , polarOfRectPoint , genPointsUniform , genPointsUniformWithSeed) where import qualified Points2D.Generate as P import qualified Data.Vector.Unboxed as V import Data.Vector.Unboxed (Vector) -- | Coordinate system. data Rect data Polar -- | A 2d point in some coordinate system. type Point coords = (Double, Double) -- | Take the magnitude of a point. magPoint :: Point Rect -> Double magPoint (x, y) = sqrt (x * x + y * y) -- | Take the angle of a point, between 0 and 2*pi radians. argPoint :: Point Rect -> Double argPoint (x, y) = normaliseAngle $ atan2 y x -- | Normalise an angle to be between 0 and 2*pi radians normaliseAngle :: Double -> Double normaliseAngle f | f < 0 = normaliseAngle (f + 2 * pi) | f > 2 * pi = normaliseAngle (f - 2 * pi) | otherwise = f -- | Convert a point from rectangular to polar coordinates. polarOfRectPoint :: Point Rect -> Point Polar polarOfRectPoint p = let r = magPoint p theta = argPoint p in (r, theta) -- | Generate some random points genPointsUniform :: Int -> Double -> Double -> Vector (Point a) genPointsUniform n mi mx = V.map (\(x, y) -> (x, y)) $ P.genPointsUniform n mi mx -- | Generate some random points using a seed value genPointsUniformWithSeed :: Int -> Int -> Double -> Double -> Vector (Point a) genPointsUniformWithSeed seed n mi mx = V.map (\(x, y) -> (x, y)) $ P.genPointsUniformWithSeed seed n mi mx
mainland/dph
dph-examples/broken/Visibility/Geometry/Point.hs
bsd-3-clause
1,494
33
11
310
494
270
224
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 This module defines interface types and binders -} {-# LANGUAGE CPP, FlexibleInstances, BangPatterns #-} {-# LANGUAGE MultiWayIf #-} -- FlexibleInstances for Binary (DefMethSpec IfaceType) module IfaceType ( IfExtName, IfLclName, IfaceType(..), IfacePredType, IfaceKind, IfaceCoercion(..), IfaceUnivCoProv(..), IfaceTyCon(..), IfaceTyConInfo(..), IfaceTyConSort(..), IsPromoted(..), IfaceTyLit(..), IfaceTcArgs(..), IfaceContext, IfaceBndr(..), IfaceOneShot(..), IfaceLamBndr, IfaceTvBndr, IfaceIdBndr, IfaceTyConBinder, IfaceForAllBndr, ArgFlag(..), ShowForAllFlag(..), ifForAllBndrTyVar, ifForAllBndrName, ifTyConBinderTyVar, ifTyConBinderName, -- Equality testing isIfaceLiftedTypeKind, -- Conversion from IfaceTcArgs -> [IfaceType] tcArgsIfaceTypes, -- Printing pprIfaceType, pprParendIfaceType, pprPrecIfaceType, pprIfaceContext, pprIfaceContextArr, pprIfaceIdBndr, pprIfaceLamBndr, pprIfaceTvBndr, pprIfaceTyConBinders, pprIfaceBndrs, pprIfaceTcArgs, pprParendIfaceTcArgs, pprIfaceForAllPart, pprIfaceForAllPartMust, pprIfaceForAll, pprIfaceSigmaType, pprIfaceTyLit, pprIfaceCoercion, pprParendIfaceCoercion, splitIfaceSigmaTy, pprIfaceTypeApp, pprUserIfaceForAll, pprIfaceCoTcApp, pprTyTcApp, pprIfacePrefixApp, suppressIfaceInvisibles, stripIfaceInvisVars, stripInvisArgs, mkIfaceTySubst, substIfaceTyVar, substIfaceTcArgs, inDomIfaceTySubst ) where #include "HsVersions.h" import GhcPrelude import {-# SOURCE #-} TysWiredIn ( liftedRepDataConTyCon ) import DynFlags import TyCon hiding ( pprPromotionQuote ) import CoAxiom import Var import PrelNames import Name import BasicTypes import Binary import Outputable import FastString import FastStringEnv import Util import Data.Maybe( isJust ) import Data.List (foldl') import qualified Data.Semigroup as Semi {- ************************************************************************ * * Local (nested) binders * * ************************************************************************ -} type IfLclName = FastString -- A local name in iface syntax type IfExtName = Name -- An External or WiredIn Name can appear in IfaceSyn -- (However Internal or System Names never should) data IfaceBndr -- Local (non-top-level) binders = IfaceIdBndr {-# UNPACK #-} !IfaceIdBndr | IfaceTvBndr {-# UNPACK #-} !IfaceTvBndr type IfaceIdBndr = (IfLclName, IfaceType) type IfaceTvBndr = (IfLclName, IfaceKind) ifaceTvBndrName :: IfaceTvBndr -> IfLclName ifaceTvBndrName (n,_) = n type IfaceLamBndr = (IfaceBndr, IfaceOneShot) data IfaceOneShot -- See Note [Preserve OneShotInfo] in CoreTicy = IfaceNoOneShot -- and Note [The oneShot function] in MkId | IfaceOneShot {- %************************************************************************ %* * IfaceType %* * %************************************************************************ -} ------------------------------- type IfaceKind = IfaceType data IfaceType -- A kind of universal type, used for types and kinds = IfaceFreeTyVar TyVar -- See Note [Free tyvars in IfaceType] | IfaceTyVar IfLclName -- Type/coercion variable only, not tycon | IfaceLitTy IfaceTyLit | IfaceAppTy IfaceType IfaceType | IfaceFunTy IfaceType IfaceType | IfaceDFunTy IfaceType IfaceType | IfaceForAllTy IfaceForAllBndr IfaceType | IfaceTyConApp IfaceTyCon IfaceTcArgs -- Not necessarily saturated -- Includes newtypes, synonyms, tuples | IfaceCastTy IfaceType IfaceCoercion | IfaceCoercionTy IfaceCoercion | IfaceTupleTy -- Saturated tuples (unsaturated ones use IfaceTyConApp) TupleSort -- What sort of tuple? IsPromoted -- A bit like IfaceTyCon IfaceTcArgs -- arity = length args -- For promoted data cons, the kind args are omitted type IfacePredType = IfaceType type IfaceContext = [IfacePredType] data IfaceTyLit = IfaceNumTyLit Integer | IfaceStrTyLit FastString deriving (Eq) type IfaceTyConBinder = TyVarBndr IfaceTvBndr TyConBndrVis type IfaceForAllBndr = TyVarBndr IfaceTvBndr ArgFlag -- See Note [Suppressing invisible arguments] -- We use a new list type (rather than [(IfaceType,Bool)], because -- it'll be more compact and faster to parse in interface -- files. Rather than two bytes and two decisions (nil/cons, and -- type/kind) there'll just be one. data IfaceTcArgs = ITC_Nil | ITC_Vis IfaceType IfaceTcArgs -- "Vis" means show when pretty-printing | ITC_Invis IfaceKind IfaceTcArgs -- "Invis" means don't show when pretty-printing -- except with -fprint-explicit-kinds instance Semi.Semigroup IfaceTcArgs where ITC_Nil <> xs = xs ITC_Vis ty rest <> xs = ITC_Vis ty (rest Semi.<> xs) ITC_Invis ki rest <> xs = ITC_Invis ki (rest Semi.<> xs) instance Monoid IfaceTcArgs where mempty = ITC_Nil mappend = (Semi.<>) -- Encodes type constructors, kind constructors, -- coercion constructors, the lot. -- We have to tag them in order to pretty print them -- properly. data IfaceTyCon = IfaceTyCon { ifaceTyConName :: IfExtName , ifaceTyConInfo :: IfaceTyConInfo } deriving (Eq) -- | Is a TyCon a promoted data constructor or just a normal type constructor? data IsPromoted = IsNotPromoted | IsPromoted deriving (Eq) -- | The various types of TyCons which have special, built-in syntax. data IfaceTyConSort = IfaceNormalTyCon -- ^ a regular tycon | IfaceTupleTyCon !Arity !TupleSort -- ^ e.g. @(a, b, c)@ or @(#a, b, c#)@. -- The arity is the tuple width, not the tycon arity -- (which is twice the width in the case of unboxed -- tuples). | IfaceSumTyCon !Arity -- ^ e.g. @(a | b | c)@ | IfaceEqualityTyCon -- ^ A heterogeneous equality TyCon -- (i.e. eqPrimTyCon, eqReprPrimTyCon, heqTyCon) -- that is actually being applied to two types -- of the same kind. This affects pretty-printing -- only: see Note [Equality predicates in IfaceType] deriving (Eq) {- Note [Free tyvars in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nowadays (since Nov 16, 2016) we pretty-print a Type by converting to an IfaceType and pretty printing that. This eliminates a lot of pretty-print duplication, and it matches what we do with pretty-printing TyThings. It works fine for closed types, but when printing debug traces (e.g. when using -ddump-tc-trace) we print a lot of /open/ types. These types are full of TcTyVars, and it's absolutely crucial to print them in their full glory, with their unique, TcTyVarDetails etc. So we simply embed a TyVar in IfaceType with the IfaceFreeTyVar constructor. Note that: * We never expect to serialise an IfaceFreeTyVar into an interface file, nor to deserialise one. IfaceFreeTyVar is used only in the "convert to IfaceType and then pretty-print" pipeline. We do the same for covars, naturally. Note [Equality predicates in IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC has several varieties of type equality (see Note [The equality types story] in TysPrim for details). In an effort to avoid confusing users, we suppress the differences during "normal" pretty printing. Specifically we display them like this: Predicate Pretty-printed as Homogeneous case Heterogeneous case ---------------- ----------------- ------------------- (~) eqTyCon ~ N/A (~~) heqTyCon ~ ~~ (~#) eqPrimTyCon ~# ~~ (~R#) eqReprPrimTyCon Coercible Coercible By "homogeneeous case" we mean cases where a hetero-kinded equality (all but the first above) is actually applied to two identical kinds. Unfortunately, determining this from an IfaceType isn't possible since we can't see through type synonyms. Consequently, we need to record whether this particular application is homogeneous in IfaceTyConSort for the purposes of pretty-printing. All this suppresses information. To get the ground truth, use -dppr-debug (see 'print_eqs' in 'ppr_equality'). See Note [The equality types story] in TysPrim. -} data IfaceTyConInfo -- Used to guide pretty-printing -- and to disambiguate D from 'D (they share a name) = IfaceTyConInfo { ifaceTyConIsPromoted :: IsPromoted , ifaceTyConSort :: IfaceTyConSort } deriving (Eq) data IfaceCoercion = IfaceReflCo Role IfaceType | IfaceFunCo Role IfaceCoercion IfaceCoercion | IfaceTyConAppCo Role IfaceTyCon [IfaceCoercion] | IfaceAppCo IfaceCoercion IfaceCoercion | IfaceForAllCo IfaceTvBndr IfaceCoercion IfaceCoercion | IfaceCoVarCo IfLclName | IfaceAxiomInstCo IfExtName BranchIndex [IfaceCoercion] | IfaceUnivCo IfaceUnivCoProv Role IfaceType IfaceType | IfaceSymCo IfaceCoercion | IfaceTransCo IfaceCoercion IfaceCoercion | IfaceNthCo Int IfaceCoercion | IfaceLRCo LeftOrRight IfaceCoercion | IfaceInstCo IfaceCoercion IfaceCoercion | IfaceCoherenceCo IfaceCoercion IfaceCoercion | IfaceKindCo IfaceCoercion | IfaceSubCo IfaceCoercion | IfaceAxiomRuleCo IfLclName [IfaceCoercion] | IfaceFreeCoVar CoVar -- See Note [Free tyvars in IfaceType] | IfaceHoleCo CoVar -- ^ See Note [Holes in IfaceCoercion] data IfaceUnivCoProv = IfaceUnsafeCoerceProv | IfacePhantomProv IfaceCoercion | IfaceProofIrrelProv IfaceCoercion | IfacePluginProv String {- Note [Holes in IfaceCoercion] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When typechecking fails the typechecker will produce a HoleCo to stand in place of the unproven assertion. While we generally don't want to let these unproven assertions leak into interface files, we still need to be able to pretty-print them as we use IfaceType's pretty-printer to render Types. For this reason IfaceCoercion has a IfaceHoleCo constructor; however, we fails when asked to serialize to a IfaceHoleCo to ensure that they don't end up in an interface file. %************************************************************************ %* * Functions over IFaceTypes * * ************************************************************************ -} ifaceTyConHasKey :: IfaceTyCon -> Unique -> Bool ifaceTyConHasKey tc key = ifaceTyConName tc `hasKey` key isIfaceLiftedTypeKind :: IfaceKind -> Bool isIfaceLiftedTypeKind (IfaceTyConApp tc ITC_Nil) = isLiftedTypeKindTyConName (ifaceTyConName tc) isIfaceLiftedTypeKind (IfaceTyConApp tc (ITC_Vis (IfaceTyConApp ptr_rep_lifted ITC_Nil) ITC_Nil)) = tc `ifaceTyConHasKey` tYPETyConKey && ptr_rep_lifted `ifaceTyConHasKey` liftedRepDataConKey isIfaceLiftedTypeKind _ = False splitIfaceSigmaTy :: IfaceType -> ([IfaceForAllBndr], [IfacePredType], IfaceType) -- Mainly for printing purposes splitIfaceSigmaTy ty = (bndrs, theta, tau) where (bndrs, rho) = split_foralls ty (theta, tau) = split_rho rho split_foralls (IfaceForAllTy bndr ty) = case split_foralls ty of { (bndrs, rho) -> (bndr:bndrs, rho) } split_foralls rho = ([], rho) split_rho (IfaceDFunTy ty1 ty2) = case split_rho ty2 of { (ps, tau) -> (ty1:ps, tau) } split_rho tau = ([], tau) suppressIfaceInvisibles :: DynFlags -> [IfaceTyConBinder] -> [a] -> [a] suppressIfaceInvisibles dflags tys xs | gopt Opt_PrintExplicitKinds dflags = xs | otherwise = suppress tys xs where suppress _ [] = [] suppress [] a = a suppress (k:ks) (x:xs) | isInvisibleTyConBinder k = suppress ks xs | otherwise = x : suppress ks xs stripIfaceInvisVars :: DynFlags -> [IfaceTyConBinder] -> [IfaceTyConBinder] stripIfaceInvisVars dflags tyvars | gopt Opt_PrintExplicitKinds dflags = tyvars | otherwise = filterOut isInvisibleTyConBinder tyvars -- | Extract an 'IfaceTvBndr' from an 'IfaceForAllBndr'. ifForAllBndrTyVar :: IfaceForAllBndr -> IfaceTvBndr ifForAllBndrTyVar = binderVar -- | Extract the variable name from an 'IfaceForAllBndr'. ifForAllBndrName :: IfaceForAllBndr -> IfLclName ifForAllBndrName fab = ifaceTvBndrName (ifForAllBndrTyVar fab) -- | Extract an 'IfaceTvBndr' from an 'IfaceTyConBinder'. ifTyConBinderTyVar :: IfaceTyConBinder -> IfaceTvBndr ifTyConBinderTyVar = binderVar -- | Extract the variable name from an 'IfaceTyConBinder'. ifTyConBinderName :: IfaceTyConBinder -> IfLclName ifTyConBinderName tcb = ifaceTvBndrName (ifTyConBinderTyVar tcb) ifTypeIsVarFree :: IfaceType -> Bool -- Returns True if the type definitely has no variables at all -- Just used to control pretty printing ifTypeIsVarFree ty = go ty where go (IfaceTyVar {}) = False go (IfaceFreeTyVar {}) = False go (IfaceAppTy fun arg) = go fun && go arg go (IfaceFunTy arg res) = go arg && go res go (IfaceDFunTy arg res) = go arg && go res go (IfaceForAllTy {}) = False go (IfaceTyConApp _ args) = go_args args go (IfaceTupleTy _ _ args) = go_args args go (IfaceLitTy _) = True go (IfaceCastTy {}) = False -- Safe go (IfaceCoercionTy {}) = False -- Safe go_args ITC_Nil = True go_args (ITC_Vis arg args) = go arg && go_args args go_args (ITC_Invis arg args) = go arg && go_args args {- Note [Substitution on IfaceType] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Substitutions on IfaceType are done only during pretty-printing to construct the result type of a GADT, and does not deal with binders (eg IfaceForAll), so it doesn't need fancy capture stuff. -} type IfaceTySubst = FastStringEnv IfaceType -- Note [Substitution on IfaceType] mkIfaceTySubst :: [(IfLclName,IfaceType)] -> IfaceTySubst -- See Note [Substitution on IfaceType] mkIfaceTySubst eq_spec = mkFsEnv eq_spec inDomIfaceTySubst :: IfaceTySubst -> IfaceTvBndr -> Bool -- See Note [Substitution on IfaceType] inDomIfaceTySubst subst (fs, _) = isJust (lookupFsEnv subst fs) substIfaceType :: IfaceTySubst -> IfaceType -> IfaceType -- See Note [Substitution on IfaceType] substIfaceType env ty = go ty where go (IfaceFreeTyVar tv) = IfaceFreeTyVar tv go (IfaceTyVar tv) = substIfaceTyVar env tv go (IfaceAppTy t1 t2) = IfaceAppTy (go t1) (go t2) go (IfaceFunTy t1 t2) = IfaceFunTy (go t1) (go t2) go (IfaceDFunTy t1 t2) = IfaceDFunTy (go t1) (go t2) go ty@(IfaceLitTy {}) = ty go (IfaceTyConApp tc tys) = IfaceTyConApp tc (substIfaceTcArgs env tys) go (IfaceTupleTy s i tys) = IfaceTupleTy s i (substIfaceTcArgs env tys) go (IfaceForAllTy {}) = pprPanic "substIfaceType" (ppr ty) go (IfaceCastTy ty co) = IfaceCastTy (go ty) (go_co co) go (IfaceCoercionTy co) = IfaceCoercionTy (go_co co) go_co (IfaceReflCo r ty) = IfaceReflCo r (go ty) go_co (IfaceFunCo r c1 c2) = IfaceFunCo r (go_co c1) (go_co c2) go_co (IfaceTyConAppCo r tc cos) = IfaceTyConAppCo r tc (go_cos cos) go_co (IfaceAppCo c1 c2) = IfaceAppCo (go_co c1) (go_co c2) go_co (IfaceForAllCo {}) = pprPanic "substIfaceCoercion" (ppr ty) go_co (IfaceFreeCoVar cv) = IfaceFreeCoVar cv go_co (IfaceCoVarCo cv) = IfaceCoVarCo cv go_co (IfaceHoleCo cv) = IfaceHoleCo cv go_co (IfaceAxiomInstCo a i cos) = IfaceAxiomInstCo a i (go_cos cos) go_co (IfaceUnivCo prov r t1 t2) = IfaceUnivCo (go_prov prov) r (go t1) (go t2) go_co (IfaceSymCo co) = IfaceSymCo (go_co co) go_co (IfaceTransCo co1 co2) = IfaceTransCo (go_co co1) (go_co co2) go_co (IfaceNthCo n co) = IfaceNthCo n (go_co co) go_co (IfaceLRCo lr co) = IfaceLRCo lr (go_co co) go_co (IfaceInstCo c1 c2) = IfaceInstCo (go_co c1) (go_co c2) go_co (IfaceCoherenceCo c1 c2) = IfaceCoherenceCo (go_co c1) (go_co c2) go_co (IfaceKindCo co) = IfaceKindCo (go_co co) go_co (IfaceSubCo co) = IfaceSubCo (go_co co) go_co (IfaceAxiomRuleCo n cos) = IfaceAxiomRuleCo n (go_cos cos) go_cos = map go_co go_prov IfaceUnsafeCoerceProv = IfaceUnsafeCoerceProv go_prov (IfacePhantomProv co) = IfacePhantomProv (go_co co) go_prov (IfaceProofIrrelProv co) = IfaceProofIrrelProv (go_co co) go_prov (IfacePluginProv str) = IfacePluginProv str substIfaceTcArgs :: IfaceTySubst -> IfaceTcArgs -> IfaceTcArgs substIfaceTcArgs env args = go args where go ITC_Nil = ITC_Nil go (ITC_Vis ty tys) = ITC_Vis (substIfaceType env ty) (go tys) go (ITC_Invis ty tys) = ITC_Invis (substIfaceType env ty) (go tys) substIfaceTyVar :: IfaceTySubst -> IfLclName -> IfaceType substIfaceTyVar env tv | Just ty <- lookupFsEnv env tv = ty | otherwise = IfaceTyVar tv {- ************************************************************************ * * Functions over IFaceTcArgs * * ************************************************************************ -} stripInvisArgs :: DynFlags -> IfaceTcArgs -> IfaceTcArgs stripInvisArgs dflags tys | gopt Opt_PrintExplicitKinds dflags = tys | otherwise = suppress_invis tys where suppress_invis c = case c of ITC_Invis _ ts -> suppress_invis ts _ -> c tcArgsIfaceTypes :: IfaceTcArgs -> [IfaceType] tcArgsIfaceTypes ITC_Nil = [] tcArgsIfaceTypes (ITC_Invis t ts) = t : tcArgsIfaceTypes ts tcArgsIfaceTypes (ITC_Vis t ts) = t : tcArgsIfaceTypes ts ifaceVisTcArgsLength :: IfaceTcArgs -> Int ifaceVisTcArgsLength = go 0 where go !n ITC_Nil = n go n (ITC_Vis _ rest) = go (n+1) rest go n (ITC_Invis _ rest) = go n rest {- Note [Suppressing invisible arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We use the IfaceTcArgs to specify which of the arguments to a type constructor should be displayed when pretty-printing, under the control of -fprint-explicit-kinds. See also Type.filterOutInvisibleTypes. For example, given T :: forall k. (k->*) -> k -> * -- Ordinary kind polymorphism 'Just :: forall k. k -> 'Maybe k -- Promoted we want T * Tree Int prints as T Tree Int 'Just * prints as Just * ************************************************************************ * * Pretty-printing * * ************************************************************************ -} if_print_coercions :: SDoc -- ^ if printing coercions -> SDoc -- ^ otherwise -> SDoc if_print_coercions yes no = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> if gopt Opt_PrintExplicitCoercions dflags || dumpStyle style || debugStyle style then yes else no pprIfaceInfixApp :: TyPrec -> SDoc -> SDoc -> SDoc -> SDoc pprIfaceInfixApp ctxt_prec pp_tc pp_ty1 pp_ty2 = maybeParen ctxt_prec TyOpPrec $ sep [pp_ty1, pp_tc <+> pp_ty2] pprIfacePrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc pprIfacePrefixApp ctxt_prec pp_fun pp_tys | null pp_tys = pp_fun | otherwise = maybeParen ctxt_prec TyConPrec $ hang pp_fun 2 (sep pp_tys) -- ----------------------------- Printing binders ------------------------------------ instance Outputable IfaceBndr where ppr (IfaceIdBndr bndr) = pprIfaceIdBndr bndr ppr (IfaceTvBndr bndr) = char '@' <+> pprIfaceTvBndr False bndr pprIfaceBndrs :: [IfaceBndr] -> SDoc pprIfaceBndrs bs = sep (map ppr bs) pprIfaceLamBndr :: IfaceLamBndr -> SDoc pprIfaceLamBndr (b, IfaceNoOneShot) = ppr b pprIfaceLamBndr (b, IfaceOneShot) = ppr b <> text "[OneShot]" pprIfaceIdBndr :: IfaceIdBndr -> SDoc pprIfaceIdBndr (name, ty) = parens (ppr name <+> dcolon <+> ppr ty) pprIfaceTvBndr :: Bool -> IfaceTvBndr -> SDoc pprIfaceTvBndr use_parens (tv, ki) | isIfaceLiftedTypeKind ki = ppr tv | otherwise = maybe_parens (ppr tv <+> dcolon <+> ppr ki) where maybe_parens | use_parens = parens | otherwise = id pprIfaceTyConBinders :: [IfaceTyConBinder] -> SDoc pprIfaceTyConBinders = sep . map go where go tcb = pprIfaceTvBndr True (ifTyConBinderTyVar tcb) instance Binary IfaceBndr where put_ bh (IfaceIdBndr aa) = do putByte bh 0 put_ bh aa put_ bh (IfaceTvBndr ab) = do putByte bh 1 put_ bh ab get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (IfaceIdBndr aa) _ -> do ab <- get bh return (IfaceTvBndr ab) instance Binary IfaceOneShot where put_ bh IfaceNoOneShot = do putByte bh 0 put_ bh IfaceOneShot = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do return IfaceNoOneShot _ -> do return IfaceOneShot -- ----------------------------- Printing IfaceType ------------------------------------ --------------------------------- instance Outputable IfaceType where ppr ty = pprIfaceType ty pprIfaceType, pprParendIfaceType :: IfaceType -> SDoc pprIfaceType = pprPrecIfaceType TopPrec pprParendIfaceType = pprPrecIfaceType TyConPrec pprPrecIfaceType :: TyPrec -> IfaceType -> SDoc pprPrecIfaceType prec ty = eliminateRuntimeRep (ppr_ty prec) ty ppr_ty :: TyPrec -> IfaceType -> SDoc ppr_ty _ (IfaceFreeTyVar tyvar) = ppr tyvar -- This is the main reson for IfaceFreeTyVar! ppr_ty _ (IfaceTyVar tyvar) = ppr tyvar -- See Note [TcTyVars in IfaceType] ppr_ty ctxt_prec (IfaceTyConApp tc tys) = pprTyTcApp ctxt_prec tc tys ppr_ty _ (IfaceTupleTy i p tys) = pprTuple i p tys ppr_ty _ (IfaceLitTy n) = pprIfaceTyLit n -- Function types ppr_ty ctxt_prec (IfaceFunTy ty1 ty2) = -- We don't want to lose synonyms, so we mustn't use splitFunTys here. maybeParen ctxt_prec FunPrec $ sep [ppr_ty FunPrec ty1, sep (ppr_fun_tail ty2)] where ppr_fun_tail (IfaceFunTy ty1 ty2) = (arrow <+> ppr_ty FunPrec ty1) : ppr_fun_tail ty2 ppr_fun_tail other_ty = [arrow <+> pprIfaceType other_ty] ppr_ty ctxt_prec (IfaceAppTy ty1 ty2) = if_print_coercions ppr_app_ty ppr_app_ty_no_casts where ppr_app_ty = maybeParen ctxt_prec TyConPrec $ ppr_ty FunPrec ty1 <+> ppr_ty TyConPrec ty2 -- Strip any casts from the head of the application ppr_app_ty_no_casts = case split_app_tys ty1 (ITC_Vis ty2 ITC_Nil) of (IfaceCastTy head _, args) -> ppr_ty ctxt_prec (mk_app_tys head args) _ -> ppr_app_ty split_app_tys :: IfaceType -> IfaceTcArgs -> (IfaceType, IfaceTcArgs) split_app_tys (IfaceAppTy t1 t2) args = split_app_tys t1 (t2 `ITC_Vis` args) split_app_tys head args = (head, args) mk_app_tys :: IfaceType -> IfaceTcArgs -> IfaceType mk_app_tys (IfaceTyConApp tc tys1) tys2 = IfaceTyConApp tc (tys1 `mappend` tys2) mk_app_tys t1 tys2 = foldl' IfaceAppTy t1 (tcArgsIfaceTypes tys2) ppr_ty ctxt_prec (IfaceCastTy ty co) = if_print_coercions (parens (ppr_ty TopPrec ty <+> text "|>" <+> ppr co)) (ppr_ty ctxt_prec ty) ppr_ty ctxt_prec (IfaceCoercionTy co) = if_print_coercions (ppr_co ctxt_prec co) (text "<>") ppr_ty ctxt_prec ty = maybeParen ctxt_prec FunPrec (pprIfaceSigmaType ShowForAllMust ty) {- Note [Defaulting RuntimeRep variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RuntimeRep variables are considered by many (most?) users to be little more than syntactic noise. When the notion was introduced there was a signficant and understandable push-back from those with pedagogy in mind, which argued that RuntimeRep variables would throw a wrench into nearly any teach approach since they appear in even the lowly ($) function's type, ($) :: forall (w :: RuntimeRep) a (b :: TYPE w). (a -> b) -> a -> b which is significantly less readable than its non RuntimeRep-polymorphic type of ($) :: (a -> b) -> a -> b Moreover, unboxed types don't appear all that often in run-of-the-mill Haskell programs, so it makes little sense to make all users pay this syntactic overhead. For this reason it was decided that we would hide RuntimeRep variables for now (see #11549). We do this by defaulting all type variables of kind RuntimeRep to PtrLiftedRep. This is done in a pass right before pretty-printing (defaultRuntimeRepVars, controlled by -fprint-explicit-runtime-reps) -} -- | Default 'RuntimeRep' variables to 'LiftedPtr'. e.g. -- -- @ -- ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r). -- (a -> b) -> a -> b -- @ -- -- turns in to, -- -- @ ($) :: forall a (b :: *). (a -> b) -> a -> b @ -- -- We do this to prevent RuntimeRep variables from incurring a significant -- syntactic overhead in otherwise simple type signatures (e.g. ($)). See -- Note [Defaulting RuntimeRep variables] and #11549 for further discussion. -- defaultRuntimeRepVars :: IfaceType -> IfaceType defaultRuntimeRepVars = go emptyFsEnv where go :: FastStringEnv () -> IfaceType -> IfaceType go subs (IfaceForAllTy bndr ty) | isRuntimeRep var_kind , isInvisibleArgFlag (binderArgFlag bndr) -- don't default *visible* quantification -- or we get the mess in #13963 = let subs' = extendFsEnv subs var () in go subs' ty | otherwise = IfaceForAllTy (TvBndr (var, go subs var_kind) (binderArgFlag bndr)) (go subs ty) where var :: IfLclName (var, var_kind) = binderVar bndr go subs (IfaceTyVar tv) | tv `elemFsEnv` subs = IfaceTyConApp liftedRep ITC_Nil go subs (IfaceFunTy kind ty) = IfaceFunTy (go subs kind) (go subs ty) go subs (IfaceAppTy x y) = IfaceAppTy (go subs x) (go subs y) go subs (IfaceDFunTy x y) = IfaceDFunTy (go subs x) (go subs y) go subs (IfaceCastTy x co) = IfaceCastTy (go subs x) co go _ other = other liftedRep :: IfaceTyCon liftedRep = IfaceTyCon dc_name (IfaceTyConInfo IsPromoted IfaceNormalTyCon) where dc_name = getName liftedRepDataConTyCon isRuntimeRep :: IfaceType -> Bool isRuntimeRep (IfaceTyConApp tc _) = tc `ifaceTyConHasKey` runtimeRepTyConKey isRuntimeRep _ = False eliminateRuntimeRep :: (IfaceType -> SDoc) -> IfaceType -> SDoc eliminateRuntimeRep f ty = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitRuntimeReps dflags then f ty else f (defaultRuntimeRepVars ty) instance Outputable IfaceTcArgs where ppr tca = pprIfaceTcArgs tca pprIfaceTcArgs, pprParendIfaceTcArgs :: IfaceTcArgs -> SDoc pprIfaceTcArgs = ppr_tc_args TopPrec pprParendIfaceTcArgs = ppr_tc_args TyConPrec ppr_tc_args :: TyPrec -> IfaceTcArgs -> SDoc ppr_tc_args ctx_prec args = let pprTys t ts = ppr_ty ctx_prec t <+> ppr_tc_args ctx_prec ts in case args of ITC_Nil -> empty ITC_Vis t ts -> pprTys t ts ITC_Invis t ts -> pprTys t ts ------------------- pprIfaceForAllPart :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPart tvs ctxt sdoc = ppr_iface_forall_part ShowForAllWhen tvs ctxt sdoc -- | Like 'pprIfaceForAllPart', but always uses an explicit @forall@. pprIfaceForAllPartMust :: [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc pprIfaceForAllPartMust tvs ctxt sdoc = ppr_iface_forall_part ShowForAllMust tvs ctxt sdoc pprIfaceForAllCoPart :: [(IfLclName, IfaceCoercion)] -> SDoc -> SDoc pprIfaceForAllCoPart tvs sdoc = sep [ pprIfaceForAllCo tvs, sdoc ] ppr_iface_forall_part :: ShowForAllFlag -> [IfaceForAllBndr] -> [IfacePredType] -> SDoc -> SDoc ppr_iface_forall_part show_forall tvs ctxt sdoc = sep [ case show_forall of ShowForAllMust -> pprIfaceForAll tvs ShowForAllWhen -> pprUserIfaceForAll tvs , pprIfaceContextArr ctxt , sdoc] -- | Render the "forall ... ." or "forall ... ->" bit of a type. pprIfaceForAll :: [IfaceForAllBndr] -> SDoc pprIfaceForAll [] = empty pprIfaceForAll bndrs@(TvBndr _ vis : _) = add_separator (forAllLit <+> doc) <+> pprIfaceForAll bndrs' where (bndrs', doc) = ppr_itv_bndrs bndrs vis add_separator stuff = case vis of Required -> stuff <+> arrow _inv -> stuff <> dot -- | Render the ... in @(forall ... .)@ or @(forall ... ->)@. -- Returns both the list of not-yet-rendered binders and the doc. -- No anonymous binders here! ppr_itv_bndrs :: [IfaceForAllBndr] -> ArgFlag -- ^ visibility of the first binder in the list -> ([IfaceForAllBndr], SDoc) ppr_itv_bndrs all_bndrs@(bndr@(TvBndr _ vis) : bndrs) vis1 | vis `sameVis` vis1 = let (bndrs', doc) = ppr_itv_bndrs bndrs vis1 in (bndrs', pprIfaceForAllBndr bndr <+> doc) | otherwise = (all_bndrs, empty) ppr_itv_bndrs [] _ = ([], empty) pprIfaceForAllCo :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCo [] = empty pprIfaceForAllCo tvs = text "forall" <+> pprIfaceForAllCoBndrs tvs <> dot pprIfaceForAllCoBndrs :: [(IfLclName, IfaceCoercion)] -> SDoc pprIfaceForAllCoBndrs bndrs = hsep $ map pprIfaceForAllCoBndr bndrs pprIfaceForAllBndr :: IfaceForAllBndr -> SDoc pprIfaceForAllBndr (TvBndr tv Inferred) = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitForalls dflags then braces $ pprIfaceTvBndr False tv else pprIfaceTvBndr True tv pprIfaceForAllBndr (TvBndr tv _) = pprIfaceTvBndr True tv pprIfaceForAllCoBndr :: (IfLclName, IfaceCoercion) -> SDoc pprIfaceForAllCoBndr (tv, kind_co) = parens (ppr tv <+> dcolon <+> pprIfaceCoercion kind_co) -- | Show forall flag -- -- Unconditionally show the forall quantifier with ('ShowForAllMust') -- or when ('ShowForAllWhen') the names used are free in the binder -- or when compiling with -fprint-explicit-foralls. data ShowForAllFlag = ShowForAllMust | ShowForAllWhen pprIfaceSigmaType :: ShowForAllFlag -> IfaceType -> SDoc pprIfaceSigmaType show_forall ty = ppr_iface_forall_part show_forall tvs theta (ppr tau) where (tvs, theta, tau) = splitIfaceSigmaTy ty pprUserIfaceForAll :: [IfaceForAllBndr] -> SDoc pprUserIfaceForAll tvs = sdocWithDynFlags $ \dflags -> ppWhen (any tv_has_kind_var tvs || gopt Opt_PrintExplicitForalls dflags) $ pprIfaceForAll tvs where tv_has_kind_var (TvBndr (_,kind) _) = not (ifTypeIsVarFree kind) ------------------- -- See equivalent function in TyCoRep.hs pprIfaceTyList :: TyPrec -> IfaceType -> IfaceType -> SDoc -- Given a type-level list (t1 ': t2), see if we can print -- it in list notation [t1, ...]. -- Precondition: Opt_PrintExplicitKinds is off pprIfaceTyList ctxt_prec ty1 ty2 = case gather ty2 of (arg_tys, Nothing) -> char '\'' <> brackets (fsep (punctuate comma (map (ppr_ty TopPrec) (ty1:arg_tys)))) (arg_tys, Just tl) -> maybeParen ctxt_prec FunPrec $ hang (ppr_ty FunPrec ty1) 2 (fsep [ colon <+> ppr_ty FunPrec ty | ty <- arg_tys ++ [tl]]) where gather :: IfaceType -> ([IfaceType], Maybe IfaceType) -- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn] -- = (tys, Just tl) means ty is of form t1:t2:...tn:tl gather (IfaceTyConApp tc tys) | tc `ifaceTyConHasKey` consDataConKey , (ITC_Invis _ (ITC_Vis ty1 (ITC_Vis ty2 ITC_Nil))) <- tys , (args, tl) <- gather ty2 = (ty1:args, tl) | tc `ifaceTyConHasKey` nilDataConKey = ([], Nothing) gather ty = ([], Just ty) pprIfaceTypeApp :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> SDoc pprIfaceTypeApp prec tc args = pprTyTcApp prec tc args pprTyTcApp :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> SDoc pprTyTcApp ctxt_prec tc tys = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> pprTyTcApp' ctxt_prec tc tys dflags style pprTyTcApp' :: TyPrec -> IfaceTyCon -> IfaceTcArgs -> DynFlags -> PprStyle -> SDoc pprTyTcApp' ctxt_prec tc tys dflags style | ifaceTyConName tc `hasKey` ipClassKey , ITC_Vis (IfaceLitTy (IfaceStrTyLit n)) (ITC_Vis ty ITC_Nil) <- tys = maybeParen ctxt_prec FunPrec $ char '?' <> ftext n <> text "::" <> ppr_ty TopPrec ty | IfaceTupleTyCon arity sort <- ifaceTyConSort info , not (debugStyle style) , arity == ifaceVisTcArgsLength tys = pprTuple sort (ifaceTyConIsPromoted info) tys | IfaceSumTyCon arity <- ifaceTyConSort info = pprSum arity (ifaceTyConIsPromoted info) tys | tc `ifaceTyConHasKey` consDataConKey , not (gopt Opt_PrintExplicitKinds dflags) , ITC_Invis _ (ITC_Vis ty1 (ITC_Vis ty2 ITC_Nil)) <- tys = pprIfaceTyList ctxt_prec ty1 ty2 | tc `ifaceTyConHasKey` tYPETyConKey , ITC_Vis (IfaceTyConApp rep ITC_Nil) ITC_Nil <- tys , rep `ifaceTyConHasKey` liftedRepDataConKey = kindStar | otherwise = getPprDebug $ \dbg -> if | not dbg && tc `ifaceTyConHasKey` errorMessageTypeErrorFamKey -- Suppress detail unles you _really_ want to see -> text "(TypeError ...)" | Just doc <- ppr_equality ctxt_prec tc (tcArgsIfaceTypes tys) -> doc | otherwise -> ppr_iface_tc_app ppr_ty ctxt_prec tc tys_wo_kinds where info = ifaceTyConInfo tc tys_wo_kinds = tcArgsIfaceTypes $ stripInvisArgs dflags tys -- | Pretty-print a type-level equality. -- Returns (Just doc) if the argument is a /saturated/ application -- of eqTyCon (~) -- eqPrimTyCon (~#) -- eqReprPrimTyCon (~R#) -- hEqTyCon (~~) -- -- See Note [Equality predicates in IfaceType] -- and Note [The equality types story] in TysPrim ppr_equality :: TyPrec -> IfaceTyCon -> [IfaceType] -> Maybe SDoc ppr_equality ctxt_prec tc args | hetero_eq_tc , [k1, k2, t1, t2] <- args = Just $ print_equality (k1, k2, t1, t2) | hom_eq_tc , [k, t1, t2] <- args = Just $ print_equality (k, k, t1, t2) | otherwise = Nothing where homogeneous = case ifaceTyConSort $ ifaceTyConInfo tc of IfaceEqualityTyCon -> True _other -> False -- True <=> a heterogeneous equality whose arguments -- are (in this case) of the same kind tc_name = ifaceTyConName tc pp = ppr_ty hom_eq_tc = tc_name `hasKey` eqTyConKey -- (~) hetero_eq_tc = tc_name `hasKey` eqPrimTyConKey -- (~#) || tc_name `hasKey` eqReprPrimTyConKey -- (~R#) || tc_name `hasKey` heqTyConKey -- (~~) print_equality args = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> print_equality' args style dflags print_equality' (ki1, ki2, ty1, ty2) style dflags | print_eqs -- No magic, just print the original TyCon = ppr_infix_eq (ppr tc) | hetero_eq_tc , print_kinds || not homogeneous = ppr_infix_eq (text "~~") | otherwise = if tc_name `hasKey` eqReprPrimTyConKey then pprIfacePrefixApp ctxt_prec (text "Coercible") [pp TyConPrec ty1, pp TyConPrec ty2] else pprIfaceInfixApp ctxt_prec (char '~') (pp TyOpPrec ty1) (pp TyOpPrec ty2) where ppr_infix_eq eq_op = pprIfaceInfixApp ctxt_prec eq_op (parens (pp TopPrec ty1 <+> dcolon <+> pp TyOpPrec ki1)) (parens (pp TopPrec ty2 <+> dcolon <+> pp TyOpPrec ki2)) print_kinds = gopt Opt_PrintExplicitKinds dflags print_eqs = gopt Opt_PrintEqualityRelations dflags || dumpStyle style || debugStyle style pprIfaceCoTcApp :: TyPrec -> IfaceTyCon -> [IfaceCoercion] -> SDoc pprIfaceCoTcApp ctxt_prec tc tys = ppr_iface_tc_app ppr_co ctxt_prec tc tys ppr_iface_tc_app :: (TyPrec -> a -> SDoc) -> TyPrec -> IfaceTyCon -> [a] -> SDoc ppr_iface_tc_app pp _ tc [ty] | tc `ifaceTyConHasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp TopPrec ty) | tc `ifaceTyConHasKey` parrTyConKey = pprPromotionQuote tc <> paBrackets (pp TopPrec ty) ppr_iface_tc_app pp ctxt_prec tc tys | tc `ifaceTyConHasKey` starKindTyConKey || tc `ifaceTyConHasKey` liftedTypeKindTyConKey || tc `ifaceTyConHasKey` unicodeStarKindTyConKey = kindStar -- Handle unicode; do not wrap * in parens | not (isSymOcc (nameOccName (ifaceTyConName tc))) = pprIfacePrefixApp ctxt_prec (ppr tc) (map (pp TyConPrec) tys) | [ty1,ty2] <- tys -- Infix, two arguments; -- we know nothing of precedence though = pprIfaceInfixApp ctxt_prec (ppr tc) (pp TyOpPrec ty1) (pp TyOpPrec ty2) | otherwise = pprIfacePrefixApp ctxt_prec (parens (ppr tc)) (map (pp TyConPrec) tys) pprSum :: Arity -> IsPromoted -> IfaceTcArgs -> SDoc pprSum _arity is_promoted args = -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in TyCon let tys = tcArgsIfaceTypes args args' = drop (length tys `div` 2) tys in pprPromotionQuoteI is_promoted <> sumParens (pprWithBars (ppr_ty TopPrec) args') pprTuple :: TupleSort -> IsPromoted -> IfaceTcArgs -> SDoc pprTuple ConstraintTuple IsNotPromoted ITC_Nil = text "() :: Constraint" -- All promoted constructors have kind arguments pprTuple sort IsPromoted args = let tys = tcArgsIfaceTypes args args' = drop (length tys `div` 2) tys in pprPromotionQuoteI IsPromoted <> tupleParens sort (pprWithCommas pprIfaceType args') pprTuple sort promoted args = -- drop the RuntimeRep vars. -- See Note [Unboxed tuple RuntimeRep vars] in TyCon let tys = tcArgsIfaceTypes args args' = case sort of UnboxedTuple -> drop (length tys `div` 2) tys _ -> tys in pprPromotionQuoteI promoted <> tupleParens sort (pprWithCommas pprIfaceType args') pprIfaceTyLit :: IfaceTyLit -> SDoc pprIfaceTyLit (IfaceNumTyLit n) = integer n pprIfaceTyLit (IfaceStrTyLit n) = text (show n) pprIfaceCoercion, pprParendIfaceCoercion :: IfaceCoercion -> SDoc pprIfaceCoercion = ppr_co TopPrec pprParendIfaceCoercion = ppr_co TyConPrec ppr_co :: TyPrec -> IfaceCoercion -> SDoc ppr_co _ (IfaceReflCo r ty) = angleBrackets (ppr ty) <> ppr_role r ppr_co ctxt_prec (IfaceFunCo r co1 co2) = maybeParen ctxt_prec FunPrec $ sep (ppr_co FunPrec co1 : ppr_fun_tail co2) where ppr_fun_tail (IfaceFunCo r co1 co2) = (arrow <> ppr_role r <+> ppr_co FunPrec co1) : ppr_fun_tail co2 ppr_fun_tail other_co = [arrow <> ppr_role r <+> pprIfaceCoercion other_co] ppr_co _ (IfaceTyConAppCo r tc cos) = parens (pprIfaceCoTcApp TopPrec tc cos) <> ppr_role r ppr_co ctxt_prec (IfaceAppCo co1 co2) = maybeParen ctxt_prec TyConPrec $ ppr_co FunPrec co1 <+> pprParendIfaceCoercion co2 ppr_co ctxt_prec co@(IfaceForAllCo {}) = maybeParen ctxt_prec FunPrec $ pprIfaceForAllCoPart tvs (pprIfaceCoercion inner_co) where (tvs, inner_co) = split_co co split_co (IfaceForAllCo (name, _) kind_co co') = let (tvs, co'') = split_co co' in ((name,kind_co):tvs,co'') split_co co' = ([], co') -- Why these three? See Note [TcTyVars in IfaceType] ppr_co _ (IfaceFreeCoVar covar) = ppr covar ppr_co _ (IfaceCoVarCo covar) = ppr covar ppr_co _ (IfaceHoleCo covar) = braces (ppr covar) ppr_co ctxt_prec (IfaceUnivCo IfaceUnsafeCoerceProv r ty1 ty2) = maybeParen ctxt_prec TyConPrec $ text "UnsafeCo" <+> ppr r <+> pprParendIfaceType ty1 <+> pprParendIfaceType ty2 ppr_co _ (IfaceUnivCo prov role ty1 ty2) = text "Univ" <> (parens $ sep [ ppr role <+> pprIfaceUnivCoProv prov , dcolon <+> ppr ty1 <> comma <+> ppr ty2 ]) ppr_co ctxt_prec (IfaceInstCo co ty) = maybeParen ctxt_prec TyConPrec $ text "Inst" <+> pprParendIfaceCoercion co <+> pprParendIfaceCoercion ty ppr_co ctxt_prec (IfaceAxiomRuleCo tc cos) = maybeParen ctxt_prec TyConPrec $ ppr tc <+> parens (interpp'SP cos) ppr_co ctxt_prec (IfaceAxiomInstCo n i cos) = ppr_special_co ctxt_prec (ppr n <> brackets (ppr i)) cos ppr_co ctxt_prec (IfaceSymCo co) = ppr_special_co ctxt_prec (text "Sym") [co] ppr_co ctxt_prec (IfaceTransCo co1 co2) = maybeParen ctxt_prec TyOpPrec $ ppr_co TyOpPrec co1 <+> semi <+> ppr_co TyOpPrec co2 ppr_co ctxt_prec (IfaceNthCo d co) = ppr_special_co ctxt_prec (text "Nth:" <> int d) [co] ppr_co ctxt_prec (IfaceLRCo lr co) = ppr_special_co ctxt_prec (ppr lr) [co] ppr_co ctxt_prec (IfaceSubCo co) = ppr_special_co ctxt_prec (text "Sub") [co] ppr_co ctxt_prec (IfaceCoherenceCo co1 co2) = ppr_special_co ctxt_prec (text "Coh") [co1,co2] ppr_co ctxt_prec (IfaceKindCo co) = ppr_special_co ctxt_prec (text "Kind") [co] ppr_special_co :: TyPrec -> SDoc -> [IfaceCoercion] -> SDoc ppr_special_co ctxt_prec doc cos = maybeParen ctxt_prec TyConPrec (sep [doc, nest 4 (sep (map pprParendIfaceCoercion cos))]) ppr_role :: Role -> SDoc ppr_role r = underscore <> pp_role where pp_role = case r of Nominal -> char 'N' Representational -> char 'R' Phantom -> char 'P' ------------------ pprIfaceUnivCoProv :: IfaceUnivCoProv -> SDoc pprIfaceUnivCoProv IfaceUnsafeCoerceProv = text "unsafe" pprIfaceUnivCoProv (IfacePhantomProv co) = text "phantom" <+> pprParendIfaceCoercion co pprIfaceUnivCoProv (IfaceProofIrrelProv co) = text "irrel" <+> pprParendIfaceCoercion co pprIfaceUnivCoProv (IfacePluginProv s) = text "plugin" <+> doubleQuotes (text s) ------------------- instance Outputable IfaceTyCon where ppr tc = pprPromotionQuote tc <> ppr (ifaceTyConName tc) pprPromotionQuote :: IfaceTyCon -> SDoc pprPromotionQuote tc = pprPromotionQuoteI $ ifaceTyConIsPromoted $ ifaceTyConInfo tc pprPromotionQuoteI :: IsPromoted -> SDoc pprPromotionQuoteI IsNotPromoted = empty pprPromotionQuoteI IsPromoted = char '\'' instance Outputable IfaceCoercion where ppr = pprIfaceCoercion instance Binary IfaceTyCon where put_ bh (IfaceTyCon n i) = put_ bh n >> put_ bh i get bh = do n <- get bh i <- get bh return (IfaceTyCon n i) instance Binary IsPromoted where put_ bh IsNotPromoted = putByte bh 0 put_ bh IsPromoted = putByte bh 1 get bh = do n <- getByte bh case n of 0 -> return IsNotPromoted 1 -> return IsPromoted _ -> fail "Binary(IsPromoted): fail)" instance Binary IfaceTyConSort where put_ bh IfaceNormalTyCon = putByte bh 0 put_ bh (IfaceTupleTyCon arity sort) = putByte bh 1 >> put_ bh arity >> put_ bh sort put_ bh (IfaceSumTyCon arity) = putByte bh 2 >> put_ bh arity put_ bh IfaceEqualityTyCon = putByte bh 3 get bh = do n <- getByte bh case n of 0 -> return IfaceNormalTyCon 1 -> IfaceTupleTyCon <$> get bh <*> get bh 2 -> IfaceSumTyCon <$> get bh _ -> return IfaceEqualityTyCon instance Binary IfaceTyConInfo where put_ bh (IfaceTyConInfo i s) = put_ bh i >> put_ bh s get bh = IfaceTyConInfo <$> get bh <*> get bh instance Outputable IfaceTyLit where ppr = pprIfaceTyLit instance Binary IfaceTyLit where put_ bh (IfaceNumTyLit n) = putByte bh 1 >> put_ bh n put_ bh (IfaceStrTyLit n) = putByte bh 2 >> put_ bh n get bh = do tag <- getByte bh case tag of 1 -> do { n <- get bh ; return (IfaceNumTyLit n) } 2 -> do { n <- get bh ; return (IfaceStrTyLit n) } _ -> panic ("get IfaceTyLit " ++ show tag) instance Binary IfaceTcArgs where put_ bh tk = case tk of ITC_Vis t ts -> putByte bh 0 >> put_ bh t >> put_ bh ts ITC_Invis t ts -> putByte bh 1 >> put_ bh t >> put_ bh ts ITC_Nil -> putByte bh 2 get bh = do c <- getByte bh case c of 0 -> do t <- get bh ts <- get bh return $! ITC_Vis t ts 1 -> do t <- get bh ts <- get bh return $! ITC_Invis t ts 2 -> return ITC_Nil _ -> panic ("get IfaceTcArgs " ++ show c) ------------------- -- Some notes about printing contexts -- -- In the event that we are printing a singleton context (e.g. @Eq a@) we can -- omit parentheses. However, we must take care to set the precedence correctly -- to TyOpPrec, since something like @a :~: b@ must be parenthesized (see -- #9658). -- -- When printing a larger context we use 'fsep' instead of 'sep' so that -- the context doesn't get displayed as a giant column. Rather than, -- instance (Eq a, -- Eq b, -- Eq c, -- Eq d, -- Eq e, -- Eq f, -- Eq g, -- Eq h, -- Eq i, -- Eq j, -- Eq k, -- Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- -- we want -- -- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, -- Eq j, Eq k, Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- | Prints "(C a, D b) =>", including the arrow. -- Used when we want to print a context in a type, so we -- use FunPrec to decide whether to parenthesise a singleton -- predicate; e.g. Num a => a -> a pprIfaceContextArr :: [IfacePredType] -> SDoc pprIfaceContextArr [] = empty pprIfaceContextArr [pred] = ppr_ty FunPrec pred <+> darrow pprIfaceContextArr preds = ppr_parend_preds preds <+> darrow -- | Prints a context or @()@ if empty -- You give it the context precedence pprIfaceContext :: TyPrec -> [IfacePredType] -> SDoc pprIfaceContext _ [] = text "()" pprIfaceContext prec [pred] = ppr_ty prec pred pprIfaceContext _ preds = ppr_parend_preds preds ppr_parend_preds :: [IfacePredType] -> SDoc ppr_parend_preds preds = parens (fsep (punctuate comma (map ppr preds))) instance Binary IfaceType where put_ _ (IfaceFreeTyVar tv) = pprPanic "Can't serialise IfaceFreeTyVar" (ppr tv) put_ bh (IfaceForAllTy aa ab) = do putByte bh 0 put_ bh aa put_ bh ab put_ bh (IfaceTyVar ad) = do putByte bh 1 put_ bh ad put_ bh (IfaceAppTy ae af) = do putByte bh 2 put_ bh ae put_ bh af put_ bh (IfaceFunTy ag ah) = do putByte bh 3 put_ bh ag put_ bh ah put_ bh (IfaceDFunTy ag ah) = do putByte bh 4 put_ bh ag put_ bh ah put_ bh (IfaceTyConApp tc tys) = do { putByte bh 5; put_ bh tc; put_ bh tys } put_ bh (IfaceCastTy a b) = do { putByte bh 6; put_ bh a; put_ bh b } put_ bh (IfaceCoercionTy a) = do { putByte bh 7; put_ bh a } put_ bh (IfaceTupleTy s i tys) = do { putByte bh 8; put_ bh s; put_ bh i; put_ bh tys } put_ bh (IfaceLitTy n) = do { putByte bh 9; put_ bh n } get bh = do h <- getByte bh case h of 0 -> do aa <- get bh ab <- get bh return (IfaceForAllTy aa ab) 1 -> do ad <- get bh return (IfaceTyVar ad) 2 -> do ae <- get bh af <- get bh return (IfaceAppTy ae af) 3 -> do ag <- get bh ah <- get bh return (IfaceFunTy ag ah) 4 -> do ag <- get bh ah <- get bh return (IfaceDFunTy ag ah) 5 -> do { tc <- get bh; tys <- get bh ; return (IfaceTyConApp tc tys) } 6 -> do { a <- get bh; b <- get bh ; return (IfaceCastTy a b) } 7 -> do { a <- get bh ; return (IfaceCoercionTy a) } 8 -> do { s <- get bh; i <- get bh; tys <- get bh ; return (IfaceTupleTy s i tys) } _ -> do n <- get bh return (IfaceLitTy n) instance Binary IfaceCoercion where put_ bh (IfaceReflCo a b) = do putByte bh 1 put_ bh a put_ bh b put_ bh (IfaceFunCo a b c) = do putByte bh 2 put_ bh a put_ bh b put_ bh c put_ bh (IfaceTyConAppCo a b c) = do putByte bh 3 put_ bh a put_ bh b put_ bh c put_ bh (IfaceAppCo a b) = do putByte bh 4 put_ bh a put_ bh b put_ bh (IfaceForAllCo a b c) = do putByte bh 5 put_ bh a put_ bh b put_ bh c put_ bh (IfaceCoVarCo a) = do putByte bh 6 put_ bh a put_ bh (IfaceAxiomInstCo a b c) = do putByte bh 7 put_ bh a put_ bh b put_ bh c put_ bh (IfaceUnivCo a b c d) = do putByte bh 8 put_ bh a put_ bh b put_ bh c put_ bh d put_ bh (IfaceSymCo a) = do putByte bh 9 put_ bh a put_ bh (IfaceTransCo a b) = do putByte bh 10 put_ bh a put_ bh b put_ bh (IfaceNthCo a b) = do putByte bh 11 put_ bh a put_ bh b put_ bh (IfaceLRCo a b) = do putByte bh 12 put_ bh a put_ bh b put_ bh (IfaceInstCo a b) = do putByte bh 13 put_ bh a put_ bh b put_ bh (IfaceCoherenceCo a b) = do putByte bh 14 put_ bh a put_ bh b put_ bh (IfaceKindCo a) = do putByte bh 15 put_ bh a put_ bh (IfaceSubCo a) = do putByte bh 16 put_ bh a put_ bh (IfaceAxiomRuleCo a b) = do putByte bh 17 put_ bh a put_ bh b put_ _ (IfaceFreeCoVar cv) = pprPanic "Can't serialise IfaceFreeCoVar" (ppr cv) put_ _ (IfaceHoleCo cv) = pprPanic "Can't serialise IfaceHoleCo" (ppr cv) -- See Note [Holes in IfaceUnivCoProv] get bh = do tag <- getByte bh case tag of 1 -> do a <- get bh b <- get bh return $ IfaceReflCo a b 2 -> do a <- get bh b <- get bh c <- get bh return $ IfaceFunCo a b c 3 -> do a <- get bh b <- get bh c <- get bh return $ IfaceTyConAppCo a b c 4 -> do a <- get bh b <- get bh return $ IfaceAppCo a b 5 -> do a <- get bh b <- get bh c <- get bh return $ IfaceForAllCo a b c 6 -> do a <- get bh return $ IfaceCoVarCo a 7 -> do a <- get bh b <- get bh c <- get bh return $ IfaceAxiomInstCo a b c 8 -> do a <- get bh b <- get bh c <- get bh d <- get bh return $ IfaceUnivCo a b c d 9 -> do a <- get bh return $ IfaceSymCo a 10-> do a <- get bh b <- get bh return $ IfaceTransCo a b 11-> do a <- get bh b <- get bh return $ IfaceNthCo a b 12-> do a <- get bh b <- get bh return $ IfaceLRCo a b 13-> do a <- get bh b <- get bh return $ IfaceInstCo a b 14-> do a <- get bh b <- get bh return $ IfaceCoherenceCo a b 15-> do a <- get bh return $ IfaceKindCo a 16-> do a <- get bh return $ IfaceSubCo a 17-> do a <- get bh b <- get bh return $ IfaceAxiomRuleCo a b _ -> panic ("get IfaceCoercion " ++ show tag) instance Binary IfaceUnivCoProv where put_ bh IfaceUnsafeCoerceProv = putByte bh 1 put_ bh (IfacePhantomProv a) = do putByte bh 2 put_ bh a put_ bh (IfaceProofIrrelProv a) = do putByte bh 3 put_ bh a put_ bh (IfacePluginProv a) = do putByte bh 4 put_ bh a get bh = do tag <- getByte bh case tag of 1 -> return $ IfaceUnsafeCoerceProv 2 -> do a <- get bh return $ IfacePhantomProv a 3 -> do a <- get bh return $ IfaceProofIrrelProv a 4 -> do a <- get bh return $ IfacePluginProv a _ -> panic ("get IfaceUnivCoProv " ++ show tag) instance Binary (DefMethSpec IfaceType) where put_ bh VanillaDM = putByte bh 0 put_ bh (GenericDM t) = putByte bh 1 >> put_ bh t get bh = do h <- getByte bh case h of 0 -> return VanillaDM _ -> do { t <- get bh; return (GenericDM t) }
shlevy/ghc
compiler/iface/IfaceType.hs
bsd-3-clause
54,737
2
17
15,899
13,432
6,684
6,748
1,007
32
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "src/Data/Version/Compat.hs" #-} {-# LANGUAGE CPP, NoImplicitPrelude #-} module Data.Version.Compat ( module Base , makeVersion ) where import Data.Version as Base
phischu/fragnix
tests/packages/scotty/Data.Version.Compat.hs
bsd-3-clause
254
0
4
79
26
19
7
7
0
module SDL.Raw.Event ( -- * Event Handling addEventWatch, delEventWatch, eventState, filterEvents, flushEvent, flushEvents, getEventFilter, getNumTouchDevices, getNumTouchFingers, getTouchDevice, getTouchFinger, hasEvent, hasEvents, loadDollarTemplates, peepEvents, pollEvent, pumpEvents, pushEvent, quitRequested, recordGesture, registerEvents, saveAllDollarTemplates, saveDollarTemplate, setEventFilter, waitEvent, waitEventTimeout, -- * Keyboard Support getKeyFromName, getKeyFromScancode, getKeyName, getKeyboardFocus, getKeyboardState, getModState, getScancodeFromKey, getScancodeFromName, getScancodeName, hasScreenKeyboardSupport, isScreenKeyboardShown, isTextInputActive, setModState, setTextInputRect, startTextInput, stopTextInput, -- * Mouse Support createColorCursor, createCursor, createSystemCursor, freeCursor, getCursor, getDefaultCursor, getMouseFocus, getMouseState, getRelativeMouseMode, getRelativeMouseState, setCursor, setRelativeMouseMode, showCursor, warpMouseInWindow, -- * Joystick Support joystickClose, joystickEventState, joystickGetAttached, joystickGetAxis, joystickGetBall, joystickGetButton, joystickGetDeviceGUID, joystickGetGUID, joystickGetGUIDFromString, joystickGetGUIDString, joystickGetHat, joystickInstanceID, joystickName, joystickNameForIndex, joystickNumAxes, joystickNumBalls, joystickNumButtons, joystickNumHats, joystickOpen, joystickUpdate, numJoysticks, -- * Game Controller Support gameControllerAddMapping, gameControllerAddMappingsFromFile, gameControllerAddMappingsFromRW, gameControllerClose, gameControllerEventState, gameControllerGetAttached, gameControllerGetAxis, gameControllerGetAxisFromString, gameControllerGetBindForAxis, gameControllerGetBindForButton, gameControllerGetButton, gameControllerGetButtonFromString, gameControllerGetJoystick, gameControllerGetStringForAxis, gameControllerGetStringForButton, gameControllerMapping, gameControllerMappingForGUID, gameControllerName, gameControllerNameForIndex, gameControllerOpen, gameControllerUpdate, isGameController ) where import Control.Monad.IO.Class import Data.Int import Data.Word import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import SDL.Raw.Enum import SDL.Raw.Filesystem import SDL.Raw.Types foreign import ccall "SDL.h SDL_AddEventWatch" addEventWatchFFI :: EventFilter -> Ptr () -> IO () foreign import ccall "SDL.h SDL_DelEventWatch" delEventWatchFFI :: EventFilter -> Ptr () -> IO () foreign import ccall "SDL.h SDL_EventState" eventStateFFI :: Word32 -> CInt -> IO Word8 foreign import ccall "SDL.h SDL_FilterEvents" filterEventsFFI :: EventFilter -> Ptr () -> IO () foreign import ccall "SDL.h SDL_FlushEvent" flushEventFFI :: Word32 -> IO () foreign import ccall "SDL.h SDL_FlushEvents" flushEventsFFI :: Word32 -> Word32 -> IO () foreign import ccall "SDL.h SDL_GetEventFilter" getEventFilterFFI :: Ptr EventFilter -> Ptr (Ptr ()) -> IO Bool foreign import ccall "SDL.h SDL_GetNumTouchDevices" getNumTouchDevicesFFI :: IO CInt foreign import ccall "SDL.h SDL_GetNumTouchFingers" getNumTouchFingersFFI :: TouchID -> IO CInt foreign import ccall "SDL.h SDL_GetTouchDevice" getTouchDeviceFFI :: CInt -> IO TouchID foreign import ccall "SDL.h SDL_GetTouchFinger" getTouchFingerFFI :: TouchID -> CInt -> IO (Ptr Finger) foreign import ccall "SDL.h SDL_HasEvent" hasEventFFI :: Word32 -> IO Bool foreign import ccall "SDL.h SDL_HasEvents" hasEventsFFI :: Word32 -> Word32 -> IO Bool foreign import ccall "SDL.h SDL_LoadDollarTemplates" loadDollarTemplatesFFI :: TouchID -> Ptr RWops -> IO CInt foreign import ccall "SDL.h SDL_PeepEvents" peepEventsFFI :: Ptr Event -> CInt -> EventAction -> Word32 -> Word32 -> IO CInt foreign import ccall "SDL.h SDL_PollEvent" pollEventFFI :: Ptr Event -> IO CInt foreign import ccall "SDL.h SDL_PumpEvents" pumpEventsFFI :: IO () foreign import ccall "SDL.h SDL_PushEvent" pushEventFFI :: Ptr Event -> IO CInt foreign import ccall "SDL.h SDL_RecordGesture" recordGestureFFI :: TouchID -> IO CInt foreign import ccall "SDL.h SDL_RegisterEvents" registerEventsFFI :: CInt -> IO Word32 foreign import ccall "SDL.h SDL_SaveAllDollarTemplates" saveAllDollarTemplatesFFI :: Ptr RWops -> IO CInt foreign import ccall "SDL.h SDL_SaveDollarTemplate" saveDollarTemplateFFI :: GestureID -> Ptr RWops -> IO CInt foreign import ccall "SDL.h SDL_SetEventFilter" setEventFilterFFI :: EventFilter -> Ptr () -> IO () foreign import ccall "SDL.h SDL_WaitEvent" waitEventFFI :: Ptr Event -> IO CInt foreign import ccall "SDL.h SDL_WaitEventTimeout" waitEventTimeoutFFI :: Ptr Event -> CInt -> IO CInt foreign import ccall "SDL.h SDL_GetKeyFromName" getKeyFromNameFFI :: CString -> IO Keycode foreign import ccall "SDL.h SDL_GetKeyFromScancode" getKeyFromScancodeFFI :: Scancode -> IO Keycode foreign import ccall "SDL.h SDL_GetKeyName" getKeyNameFFI :: Keycode -> IO CString foreign import ccall "SDL.h SDL_GetKeyboardFocus" getKeyboardFocusFFI :: IO Window foreign import ccall "SDL.h SDL_GetKeyboardState" getKeyboardStateFFI :: Ptr CInt -> IO (Ptr Word8) foreign import ccall "SDL.h SDL_GetModState" getModStateFFI :: IO Keymod foreign import ccall "SDL.h SDL_GetScancodeFromKey" getScancodeFromKeyFFI :: Keycode -> IO Scancode foreign import ccall "SDL.h SDL_GetScancodeFromName" getScancodeFromNameFFI :: CString -> IO Scancode foreign import ccall "SDL.h SDL_GetScancodeName" getScancodeNameFFI :: Scancode -> IO CString foreign import ccall "SDL.h SDL_HasScreenKeyboardSupport" hasScreenKeyboardSupportFFI :: IO Bool foreign import ccall "SDL.h SDL_IsScreenKeyboardShown" isScreenKeyboardShownFFI :: Window -> IO Bool foreign import ccall "SDL.h SDL_IsTextInputActive" isTextInputActiveFFI :: IO Bool foreign import ccall "SDL.h SDL_SetModState" setModStateFFI :: Keymod -> IO () foreign import ccall "SDL.h SDL_SetTextInputRect" setTextInputRectFFI :: Ptr Rect -> IO () foreign import ccall "SDL.h SDL_StartTextInput" startTextInputFFI :: IO () foreign import ccall "SDL.h SDL_StopTextInput" stopTextInputFFI :: IO () foreign import ccall "SDL.h SDL_CreateColorCursor" createColorCursorFFI :: Ptr Surface -> CInt -> CInt -> IO Cursor foreign import ccall "SDL.h SDL_CreateCursor" createCursorFFI :: Ptr Word8 -> Ptr Word8 -> CInt -> CInt -> CInt -> CInt -> IO Cursor foreign import ccall "SDL.h SDL_CreateSystemCursor" createSystemCursorFFI :: SystemCursor -> IO Cursor foreign import ccall "SDL.h SDL_FreeCursor" freeCursorFFI :: Cursor -> IO () foreign import ccall "SDL.h SDL_GetCursor" getCursorFFI :: IO Cursor foreign import ccall "SDL.h SDL_GetDefaultCursor" getDefaultCursorFFI :: IO Cursor foreign import ccall "SDL.h SDL_GetMouseFocus" getMouseFocusFFI :: IO Window foreign import ccall "SDL.h SDL_GetMouseState" getMouseStateFFI :: Ptr CInt -> Ptr CInt -> IO Word32 foreign import ccall "SDL.h SDL_GetRelativeMouseMode" getRelativeMouseModeFFI :: IO Bool foreign import ccall "SDL.h SDL_GetRelativeMouseState" getRelativeMouseStateFFI :: Ptr CInt -> Ptr CInt -> IO Word32 foreign import ccall "SDL.h SDL_SetCursor" setCursorFFI :: Cursor -> IO () foreign import ccall "SDL.h SDL_SetRelativeMouseMode" setRelativeMouseModeFFI :: Bool -> IO CInt foreign import ccall "SDL.h SDL_ShowCursor" showCursorFFI :: CInt -> IO CInt foreign import ccall "SDL.h SDL_WarpMouseInWindow" warpMouseInWindowFFI :: Window -> CInt -> CInt -> IO () foreign import ccall "SDL.h SDL_JoystickClose" joystickCloseFFI :: Joystick -> IO () foreign import ccall "SDL.h SDL_JoystickEventState" joystickEventStateFFI :: CInt -> IO CInt foreign import ccall "SDL.h SDL_JoystickGetAttached" joystickGetAttachedFFI :: Joystick -> IO Bool foreign import ccall "SDL.h SDL_JoystickGetAxis" joystickGetAxisFFI :: Joystick -> CInt -> IO Int16 foreign import ccall "SDL.h SDL_JoystickGetBall" joystickGetBallFFI :: Joystick -> CInt -> Ptr CInt -> Ptr CInt -> IO CInt foreign import ccall "SDL.h SDL_JoystickGetButton" joystickGetButtonFFI :: Joystick -> CInt -> IO Word8 foreign import ccall "sdlhelper.h SDLHelper_JoystickGetDeviceGUID" joystickGetDeviceGUIDFFI :: CInt -> Ptr JoystickGUID -> IO () foreign import ccall "sdlhelper.h SDLHelper_JoystickGetGUID" joystickGetGUIDFFI :: Joystick -> Ptr JoystickGUID -> IO () foreign import ccall "sdlhelper.h SDLHelper_JoystickGetGUIDFromString" joystickGetGUIDFromStringFFI :: CString -> Ptr JoystickGUID -> IO () foreign import ccall "sdlhelper.h SDLHelper_JoystickGetGUIDString" joystickGetGUIDStringFFI :: Ptr JoystickGUID -> CString -> CInt -> IO () foreign import ccall "SDL.h SDL_JoystickGetHat" joystickGetHatFFI :: Joystick -> CInt -> IO Word8 foreign import ccall "SDL.h SDL_JoystickInstanceID" joystickInstanceIDFFI :: Joystick -> IO JoystickID foreign import ccall "SDL.h SDL_JoystickName" joystickNameFFI :: Joystick -> IO CString foreign import ccall "SDL.h SDL_JoystickNameForIndex" joystickNameForIndexFFI :: CInt -> IO CString foreign import ccall "SDL.h SDL_JoystickNumAxes" joystickNumAxesFFI :: Joystick -> IO CInt foreign import ccall "SDL.h SDL_JoystickNumBalls" joystickNumBallsFFI :: Joystick -> IO CInt foreign import ccall "SDL.h SDL_JoystickNumButtons" joystickNumButtonsFFI :: Joystick -> IO CInt foreign import ccall "SDL.h SDL_JoystickNumHats" joystickNumHatsFFI :: Joystick -> IO CInt foreign import ccall "SDL.h SDL_JoystickOpen" joystickOpenFFI :: CInt -> IO Joystick foreign import ccall "SDL.h SDL_JoystickUpdate" joystickUpdateFFI :: IO () foreign import ccall "SDL.h SDL_NumJoysticks" numJoysticksFFI :: IO CInt foreign import ccall "SDL.h SDL_GameControllerAddMapping" gameControllerAddMappingFFI :: CString -> IO CInt foreign import ccall "SDL.h SDL_GameControllerAddMappingsFromRW" gameControllerAddMappingsFromRWFFI :: Ptr RWops -> CInt -> IO CInt foreign import ccall "SDL.h SDL_GameControllerClose" gameControllerCloseFFI :: GameController -> IO () foreign import ccall "SDL.h SDL_GameControllerEventState" gameControllerEventStateFFI :: CInt -> IO CInt foreign import ccall "SDL.h SDL_GameControllerGetAttached" gameControllerGetAttachedFFI :: GameController -> IO Bool foreign import ccall "SDL.h SDL_GameControllerGetAxis" gameControllerGetAxisFFI :: GameController -> GameControllerAxis -> IO Int16 foreign import ccall "SDL.h SDL_GameControllerGetAxisFromString" gameControllerGetAxisFromStringFFI :: CString -> IO GameControllerAxis foreign import ccall "sdlhelper.h SDLHelper_GameControllerGetBindForAxis" gameControllerGetBindForAxisFFI :: GameController -> GameControllerAxis -> Ptr GameControllerButtonBind -> IO () foreign import ccall "sdlhelper.h SDLHelper_GameControllerGetBindForButton" gameControllerGetBindForButtonFFI :: GameController -> GameControllerButton -> Ptr GameControllerButtonBind -> IO () foreign import ccall "SDL.h SDL_GameControllerGetButton" gameControllerGetButtonFFI :: GameController -> GameControllerButton -> IO Word8 foreign import ccall "SDL.h SDL_GameControllerGetButtonFromString" gameControllerGetButtonFromStringFFI :: CString -> IO GameControllerButton foreign import ccall "SDL.h SDL_GameControllerGetJoystick" gameControllerGetJoystickFFI :: GameController -> IO Joystick foreign import ccall "SDL.h SDL_GameControllerGetStringForAxis" gameControllerGetStringForAxisFFI :: GameControllerAxis -> IO CString foreign import ccall "SDL.h SDL_GameControllerGetStringForButton" gameControllerGetStringForButtonFFI :: GameControllerButton -> IO CString foreign import ccall "SDL.h SDL_GameControllerMapping" gameControllerMappingFFI :: GameController -> IO CString foreign import ccall "sdlhelper.h SDLHelper_GameControllerMappingForGUID" gameControllerMappingForGUIDFFI :: Ptr JoystickGUID -> IO CString foreign import ccall "SDL.h SDL_GameControllerName" gameControllerNameFFI :: GameController -> IO CString foreign import ccall "SDL.h SDL_GameControllerNameForIndex" gameControllerNameForIndexFFI :: CInt -> IO CString foreign import ccall "SDL.h SDL_GameControllerOpen" gameControllerOpenFFI :: CInt -> IO GameController foreign import ccall "SDL.h SDL_GameControllerUpdate" gameControllerUpdateFFI :: IO () foreign import ccall "SDL.h SDL_IsGameController" isGameControllerFFI :: CInt -> IO Bool addEventWatch :: MonadIO m => EventFilter -> Ptr () -> m () addEventWatch v1 v2 = liftIO $ addEventWatchFFI v1 v2 {-# INLINE addEventWatch #-} delEventWatch :: MonadIO m => EventFilter -> Ptr () -> m () delEventWatch v1 v2 = liftIO $ delEventWatchFFI v1 v2 {-# INLINE delEventWatch #-} eventState :: MonadIO m => Word32 -> CInt -> m Word8 eventState v1 v2 = liftIO $ eventStateFFI v1 v2 {-# INLINE eventState #-} filterEvents :: MonadIO m => EventFilter -> Ptr () -> m () filterEvents v1 v2 = liftIO $ filterEventsFFI v1 v2 {-# INLINE filterEvents #-} flushEvent :: MonadIO m => Word32 -> m () flushEvent v1 = liftIO $ flushEventFFI v1 {-# INLINE flushEvent #-} flushEvents :: MonadIO m => Word32 -> Word32 -> m () flushEvents v1 v2 = liftIO $ flushEventsFFI v1 v2 {-# INLINE flushEvents #-} getEventFilter :: MonadIO m => Ptr EventFilter -> Ptr (Ptr ()) -> m Bool getEventFilter v1 v2 = liftIO $ getEventFilterFFI v1 v2 {-# INLINE getEventFilter #-} getNumTouchDevices :: MonadIO m => m CInt getNumTouchDevices = liftIO getNumTouchDevicesFFI {-# INLINE getNumTouchDevices #-} getNumTouchFingers :: MonadIO m => TouchID -> m CInt getNumTouchFingers v1 = liftIO $ getNumTouchFingersFFI v1 {-# INLINE getNumTouchFingers #-} getTouchDevice :: MonadIO m => CInt -> m TouchID getTouchDevice v1 = liftIO $ getTouchDeviceFFI v1 {-# INLINE getTouchDevice #-} getTouchFinger :: MonadIO m => TouchID -> CInt -> m (Ptr Finger) getTouchFinger v1 v2 = liftIO $ getTouchFingerFFI v1 v2 {-# INLINE getTouchFinger #-} hasEvent :: MonadIO m => Word32 -> m Bool hasEvent v1 = liftIO $ hasEventFFI v1 {-# INLINE hasEvent #-} hasEvents :: MonadIO m => Word32 -> Word32 -> m Bool hasEvents v1 v2 = liftIO $ hasEventsFFI v1 v2 {-# INLINE hasEvents #-} loadDollarTemplates :: MonadIO m => TouchID -> Ptr RWops -> m CInt loadDollarTemplates v1 v2 = liftIO $ loadDollarTemplatesFFI v1 v2 {-# INLINE loadDollarTemplates #-} peepEvents :: MonadIO m => Ptr Event -> CInt -> EventAction -> Word32 -> Word32 -> m CInt peepEvents v1 v2 v3 v4 v5 = liftIO $ peepEventsFFI v1 v2 v3 v4 v5 {-# INLINE peepEvents #-} pollEvent :: MonadIO m => Ptr Event -> m CInt pollEvent v1 = liftIO $ pollEventFFI v1 {-# INLINE pollEvent #-} pumpEvents :: MonadIO m => m () pumpEvents = liftIO pumpEventsFFI {-# INLINE pumpEvents #-} pushEvent :: MonadIO m => Ptr Event -> m CInt pushEvent v1 = liftIO $ pushEventFFI v1 {-# INLINE pushEvent #-} quitRequested :: MonadIO m => m Bool quitRequested = liftIO $ do pumpEvents ev <- peepEvents nullPtr 0 SDL_PEEKEVENT SDL_QUIT SDL_QUIT return $ ev > 0 {-# INLINE quitRequested #-} recordGesture :: MonadIO m => TouchID -> m CInt recordGesture v1 = liftIO $ recordGestureFFI v1 {-# INLINE recordGesture #-} registerEvents :: MonadIO m => CInt -> m Word32 registerEvents v1 = liftIO $ registerEventsFFI v1 {-# INLINE registerEvents #-} saveAllDollarTemplates :: MonadIO m => Ptr RWops -> m CInt saveAllDollarTemplates v1 = liftIO $ saveAllDollarTemplatesFFI v1 {-# INLINE saveAllDollarTemplates #-} saveDollarTemplate :: MonadIO m => GestureID -> Ptr RWops -> m CInt saveDollarTemplate v1 v2 = liftIO $ saveDollarTemplateFFI v1 v2 {-# INLINE saveDollarTemplate #-} setEventFilter :: MonadIO m => EventFilter -> Ptr () -> m () setEventFilter v1 v2 = liftIO $ setEventFilterFFI v1 v2 {-# INLINE setEventFilter #-} waitEvent :: MonadIO m => Ptr Event -> m CInt waitEvent v1 = liftIO $ waitEventFFI v1 {-# INLINE waitEvent #-} waitEventTimeout :: MonadIO m => Ptr Event -> CInt -> m CInt waitEventTimeout v1 v2 = liftIO $ waitEventTimeoutFFI v1 v2 {-# INLINE waitEventTimeout #-} getKeyFromName :: MonadIO m => CString -> m Keycode getKeyFromName v1 = liftIO $ getKeyFromNameFFI v1 {-# INLINE getKeyFromName #-} getKeyFromScancode :: MonadIO m => Scancode -> m Keycode getKeyFromScancode v1 = liftIO $ getKeyFromScancodeFFI v1 {-# INLINE getKeyFromScancode #-} getKeyName :: MonadIO m => Keycode -> m CString getKeyName v1 = liftIO $ getKeyNameFFI v1 {-# INLINE getKeyName #-} getKeyboardFocus :: MonadIO m => m Window getKeyboardFocus = liftIO getKeyboardFocusFFI {-# INLINE getKeyboardFocus #-} getKeyboardState :: MonadIO m => Ptr CInt -> m (Ptr Word8) getKeyboardState v1 = liftIO $ getKeyboardStateFFI v1 {-# INLINE getKeyboardState #-} getModState :: MonadIO m => m Keymod getModState = liftIO getModStateFFI {-# INLINE getModState #-} getScancodeFromKey :: MonadIO m => Keycode -> m Scancode getScancodeFromKey v1 = liftIO $ getScancodeFromKeyFFI v1 {-# INLINE getScancodeFromKey #-} getScancodeFromName :: MonadIO m => CString -> m Scancode getScancodeFromName v1 = liftIO $ getScancodeFromNameFFI v1 {-# INLINE getScancodeFromName #-} getScancodeName :: MonadIO m => Scancode -> m CString getScancodeName v1 = liftIO $ getScancodeNameFFI v1 {-# INLINE getScancodeName #-} hasScreenKeyboardSupport :: MonadIO m => m Bool hasScreenKeyboardSupport = liftIO hasScreenKeyboardSupportFFI {-# INLINE hasScreenKeyboardSupport #-} isScreenKeyboardShown :: MonadIO m => Window -> m Bool isScreenKeyboardShown v1 = liftIO $ isScreenKeyboardShownFFI v1 {-# INLINE isScreenKeyboardShown #-} isTextInputActive :: MonadIO m => m Bool isTextInputActive = liftIO isTextInputActiveFFI {-# INLINE isTextInputActive #-} setModState :: MonadIO m => Keymod -> m () setModState v1 = liftIO $ setModStateFFI v1 {-# INLINE setModState #-} setTextInputRect :: MonadIO m => Ptr Rect -> m () setTextInputRect v1 = liftIO $ setTextInputRectFFI v1 {-# INLINE setTextInputRect #-} startTextInput :: MonadIO m => m () startTextInput = liftIO startTextInputFFI {-# INLINE startTextInput #-} stopTextInput :: MonadIO m => m () stopTextInput = liftIO stopTextInputFFI {-# INLINE stopTextInput #-} createColorCursor :: MonadIO m => Ptr Surface -> CInt -> CInt -> m Cursor createColorCursor v1 v2 v3 = liftIO $ createColorCursorFFI v1 v2 v3 {-# INLINE createColorCursor #-} createCursor :: MonadIO m => Ptr Word8 -> Ptr Word8 -> CInt -> CInt -> CInt -> CInt -> m Cursor createCursor v1 v2 v3 v4 v5 v6 = liftIO $ createCursorFFI v1 v2 v3 v4 v5 v6 {-# INLINE createCursor #-} createSystemCursor :: MonadIO m => SystemCursor -> m Cursor createSystemCursor v1 = liftIO $ createSystemCursorFFI v1 {-# INLINE createSystemCursor #-} freeCursor :: MonadIO m => Cursor -> m () freeCursor v1 = liftIO $ freeCursorFFI v1 {-# INLINE freeCursor #-} getCursor :: MonadIO m => m Cursor getCursor = liftIO getCursorFFI {-# INLINE getCursor #-} getDefaultCursor :: MonadIO m => m Cursor getDefaultCursor = liftIO getDefaultCursorFFI {-# INLINE getDefaultCursor #-} getMouseFocus :: MonadIO m => m Window getMouseFocus = liftIO getMouseFocusFFI {-# INLINE getMouseFocus #-} getMouseState :: MonadIO m => Ptr CInt -> Ptr CInt -> m Word32 getMouseState v1 v2 = liftIO $ getMouseStateFFI v1 v2 {-# INLINE getMouseState #-} getRelativeMouseMode :: MonadIO m => m Bool getRelativeMouseMode = liftIO getRelativeMouseModeFFI {-# INLINE getRelativeMouseMode #-} getRelativeMouseState :: MonadIO m => Ptr CInt -> Ptr CInt -> m Word32 getRelativeMouseState v1 v2 = liftIO $ getRelativeMouseStateFFI v1 v2 {-# INLINE getRelativeMouseState #-} setCursor :: MonadIO m => Cursor -> m () setCursor v1 = liftIO $ setCursorFFI v1 {-# INLINE setCursor #-} setRelativeMouseMode :: MonadIO m => Bool -> m CInt setRelativeMouseMode v1 = liftIO $ setRelativeMouseModeFFI v1 {-# INLINE setRelativeMouseMode #-} showCursor :: MonadIO m => CInt -> m CInt showCursor v1 = liftIO $ showCursorFFI v1 {-# INLINE showCursor #-} warpMouseInWindow :: MonadIO m => Window -> CInt -> CInt -> m () warpMouseInWindow v1 v2 v3 = liftIO $ warpMouseInWindowFFI v1 v2 v3 {-# INLINE warpMouseInWindow #-} joystickClose :: MonadIO m => Joystick -> m () joystickClose v1 = liftIO $ joystickCloseFFI v1 {-# INLINE joystickClose #-} joystickEventState :: MonadIO m => CInt -> m CInt joystickEventState v1 = liftIO $ joystickEventStateFFI v1 {-# INLINE joystickEventState #-} joystickGetAttached :: MonadIO m => Joystick -> m Bool joystickGetAttached v1 = liftIO $ joystickGetAttachedFFI v1 {-# INLINE joystickGetAttached #-} joystickGetAxis :: MonadIO m => Joystick -> CInt -> m Int16 joystickGetAxis v1 v2 = liftIO $ joystickGetAxisFFI v1 v2 {-# INLINE joystickGetAxis #-} joystickGetBall :: MonadIO m => Joystick -> CInt -> Ptr CInt -> Ptr CInt -> m CInt joystickGetBall v1 v2 v3 v4 = liftIO $ joystickGetBallFFI v1 v2 v3 v4 {-# INLINE joystickGetBall #-} joystickGetButton :: MonadIO m => Joystick -> CInt -> m Word8 joystickGetButton v1 v2 = liftIO $ joystickGetButtonFFI v1 v2 {-# INLINE joystickGetButton #-} joystickGetDeviceGUID :: MonadIO m => CInt -> m JoystickGUID joystickGetDeviceGUID device_index = liftIO . alloca $ \ptr -> do joystickGetDeviceGUIDFFI device_index ptr peek ptr {-# INLINE joystickGetDeviceGUID #-} joystickGetGUID :: MonadIO m => Joystick -> m JoystickGUID joystickGetGUID joystick = liftIO . alloca $ \ptr -> do joystickGetGUIDFFI joystick ptr peek ptr {-# INLINE joystickGetGUID #-} joystickGetGUIDFromString :: MonadIO m => CString -> m JoystickGUID joystickGetGUIDFromString pchGUID = liftIO . alloca $ \ptr -> do joystickGetGUIDFromStringFFI pchGUID ptr peek ptr {-# INLINE joystickGetGUIDFromString #-} joystickGetGUIDString :: MonadIO m => JoystickGUID -> CString -> CInt -> m () joystickGetGUIDString guid pszGUID cbGUID = liftIO . alloca $ \ptr -> do poke ptr guid joystickGetGUIDStringFFI ptr pszGUID cbGUID {-# INLINE joystickGetGUIDString #-} joystickGetHat :: MonadIO m => Joystick -> CInt -> m Word8 joystickGetHat v1 v2 = liftIO $ joystickGetHatFFI v1 v2 {-# INLINE joystickGetHat #-} joystickInstanceID :: MonadIO m => Joystick -> m JoystickID joystickInstanceID v1 = liftIO $ joystickInstanceIDFFI v1 {-# INLINE joystickInstanceID #-} joystickName :: MonadIO m => Joystick -> m CString joystickName v1 = liftIO $ joystickNameFFI v1 {-# INLINE joystickName #-} joystickNameForIndex :: MonadIO m => CInt -> m CString joystickNameForIndex v1 = liftIO $ joystickNameForIndexFFI v1 {-# INLINE joystickNameForIndex #-} joystickNumAxes :: MonadIO m => Joystick -> m CInt joystickNumAxes v1 = liftIO $ joystickNumAxesFFI v1 {-# INLINE joystickNumAxes #-} joystickNumBalls :: MonadIO m => Joystick -> m CInt joystickNumBalls v1 = liftIO $ joystickNumBallsFFI v1 {-# INLINE joystickNumBalls #-} joystickNumButtons :: MonadIO m => Joystick -> m CInt joystickNumButtons v1 = liftIO $ joystickNumButtonsFFI v1 {-# INLINE joystickNumButtons #-} joystickNumHats :: MonadIO m => Joystick -> m CInt joystickNumHats v1 = liftIO $ joystickNumHatsFFI v1 {-# INLINE joystickNumHats #-} joystickOpen :: MonadIO m => CInt -> m Joystick joystickOpen v1 = liftIO $ joystickOpenFFI v1 {-# INLINE joystickOpen #-} joystickUpdate :: MonadIO m => m () joystickUpdate = liftIO joystickUpdateFFI {-# INLINE joystickUpdate #-} numJoysticks :: MonadIO m => m CInt numJoysticks = liftIO numJoysticksFFI {-# INLINE numJoysticks #-} gameControllerAddMapping :: MonadIO m => CString -> m CInt gameControllerAddMapping v1 = liftIO $ gameControllerAddMappingFFI v1 {-# INLINE gameControllerAddMapping #-} gameControllerAddMappingsFromFile :: MonadIO m => CString -> m CInt gameControllerAddMappingsFromFile file = liftIO $ do rw <- withCString "rb" $ rwFromFile file gameControllerAddMappingsFromRW rw 1 {-# INLINE gameControllerAddMappingsFromFile #-} gameControllerAddMappingsFromRW :: MonadIO m => Ptr RWops -> CInt -> m CInt gameControllerAddMappingsFromRW v1 v2 = liftIO $ gameControllerAddMappingsFromRWFFI v1 v2 {-# INLINE gameControllerAddMappingsFromRW #-} gameControllerClose :: MonadIO m => GameController -> m () gameControllerClose v1 = liftIO $ gameControllerCloseFFI v1 {-# INLINE gameControllerClose #-} gameControllerEventState :: MonadIO m => CInt -> m CInt gameControllerEventState v1 = liftIO $ gameControllerEventStateFFI v1 {-# INLINE gameControllerEventState #-} gameControllerGetAttached :: MonadIO m => GameController -> m Bool gameControllerGetAttached v1 = liftIO $ gameControllerGetAttachedFFI v1 {-# INLINE gameControllerGetAttached #-} gameControllerGetAxis :: MonadIO m => GameController -> GameControllerAxis -> m Int16 gameControllerGetAxis v1 v2 = liftIO $ gameControllerGetAxisFFI v1 v2 {-# INLINE gameControllerGetAxis #-} gameControllerGetAxisFromString :: MonadIO m => CString -> m GameControllerAxis gameControllerGetAxisFromString v1 = liftIO $ gameControllerGetAxisFromStringFFI v1 {-# INLINE gameControllerGetAxisFromString #-} gameControllerGetBindForAxis :: MonadIO m => GameController -> GameControllerAxis -> m GameControllerButtonBind gameControllerGetBindForAxis gamecontroller axis = liftIO . alloca $ \ptr -> do gameControllerGetBindForAxisFFI gamecontroller axis ptr peek ptr {-# INLINE gameControllerGetBindForAxis #-} gameControllerGetBindForButton :: MonadIO m => GameController -> GameControllerButton -> m GameControllerButtonBind gameControllerGetBindForButton gamecontroller button = liftIO . alloca $ \ptr -> do gameControllerGetBindForButtonFFI gamecontroller button ptr peek ptr {-# INLINE gameControllerGetBindForButton #-} gameControllerGetButton :: MonadIO m => GameController -> GameControllerButton -> m Word8 gameControllerGetButton v1 v2 = liftIO $ gameControllerGetButtonFFI v1 v2 {-# INLINE gameControllerGetButton #-} gameControllerGetButtonFromString :: MonadIO m => CString -> m GameControllerButton gameControllerGetButtonFromString v1 = liftIO $ gameControllerGetButtonFromStringFFI v1 {-# INLINE gameControllerGetButtonFromString #-} gameControllerGetJoystick :: MonadIO m => GameController -> m Joystick gameControllerGetJoystick v1 = liftIO $ gameControllerGetJoystickFFI v1 {-# INLINE gameControllerGetJoystick #-} gameControllerGetStringForAxis :: MonadIO m => GameControllerAxis -> m CString gameControllerGetStringForAxis v1 = liftIO $ gameControllerGetStringForAxisFFI v1 {-# INLINE gameControllerGetStringForAxis #-} gameControllerGetStringForButton :: MonadIO m => GameControllerButton -> m CString gameControllerGetStringForButton v1 = liftIO $ gameControllerGetStringForButtonFFI v1 {-# INLINE gameControllerGetStringForButton #-} gameControllerMapping :: MonadIO m => GameController -> m CString gameControllerMapping v1 = liftIO $ gameControllerMappingFFI v1 {-# INLINE gameControllerMapping #-} gameControllerMappingForGUID :: MonadIO m => JoystickGUID -> m CString gameControllerMappingForGUID guid = liftIO . alloca $ \ptr -> do poke ptr guid gameControllerMappingForGUIDFFI ptr {-# INLINE gameControllerMappingForGUID #-} gameControllerName :: MonadIO m => GameController -> m CString gameControllerName v1 = liftIO $ gameControllerNameFFI v1 {-# INLINE gameControllerName #-} gameControllerNameForIndex :: MonadIO m => CInt -> m CString gameControllerNameForIndex v1 = liftIO $ gameControllerNameForIndexFFI v1 {-# INLINE gameControllerNameForIndex #-} gameControllerOpen :: MonadIO m => CInt -> m GameController gameControllerOpen v1 = liftIO $ gameControllerOpenFFI v1 {-# INLINE gameControllerOpen #-} gameControllerUpdate :: MonadIO m => m () gameControllerUpdate = liftIO gameControllerUpdateFFI {-# INLINE gameControllerUpdate #-} isGameController :: MonadIO m => CInt -> m Bool isGameController v1 = liftIO $ isGameControllerFFI v1 {-# INLINE isGameController #-}
dalaing/sdl2
src/SDL/Raw/Event.hs
bsd-3-clause
27,653
0
12
3,834
6,460
3,260
3,200
524
1
<?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="ur-PK"> <title>Sequence Scanner | 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>
kingthorin/zap-extensions
addOns/sequence/src/main/javahelp/org/zaproxy/zap/extension/sequence/resources/help_ur_PK/helpset_ur_PK.hs
apache-2.0
977
78
66
159
413
209
204
-1
-1
module DerivingEq where import DerivingUtils deriveEq stdnames src t@(_,TypeInfo{constructors=cs}) = do let pv = stdvalue stdnames mod_Prelude HsVar eq <- pv "==" true <- pv "True" false <- pv "False" andand <- pv "&&" let def = if length cs>1 then [alt2 src eq wild wild (ident false)] else [] eqalt ConInfo{conName=c0,conArity=n} = alt2 (srcLoc c0) eq (p xs) (p ys) rhs where c = convCon t c0 p vs = hsPApp c vs rhs = conj andand true comps comps = zipWith eqtst xs ys eqtst = opapp (HsVar eq) xs=take n (vars "x") ys=take n (vars "y") return [fun src (map eqalt cs++def)]
forste/haReFork
tools/base/transforms/Deriving/DerivingEq.hs
bsd-3-clause
678
7
16
208
318
157
161
21
2
module ShouldCompile where {- | blabla -} main = undefined
siddhanathan/ghc
testsuite/tests/haddock/should_compile_noflag_haddock/haddockC002.hs
bsd-3-clause
61
0
4
12
10
7
3
2
1