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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module Main where
import Gittins.Main (gittinsMain)
main :: IO ()
main = gittinsMain
| bmjames/gittins | gittins/Main.hs | bsd-3-clause | 87 | 0 | 6 | 15 | 29 | 17 | 12 | 4 | 1 |
module List (listModules) where
import Control.Applicative
import Data.List
import GHC
import Packages
import Types
import UniqFM
----------------------------------------------------------------
listModules :: Options -> IO String
listModules opt = convert opt . nub . sort <$> list opt
list :: Options -> IO [String]
list opt = withGHC $ do
initSession0 opt
getExposedModules <$> getSessionDynFlags
where
getExposedModules = map moduleNameString
. concatMap exposedModules
. eltsUFM . pkgIdMap . pkgState
| conal/ghc-mod | List.hs | bsd-3-clause | 568 | 0 | 11 | 128 | 139 | 72 | 67 | 16 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE PatternGuards #-}
module Daemon
( startServer
, sendCommand
, withUnixS
, forkUnixS
, closeUnixSocket
, bindUnixSocket
, Server
, ControlMessage(..)
) where
import Control.Applicative
import Control.Concurrent hiding (yield)
import Control.Concurrent.Async
import qualified Control.Exception as E
import Control.Lens
import Control.Monad
import Control.Monad.Extra hiding (bind)
import Control.Monad.Loops
import Control.Monad.Trans.State
import Data.Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Default
import Data.Monoid
import Data.Typeable
import qualified GHC
import Message
import Network.Socket hiding (send, recv)
import qualified Network.Socket.ByteString.Lazy as NB
import Pipes
import Pipes.Concurrent
import Pipes.Network.TCP (fromSocket, toSocket)
import qualified Pipes.Prelude as P
import System.Directory
import System.Exit
import System.IO
import System.IO.Error
import System.Posix
import System.Timeout
-- | A message to be sent to the thread processing the incoming connections.
data ControlMessage = SetTimeout (Maybe Int) -- ^ Set the timeout after which to exit starting with the next 'accept' call
-- | The state for the request handler
data ServerThread = ServerThread
{ _acceptTimeout :: Maybe Int
}
makeLenses ''ServerThread
instance Default ServerThread where
def = ServerThread Nothing
data Timeout = Timeout deriving (Typeable, Show)
instance E.Exception Timeout
-- | A server is a function that takes a producer of requests and writes it's responses to a
-- given consumer. It can also send control messages to the server runner using another
-- consumer.
type Server i o = Producer i IO () -> Consumer o IO () -> Consumer ControlMessage IO () -> IO ()
-- | @startServer f s@ listens on the given Socket and starts the server. The socket must be
-- bound to an address and in listening state.
startServer :: (FromJSON a, ToJSON r, ToJSON m) => Server a (Either r m) -> Socket -> IO ()
startServer f s = do
(reqOut,reqIn) <- spawn Unbounded
(resOut,resIn) <- spawn Unbounded
(ctlOut,ctlIn) <- spawn Unbounded
main <- myThreadId
a <- async $ flip evalStateT def $ forever $ do
lift $ putStrLn "Processing control messages ..."
whileJust_ (liftIO $ fmap join $ atomically $ fmap Just (recv ctlIn) <|> return Nothing) $ \(SetTimeout t) -> assign acceptTimeout t
t <- use acceptTimeout
lift $ putStrLn $ "Waiting for clients " ++ maybe "" (\t' -> "(Waiting at most " ++ show t' ++ " seconds)") t ++ " ..."
mbClient <- lift $ maybe (fmap Just) (timeout . (* 1000000)) t $ fmap fst $ accept s
lift $ case mbClient of
Nothing -> throwTo main Timeout
Just c -> flip E.finally (close c >> putStrLn "Closed client connection.") $ do
putStrLn "Accepted client."
void $ waitAnyCancel <=< mapM async $
[ do runEffect $ fromSocket c 4096 >-> sepP 0 >-> P.filter (not . BS.null) >-> jsonP onError >-> toOutput reqOut
putStrLn "Connection terminated by the client. "
, do runEffect $ fromInput resIn >-> handleEither >-> jsonS >-> sepS 0 >-> toSocket c
putStrLn "Connection terminated by the server."
]
E.catch (f (fromInput reqIn) (toOutput resOut) (toOutput ctlOut) `E.finally` cancel a) $ \Timeout -> putStrLn "Exiting because of timeout"
putStrLn "Performing garbage collection to exit ..."
performGC
putStrLn "Server handler exited. Stopping accept thread ..."
cancel a
where onError x = putStrLn x >> return False
handleEither = await >>= either (yield . Left) (yield . Right >=> const handleEither)
-- | Close a unix socket. This will also unlink the socket file.
closeUnixSocket :: FilePath -> Socket -> IO ()
closeUnixSocket p s = putStrLn "Closing socket" >> close s >> removeFile p `E.catch` \(_ :: E.IOException) -> return ()
-- | @withUnixS p f c@ tries to connect to a unix socket bound to the file @p@. If that fails, it calls f and tries
-- again after f returned. If a connection can be established, the connected socket is passed to c and the result of
-- c is returned in a Just. If connecting fails, Nothing is returned.
withUnixS :: FilePath -> (FilePath -> IO ()) -> (Socket -> IO r) -> IO (Maybe r)
withUnixS p f c =
E.bracket (socket AF_UNIX Stream 0) close $ \s -> do
E.catch (connect s $ SockAddrUnix p) $ \(_ :: E.IOException) -> do
f p
E.catch (connect s $ SockAddrUnix p) $ \(_ :: E.IOException) -> return ()
connected <- isConnected s
if connected
then Just <$> c s
else return Nothing
-- | Connect to the socket at the given path. This function will throw an exception
-- when the path already exists and is not a socket. If the path is a socket and exists,
-- it will be deleted.
-- This will return Nothing when binding the socket fails.
bindUnixSocket :: FilePath -> IO (Maybe Socket)
bindUnixSocket p = do
-- Remove the file if it already exists, but only if it is a socket.
-- The rationale behind this is that if the file is a socket, it was probably
-- created by our program, so it's safe to delete it.
om when (doesFileExist p) $ do
sock <- fmap isSocket $ getFileStatus p
unless sock $ ioError $ mkIOError alreadyExistsErrorType "ghc-server:forkUnixS" Nothing (Just p)
removeFile p
sock <- socket AF_UNIX Stream 0
ei <- E.try $ bind sock $ SockAddrUnix p
case ei of
Left (_ :: E.IOException) -> return Nothing
Right () -> do
listen sock maxListenQueue
return $ Just sock
-- | @forkUnixS f s p@ runs the server s in a new daemon process. It listens on the unix socket
-- at the path @p@. @f@ is the path to the log file.
-- When this function returns, connections are accepted on the given unix socket.
forkUnixS :: (FromJSON i, ToJSON r, ToJSON m) => FilePath -> Server i (Either r m) -> FilePath -> IO ()
forkUnixS f s p = do
-- Create the socket. If we created the socket only in the forked server process, then it wouldn't
-- be ready to accept connections right after the return of this function. That's the reason why
-- the socket is already bound here.
sock <- bindUnixSocket p
-- Daemonize
case sock of
Nothing -> hPutStrLn stderr "ghc-server:forkUnixS: Ignored IO exception when trying to bind socket. Not starting server."
Just sock' -> void $ forkProcess $ child1 sock'
where child1 sock = do
void createSession
void $ forkProcess $ child2 sock
exitSuccess
child2 sock = do
void $ setFileCreationMask 0
-- Remap STDIN/ERR/OUT to the log file (which might be /dev/null or a real log file).
mapM_ closeFd [stdInput, stdOutput, stdError]
fd <- openFd f ReadWrite (Just $ 8 ^ (3 :: Int) - 1) defaultFileFlags { trunc = True }
mapM_ (dupTo fd) [stdInput, stdOutput, stdError]
closeFd fd
-- Stdout or stderr might be block buffered if bound to file. We use stdout/stderr for
-- logging purposes, so there should be only line buffering. We don't disable buffering
-- entirely, because that results in the lines being mixed up when we use multiple threads.
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
putStrLn "Server process setup done."
-- Close the socket if we get killed
forM_ [sigHUP, sigINT, sigTERM, sigPIPE] $ \x ->
installHandler x (Catch $ putStrLn "Caught signal. Exiting." >> closeUnixSocket p sock >> exitSuccess) Nothing
putStrLn "Signal handlers set."
-- Now start the server process
ei <- E.try $ flip E.finally (closeUnixSocket p sock) $ do
startServer s sock
putStrLn "Server exited."
case ei of
Left e
| Just (GHC.Signal _) <- E.fromException e -> putStrLn "Exiting because of signal" >> exitSuccess -- GHC API changes signal handlers, WTF ?!
| otherwise -> putStrLn "Exception:" >> print e >> exitFailure
Right () -> putStrLn "Exit success." >> exitSuccess
-- | Send a command to the server. The second argument is the consumer which processes the responses of the server. The socket
-- must be connected to the server.
sendCommand :: (FromJSON i, ToJSON i, FromJSON o, ToJSON o) => (String -> IO Bool) -> i -> Consumer o IO r -> Socket -> IO (Maybe r)
sendCommand jsonError req c s = do
void $ NB.send s $ encode req <> LBS.singleton 0
runEffect $ (Nothing <$ fromSocket s 20 >-> sepP 0 >-> jsonP jsonError) >-> fmap Just c
| bennofs/ghc-server | src/Daemon.hs | bsd-3-clause | 9,030 | 0 | 28 | 2,288 | 2,140 | 1,071 | 1,069 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Database.Tempodb.Methods.Read
( readOne
, readMulti
)
where
import Control.Monad.Reader
import Data.Aeson as A
import Data.ByteString.Char8 as C8
import Data.ByteString.Lazy (fromStrict)
import Data.Monoid
import Database.Tempodb.Types
import Database.Tempodb.Util
import Network.HTTP.Base (urlEncodeVars)
import Network.Http.Client
readOne :: IdOrKey -> Maybe QueryArgs -> Tempodb (Maybe SeriesData)
readOne q qa = do
auth <- ask
req <- liftIO . buildRequest $ do
http GET path
auth
(_,result) <- liftIO $ runRequest req Nothing
return . A.decode $ fromStrict result
where
ident (SeriesId i) = "/id/" <> i
ident (SeriesKey k) = "/key/" <> k
path = rootpath <> "/series" <> (ident q) <> "/data" <> query
query = case qa of
Nothing -> mempty
Just qry -> "?" <> (C8.pack $ urlEncodeVars qry)
readMulti :: Maybe QueryArgs -> Tempodb (Maybe [SeriesData])
readMulti q = do
auth <- ask
req <- liftIO . buildRequest $ do
http GET path
auth
(_,result) <- liftIO $ runRequest req Nothing
return . A.decode $ fromStrict result
where
path = rootpath <> "/data" <> query
query = case q of
Nothing -> mempty
Just qry -> "?" <> (C8.pack $ urlEncodeVars qry)
| ixmatus/hs-tempodb | src/Database/Tempodb/Methods/Read.hs | bsd-3-clause | 1,436 | 0 | 13 | 436 | 453 | 234 | 219 | 39 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : System.Posix.Internals
-- Copyright : (c) The University of Glasgow, 1992-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- POSIX support layer for the standard libraries.
-- This library is built on *every* platform, including Win32.
--
-- Non-posix compliant in order to support the following features:
-- * S_ISSOCK (no sockets in POSIX)
--
-----------------------------------------------------------------------------
-- #hide
module System.Posix.Internals where
import Control.Monad
import System.Posix.Types
import Foreign
import Foreign.C
import Data.Bits
import Data.Maybe
import System.IO
import Hugs.Prelude (IOException(..), IOErrorType(..))
{-# CBITS PrelIOUtils.c dirUtils.c consUtils.c #-}
ioException = ioError
-- ---------------------------------------------------------------------------
-- Types
type CDir = ()
type CDirent = ()
type CFLock = ()
type CGroup = ()
type CLconv = ()
type CPasswd = ()
type CSigaction = ()
type CSigset = ()
type CStat = ()
type CTermios = ()
type CTm = ()
type CTms = ()
type CUtimbuf = ()
type CUtsname = ()
type FD = Int
-- ---------------------------------------------------------------------------
-- stat()-related stuff
fdFileSize :: Int -> IO Integer
fdFileSize fd =
allocaBytes sizeof_stat $ \ p_stat -> do
throwErrnoIfMinus1Retry "fileSize" $
c_fstat (fromIntegral fd) p_stat
c_mode <- st_mode p_stat :: IO CMode
if not (s_isreg c_mode)
then return (-1)
else do
c_size <- st_size p_stat :: IO COff
return (fromIntegral c_size)
data FDType = Directory | Stream | RegularFile
deriving (Eq)
fileType :: FilePath -> IO FDType
fileType file =
allocaBytes sizeof_stat $ \ p_stat -> do
withCString file $ \p_file -> do
throwErrnoIfMinus1Retry "fileType" $
c_stat p_file p_stat
statGetType p_stat
-- NOTE: On Win32 platforms, this will only work with file descriptors
-- referring to file handles. i.e., it'll fail for socket FDs.
fdType :: Int -> IO FDType
fdType fd =
allocaBytes sizeof_stat $ \ p_stat -> do
throwErrnoIfMinus1Retry "fdType" $
c_fstat (fromIntegral fd) p_stat
statGetType p_stat
statGetType p_stat = do
c_mode <- st_mode p_stat :: IO CMode
case () of
_ | s_isdir c_mode -> return Directory
| s_isfifo c_mode || s_issock c_mode || s_ischr c_mode
-> return Stream
| s_isreg c_mode -> return RegularFile
| otherwise -> ioError ioe_unknownfiletype
ioe_unknownfiletype = IOError Nothing UnsupportedOperation "fdType"
"unknown file type" Nothing
-- It isn't clear whether ftruncate is POSIX or not (I've read several
-- manpages and they seem to conflict), so we truncate using open/2.
fileTruncate :: FilePath -> IO ()
fileTruncate file = do
let flags = o_WRONLY .|. o_TRUNC
withCString file $ \file_cstr -> do
fd <- fromIntegral `liftM`
throwErrnoIfMinus1Retry "fileTruncate"
(c_open file_cstr (fromIntegral flags) 0o666)
c_close fd
return ()
closeFd :: Bool -> CInt -> IO CInt
closeFd isStream fd
| isStream = c_closesocket fd
| otherwise = c_close fd
foreign import stdcall unsafe "HsBase.h closesocket"
c_closesocket :: CInt -> IO CInt
fdGetMode :: Int -> IO IOMode
fdGetMode fd = do
flags1 <- throwErrnoIfMinus1Retry "fdGetMode"
(c__setmode (fromIntegral fd) (fromIntegral o_WRONLY))
flags <- throwErrnoIfMinus1Retry "fdGetMode"
(c__setmode (fromIntegral fd) (fromIntegral flags1))
let
wH = (flags .&. o_WRONLY) /= 0
aH = (flags .&. o_APPEND) /= 0
rwH = (flags .&. o_RDWR) /= 0
mode
| wH && aH = AppendMode
| wH = WriteMode
| rwH = ReadWriteMode
| otherwise = ReadMode
return mode
-- ---------------------------------------------------------------------------
-- Terminal-related stuff
fdIsTTY :: Int -> IO Bool
fdIsTTY fd = c_isatty (fromIntegral fd) >>= return.toBool
-- 'raw' mode for Win32 means turn off 'line input' (=> buffering and
-- character translation for the console.) The Win32 API for doing
-- this is GetConsoleMode(), which also requires echoing to be disabled
-- when turning off 'line input' processing. Notice that turning off
-- 'line input' implies enter/return is reported as '\r' (and it won't
-- report that character until another character is input..odd.) This
-- latter feature doesn't sit too well with IO actions like IO.hGetLine..
-- consider yourself warned.
setCooked :: Int -> Bool -> IO ()
setCooked fd cooked = do
x <- set_console_buffering (fromIntegral fd) (if cooked then 1 else 0)
if (x /= 0)
then ioException (ioe_unk_error "setCooked" "failed to set buffering")
else return ()
ioe_unk_error loc msg
= IOError Nothing OtherError loc msg Nothing
-- Note: echoing goes hand in hand with enabling 'line input' / raw-ness
-- for Win32 consoles, hence setEcho ends up being the inverse of setCooked.
setEcho :: Int -> Bool -> IO ()
setEcho fd on = do
x <- set_console_echo (fromIntegral fd) (if on then 1 else 0)
if (x /= 0)
then ioException (ioe_unk_error "setEcho" "failed to set echoing")
else return ()
getEcho :: Int -> IO Bool
getEcho fd = do
r <- get_console_echo (fromIntegral fd)
if (r == (-1))
then ioException (ioe_unk_error "getEcho" "failed to get echoing")
else return (r == 1)
foreign import ccall unsafe "consUtils.h set_console_buffering__"
set_console_buffering :: CInt -> CInt -> IO CInt
foreign import ccall unsafe "consUtils.h set_console_echo__"
set_console_echo :: CInt -> CInt -> IO CInt
foreign import ccall unsafe "consUtils.h get_console_echo__"
get_console_echo :: CInt -> IO CInt
-- ---------------------------------------------------------------------------
-- Turning on non-blocking for a file descriptor
-- bogus defns for win32
setNonBlockingFD fd = return ()
-- -----------------------------------------------------------------------------
-- foreign imports
foreign import ccall unsafe "HsBase.h access"
c_access :: CString -> CMode -> IO CInt
foreign import ccall unsafe "HsBase.h chmod"
c_chmod :: CString -> CMode -> IO CInt
foreign import ccall unsafe "HsBase.h chdir"
c_chdir :: CString -> IO CInt
foreign import ccall unsafe "HsBase.h close"
c_close :: CInt -> IO CInt
foreign import ccall unsafe "HsBase.h closedir"
c_closedir :: Ptr CDir -> IO CInt
foreign import ccall unsafe "HsBase.h creat"
c_creat :: CString -> CMode -> IO CInt
foreign import ccall unsafe "HsBase.h dup"
c_dup :: CInt -> IO CInt
foreign import ccall unsafe "HsBase.h dup2"
c_dup2 :: CInt -> CInt -> IO CInt
foreign import ccall unsafe "HsBase.h fstat"
c_fstat :: CInt -> Ptr CStat -> IO CInt
foreign import ccall unsafe "HsBase.h getcwd"
c_getcwd :: Ptr CChar -> CInt -> IO (Ptr CChar)
foreign import ccall unsafe "HsBase.h isatty"
c_isatty :: CInt -> IO CInt
foreign import ccall unsafe "HsBase.h lseek"
c_lseek :: CInt -> COff -> CInt -> IO COff
foreign import ccall unsafe "HsBase.h __hscore_lstat"
lstat :: CString -> Ptr CStat -> IO CInt
foreign import ccall unsafe "HsBase.h open"
c_open :: CString -> CInt -> CMode -> IO CInt
foreign import ccall unsafe "HsBase.h opendir"
c_opendir :: CString -> IO (Ptr CDir)
foreign import ccall unsafe "HsBase.h __hscore_mkdir"
mkdir :: CString -> CInt -> IO CInt
foreign import ccall unsafe "HsBase.h read"
c_read :: CInt -> Ptr CChar -> CSize -> IO CSsize
foreign import ccall unsafe "HsBase.h readdir"
c_readdir :: Ptr CDir -> IO (Ptr CDirent)
foreign import ccall unsafe "dirUtils.h __hscore_renameFile"
c_rename :: CString -> CString -> IO CInt
foreign import ccall unsafe "HsBase.h rewinddir"
c_rewinddir :: Ptr CDir -> IO ()
foreign import ccall unsafe "HsBase.h rmdir"
c_rmdir :: CString -> IO CInt
foreign import ccall unsafe "HsBase.h stat"
c_stat :: CString -> Ptr CStat -> IO CInt
foreign import ccall unsafe "HsBase.h umask"
c_umask :: CMode -> IO CMode
foreign import ccall unsafe "HsBase.h write"
c_write :: CInt -> Ptr CChar -> CSize -> IO CSsize
foreign import ccall unsafe "HsBase.h unlink"
c_unlink :: CString -> IO CInt
foreign import ccall unsafe "HsBase.h _setmode"
c__setmode :: CInt -> CInt -> IO CInt
--
-- result = _setmode( _fileno( stdin ), _O_BINARY );
-- if( result == -1 )
-- perror( "Cannot set mode" );
-- else
-- printf( "'stdin' successfully changed to binary mode\n" );
-- traversing directories
foreign import ccall unsafe "dirUtils.h __hscore_readdir"
readdir :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt
foreign import ccall unsafe "HsBase.h __hscore_free_dirent"
freeDirEnt :: Ptr CDirent -> IO ()
foreign import ccall unsafe "HsBase.h __hscore_end_of_dir"
end_of_dir :: CInt
foreign import ccall unsafe "HsBase.h __hscore_d_name"
d_name :: Ptr CDirent -> IO CString
-- POSIX flags only:
foreign import ccall unsafe "HsBase.h __hscore_o_rdonly" o_RDONLY :: CInt
foreign import ccall unsafe "HsBase.h __hscore_o_wronly" o_WRONLY :: CInt
foreign import ccall unsafe "HsBase.h __hscore_o_rdwr" o_RDWR :: CInt
foreign import ccall unsafe "HsBase.h __hscore_o_append" o_APPEND :: CInt
foreign import ccall unsafe "HsBase.h __hscore_o_creat" o_CREAT :: CInt
foreign import ccall unsafe "HsBase.h __hscore_o_excl" o_EXCL :: CInt
foreign import ccall unsafe "HsBase.h __hscore_o_trunc" o_TRUNC :: CInt
-- non-POSIX flags.
foreign import ccall unsafe "HsBase.h __hscore_o_noctty" o_NOCTTY :: CInt
foreign import ccall unsafe "HsBase.h __hscore_o_nonblock" o_NONBLOCK :: CInt
foreign import ccall unsafe "HsBase.h __hscore_o_binary" o_BINARY :: CInt
foreign import ccall unsafe "HsBase.h __hscore_s_isreg" s_isreg :: CMode -> Bool
foreign import ccall unsafe "HsBase.h __hscore_s_ischr" s_ischr :: CMode -> Bool
foreign import ccall unsafe "HsBase.h __hscore_s_isblk" s_isblk :: CMode -> Bool
foreign import ccall unsafe "HsBase.h __hscore_s_isdir" s_isdir :: CMode -> Bool
foreign import ccall unsafe "HsBase.h __hscore_s_isfifo" s_isfifo :: CMode -> Bool
foreign import ccall unsafe "HsBase.h __hscore_sizeof_stat" sizeof_stat :: Int
foreign import ccall unsafe "HsBase.h __hscore_st_mtime" st_mtime :: Ptr CStat -> IO CTime
foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO COff
foreign import ccall unsafe "HsBase.h __hscore_st_mode" st_mode :: Ptr CStat -> IO CMode
foreign import ccall unsafe "HsBase.h __hscore_echo" const_echo :: CInt
foreign import ccall unsafe "HsBase.h __hscore_tcsanow" const_tcsanow :: CInt
foreign import ccall unsafe "HsBase.h __hscore_icanon" const_icanon :: CInt
foreign import ccall unsafe "HsBase.h __hscore_vmin" const_vmin :: CInt
foreign import ccall unsafe "HsBase.h __hscore_vtime" const_vtime :: CInt
foreign import ccall unsafe "HsBase.h __hscore_sigttou" const_sigttou :: CInt
foreign import ccall unsafe "HsBase.h __hscore_sig_block" const_sig_block :: CInt
foreign import ccall unsafe "HsBase.h __hscore_sig_setmask" const_sig_setmask :: CInt
foreign import ccall unsafe "HsBase.h __hscore_f_getfl" const_f_getfl :: CInt
foreign import ccall unsafe "HsBase.h __hscore_f_setfl" const_f_setfl :: CInt
s_issock :: CMode -> Bool
s_issock cmode = False
| OS2World/DEV-UTIL-HUGS | libraries/System/Posix/Internals.hs | bsd-3-clause | 12,598 | 36 | 18 | 3,281 | 2,616 | 1,382 | 1,234 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module PipeAlgorithms where
--import Math.Probable
--import qualified Data.Sequence as S
--import Data.Random
--import Data.Random.Distribution.Uniform
--
--import Control.Monad
--
--import Pipes.Safe
--import Pipes
--
--import PipeOperators
--import Selection
--import Channels
--import PointMutation
--import Crossover
--import Rotation
--import UtilsRandom
--import RGEP
--import Types
--import Evaluation
--TODO replace init by pop32
--pipedGA ps is gens pm pc fitness = do
-- initialPopulation <- S.replicateM ps $ S.replicateM is $ stdUniformT
-- runStage' initialPopulation $ cycleNTimes gens $ geneticAlgorithmP ps is gens pm pc fitness
--
--
--geneticAlgorithmP ps is gens pm pc fitnessFunction =
-- let fitnessPipe = for cat $ \ ind -> yield (Evaled (Expressed ind ind) (fitnessFunction ind))
-- in (stage (for cat each >->
-- fitnessPipe >->
-- collect ps >->
-- tournamentSelectionP ps 2 >->
-- pmPopulationP ps pm 1 >->
-- crossoverP pc is))
--
--
--parallelGA ps is gens pm pc fitness = do
-- initialPopulation <- S.replicateM ps $ S.replicateM is $ stdUniformT
-- runStage' initialPopulation $ cycleNTimes gens $ parallelGAP ps is gens pm pc fitness
--TODO this terminates without producing a result
--may have to do with a stage ending early?
--add stages back to get parallelism
--parallelGAP ::
-- Int -> -- Population size
-- Int -> -- Individual size
-- Int -> -- Number of generations to run
-- Double -> -- Probabilty of point mutation
-- Double -> -- Probabilty of crossover
-- (Ind32 -> Double) -> -- Evaluation
-- Stage (SafeT IO) Pop32 Pop32
--parallelGAP ps is gens pm pc fitnessFunction =
-- let fitnessPipe = undefined --for cat $ \ ind -> yield (ind, fitnessFunction ind)
-- in (--(stage (for cat each)) >=>
-- --(stage fitnessPipe) >=>
-- --(stage (collect ps)) >=>
-- --((fitnessLogger True True)) >=>
-- --(stage (tournamentSelectionP ps 2)) >=>
-- (stage (pmPopulationP ps pm 1)) >=>
-- (stage (crossoverP pc is)))
--geneticAlgorithmDefaultP fitness = geneticAlgorithmP 100 10 100 0.01 0.8 fitness
{-
-- The types are slightly off here. "a" is forced to Ind32 for some reason.
-- This seems to have to do with the type of one of the operators
rgepP ::
Int -> --population size
Int -> --individual size
[Op a] -> --operators
Prob -> -- pm
Prob -> -- pr
Prob -> -- pc1
Prob -> -- pc2
Prob -> -- tournament selection prob
Int -> -- generations
a -> -- default value
(a -> R Double) ->
R Pop32
-}
--rgepP ps is ops pm pr pc1 pc2 pt gens def eval = do
-- let bits = bitsUsed ops
-- decoder = decode ops
-- rgepEvaluation pop = undefined -- evaluation (evalInd eval) (fmap (rgepRun decoder def) pop)
-- pop <- pop32 ps is bits
-- runStage' pop $ cycleNTimes gens $ parallelRGEP ps is bits gens pm pr pc1 pc2 eval
--
--parallelRGEP ps is bits gens pm pr pc1 pc2 fitnessFunction =
-- let fitnessPipe = for cat $ \ ind -> do fitness <- lift $ fitnessFunction ind
-- yield (Evaled (Expressed ind ind) fitness)
-- in ((stage (for cat each)) >=>
-- (stations 8 $ stage fitnessPipe) >=>
-- (stage (collect ps)) >=>
-- (stage (stochasticTournamentSelectionP 0.8 ps 2)) >=>
-- (stage (for cat each)) >=>
-- (stations 8 $ stage (pointMutationP pm bits)) >=>
-- (stations 8 $ stage (rotationP pm is)) >=>
-- (stage (collect ps)) >=>
-- (stations 8 $ stage (crossoverP pc1 is)))
| nsmryan/Misc | src/PipeAlgorithms.hs | bsd-3-clause | 3,574 | 0 | 2 | 811 | 85 | 84 | 1 | 2 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Yelp
( -- * @YelpT@ monad transformer
YelpT
, runYelpT
-- * Authentication
, Credentials(..)
-- * Yelp's Search API
-- ** Request
, simpleSearch
, search
, LocationQuery(..)
, BoundingBox(..)
, SearchCoordinates(..)
, Neighbourhood(..)
, Paging(..)
, SortOption(..)
, SearchFilter(..)
-- ** Response
, SearchResult(..)
, Region(..)
, CoordinateSpan(..)
-- * Yelp's Business API
-- ** Request
, getBusiness
, BusinessId
-- ** Response
, Business(..)
, Location(..)
, Deal(..)
, DealOption(..)
, GiftCertificate(..)
, Price(..)
, Review(..)
, Rating(..)
, User(..)
-- * Common Types
, Locale(..)
, Coordinates(..)
-- * Raw API access
, getObject
-- * Exceptions
, YelpException(..)
) where
import Web.Yelp.Base
import Web.Yelp.Business
import Web.Yelp.Monad
import Web.Yelp.Search
import Web.Yelp.Types
| mcschroeder/yelp | Web/Yelp.hs | bsd-3-clause | 1,046 | 0 | 5 | 319 | 232 | 166 | 66 | 38 | 0 |
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE ExistentialQuantification #-}
module Network.TLS.Crypto
( HashContext
, HashCtx
, hashInit
, hashUpdate
, hashUpdateSSL
, hashFinal
, module Network.TLS.Crypto.DH
, module Network.TLS.Crypto.IES
, module Network.TLS.Crypto.Types
-- * Hash
, hash
, Hash(..)
, hashName
, hashDigestSize
, hashBlockSize
-- * key exchange generic interface
, PubKey(..)
, PrivKey(..)
, PublicKey
, PrivateKey
, SignatureParams(..)
, findDigitalSignatureAlg
, kxEncrypt
, kxDecrypt
, kxSign
, kxVerify
, KxError(..)
, RSAEncoding(..)
) where
import qualified Crypto.Hash as H
import qualified Data.ByteString as B
import qualified Data.ByteArray as B (convert)
import Data.ByteString (ByteString)
import Crypto.Random
import qualified Crypto.PubKey.DSA as DSA
import qualified Crypto.PubKey.ECC.ECDSA as ECDSA
import qualified Crypto.PubKey.ECC.Prim as ECC
import qualified Crypto.PubKey.ECC.Types as ECC
import qualified Crypto.PubKey.RSA as RSA
import qualified Crypto.PubKey.RSA.PKCS15 as RSA
import qualified Crypto.PubKey.RSA.PSS as PSS
import Crypto.Number.Serialize (os2ip)
import Data.X509 (PrivKey(..), PubKey(..), PubKeyEC(..), SerializedPoint(..))
import Network.TLS.Crypto.DH
import Network.TLS.Crypto.IES
import Network.TLS.Crypto.Types
import Data.ASN1.Types
import Data.ASN1.Encoding
import Data.ASN1.BinaryEncoding (DER(..), BER(..))
import Data.List (find)
{-# DEPRECATED PublicKey "use PubKey" #-}
type PublicKey = PubKey
{-# DEPRECATED PrivateKey "use PrivKey" #-}
type PrivateKey = PrivKey
data KxError =
RSAError RSA.Error
| KxUnsupported
deriving (Show)
findDigitalSignatureAlg :: (PubKey, PrivKey) -> Maybe DigitalSignatureAlg
findDigitalSignatureAlg keyPair =
case keyPair of
(PubKeyRSA _, PrivKeyRSA _) -> Just RSA
(PubKeyDSA _, PrivKeyDSA _) -> Just DSS
--(PubKeyECDSA _, PrivKeyECDSA _) -> Just ECDSA
_ -> Nothing
-- functions to use the hidden class.
hashInit :: Hash -> HashContext
hashInit MD5 = HashContext $ ContextSimple (H.hashInit :: H.Context H.MD5)
hashInit SHA1 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA1)
hashInit SHA224 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA224)
hashInit SHA256 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA256)
hashInit SHA384 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA384)
hashInit SHA512 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA512)
hashInit SHA1_MD5 = HashContextSSL H.hashInit H.hashInit
hashUpdate :: HashContext -> B.ByteString -> HashCtx
hashUpdate (HashContext (ContextSimple h)) b = HashContext $ ContextSimple (H.hashUpdate h b)
hashUpdate (HashContextSSL sha1Ctx md5Ctx) b =
HashContextSSL (H.hashUpdate sha1Ctx b) (H.hashUpdate md5Ctx b)
hashUpdateSSL :: HashCtx
-> (B.ByteString,B.ByteString) -- ^ (for the md5 context, for the sha1 context)
-> HashCtx
hashUpdateSSL (HashContext _) _ = error "internal error: update SSL without a SSL Context"
hashUpdateSSL (HashContextSSL sha1Ctx md5Ctx) (b1,b2) =
HashContextSSL (H.hashUpdate sha1Ctx b2) (H.hashUpdate md5Ctx b1)
hashFinal :: HashCtx -> B.ByteString
hashFinal (HashContext (ContextSimple h)) = B.convert $ H.hashFinalize h
hashFinal (HashContextSSL sha1Ctx md5Ctx) =
B.concat [B.convert (H.hashFinalize md5Ctx), B.convert (H.hashFinalize sha1Ctx)]
data Hash = MD5 | SHA1 | SHA224 | SHA256 | SHA384 | SHA512 | SHA1_MD5
deriving (Show,Eq)
data HashContext =
HashContext ContextSimple
| HashContextSSL (H.Context H.SHA1) (H.Context H.MD5)
instance Show HashContext where
show _ = "hash-context"
data ContextSimple = forall alg . H.HashAlgorithm alg => ContextSimple (H.Context alg)
type HashCtx = HashContext
hash :: Hash -> B.ByteString -> B.ByteString
hash MD5 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.MD5) $ b
hash SHA1 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA1) $ b
hash SHA224 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA224) $ b
hash SHA256 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA256) $ b
hash SHA384 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA384) $ b
hash SHA512 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA512) $ b
hash SHA1_MD5 b =
B.concat [B.convert (md5Hash b), B.convert (sha1Hash b)]
where
sha1Hash :: B.ByteString -> H.Digest H.SHA1
sha1Hash = H.hash
md5Hash :: B.ByteString -> H.Digest H.MD5
md5Hash = H.hash
hashName :: Hash -> String
hashName = show
hashDigestSize :: Hash -> Int
hashDigestSize MD5 = 16
hashDigestSize SHA1 = 20
hashDigestSize SHA224 = 28
hashDigestSize SHA256 = 32
hashDigestSize SHA384 = 48
hashDigestSize SHA512 = 64
hashDigestSize SHA1_MD5 = 36
hashBlockSize :: Hash -> Int
hashBlockSize MD5 = 64
hashBlockSize SHA1 = 64
hashBlockSize SHA224 = 64
hashBlockSize SHA256 = 64
hashBlockSize SHA384 = 128
hashBlockSize SHA512 = 128
hashBlockSize SHA1_MD5 = 64
{- key exchange methods encrypt and decrypt for each supported algorithm -}
generalizeRSAError :: Either RSA.Error a -> Either KxError a
generalizeRSAError (Left e) = Left (RSAError e)
generalizeRSAError (Right x) = Right x
kxEncrypt :: MonadRandom r => PublicKey -> ByteString -> r (Either KxError ByteString)
kxEncrypt (PubKeyRSA pk) b = generalizeRSAError `fmap` RSA.encrypt pk b
kxEncrypt _ _ = return (Left KxUnsupported)
kxDecrypt :: MonadRandom r => PrivateKey -> ByteString -> r (Either KxError ByteString)
kxDecrypt (PrivKeyRSA pk) b = generalizeRSAError `fmap` RSA.decryptSafer pk b
kxDecrypt _ _ = return (Left KxUnsupported)
data RSAEncoding = RSApkcs1 | RSApss deriving (Show,Eq)
-- Signature algorithm and associated parameters.
--
-- FIXME add RSAPSSParams, Ed25519Params, Ed448Params
data SignatureParams =
RSAParams Hash RSAEncoding
| DSSParams
| ECDSAParams Hash
deriving (Show,Eq)
-- Verify that the signature matches the given message, using the
-- public key.
--
kxVerify :: PublicKey -> SignatureParams -> ByteString -> ByteString -> Bool
kxVerify (PubKeyRSA pk) (RSAParams alg RSApkcs1) msg sign = rsaVerifyHash alg pk msg sign
kxVerify (PubKeyRSA pk) (RSAParams alg RSApss) msg sign = rsapssVerifyHash alg pk msg sign
kxVerify (PubKeyDSA pk) DSSParams msg signBS =
case dsaToSignature signBS of
Just sig -> DSA.verify H.SHA1 pk sig msg
_ -> False
where
dsaToSignature :: ByteString -> Maybe DSA.Signature
dsaToSignature b =
case decodeASN1' BER b of
Left _ -> Nothing
Right asn1 ->
case asn1 of
Start Sequence:IntVal r:IntVal s:End Sequence:_ ->
Just $ DSA.Signature { DSA.sign_r = r, DSA.sign_s = s }
_ ->
Nothing
kxVerify (PubKeyEC key) (ECDSAParams alg) msg sigBS = maybe False id $ do
-- get the curve name and the public key data
(curveName, pubBS) <- case key of
PubKeyEC_Named curveName' pub -> Just (curveName',pub)
PubKeyEC_Prime {} ->
case find matchPrimeCurve $ enumFrom $ toEnum 0 of
Nothing -> Nothing
Just curveName' -> Just (curveName', pubkeyEC_pub key)
-- decode the signature
signature <- case decodeASN1' BER sigBS of
Left _ -> Nothing
Right [Start Sequence,IntVal r,IntVal s,End Sequence] -> Just $ ECDSA.Signature r s
Right _ -> Nothing
-- decode the public key related to the curve
pubkey <- unserializePoint (ECC.getCurveByName curveName) pubBS
verifyF <- case alg of
MD5 -> Just (ECDSA.verify H.MD5)
SHA1 -> Just (ECDSA.verify H.SHA1)
SHA224 -> Just (ECDSA.verify H.SHA224)
SHA256 -> Just (ECDSA.verify H.SHA256)
SHA384 -> Just (ECDSA.verify H.SHA384)
SHA512 -> Just (ECDSA.verify H.SHA512)
_ -> Nothing
return $ verifyF pubkey signature msg
where
matchPrimeCurve c =
case ECC.getCurveByName c of
ECC.CurveFP (ECC.CurvePrime p cc) ->
ECC.ecc_a cc == pubkeyEC_a key &&
ECC.ecc_b cc == pubkeyEC_b key &&
ECC.ecc_n cc == pubkeyEC_order key &&
p == pubkeyEC_prime key
_ -> False
unserializePoint curve (SerializedPoint bs) =
case B.uncons bs of
Nothing -> Nothing
Just (ptFormat, input) ->
case ptFormat of
4 -> if B.length input /= 2 * bytes
then Nothing
else
let (x, y) = B.splitAt bytes input
p = ECC.Point (os2ip x) (os2ip y)
in if ECC.isPointValid curve p
then Just $ ECDSA.PublicKey curve p
else Nothing
-- 2 and 3 for compressed format.
_ -> Nothing
where bits = ECC.curveSizeBits curve
bytes = (bits + 7) `div` 8
kxVerify _ _ _ _ = False
-- Sign the given message using the private key.
--
kxSign :: MonadRandom r
=> PrivateKey
-> SignatureParams
-> ByteString
-> r (Either KxError ByteString)
kxSign (PrivKeyRSA pk) (RSAParams hashAlg RSApkcs1) msg =
generalizeRSAError `fmap` rsaSignHash hashAlg pk msg
kxSign (PrivKeyRSA pk) (RSAParams hashAlg RSApss) msg =
generalizeRSAError `fmap` rsapssSignHash hashAlg pk msg
kxSign (PrivKeyDSA pk) DSSParams msg = do
sign <- DSA.sign pk H.SHA1 msg
return (Right $ encodeASN1' DER $ dsaSequence sign)
where dsaSequence sign = [Start Sequence,IntVal (DSA.sign_r sign),IntVal (DSA.sign_s sign),End Sequence]
kxSign _ _ _ =
return (Left KxUnsupported)
rsaSignHash :: MonadRandom m => Hash -> RSA.PrivateKey -> ByteString -> m (Either RSA.Error ByteString)
rsaSignHash SHA1_MD5 pk msg = RSA.signSafer noHash pk msg
rsaSignHash MD5 pk msg = RSA.signSafer (Just H.MD5) pk msg
rsaSignHash SHA1 pk msg = RSA.signSafer (Just H.SHA1) pk msg
rsaSignHash SHA224 pk msg = RSA.signSafer (Just H.SHA224) pk msg
rsaSignHash SHA256 pk msg = RSA.signSafer (Just H.SHA256) pk msg
rsaSignHash SHA384 pk msg = RSA.signSafer (Just H.SHA384) pk msg
rsaSignHash SHA512 pk msg = RSA.signSafer (Just H.SHA512) pk msg
rsapssSignHash :: MonadRandom m => Hash -> RSA.PrivateKey -> ByteString -> m (Either RSA.Error ByteString)
rsapssSignHash SHA256 pk msg = PSS.signSafer (PSS.defaultPSSParams H.SHA256) pk msg
rsapssSignHash SHA384 pk msg = PSS.signSafer (PSS.defaultPSSParams H.SHA384) pk msg
rsapssSignHash SHA512 pk msg = PSS.signSafer (PSS.defaultPSSParams H.SHA512) pk msg
rsapssSignHash _ _ _ = error "rsapssSignHash: unsupported hash"
rsaVerifyHash :: Hash -> RSA.PublicKey -> ByteString -> ByteString -> Bool
rsaVerifyHash SHA1_MD5 = RSA.verify noHash
rsaVerifyHash MD5 = RSA.verify (Just H.MD5)
rsaVerifyHash SHA1 = RSA.verify (Just H.SHA1)
rsaVerifyHash SHA224 = RSA.verify (Just H.SHA224)
rsaVerifyHash SHA256 = RSA.verify (Just H.SHA256)
rsaVerifyHash SHA384 = RSA.verify (Just H.SHA384)
rsaVerifyHash SHA512 = RSA.verify (Just H.SHA512)
rsapssVerifyHash :: Hash -> RSA.PublicKey -> ByteString -> ByteString -> Bool
rsapssVerifyHash SHA256 = PSS.verify (PSS.defaultPSSParams H.SHA256)
rsapssVerifyHash SHA384 = PSS.verify (PSS.defaultPSSParams H.SHA384)
rsapssVerifyHash SHA512 = PSS.verify (PSS.defaultPSSParams H.SHA512)
rsapssVerifyHash _ = error "rsapssVerifyHash: unsupported hash"
noHash :: Maybe H.MD5
noHash = Nothing
| erikd/hs-tls | core/Network/TLS/Crypto.hs | bsd-3-clause | 12,284 | 0 | 20 | 3,261 | 3,714 | 1,929 | 1,785 | 246 | 19 |
module CheckedLang.Data where
import qualified Data.List as L
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import qualified Text.Megaparsec as Mega
type Try = Either LangError
throwError :: LangError -> Try a
throwError = Left
type GeneralEnv = M.Map String
type Environment = GeneralEnv DenotedValue
type TypeEnvironment = GeneralEnv Type
empty :: GeneralEnv a
empty = M.empty
initEnvironment :: [(String, a)] -> GeneralEnv a
initEnvironment = M.fromList
extend :: String -> a -> GeneralEnv a -> GeneralEnv a
extend = M.insert
extendRec :: String -> [String] -> Expression -> Environment -> Environment
extendRec name params body env = newEnv
where newEnv = extend name (DenoProc $ Procedure params body newEnv) env
extendRecMany :: [(String, [String], Expression)] -> Environment -> Environment
extendRecMany triples env = newEnv
where
newEnv =
extendMany
(fmap (\(name, params, body) ->
(name, DenoProc $ Procedure params body newEnv)) triples)
env
apply :: GeneralEnv a -> String -> Maybe a
apply = flip M.lookup
extendMany :: [(String, a)] -> GeneralEnv a -> GeneralEnv a
extendMany = flip (foldl func)
where
func env (var, val) = extend var val env
applyForce :: GeneralEnv a -> String -> a
applyForce env var = fromMaybe
(error $ "Var " `mappend` var `mappend` " is not in environment!")
(apply env var)
data Program = Prog Expression
deriving (Show, Eq)
data Type = TypeInt | TypeBool | TypeProc [Type] Type deriving (Eq)
instance Show Type where
show TypeInt = "int"
show TypeBool = "bool"
show (TypeProc argTypes resType) =
let argNames = fmap show argTypes
sepComma = L.intersperse ", " argNames
argStr = concat sepComma
in concat [ "(", "(", argStr, ")", " -> ", show resType, ")" ]
data Expression =
ConstExpr ExpressedValue
| VarExpr String
| LetExpr [(String, Expression)] Expression
| BinOpExpr BinOp Expression Expression
| UnaryOpExpr UnaryOp Expression
| CondExpr [(Expression, Expression)]
| ProcExpr [(String, Type)] Expression
| CallExpr Expression [Expression]
| LetRecExpr [(Type, String, [(String, Type)], Expression)] Expression
deriving(Show, Eq)
data BinOp =
Add | Sub | Mul | Div | Gt | Le | Eq
deriving(Show, Eq)
data UnaryOp = Minus | IsZero
deriving(Show, Eq)
data Procedure = Procedure [String] Expression Environment
instance Show Procedure where
show _ = "<procedure>"
data ExpressedValue = ExprNum Integer
| ExprBool Bool
| ExprProc Procedure
instance Show ExpressedValue where
show (ExprNum i) = show i
show (ExprBool b) = show b
show (ExprProc p) = show p
instance Eq ExpressedValue where
(ExprNum i1) == (ExprNum i2) = i1 == i2
(ExprBool b1) == (ExprBool b2) = b1 == b2
_ == _ = False
data DenotedValue = DenoNum Integer
| DenoBool Bool
| DenoProc Procedure
instance Show DenotedValue where
show (DenoNum i) = show i
show (DenoBool b) = show b
show (DenoProc p) = show p
instance Eq DenotedValue where
(DenoNum i1) == (DenoNum i2) = i1 == i2
(DenoBool b1) == (DenoBool b2) = b1 == b2
_ == _ = False
data LangError =
ParseError (Mega.ParseError (Mega.Token String) Mega.Dec)
| TypeCheckerError TypeError
-- | TypeMismatch String ExpressedValue
| IndexOutOfBound String
| ArgNumMismatch Integer [ExpressedValue]
-- | UnknownOperator String
-- | UnboundVar String
| RuntimeError String
| DefaultError String
deriving (Show, Eq)
data TypeError =
TypeMismatch Type Type Expression
| ParamsTypeMismatch [Type] [Type] Expression
| CallNotProcVal Type
| UnboundVar String
| UnknownOperator String
| TypeDefaultError String
deriving (Eq)
instance Show TypeError where
show (TypeMismatch t1 t2 expr) =
concat [ "Expect type: ", show t1
, ", but got: ", show t2
, ", in expression: ", show expr
]
show (ParamsTypeMismatch paramTypes argTypes proc) =
concat [ "Expect types: ", show paramTypes
, ", but got: ", show argTypes
, ", when calling: ", show proc
]
show (CallNotProcVal typ) =
"Operator of call expression should be procedure but got: "
`mappend` show typ
show (UnboundVar name) =
"Trying to check type of an unbound variable: " `mappend` name
show (UnknownOperator name) =
"Unknown operator: " `mappend` name
show (TypeDefaultError msg) = msg
type Unpacker a = ExpressedValue -> Try a
unpackNum :: Unpacker Integer
unpackNum (ExprNum n) = return n
unpackNum notNum = error $ "Can't match type number to " `mappend` show notNum
unpackBool :: Unpacker Bool
unpackBool (ExprBool b) = return b
unpackBool notBool =
error $ "Can't match type boolean to " `mappend` show notBool
unpackProc :: Unpacker Procedure
unpackProc (ExprProc proc) = Right proc
unpackProc notProc =
error $ "Can't match type procedure to " `mappend` show notProc
| li-zhirui/EoplLangs | src/CheckedLang/Data.hs | bsd-3-clause | 5,028 | 0 | 14 | 1,177 | 1,610 | 866 | 744 | 133 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
--
-- Regs.hs --- ADC peripheral registers for the STM32F4.
--
-- Copyright (C) 2015, Galois, Inc.
-- All Rights Reserved.
--
module Ivory.BSP.STM32.Peripheral.ADC.Regs where
import Ivory.BSP.STM32.Peripheral.ADC.RegTypes
import Ivory.Language
[ivory|
bitdata ADC_SR :: Bits 32 = adc_sr
{ _ :: Bits 26
, adc_sr_ovr :: Bit
, adc_sr_strt :: Bit
, adc_sr_jstrt :: Bit
, adc_sr_jeoc :: Bit
, adc_sr_eoc :: Bit
, adc_sr_awd :: Bit
}
bitdata ADC_CR1 :: Bits 32 = adc_cr1
{ _ :: Bits 5
, adc_cr1_ovrie :: Bit
, adc_cr1_res :: ADCResolution
, adc_cr1_awden :: Bit
, adc_cr1_jawden :: Bit
, _ :: Bits 6
, adc_cr1_discnum :: Bits 3
, adc_cr1_jdiscen :: Bit
, adc_cr1_discen :: Bit
, adc_cr1_jauto :: Bit
, adc_cr1_awdsgl :: Bit
, adc_cr1_scan :: Bit
, adc_cr1_jeocie :: Bit
, adc_cr1_awdie :: Bit
, adc_cr1_eocie :: Bit
, adc_cr1_awdch :: Bits 5
}
bitdata ADC_CR2 :: Bits 32 = adc_cr2
{ _ :: Bit
, adc_cr2_swstart :: Bit
, adc_cr2_exten :: Bits 2
, adc_cr2_extsel :: Bits 4
, _ :: Bit
, adc_cr2_jswstart :: Bit
, adc_cr2_jexten :: Bits 2
, adc_cr2_jextsel :: Bits 4
, _ :: Bits 4
, adc_cr2_align :: Bit
, adc_cr2_eocs :: Bit
, adc_cr2_dds :: Bit
, adc_cr2_dma :: Bit
, _ :: Bits 6
, adc_cr2_cont :: Bit
, adc_cr2_adon :: Bit
}
bitdata ADC_SQR1 :: Bits 32 = adc_sqr1
{ _ :: Bits 8
, adc_sqr1_l :: Bits 4
, adc_sqr1_sq16 :: Bits 5
, adc_sqr1_sq15 :: Bits 5
, adc_sqr1_sq14 :: Bits 5
, adc_sqr1_sq13 :: Bits 5
}
bitdata ADC_SQR2 :: Bits 32 = adc_sqr2
{ _ :: Bits 2
, adc_sqr2_sq12 :: Bits 5
, adc_sqr2_sq11 :: Bits 5
, adc_sqr2_sq10 :: Bits 5
, adc_sqr2_sq9 :: Bits 5
, adc_sqr2_sq8 :: Bits 5
, adc_sqr2_sq7 :: Bits 5
}
bitdata ADC_SQR3 :: Bits 32 = adc_sqr3
{ _ :: Bits 2
, adc_sqr3_sq6 :: Bits 5
, adc_sqr3_sq5 :: Bits 5
, adc_sqr3_sq4 :: Bits 5
, adc_sqr3_sq3 :: Bits 5
, adc_sqr3_sq2 :: Bits 5
, adc_sqr3_sq1 :: Bits 5
}
bitdata ADC_DR :: Bits 32 = adc_dr
{ _ :: Bits 16
, adc_dr_data :: Bits 16
}
|]
| GaloisInc/ivory-tower-stm32 | ivory-bsp-stm32/src/Ivory/BSP/STM32/Peripheral/ADC/Regs.hs | bsd-3-clause | 2,181 | 0 | 4 | 539 | 41 | 33 | 8 | 8 | 0 |
module ScrabbleScoreKata.Day1Spec (spec) where
import Test.Hspec
import ScrabbleScoreKata.Day1 (score)
spec :: Spec
spec = do
it "is zero when empty input" $ do
score "" `shouldBe` 0
it "lowercase letter" $ do
score "a" `shouldBe` 1
it "uppercase letter" $ do
score "A" `shouldBe` 1
it "valuable letter" $ do
score "f" `shouldBe` 4
it "short word" $ do
score "at" `shouldBe` 2
it "short, valuable word" $ do
score "zoo" `shouldBe` 12
it "medium" $ do
score "street" `shouldBe` 6
it "medium, valuable word" $ do
score "quirky" `shouldBe` 22
it "long, mixed-case word" $ do
score "OxyphenButazone" `shouldBe` 41
it "english-like word" $ do
score "pinata" `shouldBe` 8
it "non-english letter is not scored" $ do
score "piñata" `shouldBe` 7
| Alex-Diez/haskell-tdd-kata | old-katas/test/ScrabbleScoreKata/Day1Spec.hs | bsd-3-clause | 986 | 0 | 11 | 370 | 278 | 132 | 146 | 27 | 1 |
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
--
-- Removing comments from a string. This is a very basic example that doesn't
-- handle nested comments, or quoted comments.
module Main (
main
) where
import Data.Bool
import qualified "text" Data.Text as T
import qualified "text" Data.Text.IO as T
import qualified "foldl" Control.Foldl as L
import "foldl-transduce" Control.Foldl.Transduce (transduce,ignore,groups,Moore(..),unfold,reify)
import "foldl-transduce" Control.Foldl.Transduce.Text (sections)
textWithComments :: [T.Text]
textWithComments = [
"foo"
, "{- hi"
, "there -}"
, "bar"
, "{- another"
, "comment -}"
, "baz"
]
removeComments :: L.Fold T.Text T.Text
removeComments =
groups sectionSplitter ignoreAlternating L.mconcat
where
sectionSplitter = sections (cycle ["{-","-}"])
ignoreAlternating = Moore $
unfold
(\ts -> (head ts, \_ -> tail ts))
(cycle [reify id,reify (transduce ignore)])
main :: IO ()
main = do
T.putStrLn (L.fold removeComments textWithComments)
| danidiaz/foldl-transduce | examples/Comments.hs | bsd-3-clause | 1,110 | 0 | 14 | 238 | 276 | 166 | 110 | 30 | 1 |
module Exercises.FindMissingNumbersSpec (main, spec) where
import Test.Hspec
import Data.List (delete)
import Test.QuickCheck
import Exercises.FindMissingNumbers
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "findMissingPair" $ do
context "when input sequence contains only one or no missed numbers" $
it "finds nothing" $ do
findMissingPair [1..10] `shouldBe` Nothing
findMissingPair [1,2,3,5,6] `shouldBe` Nothing
it "finds two numbers that are missed in sequence from 1 to 1000000" $
property $
\(NonNegative a) (NonNegative b) -> (0 < a && a < b && b < 1000000)
==>
findMissingPair (delete a . delete b $ [1..1000000])
==
Just (a, b)
| WarKnife/exercises | test/Exercises/FindMissingNumbersSpec.hs | bsd-3-clause | 746 | 0 | 17 | 194 | 233 | 123 | 110 | 21 | 1 |
module Text.XML.Monad
(
module Text.XML.Monad.Core
, module Text.XML.Monad.Input
, module Text.XML.Monad.Proc
, module Text.XML.Monad.Output
, module Text.XML.Monad.Name
, module Text.XML.Monad.Error
)
where
import Text.XML.Monad.Core
import Text.XML.Monad.Input
import Text.XML.Monad.Proc
import Text.XML.Monad.Output
import Text.XML.Monad.Name
import Text.XML.Monad.Error
| aristidb/xml-monad | Text/XML/Monad.hs | bsd-3-clause | 379 | 0 | 5 | 39 | 99 | 72 | 27 | 14 | 0 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings, TupleSections, ScopedTypeVariables #-}
-- | Comment handling.
module HIndent.Comments where
import Control.Applicative ((<|>))
import Control.Arrow (first, second)
import Control.Monad.State.Strict
import Data.Data
import qualified Data.Map.Strict as M
import Data.Traversable
import HIndent.Types
import Language.Haskell.Exts.Annotated hiding (Style,prettyPrint,Pretty,style,parse)
-- Order by start of span, larger spans before smaller spans.
newtype OrderByStart =
OrderByStart SrcSpan
deriving (Eq)
instance Ord OrderByStart where
compare (OrderByStart l) (OrderByStart r) =
compare (srcSpanStartLine l)
(srcSpanStartLine r) `mappend`
compare (srcSpanStartColumn l)
(srcSpanStartColumn r) `mappend`
compare (srcSpanEndLine r)
(srcSpanEndLine l) `mappend`
compare (srcSpanEndColumn r)
(srcSpanEndColumn l)
-- Order by end of span, smaller spans before larger spans.
newtype OrderByEnd =
OrderByEnd SrcSpan
deriving (Eq)
instance Ord OrderByEnd where
compare (OrderByEnd l) (OrderByEnd r) =
compare (srcSpanEndLine l)
(srcSpanEndLine r) `mappend`
compare (srcSpanEndColumn l)
(srcSpanEndColumn r) `mappend`
compare (srcSpanStartLine r)
(srcSpanStartLine l) `mappend`
compare (srcSpanStartColumn r)
(srcSpanStartColumn l)
-- | Annotate the AST with comments.
annotateComments :: forall ast. (Data (ast NodeInfo),Traversable ast,Annotated ast,Show (ast NodeInfo))
=> ast SrcSpanInfo -> [Comment] -> ([ComInfo],ast NodeInfo)
annotateComments src comments =
evalState (do _ <- traverse assignComment comments
cis <- gets fst
ast <- traverse transferComments src
return (cis,ast))
([],nodeinfos)
where
nodeinfos :: M.Map SrcSpanInfo NodeInfo
nodeinfos = foldr (\ssi -> M.insert ssi (NodeInfo ssi [])) M.empty src
-- Assign a single comment to the right AST node
assignComment :: Comment -> State ([ComInfo],M.Map SrcSpanInfo NodeInfo) ()
assignComment comment@(Comment _ cspan _) =
-- Find the biggest AST node directly in front of this comment.
case nodeBefore comment of
-- Comments before any AST node are handled separately.
Nothing -> modify $ first $ (:) (ComInfo comment Nothing)
Just ssi ->
-- Comments on the same line as the AST node belong to this node.
if sameline (srcInfoSpan ssi) cspan
then insertComment After ssi
else do nodeinfo <- gets ((M.! ssi) . snd)
case nodeinfo of
-- We've already collected comments for this
-- node and this comment is a continuation.
NodeInfo _ ((ComInfo c' _):_)
| aligned c' comment -> insertComment After ssi
-- The comment does not belong to this node.
-- If there is a node following this comment,
-- assign it to that node, else keep it here,
-- anyway.
_ ->
case nodeAfter comment of
Nothing -> insertComment After ssi
Just ssi' -> insertComment Before ssi'
where
sameline :: SrcSpan -> SrcSpan -> Bool
sameline before after = srcSpanEndLine before == srcSpanStartLine after
aligned :: Comment -> Comment -> Bool
aligned (Comment _ before _) (Comment _ after _) =
srcSpanEndLine before == srcSpanStartLine after - 1 &&
srcSpanStartColumn before == srcSpanStartColumn after
insertComment :: ComInfoLocation -> SrcSpanInfo -> State ([ComInfo],M.Map SrcSpanInfo NodeInfo) ()
insertComment l ssi = modify $ second $ M.adjust (addComment (ComInfo comment (Just l))) ssi
addComment :: ComInfo -> NodeInfo -> NodeInfo
addComment x (NodeInfo s xs) = NodeInfo s (x : xs)
-- Transfer collected comments into the AST.
transferComments :: SrcSpanInfo -> State ([ComInfo],M.Map SrcSpanInfo NodeInfo) NodeInfo
transferComments ssi =
do ni <- gets ((M.! ssi) . snd)
-- Sometimes, there are multiple AST nodes with the same
-- SrcSpan. Make sure we assign comments to only one of
-- them.
modify $ second $ M.adjust (\(NodeInfo s _) -> NodeInfo s []) ssi
return ni { nodeInfoComments = reverse $ nodeInfoComments ni }
nodeBefore (Comment _ ss _) = fmap snd $ (OrderByEnd ss) `M.lookupLT` spansByEnd
nodeAfter (Comment _ ss _) = fmap snd $ (OrderByStart ss) `M.lookupGT` spansByStart
spansByStart = foldr (\ssi -> M.insert (OrderByStart $ srcInfoSpan ssi) ssi) M.empty src
spansByEnd = foldr (\ssi -> M.insert (OrderByEnd $ srcInfoSpan ssi) ssi) M.empty src
| lunaris/hindent | src/HIndent/Comments.hs | bsd-3-clause | 4,969 | 0 | 20 | 1,418 | 1,308 | 683 | 625 | 81 | 5 |
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Copyright : (c) Andreas Reuleaux 2015
-- License : BSD2
-- Maintainer: Andreas Reuleaux <rx@a-rx.info>
-- Stability : experimental
-- Portability: non-portable
--
-- This module provides Pire's syntax,
-- ie. Pire's flavour of Pi-forall syntax: smart constructors, and destructors
module Pire.Syntax.Smart where
import Bound
import Bound.Name
import Data.List
import Pire.Syntax.Expr
import Pire.Syntax.Ws
import Pire.Syntax.Token
import Pire.Syntax.Binder
-- smart constructors
-- |
-- >>> lam "x" $ V "x"
-- Lam "x" (Scope (V (B ())))
-- >>> lam "x" $ V "f" :@ V "x"
-- Lam "x" (Scope (V (F (V "f")) :@ V (B ())))
-- >>> lam "y" $ lam "x" $ V "x" :@ V "y"
-- Lam "y" (Scope (Lam "x" (Scope (V (B ()) :@ V (F (V (B ())))))))
-- >>> lam "y" $ lam "x" $ V "x" :@ (V "y" :@ V "z")
-- Lam "y" (Scope (Lam "x" (Scope (V (B ()) :@ (V (F (V (B ()))) :@ V (F (V (F (V "z")))))))))
lam v b = Lam v (abstract1 v b)
-- doctests missing
elam v e = ErasedLam v (abstract1 v e)
-- |
-- >>> lam_ "x" $ (Ws_ (V "b") $ Ws "{-foo-}")
-- Lam_ (LamTok "\\" NoWs) (Binder "x") (Dot "." NoWs) (Scope (Ws_ (V (F (V "b"))) (Ws "{-foo-}")))
lam_ v e = Lam_ (LamTok "\\" NoWs) (Binder v) (Dot "." $ NoWs) (abstract1 v e)
-- |
-- >>> lam' "x" $ V "x"
-- Lam' "x" (Scope (V (B (Name "x" ()))))
-- >>> lam' "x" $ V "f" :@ V "x"
-- Lam' "x" (Scope (V (F (V "f")) :@ V (B (Name "x" ()))))
-- >>> lam' "y" $ lam' "x" $ V "x" :@ V "y"
-- Lam' "y" (Scope (Lam' "x" (Scope (V (B (Name "x" ())) :@ V (F (V (B (Name "y" ()))))))))
lam' v b = Lam' v (abstract1Name v b)
-- |
-- >>> lams ["x", "y"] $ V "z" :@ V "x"
-- Lams ["x","y"] (Scope (V (F (V "z")) :@ V (B 0)))
-- >>> lams ["x", "y"] $ lams ["a", "b"] $ V "x" :@ V "a"
-- Lams ["x","y"] (Scope (Lams ["a","b"] (Scope (V (F (V (B 0))) :@ V (B 0)))))
lams ls b = Lams ls $ abstract (`elemIndex` ls) b
-- |
-- >>> lams_ ["x", "y"] $ V "z" :@ V "x"
-- Lams_ (LamTok "\\" NoWs) [Binder "x",Binder "y"] (Dot "." NoWs) (Scope (V (F (V "z")) :@ V (B 0)))
-- >>> lams_ ["x", "y"] $ (Ws_ (V "b") $ Ws "{-foo-}")
-- Lams_ (LamTok "\\" NoWs) [Binder "x",Binder "y"] (Dot "." NoWs) (Scope (Ws_ (V (F (V "b"))) (Ws "{-foo-}")))
lams_ vs b = Lams_ (LamTok "\\" $ NoWs) [Binder v | v <- vs] (Dot "." NoWs) $ abstract (`elemIndex` vs) b
-- |
-- >>> lams' ["x", "y"] $ V "z" :@ V "x"
-- Lams' ["x","y"] (Scope (V (F (V "z")) :@ V (B (Name "x" 0))))
lams' ls b = Lams' ls $ abstractName (`elemIndex` ls) b
-- -- smart destructors
scope (Lam _ s) = s
scope (Lam_ _ _ _ s) = s
scope (Pi _ _ s) = s
-- plural (Int index) version of the above
scopepl (Lams _ s) = s
scopepl (Lams_ _ _ _ s) = s
scopepl (LamPAs _ s) = s
scopepl (LamPAs_ _ _ _ s) = s
-- scopes w/ Name's
scope' (Lam' _ s) = s
scopepl' (Lams' _ s) = s
| reuleaux/pire | src/Pire/Syntax/Smart.hs | bsd-3-clause | 2,858 | 0 | 9 | 697 | 489 | 276 | 213 | 25 | 1 |
-- Adapted from Agda sources.
{-# LANGUAGE UnicodeSyntax #-}
module Main ( main ) where
import Control.Monad ( liftM, when )
import Data.Char as Char ( isSpace )
import Data.Text ( Text )
import qualified Data.Text as Text ( dropWhileEnd, lines, null, unlines )
import qualified Data.Text.IO as Text ( hGetContents, hPutStr ) -- Strict IO.
import System.Directory ( getCurrentDirectory )
import System.Environment ( getArgs )
import System.Exit ( exitFailure )
import System.FilePath.Find
( (||?)
, (==?)
, extension
, fileName
, find
, FindClause
, RecursionPredicate
)
import System.IO
( hPutStr
, hPutStrLn
, IOMode(ReadMode, WriteMode)
, stderr
, withFile
)
------------------------------------------------------------------------------
-- Configuration parameters.
extensions ∷ [String]
extensions =
[ ".agda"
, ".cabal"
, ".el"
, ".java"
, ".hs"
, ".hs-boot"
, ".md"
, ".smt"
, ".smt2"
, ".tex"
, ".thy"
-- , ".test"
, ".tptp"
, ".txt"
, ".v"
, ".x"
, ".y"
]
-- ASR (16 June 2014). In test/succeed/LineEndings/ we test that Agda
-- can handle various kinds of whitespace (pointed out by Nils), so we
-- exclude this directory.
excludedDirs :: [String]
excludedDirs =
["_darcs", ".git", "dist", "LineEndings", "MAlonzo", "std-lib"]
-- Auxiliary functions.
filesFilter :: FindClause Bool
filesFilter = foldr1 (||?) $ map (extension ==?) extensions
-- ASR (12 June 2014). Adapted from the examples of fileManip 0.3.6.2.
--
-- A recursion control predicate that will avoid recursing into the
-- @excludeDirs@ directories list.
nonRCS :: RecursionPredicate
nonRCS = (`notElem` excludedDirs) `liftM` fileName
-- Modes.
data Mode
= Fix -- ^ Fix whitespace issues.
| Check -- ^ Check if there are any whitespace issues.
deriving Eq
main ∷ IO ()
main = do
args ← getArgs
mode ← case args of
[] → return Fix
["--check"] → return Check
_ → hPutStr stderr usage >> exitFailure
dir <- getCurrentDirectory
changes <- mapM (fix mode) =<< find nonRCS filesFilter dir
when (or changes && mode == Check) exitFailure
-- | Usage info.
usage ∷ String
usage = unlines
[ "fix-agda-whitespace: Fixes whitespace issues."
, ""
, "Usage: fix-agda-whitespace [--check]"
, ""
, "This program should be run in the base directory."
, ""
, "By default the program does the following for every"
, list extensions ++ " file under the current directory:"
, "* Removes trailing whitespace."
, "* Removes trailing lines containing nothing but whitespace."
, "* Ensures that the file ends in a newline character."
, ""
, "With the --check flag the program does not change any files,"
, "it just checks if any files would have been changed. In this"
, "case it returns with a non-zero exit code."
, ""
, "Background: Agda was reported to fail to compile on Windows"
, "because a file did not end with a newline character (Agda"
, "uses -Werror)."
]
where
list ∷ [String] → String
list [x] = x
list [x, y] = x ++ " and " ++ y
list (x : xs) = x ++ ", " ++ list xs
list _ = error "Impossible list"
-- | Fix a file. Only performs changes if the mode is 'Fix'. Returns
-- 'True' iff any changes would have been performed in the 'Fix' mode.
fix ∷ Mode → FilePath → IO Bool
fix mode f = do
new ← withFile f ReadMode $ \h → do
s ← Text.hGetContents h
let s' = transform s
return $ if s' == s then Nothing else Just s'
case new of
Nothing → return False
Just s → do
hPutStrLn stderr $
"Whitespace violation " ++
(if mode == Fix then "fixed" else "detected") ++
" in " ++ f ++ "."
when (mode == Fix) $
withFile f WriteMode $ \h → Text.hPutStr h s
return True
-- | Transforms the contents of a file.
transform ∷ Text → Text
transform =
Text.unlines .
removeFinalEmptyLinesExceptOne .
map removeTrailingWhitespace .
Text.lines
where
removeFinalEmptyLinesExceptOne ∷ [Text] → [Text]
removeFinalEmptyLinesExceptOne = reverse . dropWhile1 Text.null . reverse
removeTrailingWhitespace ∷ Text → Text
removeTrailingWhitespace = Text.dropWhileEnd Char.isSpace
-- | 'dropWhile' except keep the first of the dropped elements
dropWhile1 :: (a → Bool) → [a] → [a]
dropWhile1 _ [] = []
dropWhile1 p (x : xs)
| p x = x : dropWhile p xs
| otherwise = x : xs
| jonaprieto/online-atps | src/fix-whitespace/FixWhitespace.hs | mit | 4,564 | 0 | 18 | 1,117 | 1,022 | 575 | 447 | 120 | 4 |
{-# 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.Route53Domains.DisableDomainTransferLock
-- 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)
--
-- This operation removes the transfer lock on the domain (specifically the
-- 'clientTransferProhibited' status) to allow domain transfers. We
-- recommend you refrain from performing this action unless you intend to
-- transfer the domain to a different registrar. Successful submission
-- returns an operation ID that you can use to track the progress and
-- completion of the action. If the request is not completed successfully,
-- the domain registrant will be notified by email.
--
-- /See:/ <http://docs.aws.amazon.com/Route53/latest/APIReference/api-DisableDomainTransferLock.html AWS API Reference> for DisableDomainTransferLock.
module Network.AWS.Route53Domains.DisableDomainTransferLock
(
-- * Creating a Request
disableDomainTransferLock
, DisableDomainTransferLock
-- * Request Lenses
, ddtlDomainName
-- * Destructuring the Response
, disableDomainTransferLockResponse
, DisableDomainTransferLockResponse
-- * Response Lenses
, ddtlrsResponseStatus
, ddtlrsOperationId
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.Route53Domains.Types
import Network.AWS.Route53Domains.Types.Product
-- | The DisableDomainTransferLock request includes the following element.
--
-- /See:/ 'disableDomainTransferLock' smart constructor.
newtype DisableDomainTransferLock = DisableDomainTransferLock'
{ _ddtlDomainName :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DisableDomainTransferLock' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ddtlDomainName'
disableDomainTransferLock
:: Text -- ^ 'ddtlDomainName'
-> DisableDomainTransferLock
disableDomainTransferLock pDomainName_ =
DisableDomainTransferLock'
{ _ddtlDomainName = pDomainName_
}
-- | The name of a domain.
--
-- Type: String
--
-- Default: None
--
-- Constraints: The domain name can contain only the letters a through z,
-- the numbers 0 through 9, and hyphen (-). Internationalized Domain Names
-- are not supported.
--
-- Required: Yes
ddtlDomainName :: Lens' DisableDomainTransferLock Text
ddtlDomainName = lens _ddtlDomainName (\ s a -> s{_ddtlDomainName = a});
instance AWSRequest DisableDomainTransferLock where
type Rs DisableDomainTransferLock =
DisableDomainTransferLockResponse
request = postJSON route53Domains
response
= receiveJSON
(\ s h x ->
DisableDomainTransferLockResponse' <$>
(pure (fromEnum s)) <*> (x .:> "OperationId"))
instance ToHeaders DisableDomainTransferLock where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("Route53Domains_v20140515.DisableDomainTransferLock"
:: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON DisableDomainTransferLock where
toJSON DisableDomainTransferLock'{..}
= object
(catMaybes [Just ("DomainName" .= _ddtlDomainName)])
instance ToPath DisableDomainTransferLock where
toPath = const "/"
instance ToQuery DisableDomainTransferLock where
toQuery = const mempty
-- | The DisableDomainTransferLock response includes the following element.
--
-- /See:/ 'disableDomainTransferLockResponse' smart constructor.
data DisableDomainTransferLockResponse = DisableDomainTransferLockResponse'
{ _ddtlrsResponseStatus :: !Int
, _ddtlrsOperationId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DisableDomainTransferLockResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ddtlrsResponseStatus'
--
-- * 'ddtlrsOperationId'
disableDomainTransferLockResponse
:: Int -- ^ 'ddtlrsResponseStatus'
-> Text -- ^ 'ddtlrsOperationId'
-> DisableDomainTransferLockResponse
disableDomainTransferLockResponse pResponseStatus_ pOperationId_ =
DisableDomainTransferLockResponse'
{ _ddtlrsResponseStatus = pResponseStatus_
, _ddtlrsOperationId = pOperationId_
}
-- | The response status code.
ddtlrsResponseStatus :: Lens' DisableDomainTransferLockResponse Int
ddtlrsResponseStatus = lens _ddtlrsResponseStatus (\ s a -> s{_ddtlrsResponseStatus = a});
-- | Identifier for tracking the progress of the request. To use this ID to
-- query the operation status, use GetOperationDetail.
--
-- Type: String
--
-- Default: None
--
-- Constraints: Maximum 255 characters.
ddtlrsOperationId :: Lens' DisableDomainTransferLockResponse Text
ddtlrsOperationId = lens _ddtlrsOperationId (\ s a -> s{_ddtlrsOperationId = a});
| fmapfmapfmap/amazonka | amazonka-route53-domains/gen/Network/AWS/Route53Domains/DisableDomainTransferLock.hs | mpl-2.0 | 5,612 | 0 | 14 | 1,098 | 600 | 369 | 231 | 79 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-| Helpers for creating various kinds of 'Field's.
They aren't directly needed for the Template Haskell code in Ganeti.THH,
so better keep them in a separate module.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.THH.Field
( specialNumericalField
, timeAsDoubleField
, timeStampFields
, uuidFields
, serialFields
, TagSet(..)
, emptyTagSet
, tagsFields
, fileModeAsIntField
, processIdField
) where
import Control.Monad
import qualified Data.ByteString as BS
import qualified Data.Set as Set
import Language.Haskell.TH
import qualified Text.JSON as JSON
import System.Posix.Types (FileMode, ProcessID)
import System.Time (ClockTime(..))
import Ganeti.JSON (TimeAsDoubleJSON(..))
import Ganeti.THH
-- * Internal functions
-- | Wrapper around a special parse function, suitable as field-parsing
-- function.
numericalReadFn :: JSON.JSON a => (String -> JSON.Result a)
-> [(String, JSON.JSValue)] -> JSON.JSValue -> JSON.Result a
numericalReadFn _ _ v@(JSON.JSRational _ _) = JSON.readJSON v
numericalReadFn f _ (JSON.JSString x) = f $ JSON.fromJSString x
numericalReadFn _ _ _ = JSON.Error "A numerical field has to be a number or\
\ a string."
-- | Sets the read function to also accept string parsable by the given
-- function.
specialNumericalField :: Name -> Field -> Field
specialNumericalField f field =
field { fieldRead = Just (appE (varE 'numericalReadFn) (varE f)) }
-- | Creates a new mandatory field that reads time as the (floating point)
-- number of seconds since the standard UNIX epoch, and represents it in
-- Haskell as 'ClockTime'.
timeAsDoubleField :: String -> Field
timeAsDoubleField fname =
(simpleField fname [t| ClockTime |])
{ fieldRead = Just $ [| \_ -> liftM unTimeAsDoubleJSON . JSON.readJSON |]
, fieldShow = Just $ [| \c -> (JSON.showJSON $ TimeAsDoubleJSON c, []) |]
}
-- | A helper function for creating fields whose Haskell representation is
-- 'Integral' and which are serialized as numbers.
integralField :: Q Type -> String -> Field
integralField typq fname =
let (~->) = appT . appT arrowT -- constructs an arrow type
(~::) = sigE . varE -- (f ~:: t) constructs (f :: t)
in (simpleField fname typq)
{ fieldRead = Just $
[| \_ -> liftM $('fromInteger ~:: (conT ''Integer ~-> typq))
. JSON.readJSON |]
, fieldShow = Just $
[| \c -> (JSON.showJSON
. $('toInteger ~:: (typq ~-> conT ''Integer))
$ c, []) |]
}
-- * External functions and data types
-- | Timestamp fields description.
timeStampFields :: [Field]
timeStampFields = map (defaultField [| TOD 0 0 |] . timeAsDoubleField)
["ctime", "mtime"]
-- | Serial number fields description.
serialFields :: [Field]
serialFields =
[ presentInForthcoming . renameField "Serial"
$ simpleField "serial_no" [t| Int |] ]
-- | UUID fields description.
uuidFields :: [Field]
uuidFields = [ presentInForthcoming $ simpleField "uuid" [t| BS.ByteString |] ]
-- | Tag set type.
newtype TagSet = TagSet { fromTagSet :: Set.Set String }
deriving (Show, Eq)
instance JSON.JSON TagSet where
readJSON = liftM TagSet . JSON.readJSON
showJSON = JSON.showJSON . fromTagSet
-- | The empty tag set.
emptyTagSet :: TagSet
emptyTagSet = TagSet Set.empty
-- | Tag field description.
tagsFields :: [Field]
tagsFields = [ defaultField [| emptyTagSet |] $
simpleField "tags" [t| TagSet |] ]
-- ** Fields related to POSIX data types
-- | Creates a new mandatory field that reads a file mode in the standard
-- POSIX file mode representation. The Haskell type of the field is 'FileMode'.
fileModeAsIntField :: String -> Field
fileModeAsIntField = integralField [t| FileMode |]
-- | Creates a new mandatory field that contains a POSIX process ID.
processIdField :: String -> Field
processIdField = integralField [t| ProcessID |]
| onponomarev/ganeti | src/Ganeti/THH/Field.hs | bsd-2-clause | 5,269 | 0 | 11 | 1,067 | 746 | 446 | 300 | 69 | 1 |
------------------------------------------------------------------------------
-- |
-- Module: Database.PostgreSQL.Simple.Time
-- Copyright: (c) 2012 Leon P Smith
-- License: BSD3
-- Maintainer: Leon P Smith <leon@melding-monads.com>
-- Stability: experimental
--
-- Time types that supports positive and negative infinity. Also includes
-- new time parsers and printers with better performance than GHC's time
-- package.
--
-- The parsers only understand the specific variant of ISO 8601 that
-- PostgreSQL emits, and the printers attempt to duplicate this syntax.
-- Thus the @datestyle@ parameter for the connection must be set to @ISO@.
--
-- These parsers and printers likely have problems and shortcomings. Some
-- that I know of:
--
-- 1 @TimestampTZ@s before a timezone-dependent point in time cannot be
-- parsed, because the parsers can only handle timezone offsets of a
-- integer number of minutes. However, PostgreSQL will include seconds
-- in the offset, depending on the historical time standards for the city
-- identifying the time zone.
--
-- This boundary point often marks an event of some interest. In the US
-- for example, @timestamptz@s before @1883-Nov-18 12:00:00@ local time
-- cannot be parsed. This is the moment Standard Railway Time went live.
-- Concretely, PostgreSQL will emit @1883-11-18 12:03:57-04:56:02@
-- instead of @1883-11-18 11:59:59-05@ when the @timezone@ parameter
-- for the connection is set to @America/New_York@.
--
-- 2. Dates and times surrounding @1582-Feb-24@, the date the Gregorian
-- Calendar was introduced, should be investigated for conversion errors.
--
-- 3. Points in time Before Christ are not also not supported. For example,
-- PostgreSQL will emit @0045-01-01 BC@ for a value of a @date@ type.
-- This is the year that the Julian Calendar was adopted.
--
-- However, it should be noted that the old parsers also had issues 1 and 3.
-- Also, the new parsers now correctly handle time zones that include minutes
-- in their offset. Most notably, this includes all of India and parts of
-- Canada and Australia.
--
-- PostgreSQL uses the zoneinfo database for its time zone information.
-- You can read more about PostgreSQL's date and time types at
-- <http://www.postgresql.org/docs/9.1/static/datatype-datetime.html>,
-- and zoneinfo at <http://en.wikipedia.org/wiki/Tz_database>.
--
------------------------------------------------------------------------------
module Database.PostgreSQL.Simple.Time
( Unbounded(..)
, Date
, UTCTimestamp
, ZonedTimestamp
, LocalTimestamp
, parseDay
, parseUTCTime
, parseZonedTime
, parseLocalTime
, parseTimeOfDay
, parseDate
, parseUTCTimestamp
, parseZonedTimestamp
, parseLocalTimestamp
, dayToBuilder
, utcTimeToBuilder
, zonedTimeToBuilder
, localTimeToBuilder
, timeOfDayToBuilder
, timeZoneToBuilder
, dateToBuilder
, utcTimestampToBuilder
, zonedTimestampToBuilder
, localTimestampToBuilder
, unboundedToBuilder
, nominalDiffTimeToBuilder
) where
import Database.PostgreSQL.Simple.Time.Implementation
| timmytofu/postgresql-simple | src/Database/PostgreSQL/Simple/Time.hs | bsd-3-clause | 3,219 | 0 | 5 | 622 | 150 | 118 | 32 | 28 | 0 |
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Word
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Unsigned integer types.
--
-----------------------------------------------------------------------------
module Data.Word
(
-- * Unsigned integral types
Word,
Word8, Word16, Word32, Word64,
-- * Notes
-- $notes
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Word
#endif
#ifdef __HUGS__
import Hugs.Word
#endif
#ifdef __NHC__
import NHC.FFI (Word8, Word16, Word32, Word64)
import NHC.SizedTypes (Word8, Word16, Word32, Word64) -- instances of Bits
type Word = Word32
#endif
{- $notes
* All arithmetic is performed modulo 2^n, where n is the number of
bits in the type. One non-obvious consequence of this is that 'Prelude.negate'
should /not/ raise an error on negative arguments.
* For coercing between any two integer types, use
'Prelude.fromIntegral', which is specialized for all the
common cases so should be fast enough. Coercing word types to and
from integer types preserves representation, not sign.
* It would be very natural to add a type @Natural@ providing an unbounded
size unsigned integer, just as 'Prelude.Integer' provides unbounded
size signed integers. We do not do that yet since there is no demand
for it.
* The rules that hold for 'Prelude.Enum' instances over a bounded type
such as 'Prelude.Int' (see the section of the Haskell report dealing
with arithmetic sequences) also hold for the 'Prelude.Enum' instances
over the various 'Word' types defined here.
* Right and left shifts by amounts greater than or equal to the width
of the type result in a zero result. This is contrary to the
behaviour in C, which is undefined; a common interpretation is to
truncate the shift count to the width of the type, for example @1 \<\<
32 == 1@ in some C implementations.
-}
| alekar/hugs | packages/base/Data/Word.hs | bsd-3-clause | 2,127 | 6 | 5 | 389 | 109 | 78 | 31 | 5 | 0 |
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-}
-- | Management for the installed package store.
--
module Distribution.Client.Store (
-- * The store layout
StoreDirLayout(..),
defaultStoreDirLayout,
-- * Reading store entries
getStoreEntries,
doesStoreEntryExist,
-- * Creating store entries
newStoreEntry,
NewStoreEntryOutcome(..),
-- * Concurrency strategy
-- $concurrency
) where
import Prelude ()
import Distribution.Client.Compat.Prelude
import Distribution.Client.Compat.FileLock
import Distribution.Client.DistDirLayout
import Distribution.Client.RebuildMonad
import Distribution.Package (UnitId, mkUnitId)
import Distribution.Compiler (CompilerId)
import Distribution.Simple.Utils
( withTempDirectory, debug, info )
import Distribution.Verbosity
import Distribution.Text
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Exception
import System.FilePath
import System.Directory
import System.IO
-- $concurrency
--
-- We access and update the store concurrently. Our strategy to do that safely
-- is as follows.
--
-- The store entries once created are immutable. This alone simplifies matters
-- considerably.
--
-- Additionally, the way 'UnitId' hashes are constructed means that if a store
-- entry exists already then we can assume its content is ok to reuse, rather
-- than having to re-recreate. This is the nix-style input hashing concept.
--
-- A consequence of this is that with a little care it is /safe/ to race
-- updates against each other. Consider two independent concurrent builds that
-- both want to build a particular 'UnitId', where that entry does not yet
-- exist in the store. It is safe for both to build and try to install this
-- entry into the store provided that:
--
-- * only one succeeds
-- * the looser discovers that they lost, they abandon their own build and
-- re-use the store entry installed by the winner.
--
-- Note that because builds are not reproducible in general (nor even
-- necessarily ABI compatible) then it is essential that the loser abandon
-- their build and use the one installed by the winner, so that subsequent
-- packages are built against the exact package from the store rather than some
-- morally equivalent package that may not be ABI compatible.
--
-- Our overriding goal is that store reads be simple, cheap and not require
-- locking. We will derive our write-side protocol to make this possible.
--
-- The read-side protocol is simply:
--
-- * check for the existence of a directory entry named after the 'UnitId' in
-- question. That is, if the dir entry @$root/foo-1.0-fe56a...@ exists then
-- the store entry can be assumed to be complete and immutable.
--
-- Given our read-side protocol, the final step on the write side must be to
-- atomically rename a fully-formed store entry directory into its final
-- location. While this will indeed be the final step, the preparatory steps
-- are more complicated. The tricky aspect is that the store also contains a
-- number of shared package databases (one per compiler version). Our read
-- strategy means that by the time we install the store dir entry the package
-- db must already have been updated. We cannot do the package db update
-- as part of atomically renaming the store entry directory however. Furthermore
-- it is not safe to allow either package db update because the db entry
-- contains the ABI hash and this is not guaranteed to be deterministic. So we
-- must register the new package prior to the atomic dir rename. Since this
-- combination of steps are not atomic then we need locking.
--
-- The write-side protocol is:
--
-- * Create a unique temp dir and write all store entry files into it.
--
-- * Take a lock named after the 'UnitId' in question.
--
-- * Once holding the lock, check again for the existence of the final store
-- entry directory. If the entry exists then the process lost the race and it
-- must abandon, unlock and re-use the existing store entry. If the entry
-- does not exist then the process won the race and it can proceed.
--
-- * Register the package into the package db. Note that the files are not in
-- their final location at this stage so registration file checks may need
-- to be disabled.
--
-- * Atomically rename the temp dir to the final store entry location.
--
-- * Release the previously-acquired lock.
--
-- Obviously this means it is possible to fail after registering but before
-- installing the store entry, leaving a dangling package db entry. This is not
-- much of a problem because this entry does not determine package existence
-- for cabal. It does mean however that the package db update should be insert
-- or replace, i.e. not failing if the db entry already exists.
-- | Check if a particular 'UnitId' exists in the store.
--
doesStoreEntryExist :: StoreDirLayout -> CompilerId -> UnitId -> IO Bool
doesStoreEntryExist StoreDirLayout{storePackageDirectory} compid unitid =
doesDirectoryExist (storePackageDirectory compid unitid)
-- | Return the 'UnitId's of all packages\/components already installed in the
-- store.
--
getStoreEntries :: StoreDirLayout -> CompilerId -> Rebuild (Set UnitId)
getStoreEntries StoreDirLayout{storeDirectory} compid = do
paths <- getDirectoryContentsMonitored (storeDirectory compid)
return $! mkEntries paths
where
mkEntries = Set.delete (mkUnitId "package.db")
. Set.delete (mkUnitId "incoming")
. Set.fromList
. map mkUnitId
. filter valid
valid ('.':_) = False
valid _ = True
-- | The outcome of 'newStoreEntry': either the store entry was newly created
-- or it existed already. The latter case happens if there was a race between
-- two builds of the same store entry.
--
data NewStoreEntryOutcome = UseNewStoreEntry
| UseExistingStoreEntry
deriving (Eq, Show)
-- | Place a new entry into the store. See the concurrency strategy description
-- for full details.
--
-- In particular, it takes two actions: one to place files into a temporary
-- location, and a second to perform any necessary registration. The first
-- action is executed without any locks held (the temp dir is unique). The
-- second action holds a lock that guarantees that only one cabal process is
-- able to install this store entry. This means it is safe to register into
-- the compiler package DB or do other similar actions.
--
-- Note that if you need to use the registration information later then you
-- /must/ check the 'NewStoreEntryOutcome' and if it's'UseExistingStoreEntry'
-- then you must read the existing registration information (unless your
-- registration information is constructed fully deterministically).
--
newStoreEntry :: Verbosity
-> StoreDirLayout
-> CompilerId
-> UnitId
-> (FilePath -> IO FilePath) -- ^ Action to place files.
-> IO () -- ^ Register action, if necessary.
-> IO NewStoreEntryOutcome
newStoreEntry verbosity storeDirLayout@StoreDirLayout{..}
compid unitid
copyFiles register =
-- See $concurrency above for an explanation of the concurrency protocol
withTempIncomingDir storeDirLayout compid $ \incomingTmpDir -> do
-- Write all store entry files within the temp dir and return the prefix.
incomingEntryDir <- copyFiles incomingTmpDir
-- Take a lock named after the 'UnitId' in question.
withIncomingUnitIdLock verbosity storeDirLayout compid unitid $ do
-- Check for the existence of the final store entry directory.
exists <- doesStoreEntryExist storeDirLayout compid unitid
if exists
-- If the entry exists then we lost the race and we must abandon,
-- unlock and re-use the existing store entry.
then do
info verbosity $
"Concurrent build race: abandoning build in favour of existing "
++ "store entry " ++ display compid </> display unitid
return UseExistingStoreEntry
-- If the entry does not exist then we won the race and can proceed.
else do
-- Register the package into the package db (if appropriate).
register
-- Atomically rename the temp dir to the final store entry location.
renameDirectory incomingEntryDir finalEntryDir
debug verbosity $
"Installed store entry " ++ display compid </> display unitid
return UseNewStoreEntry
where
finalEntryDir = storePackageDirectory compid unitid
withTempIncomingDir :: StoreDirLayout -> CompilerId
-> (FilePath -> IO a) -> IO a
withTempIncomingDir StoreDirLayout{storeIncomingDirectory} compid action = do
createDirectoryIfMissing True incomingDir
withTempDirectory silent incomingDir "new" action
where
incomingDir = storeIncomingDirectory compid
withIncomingUnitIdLock :: Verbosity -> StoreDirLayout
-> CompilerId -> UnitId
-> IO a -> IO a
withIncomingUnitIdLock verbosity StoreDirLayout{storeIncomingLock}
compid unitid action =
bracket takeLock releaseLock (\_hnd -> action)
where
takeLock = do
h <- openFile (storeIncomingLock compid unitid) ReadWriteMode
-- First try non-blocking, but if we would have to wait then
-- log an explanation and do it again in blocking mode.
gotlock <- hTryLock h ExclusiveLock
unless gotlock $ do
info verbosity $ "Waiting for file lock on store entry "
++ display compid </> display unitid
hLock h ExclusiveLock
return h
releaseLock = hClose
| themoritz/cabal | cabal-install/Distribution/Client/Store.hs | bsd-3-clause | 9,963 | 0 | 19 | 2,356 | 949 | 538 | 411 | 90 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Text.ICalendar.Parser
( parseICalendar
, parseICalendarFile
, parseICal
, parseICalFile
, DecodingFunctions(..)
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Error
import Control.Monad.RWS (runRWS)
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Monoid
import Prelude
import Text.Parsec.ByteString.Lazy ()
import Text.Parsec.Pos
import Text.Parsec.Prim hiding (many, (<|>))
import Text.Parsec.Text.Lazy ()
import Text.ICalendar.Parser.Common
import Text.ICalendar.Parser.Components
import Text.ICalendar.Parser.Content
import Text.ICalendar.Types
-- | Parse a ByteString containing iCalendar data.
--
-- Returns either an error, or a tuple of the result and a list of warnings.
parseICalendar :: DecodingFunctions
-> FilePath -- ^ Used in error messages.
-> ByteString
-> Either String ([VCalendar], [String])
parseICalendar s f bs = do
a <- either (Left . show) Right $ runParser parseToContent s f bs
when (null a) $ throwError "Missing content."
let xs = map (runCP s . parseVCalendar) a
(x, w) <- ((flip.).) flip foldM ([], []) xs $ \(x, ws) (g, (pos, _), w) ->
case g of
Left e -> Left $ show pos ++ ": " ++ e
Right y -> Right (y:x, w <> ws)
return (x, w)
-- | Deprecated synonym for parseICalendar
parseICal :: DecodingFunctions
-> FilePath
-> ByteString
-> Either String ([VCalendar], [String])
parseICal = parseICalendar
{-# DEPRECATED parseICal "Use parseICalendar instead" #-}
-- | Parse an iCalendar file.
parseICalendarFile :: DecodingFunctions
-> FilePath
-> IO (Either String ([VCalendar], [String]))
parseICalendarFile s f = parseICal s f <$> B.readFile f
-- | Deprecated synonym for parseICalendarFile
parseICalFile :: DecodingFunctions
-> FilePath
-> IO (Either String ([VCalendar], [String]))
parseICalFile = parseICalendarFile
{-# DEPRECATED parseICalFile "Use parseICalendarFile instead" #-}
runCP :: DecodingFunctions -> ContentParser a
-> (Either String a, (SourcePos, [Content]), [String])
runCP s = ((flip .) . flip) runRWS s (undefined, undefined) . runErrorT
| chrra/iCalendar | Text/ICalendar/Parser.hs | bsd-3-clause | 2,580 | 0 | 16 | 659 | 644 | 372 | 272 | 57 | 2 |
{-# LANGUAGE
MultiParamTypeClasses,
TypeFamilies,
DeriveFunctor,
DeriveFoldable,
DeriveTraversable,
FlexibleInstances,
FlexibleContexts,
ConstraintKinds,
NoMonomorphismRestriction,
UndecidableInstances,
GeneralizedNewtypeDeriving #-}
module Update3 where
-- Copied from https://ghc.haskell.org/trac/ghc/wiki/Records/OverloadedRecordFields/Plan
-- Simplified to capture a single type
import Control.Applicative
import Control.Lens
import Data.Semigroup
import Data.Foldable
import Data.Traversable
import Data.AffineSpace -- tests
import qualified Music.Pitch as M
-- Constraint versions of the lens laws
-- type GetPut s = (s ~ SetPitch (Pitch s) s)
-- type PutGet s a = (a ~ Pitch (SetPitch a s))
-- type PutPut s a b = (b ~ SetPitch b (SetPitch a s))
class HasPitch s where
type Pitch (s :: *) :: *
getPitch :: (a ~ Pitch s) => s -> a
class (HasPitch s, s ~ SetPitch (Pitch s) s) => UpdatePitch (b :: *) (s :: *) where
type SetPitch (b :: *) (s :: *) :: *
setPitch :: (b ~ Pitch t, t ~ SetPitch b s) => b -> s -> t
type HasPitch2 s t = (UpdatePitch (Pitch t) s, SetPitch (Pitch t) s ~ t)
type HasPitch' s = HasPitch2 s s
mapPitch :: (HasPitch2 s t) => (Pitch s -> Pitch t) -> s -> t
mapPitch f x = setPitch p x where p = f (getPitch x)
mapPitch' :: (HasPitch' s) => (Pitch s -> Pitch s) -> s -> s
mapPitch' = mapPitch
data PitchT f a = PitchT f a
deriving (Show, Functor, Foldable, Traversable)
instance (Semigroup p, Monoid p) => Applicative (PitchT p) where
pure = PitchT mempty
PitchT pf vf <*> PitchT px vx = PitchT (pf <> px) (vf $ vx)
instance HasPitch (PitchT f a) where
type Pitch (PitchT f a) = f
getPitch (PitchT f a) = f
instance UpdatePitch g (PitchT f a) where
type SetPitch g (PitchT f a) = PitchT g a
setPitch g (PitchT f a) = PitchT g a
instance HasPitch a => HasPitch [a] where
type Pitch [a] = Pitch a
getPitch [x] = getPitch x
-- TODO crashes when updating longer lists etc
-- Undecidable
instance (UpdatePitch b a) => UpdatePitch b [a] where
type SetPitch b [a] = [SetPitch b a]
setPitch b = fmap (setPitch b)
instance HasPitch a => HasPitch (c,a) where
type Pitch (c,a) = Pitch a
getPitch (c,a) = getPitch a
--
-- Undecidable ??
instance (UpdatePitch b a) => UpdatePitch b (c,a) where
type SetPitch b (c,a) = (c,SetPitch b a)
setPitch b = fmap (setPitch b)
instance HasPitch M.Pitch where
type Pitch M.Pitch = M.Pitch
getPitch = id
instance UpdatePitch M.Pitch M.Pitch where
type SetPitch M.Pitch M.Pitch = M.Pitch
setPitch = const
type Interval a = Diff (Pitch a)
up :: (UpdatePitch (Pitch t) t, AffineSpace (Pitch t)) => Interval t -> t -> t
up x = mapPitch (.+^ x)
(x,int2float) = (PitchT 3 (True, 0), fromIntegral)
int2float :: Int -> Float
x :: PitchT Int (Bool, Int)
y :: PitchT Float (Int, Bool)
y = fmap swap $ mapPitch (int2float) x
swap (x,y) = (y,x)
| FranklinChen/music-score | sketch/old/update/update3.hs | bsd-3-clause | 2,980 | 0 | 10 | 692 | 1,081 | 584 | 497 | 70 | 1 |
module HList
( H
, repH
, absH
, myAppend
) where
type H a = [a] -> [a]
-- {-# INLINABLE repH #-}
repH :: [a] -> H a
repH xs = (xs ++)
-- {-# INLINABLE absH #-}
absH :: H a -> [a]
absH f = f []
-- Because we can't get unfolding for ++
myAppend :: [a] -> [a] -> [a]
myAppend [] ys = ys
myAppend (x:xs) ys = x : myAppend xs ys
-- {-# RULES "appendFix" [~] (++) = myAppend #-}
-- -- Algebra for repH
-- {-# RULES "repH []" [~] repH [] = id #-}
-- {-# RULES "repH (:)" [~] forall x xs. repH (x:xs) = (x:) . repH xs #-}
-- {-# RULES "repH ++" [~] forall xs ys. repH (xs ++ ys) = repH xs . repH ys #-}
-- -- Needed because the fusion rule we generate isn't too useful yet.
-- {-# RULES "repH-absH-fusion" [~] forall h. repH (absH h) = h #-}
| conal/hermit | examples/new_reverse/HList.hs | bsd-2-clause | 782 | 0 | 7 | 215 | 160 | 94 | 66 | 13 | 1 |
-- |
-- Statistics for per-module compilations
--
-- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
--
{-# LANGUAGE FlexibleContexts #-}
module HscStats ( ppSourceStats ) where
import Bag
import HsSyn
import Outputable
import RdrName
import SrcLoc
import Util
import Data.Char
-- | Source Statistics
ppSourceStats :: Bool -> Located (HsModule RdrName) -> SDoc
ppSourceStats short (L _ (HsModule _ exports imports ldecls _ _))
= (if short then hcat else vcat)
(map pp_val
[("ExportAll ", export_all), -- 1 if no export list
("ExportDecls ", export_ds),
("ExportModules ", export_ms),
("Imports ", imp_no),
(" ImpSafe ", imp_safe),
(" ImpQual ", imp_qual),
(" ImpAs ", imp_as),
(" ImpAll ", imp_all),
(" ImpPartial ", imp_partial),
(" ImpHiding ", imp_hiding),
("FixityDecls ", fixity_sigs),
("DefaultDecls ", default_ds),
("TypeDecls ", type_ds),
("DataDecls ", data_ds),
("NewTypeDecls ", newt_ds),
("TypeFamilyDecls ", type_fam_ds),
("DataConstrs ", data_constrs),
("DataDerivings ", data_derivs),
("ClassDecls ", class_ds),
("ClassMethods ", class_method_ds),
("DefaultMethods ", default_method_ds),
("InstDecls ", inst_ds),
("InstMethods ", inst_method_ds),
("InstType ", inst_type_ds),
("InstData ", inst_data_ds),
("TypeSigs ", bind_tys),
("ClassOpSigs ", generic_sigs),
("ValBinds ", val_bind_ds),
("FunBinds ", fn_bind_ds),
("PatSynBinds ", patsyn_ds),
("InlineMeths ", method_inlines),
("InlineBinds ", bind_inlines),
("SpecialisedMeths ", method_specs),
("SpecialisedBinds ", bind_specs)
])
where
decls = map unLoc ldecls
pp_val (_, 0) = empty
pp_val (str, n)
| not short = hcat [text str, int n]
| otherwise = hcat [text (trim str), equals, int n, semi]
trim ls = takeWhile (not.isSpace) (dropWhile isSpace ls)
(fixity_sigs, bind_tys, bind_specs, bind_inlines, generic_sigs)
= count_sigs [d | SigD d <- decls]
-- NB: this omits fixity decls on local bindings and
-- in class decls. ToDo
tycl_decls = [d | TyClD d <- decls]
(class_ds, type_ds, data_ds, newt_ds, type_fam_ds) =
countTyClDecls tycl_decls
inst_decls = [d | InstD d <- decls]
inst_ds = length inst_decls
default_ds = count (\ x -> case x of { DefD{} -> True; _ -> False}) decls
val_decls = [d | ValD d <- decls]
real_exports = case exports of { Nothing -> []; Just (L _ es) -> es }
n_exports = length real_exports
export_ms = count (\ e -> case unLoc e of { IEModuleContents{} -> True;_ -> False})
real_exports
export_ds = n_exports - export_ms
export_all = case exports of { Nothing -> 1; _ -> 0 }
(val_bind_ds, fn_bind_ds, patsyn_ds)
= sum3 (map count_bind val_decls)
(imp_no, imp_safe, imp_qual, imp_as, imp_all, imp_partial, imp_hiding)
= sum7 (map import_info imports)
(data_constrs, data_derivs)
= sum2 (map data_info tycl_decls)
(class_method_ds, default_method_ds)
= sum2 (map class_info tycl_decls)
(inst_method_ds, method_specs, method_inlines, inst_type_ds, inst_data_ds)
= sum5 (map inst_info inst_decls)
count_bind (PatBind { pat_lhs = L _ (VarPat _) }) = (1,0,0)
count_bind (PatBind {}) = (0,1,0)
count_bind (FunBind {}) = (0,1,0)
count_bind (PatSynBind {}) = (0,0,1)
count_bind b = pprPanic "count_bind: Unhandled binder" (ppr b)
count_sigs sigs = sum5 (map sig_info sigs)
sig_info (FixSig {}) = (1,0,0,0,0)
sig_info (TypeSig {}) = (0,1,0,0,0)
sig_info (SpecSig {}) = (0,0,1,0,0)
sig_info (InlineSig {}) = (0,0,0,1,0)
sig_info (ClassOpSig {}) = (0,0,0,0,1)
sig_info _ = (0,0,0,0,0)
import_info (L _ (ImportDecl { ideclSafe = safe, ideclQualified = qual
, ideclAs = as, ideclHiding = spec }))
= add7 (1, safe_info safe, qual_info qual, as_info as, 0,0,0) (spec_info spec)
safe_info = qual_info
qual_info False = 0
qual_info True = 1
as_info Nothing = 0
as_info (Just _) = 1
spec_info Nothing = (0,0,0,0,1,0,0)
spec_info (Just (False, _)) = (0,0,0,0,0,1,0)
spec_info (Just (True, _)) = (0,0,0,0,0,0,1)
data_info (DataDecl { tcdDataDefn = HsDataDefn { dd_cons = cs
, dd_derivs = derivs}})
= (length cs, case derivs of Nothing -> 0
Just (L _ ds) -> length ds)
data_info _ = (0,0)
class_info decl@(ClassDecl {})
= (classops, addpr (sum3 (map count_bind methods)))
where
methods = map unLoc $ bagToList (tcdMeths decl)
(_, classops, _, _, _) = count_sigs (map unLoc (tcdSigs decl))
class_info _ = (0,0)
inst_info (TyFamInstD {}) = (0,0,0,1,0)
inst_info (DataFamInstD {}) = (0,0,0,0,1)
inst_info (ClsInstD { cid_inst = ClsInstDecl {cid_binds = inst_meths
, cid_sigs = inst_sigs
, cid_tyfam_insts = ats
, cid_datafam_insts = adts } })
= case count_sigs (map unLoc inst_sigs) of
(_,_,ss,is,_) ->
(addpr (sum3 (map count_bind methods)),
ss, is, length ats, length adts)
where
methods = map unLoc $ bagToList inst_meths
-- TODO: use Sum monoid
addpr :: (Int,Int,Int) -> Int
sum2 :: [(Int, Int)] -> (Int, Int)
sum3 :: [(Int, Int, Int)] -> (Int, Int, Int)
sum5 :: [(Int, Int, Int, Int, Int)] -> (Int, Int, Int, Int, Int)
sum7 :: [(Int, Int, Int, Int, Int, Int, Int)] -> (Int, Int, Int, Int, Int, Int, Int)
add7 :: (Int, Int, Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int, Int)
-> (Int, Int, Int, Int, Int, Int, Int)
addpr (x,y,z) = x+y+z
sum2 = foldr add2 (0,0)
where
add2 (x1,x2) (y1,y2) = (x1+y1,x2+y2)
sum3 = foldr add3 (0,0,0)
where
add3 (x1,x2,x3) (y1,y2,y3) = (x1+y1,x2+y2,x3+y3)
sum5 = foldr add5 (0,0,0,0,0)
where
add5 (x1,x2,x3,x4,x5) (y1,y2,y3,y4,y5) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5)
sum7 = foldr add7 (0,0,0,0,0,0,0)
add7 (x1,x2,x3,x4,x5,x6,x7) (y1,y2,y3,y4,y5,y6,y7) = (x1+y1,x2+y2,x3+y3,x4+y4,x5+y5,x6+y6,x7+y7)
| vTurbine/ghc | compiler/main/HscStats.hs | bsd-3-clause | 7,046 | 0 | 15 | 2,430 | 2,578 | 1,505 | 1,073 | 138 | 25 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
module Fun00005 where
prjF :: Project (sub :|| Type) sup => sup sig -> Maybe ((sub :|| Type) sig)
prjF = prj
class
( AlphaEq dom dom (dom :|| Typeable) [(VarId, VarId)]
, AlphaEq dom dom (Decor Info (dom :|| Typeable)) [(VarId, VarId)]
, EvalBind dom
, (Literal :|| Type) :<: dom
, Typed dom
, Render dom -- For debug
, Constrained dom
, Optimize dom dom
) =>
OptimizeSuper dom
optimizeM :: (OptimizeSuper dom)
=> FeldOpts -> ASTF (dom :|| Typeable) a -> Opt (ASTF (Decor Info (dom :|| Typeable)) a)
optimizeM opts a
| Dict <- exprDict a
= constFold <$> matchTrans (\(C' x) -> optimizeFeat opts x) a
optimizeN :: (OptimizeSuper dom, t1 ~ t2)
=> FeldOpts -> ASTF (dom :|| Typeable) a -> Opt (ASTF (Decor Info (dom :|| Typeable)) a)
optimizeO :: ()
=> FeldOpts -> ASTF (dom :|| Typeable) a -> Opt (ASTF (Decor Info (dom :|| Typeable)) a)
instance Bounded a => ([a] :|| b) where
class GMapKey k where
data GMap k :: * -> *
instance (GMapKey a, GMapKey b) => GMapKey (Either a b) where
data GMap (Either a b) v = GMapEither (GMap a v) (GMap b v)
instance Eq e => Collects [e] where
type Elem [e] = e
empty = []
| charleso/intellij-haskforce | tests/gold/parser/Fun00005.hs | apache-2.0 | 1,355 | 3 | 15 | 345 | 494 | 276 | 218 | -1 | -1 |
data DList a = DLNode (DList a) a (DList a)
rot :: Integer -> [a] -> [a]
rot n xs | n < 0 = rot (n+1) ((last xs):(init xs))
| n == 0 = xs
| n > 0 = rot (n-1) (tail xs ++ [head xs])
mkDList :: [a] -> DList a
mkDList [] = error "Must have at least one element."
mkDList xs = DLNode (mkDList $ rot (-1) xs) (head xs) (mkDList $ rot 1 xs)
| bitemyapp/ghc-vis | docs/dll2.hs | bsd-3-clause | 374 | 0 | 10 | 119 | 229 | 115 | 114 | 8 | 1 |
module MediaWiki.API.Query.LangLinks.Import where
import MediaWiki.API.Types
import MediaWiki.API.Utils
import MediaWiki.API.Query.LangLinks
import Text.XML.Light.Types
import Text.XML.Light.Proc ( strContent )
import Control.Monad
import Data.Maybe
stringXml :: String -> Either (String,[{-Error msg-}String]) LangLinksResponse
stringXml s = parseDoc xml s
xml :: Element -> Maybe LangLinksResponse
xml e = do
guard (elName e == nsName "api")
let es1 = children e
p <- pNode "query" es1
let es = children p
ps <- fmap (mapMaybe xmlPage) (fmap children $ pNode "pages" es)
let cont = pNode "query-continue" es1 >>= xmlContinue "langlinks" "llcontinue"
return emptyLangLinksResponse
{ llPages = ps
, llContinue = cont
}
xmlPage :: Element -> Maybe (PageTitle,[LangPageInfo])
xmlPage e = do
guard (elName e == nsName "page")
let pid = fmap read $ pAttr "pageid" e
let ns = fromMaybe mainNamespace $ pAttr "ns" e
let tit = fromMaybe "" $ pAttr "title" e
let es = children e
ls <- fmap (mapMaybe xmlLangLink) (fmap children $ pNode "langlinks" es)
let pg = emptyPageTitle{pgNS=ns,pgMbId=pid,pgTitle=tit}
return (pg, ls)
xmlLangLink :: Element -> Maybe LangPageInfo
xmlLangLink e = do
guard (elName e == nsName "ll")
let la = fromMaybe "en" $ pAttr "lang" e
let tit = case strContent e of { "" -> Nothing ; xs -> Just xs}
return emptyLangPageInfo{langName=la,langTitle=tit}
| neobrain/neobot | mediawiki/MediaWiki/API/Query/LangLinks/Import.hs | bsd-3-clause | 1,459 | 2 | 13 | 296 | 558 | 278 | 280 | 37 | 2 |
{-# LANGUAGE CPP, ForeignFunctionInterface, ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Utils
-- Copyright : Isaac Jones, Simon Marlow 2003-2004
-- License : BSD3
-- portions Copyright (c) 2007, Galois Inc.
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- A large and somewhat miscellaneous collection of utility functions used
-- throughout the rest of the Cabal lib and in other tools that use the Cabal
-- lib like @cabal-install@. It has a very simple set of logging actions. It
-- has low level functions for running programs, a bunch of wrappers for
-- various directory and file functions that do extra logging.
module Distribution.Simple.Utils (
cabalVersion,
-- * logging and errors
die,
dieWithLocation,
topHandler, topHandlerWith,
warn, notice, setupMessage, info, debug,
debugNoWrap, chattyTry,
printRawCommandAndArgs, printRawCommandAndArgsAndEnv,
-- * running programs
rawSystemExit,
rawSystemExitCode,
rawSystemExitWithEnv,
rawSystemStdout,
rawSystemStdInOut,
rawSystemIOWithEnv,
createProcessWithEnv,
maybeExit,
xargs,
findProgramLocation,
findProgramVersion,
-- * copying files
smartCopySources,
createDirectoryIfMissingVerbose,
copyFileVerbose,
copyDirectoryRecursiveVerbose,
copyFiles,
copyFileTo,
-- * installing files
installOrdinaryFile,
installExecutableFile,
installMaybeExecutableFile,
installOrdinaryFiles,
installExecutableFiles,
installMaybeExecutableFiles,
installDirectoryContents,
copyDirectoryRecursive,
-- * File permissions
doesExecutableExist,
setFileOrdinary,
setFileExecutable,
-- * file names
currentDir,
shortRelativePath,
-- * finding files
findFile,
findFirstFile,
findFileWithExtension,
findFileWithExtension',
findAllFilesWithExtension,
findModuleFile,
findModuleFiles,
getDirectoryContentsRecursive,
-- * environment variables
isInSearchPath,
addLibraryPath,
-- * simple file globbing
matchFileGlob,
matchDirFileGlob,
parseFileGlob,
FileGlob(..),
-- * modification time
moreRecentFile,
existsAndIsMoreRecentThan,
-- * temp files and dirs
TempFileOptions(..), defaultTempFileOptions,
withTempFile, withTempFileEx,
withTempDirectory, withTempDirectoryEx,
-- * .cabal and .buildinfo files
defaultPackageDesc,
findPackageDesc,
tryFindPackageDesc,
defaultHookedPackageDesc,
findHookedPackageDesc,
-- * reading and writing files safely
withFileContents,
writeFileAtomic,
rewriteFile,
-- * Unicode
fromUTF8,
toUTF8,
readUTF8File,
withUTF8FileContents,
writeUTF8File,
normaliseLineEndings,
-- * BOM
startsWithBOM,
fileHasBOM,
ignoreBOM,
-- * generic utils
dropWhileEndLE,
takeWhileEndLE,
equating,
comparing,
isInfixOf,
intercalate,
lowercase,
listUnion,
listUnionRight,
ordNub,
ordNubRight,
wrapText,
wrapLine,
) where
import Control.Monad
( when, unless, filterM )
import Control.Concurrent.MVar
( newEmptyMVar, putMVar, takeMVar )
import Data.Bits
( Bits((.|.), (.&.), shiftL, shiftR) )
import Data.Char as Char
( isDigit, toLower, chr, ord )
import Data.Foldable
( traverse_ )
import Data.List
( nub, unfoldr, isPrefixOf, tails, intercalate )
import Data.Typeable
( cast )
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as BS.Char8
import qualified Data.Set as Set
import System.Directory
( Permissions(executable), getDirectoryContents, getPermissions
, doesDirectoryExist, doesFileExist, removeFile, findExecutable
, getModificationTime )
import System.Environment
( getProgName )
import System.Exit
( exitWith, ExitCode(..) )
import System.FilePath
( normalise, (</>), (<.>)
, getSearchPath, joinPath, takeDirectory, splitFileName
, splitExtension, splitExtensions, splitDirectories
, searchPathSeparator )
import System.Directory
( createDirectory, renameFile, removeDirectoryRecursive )
import System.IO
( Handle, openFile, openBinaryFile, openBinaryTempFileWithDefaultPermissions
, IOMode(ReadMode), hSetBinaryMode
, hGetContents, stderr, stdout, hPutStr, hFlush, hClose )
import System.IO.Error as IO.Error
( isDoesNotExistError, isAlreadyExistsError
, ioeSetFileName, ioeGetFileName, ioeGetErrorString )
import System.IO.Error
( ioeSetLocation, ioeGetLocation )
import System.IO.Unsafe
( unsafeInterleaveIO )
import qualified Control.Exception as Exception
import Distribution.Text
( display, simpleParse )
import Distribution.Package
( PackageIdentifier )
import Distribution.ModuleName (ModuleName)
import qualified Distribution.ModuleName as ModuleName
import Distribution.System
( OS (..) )
import Distribution.Version
(Version(..))
import Control.Exception (IOException, evaluate, throwIO)
import Control.Concurrent (forkIO)
import qualified System.Process as Process
( CreateProcess(..), StdStream(..), proc)
import System.Process
( ProcessHandle, createProcess, rawSystem, runInteractiveProcess
, showCommandForUser, waitForProcess)
import Distribution.Compat.CopyFile
( copyFile, copyOrdinaryFile, copyExecutableFile
, setFileOrdinary, setFileExecutable, setDirOrdinary )
import Distribution.Compat.Internal.TempFile
( openTempFile, createTempDirectory )
import Distribution.Compat.Exception
( tryIO, catchIO, catchExit )
import Distribution.Verbosity
#ifdef VERSION_base
import qualified Paths_Cabal (version)
#endif
-- We only get our own version number when we're building with ourselves
cabalVersion :: Version
#if defined(VERSION_base)
cabalVersion = Paths_Cabal.version
#elif defined(CABAL_VERSION)
cabalVersion = Version [CABAL_VERSION] []
#else
cabalVersion = Version [1,9999] [] --used when bootstrapping
#endif
-- ----------------------------------------------------------------------------
-- Exception and logging utils
dieWithLocation :: FilePath -> Maybe Int -> String -> IO a
dieWithLocation filename lineno msg =
ioError . setLocation lineno
. flip ioeSetFileName (normalise filename)
$ userError msg
where
setLocation Nothing err = err
setLocation (Just n) err = ioeSetLocation err (show n)
die :: String -> IO a
die msg = ioError (userError msg)
topHandlerWith :: forall a. (Exception.SomeException -> IO a) -> IO a -> IO a
topHandlerWith cont prog =
Exception.catches prog [
Exception.Handler rethrowAsyncExceptions
, Exception.Handler rethrowExitStatus
, Exception.Handler handle
]
where
-- Let async exceptions rise to the top for the default top-handler
rethrowAsyncExceptions :: Exception.AsyncException -> IO a
rethrowAsyncExceptions = throwIO
-- ExitCode gets thrown asynchronously too, and we don't want to print it
rethrowExitStatus :: ExitCode -> IO a
rethrowExitStatus = throwIO
-- Print all other exceptions
handle :: Exception.SomeException -> IO a
handle se = do
hFlush stdout
pname <- getProgName
hPutStr stderr (message pname se)
cont se
message :: String -> Exception.SomeException -> String
message pname (Exception.SomeException se) =
case cast se :: Maybe Exception.IOException of
Just ioe ->
let file = case ioeGetFileName ioe of
Nothing -> ""
Just path -> path ++ location ++ ": "
location = case ioeGetLocation ioe of
l@(n:_) | Char.isDigit n -> ':' : l
_ -> ""
detail = ioeGetErrorString ioe
in wrapText (pname ++ ": " ++ file ++ detail)
Nothing ->
#if __GLASGOW_HASKELL__ < 710
show se
#else
Exception.displayException se
#endif
topHandler :: IO a -> IO a
topHandler prog = topHandlerWith (const $ exitWith (ExitFailure 1)) prog
-- | Non fatal conditions that may be indicative of an error or problem.
--
-- We display these at the 'normal' verbosity level.
--
warn :: Verbosity -> String -> IO ()
warn verbosity msg =
when (verbosity >= normal) $ do
hFlush stdout
hPutStr stderr (wrapText ("Warning: " ++ msg))
-- | Useful status messages.
--
-- We display these at the 'normal' verbosity level.
--
-- This is for the ordinary helpful status messages that users see. Just
-- enough information to know that things are working but not floods of detail.
--
notice :: Verbosity -> String -> IO ()
notice verbosity msg =
when (verbosity >= normal) $
putStr (wrapText msg)
setupMessage :: Verbosity -> String -> PackageIdentifier -> IO ()
setupMessage verbosity msg pkgid =
notice verbosity (msg ++ ' ': display pkgid ++ "...")
-- | More detail on the operation of some action.
--
-- We display these messages when the verbosity level is 'verbose'
--
info :: Verbosity -> String -> IO ()
info verbosity msg =
when (verbosity >= verbose) $
putStr (wrapText msg)
-- | Detailed internal debugging information
--
-- We display these messages when the verbosity level is 'deafening'
--
debug :: Verbosity -> String -> IO ()
debug verbosity msg =
when (verbosity >= deafening) $ do
putStr (wrapText msg)
hFlush stdout
-- | A variant of 'debug' that doesn't perform the automatic line
-- wrapping. Produces better output in some cases.
debugNoWrap :: Verbosity -> String -> IO ()
debugNoWrap verbosity msg =
when (verbosity >= deafening) $ do
putStrLn msg
hFlush stdout
-- | Perform an IO action, catching any IO exceptions and printing an error
-- if one occurs.
chattyTry :: String -- ^ a description of the action we were attempting
-> IO () -- ^ the action itself
-> IO ()
chattyTry desc action =
catchIO action $ \exception ->
putStrLn $ "Error while " ++ desc ++ ": " ++ show exception
-- -----------------------------------------------------------------------------
-- Helper functions
-- | Wraps text to the default line width. Existing newlines are preserved.
wrapText :: String -> String
wrapText = unlines
. map (intercalate "\n"
. map unwords
. wrapLine 79
. words)
. lines
-- | Wraps a list of words to a list of lines of words of a particular width.
wrapLine :: Int -> [String] -> [[String]]
wrapLine width = wrap 0 []
where wrap :: Int -> [String] -> [String] -> [[String]]
wrap 0 [] (w:ws)
| length w + 1 > width
= wrap (length w) [w] ws
wrap col line (w:ws)
| col + length w + 1 > width
= reverse line : wrap 0 [] (w:ws)
wrap col line (w:ws)
= let col' = col + length w + 1
in wrap col' (w:line) ws
wrap _ [] [] = []
wrap _ line [] = [reverse line]
-- -----------------------------------------------------------------------------
-- rawSystem variants
maybeExit :: IO ExitCode -> IO ()
maybeExit cmd = do
res <- cmd
unless (res == ExitSuccess) $ exitWith res
printRawCommandAndArgs :: Verbosity -> FilePath -> [String] -> IO ()
printRawCommandAndArgs verbosity path args =
printRawCommandAndArgsAndEnv verbosity path args Nothing
printRawCommandAndArgsAndEnv :: Verbosity
-> FilePath
-> [String]
-> Maybe [(String, String)]
-> IO ()
printRawCommandAndArgsAndEnv verbosity path args menv
| verbosity >= deafening = do
traverse_ (putStrLn . ("Environment: " ++) . show) menv
print (path, args)
| verbosity >= verbose = putStrLn $ showCommandForUser path args
| otherwise = return ()
-- Exit with the same exit code if the subcommand fails
rawSystemExit :: Verbosity -> FilePath -> [String] -> IO ()
rawSystemExit verbosity path args = do
printRawCommandAndArgs verbosity path args
hFlush stdout
exitcode <- rawSystem path args
unless (exitcode == ExitSuccess) $ do
debug verbosity $ path ++ " returned " ++ show exitcode
exitWith exitcode
rawSystemExitCode :: Verbosity -> FilePath -> [String] -> IO ExitCode
rawSystemExitCode verbosity path args = do
printRawCommandAndArgs verbosity path args
hFlush stdout
exitcode <- rawSystem path args
unless (exitcode == ExitSuccess) $ do
debug verbosity $ path ++ " returned " ++ show exitcode
return exitcode
rawSystemExitWithEnv :: Verbosity
-> FilePath
-> [String]
-> [(String, String)]
-> IO ()
rawSystemExitWithEnv verbosity path args env = do
printRawCommandAndArgsAndEnv verbosity path args (Just env)
hFlush stdout
(_,_,_,ph) <- createProcess $
(Process.proc path args) { Process.env = (Just env)
#ifdef MIN_VERSION_process
#if MIN_VERSION_process(1,2,0)
-- delegate_ctlc has been added in process 1.2, and we still want to be able to
-- bootstrap GHC on systems not having that version
, Process.delegate_ctlc = True
#endif
#endif
}
exitcode <- waitForProcess ph
unless (exitcode == ExitSuccess) $ do
debug verbosity $ path ++ " returned " ++ show exitcode
exitWith exitcode
-- Closes the passed in handles before returning.
rawSystemIOWithEnv :: Verbosity
-> FilePath
-> [String]
-> Maybe FilePath -- ^ New working dir or inherit
-> Maybe [(String, String)] -- ^ New environment or inherit
-> Maybe Handle -- ^ stdin
-> Maybe Handle -- ^ stdout
-> Maybe Handle -- ^ stderr
-> IO ExitCode
rawSystemIOWithEnv verbosity path args mcwd menv inp out err = do
(_,_,_,ph) <- createProcessWithEnv verbosity path args mcwd menv
(mbToStd inp) (mbToStd out) (mbToStd err)
exitcode <- waitForProcess ph
unless (exitcode == ExitSuccess) $ do
debug verbosity $ path ++ " returned " ++ show exitcode
return exitcode
where
mbToStd :: Maybe Handle -> Process.StdStream
mbToStd = maybe Process.Inherit Process.UseHandle
createProcessWithEnv :: Verbosity
-> FilePath
-> [String]
-> Maybe FilePath -- ^ New working dir or inherit
-> Maybe [(String, String)] -- ^ New environment or inherit
-> Process.StdStream -- ^ stdin
-> Process.StdStream -- ^ stdout
-> Process.StdStream -- ^ stderr
-> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
-- ^ Any handles created for stdin, stdout, or stderr
-- with 'CreateProcess', and a handle to the process.
createProcessWithEnv verbosity path args mcwd menv inp out err = do
printRawCommandAndArgsAndEnv verbosity path args menv
hFlush stdout
(inp', out', err', ph) <- createProcess $
(Process.proc path args) {
Process.cwd = mcwd
, Process.env = menv
, Process.std_in = inp
, Process.std_out = out
, Process.std_err = err
#ifdef MIN_VERSION_process
#if MIN_VERSION_process(1,2,0)
-- delegate_ctlc has been added in process 1.2, and we still want to be able to
-- bootstrap GHC on systems not having that version
, Process.delegate_ctlc = True
#endif
#endif
}
return (inp', out', err', ph)
-- | Run a command and return its output.
--
-- The output is assumed to be text in the locale encoding.
--
rawSystemStdout :: Verbosity -> FilePath -> [String] -> IO String
rawSystemStdout verbosity path args = do
(output, errors, exitCode) <- rawSystemStdInOut verbosity path args
Nothing Nothing
Nothing False
when (exitCode /= ExitSuccess) $
die errors
return output
-- | Run a command and return its output, errors and exit status. Optionally
-- also supply some input. Also provides control over whether the binary/text
-- mode of the input and output.
--
rawSystemStdInOut :: Verbosity
-> FilePath -- ^ Program location
-> [String] -- ^ Arguments
-> Maybe FilePath -- ^ New working dir or inherit
-> Maybe [(String, String)] -- ^ New environment or inherit
-> Maybe (String, Bool) -- ^ input text and binary mode
-> Bool -- ^ output in binary mode
-> IO (String, String, ExitCode) -- ^ output, errors, exit
rawSystemStdInOut verbosity path args mcwd menv input outputBinary = do
printRawCommandAndArgs verbosity path args
Exception.bracket
(runInteractiveProcess path args mcwd menv)
(\(inh,outh,errh,_) -> hClose inh >> hClose outh >> hClose errh)
$ \(inh,outh,errh,pid) -> do
-- output mode depends on what the caller wants
hSetBinaryMode outh outputBinary
-- but the errors are always assumed to be text (in the current locale)
hSetBinaryMode errh False
-- fork off a couple threads to pull on the stderr and stdout
-- so if the process writes to stderr we do not block.
err <- hGetContents errh
out <- hGetContents outh
mv <- newEmptyMVar
let force str = (evaluate (length str) >> return ())
`Exception.finally` putMVar mv ()
--TODO: handle exceptions like text decoding.
_ <- forkIO $ force out
_ <- forkIO $ force err
-- push all the input, if any
case input of
Nothing -> return ()
Just (inputStr, inputBinary) -> do
-- input mode depends on what the caller wants
hSetBinaryMode inh inputBinary
hPutStr inh inputStr
hClose inh
--TODO: this probably fails if the process refuses to consume
-- or if it closes stdin (eg if it exits)
-- wait for both to finish, in either order
takeMVar mv
takeMVar mv
-- wait for the program to terminate
exitcode <- waitForProcess pid
unless (exitcode == ExitSuccess) $
debug verbosity $ path ++ " returned " ++ show exitcode
++ if null err then "" else
" with error message:\n" ++ err
++ case input of
Nothing -> ""
Just ("", _) -> ""
Just (inp, _) -> "\nstdin input:\n" ++ inp
return (out, err, exitcode)
-- | Look for a program on the path.
findProgramLocation :: Verbosity -> FilePath -> IO (Maybe FilePath)
findProgramLocation verbosity prog = do
debug verbosity $ "searching for " ++ prog ++ " in path."
res <- findExecutable prog
case res of
Nothing -> debug verbosity ("Cannot find " ++ prog ++ " on the path")
Just path -> debug verbosity ("found " ++ prog ++ " at "++ path)
return res
-- | Look for a program and try to find it's version number. It can accept
-- either an absolute path or the name of a program binary, in which case we
-- will look for the program on the path.
--
findProgramVersion :: String -- ^ version args
-> (String -> String) -- ^ function to select version
-- number from program output
-> Verbosity
-> FilePath -- ^ location
-> IO (Maybe Version)
findProgramVersion versionArg selectVersion verbosity path = do
str <- rawSystemStdout verbosity path [versionArg]
`catchIO` (\_ -> return "")
`catchExit` (\_ -> return "")
let version :: Maybe Version
version = simpleParse (selectVersion str)
case version of
Nothing -> warn verbosity $ "cannot determine version of " ++ path
++ " :\n" ++ show str
Just v -> debug verbosity $ path ++ " is version " ++ display v
return version
-- | Like the Unix xargs program. Useful for when we've got very long command
-- lines that might overflow an OS limit on command line length and so you
-- need to invoke a command multiple times to get all the args in.
--
-- Use it with either of the rawSystem variants above. For example:
--
-- > xargs (32*1024) (rawSystemExit verbosity) prog fixedArgs bigArgs
--
xargs :: Int -> ([String] -> IO ())
-> [String] -> [String] -> IO ()
xargs maxSize rawSystemFun fixedArgs bigArgs =
let fixedArgSize = sum (map length fixedArgs) + length fixedArgs
chunkSize = maxSize - fixedArgSize
in mapM_ (rawSystemFun . (fixedArgs ++)) (chunks chunkSize bigArgs)
where chunks len = unfoldr $ \s ->
if null s then Nothing
else Just (chunk [] len s)
chunk acc _ [] = (reverse acc,[])
chunk acc len (s:ss)
| len' < len = chunk (s:acc) (len-len'-1) ss
| otherwise = (reverse acc, s:ss)
where len' = length s
-- ------------------------------------------------------------
-- * File Utilities
-- ------------------------------------------------------------
----------------
-- Finding files
-- | Find a file by looking in a search path. The file path must match exactly.
--
findFile :: [FilePath] -- ^search locations
-> FilePath -- ^File Name
-> IO FilePath
findFile searchPath fileName =
findFirstFile id
[ path </> fileName
| path <- nub searchPath]
>>= maybe (die $ fileName ++ " doesn't exist") return
-- | Find a file by looking in a search path with one of a list of possible
-- file extensions. The file base name should be given and it will be tried
-- with each of the extensions in each element of the search path.
--
findFileWithExtension :: [String]
-> [FilePath]
-> FilePath
-> IO (Maybe FilePath)
findFileWithExtension extensions searchPath baseName =
findFirstFile id
[ path </> baseName <.> ext
| path <- nub searchPath
, ext <- nub extensions ]
findAllFilesWithExtension :: [String]
-> [FilePath]
-> FilePath
-> IO [FilePath]
findAllFilesWithExtension extensions searchPath basename =
findAllFiles id
[ path </> basename <.> ext
| path <- nub searchPath
, ext <- nub extensions ]
-- | Like 'findFileWithExtension' but returns which element of the search path
-- the file was found in, and the file path relative to that base directory.
--
findFileWithExtension' :: [String]
-> [FilePath]
-> FilePath
-> IO (Maybe (FilePath, FilePath))
findFileWithExtension' extensions searchPath baseName =
findFirstFile (uncurry (</>))
[ (path, baseName <.> ext)
| path <- nub searchPath
, ext <- nub extensions ]
findFirstFile :: (a -> FilePath) -> [a] -> IO (Maybe a)
findFirstFile file = findFirst
where findFirst [] = return Nothing
findFirst (x:xs) = do exists <- doesFileExist (file x)
if exists
then return (Just x)
else findFirst xs
findAllFiles :: (a -> FilePath) -> [a] -> IO [a]
findAllFiles file = filterM (doesFileExist . file)
-- | Finds the files corresponding to a list of Haskell module names.
--
-- As 'findModuleFile' but for a list of module names.
--
findModuleFiles :: [FilePath] -- ^ build prefix (location of objects)
-> [String] -- ^ search suffixes
-> [ModuleName] -- ^ modules
-> IO [(FilePath, FilePath)]
findModuleFiles searchPath extensions moduleNames =
mapM (findModuleFile searchPath extensions) moduleNames
-- | Find the file corresponding to a Haskell module name.
--
-- This is similar to 'findFileWithExtension'' but specialised to a module
-- name. The function fails if the file corresponding to the module is missing.
--
findModuleFile :: [FilePath] -- ^ build prefix (location of objects)
-> [String] -- ^ search suffixes
-> ModuleName -- ^ module
-> IO (FilePath, FilePath)
findModuleFile searchPath extensions moduleName =
maybe notFound return
=<< findFileWithExtension' extensions searchPath
(ModuleName.toFilePath moduleName)
where
notFound = die $ "Error: Could not find module: " ++ display moduleName
++ " with any suffix: " ++ show extensions
++ " in the search path: " ++ show searchPath
-- | List all the files in a directory and all subdirectories.
--
-- The order places files in sub-directories after all the files in their
-- parent directories. The list is generated lazily so is not well defined if
-- the source directory structure changes before the list is used.
--
getDirectoryContentsRecursive :: FilePath -> IO [FilePath]
getDirectoryContentsRecursive topdir = recurseDirectories [""]
where
recurseDirectories :: [FilePath] -> IO [FilePath]
recurseDirectories [] = return []
recurseDirectories (dir:dirs) = unsafeInterleaveIO $ do
(files, dirs') <- collect [] [] =<< getDirectoryContents (topdir </> dir)
files' <- recurseDirectories (dirs' ++ dirs)
return (files ++ files')
where
collect files dirs' [] = return (reverse files
,reverse dirs')
collect files dirs' (entry:entries) | ignore entry
= collect files dirs' entries
collect files dirs' (entry:entries) = do
let dirEntry = dir </> entry
isDirectory <- doesDirectoryExist (topdir </> dirEntry)
if isDirectory
then collect files (dirEntry:dirs') entries
else collect (dirEntry:files) dirs' entries
ignore ['.'] = True
ignore ['.', '.'] = True
ignore _ = False
------------------------
-- Environment variables
-- | Is this directory in the system search path?
isInSearchPath :: FilePath -> IO Bool
isInSearchPath path = fmap (elem path) getSearchPath
addLibraryPath :: OS
-> [FilePath]
-> [(String,String)]
-> [(String,String)]
addLibraryPath os paths = addEnv
where
pathsString = intercalate [searchPathSeparator] paths
ldPath = case os of
OSX -> "DYLD_LIBRARY_PATH"
_ -> "LD_LIBRARY_PATH"
addEnv [] = [(ldPath,pathsString)]
addEnv ((key,value):xs)
| key == ldPath =
if null value
then (key,pathsString):xs
else (key,value ++ (searchPathSeparator:pathsString)):xs
| otherwise = (key,value):addEnv xs
----------------
-- File globbing
data FileGlob
-- | No glob at all, just an ordinary file
= NoGlob FilePath
-- | dir prefix and extension, like @\"foo\/bar\/\*.baz\"@ corresponds to
-- @FileGlob \"foo\/bar\" \".baz\"@
| FileGlob FilePath String
parseFileGlob :: FilePath -> Maybe FileGlob
parseFileGlob filepath = case splitExtensions filepath of
(filepath', ext) -> case splitFileName filepath' of
(dir, "*") | '*' `elem` dir
|| '*' `elem` ext
|| null ext -> Nothing
| null dir -> Just (FileGlob "." ext)
| otherwise -> Just (FileGlob dir ext)
_ | '*' `elem` filepath -> Nothing
| otherwise -> Just (NoGlob filepath)
matchFileGlob :: FilePath -> IO [FilePath]
matchFileGlob = matchDirFileGlob "."
matchDirFileGlob :: FilePath -> FilePath -> IO [FilePath]
matchDirFileGlob dir filepath = case parseFileGlob filepath of
Nothing -> die $ "invalid file glob '" ++ filepath
++ "'. Wildcards '*' are only allowed in place of the file"
++ " name, not in the directory name or file extension."
++ " If a wildcard is used it must be with an file extension."
Just (NoGlob filepath') -> return [filepath']
Just (FileGlob dir' ext) -> do
files <- getDirectoryContents (dir </> dir')
case [ dir' </> file
| file <- files
, let (name, ext') = splitExtensions file
, not (null name) && ext' == ext ] of
[] -> die $ "filepath wildcard '" ++ filepath
++ "' does not match any files."
matches -> return matches
--------------------
-- Modification time
-- | Compare the modification times of two files to see if the first is newer
-- than the second. The first file must exist but the second need not.
-- The expected use case is when the second file is generated using the first.
-- In this use case, if the result is True then the second file is out of date.
--
moreRecentFile :: FilePath -> FilePath -> IO Bool
moreRecentFile a b = do
exists <- doesFileExist b
if not exists
then return True
else do tb <- getModificationTime b
ta <- getModificationTime a
return (ta > tb)
-- | Like 'moreRecentFile', but also checks that the first file exists.
existsAndIsMoreRecentThan :: FilePath -> FilePath -> IO Bool
existsAndIsMoreRecentThan a b = do
exists <- doesFileExist a
if not exists
then return False
else a `moreRecentFile` b
----------------------------------------
-- Copying and installing files and dirs
-- | Same as 'createDirectoryIfMissing' but logs at higher verbosity levels.
--
createDirectoryIfMissingVerbose :: Verbosity
-> Bool -- ^ Create its parents too?
-> FilePath
-> IO ()
createDirectoryIfMissingVerbose verbosity create_parents path0
| create_parents = createDirs (parents path0)
| otherwise = createDirs (take 1 (parents path0))
where
parents = reverse . scanl1 (</>) . splitDirectories . normalise
createDirs [] = return ()
createDirs (dir:[]) = createDir dir throwIO
createDirs (dir:dirs) =
createDir dir $ \_ -> do
createDirs dirs
createDir dir throwIO
createDir :: FilePath -> (IOException -> IO ()) -> IO ()
createDir dir notExistHandler = do
r <- tryIO $ createDirectoryVerbose verbosity dir
case (r :: Either IOException ()) of
Right () -> return ()
Left e
| isDoesNotExistError e -> notExistHandler e
-- createDirectory (and indeed POSIX mkdir) does not distinguish
-- between a dir already existing and a file already existing. So we
-- check for it here. Unfortunately there is a slight race condition
-- here, but we think it is benign. It could report an exception in
-- the case that the dir did exist but another process deletes the
-- directory and creates a file in its place before we can check
-- that the directory did indeed exist.
| isAlreadyExistsError e -> (do
isDir <- doesDirectoryExist dir
if isDir then return ()
else throwIO e
) `catchIO` ((\_ -> return ()) :: IOException -> IO ())
| otherwise -> throwIO e
createDirectoryVerbose :: Verbosity -> FilePath -> IO ()
createDirectoryVerbose verbosity dir = do
info verbosity $ "creating " ++ dir
createDirectory dir
setDirOrdinary dir
-- | Copies a file without copying file permissions. The target file is created
-- with default permissions. Any existing target file is replaced.
--
-- At higher verbosity levels it logs an info message.
--
copyFileVerbose :: Verbosity -> FilePath -> FilePath -> IO ()
copyFileVerbose verbosity src dest = do
info verbosity ("copy " ++ src ++ " to " ++ dest)
copyFile src dest
-- | Install an ordinary file. This is like a file copy but the permissions
-- are set appropriately for an installed file. On Unix it is \"-rw-r--r--\"
-- while on Windows it uses the default permissions for the target directory.
--
installOrdinaryFile :: Verbosity -> FilePath -> FilePath -> IO ()
installOrdinaryFile verbosity src dest = do
info verbosity ("Installing " ++ src ++ " to " ++ dest)
copyOrdinaryFile src dest
-- | Install an executable file. This is like a file copy but the permissions
-- are set appropriately for an installed file. On Unix it is \"-rwxr-xr-x\"
-- while on Windows it uses the default permissions for the target directory.
--
installExecutableFile :: Verbosity -> FilePath -> FilePath -> IO ()
installExecutableFile verbosity src dest = do
info verbosity ("Installing executable " ++ src ++ " to " ++ dest)
copyExecutableFile src dest
-- | Install a file that may or not be executable, preserving permissions.
installMaybeExecutableFile :: Verbosity -> FilePath -> FilePath -> IO ()
installMaybeExecutableFile verbosity src dest = do
perms <- getPermissions src
if (executable perms) --only checks user x bit
then installExecutableFile verbosity src dest
else installOrdinaryFile verbosity src dest
-- | Given a relative path to a file, copy it to the given directory, preserving
-- the relative path and creating the parent directories if needed.
copyFileTo :: Verbosity -> FilePath -> FilePath -> IO ()
copyFileTo verbosity dir file = do
let targetFile = dir </> file
createDirectoryIfMissingVerbose verbosity True (takeDirectory targetFile)
installOrdinaryFile verbosity file targetFile
-- | Common implementation of 'copyFiles', 'installOrdinaryFiles',
-- 'installExecutableFiles' and 'installMaybeExecutableFiles'.
copyFilesWith :: (Verbosity -> FilePath -> FilePath -> IO ())
-> Verbosity -> FilePath -> [(FilePath, FilePath)] -> IO ()
copyFilesWith doCopy verbosity targetDir srcFiles = do
-- Create parent directories for everything
let dirs = map (targetDir </>) . nub . map (takeDirectory . snd) $ srcFiles
mapM_ (createDirectoryIfMissingVerbose verbosity True) dirs
-- Copy all the files
sequence_ [ let src = srcBase </> srcFile
dest = targetDir </> srcFile
in doCopy verbosity src dest
| (srcBase, srcFile) <- srcFiles ]
-- | Copies a bunch of files to a target directory, preserving the directory
-- structure in the target location. The target directories are created if they
-- do not exist.
--
-- The files are identified by a pair of base directory and a path relative to
-- that base. It is only the relative part that is preserved in the
-- destination.
--
-- For example:
--
-- > copyFiles normal "dist/src"
-- > [("", "src/Foo.hs"), ("dist/build/", "src/Bar.hs")]
--
-- This would copy \"src\/Foo.hs\" to \"dist\/src\/src\/Foo.hs\" and
-- copy \"dist\/build\/src\/Bar.hs\" to \"dist\/src\/src\/Bar.hs\".
--
-- This operation is not atomic. Any IO failure during the copy (including any
-- missing source files) leaves the target in an unknown state so it is best to
-- use it with a freshly created directory so that it can be simply deleted if
-- anything goes wrong.
--
copyFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)] -> IO ()
copyFiles = copyFilesWith copyFileVerbose
-- | This is like 'copyFiles' but uses 'installOrdinaryFile'.
--
installOrdinaryFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)] -> IO ()
installOrdinaryFiles = copyFilesWith installOrdinaryFile
-- | This is like 'copyFiles' but uses 'installExecutableFile'.
--
installExecutableFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)]
-> IO ()
installExecutableFiles = copyFilesWith installExecutableFile
-- | This is like 'copyFiles' but uses 'installMaybeExecutableFile'.
--
installMaybeExecutableFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)]
-> IO ()
installMaybeExecutableFiles = copyFilesWith installMaybeExecutableFile
-- | This installs all the files in a directory to a target location,
-- preserving the directory layout. All the files are assumed to be ordinary
-- rather than executable files.
--
installDirectoryContents :: Verbosity -> FilePath -> FilePath -> IO ()
installDirectoryContents verbosity srcDir destDir = do
info verbosity ("copy directory '" ++ srcDir ++ "' to '" ++ destDir ++ "'.")
srcFiles <- getDirectoryContentsRecursive srcDir
installOrdinaryFiles verbosity destDir [ (srcDir, f) | f <- srcFiles ]
-- | Recursively copy the contents of one directory to another path.
copyDirectoryRecursive :: Verbosity -> FilePath -> FilePath -> IO ()
copyDirectoryRecursive verbosity srcDir destDir = do
info verbosity ("copy directory '" ++ srcDir ++ "' to '" ++ destDir ++ "'.")
srcFiles <- getDirectoryContentsRecursive srcDir
copyFilesWith (const copyFile) verbosity destDir [ (srcDir, f) | f <- srcFiles ]
-------------------
-- File permissions
-- | Like 'doesFileExist', but also checks that the file is executable.
doesExecutableExist :: FilePath -> IO Bool
doesExecutableExist f = do
exists <- doesFileExist f
if exists
then do perms <- getPermissions f
return (executable perms)
else return False
---------------------------------
-- Deprecated file copy functions
{-# DEPRECATED smartCopySources
"Use findModuleFiles and copyFiles or installOrdinaryFiles" #-}
smartCopySources :: Verbosity -> [FilePath] -> FilePath
-> [ModuleName] -> [String] -> IO ()
smartCopySources verbosity searchPath targetDir moduleNames extensions =
findModuleFiles searchPath extensions moduleNames
>>= copyFiles verbosity targetDir
{-# DEPRECATED copyDirectoryRecursiveVerbose
"You probably want installDirectoryContents instead" #-}
copyDirectoryRecursiveVerbose :: Verbosity -> FilePath -> FilePath -> IO ()
copyDirectoryRecursiveVerbose verbosity srcDir destDir = do
info verbosity ("copy directory '" ++ srcDir ++ "' to '" ++ destDir ++ "'.")
srcFiles <- getDirectoryContentsRecursive srcDir
copyFiles verbosity destDir [ (srcDir, f) | f <- srcFiles ]
---------------------------
-- Temporary files and dirs
-- | Advanced options for 'withTempFile' and 'withTempDirectory'.
data TempFileOptions = TempFileOptions {
optKeepTempFiles :: Bool -- ^ Keep temporary files?
}
defaultTempFileOptions :: TempFileOptions
defaultTempFileOptions = TempFileOptions { optKeepTempFiles = False }
-- | Use a temporary filename that doesn't already exist.
--
withTempFile :: FilePath -- ^ Temp dir to create the file in
-> String -- ^ File name template. See 'openTempFile'.
-> (FilePath -> Handle -> IO a) -> IO a
withTempFile tmpDir template action =
withTempFileEx defaultTempFileOptions tmpDir template action
-- | A version of 'withTempFile' that additionally takes a 'TempFileOptions'
-- argument.
withTempFileEx :: TempFileOptions
-> FilePath -- ^ Temp dir to create the file in
-> String -- ^ File name template. See 'openTempFile'.
-> (FilePath -> Handle -> IO a) -> IO a
withTempFileEx opts tmpDir template action =
Exception.bracket
(openTempFile tmpDir template)
(\(name, handle) -> do hClose handle
unless (optKeepTempFiles opts) $ removeFile name)
(uncurry action)
-- | Create and use a temporary directory.
--
-- Creates a new temporary directory inside the given directory, making use
-- of the template. The temp directory is deleted after use. For example:
--
-- > withTempDirectory verbosity "src" "sdist." $ \tmpDir -> do ...
--
-- The @tmpDir@ will be a new subdirectory of the given directory, e.g.
-- @src/sdist.342@.
--
withTempDirectory :: Verbosity
-> FilePath -> String -> (FilePath -> IO a) -> IO a
withTempDirectory verbosity targetDir template =
withTempDirectoryEx verbosity defaultTempFileOptions targetDir template
-- | A version of 'withTempDirectory' that additionally takes a
-- 'TempFileOptions' argument.
withTempDirectoryEx :: Verbosity
-> TempFileOptions
-> FilePath -> String -> (FilePath -> IO a) -> IO a
withTempDirectoryEx _verbosity opts targetDir template =
Exception.bracket
(createTempDirectory targetDir template)
(unless (optKeepTempFiles opts) . removeDirectoryRecursive)
-----------------------------------
-- Safely reading and writing files
-- | Gets the contents of a file, but guarantee that it gets closed.
--
-- The file is read lazily but if it is not fully consumed by the action then
-- the remaining input is truncated and the file is closed.
--
withFileContents :: FilePath -> (String -> IO a) -> IO a
withFileContents name action =
Exception.bracket (openFile name ReadMode) hClose
(\hnd -> hGetContents hnd >>= action)
-- | Writes a file atomically.
--
-- The file is either written successfully or an IO exception is raised and
-- the original file is left unchanged.
--
-- On windows it is not possible to delete a file that is open by a process.
-- This case will give an IO exception but the atomic property is not affected.
--
writeFileAtomic :: FilePath -> BS.ByteString -> IO ()
writeFileAtomic targetPath content = do
let (targetDir, targetFile) = splitFileName targetPath
Exception.bracketOnError
(openBinaryTempFileWithDefaultPermissions targetDir $ targetFile <.> "tmp")
(\(tmpPath, handle) -> hClose handle >> removeFile tmpPath)
(\(tmpPath, handle) -> do
BS.hPut handle content
hClose handle
renameFile tmpPath targetPath)
-- | Write a file but only if it would have new content. If we would be writing
-- the same as the existing content then leave the file as is so that we do not
-- update the file's modification time.
--
-- NB: the file is assumed to be ASCII-encoded.
rewriteFile :: FilePath -> String -> IO ()
rewriteFile path newContent =
flip catchIO mightNotExist $ do
existingContent <- readFile path
_ <- evaluate (length existingContent)
unless (existingContent == newContent) $
writeFileAtomic path (BS.Char8.pack newContent)
where
mightNotExist e | isDoesNotExistError e = writeFileAtomic path
(BS.Char8.pack newContent)
| otherwise = ioError e
-- | The path name that represents the current directory.
-- In Unix, it's @\".\"@, but this is system-specific.
-- (E.g. AmigaOS uses the empty string @\"\"@ for the current directory.)
currentDir :: FilePath
currentDir = "."
shortRelativePath :: FilePath -> FilePath -> FilePath
shortRelativePath from to =
case dropCommonPrefix (splitDirectories from) (splitDirectories to) of
(stuff, path) -> joinPath (map (const "..") stuff ++ path)
where
dropCommonPrefix :: Eq a => [a] -> [a] -> ([a],[a])
dropCommonPrefix (x:xs) (y:ys)
| x == y = dropCommonPrefix xs ys
dropCommonPrefix xs ys = (xs,ys)
-- ------------------------------------------------------------
-- * Finding the description file
-- ------------------------------------------------------------
-- |Package description file (/pkgname/@.cabal@)
defaultPackageDesc :: Verbosity -> IO FilePath
defaultPackageDesc _verbosity = tryFindPackageDesc currentDir
-- |Find a package description file in the given directory. Looks for
-- @.cabal@ files.
findPackageDesc :: FilePath -- ^Where to look
-> IO (Either String FilePath) -- ^<pkgname>.cabal
findPackageDesc dir
= do files <- getDirectoryContents dir
-- to make sure we do not mistake a ~/.cabal/ dir for a <pkgname>.cabal
-- file we filter to exclude dirs and null base file names:
cabalFiles <- filterM doesFileExist
[ dir </> file
| file <- files
, let (name, ext) = splitExtension file
, not (null name) && ext == ".cabal" ]
case cabalFiles of
[] -> return (Left noDesc)
[cabalFile] -> return (Right cabalFile)
multiple -> return (Left $ multiDesc multiple)
where
noDesc :: String
noDesc = "No cabal file found.\n"
++ "Please create a package description file <pkgname>.cabal"
multiDesc :: [String] -> String
multiDesc l = "Multiple cabal files found.\n"
++ "Please use only one of: "
++ intercalate ", " l
-- |Like 'findPackageDesc', but calls 'die' in case of error.
tryFindPackageDesc :: FilePath -> IO FilePath
tryFindPackageDesc dir = either die return =<< findPackageDesc dir
-- |Optional auxiliary package information file (/pkgname/@.buildinfo@)
defaultHookedPackageDesc :: IO (Maybe FilePath)
defaultHookedPackageDesc = findHookedPackageDesc currentDir
-- |Find auxiliary package information in the given directory.
-- Looks for @.buildinfo@ files.
findHookedPackageDesc
:: FilePath -- ^Directory to search
-> IO (Maybe FilePath) -- ^/dir/@\/@/pkgname/@.buildinfo@, if present
findHookedPackageDesc dir = do
files <- getDirectoryContents dir
buildInfoFiles <- filterM doesFileExist
[ dir </> file
| file <- files
, let (name, ext) = splitExtension file
, not (null name) && ext == buildInfoExt ]
case buildInfoFiles of
[] -> return Nothing
[f] -> return (Just f)
_ -> die ("Multiple files with extension " ++ buildInfoExt)
buildInfoExt :: String
buildInfoExt = ".buildinfo"
-- ------------------------------------------------------------
-- * Unicode stuff
-- ------------------------------------------------------------
-- This is a modification of the UTF8 code from gtk2hs and the
-- utf8-string package.
fromUTF8 :: String -> String
fromUTF8 [] = []
fromUTF8 (c:cs)
| c <= '\x7F' = c : fromUTF8 cs
| c <= '\xBF' = replacementChar : fromUTF8 cs
| c <= '\xDF' = twoBytes c cs
| c <= '\xEF' = moreBytes 3 0x800 cs (ord c .&. 0xF)
| c <= '\xF7' = moreBytes 4 0x10000 cs (ord c .&. 0x7)
| c <= '\xFB' = moreBytes 5 0x200000 cs (ord c .&. 0x3)
| c <= '\xFD' = moreBytes 6 0x4000000 cs (ord c .&. 0x1)
| otherwise = replacementChar : fromUTF8 cs
where
twoBytes c0 (c1:cs')
| ord c1 .&. 0xC0 == 0x80
= let d = ((ord c0 .&. 0x1F) `shiftL` 6)
.|. (ord c1 .&. 0x3F)
in if d >= 0x80
then chr d : fromUTF8 cs'
else replacementChar : fromUTF8 cs'
twoBytes _ cs' = replacementChar : fromUTF8 cs'
moreBytes :: Int -> Int -> [Char] -> Int -> [Char]
moreBytes 1 overlong cs' acc
| overlong <= acc && acc <= 0x10FFFF
&& (acc < 0xD800 || 0xDFFF < acc)
&& (acc < 0xFFFE || 0xFFFF < acc)
= chr acc : fromUTF8 cs'
| otherwise
= replacementChar : fromUTF8 cs'
moreBytes byteCount overlong (cn:cs') acc
| ord cn .&. 0xC0 == 0x80
= moreBytes (byteCount-1) overlong cs'
((acc `shiftL` 6) .|. ord cn .&. 0x3F)
moreBytes _ _ cs' _
= replacementChar : fromUTF8 cs'
replacementChar = '\xfffd'
toUTF8 :: String -> String
toUTF8 [] = []
toUTF8 (c:cs)
| c <= '\x07F' = c
: toUTF8 cs
| c <= '\x7FF' = chr (0xC0 .|. (w `shiftR` 6))
: chr (0x80 .|. (w .&. 0x3F))
: toUTF8 cs
| c <= '\xFFFF'= chr (0xE0 .|. (w `shiftR` 12))
: chr (0x80 .|. ((w `shiftR` 6) .&. 0x3F))
: chr (0x80 .|. (w .&. 0x3F))
: toUTF8 cs
| otherwise = chr (0xf0 .|. (w `shiftR` 18))
: chr (0x80 .|. ((w `shiftR` 12) .&. 0x3F))
: chr (0x80 .|. ((w `shiftR` 6) .&. 0x3F))
: chr (0x80 .|. (w .&. 0x3F))
: toUTF8 cs
where w = ord c
-- | Whether BOM is at the beginning of the input
startsWithBOM :: String -> Bool
startsWithBOM ('\xFEFF':_) = True
startsWithBOM _ = False
-- | Check whether a file has Unicode byte order mark (BOM).
fileHasBOM :: FilePath -> IO Bool
fileHasBOM f = fmap (startsWithBOM . fromUTF8)
. hGetContents =<< openBinaryFile f ReadMode
-- | Ignore a Unicode byte order mark (BOM) at the beginning of the input
--
ignoreBOM :: String -> String
ignoreBOM ('\xFEFF':string) = string
ignoreBOM string = string
-- | Reads a UTF8 encoded text file as a Unicode String
--
-- Reads lazily using ordinary 'readFile'.
--
readUTF8File :: FilePath -> IO String
readUTF8File f = fmap (ignoreBOM . fromUTF8)
. hGetContents =<< openBinaryFile f ReadMode
-- | Reads a UTF8 encoded text file as a Unicode String
--
-- Same behaviour as 'withFileContents'.
--
withUTF8FileContents :: FilePath -> (String -> IO a) -> IO a
withUTF8FileContents name action =
Exception.bracket
(openBinaryFile name ReadMode)
hClose
(\hnd -> hGetContents hnd >>= action . ignoreBOM . fromUTF8)
-- | Writes a Unicode String as a UTF8 encoded text file.
--
-- Uses 'writeFileAtomic', so provides the same guarantees.
--
writeUTF8File :: FilePath -> String -> IO ()
writeUTF8File path = writeFileAtomic path . BS.Char8.pack . toUTF8
-- | Fix different systems silly line ending conventions
normaliseLineEndings :: String -> String
normaliseLineEndings [] = []
normaliseLineEndings ('\r':'\n':s) = '\n' : normaliseLineEndings s -- windows
normaliseLineEndings ('\r':s) = '\n' : normaliseLineEndings s -- old OS X
normaliseLineEndings ( c :s) = c : normaliseLineEndings s
-- ------------------------------------------------------------
-- * Common utils
-- ------------------------------------------------------------
-- | @dropWhileEndLE p@ is equivalent to @reverse . dropWhile p . reverse@, but
-- quite a bit faster. The difference between "Data.List.dropWhileEnd" and this
-- version is that the one in "Data.List" is strict in elements, but spine-lazy,
-- while this one is spine-strict but lazy in elements. That's what @LE@ stands
-- for - "lazy in elements".
--
-- Example:
--
-- @
-- > tail $ Data.List.dropWhileEnd (<3) [undefined, 5, 4, 3, 2, 1]
-- *** Exception: Prelude.undefined
-- > tail $ dropWhileEndLE (<3) [undefined, 5, 4, 3, 2, 1]
-- [5,4,3]
-- > take 3 $ Data.List.dropWhileEnd (<3) [5, 4, 3, 2, 1, undefined]
-- [5,4,3]
-- > take 3 $ dropWhileEndLE (<3) [5, 4, 3, 2, 1, undefined]
-- *** Exception: Prelude.undefined
-- @
dropWhileEndLE :: (a -> Bool) -> [a] -> [a]
dropWhileEndLE p = foldr (\x r -> if null r && p x then [] else x:r) []
-- | @takeWhileEndLE p@ is equivalent to @reverse . takeWhile p . reverse@, but
-- is usually faster (as well as being easier to read).
takeWhileEndLE :: (a -> Bool) -> [a] -> [a]
takeWhileEndLE p = fst . foldr go ([], False)
where
go x (rest, done)
| not done && p x = (x:rest, False)
| otherwise = (rest, True)
-- | Like "Data.List.nub", but has @O(n log n)@ complexity instead of
-- @O(n^2)@. Code for 'ordNub' and 'listUnion' taken from Niklas Hambüchen's
-- <http://github.com/nh2/haskell-ordnub ordnub> package.
ordNub :: (Ord a) => [a] -> [a]
ordNub l = go Set.empty l
where
go _ [] = []
go s (x:xs) = if x `Set.member` s then go s xs
else x : go (Set.insert x s) xs
-- | Like "Data.List.union", but has @O(n log n)@ complexity instead of
-- @O(n^2)@.
listUnion :: (Ord a) => [a] -> [a] -> [a]
listUnion a b = a ++ ordNub (filter (`Set.notMember` aSet) b)
where
aSet = Set.fromList a
-- | A right-biased version of 'ordNub'.
--
-- Example:
--
-- @
-- > ordNub [1,2,1]
-- [1,2]
-- > ordNubRight [1,2,1]
-- [2,1]
-- @
ordNubRight :: (Ord a) => [a] -> [a]
ordNubRight = fst . foldr go ([], Set.empty)
where
go x p@(l, s) = if x `Set.member` s then p
else (x:l, Set.insert x s)
-- | A right-biased version of 'listUnion'.
--
-- Example:
--
-- @
-- > listUnion [1,2,3,4,3] [2,1,1]
-- [1,2,3,4,3]
-- > listUnionRight [1,2,3,4,3] [2,1,1]
-- [4,3,2,1,1]
-- @
listUnionRight :: (Ord a) => [a] -> [a] -> [a]
listUnionRight a b = ordNubRight (filter (`Set.notMember` bSet) a) ++ b
where
bSet = Set.fromList b
equating :: Eq a => (b -> a) -> b -> b -> Bool
equating p x y = p x == p y
comparing :: Ord a => (b -> a) -> b -> b -> Ordering
comparing p x y = p x `compare` p y
isInfixOf :: String -> String -> Bool
isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
lowercase :: String -> String
lowercase = map Char.toLower
| trskop/cabal | Cabal/Distribution/Simple/Utils.hs | bsd-3-clause | 53,840 | 0 | 21 | 14,657 | 11,503 | 6,072 | 5,431 | 887 | 7 |
module Main
( main
) where
import Test.Tasty
import qualified UnitTests.Distribution.Compat.CreatePipe
import qualified UnitTests.Distribution.Compat.ReadP
import qualified UnitTests.Distribution.Simple.Program.Internal
import qualified UnitTests.Distribution.Utils.NubList
tests :: TestTree
tests = testGroup "Unit Tests" $
[ testGroup "Distribution.Compat.ReadP"
UnitTests.Distribution.Compat.ReadP.tests
, testGroup "Distribution.Compat.CreatePipe"
UnitTests.Distribution.Compat.CreatePipe.tests
, testGroup "Distribution.Simple.Program.Internal"
UnitTests.Distribution.Simple.Program.Internal.tests
, testGroup "Distribution.Utils.NubList"
UnitTests.Distribution.Utils.NubList.tests
]
main :: IO ()
main = defaultMain tests
| corngood/cabal | Cabal/tests/UnitTests.hs | bsd-3-clause | 792 | 0 | 8 | 118 | 135 | 85 | 50 | 19 | 1 |
{-# LANGUAGE OverloadedStrings, CPP #-}
-- | High-ish level bindings to the HTML5 audio tag and JS API.
module Haste.Audio (
module Events,
Audio, AudioSettings (..), AudioType (..), AudioSource (..),
AudioPreload (..), AudioState (..), Seek (..),
defaultAudioSettings,
mkSource, newAudio, setSource,
getState,
setMute, isMute, toggleMute,
setLooping, isLooping, toggleLooping,
getVolume, setVolume, modVolume,
play, pause, stop, togglePlaying,
seek, getDuration, getCurrentTime
) where
import Haste.Audio.Events as Events
import Haste.DOM.JSString
import Haste.Foreign
import Haste.Prim.JSType
import Haste.Prim
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Monad
import Control.Monad.IO.Class
import Data.String
-- | Represents an audio player.
data Audio = Audio Elem
instance IsElem Audio where
elemOf (Audio e) = e
fromElem e = do
tn <- getProp e "tagName"
return $ case tn of
"AUDIO" -> Just $ Audio e
_ -> Nothing
data AudioState = Playing | Paused | Ended
deriving (Show, Eq)
data AudioType = MP3 | OGG | WAV
deriving (Show, Eq)
data AudioSource = AudioSource !AudioType !JSString
deriving (Show, Eq)
data AudioPreload = None | Metadata | Auto
deriving Eq
data Seek = Start | End | Seconds Double
deriving Eq
instance JSType AudioPreload where
toJSString None = "none"
toJSString Metadata = "metadata"
toJSString Auto = "auto"
fromJSString "none" = Just None
fromJSString "metadata" = Just Metadata
fromJSString "auto" = Just Auto
fromJSString _ = Nothing
data AudioSettings = AudioSettings {
-- | Show controls?
-- Default: False
audioControls :: !Bool,
-- | Immediately start playing?
-- Default: False
audioAutoplay :: !Bool,
-- | Initially looping?
-- Default: False
audioLooping :: !Bool,
-- | How much audio to preload.
-- Default: Auto
audioPreload :: !AudioPreload,
-- | Initially muted?
-- Default: False
audioMuted :: !Bool,
-- | Initial volume
-- Default: 0
audioVolume :: !Double
}
defaultAudioSettings :: AudioSettings
defaultAudioSettings = AudioSettings {
audioControls = False,
audioAutoplay = False,
audioLooping = False,
audioPreload = Auto,
audioMuted = False,
audioVolume = 0
}
-- | Create an audio source with automatically detected media type, based on
-- the given URL's file extension.
-- Returns Nothing if the given URL has an unrecognized media type.
mkSource :: JSString -> Maybe AudioSource
mkSource url =
case take 3 $ reverse $ fromJSStr url of
"3pm" -> Just $ AudioSource MP3 url
"ggo" -> Just $ AudioSource OGG url
"vaw" -> Just $ AudioSource WAV url
_ -> Nothing
instance IsString AudioSource where
fromString s =
case mkSource $ Data.String.fromString s of
Just src -> src
_ -> error $ "Not a valid audio source: " ++ s
mimeStr :: AudioType -> JSString
mimeStr MP3 = "audio/mpeg"
mimeStr OGG = "audio/ogg"
mimeStr WAV = "audio/wav"
-- | Create a new audio element.
newAudio :: MonadIO m => AudioSettings -> [AudioSource] -> m Audio
newAudio cfg sources = liftIO $ do
srcs <- forM sources $ \(AudioSource t url) -> do
newElem "source" `with` ["type" =: mimeStr t, "src" =: toJSString url]
Audio <$> newElem "audio" `with` [
"controls" =: falseAsEmpty (audioControls cfg),
"autoplay" =: falseAsEmpty (audioAutoplay cfg),
"loop" =: falseAsEmpty (audioLooping cfg),
"muted" =: falseAsEmpty (audioMuted cfg),
"volume" =: toJSString (audioVolume cfg),
"preload" =: toJSString (audioPreload cfg),
children srcs
]
-- | Returns "true" or "", depending on the given boolean.
falseAsEmpty :: Bool -> JSString
falseAsEmpty True = "true"
falseAsEmpty _ = ""
-- | (Un)mute the given audio object.
setMute :: MonadIO m => Audio -> Bool -> m ()
setMute (Audio e) = setAttr e "muted" . falseAsEmpty
-- | Is the given audio object muted?
isMute :: MonadIO m => Audio -> m Bool
isMute (Audio e) = liftIO $ maybe False id . fromJSString <$> getProp e "muted"
-- | Mute/unmute.
toggleMute :: MonadIO m => Audio -> m ()
toggleMute a = isMute a >>= setMute a . not
-- | Set whether the given sound should loop upon completion or not.
setLooping :: MonadIO m => Audio -> Bool -> m ()
setLooping (Audio e) = setAttr e "loop" . falseAsEmpty
-- | Is the given audio object looping?
isLooping :: MonadIO m => Audio -> m Bool
isLooping (Audio e) =
liftIO $ maybe False id . fromJSString <$> getProp e "looping"
-- | Toggle looping on/off.
toggleLooping :: MonadIO m => Audio -> m ()
toggleLooping a = isLooping a >>= setLooping a . not
-- | Starts playing audio from the given element.
play :: MonadIO m => Audio -> m ()
play a@(Audio e) = do
st <- getState a
when (st == Ended) $ seek a Start
liftIO $ play' e
where
play' :: Elem -> IO ()
play' = ffi "(function(x){x.play();})"
-- | Get the current state of the given audio object.
getState :: MonadIO m => Audio -> m AudioState
getState (Audio e) = liftIO $ do
ended <- maybe False id . fromJSString <$> getProp e "ended"
if ended
then return Ended
else maybe Playing paused . fromJSString <$> getProp e "paused"
where
paused True = Paused
paused _ = Playing
-- | Pause the given audio element.
pause :: MonadIO m => Audio -> m ()
pause (Audio e) = liftIO $ pause' e
pause' :: Elem -> IO ()
pause' = ffi "(function(x){x.pause();})"
-- | If playing, stop. Otherwise, start playing.
togglePlaying :: MonadIO m => Audio -> m ()
togglePlaying a = do
st <- getState a
case st of
Playing -> pause a
Ended -> seek a Start >> play a
Paused -> play a
-- | Stop playing a track, and seek back to its beginning.
stop :: MonadIO m => Audio -> m ()
stop a = pause a >> seek a Start
-- | Get the volume for the given audio element as a value between 0 and 1.
getVolume :: MonadIO m => Audio -> m Double
getVolume (Audio e) = liftIO $ maybe 0 id . fromJSString <$> getProp e "volume"
-- | Set the volume for the given audio element. The value will be clamped to
-- [0, 1].
setVolume :: MonadIO m => Audio -> Double -> m ()
setVolume (Audio e) = setProp e "volume" . toJSString . clamp
-- | Modify the volume for the given audio element. The resulting volume will
-- be clamped to [0, 1].
modVolume :: MonadIO m => Audio -> Double -> m ()
modVolume a diff = getVolume a >>= setVolume a . (+ diff)
-- | Clamp a value to [0, 1].
clamp :: Double -> Double
clamp = max 0 . min 1
-- | Seek to the specified time.
seek :: MonadIO m => Audio -> Seek -> m ()
seek a@(Audio e) st = liftIO $ do
case st of
Start -> seek' e 0
End -> getDuration a >>= seek' e
Seconds s -> seek' e s
where
seek' :: Elem -> Double -> IO ()
seek' = ffi "(function(e,t) {e.currentTime = t;})"
-- | Get the duration of the loaded sound, in seconds.
getDuration :: MonadIO m => Audio -> m Double
getDuration (Audio e) = do
dur <- getProp e "duration"
case fromJSString dur of
Just d -> return d
_ -> return 0
-- | Get the current play time of the loaded sound, in seconds.
getCurrentTime :: MonadIO m => Audio -> m Double
getCurrentTime (Audio e) = do
dur <- getProp e "currentTime"
case fromJSString dur of
Just d -> return d
_ -> return 0
-- | Set the source of the given audio element.
setSource :: MonadIO m => Audio -> AudioSource -> m ()
setSource (Audio e) (AudioSource _ url) = setProp e "src" (toJSString url)
| jtojnar/haste-compiler | libraries/haste-lib/src/Haste/Audio.hs | bsd-3-clause | 7,618 | 0 | 16 | 1,807 | 2,208 | 1,133 | 1,075 | 181 | 4 |
import Control.Exception as E
import Data.Int
main :: IO ()
main = do putStrLn "Int8"
mapM_ p =<< (f :: IO [Either Int8 String])
putStrLn "Int16"
mapM_ p =<< (f :: IO [Either Int16 String])
putStrLn "Int32"
mapM_ p =<< (f :: IO [Either Int32 String])
putStrLn "Int64"
mapM_ p =<< (f :: IO [Either Int64 String])
putStrLn "Int"
mapM_ p =<< (f :: IO [Either Int String])
where p (Left x) = print x
p (Right e) = putStrLn e
f :: (Integral a, Bounded a) => IO [Either a String]
f = sequence [ g (minBound `div` (-1)),
g (minBound `mod` (-1)),
g (case minBound `divMod` (-1) of (x, _) -> x),
g (case minBound `divMod` (-1) of (_, x) -> x),
g (minBound `quot` (-1)),
g (minBound `rem` (-1)),
g (case minBound `quotRem` (-1) of (x, _) -> x),
g (case minBound `quotRem` (-1) of (_, x) -> x) ]
where g x = do x' <- evaluate x
return (Left x')
`E.catch`
\e -> return (Right (show (e :: SomeException)))
| urbanslug/ghc | libraries/base/tests/quotOverflow.hs | bsd-3-clause | 1,165 | 0 | 14 | 446 | 558 | 293 | 265 | 28 | 2 |
module T5252Take2 where
import qualified T5252Take2a as M
write_message :: M.WriteMessage -> IO Bool
write_message (M.WriteMessage _) = return True
| urbanslug/ghc | testsuite/tests/deSugar/should_compile/T5252Take2.hs | bsd-3-clause | 149 | 0 | 8 | 21 | 43 | 24 | 19 | 4 | 1 |
{-# LANGUAGE OverloadedLists, TypeFamilies, RebindableSyntax #-}
import Prelude
import Data.List
main = do print []
print [0,3..20]
print [3]
print [2..7]
print [20,2]
print [1,2,37]
fromListN _ = length
fromList = length
| urbanslug/ghc | testsuite/tests/overloadedlists/should_run/overloadedlistsrun05.hs | bsd-3-clause | 304 | 0 | 8 | 114 | 97 | 49 | 48 | 11 | 1 |
module A where
import C
-- THIS FIXES IT:
-- import B
| urbanslug/ghc | testsuite/tests/programs/hs-boot/A.hs | bsd-3-clause | 56 | 0 | 3 | 14 | 9 | 7 | 2 | 2 | 0 |
{-# OPTIONS_GHC -Wno-overlapping-patterns -Wno-incomplete-patterns -Wno-incomplete-uni-patterns -Wno-incomplete-record-updates #-}
-- | Index simplification mechanics.
module Futhark.Optimise.Simplify.Rules.Index
( IndexResult (..),
simplifyIndexing,
)
where
import Data.List.NonEmpty (NonEmpty (..))
import Data.Maybe
import Futhark.Analysis.PrimExp.Convert
import qualified Futhark.Analysis.SymbolTable as ST
import Futhark.Construct
import Futhark.IR
import Futhark.Optimise.Simplify.Rules.Simple
import Futhark.Util
isCt1 :: SubExp -> Bool
isCt1 (Constant v) = oneIsh v
isCt1 _ = False
isCt0 :: SubExp -> Bool
isCt0 (Constant v) = zeroIsh v
isCt0 _ = False
-- | Some index expressions can be simplified to t'SubExp's, while
-- others produce another index expression (which may be further
-- simplifiable).
data IndexResult
= IndexResult Certs VName (Slice SubExp)
| SubExpResult Certs SubExp
-- | Try to simplify an index operation.
simplifyIndexing ::
MonadBuilder m =>
ST.SymbolTable (Rep m) ->
TypeLookup ->
VName ->
Slice SubExp ->
Bool ->
Maybe (m IndexResult)
simplifyIndexing vtable seType idd (Slice inds) consuming =
case defOf idd of
_
| Just t <- seType (Var idd),
Slice inds == fullSlice t [] ->
Just $ pure $ SubExpResult mempty $ Var idd
| Just inds' <- sliceIndices (Slice inds),
Just (ST.Indexed cs e) <- ST.index idd inds' vtable,
worthInlining e,
all (`ST.elem` vtable) (unCerts cs) ->
Just $ SubExpResult cs <$> toSubExp "index_primexp" e
| Just inds' <- sliceIndices (Slice inds),
Just (ST.IndexedArray cs arr inds'') <- ST.index idd inds' vtable,
all (worthInlining . untyped) inds'',
arr `ST.available` vtable,
all (`ST.elem` vtable) (unCerts cs) ->
Just $
IndexResult cs arr . Slice . map DimFix
<$> mapM (toSubExp "index_primexp") inds''
Nothing -> Nothing
Just (SubExp (Var v), cs) ->
Just $ pure $ IndexResult cs v $ Slice inds
Just (Iota _ x s to_it, cs)
| [DimFix ii] <- inds,
Just (Prim (IntType from_it)) <- seType ii ->
Just $
let mul = BinOpExp $ Mul to_it OverflowWrap
add = BinOpExp $ Add to_it OverflowWrap
in fmap (SubExpResult cs) $
toSubExp "index_iota" $
( sExt to_it (primExpFromSubExp (IntType from_it) ii)
`mul` primExpFromSubExp (IntType to_it) s
)
`add` primExpFromSubExp (IntType to_it) x
| [DimSlice i_offset i_n i_stride] <- inds ->
Just $ do
i_offset' <- asIntS to_it i_offset
i_stride' <- asIntS to_it i_stride
let mul = BinOpExp $ Mul to_it OverflowWrap
add = BinOpExp $ Add to_it OverflowWrap
i_offset'' <-
toSubExp "iota_offset" $
( primExpFromSubExp (IntType to_it) x
`mul` primExpFromSubExp (IntType to_it) s
)
`add` primExpFromSubExp (IntType to_it) i_offset'
i_stride'' <-
letSubExp "iota_offset" $
BasicOp $ BinOp (Mul Int64 OverflowWrap) s i_stride'
fmap (SubExpResult cs) $
letSubExp "slice_iota" $
BasicOp $ Iota i_n i_offset'' i_stride'' to_it
-- A rotate cannot be simplified away if we are slicing a rotated dimension.
Just (Rotate offsets a, cs)
| not $ or $ zipWith rotateAndSlice offsets inds -> Just $ do
dims <- arrayDims <$> lookupType a
let adjustI i o d = do
i_p_o <- letSubExp "i_p_o" $ BasicOp $ BinOp (Add Int64 OverflowWrap) i o
letSubExp "rot_i" (BasicOp $ BinOp (SMod Int64 Unsafe) i_p_o d)
adjust (DimFix i, o, d) =
DimFix <$> adjustI i o d
adjust (DimSlice i n s, o, d) =
DimSlice <$> adjustI i o d <*> pure n <*> pure s
IndexResult cs a . Slice <$> mapM adjust (zip3 inds offsets dims)
where
rotateAndSlice r DimSlice {} = not $ isCt0 r
rotateAndSlice _ _ = False
Just (Index aa ais, cs) ->
Just $
IndexResult cs aa
<$> subExpSlice (sliceSlice (primExpSlice ais) (primExpSlice (Slice inds)))
Just (Replicate (Shape [_]) (Var vv), cs)
| [DimFix {}] <- inds,
not consuming,
ST.available vv vtable ->
Just $ pure $ SubExpResult cs $ Var vv
| DimFix {} : is' <- inds,
not consuming,
ST.available vv vtable ->
Just $ pure $ IndexResult cs vv $ Slice is'
Just (Replicate (Shape [_]) val@(Constant _), cs)
| [DimFix {}] <- inds, not consuming -> Just $ pure $ SubExpResult cs val
Just (Replicate (Shape ds) v, cs)
| (ds_inds, rest_inds) <- splitAt (length ds) inds,
(ds', ds_inds') <- unzip $ mapMaybe index ds_inds,
ds' /= ds ->
Just $ do
arr <- letExp "smaller_replicate" $ BasicOp $ Replicate (Shape ds') v
return $ IndexResult cs arr $ Slice $ ds_inds' ++ rest_inds
where
index DimFix {} = Nothing
index (DimSlice _ n s) = Just (n, DimSlice (constant (0 :: Int64)) n s)
Just (Rearrange perm src, cs)
| rearrangeReach perm <= length (takeWhile isIndex inds) ->
let inds' = rearrangeShape (rearrangeInverse perm) inds
in Just $ pure $ IndexResult cs src $ Slice inds'
where
isIndex DimFix {} = True
isIndex _ = False
Just (Copy src, cs)
| Just dims <- arrayDims <$> seType (Var src),
length inds == length dims,
-- It is generally not safe to simplify a slice of a copy,
-- because the result may be used in an in-place update of the
-- original. But we know this can only happen if the original
-- is bound the same depth as we are!
all (isJust . dimFix) inds
|| maybe True ((ST.loopDepth vtable /=) . ST.entryDepth) (ST.lookup src vtable),
not consuming,
ST.available src vtable ->
Just $ pure $ IndexResult cs src $ Slice inds
Just (Reshape newshape src, cs)
| Just newdims <- shapeCoercion newshape,
Just olddims <- arrayDims <$> seType (Var src),
changed_dims <- zipWith (/=) newdims olddims,
not $ or $ drop (length inds) changed_dims ->
Just $ pure $ IndexResult cs src $ Slice inds
| Just newdims <- shapeCoercion newshape,
Just olddims <- arrayDims <$> seType (Var src),
length newshape == length inds,
length olddims == length newdims ->
Just $ pure $ IndexResult cs src $ Slice inds
Just (Reshape [_] v2, cs)
| Just [_] <- arrayDims <$> seType (Var v2) ->
Just $ pure $ IndexResult cs v2 $ Slice inds
Just (Concat d (x :| xs) _, cs)
| -- HACK: simplifying the indexing of an N-array concatenation
-- is going to produce an N-deep if expression, which is bad
-- when N is large. To try to avoid that, we use the
-- heuristic not to simplify as long as any of the operands
-- are themselves Concats. The hope it that this will give
-- simplification some time to cut down the concatenation to
-- something smaller, before we start inlining.
not $ any isConcat $ x : xs,
Just (ibef, DimFix i, iaft) <- focusNth d inds,
Just (Prim res_t) <-
(`setArrayDims` sliceDims (Slice inds))
<$> ST.lookupType x vtable -> Just $ do
x_len <- arraySize d <$> lookupType x
xs_lens <- mapM (fmap (arraySize d) . lookupType) xs
let add n m = do
added <- letSubExp "index_concat_add" $ BasicOp $ BinOp (Add Int64 OverflowWrap) n m
return (added, n)
(_, starts) <- mapAccumLM add x_len xs_lens
let xs_and_starts = reverse $ zip xs starts
let mkBranch [] =
letSubExp "index_concat" $ BasicOp $ Index x $ Slice $ ibef ++ DimFix i : iaft
mkBranch ((x', start) : xs_and_starts') = do
cmp <- letSubExp "index_concat_cmp" $ BasicOp $ CmpOp (CmpSle Int64) start i
(thisres, thisstms) <- collectStms $ do
i' <- letSubExp "index_concat_i" $ BasicOp $ BinOp (Sub Int64 OverflowWrap) i start
letSubExp "index_concat" . BasicOp . Index x' $
Slice $ ibef ++ DimFix i' : iaft
thisbody <- mkBodyM thisstms [subExpRes thisres]
(altres, altstms) <- collectStms $ mkBranch xs_and_starts'
altbody <- mkBodyM altstms [subExpRes altres]
letSubExp "index_concat_branch" $
If cmp thisbody altbody $
IfDec [primBodyType res_t] IfNormal
SubExpResult cs <$> mkBranch xs_and_starts
Just (ArrayLit ses _, cs)
| DimFix (Constant (IntValue (Int64Value i))) : inds' <- inds,
Just se <- maybeNth i ses ->
case inds' of
[] -> Just $ pure $ SubExpResult cs se
_ | Var v2 <- se -> Just $ pure $ IndexResult cs v2 $ Slice inds'
_ -> Nothing
-- Indexing single-element arrays. We know the index must be 0.
_
| Just t <- seType $ Var idd,
isCt1 $ arraySize 0 t,
DimFix i : inds' <- inds,
not $ isCt0 i ->
Just . pure . IndexResult mempty idd . Slice $
DimFix (constant (0 :: Int64)) : inds'
_ -> Nothing
where
defOf v = do
(BasicOp op, def_cs) <- ST.lookupExp v vtable
return (op, def_cs)
worthInlining e
| primExpSizeAtLeast 20 e = False -- totally ad-hoc.
| otherwise = worthInlining' e
worthInlining' (BinOpExp Pow {} _ _) = False
worthInlining' (BinOpExp FPow {} _ _) = False
worthInlining' (BinOpExp _ x y) = worthInlining' x && worthInlining' y
worthInlining' (CmpOpExp _ x y) = worthInlining' x && worthInlining' y
worthInlining' (ConvOpExp _ x) = worthInlining' x
worthInlining' (UnOpExp _ x) = worthInlining' x
worthInlining' FunExp {} = False
worthInlining' _ = True
isConcat v
| Just (Concat {}, _) <- defOf v =
True
| otherwise =
False
| diku-dk/futhark | src/Futhark/Optimise/Simplify/Rules/Index.hs | isc | 10,189 | 0 | 27 | 3,155 | 3,422 | 1,647 | 1,775 | 207 | 31 |
module Main where
import MessageLoop
main :: IO ()
main = loop
| torus/haskell-eloima | app/Main.hs | isc | 65 | 0 | 6 | 14 | 22 | 13 | 9 | 4 | 1 |
reverseList :: [a] -> [a]
reverseList [] = []
reverseList (h:t) = reverseList t ++ [h]
{- Find out whether a list is a palindrome. -}
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome l = l == (reverseList l)
| andrewaguiar/s99-haskell | p06.hs | mit | 214 | 0 | 7 | 45 | 93 | 50 | 43 | 5 | 1 |
module GitHub.Search where
import GitHub.Internal
--| GET /legacy/issues/search/:owner/:repository/:state/:keyword
searchIssues ::
OwnerName ->
RepoName ->
IssueState ->
Text ->
GitHub IssuesSearchResultsData
--| GET /legacy/repos/search/:keyword
searchRepositories ::
Text ->
Language ->
Int ->
RepoSortBy ->
SortOrder ->
GitHub RepositoriesSearchResultsData
--| GET /legacy/user/search/:keyword
searchUsers ::
Text ->
Int ->
UserSortBy ->
SortOrder ->
GitHub UsersSearchResultsData
| SaneApp/github-api | src/GitHub/Search.hs | mit | 503 | 32 | 13 | 71 | 206 | 103 | 103 | -1 | -1 |
module Network.Skype.Parser.User where
import Control.Applicative
import Data.Attoparsec.ByteString.Char8 (anyChar, decimal)
import Data.Attoparsec.ByteString.Lazy
import Data.Word8
import Network.Skype.Parser.Types
import Network.Skype.Protocol.User
userProperty :: Parser UserProperty
userProperty = choice
[ UserHandle <$> (property "HANDLE" *> userID)
, UserFullName <$> (property "FULLNAME" *> userFullName)
, UserBirthday <$> (property "BIRTHDAY" *> userBirthday)
, UserSex <$> (property "SEX" *> userSex)
, UserLanguage <$> (property "LANGUAGE" *> userLanguage)
, UserCountry <$> (property "COUNTRY" *> userCountry)
, UserProvince <$> (property "PROVINCE" *> userProvince)
, UserCity <$> (property "CITY" *> userCity)
, UserHomePhone <$> (property "PHONE_HOME" *> userPhone)
, UserOfficePhone <$> (property "PHONE_OFFICE" *> userPhone)
, UserMobilePhone <$> (property "PHONE_MOBILE" *> userPhone)
, UserHomepage <$> (property "HOMEPAGE" *> userHomepage)
, UserAbout <$> (property "ABOUT" *> userAbout)
, UserHasCallEquipment <$> (property "HASCALLEQUIPMENT" *> boolean)
, UserIsVideoCapable <$> (property "IS_VIDEO_CAPABLE" *> boolean)
, UserIsVoicemailCapable <$> (property "IS_VOICEMAIL_CAPABLE" *> boolean)
, UserBuddyStatus <$> (property "BUDDYSTATUS" *> userBuddyStatus)
, UserIsAuthorized <$> (property "ISAUTHORIZED" *> boolean)
, UserIsBlocked <$> (property "ISBLOCKED" *> boolean)
, UserOnlineStatus <$> (property "ONLINESTATUS" *> userOnlineStatus)
, UserLastOnlineTimestamp <$> (property "LASTONLINETIMESTAMP" *> timestamp)
, UserCanLeaveVoicemail <$> (property "CAN_LEAVE_VM" *> boolean)
, UserSpeedDial <$> (property "SPEEDDIAL" *> userSpeedDial)
, UserReceiveAuthRequest <$> (property "RECEIVEDAUTHREQUEST" *> userAuthRequestMessage)
, UserMoodText <$> (property "MOOD_TEXT" *> userMoodText)
, UserRichMoodText <$> (property "RICH_MOOD_TEXT" *> userRichMoodText)
, UserTimezone <$> (property "TIMEZONE" *> userTimezoneOffset)
, UserIsCallForwardingActive <$> (property "IS_CF_ACTIVE" *> boolean)
, UserNumberOfAuthedBuddies <$> (property "NROF_AUTHED_BUDDIES" *> decimal)
, UserDisplayName <$> (property "DISPLAYNAME" *> userDisplayName)
]
where
property prop = string prop *> spaces
userSex :: Parser UserSex
userSex = choice
[ UserSexUnknown <$ string "UNKNOWN"
, UserSexMale <$ string "MALE"
, UserSexFemale <$ string "FEMALE"
]
userStatus :: Parser UserStatus
userStatus = choice
[ UserStatusUnknown <$ string "UNKNOWN"
, UserStatusOnline <$ string "ONLINE"
, UserStatusOffline <$ string "OFFLINE"
, UserStatusSkypeMe <$ string "SKYPEME"
, UserStatusAway <$ string "AWAY"
, UserStatusNotAvailable <$ string "NA"
, UserStatusDoNotDisturb <$ string "DND"
, UserStatusInvisible <$ string "INVISIBLE"
, UserStatusLoggedOut <$ string "LOGGEDOUT"
]
userBuddyStatus :: Parser UserBuddyStatus
userBuddyStatus = choice
[ UserBuddyStatusNeverBeen <$ word8 _0
, UserBuddyStatusDeleted <$ word8 _1
, UserBuddyStatusPending <$ word8 _2
, UserBuddyStatusAdded <$ word8 _3
]
userOnlineStatus :: Parser UserOnlineStatus
userOnlineStatus = choice
[ UserOnlineStatusUnknown <$ string "UNKNOWN"
, UserOnlineStatusOffline <$ string "OFFLINE"
, UserOnlineStatusOnline <$ string "ONLINE"
, UserOnlineStatusAway <$ string "AWAY"
, UserOnlineStatusNotAvailable <$ string "NA"
, UserOnlineStatusDoNotDisturb <$ string "DND"
]
userAvater :: Parser (Int, FilePath)
userAvater = (,) <$> decimal <*> many anyChar
| emonkak/skype4hs | src/Network/Skype/Parser/User.hs | mit | 3,934 | 0 | 10 | 923 | 914 | 483 | 431 | 72 | 1 |
-- | <http://strava.github.io/api/v3/comments/>
module Strive.Actions.Comments
( getActivityComments
) where
import Network.HTTP.Types (toQuery)
import Strive.Aliases (ActivityId, Result)
import Strive.Client (Client)
import Strive.Internal.HTTP (get)
import Strive.Options (GetActivityCommentsOptions)
import Strive.Types (CommentSummary)
-- | <http://strava.github.io/api/v3/comments/#list>
getActivityComments
:: Client
-> ActivityId
-> GetActivityCommentsOptions
-> IO (Result [CommentSummary])
getActivityComments client activityId options = get client resource query
where
resource = "api/v3/activities/" <> show activityId <> "/comments"
query = toQuery options
| tfausak/strive | source/library/Strive/Actions/Comments.hs | mit | 688 | 0 | 11 | 83 | 153 | 87 | 66 | 16 | 1 |
module Main (main) where
import XMonad
import XMonad.Actions.UpdatePointer
import qualified Data.Map as M
import Graphics.X11.ExtraTypes.XF86
import XMonad.Hooks.ManageHelpers (isFullscreen, doFullFloat)
-- needed by CopyWindows bindings
import qualified XMonad.StackSet as W
import XMonad.Actions.CopyWindow
-- XMobar
import XMonad.Util.Run(spawnPipe)
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.DynamicLog
import System.IO
import XMonad.Util.EZConfig(additionalKeys)
import XMonad.Util.Paste
-- https://github.com/fancypantalons/XMonad-Config/blob/master/xmonad.hs
roleName :: Query String
roleName = stringProperty "WM_WINDOW_ROLE"
ctrlBackSpace w =
let translatedProgs = ["Terminator"] in do
c <- runQuery className w
let toTranslate = any (== c) translatedProgs
-- Unfortunately pasteSelection only supports ASCII
-- If we simply use xdotool to send a middle click, it doens't always work depending on the position of the mouse pointer
if toTranslate then sendKey controlMask xK_w else sendKey controlMask xK_BackSpace
main :: IO ()
main = do
xmproc <- spawnPipe "/usr/bin/xmobar ~/.xmobarrc"
xmonad $ defaultConfig{
keys = myKeys <+> keys defaultConfig
, terminal = "terminator"
, workspaces = ["Aw", "Sw", "Dw" , "Fd", "Gd", "Hm", "Jp", "K", "L", "Ö", "Ä"]
, modMask = mod4Mask
, manageHook = myManageHook <+> manageHook defaultConfig
, layoutHook = avoidStruts $ layoutHook defaultConfig
, logHook = dynamicLogWithPP xmobarPP
{ ppOutput = hPutStrLn xmproc
, ppTitle = xmobarColor "green" "" . shorten 50
}
>> updatePointer (Relative 0.99 0)
} `additionalKeys`
[ ((mod4Mask .|. shiftMask, xK_z), spawn "xscreensaver-command -lock")
, ((mod4Mask, xK_b), sendMessage ToggleStruts)
, ((mod4Mask, xK_n), spawn "~/bin/pomodoro-stop")
, ((mod4Mask, xK_v), spawn "~/bin/pomodoro-interrupt")
, ((0, xF86XK_MonBrightnessUp), spawn "sudo /usr/local/sbin/backlight up")
, ((0, xF86XK_MonBrightnessDown), spawn "sudo /usr/local/sbin/backlight down")
, ((0, xF86XK_Launch1), spawn "sudo /usr/local/sbin/backlight toggle")
, ((0, xF86XK_Launch3), spawn "/usr/local/sbin/cpufreq_toggle_osd")
, ((mod4Mask, xK_y ), sendMessage Shrink)
, ((mod4Mask, xK_o ), sendMessage Expand)
, ((mod4Mask, xK_u ), windows W.focusDown )
, ((mod4Mask, xK_i ), windows W.focusUp )
, ((mod3Mask, xK_e ), withFocused ctrlBackSpace )
, ((mod3Mask, xK_r ), sendKey controlMask xK_Delete )
, ((mod3Mask, xK_u ), sendKey controlMask xK_Left )
, ((mod3Mask, xK_o ), sendKey controlMask xK_Right )
, ((mod3Mask .|. mod5Mask, xK_u ), sendKey controlMask xK_Up )
, ((mod3Mask .|. mod5Mask, xK_o ), sendKey controlMask xK_Down )
, ((mod3Mask, xK_n ), sendKey controlMask xK_Left )
, ((mod3Mask, xK_n ), sendKey controlMask xK_Home )
, ((mod3Mask .|. mod5Mask, xK_n ), sendKey controlMask xK_End )
, ((mod3Mask, xK_period ), sendKey controlMask xK_x )
, ((mod3Mask, xK_semicolon ), sendKey controlMask xK_c )
, ((mod3Mask, xK_odiaeresis ), sendKey controlMask xK_v )
]
myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList
[
((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) workspaceKeys
, (f, m) <- [(W.view, 0), (W.shift, shiftMask), (copy, shiftMask .|. controlMask)]
]
where workspaceKeys = [xK_a, xK_s, xK_d, xK_f, xK_g, xK_h, xK_j, xK_k, xK_l, xK_odiaeresis, xK_adiaeresis]
myManageHook = composeAll
[ className =? "Thunderbird" --> doShift "Hm"
, title =? "password-private" --> doShift "Jp"
, title =? "password-kifi" --> doShift "Jp"
, roleName =? "terminal" --> doShift "Gd"
, className =? "Emacs" --> doShift "Fd"
, manageDocks
]
<+> (isFullscreen --> doFullFloat)
| ajsalminen/ansible-role-dotfiles-xmonad | files/dotfiles/xmonad.hs | mit | 4,053 | 0 | 16 | 949 | 1,121 | 654 | 467 | 74 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
--------------------------------------------------------------------------------
-- Module : TypeUtils
-- Maintainer : refactor-fp\@kent.ac.uk
-- |
--
-- This module contains a collection of program analysis and
-- transformation functions (the API) that work over the Type
-- Decorated AST. Most of the functions defined in the module are
-- taken directly from the API, but in some cases are modified to work
-- with the type decorated AST.
--
-- In particular some new functions have been added to make type
-- decorated AST traversals easier.
--
-- In HaRe, in order to preserve the comments and layout of refactored
-- programs, a refactoring modifies not only the AST but also the
-- token stream, and the program source after the refactoring is
-- extracted from the token stream rather than the AST, for the
-- comments and layout information is kept in the token steam instead
-- of the AST. As a consequence, a program transformation function
-- from this API modifies both the AST and the token stream (unless
-- explicitly stated). So when you build your own program
-- transformations, try to use the API to do the transformation, as
-- this can liberate you from caring about the token stream.
--
-- This type decorated API is still in development. Any suggestions
-- and comments are very much welcome.
--------------------------------------------------------------------------------
module Language.Haskell.Refact.Utils.TypeUtils
(
-- * Program Analysis
-- ** Imports and exports
inScopeInfo, isInScopeAndUnqualified, isInScopeAndUnqualifiedGhc, inScopeNames
, isExported, isExplicitlyExported, modIsExported
, equivalentNameInNewMod
, hsQualifier
-- ** Property checking
,isVarId,isConId,isOperator,isTopLevelPN,isLocalPN,isNonLibraryName
,isQualifiedPN, isFunOrPatName, isTypeSig, isTypeSigDecl
,isFunBindP,isFunBindR,isPatBindP,isPatBindR,isSimplePatBind,isSimplePatDecl
,isComplexPatBind,isComplexPatDecl,isFunOrPatBindP,isFunOrPatBindR
-- ** Getting
, findEntity'
, findIdForName
, getTypeForName
,definesTypeSigRdr
,sameBindRdr
,UsedByRhs(..)
-- ** Modules and files
-- ,clientModsAndFiles,serverModsAndFiles,isAnExistingMod
-- ,fileNameToModName, strToModName, modNameToStr
, isMainModule
, getModule
-- ** Locations
,defineLoc, useLoc, locToExp
-- ,locToName
, locToRdrName
,getName
-- * Program transformation
-- ** Adding
,addDecl, addItemsToImport, addItemsToExport, addHiding
,addParamsToDecls, addParamsToSigs, addActualParamsToRhs, addImportDecl, duplicateDecl
-- ** Removing
,rmDecl, rmTypeSig, rmTypeSigs -- , commentOutTypeSig, rmParams
-- ,rmItemsFromExport, rmSubEntsFromExport, Delete(delete)
-- ** Updating
, rmQualifier, qualifyToplevelName, renamePN, HowToQual(..), autoRenameLocalVar
-- ** Identifiers, expressions, patterns and declarations
, expToNameRdr
,nameToString
,patToNameRdr
, pNtoPat
, usedWithoutQualR
-- ** Others
, divideDecls
, mkRdrName,mkQualifiedRdrName,mkNewGhcName,mkNewName,mkNewToplevelName
, registerRdrName
-- The following functions are not in the the API yet.
, causeNameClashInExports {- , inRegion , unmodified -}
, declsSybTransform
-- * Typed AST traversals (added by CMB)
-- * Miscellous
-- ,removeFromInts, getDataName, checkTypes, getPNs, getPN, getPNPats, mapASTOverTAST
-- * Debug stuff
, rdrNameFromName
) where
import Control.Monad.State
import Data.Char
import Data.Foldable
import Data.List
import Data.Maybe
import Exception
import Language.Haskell.Refact.Utils.ExactPrint
import Language.Haskell.Refact.Utils.GhcUtils
import Language.Haskell.Refact.Utils.GhcVersionSpecific
import Language.Haskell.Refact.Utils.LocUtils
import Language.Haskell.Refact.Utils.Monad
import Language.Haskell.Refact.Utils.MonadFunctions
import Language.Haskell.Refact.Utils.TypeSyn
import Language.Haskell.Refact.Utils.Types
import Language.Haskell.Refact.Utils.Variables
import Language.Haskell.GHC.ExactPrint
import Language.Haskell.GHC.ExactPrint.Types
import Language.Haskell.GHC.ExactPrint.Utils
-- Modules from GHC
import qualified FastString as GHC
import qualified GHC as GHC
import qualified Module as GHC
import qualified Name as GHC
import qualified Outputable as GHC
import qualified RdrName as GHC
import qualified TyCon as GHC
#if __GLASGOW_HASKELL__ <= 710
import qualified TypeRep as GHC
#else
import qualified TyCoRep as GHC
import qualified BasicTypes as GHC
#endif
import qualified Unique as GHC
import qualified Var as GHC
import qualified Var as Var
import qualified Data.Generics as SYB
import qualified GHC.SYB.Utils as SYB
import qualified Data.Map as Map
import Data.Generics.Strafunski.StrategyLib.StrategyLib hiding (liftIO,MonadPlus,mzero)
-- ---------------------------------------------------------------------
-- |Process the inscope relation returned from the parsing and module
-- analysis pass, and return a list of four-element tuples. Each tuple
-- contains an identifier name, the identifier's namespace info, the
-- identifier's defining module name and its qualifier name.
--
-- The same identifier may have multiple entries in the result because
-- it may have different qualifiers. This makes it easier to decide
-- whether the identifier can be used unqualifiedly by just checking
-- whether there is an entry for it with the qualifier field being
-- Nothing.
--
inScopeInfo :: InScopes -- ^ The inscope relation .
->[(String, GHC.NameSpace, GHC.ModuleName, Maybe GHC.ModuleName)] -- ^ The result
inScopeInfo names = nub $ map getEntInfo $ names
where
getEntInfo name
=(showGhc name,
GHC.occNameSpace $ GHC.nameOccName name,
GHC.moduleName $ GHC.nameModule name,
getQualMaybe $ GHC.nameRdrName name)
getQualMaybe rdrName = case rdrName of
GHC.Qual modName _occName -> Just modName
_ -> Nothing
-- ---------------------------------------------------------------------
-- | Return True if the identifier is inscope and can be used without
-- a qualifier.
isInScopeAndUnqualified::String -- ^ The identifier name.
->InScopes -- ^ The inscope relation
->Bool -- ^ The result.
isInScopeAndUnqualified n names
= isJust $ find (\ (x, _,_, qual) -> x == n && isNothing qual ) $ inScopeInfo names
-- | Return True if the identifier is inscope and can be used without
-- a qualifier. The identifier name string may have a qualifier
-- already
-- NOTE: may require qualification based on name clash with an
-- existing identifier.
isInScopeAndUnqualifiedGhc ::
String -- ^ The identifier name.
-> (Maybe GHC.Name) -- ^ Existing name, to be excluded from test, if
-- known
-> RefactGhc Bool -- ^ The result.
isInScopeAndUnqualifiedGhc n maybeExising = do
names <- ghandle handler (GHC.parseName n)
logm $ "isInScopeAndUnqualifiedGhc:(n,(maybeExising,names))=" ++ (show n) ++ ":" ++ (showGhc (maybeExising,names))
ctx <- GHC.getContext
logm $ "isInScopeAndUnqualifiedGhc:ctx=" ++ (showGhc ctx)
let nameList = case maybeExising of
Nothing -> names
Just n' -> filter (\x -> (showGhcQual x) /= (showGhcQual n')) names
logm $ "isInScopeAndUnqualifiedGhc:(n,nameList)=" ++ (show n) ++ ":" ++ (showGhc nameList)
return $ nameList /= []
where
handler:: SomeException -> RefactGhc [GHC.Name]
handler e = do
logm $ "isInScopeAndUnqualifiedGhc.handler e=" ++ (show e)
return []
-- ---------------------------------------------------------------------
-- |Return all 'GHC.Name's that correspond to the given string, in the current
-- module.
-- Note: this returns a list because TH constructor names do not have the
-- correct namespace so the two variants are returned, constructor and
-- non-constructor. I suspect that when this is looked up only one will ever
-- come through. Hence we should only ever see 0 or 1 names here.
inScopeNames :: String -- ^ The identifier name.
-> RefactGhc [GHC.Name] -- ^ The result.
inScopeNames n = do
names <- ghandle handler (GHC.parseName n)
logm $ "inScopeNames:(n,names)=" ++ (show n) ++ ":" ++ (showGhc names)
return $ names
where
handler:: SomeException -> RefactGhc [GHC.Name]
handler e = do
logm $ "inScopeNames.handler e=" ++ (show e)
return []
-- ---------------------------------------------------------------------
-- |Given a 'GHC.Name' defined in one module, find the equivalent one in the
-- currently loaded module. This is required otherwise name equality checking
-- based on 'GHC.nameUnique' will fail.
equivalentNameInNewMod :: GHC.Name -> RefactGhc [GHC.Name]
equivalentNameInNewMod old = do
-- we have to do it this way otherwise names imported qualified will not be
-- detected
-- ghc-mod 5.6 introduced a funny whereby the packagekey for the inscopes is
-- "main@main" but for the current file is "main@main"
-- So ignore the packagekey for now
-- See https://github.com/DanielG/ghc-mod/issues/811
-- TODO: revisit this
-- let eqModules (GHC.Module pk1 mn1) (GHC.Module pk2 mn2) = mn1 == mn2
let eqModules (GHC.Module pk1 mn1) (GHC.Module pk2 mn2) = mn1 == mn2 && pk1 == pk2
gnames <- GHC.getNamesInScope
logm $ "equivalentNameInNewMod:gnames=" ++ showGhcQual (map (\n -> (GHC.nameModule n,n)) gnames)
let clientModule = GHC.nameModule old
logm $ "equivalentNameInNewMod:(old,clientModule)=" ++ showGhcQual (old,clientModule)
let clientInscopes = filter (\n -> clientModule == GHC.nameModule n) gnames
let clientInscopes = filter (\n -> eqModules clientModule (GHC.nameModule n)) gnames
logm $ "equivalentNameInNewMod:clientInscopes=" ++ showGhcQual clientInscopes
let newNames = filter (\n -> showGhcQual n == showGhcQual old) clientInscopes
return newNames
-- ---------------------------------------------------------------------
-- | Return all the possible qualifiers for the identifier. The identifier
-- is not inscope if the result is an empty list. NOTE: This is intended to be
-- used when processing a client module, so the 'GHC.Name' parameter is actually
-- from a different module.
hsQualifier :: GHC.Name -- ^ The identifier.
-> RefactGhc [GHC.ModuleName] -- ^ The result.
hsQualifier pname = do
names <- inScopeNames (showGhc pname)
let mods = map (GHC.moduleName . GHC.nameModule) names
return mods
-- ---------------------------------------------------------------------
-- |Make a qualified 'GHC.RdrName'
mkQualifiedRdrName :: GHC.ModuleName -> String -> GHC.RdrName
mkQualifiedRdrName mn s = GHC.mkRdrQual mn (GHC.mkVarOcc s)
-- |Make a simple unqualified 'GHC.RdrName'
mkRdrName :: String -> GHC.RdrName
mkRdrName s = GHC.mkVarUnqual (GHC.mkFastString s)
-- ---------------------------------------------------------------------
-- |Register a 'GHC.Located' 'GHC.RdrName' in the 'NameMap' so it can be looked
-- up if needed. This will create a brand new 'GHC.Name', so no guarantees are
-- given as to matches later. Perhaps this is a bad idea.
registerRdrName :: GHC.Located GHC.RdrName -> RefactGhc ()
registerRdrName (GHC.L l rn) = do
case GHC.isQual_maybe rn of
Nothing -> do
n <- mkNewGhcName Nothing (showGhc rn)
addToNameMap l n
Just (mn,oc) -> do
#if __GLASGOW_HASKELL__ <= 710
n <- mkNewGhcName (Just (GHC.Module (GHC.stringToPackageKey "HaRe") mn)) (showGhc oc)
#else
n <- mkNewGhcName (Just (GHC.Module (GHC.stringToUnitId "HaRe") mn)) (showGhc oc)
#endif
addToNameMap l n
-- ---------------------------------------------------------------------
-- | Make a new GHC.Name, using the Unique Int sequence stored in the
-- RefactState.
mkNewGhcName :: Maybe GHC.Module -> String -> RefactGhc GHC.Name
mkNewGhcName maybeMod name = do
s <- get
u <- gets rsUniqState
put s { rsUniqState = (u+1) }
return (mkNewGhcNamePure 'H' (u + 1) maybeMod name)
-- ---------------------------------------------------------------------
mkNewToplevelName :: GHC.Module -> String -> GHC.SrcSpan -> RefactGhc GHC.Name
mkNewToplevelName modid name defLoc = do
s <- get
u <- gets rsUniqState
put s { rsUniqState = (u+1) }
let un = GHC.mkUnique 'H' (u+1) -- H for HaRe :)
n = GHC.mkExternalName un modid (GHC.mkVarOcc name) defLoc
return n
---------------------------------------------------------------------------
-- |Create a new name base on the old name. Suppose the old name is 'f', then
-- the new name would be like 'f_i' where 'i' is an integer.
mkNewName::String -- ^ The old name
->[String] -- ^ The set of names which the new name cannot take
->Int -- ^ The posfix value
->String -- ^ The result
mkNewName oldName fds suffix
=let newName=if suffix==0 then oldName
else oldName++"_"++ show suffix
in if elem newName fds
then mkNewName oldName fds (suffix+1)
else newName
-- ---------------------------------------------------------------------
-- | Return True if the current module is exported either by default
-- or by specifying the module name in the export.
modIsExported:: GHC.ModuleName -- ^ The module name
-> GHC.RenamedSource -- ^ The AST of the module
-> Bool -- ^ The result
modIsExported modName (_g,_emps,mexps,_mdocs)
= let
modExported (GHC.L _ (GHC.IEModuleContents (GHC.L _ name))) = name == modName
modExported _ = False
moduleExports = filter modExported $ fromMaybe [] mexps
in if isNothing mexps
then True
else (nonEmptyList moduleExports)
-- ---------------------------------------------------------------------
-- | Return True if an identifier is exported by the module currently
-- being refactored.
isExported :: GHC.Name -> RefactGhc Bool
isExported n = do
typechecked <- getTypecheckedModule
let modInfo = GHC.tm_checked_module_info typechecked
return $ GHC.modInfoIsExportedName modInfo n
-- ---------------------------------------------------------------------
-- | Return True if an identifier is explicitly exported by the module.
isExplicitlyExported:: NameMap
-> GHC.Name -- ^ The identifier
-> GHC.ParsedSource -- ^ The AST of the module
-> Bool -- ^ The result
isExplicitlyExported nm pn (GHC.L _ p)
= findNameInRdr nm pn (GHC.hsmodExports p)
-- ---------------------------------------------------------------------
-- | Check if the proposed new name will conflict with an existing export
causeNameClashInExports:: NameMap
-> GHC.Name -- ^ The original name
-> GHC.Name -- ^ The new name
-> GHC.ModuleName -- ^ The identity of the module
-> GHC.ParsedSource -- ^ The AST of the module
-> Bool -- ^ The result
-- Note that in the abstract representation of exps, there is no qualified entities.
causeNameClashInExports nm pn newName modName parsed@(GHC.L _ p)
= let exps = GHC.unLoc $ fromMaybe (GHC.noLoc []) (GHC.hsmodExports p)
varExps = concatMap nameFromExport $ filter isImpVar exps
nameFromExport (GHC.L _ (GHC.IEVar x)) = [rdrName2NamePure nm x]
nameFromExport _ = []
-- TODO: make withoutQual part of the API
withoutQual n = showGhc $ GHC.localiseName n
modNames=nub (concatMap (\x -> if withoutQual x== withoutQual newName
then [GHC.moduleName $ GHC.nameModule x]
else []) varExps)
res = (isExplicitlyExported nm pn parsed) &&
( any modIsUnQualifedImported modNames
|| elem modName modNames)
in res
where
isImpVar (GHC.L _ x) = case x of
GHC.IEVar _ -> True
_ -> False
modIsUnQualifedImported modName'
=let
in isJust $ find (\(GHC.L _ (GHC.ImportDecl _ (GHC.L _ modName1) _qualify _source _safe isQualified _isImplicit _as _h))
-> modName1 == modName' && (not isQualified)) (GHC.hsmodImports p)
-- Original seems to be
-- 1. pick up any module names in the export list with same unQual
-- part as the new name
-- 2. Check if the old is exported explicitly
-- 3. if so, if the new module is exported unqualified
-- or belongs to the current module
-- then it will cause a clash
------------------------------------------------------------------------
-- | Return True if the identifier is unqualifiedly used in the given syntax
-- phrase. Check in a way that the test can be done in a client module, i.e. not
-- using the nameUnique
-- usedWithoutQualR :: GHC.Name -> GHC.ParsedSource -> Bool
usedWithoutQualR :: (SYB.Data t) => GHC.Name -> t -> Bool
usedWithoutQualR name t = isJust $ SYB.something (inName) t
where
inName :: (SYB.Typeable a) => a -> Maybe Bool
inName = nameSybQuery checkName
-- ----------------
checkName ((GHC.L _ pn)::GHC.Located GHC.RdrName)
-- Check the OccName match, for use in a client module refactoring
| ((GHC.rdrNameOcc pn) == (GHC.nameOccName name)) &&
GHC.isUnqual pn = Just True
checkName _ = Nothing
-----------------------------------------------------------------------------
getModule :: RefactGhc GHC.Module
getModule = do
typechecked <- getTypecheckedModule
return $ GHC.ms_mod $ GHC.pm_mod_summary $ GHC.tm_parsed_module typechecked
-- ---------------------------------------------------------------------
-- | Return True if a string is a lexically valid variable name.
isVarId :: String -> Bool
isVarId mid = isId mid && isSmall (ghead "isVarId" mid)
where isSmall c=isLower c || c=='_'
-- | Return True if a string is a lexically valid constructor name.
isConId :: String -> Bool
isConId mid = isId mid && isUpper (ghead "isConId" mid)
-- | Return True if a string is a lexically valid operator name.
isOperator :: String -> Bool
isOperator mid = mid /= [] && isOpSym (ghead "isOperator" mid) &&
isLegalOpTail (tail mid) && not (isReservedOp mid)
where
isOpSym mid' = elem mid' opSymbols
where opSymbols = ['!', '#', '$', '%', '&', '*', '+','.','/','<','=','>','?','@','\'','^','|','-','~']
isLegalOpTail tail' = all isLegal tail'
where isLegal c = isOpSym c || c==':'
isReservedOp mid' = elem mid' reservedOps
where reservedOps = ["..", ":","::","=","\"", "|","<-","@","~","=>"]
-- | Returns True if a string lexically is an identifier.
-- *This function should not be exported.*
isId::String->Bool
isId mid = mid/=[] && isLegalIdTail (tail mid) && not (isReservedId mid)
where
isLegalIdTail tail' = all isLegal tail'
where isLegal c=isSmall c|| isUpper c || isDigit c || c=='\''
isReservedId mid' = elem mid' reservedIds
where reservedIds=["case", "class", "data", "default", "deriving","do","else" ,"if",
"import", "in", "infix","infixl","infixr","instance","let","module",
"newtype", "of","then","type","where","_"]
isSmall c=isLower c || c=='_'
-----------------------------------------------------------------------------
-- |Return True if a PName is a toplevel PName.
isTopLevelPN::GHC.Name -> RefactGhc Bool
isTopLevelPN n = do
typechecked <- getTypecheckedModule
let maybeNames = GHC.modInfoTopLevelScope $ GHC.tm_checked_module_info typechecked
let names = fromMaybe [] maybeNames
return $ n `elem` names
-- |Return True if a PName is a local PName.
isLocalPN::GHC.Name -> Bool
isLocalPN = GHC.isInternalName
-- |Return True if the name has a @GHC.SrcSpan@, i.e. is declared in
-- source we care about
isNonLibraryName :: GHC.Name -> Bool
isNonLibraryName n = case (GHC.nameSrcSpan n) of
GHC.UnhelpfulSpan _ -> False
_ -> True
-- |Return True if a PName is a function\/pattern name defined in t.
isFunOrPatName :: (SYB.Data t) => NameMap -> GHC.Name -> t -> Bool
isFunOrPatName nm pn
= isJust . SYB.something (Nothing `SYB.mkQ` worker `SYB.extQ` workerDecl)
where
worker (decl::GHC.LHsBind GHC.RdrName)
| definesRdr nm pn decl = Just True
worker _ = Nothing
workerDecl (GHC.L l (GHC.ValD decl)::GHC.LHsDecl GHC.RdrName)
| definesRdr nm pn (GHC.L l decl) = Just True
workerDecl _ = Nothing
-------------------------------------------------------------------------------
-- |Return True if a PName is a qualified PName.
-- AZ:NOTE: this tests the use instance, the underlying name may be qualified.
-- e.g. used name is zip, GHC.List.zip
-- NOTE2: not sure if this gives a meaningful result for a GHC.Name
isQualifiedPN :: GHC.Name -> RefactGhc Bool
isQualifiedPN name = return $ GHC.isQual $ GHC.nameRdrName name
-- | Return True if a declaration is a type signature declaration.
isTypeSig :: GHC.LSig a -> Bool
isTypeSig (GHC.L _ (GHC.TypeSig{})) = True
isTypeSig _ = False
-- | Return True if a declaration is a type signature declaration.
isTypeSigDecl :: GHC.LHsDecl a -> Bool
isTypeSigDecl (GHC.L _ (GHC.SigD (GHC.TypeSig{}))) = True
isTypeSigDecl _ = False
-- | Return True if a declaration is a function definition.
isFunBindP :: GHC.LHsDecl GHC.RdrName -> Bool
isFunBindP (GHC.L _ (GHC.ValD (GHC.FunBind{}))) = True
isFunBindP _ =False
isFunBindR::GHC.LHsBind t -> Bool
isFunBindR (GHC.L _l (GHC.FunBind{})) = True
isFunBindR _ =False
-- | Returns True if a declaration is a pattern binding.
isPatBindP :: GHC.LHsDecl GHC.RdrName -> Bool
isPatBindP (GHC.L _ (GHC.ValD (GHC.PatBind _ _ _ _ _))) = True
isPatBindP _=False
isPatBindR :: GHC.LHsBind t -> Bool
isPatBindR (GHC.L _ (GHC.PatBind _ _ _ _ _)) = True
isPatBindR _=False
-- | Return True if a declaration is a pattern binding which only
-- defines a variable value.
isSimplePatDecl :: GHC.LHsDecl GHC.RdrName -> Bool
isSimplePatDecl decl = case decl of
(GHC.L _l (GHC.ValD (GHC.PatBind p _rhs _ty _fvs _))) -> hsNamessRdr p /= []
_ -> False
-- | Return True if a declaration is a pattern binding which only
-- defines a variable value.
isSimplePatBind :: (GHC.DataId t) => GHC.LHsBind t-> Bool
isSimplePatBind decl = case decl of
(GHC.L _l (GHC.PatBind p _rhs _ty _fvs _)) -> hsNamessRdr p /= []
_ -> False
-- | Return True if a declaration is a pattern binding but not a simple one.
isComplexPatDecl::GHC.LHsDecl name -> Bool
isComplexPatDecl (GHC.L l (GHC.ValD decl)) = isComplexPatBind (GHC.L l decl)
isComplexPatDecl _ = False
-- | Return True if a LHsBin is a pattern binding but not a simple one.
isComplexPatBind::GHC.LHsBind name -> Bool
isComplexPatBind decl
= case decl of
(GHC.L _l (GHC.PatBind (GHC.L _ (GHC.VarPat _)) _rhs _ty _fvs _)) -> True
_ -> False
-- | Return True if a declaration is a function\/pattern definition.
isFunOrPatBindP :: HsDeclP -> Bool
isFunOrPatBindP decl = isFunBindP decl || isPatBindP decl
-- | Return True if a declaration is a function\/pattern definition.
isFunOrPatBindR :: GHC.LHsBind t -> Bool
isFunOrPatBindR decl = isFunBindR decl || isPatBindR decl
-- ---------------------------------------------------------------------
-- | Returns True is a syntax phrase, say a, is part of another syntax
-- phrase, say b.
-- Expects to be at least Parser output
findEntity':: (SYB.Data a, SYB.Data b)
=> a -> b -> Maybe (SimpPos,SimpPos)
findEntity' a b = res
where
-- ++AZ++ do a generic traversal, and see if it matches.
res = SYB.somethingStaged SYB.Parser Nothing worker b
worker :: (SYB.Data c)
=> c -> Maybe (SimpPos,SimpPos)
worker x = if SYB.typeOf a == SYB.typeOf x
-- then Just (getStartEndLoc b == getStartEndLoc a)
then Just (getStartEndLoc x)
else Nothing
--------------------------------------------------------------------------------
sameBindRdr :: NameMap -> GHC.LHsDecl GHC.RdrName -> GHC.LHsDecl GHC.RdrName -> Bool
sameBindRdr nm b1 b2 = (definedNamesRdr nm b1) == (definedNamesRdr nm b2)
-- ---------------------------------------------------------------------
-- TODO: is this the same is isUsedInRhs?
class (SYB.Data t) => UsedByRhs t where
-- | Return True if any of the GHC.Name's appear in the given
-- syntax element
usedByRhsRdr :: NameMap -> t -> [GHC.Name] -> Bool
instance UsedByRhs (GHC.HsModule GHC.RdrName) where
-- Not a meaningful question at this level
usedByRhsRdr _ _parsed _pns = False
-- -------------------------------------
instance (UsedByRhs a) => UsedByRhs (GHC.Located a) where
usedByRhsRdr nm (GHC.L _ d) pns = usedByRhsRdr nm d pns
-- -------------------------------------
instance (UsedByRhs a) => UsedByRhs (Maybe a) where
usedByRhsRdr _ Nothing _ = False
usedByRhsRdr nm (Just a) pns = usedByRhsRdr nm a pns
-- -------------------------------------
instance UsedByRhs [GHC.LIE GHC.RdrName] where
usedByRhsRdr nm ds pns = or $ map (\d -> usedByRhsRdr nm d pns) ds
-- -------------------------------------
instance UsedByRhs (GHC.IE GHC.RdrName) where
usedByRhsRdr _ _ _ = False
-- -------------------------------------
instance UsedByRhs [GHC.LHsDecl GHC.RdrName] where
usedByRhsRdr nm ds pns = or $ map (\d -> usedByRhsRdr nm d pns) ds
-- -------------------------------------
instance UsedByRhs (GHC.HsDecl GHC.RdrName) where
usedByRhsRdr nm de pns =
case de of
GHC.TyClD d -> f d
GHC.InstD d -> f d
GHC.DerivD d -> f d
GHC.ValD d -> f d
GHC.SigD d -> f d
GHC.DefD d -> f d
GHC.ForD d -> f d
GHC.WarningD d -> f d
GHC.AnnD d -> f d
GHC.RuleD d -> f d
GHC.VectD d -> f d
GHC.SpliceD d -> f d
GHC.DocD d -> f d
GHC.RoleAnnotD d -> f d
#if __GLASGOW_HASKELL__ < 711
GHC.QuasiQuoteD d -> f d
#endif
where
f d' = usedByRhsRdr nm d' pns
-- -------------------------------------
instance UsedByRhs (GHC.TyClDecl GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.InstDecl GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.DerivDecl GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.ForeignDecl GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.WarnDecls GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.AnnDecl GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.RoleAnnotDecl GHC.RdrName) where
usedByRhsRdr = assert False undefined
#if __GLASGOW_HASKELL__ <= 710
instance UsedByRhs (GHC.HsQuasiQuote GHC.RdrName) where
usedByRhsRdr = assert False undefined
#endif
instance UsedByRhs (GHC.DefaultDecl GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.SpliceDecl GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.VectDecl GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.RuleDecls GHC.RdrName) where
usedByRhsRdr = assert False undefined
instance UsedByRhs GHC.DocDecl where
usedByRhsRdr = assert False undefined
instance UsedByRhs (GHC.Sig GHC.RdrName) where
usedByRhsRdr _ _ _ = False
-- -------------------------------------
instance UsedByRhs (GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName)) where
usedByRhsRdr nm (GHC.Match _ _ _ (GHC.GRHSs rhs _)) pns
= findNamesRdr nm pns rhs
-- -------------------------------------
instance UsedByRhs (GHC.HsBind GHC.RdrName) where
#if __GLASGOW_HASKELL__ <= 710
usedByRhsRdr nm (GHC.FunBind _ _ matches _ _ _) pns = findNamesRdr nm pns matches
#else
usedByRhsRdr nm (GHC.FunBind _ matches _ _ _) pns = findNamesRdr nm pns matches
#endif
usedByRhsRdr nm (GHC.PatBind _ rhs _ _ _) pns = findNamesRdr nm pns rhs
usedByRhsRdr nm (GHC.PatSynBind (GHC.PSB _ _ _ rhs _)) pns = findNamesRdr nm pns rhs
usedByRhsRdr nm (GHC.VarBind _ rhs _) pns = findNamesRdr nm pns rhs
usedByRhsRdr _nm (GHC.AbsBinds _ _ _ _ _) _pns = False
#if __GLASGOW_HASKELL__ > 710
usedByRhsRdr _nm (GHC.AbsBindsSig _ _ _ _ _ _) _pns = False
#endif
-- -------------------------------------
instance UsedByRhs (GHC.HsExpr GHC.RdrName) where
usedByRhsRdr nm (GHC.HsLet _lb e) pns = findNamesRdr nm pns e
usedByRhsRdr _ e _pns = error $ "undefined usedByRhsRdr:" ++ (showGhc e)
-- -------------------------------------
instance UsedByRhs (GHC.Stmt GHC.RdrName (GHC.LHsExpr GHC.RdrName)) where
usedByRhsRdr nm (GHC.LetStmt lb) pns = findNamesRdr nm pns lb
usedByRhsRdr _ s _pns = error $ "undefined usedByRhsRdr:" ++ (showGhc s)
--------------------------------------------------------------------------------
-- |Find the identifier with the given name. This looks through the
-- given syntax phrase for the first GHC.Name which matches. Because
-- it is Renamed source, the GHC.Name will include its defining
-- location. Returns Nothing if the name is not found.
getName::(SYB.Data t)=> String -- ^ The name to find
-> t -- ^ The syntax phrase
-> Maybe GHC.Name -- ^ The result
getName str t
= res
-- ++AZ++:TODO use nameSybQuery?
where
res = SYB.somethingStaged SYB.Renamer Nothing
(Nothing `SYB.mkQ` worker
#if __GLASGOW_HASKELL__ <= 710
`SYB.extQ` workerBind
`SYB.extQ` workerExpr
#endif
) t
worker ((GHC.L _ n) :: (GHC.Located GHC.Name))
| showGhcQual n == str = Just n
worker _ = Nothing
#if __GLASGOW_HASKELL__ <= 710
workerBind (GHC.L _ (GHC.VarPat name) :: (GHC.Located (GHC.Pat GHC.Name)))
| showGhcQual name == str = Just name
workerBind _ = Nothing
workerExpr ((GHC.L _ (GHC.HsVar name)) :: (GHC.Located (GHC.HsExpr GHC.Name)))
| showGhcQual name == str = Just name
workerExpr _ = Nothing
#endif
-- ---------------------------------------------------------------------
-- | Add identifiers to the export list of a module. If the second argument is
-- like: Just p, then do the adding only if p occurs in the export list, and the
-- new identifiers are added right after p in the export list. Otherwise the new
-- identifiers are add to the beginning of the export list. In the case that the
-- export list is emport, then if the third argument is True, then create an
-- explict export list to contain only the new identifiers, otherwise do
-- nothing.
addImportDecl ::
GHC.ParsedSource
-> GHC.ModuleName
#if __GLASGOW_HASKELL__ <= 710
-> Maybe GHC.FastString -- ^qualifier
#else
-> Maybe GHC.StringLiteral -- ^qualifier
#endif
-> Bool -> Bool -> Bool
-> Maybe String -- ^alias
-> Bool
-> [GHC.RdrName]
-> RefactGhc GHC.ParsedSource
-- addImportDecl (groupedDecls,imp, b, c) modName pkgQual source safe qualify alias hide idNames
addImportDecl (GHC.L l p) modName pkgQual source safe qualify alias hide idNames
= do
let imp = GHC.hsmodImports p
impDecl <- mkImpDecl
newSpan <- liftT uniqueSrcSpanT
let newImp = GHC.L newSpan impDecl
liftT $ addSimpleAnnT newImp (DP (1,0)) [((G GHC.AnnImport),DP (0,0))]
return (GHC.L l p { GHC.hsmodImports = (imp++[newImp])})
where
alias' = case alias of
Just stringName -> Just $ GHC.mkModuleName stringName
_ -> Nothing
mkImpDecl = do
newSpan1 <- liftT uniqueSrcSpanT
newSpan2 <- liftT uniqueSrcSpanT
newEnts <- mkNewEntList idNames
let lNewEnts = GHC.L newSpan2 newEnts
-- logm $ "addImportDecl.mkImpDecl:adding anns for:" ++ showGhc lNewEnts
liftT $ addSimpleAnnT lNewEnts (DP (0,1)) [((G GHC.AnnHiding),DP (0,0)),((G GHC.AnnOpenP),DP (0,1)),((G GHC.AnnCloseP),DP (0,0))]
let lmodname = GHC.L newSpan1 modName
liftT $ addSimpleAnnT lmodname (DP (0,1)) [((G GHC.AnnVal),DP (0,0))]
return $ GHC.ImportDecl
{ GHC.ideclSourceSrc = Nothing
, GHC.ideclName = lmodname
, GHC.ideclPkgQual = pkgQual
, GHC.ideclSource = source
, GHC.ideclSafe = safe
, GHC.ideclQualified = qualify
, GHC.ideclImplicit = False
, GHC.ideclAs = alias'
, GHC.ideclHiding =
(if idNames == [] && hide == False then
Nothing
else
(Just (hide, lNewEnts)))
}
-- ---------------------------------------------------------------------
-- | Adding a declaration to the declaration list of the given syntax
-- phrase. If the second argument is Nothing, then the declaration
-- will be added to the beginning of the declaration list, but after
-- the data type declarations is there is any.
addDecl:: (SYB.Data t,SYB.Typeable t)
=> t -- ^The AST to be updated
-> Maybe GHC.Name -- ^If this is Just, then the declaration
-- will be added right after this
-- identifier's definition.
-> ([GHC.LHsDecl GHC.RdrName], Maybe Anns)
-- ^ The declaration with optional signatures to be added, together
-- with optional Annotations.
-> RefactGhc t
addDecl parent pn (declSig, mDeclAnns) = do
logm $ "addDecl:declSig=" ++ showGhc declSig
case mDeclAnns of
Nothing -> return ()
Just declAnns -> -- addRefactAnns declAnns
liftT $ modifyAnnsT (mergeAnns declAnns)
case pn of
Just pn' -> appendDecl parent pn' declSig
Nothing -> addLocalDecl parent declSig
where
setDeclSpacing newDeclSig n c = do
-- First clear any previous indentation
mapM_ (\d -> setPrecedingLinesDeclT d 1 0) newDeclSig
setPrecedingLinesT (ghead "addDecl" newDeclSig) n c
-- mapM_ (\d -> setPrecedingLinesT d 1 0) (gtail "addDecl" newDeclSig)
appendDecl :: (SYB.Data t)
=> t -- ^Original AST
-> GHC.Name -- ^Name to add the declaration after
-> [GHC.LHsDecl GHC.RdrName] -- ^declaration and maybe sig
-> RefactGhc t -- ^updated AST
appendDecl parent1 pn' newDeclSig = do
hasDeclsSybTransform workerHsDecls workerBind parent1
where
workerHsDecls :: forall t. HasDecls t => t -> RefactGhc t
workerHsDecls parent' = do
-- logm $ "addDecl.appendDecl:(pn')=" ++ showGhc pn'
liftT $ setDeclSpacing newDeclSig 2 0
nameMap <- getRefactNameMap
decls <- liftT $ hsDecls parent'
let
(before,after) = break (definesDeclRdr nameMap pn') decls
-- logm $ "addDecl.appendDecl:(before,after)=" ++ showGhc (before,after)
let (decls1,decls2) = case after of
[] -> (before,[])
_ -> (before ++ [ghead "appendDecl14" after],
gtail "appendDecl15" after)
unless (null decls1 || null decls2) $ do liftT $ balanceComments (last decls1) (head decls2)
liftT $ replaceDecls parent' (decls1++newDeclSig++decls2)
workerBind :: (GHC.LHsBind GHC.RdrName -> RefactGhc (GHC.LHsBind GHC.RdrName))
workerBind = assert False undefined
addLocalDecl :: (SYB.Typeable t,SYB.Data t)
=> t -> [GHC.LHsDecl GHC.RdrName]
-> RefactGhc t
addLocalDecl parent' newDeclSig = do
logm $ "addLocalDecl entered"
-- logDataWithAnns "addLocalDecl.parent'" parent'
hasDeclsSybTransform workerHasDecls workerBind parent'
where
workerDecls :: [GHC.LHsDecl GHC.RdrName] -> RefactGhc [GHC.LHsDecl GHC.RdrName]
workerDecls decls = do
logm $ "workerDecls entered"
case decls of
[] -> liftT $ setDeclSpacing newDeclSig 2 0
ds -> do
DP (r,c) <- liftT (getEntryDPT (head ds))
liftT $ setDeclSpacing newDeclSig r c
liftT $ setPrecedingLinesT (head ds) 2 0
return (newDeclSig++decls)
workerHasDecls :: (HasDecls t) => t -> RefactGhc t
workerHasDecls p = do
logm $ "workerHasDecls entered"
decls <- liftT (hsDecls p)
decls' <- workerDecls decls
r <- liftT $ replaceDecls p decls'
return r
workerBind :: GHC.LHsBind GHC.RdrName -> RefactGhc (GHC.LHsBind GHC.RdrName)
workerBind b = do
logm $ "workerBind entered"
case b of
#if __GLASGOW_HASKELL__ <= 710
GHC.L l (GHC.FunBind n i (GHC.MG [match] a ptt o) co fvs t) -> do
#else
GHC.L l (GHC.FunBind n (GHC.MG (GHC.L lm [match]) a ptt o) co fvs t) -> do
#endif
match' <- workerHasDecls match
#if __GLASGOW_HASKELL__ <= 710
return (GHC.L l (GHC.FunBind n i (GHC.MG [match'] a ptt o) co fvs t))
#else
return (GHC.L l (GHC.FunBind n (GHC.MG (GHC.L lm [match']) a ptt o) co fvs t))
#endif
#if __GLASGOW_HASKELL__ <= 710
GHC.L _ (GHC.FunBind _ _ (GHC.MG _matches _ _ _) _ _ _) -> do
#else
GHC.L _ (GHC.FunBind _ (GHC.MG _matches _ _ _) _ _ _) -> do
#endif
error "addDecl:Cannot add a local decl to a FunBind with multiple matches"
p@(GHC.L _ (GHC.PatBind _pat _rhs _ty _fvs _t)) -> do
logm $ "workerBind.PatBind entered"
decls <- liftT (hsDeclsPatBind p)
decls' <- workerDecls decls
r <- liftT $ replaceDeclsPatBind p decls'
return r
x -> error $ "addLocalDecl.workerBind:not processing:" ++ SYB.showData SYB.Parser 0 x
-- ---------------------------------------------------------------------
--
-- ---------------------------------------------------------------------
rdrNameFromName :: Bool -> GHC.Name -> RefactGhc GHC.RdrName
rdrNameFromName useQual newName = do
mname <- case (GHC.nameModule_maybe newName) of
Just (GHC.Module _ mn) -> return mn
Nothing -> do
GHC.Module _ mn <- getRefactModule
return mn
if useQual
then return $ GHC.mkRdrQual mname (GHC.nameOccName newName)
else return $ GHC.mkRdrUnqual (GHC.nameOccName newName)
-- ---------------------------------------------------------------------
-- | add items to the hiding list of an import declaration which
-- imports the specified module.
addHiding::
GHC.ModuleName -- ^ The imported module name
-> GHC.ParsedSource -- ^ The current module
-> [GHC.RdrName] -- ^ The items to be added
-> RefactGhc GHC.ParsedSource -- ^ The result
addHiding mn p ns = do
logm $ "addHiding called for (module,names):" ++ showGhc (mn,ns)
p' <- addItemsToImport' mn p (Left ns) Hide
putRefactParsed p' emptyAnns
return p'
-- --------------------------------------------------------------------
-- | Creates a new entity list for hiding a name in an ImportDecl.
mkNewEntList :: [GHC.RdrName] -> RefactGhc [GHC.LIE GHC.RdrName]
mkNewEntList idNames = do
case idNames of
[] -> return []
_ -> do
newEntsInit <- mapM (mkNewEnt True) (init idNames)
newEntsLast <- mkNewEnt False (last idNames)
return (newEntsInit ++ [newEntsLast])
-- | Creates a new entity for hiding a name in an ImportDecl.
mkNewEnt :: Bool -> GHC.RdrName -> RefactGhc (GHC.LIE GHC.RdrName)
mkNewEnt addCommaAnn pn = do
newSpan <- liftT uniqueSrcSpanT
let lpn = GHC.L newSpan pn
if addCommaAnn
then liftT $ addSimpleAnnT lpn (DP (0,0)) [((G GHC.AnnVal),DP (0,0)),((G GHC.AnnComma),DP (0,0))]
else liftT $ addSimpleAnnT lpn (DP (0,0)) [((G GHC.AnnVal),DP (0,0))]
return (GHC.L newSpan (GHC.IEVar lpn))
-- | Represents the operation type we want to select on addItemsToImport'
data ImportType = Hide -- ^ Used for addHiding
| Import -- ^ Used for addItemsToImport
-- | Add identifiers (given by the third argument) to the explicit entity list
-- in the declaration importing the specified module name. This function does
-- nothing if the import declaration does not have an explicit entity list.
addItemsToImport ::
GHC.ModuleName -- ^ The imported module name
-> Maybe GHC.Name -- ^ The condition identifier.
-> Either [GHC.RdrName] [GHC.LIE GHC.RdrName] -- ^ The items to be added
-> GHC.ParsedSource -- ^ The current module
-> RefactGhc GHC.ParsedSource -- ^ The result
addItemsToImport mn mc ns r = addItemsToImport' mn r ns Import
-- | Add identifiers (given by the third argument) to the explicit entity list
-- in the declaration importing the specified module name. If the ImportType
-- argument is Hide, then the items will be added to the "hiding" list. If it
-- is Import, they will be added to the explicit import entries. This function
-- does nothing if the import declaration does not have an explicit entity
-- list and ImportType is Import.
addItemsToImport'::
GHC.ModuleName -- ^ The imported module name
-> GHC.ParsedSource -- ^ The current module
-- -> [GHC.RdrName] -- ^ The items to be added
-> Either [GHC.RdrName] [GHC.LIE GHC.RdrName] -- ^ The items to be added
-- ->Maybe GHC.Name -- ^ The condition identifier.
-> ImportType -- ^ Whether to hide the names or import them. Uses special data for clarity.
-> RefactGhc GHC.ParsedSource -- ^ The result
addItemsToImport' serverModName (GHC.L l p) pns impType = do
let imps = GHC.hsmodImports p
imps' <- mapM inImport imps
return $ GHC.L l p {GHC.hsmodImports = imps'}
where
isHide = case impType of
Hide -> True
Import -> False
inImport :: GHC.LImportDecl GHC.RdrName -> RefactGhc (GHC.LImportDecl GHC.RdrName)
inImport imp@(GHC.L _ (GHC.ImportDecl _st (GHC.L _ modName) _qualify _source _safe isQualified _isImplicit _as h))
| serverModName == modName && not isQualified -- && (if isJust pn then findPN (gfromJust "addItemsToImport" pn) h else True)
= case h of
Nothing -> insertEnts imp [] True
Just (_isHide, (GHC.L _le ents)) -> insertEnts imp ents False
inImport x = return x
insertEnts ::
GHC.LImportDecl GHC.RdrName
-> [GHC.LIE GHC.RdrName]
-> Bool -- True means there are already existing entities
-> RefactGhc ( GHC.LImportDecl GHC.RdrName )
insertEnts imp ents isNew = do
logm $ "addItemsToImport':insertEnts:(imp,ents,isNew):" ++ showGhc (imp,ents,isNew)
if isNew && not isHide then return imp
else do
logm $ "addItemsToImport':insertEnts:doing stuff"
newSpan <- liftT uniqueSrcSpanT
-- newEnts <- mkNewEntList pns
newEnts <- case pns of
Left pns' -> mkNewEntList pns'
Right pns' -> return pns'
let lNewEnts = GHC.L newSpan (ents++newEnts)
logm $ "addImportDecl.mkImpDecl:adding anns for:" ++ showGhc lNewEnts
if isHide
then
liftT $ addSimpleAnnT lNewEnts (DP (0,1)) [((G GHC.AnnHiding),DP (0,0)),((G GHC.AnnOpenP),DP (0,1)),((G GHC.AnnCloseP),DP (0,0))]
else
liftT $ addSimpleAnnT lNewEnts (DP (0,1)) [((G GHC.AnnOpenP),DP (0,0)),((G GHC.AnnCloseP),DP (0,0))]
when (not (null ents)) $ do liftT (addTrailingCommaT (last ents))
return (replaceHiding imp (Just (isHide, lNewEnts)))
replaceHiding (GHC.L l1 (GHC.ImportDecl st mn q src safe isQ isImp as _h)) h1 =
(GHC.L l1 (GHC.ImportDecl st mn q src safe isQ isImp as h1))
-- ---------------------------------------------------------------------
addParamsToSigs :: [GHC.Name] -> GHC.LSig GHC.RdrName -> RefactGhc (GHC.LSig GHC.RdrName)
addParamsToSigs [] ms = return ms
#if __GLASGOW_HASKELL__ <= 710
addParamsToSigs newParams (GHC.L l (GHC.TypeSig lns ltyp pns)) = do
#else
addParamsToSigs newParams (GHC.L l (GHC.TypeSig lns (GHC.HsIB ivs (GHC.HsWC wcs mwc ltyp)))) = do
#endif
logm $ "addParamsToSigs:newParams=" ++ showGhc newParams
mts <- mapM getTypeForName newParams
let ts = catMaybes mts
logm $ "addParamsToSigs:ts=" ++ showGhc ts
logDataWithAnns "addParamsToSigs:ts=" ts
let newStr = ":: " ++ (intercalate " -> " $ map printSigComponent ts) ++ " -> "
logm $ "addParamsToSigs:newStr=[" ++ newStr ++ "]"
typ' <- liftT $ foldlM addOneType ltyp (reverse ts)
sigOk <- isNewSignatureOk ts
logm $ "addParamsToSigs:(sigOk,newStr)=" ++ show (sigOk,newStr)
if sigOk
#if __GLASGOW_HASKELL__ <= 710
then return (GHC.L l (GHC.TypeSig lns typ' pns))
#else
then return (GHC.L l (GHC.TypeSig lns (GHC.HsIB ivs (GHC.HsWC wcs mwc typ'))))
#endif
else error $ "\nNew type signature may fail type checking: " ++ newStr ++ "\n"
where
addOneType :: GHC.LHsType GHC.RdrName -> GHC.Type -> Transform (GHC.LHsType GHC.RdrName)
addOneType et t = do
hst <- typeToLHsType t
ss1 <- uniqueSrcSpanT
#if __GLASGOW_HASKELL__ <= 710
hst1 <- case t of
(GHC.FunTy _ _) -> do
ss <- uniqueSrcSpanT
let t1 = GHC.L ss (GHC.HsParTy hst)
setEntryDPT hst (DP (0,0))
addSimpleAnnT t1 (DP (0,0)) [((G GHC.AnnOpenP),DP (0,1)),((G GHC.AnnCloseP),DP (0,0))]
return t1
_ -> return hst
let typ = GHC.L ss1 (GHC.HsFunTy hst1 et)
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnRarrow),DP (0,1))]
#else
hst1 <- case t of
-- GHC 8: (ForAllTy (Anon arg) res used to be called FunTy arg res.)
(GHC.ForAllTy (GHC.Anon _) _) -> do
ss <- uniqueSrcSpanT
let t1 = GHC.L ss (GHC.HsParTy hst)
setEntryDPT hst (DP (0,0))
addSimpleAnnT t1 (DP (0,0)) [((G GHC.AnnOpenP),DP (0,1)),((G GHC.AnnCloseP),DP (0,0))]
return t1
_ -> return hst
let typ = GHC.L ss1 (GHC.HsFunTy hst1 et)
-- let typ = error $ "addParamsToSigs:need to update for GHC 8:hst=" ++ SYB.showData SYB.Parser 0 hst
-- let typ = GHC.L ss1 (GHC.HsFunTy hst et)
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnRarrow),DP (0,1))]
#endif
return typ
printSigComponent :: GHC.Type -> String
printSigComponent x = ppType x
addParamsToSigs np ls = error $ "addParamsToSigs: no match for:" ++ showGhc (np,ls)
-- ---------------------------------------------------------------------
-- |Fail any signature having a forall in it.
-- TODO: this is unnecesarily restrictive, but needs
-- a) proper reversing of GHC.Type to GHC.LhsType
-- b) some serious reverse type inference to ensure that the
-- constraints are modified properly to merge the old signature
-- part and the new.
isNewSignatureOk :: [GHC.Type] -> RefactGhc Bool
isNewSignatureOk types = do
logm $ "isNewSignatureOk:types=" ++ SYB.showData SYB.Parser 0 types
-- NOTE: under some circumstances enabling Rank2Types or RankNTypes
-- can resolve the type conflict, this can potentially be checked
-- for.
-- NOTE2: perhaps proceed and reload the tentative refactoring into
-- the GHC session and accept it only if it type checks
-- GHC 8: (ForAllTy (Anon arg) res used to be called FunTy arg res.)
let
r = SYB.everythingStaged SYB.TypeChecker (++) []
([] `SYB.mkQ` usesForAll) types
#if __GLASGOW_HASKELL__ <= 710
usesForAll (GHC.ForAllTy _ _) = [1::Int]
#else
usesForAll (GHC.ForAllTy (GHC.Named _ _) _) = [1::Int]
#endif
usesForAll _ = []
return $ emptyList r
-- ---------------------------------------------------------------------
-- TODO: complete this
typeToLHsType :: GHC.Type -> Transform (GHC.LHsType GHC.RdrName)
typeToLHsType (GHC.TyVarTy v) = do
ss <- uniqueSrcSpanT
#if __GLASGOW_HASKELL__ <= 710
let typ = GHC.L ss (GHC.HsTyVar (GHC.nameRdrName $ Var.varName v))
#else
let typ = GHC.L ss (GHC.HsTyVar (GHC.L ss (GHC.nameRdrName $ Var.varName v)))
#endif
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,0))]
return typ
typeToLHsType (GHC.AppTy t1 t2) = do
t1' <- typeToLHsType t1
t2' <- typeToLHsType t2
ss <- uniqueSrcSpanT
return $ GHC.L ss (GHC.HsAppTy t1' t2')
typeToLHsType t@(GHC.TyConApp _tc _ts) = tyConAppToHsType t
#if __GLASGOW_HASKELL__ <= 710
typeToLHsType (GHC.FunTy t1 t2) = do
t1' <- typeToLHsType t1
t2' <- typeToLHsType t2
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsFunTy t1' t2')
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnRarrow),DP (0,1))]
return typ
#else
-- GHC 8: (ForAllTy (Anon arg) res used to be called FunTy arg res.)
typeToLHsType (GHC.ForAllTy (GHC.Anon t1) t2) = do
t1' <- typeToLHsType t1
t2' <- typeToLHsType t2
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsFunTy t1' t2')
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnRarrow),DP (0,1))]
return typ
#endif
typeToLHsType (GHC.ForAllTy _v t) = do
t' <- typeToLHsType t
ss1 <- uniqueSrcSpanT
#if __GLASGOW_HASKELL__ <= 710
ss2 <- uniqueSrcSpanT
return $ GHC.L ss1 (GHC.HsForAllTy GHC.Explicit Nothing (GHC.HsQTvs [] []) (GHC.L ss2 []) t')
#else
return $ GHC.L ss1 (GHC.HsForAllTy [] t')
#endif
typeToLHsType (GHC.LitTy (GHC.NumTyLit i)) = do
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsTyLit (GHC.HsNumTy (show i) i)) :: GHC.LHsType GHC.RdrName
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,0))]
return typ
typeToLHsType (GHC.LitTy (GHC.StrTyLit s)) = do
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsTyLit (GHC.HsStrTy "" s)) :: GHC.LHsType GHC.RdrName
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,0))]
return typ
{-
data Type
= TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable)
| AppTy -- See Note [AppTy invariant]
Type
Type -- ^ Type application to something other than a 'TyCon'. Parameters:
--
-- 1) Function: must /not/ be a 'TyConApp',
-- must be another 'AppTy', or 'TyVarTy'
--
-- 2) Argument type
| TyConApp -- See Note [AppTy invariant]
TyCon
[KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
-- Invariant: saturated appliations of 'FunTyCon' must
-- use 'FunTy' and saturated synonyms must use their own
-- constructors. However, /unsaturated/ 'FunTyCon's
-- do appear as 'TyConApp's.
-- Parameters:
--
-- 1) Type constructor being applied to.
--
-- 2) Type arguments. Might not have enough type arguments
-- here to saturate the constructor.
-- Even type synonyms are not necessarily saturated;
-- for example unsaturated type synonyms
-- can appear as the right hand side of a type synonym.
| FunTy
Type
Type -- ^ Special case of 'TyConApp': @TyConApp FunTyCon [t1, t2]@
-- See Note [Equality-constrained types]
| ForAllTy
Var -- Type or kind variable
Type -- ^ A polymorphic type
| LitTy TyLit -- ^ Type literals are simillar to type constructors.
-}
tyConAppToHsType :: GHC.Type -> Transform (GHC.LHsType GHC.RdrName)
tyConAppToHsType (GHC.TyConApp tc _ts) = r (show $ GHC.tyConName tc)
where
r str = do
ss <- uniqueSrcSpanT
let typ = GHC.L ss (GHC.HsTyLit (GHC.HsStrTy str $ GHC.mkFastString str)) :: GHC.LHsType GHC.RdrName
addSimpleAnnT typ (DP (0,0)) [((G GHC.AnnVal),DP (0,1))]
return typ
-- tyConAppToHsType t@(GHC.TyConApp _tc _ts)
-- = error $ "tyConAppToHsType: unexpected:" ++ (SYB.showData SYB.TypeChecker 0 t)
{-
HsType
HsForAllTy HsExplicitFlag (LHsTyVarBndrs name) (LHsContext name) (LHsType name)
HsTyVar name
HsAppTy (LHsType name) (LHsType name)
HsFunTy (LHsType name) (LHsType name)
HsListTy (LHsType name)
HsPArrTy (LHsType name)
HsTupleTy HsTupleSort [LHsType name]
HsOpTy (LHsType name) (LHsTyOp name) (LHsType name)
HsParTy (LHsType name)
HsIParamTy HsIPName (LHsType name)
HsEqTy (LHsType name) (LHsType name)
HsKindSig (LHsType name) (LHsKind name)
HsQuasiQuoteTy (HsQuasiQuote name)
HsSpliceTy (HsSplice name) FreeVars PostTcKind
HsDocTy (LHsType name) LHsDocString
HsBangTy HsBang (LHsType name)
HsRecTy [ConDeclField name]
HsCoreTy Type
HsExplicitListTy PostTcKind [LHsType name]
HsExplicitTupleTy [PostTcKind] [LHsType name]
HsTyLit HsTyLit
HsWrapTy HsTyWrapper (HsType name)
-}
-- ---------------------------------------------------------------------
addParamsToDecls::
[GHC.LHsDecl GHC.RdrName] -- ^ A declaration list where the function is defined and\/or used.
-> GHC.Name -- ^ The function name.
-> [GHC.RdrName] -- ^ The parameters to be added.
-> RefactGhc [GHC.LHsDecl GHC.RdrName] -- ^ The result.
addParamsToDecls decls pn paramPNames = do
logm $ "addParamsToDecls (pn,paramPNames)=" ++ (showGhc (pn,paramPNames))
nameMap <- getRefactNameMap
if (paramPNames /= [])
then mapM (addParamToDecl nameMap) decls
else return decls
where
addParamToDecl :: NameMap -> GHC.LHsDecl GHC.RdrName -> RefactGhc (GHC.LHsDecl GHC.RdrName)
#if __GLASGOW_HASKELL__ <= 710
addParamToDecl nameMap (GHC.L l1 (GHC.ValD (GHC.FunBind lp@(GHC.L l2 pname) i (GHC.MG matches a ptt o) co fvs t)))
#else
addParamToDecl nameMap (GHC.L l1 (GHC.ValD (GHC.FunBind lp@(GHC.L l2 pname) (GHC.MG (GHC.L lm matches) a ptt o) co fvs t)))
#endif
| eqRdrNamePure nameMap lp pn
= do
matches' <- mapM addParamtoMatch matches
#if __GLASGOW_HASKELL__ <= 710
return (GHC.L l1 (GHC.ValD (GHC.FunBind (GHC.L l2 pname) i (GHC.MG matches' a ptt o) co fvs t)))
#else
return (GHC.L l1 (GHC.ValD (GHC.FunBind (GHC.L l2 pname) (GHC.MG (GHC.L lm matches') a ptt o) co fvs t)))
#endif
where
addParamtoMatch (GHC.L l (GHC.Match fn1 pats mtyp rhs))
= do
rhs' <- addActualParamsToRhs pn paramPNames rhs
pats' <- liftT $ mapM addParam paramPNames
-- logDataWithAnns "addParamToDecl.addParam:pats'" pats'
return (GHC.L l (GHC.Match fn1 (pats'++pats) mtyp rhs'))
-- TODO: The following will never match, as a PatBind only deals with complex patterns.
addParamToDecl _nameMap x@(GHC.L _l1 (GHC.ValD (GHC.PatBind _pat@(GHC.L _l2 (GHC.VarPat _p)) _rhs _ty _fvs _t)))
= return x
addParamToDecl _ x = return x
addParam n = do
newSpan <- uniqueSrcSpanT
#if __GLASGOW_HASKELL__ <= 710
let vn = (GHC.L newSpan (GHC.VarPat n))
#else
let vn = (GHC.L newSpan (GHC.VarPat (GHC.L newSpan n)))
#endif
addSimpleAnnT vn (DP (0,1)) [((G GHC.AnnVal),DP (0,0))]
return vn
-- ---------------------------------------------------------------------
-- ++AZ++: This looks like it is trying to do too many things
-- | Add identifiers to the export list of a module. If the second argument
-- is like: Just p, then do the adding only if p occurs in the export list, and
-- the new identifiers are added right after p in the export list. Otherwise the
-- new identifiers are add to the beginning of the export list. In the case that
-- the export list is empty, then if the third argument is True, then create an
-- explict export list to contain only the new identifiers, otherwise do
-- nothing.
-- TODO:AZ: re-arrange params to line up with addItemsToExport
addItemsToExport ::
GHC.ParsedSource -- ^The module AST.
-> Maybe GHC.Name -- ^The condtion identifier.
-> Bool -- ^Create an explicit list or not
-> Either [GHC.RdrName] [GHC.LIE GHC.RdrName]
-- ^The identifiers to add in either String or HsExportEntP format.
-> RefactGhc GHC.ParsedSource -- ^The result.
addItemsToExport modu _ _ (Left []) = return modu
addItemsToExport modu _ _ (Right []) = return modu
-- addItemsToExport modu@(HsModule loc modName exps imps ds) (Just pn) _ ids
addItemsToExport modu@(GHC.L l (GHC.HsModule modName exps imps ds deps hs)) (Just pn) _ ids
= case exps of
Just (GHC.L le ents) -> do
logm $ "addItemsToExport:pn=" ++ showGhc pn
nm <- getRefactNameMap
let (e1,e2) = break (findLRdrName nm pn) ents
if e2 /= []
then do
es <- case ids of
Left is' -> mkNewEntList is'
Right es' -> return es'
let e = (ghead "addVarItemInExport" e2)
lNewEnts = GHC.L le (e1++(e:es)++tail e2)
liftT (addTrailingCommaT e)
return (GHC.L l (GHC.HsModule modName (Just lNewEnts) imps ds deps hs))
-- then do ((toks,_),others)<-get
-- let e = (ghead "addVarItemInExport" e2)
-- es = case ids of
-- (Left is' ) ->map (\x-> (EntE (Var (nameToPNT x)))) is'
-- (Right es') -> es'
-- let (_,endPos) = getStartEndLoc toks e
-- (t, (_,s)) = ghead "addVarItemInExport" $ getToks (endPos,endPos) toks
-- newToken = mkToken t endPos (s++","++ showEntities (render.ppi) es)
-- toks' = replaceToks toks endPos endPos [newToken]
-- put ((toks',modified),others)
-- return (HsModule loc modName (Just (e1++(e:es)++tail e2)) imps ds)
else return modu
Nothing -> return modu
addItemsToExport (GHC.L l (GHC.HsModule _ (Just ents) _ _ _ _)) Nothing createExp ids
= assert False undefined
-- = do ((toks,_),others)<-get
-- let es = case ids of
-- (Left is' ) ->map (\x-> (EntE (Var (nameToPNT x)))) is'
-- (Right es') -> es'
-- (t, (pos,s))=fromJust $ find isOpenBracket toks -- s is the '('
-- newToken = if ents /=[] then (t, (pos,(s++showEntities (render.ppi) es++",")))
-- else (t, (pos,(s++showEntities (render.ppi) es)))
-- pos'= simpPos pos
-- toks' = replaceToks toks pos' pos' [newToken]
-- put ((toks',modified),others)
-- return modu {hsModExports=Just (es++ ents)}
-- addItemsToExport mod@(HsModule _ (SN modName (SrcLoc _ c row col)) Nothing _ _) Nothing createExp ids
addItemsToExport modu@(GHC.L l (GHC.HsModule modName Nothing _ _ _ _)) Nothing createExp ids
= assert False undefined
-- =case createExp of
-- True ->do ((toks,_),others)<-get
-- let es = case ids of
-- (Left is' ) ->map (\x-> (EntE (Var (nameToPNT x)))) is'
-- (Right es') -> es'
-- pos = (row,col)
-- newToken = mkToken Varid pos (modNameToStr modName++ "("
-- ++ showEntities (render.ppi) es++")")
-- toks' = replaceToks toks pos pos [newToken]
-- put ((toks', modified), others)
-- return modu {hsModExports=Just es}
-- False ->return modu
{-
-- | Add identifiers to the export list of a module. If the second argument is like: Just p, then do the adding only if p occurs
-- in the export list, and the new identifiers are added right after p in the export list. Otherwise the new identifiers are add
-- to the beginning of the export list. In the case that the export list is emport, then if the third argument is True, then create
-- an explict export list to contain only the new identifiers, otherwise do nothing.
{-
addItemsToExport::( )
=> HsModuleP -- The module AST.
-> Maybe PName -- The condtion identifier.
-> Bool -- Create an explicit list or not
-> Either [String] [HsExportEntP] -- The identifiers to add in either String or HsExportEntP format.
-> m HsModuleP -- The result.
-}
addItemsToExport::(MonadState (([PosToken],Bool), t1) m)
=> HsModuleP -- The module AST.
-> Maybe PName -- The condtion identifier.
-> Bool -- Create an explicit list or not
-> Either [String] [HsExportEntP] -- The identifiers to add in either String or HsExportEntP format.
-> m HsModuleP -- The result.
addItemsToExport mod _ _ (Left []) = return mod
addItemsToExport mod _ _ (Right []) = return mod
addItemsToExport mod@(HsModule loc modName exps imps ds) (Just pn) _ ids
= case exps of
Just ents ->let (e1,e2) = break (findEntity pn) ents
in if e2 /=[]
then do ((toks,_),others)<-get
let e = (ghead "addVarItemInExport" e2)
es = case ids of
(Left is' ) ->map (\x-> (EntE (Var (nameToPNT x)))) is'
(Right es') -> es'
let (_,endPos) = getStartEndLoc toks e
(t, (_,s)) = ghead "addVarItemInExport" $ getToks (endPos,endPos) toks
newToken = mkToken t endPos (s++","++ showEntities (render.ppi) es)
toks' = replaceToks toks endPos endPos [newToken]
put ((toks',modified),others)
return (HsModule loc modName (Just (e1++(e:es)++tail e2)) imps ds)
else return mod
Nothing -> return mod
addItemsToExport mod@(HsModule _ _ (Just ents) _ _) Nothing createExp ids
= do ((toks,_),others)<-get
let es = case ids of
(Left is' ) ->map (\x-> (EntE (Var (nameToPNT x)))) is'
(Right es') -> es'
(t, (pos,s))=fromJust $ find isOpenBracket toks -- s is the '('
newToken = if ents /=[] then (t, (pos,(s++showEntities (render.ppi) es++",")))
else (t, (pos,(s++showEntities (render.ppi) es)))
pos'= simpPos pos
toks' = replaceToks toks pos' pos' [newToken]
put ((toks',modified),others)
return mod {hsModExports=Just (es++ ents)}
addItemsToExport mod@(HsModule _ (SN modName (SrcLoc _ c row col)) Nothing _ _) Nothing createExp ids
=case createExp of
True ->do ((toks,_),others)<-get
let es = case ids of
(Left is' ) ->map (\x-> (EntE (Var (nameToPNT x)))) is'
(Right es') -> es'
pos = (row,col)
newToken = mkToken Varid pos (modNameToStr modName++ "("
++ showEntities (render.ppi) es++")")
toks' = replaceToks toks pos pos [newToken]
put ((toks', modified), others)
return mod {hsModExports=Just es}
False ->return mod
-}
-- ---------------------------------------------------------------------
addActualParamsToRhs :: (SYB.Data t) =>
GHC.Name -> [GHC.RdrName] -> t -> RefactGhc t
addActualParamsToRhs pn paramPNames rhs = do
logm $ "addActualParamsToRhs:entered:(pn,paramPNames)=" ++ showGhc (pn,paramPNames)
nameMap <- getRefactNameMap
let
worker :: (GHC.LHsExpr GHC.RdrName) -> RefactGhc (GHC.LHsExpr GHC.RdrName)
#if __GLASGOW_HASKELL__ <= 710
worker oldExp@(GHC.L l2 (GHC.HsVar pname))
#else
worker oldExp@(GHC.L l2 (GHC.HsVar (GHC.L _ pname)))
#endif
| eqRdrNamePure nameMap (GHC.L l2 pname) pn
= do
logDataWithAnns "addActualParamsToRhs:oldExp=" oldExp
newExp' <- foldlM addParamToExp oldExp paramPNames
edp <- liftT $ getEntryDPT oldExp
liftT $ setEntryDPT oldExp (DP (0,0))
l2' <- liftT $ uniqueSrcSpanT
let newExp = (GHC.L l2' (GHC.HsPar newExp'))
liftT $ addSimpleAnnT newExp (DP (0,0)) [(G GHC.AnnOpenP,DP (0,0)),(G GHC.AnnCloseP,DP (0,0))]
liftT $ setEntryDPT newExp edp
return newExp
worker x = return x
addParamToExp :: (GHC.LHsExpr GHC.RdrName) -> GHC.RdrName -> RefactGhc (GHC.LHsExpr GHC.RdrName)
addParamToExp expr param = do
ss1 <- liftT $ uniqueSrcSpanT
ss2 <- liftT $ uniqueSrcSpanT
logm $ "addActualParamsToRhs.addParamsToExp:(ss1,ss2):" ++ showGhc (ss1,ss2)
registerRdrName (GHC.L ss2 param)
#if __GLASGOW_HASKELL__ <= 710
let var = GHC.L ss2 (GHC.HsVar param)
#else
let var = GHC.L ss2 (GHC.HsVar (GHC.L ss2 param))
#endif
liftT $ addSimpleAnnT var (DP (0,0)) [(G GHC.AnnVal,DP (0,1))]
let expr' = GHC.L ss1 (GHC.HsApp expr var)
liftT $ addSimpleAnnT expr' (DP (0,0)) []
return expr'
r <- applyTP (full_buTP (idTP `adhocTP` worker)) rhs
return r
{-
The code
sumSqu (x:xs) = (sq bar2) x + sumSquares xs
results in
(GRHSs
[
({ LiftToToplevel/D1.hs:(13,15)-(15,16) }
Just (Ann (DP (0,-1)) [] [] [] Nothing Nothing)
(GRHS
[]
({ LiftToToplevel/D1.hs:13:17-43 }
Just (Ann (DP (0,1)) [] [] [] Nothing Nothing)
(OpApp
({ LiftToToplevel/D1.hs:13:17-27 }
Just (Ann (DP (0,0)) [] [] [] Nothing Nothing)
(HsApp
({ LiftToToplevel/D1.hs:13:17-25 }
Just (Ann (DP (0,0)) [] [] [((G AnnOpenP),DP (0,0)),((G AnnCloseP),DP (0,0))] Nothing Nothing)
(HsPar
({ LiftToToplevel/D1.hs:13:18-24 }
Just (Ann (DP (0,0)) [] [] [] Nothing Nothing)
(HsApp
({ LiftToToplevel/D1.hs:13:18-19 }
Just (Ann (DP (0,0)) [] [] [((G AnnVal),DP (0,0))] Nothing Nothing)
(HsVar
(Unqual {OccName: sq})))
({ LiftToToplevel/D1.hs:13:21-24 }
Just (Ann (DP (0,1)) [] [] [((G AnnVal),DP (0,0))] Nothing Nothing)
(HsVar
(Unqual {OccName: bar2})))))))
({ LiftToToplevel/D1.hs:13:27 }
Just (Ann (DP (0,1)) [] [] [((G AnnVal),DP (0,0))] Nothing Nothing)
(HsVar
(Unqual {OccName: x})))))
({ LiftToToplevel/D1.hs:13:29 }
Just (Ann (DP (0,1)) [] [] [((G AnnVal),DP (0,0))] Nothing Nothing)
(HsVar
(Unqual {OccName: +})))
(PlaceHolder)
({ LiftToToplevel/D1.hs:13:31-43 }
Just (Ann (DP (0,1)) [] [] [] Nothing Nothing)
(HsApp
({ LiftToToplevel/D1.hs:13:31-40 }
Just (Ann (DP (0,0)) [] [] [((G AnnVal),DP (0,0))] Nothing Nothing)
(HsVar
(Unqual {OccName: sumSquares})))
({ LiftToToplevel/D1.hs:13:42-43 }
Just (Ann (DP (0,1)) [] [] [((G AnnVal),DP (0,0))] Nothing Nothing)
(HsVar
(Unqual {OccName: xs})))))))))]
-}
{-
Required end result : (sq pow) x + sumSquares xs
(L {test/testdata/LiftToToplevel/D2.hs:6:21-46}
(OpApp
(L {test/testdata/LiftToToplevel/D2.hs:6:21-30}
(HsApp
(L {test/testdata/LiftToToplevel/D2.hs:6:21-28}
(HsPar
(L {test/testdata/LiftToToplevel/D2.hs:6:22-27}
(HsApp
(L {test/testdata/LiftToToplevel/D2.hs:6:22-23}
(HsVar {Name: LiftToToplevel.D2.sq}))
(L {test/testdata/LiftToToplevel/D2.hs:6:25-27}
(HsVar {Name: pow}))))))
(L {test/testdata/LiftToToplevel/D2.hs:6:30}
(HsVar {Name: x}))))
(L {test/testdata/LiftToToplevel/D2.hs:6:32}
(HsVar {Name: GHC.Num.+})) {Fixity: infixl 6}
(L {test/testdata/LiftToToplevel/D2.hs:6:34-46}
(HsApp
(L {test/testdata/LiftToToplevel/D2.hs:6:34-43}
(HsVar {Name: LiftToToplevel.D2.sumSquares}))
(L {test/testdata/LiftToToplevel/D2.hs:6:45-46}
(HsVar {Name: xs}))))))))]
Alternate, no parens : sq pow x + sumSquares xs
(L {test/testdata/LiftToToplevel/D2.hs:6:21-44}
(OpApp
(L {test/testdata/LiftToToplevel/D2.hs:6:21-28}
(HsApp
(L {test/testdata/LiftToToplevel/D2.hs:6:21-26}
(HsApp
(L {test/testdata/LiftToToplevel/D2.hs:6:21-22}
(HsVar {Name: LiftToToplevel.D2.sq}))
(L {test/testdata/LiftToToplevel/D2.hs:6:24-26}
(HsVar {Name: pow}))))
(L {test/testdata/LiftToToplevel/D2.hs:6:28}
(HsVar {Name: x}))))
(L {test/testdata/LiftToToplevel/D2.hs:6:30}
(HsVar {Name: GHC.Num.+})) {Fixity: infixl 6}
(L {test/testdata/LiftToToplevel/D2.hs:6:32-44}
(HsApp
(L {test/testdata/LiftToToplevel/D2.hs:6:32-41}
(HsVar {Name: LiftToToplevel.D2.sumSquares}))
(L {test/testdata/LiftToToplevel/D2.hs:6:43-44}
(HsVar {Name: xs}))))))))]
Original : sq x + sumSquares xs
(L {test/testdata/LiftToToplevel/D2.hs:6:21-40}
(OpApp
(L {test/testdata/LiftToToplevel/D2.hs:6:21-24}
(HsApp
(L {test/testdata/LiftToToplevel/D2.hs:6:21-22}
(HsVar {Name: sq}))
(L {test/testdata/LiftToToplevel/D2.hs:6:24}
(HsVar {Name: x}))))
(L {test/testdata/LiftToToplevel/D2.hs:6:26}
(HsVar {Name: GHC.Num.+})) {Fixity: infixl 6}
(L {test/testdata/LiftToToplevel/D2.hs:6:28-40}
(HsApp
(L {test/testdata/LiftToToplevel/D2.hs:6:28-37}
(HsVar {Name: LiftToToplevel.D2.sumSquares}))
(L {test/testdata/LiftToToplevel/D2.hs:6:39-40}
(HsVar {Name: xs}))))))))]
-}
-- ---------------------------------------------------------------------
-- | Duplicate a function\/pattern binding declaration under a new name
-- right after the original one.
duplicateDecl ::
[GHC.LHsDecl GHC.RdrName] -- ^ decls to be updated, containing the original decl (and sig)
->GHC.Name -- ^ The identifier whose definition is to be duplicated
->GHC.Name -- ^ The new name (possibly qualified)
->RefactGhc [GHC.LHsDecl GHC.RdrName] -- ^ The result
duplicateDecl decls n newFunName
= do
logm $ "duplicateDecl entered:(decls,n,newFunName)=" ++ showGhc (decls,n,newFunName)
nm <- getRefactNameMap
let
declsToDup = definingDeclsRdrNames nm [n] decls True False
funBinding = filter isFunOrPatBindP declsToDup --get the fun binding.
typeSig = map wrapSig $ definingSigsRdrNames nm [n] decls
funBinding'' <- renamePN n newFunName PreserveQualify funBinding
typeSig'' <- renamePN n newFunName PreserveQualify typeSig
logm $ "duplicateDecl:funBinding''=" ++ showGhc funBinding''
funBinding3 <- mapM (\f@(GHC.L _ fb) -> do
newSpan <- liftT uniqueSrcSpanT
let fb' = GHC.L newSpan fb
liftT $ modifyAnnsT (copyAnn f fb')
return fb'
) (typeSig'' ++ funBinding'')
when (not $ null funBinding3) $ do
liftT $ setEntryDPT (head funBinding3) (DP (2,0))
liftT $ mapM_ (\d -> setEntryDPT d (DP (1,0))) (tail funBinding3)
let (decls1,decls2) = break (definesDeclRdr nm n) decls
(declsToDup',declsRest) = break (not . definesDeclRdr nm n) decls2
-- logDataWithAnns "duplicateDecl:funBinding3" funBinding3
return $ decls1 ++ declsToDup' ++ funBinding3 ++ declsRest
-- ---------------------------------------------------------------------
-- |Divide a declaration list into three parts (before, parent, after)
-- according to the PNT, where 'parent' is the first decl containing
-- the PNT, 'before' are those decls before 'parent' and 'after' are
-- those decls after 'parent'.
divideDecls :: SYB.Data t =>
[t] -> GHC.Located GHC.Name -> RefactGhc ([t], [t], [t])
divideDecls ds (GHC.L _ pnt) = do
nm <- getRefactNameMap
let (before,after) = break (\x -> findNameInRdr nm pnt x) ds
return $ if (not $ emptyList after)
then (before, [ghead "divideDecls" after], gtail "divideDecls" after)
else (ds,[],[])
-- ---------------------------------------------------------------------
-- | Remove the declaration (and the type signature is the second
-- parameter is True) that defines the given identifier from the
-- declaration list.
rmDecl:: (SYB.Data t)
=> GHC.Name -- ^ The identifier whose definition is to be removed.
-> Bool -- ^ True means including the type signature.
-> t -- ^ The AST fragment containting the declarations,
-- originating from the ParsedSource
-> RefactGhc
(t,
GHC.LHsDecl GHC.RdrName,
Maybe (GHC.LSig GHC.RdrName)) -- ^ The result and the removed declaration
-- and the possibly removed siganture
rmDecl pn incSig t = do
setStateStorage StorageNone
t' <- everywhereMStaged' SYB.Parser (SYB.mkM inModule
`SYB.extM` inLet
`SYB.extM` inMatch
) t -- top down
-- applyTP (once_tdTP (failTP `adhocTP` inBinds)) t
storage <- getStateStorage
let decl' = case storage of
StorageDeclRdr decl -> decl
x -> error $ "rmDecl: unexpected value in StateStorage:" ++ (show x)
setStateStorage StorageNone
(t'',sig') <- if incSig
then rmTypeSig pn t'
else return (t', Nothing)
return (t'',decl',sig')
where
inModule (p :: GHC.ParsedSource)
= doRmDeclList p
inMatch x@(((GHC.L _ (GHC.Match _ _ _ (GHC.GRHSs _ _localDecls)))):: (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)))
= doRmDeclList x
inLet :: GHC.LHsExpr GHC.RdrName -> RefactGhc (GHC.LHsExpr GHC.RdrName)
inLet letExpr@(GHC.L _ (GHC.HsLet _localDecls expr))
= do
isDone <- getDone
if isDone
then return letExpr
else do
nameMap <- getRefactNameMap
-- decls <- liftT $ hsDecls localDecls
decls <- liftT $ hsDecls letExpr
let (decls1,decls2) = break (definesDeclRdr nameMap pn) decls
if not $ emptyList decls2
then do
let decl = ghead "rmDecl" decls2
setStateStorage (StorageDeclRdr decl)
case length decls of
1 -> do -- Removing the last declaration
return expr
_ -> do
-- logm $ "rmDecl.inLet:length decls /= 1"
decls' <- doRmDecl decls1 decls2
letExpr' <- liftT $ replaceDecls letExpr decls'
return letExpr'
else do
-- liftT $ replaceDecls localDecls decls
return letExpr
inLet x = return x
-- ---------------------------------
doRmDeclList parent
= do
isDone <- getDone
-- logm $ "doRmDeclList:isDone=" ++ show isDone
-- logm $ "doRmDeclList:parent=" ++ SYB.showData SYB.Parser 0 parent
if isDone
then return parent
else do
nameMap <- getRefactNameMap
decls <- liftT $ hsDecls parent
let (decls1,decls2) = break (definesDeclRdr nameMap pn) decls
if not (null decls2)
then do
-- logDataWithAnns "doRmDeclList:(parent)" (parent)
let decl = ghead "doRmDeclList" decls2
setStateStorage (StorageDeclRdr decl)
decls' <- doRmDecl decls1 decls2
parent' <- liftT $ replaceDecls parent decls'
-- logDataWithAnns "doRmDeclList:(parent')" (parent')
return parent'
else do
return parent
-- ---------------------------------
getDone = do
s <- getStateStorage
case s of
StorageNone -> return False
_ -> return True
-- ---------------------------------------------------------------------
-- ++AZ++ TODO: I think this has been superseded by hasDeclsSybTransform
declsSybTransform :: (SYB.Typeable a)
=> (forall b. HasDecls b => b -> RefactGhc b)
-> a -> RefactGhc a
declsSybTransform transform = mt
where
mt = SYB.mkM inMatch
`SYB.extM` inPatDecl
`SYB.extM` inModule
`SYB.extM` inHsLet
inModule :: GHC.ParsedSource -> RefactGhc GHC.ParsedSource
inModule (modu :: GHC.ParsedSource)
= transform modu
inMatch :: GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> RefactGhc (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName))
inMatch x@(GHC.L _ (GHC.Match _ _ _ (GHC.GRHSs _ _localDecls)))
= transform x
inPatDecl ::GHC.LHsDecl GHC.RdrName -> RefactGhc (GHC.LHsDecl GHC.RdrName)
inPatDecl (GHC.L _ (GHC.ValD (GHC.PatBind _ _ _ _ _)))
-- = transform x
= error $ "declsSybTransform:need to reimplement PatBind case"
inPatDecl x = return x
inHsLet :: GHC.LHsExpr GHC.RdrName -> RefactGhc (GHC.LHsExpr GHC.RdrName)
inHsLet x@(GHC.L _ (GHC.HsLet{}))
= transform x
inHsLet x = return x
---------------------------------------------------------------------
-- |Utility function to remove a decl from the middle of a list, assuming the
-- list has already been split into a (possibly empty) front before the decl,
-- and a back where the head is the decl to be removed.
doRmDecl :: [GHC.LHsDecl GHC.RdrName] -> [GHC.LHsDecl GHC.RdrName] -> RefactGhc [GHC.LHsDecl GHC.RdrName]
doRmDecl decls1 decls2
= do
let decls2' = gtail "doRmDecl 1" decls2
declToRemove = head decls2
-- logDataWithAnns "doRmDecl:(decls1,decls2)" (decls1,decls2)
unless (null decls1) $ do liftT $ balanceComments (last decls1) declToRemove
unless (null decls2') $ do liftT $ balanceComments declToRemove (head decls2')
when (not (null decls2') && null decls1) $ do liftT $ transferEntryDPT declToRemove (head decls2')
when (not (null decls2') && not (null decls1) && not (isTypeSigDecl (last decls1)))
$ do liftT $ transferEntryDPT declToRemove (head decls2')
-- logDataWithAnns "doRmDecl:(decls2')" (decls2')
return $ (decls1 ++ decls2')
-- ---------------------------------------------------------------------
-- | Remove multiple type signatures
rmTypeSigs :: (SYB.Data t) =>
[GHC.Name] -- ^ The identifiers whose type signatures are to be removed.
-> t -- ^ The declarations
-> RefactGhc (t,[GHC.LSig GHC.RdrName])
-- ^ The result and removed signatures, if there
-- were any
rmTypeSigs pns t = do
(t',demotedSigsMaybe) <- foldM (\(tee,ds) n -> do { (tee',d) <- rmTypeSig n tee; return (tee', ds++[d])}) (t,[]) pns
return (t',catMaybes demotedSigsMaybe)
-- ---------------------------------------------------------------------
-- | Remove the type signature that defines the given identifier's
-- type from the declaration list.
rmTypeSig :: (SYB.Data t) =>
GHC.Name -- ^ The identifier whose type signature is to be removed.
-> t -- ^ The declarations
-> RefactGhc (t,Maybe (GHC.LSig GHC.RdrName))
-- ^ The result and removed signature, if there
-- was one
-- NOTE: It may have originated from a SigD, it is up
-- to the calling function to insert this if required
rmTypeSig pn t
= do
setStateStorage StorageNone
t' <- SYB.everywhereMStaged SYB.Renamer (SYB.mkM inMatch `SYB.extM` inPatDecl `SYB.extM` inModule) t
storage <- getStateStorage
let sig' = case storage of
StorageSigRdr sig -> Just sig
StorageNone -> Nothing
x -> error $ "rmTypeSig: unexpected value in StateStorage:" ++ (show x)
return (t',sig')
where
inModule :: GHC.ParsedSource -> RefactGhc GHC.ParsedSource
inModule (modu :: GHC.ParsedSource)
= doRmTypeSig modu
-- Deals with the distrinct parts of a FunBind
inMatch :: GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)
-> RefactGhc (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName))
inMatch x@(GHC.L _ (GHC.Match _ _ _ (GHC.GRHSs _ _localDecls)))
= doRmTypeSig x
inPatDecl ::GHC.LHsDecl GHC.RdrName -> RefactGhc (GHC.LHsDecl GHC.RdrName)
inPatDecl x@(GHC.L _ (GHC.ValD (GHC.PatBind _ _ _ _ _))) = do
decls <- liftT $ hsDeclsPatBindD x
decls' <- doRmTypeSigDecls decls
liftT $ replaceDeclsPatBindD x decls'
inPatDecl x = return x
-- ----------------------------------
doRmTypeSig :: (HasDecls t) => t -> RefactGhc t
doRmTypeSig parent = do
decls <- liftT $ hsDecls parent
decls' <- doRmTypeSigDecls decls
liftT $ replaceDecls parent decls'
doRmTypeSigDecls :: [GHC.LHsDecl GHC.RdrName] -> RefactGhc [GHC.LHsDecl GHC.RdrName]
doRmTypeSigDecls decls = do
isDone <- getDone
if isDone
then return decls
else do
-- logDataWithAnns "doRmTypeSig:decls" decls
nameMap <- getRefactNameMap
let (decls1,decls2)= break (definesSigDRdr nameMap pn) decls
if not $ null decls2
then do
-- logDataWithAnns "doRmTypeSig:parent" parent
#if __GLASGOW_HASKELL__ <= 710
let sig@(GHC.L sspan (GHC.SigD (GHC.TypeSig names typ p))) = ghead "rmTypeSig" decls2
#else
let sig@(GHC.L sspan (GHC.SigD (GHC.TypeSig names typ))) = ghead "rmTypeSig" decls2
#endif
if length names > 1
then do
let newNames = filter (\rn -> rdrName2NamePure nameMap rn /= pn) names
#if __GLASGOW_HASKELL__ <= 710
newSig = GHC.L sspan (GHC.SigD (GHC.TypeSig newNames typ p))
#else
newSig = GHC.L sspan (GHC.SigD (GHC.TypeSig newNames typ))
#endif
liftT $ removeTrailingCommaT (glast "doRmTypeSig" newNames)
let pnt = ghead "rmTypeSig" (filter (\rn -> rdrName2NamePure nameMap rn == pn) names)
liftT $ removeTrailingCommaT pnt
-- Construct the old signature, by keeping the
-- signature part but discarding the other names
newSpan <- liftT uniqueSrcSpanT
#if __GLASGOW_HASKELL__ <= 710
let oldSig = (GHC.L newSpan (GHC.TypeSig [pnt] typ p))
#else
let oldSig = (GHC.L newSpan (GHC.TypeSig [pnt] typ))
#endif
liftT $ modifyAnnsT (copyAnn sig oldSig)
setStateStorage (StorageSigRdr oldSig)
return (decls1++[newSig]++gtail "doRmTypeSig" decls2)
else do
let [oldSig] = decl2Sig sig
setStateStorage (StorageSigRdr oldSig)
decls' <- doRmDecl decls1 decls2
return decls'
else do
return decls
getDone = do
s <- getStateStorage
case s of
StorageNone -> return False
_ -> return True
-- ---------------------------------------------------------------------
-- TODO: Is this function needed with GHC?
-- | Remove the qualifier from the given identifiers in the given syntax phrase.
rmQualifier:: (SYB.Data t)
=>[GHC.Name] -- ^ The identifiers.
->t -- ^ The syntax phrase.
->RefactGhc t -- ^ The result.
rmQualifier pns t = do
nm <- getRefactNameMap
SYB.everywhereM (nameSybTransform (rename nm)) t
where
rename nm (ln@(GHC.L l pn)::GHC.Located GHC.RdrName)
| elem (rdrName2NamePure nm ln) pns
= do
case pn of
GHC.Qual _ n -> return (GHC.L l (GHC.Unqual n))
_ -> return ln
rename _ x = return x
-- ---------------------------------------------------------------------
-- | Replace all occurences of a top level GHC.Name with a qualified version.
qualifyToplevelName :: GHC.Name -> RefactGhc ()
qualifyToplevelName n = do
parsed <- getRefactParsed
parsed' <- renamePN n n Qualify parsed
putRefactParsed parsed' emptyAnns
return ()
-- ---------------------------------------------------------------------
data HowToQual = Qualify | NoQualify | PreserveQualify
deriving (Show,Eq)
instance GHC.Outputable HowToQual where
ppr x = GHC.text (show x)
-- | Rename each occurrences of the identifier in the given syntax
-- phrase with the new name.
-- TODO: the syntax phrase is required to be GHC.Located, not sure how
-- to specify this without breaking the everywhereMStaged call
renamePN::(SYB.Data t)
=> GHC.Name -- ^ The identifier to be renamed.
-> GHC.Name -- ^ The new name, including possible qualifier
-> HowToQual
-- the new name.
-> t -- ^ The syntax phrase
-> RefactGhc t
renamePN oldPN newName useQual t = do
-- logm $ "renamePN: (oldPN,newName)=" ++ (showGhc (oldPN,newName))
-- logm $ "renamePN: t=" ++ (SYB.showData SYB.Parser 0 t)
-- nm <- getRefactNameMap
newNameQual <- rdrNameFromName True newName
newNameUnqual <- rdrNameFromName False newName
-- newNameRdr <- rdrNameFromName useQual newName
-- logm $ "renamePN: (newNameQual,newNameUnqual,newNameRdr)=" ++ showGhc (newNameQual,newNameUnqual,newNameRdr)
let
cond :: NameMap -> GHC.Located GHC.RdrName -> Bool
cond nm (GHC.L ln _) =
case Map.lookup ln nm of
Nothing -> False
Just n -> GHC.nameUnique n == GHC.nameUnique oldPN || GHC.nameUnique n == GHC.nameUnique newName
-- Decision process for new names
newNameCalc :: HowToQual -> GHC.RdrName -> GHC.RdrName
newNameCalc uq old = newNameCalc' uq (GHC.isQual_maybe old)
where
newNameCalc' :: HowToQual -> (Maybe (GHC.ModuleName,GHC.OccName)) -> GHC.RdrName
newNameCalc' Qualify (Just (mn,_)) = GHC.Qual mn (GHC.occName newName)
newNameCalc' PreserveQualify (Just (mn,_)) = GHC.Qual mn (GHC.occName newName)
newNameCalc' NoQualify (Just (_n,_)) = GHC.Unqual (GHC.occName newName)
newNameCalc' uq' _ = if uq' == Qualify then newNameQual else newNameUnqual
-- ---------------------------------
makeNewName :: GHC.Located GHC.RdrName -> GHC.RdrName -> RefactGhc (GHC.Located GHC.RdrName)
makeNewName old newRdr = do
ss' <- liftT $ uniqueSrcSpanT
let new = (GHC.L ss' newRdr)
liftT $ modifyAnnsT (copyAnn old new)
addToNameMap ss' newName
return new
-- ---------------------------------
renameLRdr :: HowToQual -> GHC.Located GHC.RdrName -> RefactGhc (GHC.Located GHC.RdrName)
renameLRdr useQual' old@(GHC.L _ n) = do
nm <- getRefactNameMap
if cond nm old
then do
logDataWithAnns "renamePN:rename old :" old
-- let nn = newNameCalcBool useQual' n
let nn = newNameCalc useQual' n
new <- makeNewName old nn
logDataWithAnns "renamePN:rename new :" new
logDataWithAnns "renamePN:rename old2 :" old
return new
else return old
-- ---------------------------------
renameVar :: HowToQual -> GHC.LHsExpr GHC.RdrName -> RefactGhc (GHC.LHsExpr GHC.RdrName)
#if __GLASGOW_HASKELL__ <= 710
renameVar useQual' x@(GHC.L l (GHC.HsVar n)) = do
#else
renameVar useQual' x@(GHC.L l (GHC.HsVar (GHC.L _ n))) = do
#endif
nm <- getRefactNameMap
if cond nm (GHC.L l n)
then do
let nn = newNameCalc useQual' n
#if __GLASGOW_HASKELL__ <= 710
ss' <- liftT $ uniqueSrcSpanT
let (GHC.L l' _) = (GHC.L ss' nn)
liftT $ modifyAnnsT (copyAnn x (GHC.L ss' (GHC.HsVar nn)))
addToNameMap ss' newName
return (GHC.L l' (GHC.HsVar nn))
#else
new <- makeNewName (GHC.L l n) nn
return (GHC.L l (GHC.HsVar new))
#endif
else return x
renameVar _ x = return x
-- ---------------------------------
renameTyVar :: HowToQual -> (GHC.Located (GHC.HsType GHC.RdrName)) -> RefactGhc (GHC.Located (GHC.HsType GHC.RdrName))
#if __GLASGOW_HASKELL__ <= 710
renameTyVar useQual' x@(GHC.L l (GHC.HsTyVar n)) = do
#else
renameTyVar useQual' x@(GHC.L l (GHC.HsTyVar (GHC.L _ n))) = do
#endif
nm <- getRefactNameMap
if cond nm (GHC.L l n)
then do
logm $ "renamePN:renameTyVar at :" ++ (showGhc l)
let nn = newNameCalc useQual' n
#if __GLASGOW_HASKELL__ <= 710
ss' <- liftT $ uniqueSrcSpanT
let (GHC.L l' _) = (GHC.L ss' nn)
liftT $ modifyAnnsT (copyAnn x (GHC.L ss' (GHC.HsTyVar nn)))
addToNameMap ss' newName
return (GHC.L l' (GHC.HsTyVar nn))
#else
new <- makeNewName (GHC.L l n) nn
return (GHC.L l (GHC.HsTyVar new))
#endif
else return x
renameTyVar _ x = return x
-- ---------------------------------
renameHsTyVarBndr :: HowToQual -> GHC.LHsTyVarBndr GHC.RdrName -> RefactGhc (GHC.LHsTyVarBndr GHC.RdrName)
#if __GLASGOW_HASKELL__ <= 710
renameHsTyVarBndr useQual' x@(GHC.L l (GHC.UserTyVar n)) = do
#else
renameHsTyVarBndr useQual' x@(GHC.L l (GHC.UserTyVar (GHC.L _ n))) = do
#endif
nm <- getRefactNameMap
if cond nm (GHC.L l n)
then do
logm $ "renamePN:renameHsTyVarBndr at :" ++ (showGhc l)
-- let nn = newNameCalcBool useQual' n
let nn = newNameCalc useQual' n
#if __GLASGOW_HASKELL__ <= 710
addToNameMap l newName
return (GHC.L l (GHC.UserTyVar nn))
#else
new <- makeNewName (GHC.L l n) nn
return (GHC.L l (GHC.UserTyVar new))
#endif
else return x
renameHsTyVarBndr _ x = return x
-- ---------------------------------
renameLIE :: HowToQual -> (GHC.LIE GHC.RdrName) -> RefactGhc (GHC.LIE GHC.RdrName)
renameLIE useQual' x@(GHC.L l (GHC.IEVar old@(GHC.L ln n))) = do
nm <- getRefactNameMap
if cond nm (GHC.L ln n)
then do
-- logm $ "renamePN:renameLIE.IEVar at :" ++ (showGhc l)
let nn = newNameCalc useQual' n
new <- makeNewName old nn
return (GHC.L l (GHC.IEVar new))
else return x
renameLIE useQual' x@(GHC.L l (GHC.IEThingAbs old@(GHC.L _ln n))) = do
nm <- getRefactNameMap
if cond nm (GHC.L l n)
then do
-- logm $ "renamePN:renameLIE.IEThingAbs at :" ++ (showGhc l)
let nn = newNameCalc useQual' n
new <- makeNewName old nn
return (GHC.L l (GHC.IEThingAbs new))
else return x
renameLIE useQual' x@(GHC.L l (GHC.IEThingAll old@(GHC.L ln n))) = do
nm <- getRefactNameMap
if cond nm (GHC.L ln n)
then do
-- logm $ "renamePN:renameLIE.IEThingAll at :" ++ (showGhc l)
let nn = newNameCalc useQual' n
new <- makeNewName old nn
return (GHC.L l (GHC.IEThingAll new))
else return x
-- TODO: check inside the ns here too
#if __GLASGOW_HASKELL__ <= 710
renameLIE useQual' (GHC.L l (GHC.IEThingWith old@(GHC.L ln n) ns))
#else
renameLIE useQual' (GHC.L l (GHC.IEThingWith old@(GHC.L ln n) wc ns fls))
#endif
= do
nm <- getRefactNameMap
old' <- if (cond nm (GHC.L ln n))
then do
logm $ "renamePN:renameLIE.IEThingWith at :" ++ (showGhc l)
-- let nn = newNameCalcBool useQual' n
let nn = newNameCalc useQual' n
new <- makeNewName old nn
return new
else return old
ns' <- if (any (\(GHC.L lnn nn) -> cond nm (GHC.L lnn nn)) ns)
then renameTransform useQual' ns
else return ns
#if __GLASGOW_HASKELL__ <= 710
return (GHC.L l (GHC.IEThingWith old' ns'))
#else
return (GHC.L l (GHC.IEThingWith old' wc ns' fls))
#endif
renameLIE _ x = do
-- logm $ "renamePN:renameLIE miss for :" ++ (showGhc x)
return x
-- ---------------------------------
renameLPat :: HowToQual -> (GHC.LPat GHC.RdrName) -> RefactGhc (GHC.LPat GHC.RdrName)
#if __GLASGOW_HASKELL__ <= 710
renameLPat useQual' x@(GHC.L l (GHC.VarPat n)) = do
#else
renameLPat useQual' x@(GHC.L l (GHC.VarPat (GHC.L _ n))) = do
#endif
nm <- getRefactNameMap
if cond nm (GHC.L l n)
then do
logm $ "renamePNworker:renameLPat at :" ++ (showGhc l)
let nn = newNameCalc useQual' n
#if __GLASGOW_HASKELL__ <= 710
ss' <- liftT $ uniqueSrcSpanT
let (GHC.L l' _) = (GHC.L ss' nn)
liftT $ modifyAnnsT (copyAnn x (GHC.L ss' (GHC.VarPat nn)))
addToNameMap ss' newName
return (GHC.L l' (GHC.VarPat nn))
#else
new <- makeNewName (GHC.L l n) nn
return (GHC.L l (GHC.VarPat new))
#endif
else return x
renameLPat _ x = return x
-- ---------------------------------
renameMatch :: HowToQual -> GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName)
-> RefactGhc (GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName))
renameMatch _useQual (GHC.Match mln pats ty grhss) = do
logm $ "renamePN.renameMatch entered:"
pats' <- renameTransform _useQual pats
ty' <- renameTransform _useQual ty
grhss' <- renameTransform _useQual grhss
mln' <- case mln of
#if __GLASGOW_HASKELL__ <= 710
Just (old@(GHC.L lmn mn),f) -> do
nm <- getRefactNameMap
if cond nm (GHC.L lmn mn)
then do
new <- makeNewName old newNameUnqual
return (Just (new,f))
else return mln
Nothing -> return mln
#else
GHC.FunBindMatch old f -> do
nm <- getRefactNameMap
if cond nm old
then do
new <- makeNewName old newNameUnqual
return (GHC.FunBindMatch new f)
else return mln
GHC.NonFunBindMatch -> return mln
#endif
return (GHC.Match mln' pats' ty' grhss')
-- ---------------------------------
renameImportDecl :: HowToQual -> GHC.ImportDecl GHC.RdrName -> RefactGhc (GHC.ImportDecl GHC.RdrName)
renameImportDecl _useQual (GHC.ImportDecl src mn mq isrc isafe iq ii ma (Just (ij,GHC.L ll ies))) = do
ies' <- mapM (renameLIE PreserveQualify) ies
logm $ "renamePN'.renameImportDecl:(ies,ies')=" ++ showGhc (ies,ies')
return (GHC.ImportDecl src mn mq isrc isafe iq ii ma (Just (ij,GHC.L ll ies')))
renameImportDecl _ x = return x
-- ---------------------------------
renameTypeSig :: HowToQual -> (GHC.Sig GHC.RdrName) -> RefactGhc (GHC.Sig GHC.RdrName)
#if __GLASGOW_HASKELL__ <= 710
renameTypeSig _useQual (GHC.TypeSig ns typ p)
#else
renameTypeSig _useQual (GHC.TypeSig ns typ)
#endif
= do
logm $ "renamePN:renameTypeSig"
ns' <- mapM (renameLRdr NoQualify) ns
typ' <- renameTransform _useQual typ
logm $ "renamePN:renameTypeSig done"
#if __GLASGOW_HASKELL__ <= 710
return (GHC.TypeSig ns' typ' p)
#else
return (GHC.TypeSig ns' typ')
#endif
#if __GLASGOW_HASKELL__ > 710
renameTypeSig _useQual (GHC.ClassOpSig f ns typ)
= do
ns' <- mapM (renameLRdr NoQualify) ns
typ' <- renameTransform _useQual typ
return (GHC.ClassOpSig f ns' typ')
#endif
renameTypeSig _ x = return x
-- ---------------------------------
everywhereMSkip :: Monad m => SYB.GenericM m -> SYB.GenericM m
everywhereMSkip f x
| (const False `SYB.extQ` typeSig) x = f x -- no recursion for typeSig
| (const False `SYB.extQ` match) x = f x -- no recursion for FunBind
| (const False `SYB.extQ` importDecl) x = f x -- no recursion for ImportDecl
| otherwise = do x' <- f x
SYB.gmapM (everywhereMSkip f) x'
where
typeSig = const True :: GHC.Sig GHC.RdrName -> Bool
match = const True :: GHC.Match GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> Bool
importDecl = const True :: GHC.ImportDecl GHC.RdrName -> Bool
renameTransform useQual' t' =
(everywhereMSkip ( -- top-down, skipping Located Names for Sig/Match
SYB.mkM (renameVar useQual')
`SYB.extM` (renameLRdr useQual')
`SYB.extM` (renameTyVar useQual')
`SYB.extM` (renameHsTyVarBndr useQual')
`SYB.extM` (renameLIE useQual')
`SYB.extM` (renameLPat useQual')
`SYB.extM` (renameTypeSig useQual')
`SYB.extM` (renameImportDecl useQual')
`SYB.extM` (renameMatch useQual')
) t')
t' <- renameTransform useQual t
return t'
-- ---------------------------------------------------------------------
-- | Check whether the specified identifier is declared in the given syntax phrase t,
-- if so, rename the identifier by creating a new name automatically.
autoRenameLocalVar:: (SYB.Data t)
=> GHC.Name -- ^ The identifier.
-> t -- ^ The syntax phrase.
-> RefactGhc t -- ^ The result.
autoRenameLocalVar pn t = do
logm $ "autoRenameLocalVar: (pn)=" ++ (showGhc (pn))
-- = everywhereMStaged SYB.Renamer (SYB.mkM renameInMatch)
nm <- getRefactNameMap
decls <- liftT $ hsDeclsGeneric t
if isDeclaredInRdr nm pn decls
then do t' <- worker t
return t'
else do return t
where
worker :: (SYB.Data t) => t -> RefactGhc t
worker tt
=do (f,d) <- hsFDNamesFromInsideRdr tt
ds <- hsVisibleNamesRdr pn tt
let newNameStr = mkNewName (nameToString pn) (nub (f `union` d `union` ds)) 1
newName <- mkNewGhcName Nothing newNameStr
renamePN pn newName PreserveQualify tt
-- ---------------------------------------------------------------------
isMainModule :: GHC.Module -> Bool
#if __GLASGOW_HASKELL__ <= 710
isMainModule modu = GHC.modulePackageKey modu == GHC.mainPackageKey
#else
isMainModule modu = GHC.moduleUnitId modu == GHC.mainUnitId
#endif
-- ---------------------------------------------------------------------
-- | Return the identifier's defining location.
-- defineLoc::PNT->SrcLoc
defineLoc :: GHC.Located GHC.Name -> GHC.SrcLoc
defineLoc (GHC.L _ name) = GHC.nameSrcLoc name
-- | Return the identifier's source location.
-- useLoc::PNT->SrcLoc
useLoc:: (GHC.Located GHC.Name) -> GHC.SrcLoc
-- useLoc (GHC.L l _) = getGhcLoc l
useLoc (GHC.L l _) = GHC.srcSpanStart l
-- ---------------------------------------------------------------------
-- | Return the type checked `GHC.Id` corresponding to the given
-- `GHC.Name`
-- TODO: there has to be a simpler way, using the appropriate GHC internals
findIdForName :: GHC.Name -> RefactGhc (Maybe GHC.Id)
findIdForName n = do
tm <- getTypecheckedModule
let t = GHC.tm_typechecked_source tm
let r = SYB.somethingStaged SYB.Parser Nothing (Nothing `SYB.mkQ` worker) t
worker (i::GHC.Id)
| (GHC.nameUnique n) == (GHC.varUnique i) = Just i
worker _ = Nothing
return r
-- ---------------------------------------------------------------------
getTypeForName :: GHC.Name -> RefactGhc (Maybe GHC.Type)
getTypeForName n = do
mId <- findIdForName n
case mId of
Nothing -> return Nothing
Just i -> return $ Just (GHC.varType i)
-- ---------------------------------------------------------------------
-- | Given the syntax phrase, find the largest-leftmost expression
-- contained in the region specified by the start and end position, if
-- found.
locToExp:: (SYB.Data t,SYB.Typeable n) =>
SimpPos -- ^ The start position.
-> SimpPos -- ^ The end position.
-> t -- ^ The syntax phrase.
-> Maybe (GHC.LHsExpr n) -- ^ The result.
locToExp beginPos endPos t = res
where
res = SYB.somethingStaged SYB.Parser Nothing (Nothing `SYB.mkQ` expr) t
expr :: GHC.LHsExpr n -> Maybe (GHC.LHsExpr n)
expr e
|inScope e = Just e
expr _ = Nothing
inScope :: GHC.Located e -> Bool
inScope (GHC.L l _) =
let
(startLoc,endLoc) = case l of
(GHC.RealSrcSpan ss) ->
((GHC.srcSpanStartLine ss,GHC.srcSpanStartCol ss),
(GHC.srcSpanEndLine ss,GHC.srcSpanEndCol ss))
(GHC.UnhelpfulSpan _) -> ((0,0),(0,0))
in
(startLoc>=beginPos) && (startLoc<= endPos) && (endLoc>= beginPos) && (endLoc<=endPos)
--------------------------------------------------------------------------------
-- | If an expression consists of only one identifier then return this
-- identifier in the GHC.Name format, otherwise return the default Name
expToNameRdr :: NameMap -> GHC.LHsExpr GHC.RdrName -> Maybe GHC.Name
#if __GLASGOW_HASKELL__ <= 710
expToNameRdr nm (GHC.L l (GHC.HsVar pnt)) = Just (rdrName2NamePure nm (GHC.L l pnt))
#else
expToNameRdr nm (GHC.L _ (GHC.HsVar pnt)) = Just (rdrName2NamePure nm pnt)
#endif
expToNameRdr nm (GHC.L _ (GHC.HsPar e)) = expToNameRdr nm e
expToNameRdr _ _ = Nothing
nameToString :: GHC.Name -> String
-- nameToString name = showGhc name
nameToString name = showGhcQual name
-- | If a pattern consists of only one identifier then return this
-- identifier, otherwise return Nothing
patToNameRdr :: NameMap -> GHC.LPat GHC.RdrName -> Maybe GHC.Name
#if __GLASGOW_HASKELL__ <= 710
patToNameRdr nm (GHC.L l (GHC.VarPat n)) = Just (rdrName2NamePure nm (GHC.L l n))
#else
patToNameRdr nm (GHC.L _ (GHC.VarPat n)) = Just (rdrName2NamePure nm n)
#endif
patToNameRdr _ _ = Nothing
-- | Compose a pattern from a pName.
{-# DEPRECATED pNtoPat "Can't use Renamed in GHC 8" #-}
pNtoPat :: name -> GHC.Pat name
#if __GLASGOW_HASKELL__ <= 710
pNtoPat pname = GHC.VarPat pname
#else
pNtoPat pname = GHC.VarPat (GHC.noLoc pname)
#endif
-- EOF
| SAdams601/ParRegexSearch | test/HaRe/src/Language/Haskell/Refact/Utils/TypeUtils.hs | mit | 105,025 | 16 | 27 | 29,076 | 21,743 | 11,075 | 10,668 | 1,311 | 28 |
fact :: Integer -> Integer
fact 0 = 1
fact x = x*fact (x-1)
twice :: Integer -> Integer
twice x = x^x
dist :: Double -> Double -> Double -> Double
dist v a t = 0.5 * a * t + v * t
main = do
putStrLn "Hello"
print (fact 3)
print (map twice [1,2,3])
print (sum (map twice [1,2,3]) )
print (sum (map (\x -> x^4) [1,2,3]) )
print pi
print (dist 1 1 10)
| ddeeff/sandbox | haskell/test.hs | mit | 362 | 0 | 14 | 92 | 244 | 122 | 122 | 15 | 1 |
-- Copyright © 2013 Julian Blake Kongslie <jblake@omgwallhack.org>
-- Licensed under the MIT license.
module Main
where
import Control.Applicative
import Control.Monad
import Data.List
import Data.List.Split
import qualified Data.Map as M
import Data.Maybe
import System.Directory
import System.Environment
import System.FilePath
import System.Posix.Files
import Text.JSON
import API
import Spec
main :: IO ()
main = do
[specFile, outputDir, outputURL] <- getArgs
isFile <- doesFileExist specFile
isDir <- doesDirectoryExist specFile
if isFile
then do
modPacksS <- readFile specFile
let modPacks = decodeStrict modPacksS >>= readMap
case modPacks of
Error m -> putStrLn $ "Error parsing " ++ specFile ++ ": " ++ m
Ok mps -> mkAPI $ Spec outputDir outputURL mps
else if isDir
then do
mps <- getModPacks specFile
mkAPI $ Spec outputDir outputURL mps
else putStrLn $ specFile ++ " does not exist!"
getModPacks :: FilePath -> IO (M.Map String ModPack)
getModPacks dir = do
packs <- filter (not . isPrefixOf ".") <$> getDirectoryContents dir
M.fromList <$> forM packs (getModPack dir)
getModPack :: FilePath -> FilePath -> IO (String, ModPack)
getModPack dir mp = do
name <- head <$> lines <$> readFile (dir </> mp </> "name.txt")
latest <- getVersion dir mp "latest"
recommended <- getVersion dir mp "recommended"
versions <- filter (/= "recommended") <$> filter (/= "latest") <$> filter (not . isPrefixOf ".") <$> getDirectoryContents (dir </> mp)
mpvs <- M.fromList <$> catMaybes <$> forM versions (getModPackVersion dir mp)
return (mp, ModPack
{ niceName = name
, background = dir </> mp </> "background.jpg"
, icon = dir </> mp </> "icon.png"
, logo = dir </> mp </> "logo.png"
, versions = mpvs
, recVersion = recommended
, newVersion = latest
})
getVersion :: FilePath -> FilePath -> FilePath -> IO String
getVersion dir mp v = do
isFile <- doesFileExist $ dir </> mp </> v
if isFile
then head <$> lines <$> readFile (dir </> mp </> v)
else do
v <- makeRelative (dir </> mp) <$> readSymbolicLink (dir </> mp </> v)
if null $ filter (== '/') v
then return v
else fail $ "Symbolic link " ++ (dir </> mp </> v) ++ " points outside " ++ (dir </> mp)
getModPackVersion :: FilePath -> FilePath -> FilePath -> IO (Maybe (String, ModPackVersion))
getModPackVersion dir mp mpv = do
isDir <- doesDirectoryExist $ dir </> mp </> mpv
if not isDir
then return Nothing
else Just <$> getModPackVersion' dir mp mpv
getModPackVersion' :: FilePath -> FilePath -> FilePath -> IO (String, ModPackVersion)
getModPackVersion' dir mp mpv = do
minecraft <- head <$> lines <$> readFile (dir </> mp </> mpv </> "minecraft.txt")
files <- filter (not . isPrefixOf ".") <$> getDirectoryContents (dir </> mp </> mpv)
return (mpv, ModPackVersion
{ minecraftVersion = minecraft
, minecraftJar = dir </> mp </> mpv </> "minecraft.jar"
, mods = M.fromList $ catMaybes $ map (parseMod dir mp mpv) files
})
parseMod :: FilePath -> FilePath -> FilePath -> FilePath -> Maybe (String, ModVersion)
parseMod dir mp mpv fp = case splitOn "_" fp of
[modName, versionDotZip] ->
let
vSplit = splitOn "." versionDotZip
version = init vSplit
zip = last vSplit
in case zip of
"zip" -> Just (modName, ModVersion (intercalate "." version) (dir </> mp </> mpv </> fp))
_ -> Nothing
_ -> Nothing
| jblake/solderapi | src/MkSolder.hs | mit | 3,524 | 0 | 19 | 816 | 1,189 | 606 | 583 | 85 | 4 |
module Sing where
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
sing1 = if ( x > y ) then fstString x else sndString y
where x = "Singin"
y = "Somewhere"
sing2 = if ( x < y ) then fstString x else sndString y
where x = "Singin"
y = "Somewhere"
main :: IO ()
main = do
putStrLn sing1
putStrLn sing2
| Lyapunov/haskell-programming-from-first-principles | chapter_5/sing.hs | mit | 440 | 0 | 7 | 139 | 161 | 87 | 74 | 15 | 2 |
{-
foldl (\x y -> 2*x + y) 4 [1,2,3]
= { applying (\x y -> 2*x + y), (x,y)=(4, 1) }
2*(4) + 1 = 9
= { applying (\x y -> 2*x + y), (x,y)=(9, 2) }
2*(9) + 2 = 20
= { applying (\x y -> 2*x + y), (x,y)=(20,3) }
2*(20) + 3 = 43
-}
| calebgregory/fp101x | wk3/foldl.hs | mit | 240 | 0 | 2 | 75 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE BangPatterns #-}
module Main where
import Control.Applicative ((<$>))
import Control.Concurrent.Async
import Control.Concurrent.MVar
import Control.Concurrent.STM
import Control.DeepSeq
import Control.Exception (evaluate)
import Control.Monad
import Control.Monad.IO.Class (liftIO)
import Criterion.Main
import Data.Hashable
import Data.List (foldl')
import Data.Foldable (foldlM)
import Data.Maybe
import System.Random
import System.Random.Shuffle
import System.IO.Unsafe
import Text.Printf
import qualified Control.Concurrent.Map as CM
import qualified Data.Map as M
import qualified Data.IntMap as IM
import qualified Data.HashMap.Strict as HM
instance (NFData k, NFData v) => NFData (CM.Map k v) where
rnf m = rnf $ unsafePerformIO $ CM.unsafeToList m
main :: IO ()
main = do
let o = 2^12
let bench_ t o n io = env (mkElems t o n) $ \elems ->
bench (printf "t=%d, o=%d, n=%d" t o n) $ whnfIO $ io elems
let bench_cm t o n = bench_ t o n $ \elems -> do
m <- CM.empty
runOps (\k -> CM.insert k k m) elems
bench_hm_mvar t o n = bench_ t o n $ \elems -> do
m <- newMVar HM.empty
runOps (\k -> hm_insert k k m) elems
bench_hm_tvar t o n = bench_ t o n $ \elems -> do
m <- newTVarIO HM.empty
runOps (\k -> hm_insert_tvar k k m) elems
defaultMain
[ bgroup "Insert"
[ bgroup "Control.Concurrent.Map"
[ bench_cm 100 o 1
, bench_cm 100 o (o `div` 10)
, bench_cm 100 o o
, bench_cm 1000 o 1
, bench_cm 1000 o (o `div` 10)
, bench_cm 1000 o o
]
, bgroup "Data.HashMap (TVar)"
[ bench_hm_tvar 100 o 1
, bench_hm_tvar 100 o (o `div` 10)
, bench_hm_tvar 100 o o
, bench_hm_tvar 1000 o 1
, bench_hm_tvar 1000 o (o `div` 10)
, bench_hm_tvar 1000 o o
]
--, bgroup "Data.HashMap (MVar)"
-- [ bench_hm_mvar 100 o 1
-- , bench_hm_mvar 100 o (o `div` 10)
-- , bench_hm_mvar 100 o o
-- ]
]
]
mkElems :: Int -> Int -> Int -> IO [[Int]]
mkElems t o n = return $ [take o $ randomRs (0, n-1) (mkStdGen s) | s <- [1..t]]
runOps :: (k -> IO a) -> [[k]] -> IO ()
runOps f elems = mapM_ wait =<< mapM (async . sequence_ . map f) elems
-----------------------------------------------------------------------
-- Control.Concurrent.Map
cm_lookup :: (Eq k, Hashable k) => k -> CM.Map k v -> IO ()
cm_lookup k m = do
let v = CM.lookup k m
v `seq` return ()
{-# SPECIALIZE cm_lookup :: String -> CM.Map String Int -> IO () #-}
{-# SPECIALIZE cm_lookup :: Int -> CM.Map Int Int -> IO () #-}
-----------------------------------------------------------------------
-- Data.HashMap (MVar)
hm_lookup :: (Eq k, Hashable k) => k -> MVar (HM.HashMap k v) -> IO ()
hm_lookup k mvar = do
m <- takeMVar mvar
putMVar mvar m
let v = HM.lookup k m
v `seq` return ()
{-# SPECIALIZE hm_lookup :: String -> MVar (HM.HashMap String Int) -> IO () #-}
{-# SPECIALIZE hm_lookup :: Int -> MVar (HM.HashMap Int Int) -> IO () #-}
hm_insert :: (Eq k, Hashable k) => k -> v -> MVar (HM.HashMap k v) -> IO ()
hm_insert k v mvar = do
m <- takeMVar mvar
putMVar mvar $! HM.insert k v m
{-# SPECIALIZE hm_insert :: String -> Int -> MVar (HM.HashMap String Int) -> IO () #-}
{-# SPECIALIZE hm_insert :: Int -> Int -> MVar (HM.HashMap Int Int) -> IO () #-}
hm_delete :: (Eq k, Hashable k) => k -> MVar (HM.HashMap k v) -> IO ()
hm_delete k mvar = do
m <- takeMVar mvar
putMVar mvar $! HM.delete k m
{-# SPECIALIZE hm_delete :: String -> MVar (HM.HashMap String Int) -> IO () #-}
{-# SPECIALIZE hm_delete :: Int -> MVar (HM.HashMap Int Int) -> IO () #-}
-----------------------------------------------------------------------
-- Data.HashMap (TVar)
hm_lookup_tvar :: (Eq k, Hashable k) => k -> TVar (HM.HashMap k v) -> IO ()
hm_lookup_tvar k tvar = do
v <- atomically $ do m <- readTVar tvar
return $ HM.lookup k m
v `seq` return ()
{-# SPECIALIZE hm_lookup_tvar :: String -> TVar (HM.HashMap String Int) -> IO () #-}
{-# SPECIALIZE hm_lookup_tvar :: Int -> TVar (HM.HashMap Int Int) -> IO () #-}
hm_insert_tvar :: (Eq k, Hashable k) => k -> v -> TVar (HM.HashMap k v) -> IO ()
hm_insert_tvar k v tvar = atomically $ modifyTVar' tvar (HM.insert k v)
{-# SPECIALIZE hm_insert_tvar :: String -> Int -> TVar (HM.HashMap String Int) -> IO () #-}
{-# SPECIALIZE hm_insert_tvar :: Int -> Int -> TVar (HM.HashMap Int Int) -> IO () #-}
hm_delete_tvar :: (Eq k, Hashable k) => k -> TVar (HM.HashMap k v) -> IO ()
hm_delete_tvar k tvar = atomically $ modifyTVar' tvar (HM.delete k)
{-# SPECIALIZE hm_delete_tvar :: String -> TVar (HM.HashMap String Int) -> IO () #-}
{-# SPECIALIZE hm_delete_tvar :: Int -> TVar (HM.HashMap Int Int) -> IO () #-}
| mcschroeder/ctrie | benchmarks/Concurrent.hs | mit | 5,062 | 0 | 18 | 1,385 | 1,482 | 767 | 715 | 100 | 1 |
main = print "NYI"
| TimoFreiberg/hanabi | test/Spec.hs | mit | 19 | 0 | 5 | 4 | 9 | 4 | 5 | 1 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Control.OperationalTransformation.Text.Gen
( genOperation'
, genOperation
) where
import Control.OperationalTransformation.Text
import Control.OperationalTransformation.Properties (ArbitraryFor (..))
import Test.QuickCheck hiding (Result)
import qualified Data.Text as T
import Control.Applicative ((<$>))
import Data.Monoid ((<>))
genOperation' :: Int -> Gen TextOperation
genOperation' = fmap TextOperation . gen
where
maxLength = 32
arbitraryText n = fmap (T.pack . take n) $ listOf1 (choose ('!', '~'))
insert text [] = [Insert text]
insert text (Insert text' : ops) = Insert (text <> text') : ops
insert text ops@(Retain _ : _) = Insert text : ops
insert text ops@(Delete _ : _) = Insert text : ops
delete d [] = [Delete d]
delete d (Insert text : ops) = Insert text : delete d ops
delete d ops@(Retain _ : _) = Delete d : ops
delete d (Delete d' : ops) = Delete (d+d') : ops
retain r [] = [Retain r]
retain r ops@(Insert _ : _) = Retain r : ops
retain r (Retain r' : ops) = Retain (r+r') : ops
retain r ops@(Delete _ : _) = Retain r : ops
gen l =
if l <= 0
then oneof [return [], fmap ((:[]) . Insert) (arbitraryText maxLength)]
else do
len <- choose (1, min maxLength l)
oneof [ retain len <$> gen (l - len)
, do s2 <- arbitraryText len
insert s2 <$> gen l
, delete len <$> gen (l - len)
]
genOperation :: T.Text -> Gen TextOperation
genOperation = genOperation' . T.length
instance ArbitraryFor T.Text TextOperation where
arbitraryFor = genOperation
instance Arbitrary T.Text where
arbitrary = T.pack <$> listOf (choose ('!', '~'))
instance Arbitrary TextOperation where
arbitrary = arbitrary >>= genOperation
| Operational-Transformation/ot.hs | test/Control/OperationalTransformation/Text/Gen.hs | mit | 1,879 | 0 | 15 | 459 | 739 | 385 | 354 | 44 | 11 |
module Main
where
import System.IO
import qualified Data.Tuple as T
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Foldable as F
import qualified Data.Array as Array
import qualified Data.Monoid as Monoid
import qualified Data.Char as Char
import qualified Data.Map.Strict as Map
import qualified Control.Arrow as Arrow
newtype Alphabet = Alphabet { getSize :: Int }
type Dictionary = S.Set String
type CharArray = Array.Array Int Char
type DPSet = S.Set CharArray
type DPArray = Array.Array Int DPSet
type Message = (Bool, Dictionary, Dictionary)
-- Make an alphabet of given size.
mkAlphabet :: Int -> Alphabet
mkAlphabet n
| n <= 0 = Alphabet { getSize = 0 }
| otherwise = Alphabet { getSize = n }
-- Return the first letter of the alphabet.
firstChar :: Char
firstChar = 'a'
-- Return the last letter of the alphabet.
lastChar :: Alphabet -> Char
lastChar Alphabet { getSize = s } = Char.chr $ Char.ord 'a' + (s-1)
-- Return the next letter.
nextLetter :: Alphabet -> Char -> Maybe Char
nextLetter alphabet c
| c < firstChar = Nothing
| c >= lastChar alphabet = Nothing
| otherwise = Just $ Char.chr ((1 + Char.ord c - Char.ord 'a') + Char.ord 'a')
-- Return the list of all even length prefixes of 'xs'.
evenPrefixes :: String -> [String]
evenPrefixes = fmap T.snd . L.filter (even . T.fst) . L.zip [1..] . L.tail . L.inits
-- Returns true iff each element has an even number of occurrences.
evenParikh :: String -> Bool
evenParikh = F.all (even . T.fst) . fmap (F.length Arrow.&&& L.head) . L.group . L.sort
-- Return true if the input string is a perfect square.
perfectSquare :: String -> Bool
perfectSquare xs = T.uncurry (==) $ L.splitAt (L.length xs `div` 2) xs
-- Return true if the input string is a square w.r.t. to the shufle product.
shuffleSquare :: String -> Bool
shuffleSquare xs = perfectSquare xs || (not . L.null $ shuffleSquareRoots xs)
-- Rreturn all shuffle square roots.
shuffleSquareRoots :: String -> [String]
shuffleSquareRoots xs
| odd n = []
| not (evenParikh xs) = []
| otherwise = shuffleSquareRoots' a n
where
n = L.length xs
a = Array.array (0, n-1) $ L.zip [0..] xs
shuffleSquareRoots' :: Array.Array Int Char -> Int -> [String]
shuffleSquareRoots' a n = shuffleSquareRootsStep 2 a n t
where
a' = Array.array (0, 0) [(0, a Array.! 0)]
t = Array.array (0, 0) [(0, S.singleton a')]
shuffleSquareRootsStep :: Int -> Array.Array Int Char -> Int -> DPArray -> [String]
shuffleSquareRootsStep i a n t
| i > n = fmap Array.elems . S.toList $ t Array.! (n `div` 2)
| otherwise = shuffleSquareRootsStep (i+1) a n t'
where
t' = mkArrayshuffleSquareRootsStep i a n t
mkArrayshuffleSquareRootsStep :: Int -> Array.Array Int Char -> Int -> DPArray -> DPArray
mkArrayshuffleSquareRootsStep i a n t = Array.array (lb, ub) assocs
where
lb = max 0 (i - (n `div` 2))
ub = i `div` 2
assocs = [(j, mkSet j) | j <- [lb..ub]]
mkSet j = S.union set1 set2
where
set1 = S.fromList $ mkSetAux1 j
set2 = S.fromList $ mkSetAux2 j
mkSetAux1 j
| j > 0 = [a' | a' <- S.toList $ t Array.! (j-1)
, a' Array.! (j-1) == a Array.! (i-1)]
| otherwise = []
mkSetAux2 j
| j <= b = [Array.array (lb', ub'+1) assocs | a' <- S.toList $ t Array.! j
, let (lb', ub') = Array.bounds a'
, let assoc = (ub'+1, a Array.! (i-1))
, let assocs = assoc : Array.assocs a']
| otherwise = []
where
b = min ((i-1) `div` 2) (n `div` 2)
-- Backtrack for next string.
backward :: Alphabet -> String -> String
backward alphabet [] = []
backward alphabet (x : xs) = case nextLetter alphabet x of
Nothing -> backward alphabet xs
Just x' -> x' : xs
-- Forward for next string.
forward :: String -> String
forward xs = firstChar : xs
explore :: Alphabet -> String -> IO ()
explore alphabet = aux S.empty S.empty
where
aux _ _ [] = error "unexpected empty buffer"
aux allowed forbidden xs =
if L.length xs == 1 && xs /= [firstChar]
then print "done."
else
let (res, allowed', forbidden') = explore' allowed forbidden xs in
if res
then do
putStrLn $ show (L.length xs) `Monoid.mappend`
". (allow: " `Monoid.mappend`
show (S.size allowed') `Monoid.mappend`
", forbidden: " `Monoid.mappend`
show (S.size forbidden') `Monoid.mappend`
"):\n" `Monoid.mappend`
show xs
hFlush stdout
aux allowed' forbidden' $ forward xs
else aux allowed' forbidden' $ backward alphabet xs
explore' :: Dictionary -> Dictionary -> String -> Message
explore' allowed forbidden = aux allowed forbidden . evenPrefixes
where
aux allowed' forbidden' [] = (True, allowed', forbidden')
aux allowed' forbidden' (p : ps)
| S.member p allowed' = aux allowed' forbidden' ps
| S.member p forbidden' = (False, allowed', forbidden')
| shuffleSquare p = (False, allowed', S.insert (L.reverse p) $ S.insert p forbidden')
| otherwise = aux (S.insert (L.reverse p) $ S.insert p allowed') forbidden' ps
main :: IO ()
main = let axiom = "a" in explore (mkAlphabet 4) axiom
| vialette/square-free-shuffle | Main.hs | mit | 5,951 | 0 | 23 | 1,969 | 1,990 | 1,042 | 948 | 109 | 4 |
module Text.Docvim.Visitor.Footer (extractFooter) where
import Control.Applicative
import Text.Docvim.AST
import Text.Docvim.Visitor
-- | Extracts a list of nodes (if any exist) from the `@footer` section(s) of
-- the source code.
--
-- It is not recommended to have multiple footers in a project. If multiple
-- footers (potentially across multiple translation units) exist, there are no
-- guarantees about order but they just get concatenated in the order we see
-- them.
extractFooter :: Alternative f => [Node] -> (f [Node], [Node])
extractFooter = extractBlocks f
where
f x = if x == FooterAnnotation
then Just endSection
else Nothing
| wincent/docvim | lib/Text/Docvim/Visitor/Footer.hs | mit | 669 | 0 | 9 | 126 | 104 | 63 | 41 | 9 | 2 |
module Main where
import Akari
import Data.Attoparsec.ByteString
import Data.ByteString.Char8
import System.IO (isEOF)
import Text.Printf
parseLoop :: (a -> IO ()) -> Parser a -> IO ()
parseLoop callback parser =
go (parse parser)
where
go cont = do
eof <- isEOF
if eof then pure () else do
line <- flip snoc '\n' <$> Data.ByteString.Char8.getLine
case cont line of
Fail _ _ e -> do
printf "Parse failed: %s\n" (show e)
go (parse parser)
Partial cont' -> go cont'
Done _ x -> do
printf "Working...\n"
callback x
go (parse parser)
main :: IO ()
main = parseLoop akari akariParser
| tjhance/logic-puzzles | src/Solvers/Akari/Main.hs | mit | 782 | 0 | 19 | 303 | 255 | 123 | 132 | 24 | 4 |
module Red.Parse.Prim
( wordToFloat
, wordToInt32
, niceHex8
, niceHex16
, niceHex32
, hexPrint
)
where
import Data.Word
import Data.Int
import Numeric
import qualified Foreign as F
import qualified Data.ByteString as B
import System.IO.Unsafe (unsafePerformIO)
toTarget :: (F.Storable word, F.Storable target) => word -> target
toTarget word = unsafePerformIO $ F.alloca $ \buf -> do
F.poke (F.castPtr buf) word
F.peek buf
fromTarget :: (F.Storable word, F.Storable target) => target -> word
fromTarget float = unsafePerformIO $ F.alloca $ \buf -> do
F.poke (F.castPtr buf) float
F.peek buf
floatToWord :: Float -> F.Word32
floatToWord = fromTarget
wordToFloat :: F.Word32 -> Float
wordToFloat = toTarget
wordToInt32 :: F.Word32 -> Int
wordToInt32 w = fromIntegral res
where
res :: Int32
res = toTarget w
niceHex8 :: Word8 -> String
niceHex8 v
| v < 16 = '0' : ps v
| otherwise = ps v
where ps = flip showHex ""
niceHex16 :: Word16 -> String
niceHex16 v
| v < 16 = '0' : '0' : '0' : ps v
| v < 256 = '0' : '0' : ps v
| v < 4096 = '0' : ps v
| otherwise = ps v
where ps = flip showHex ""
niceHex32 :: Word32 -> String
niceHex32 v
| v < 16 = '0' : '0' : '0' : '0' : '0' : '0' : '0' : ps v
| v < 256 = '0' : '0' : '0' : '0' : '0' : '0' : ps v
| v < 4096 = '0' : '0' : '0' : '0' : '0' : ps v
| v < 65536 = '0' : '0' : '0' : '0' : ps v
| v < 1048576 = '0' : '0' : '0' : ps v
| v < 16777216 = '0' : '0' : ps v
| v < 268435456 = '0' : ps v
| otherwise = ps v
where ps = flip showHex ""
hexPrint :: B.ByteString -> String
hexPrint = concat . map niceHex8 . B.unpack
| LeviSchuck/RedReader | Red/Parse/Prim.hs | mit | 1,775 | 0 | 12 | 551 | 747 | 373 | 374 | 54 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html
module Stratosphere.ResourceProperties.DLMLifecyclePolicyCreateRule where
import Stratosphere.ResourceImports
-- | Full data type definition for DLMLifecyclePolicyCreateRule. See
-- 'dlmLifecyclePolicyCreateRule' for a more convenient constructor.
data DLMLifecyclePolicyCreateRule =
DLMLifecyclePolicyCreateRule
{ _dLMLifecyclePolicyCreateRuleInterval :: Val Integer
, _dLMLifecyclePolicyCreateRuleIntervalUnit :: Val Text
, _dLMLifecyclePolicyCreateRuleTimes :: Maybe (ValList Text)
} deriving (Show, Eq)
instance ToJSON DLMLifecyclePolicyCreateRule where
toJSON DLMLifecyclePolicyCreateRule{..} =
object $
catMaybes
[ (Just . ("Interval",) . toJSON) _dLMLifecyclePolicyCreateRuleInterval
, (Just . ("IntervalUnit",) . toJSON) _dLMLifecyclePolicyCreateRuleIntervalUnit
, fmap (("Times",) . toJSON) _dLMLifecyclePolicyCreateRuleTimes
]
-- | Constructor for 'DLMLifecyclePolicyCreateRule' containing required fields
-- as arguments.
dlmLifecyclePolicyCreateRule
:: Val Integer -- ^ 'dlmlpcrInterval'
-> Val Text -- ^ 'dlmlpcrIntervalUnit'
-> DLMLifecyclePolicyCreateRule
dlmLifecyclePolicyCreateRule intervalarg intervalUnitarg =
DLMLifecyclePolicyCreateRule
{ _dLMLifecyclePolicyCreateRuleInterval = intervalarg
, _dLMLifecyclePolicyCreateRuleIntervalUnit = intervalUnitarg
, _dLMLifecyclePolicyCreateRuleTimes = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html#cfn-dlm-lifecyclepolicy-createrule-interval
dlmlpcrInterval :: Lens' DLMLifecyclePolicyCreateRule (Val Integer)
dlmlpcrInterval = lens _dLMLifecyclePolicyCreateRuleInterval (\s a -> s { _dLMLifecyclePolicyCreateRuleInterval = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html#cfn-dlm-lifecyclepolicy-createrule-intervalunit
dlmlpcrIntervalUnit :: Lens' DLMLifecyclePolicyCreateRule (Val Text)
dlmlpcrIntervalUnit = lens _dLMLifecyclePolicyCreateRuleIntervalUnit (\s a -> s { _dLMLifecyclePolicyCreateRuleIntervalUnit = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dlm-lifecyclepolicy-createrule.html#cfn-dlm-lifecyclepolicy-createrule-times
dlmlpcrTimes :: Lens' DLMLifecyclePolicyCreateRule (Maybe (ValList Text))
dlmlpcrTimes = lens _dLMLifecyclePolicyCreateRuleTimes (\s a -> s { _dLMLifecyclePolicyCreateRuleTimes = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/DLMLifecyclePolicyCreateRule.hs | mit | 2,689 | 0 | 13 | 268 | 356 | 202 | 154 | 34 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE KindSignatures #-}
infixr 5 :::
data HList (ts :: [ * ]) where
Nil :: HList '[]
(:::) :: t -> HList ts -> HList (t ': ts)
-- Take the head of a non-empty list with the first value as Bool type.
headBool :: HList (Bool ': xs) -> Bool
headBool hlist = case hlist of
(a ::: _) -> a
hlength :: HList x -> Int
hlength Nil = 0
hlength (_ ::: b) = 1 + (hlength b)
example1 :: (Bool, (String, (Double, ())))
example1 = (True, ("foo", (3.14, ())))
example2 :: HList '[Bool, String , Double , ()]
example2 = True ::: "foo" ::: 3.14 ::: () ::: Nil
| riwsky/wiwinwlh | src/hlist.hs | mit | 644 | 0 | 10 | 140 | 254 | 145 | 109 | 18 | 1 |
-- Project Euler Problem 27 - quadratic primes
--
-- Product a*b, |a|<1000, |b|<1000, s.t. n^2 + an + b \in [Prime] for [1..k] s.t. k is maximized
--
import Data.List
import Data.Ord
max_value = 10000
-- Note coprimes assumes the input list is sorted
coprimes :: (Integral a) => [a] -> [a]
coprimes [] = []
coprimes [x] = [x]
coprimes (x:xs) = x:(coprimes [a | a <- xs, a `mod` x /= 0])
primes = coprimes [2..max_value]
quad_seq a b = takeWhile (`elem` primes) [n^2 + a*n + b | n <- [0..]]
quad_lengths = [(l,(a,b)) | a <- [-999..999], b <- [-999..999], let q = quad_seq a b, let l = length q, l>0]
main = do
print (maximumBy (comparing fst) quad_lengths)
--print (sortBy (comparing fst) quad_lengths)
--print (quad_seq 1 41)
| yunwilliamyu/programming-exercises | project_euler/p027_quadratic_primes.hs | cc0-1.0 | 749 | 2 | 11 | 157 | 300 | 165 | 135 | 12 | 1 |
{-# LANGUAGE DoAndIfThenElse #-}
module Parser.CSV(parseCSV) where
import qualified Data.Text as Dtext
import Text.ParserCombinators.Parsec
import qualified Control.Exception as Exception
import Text.ARFF as ARFF
import qualified Data.ByteString as BS
import Data.ByteString.Char8(pack,unpack)
import Data.List(sort)
csvFile = endBy Parser.CSV.line eol
line = sepBy cell (char ',')
cell = many (noneOf ",\n")
eol = char '\n'
parseCSVt :: String -> String -> Either ParseError [[String]]
parseCSVt input filename = parse csvFile ("Error in : "++filename) input
-- | ParseCSV takes two arguments : contents of input file and its name. It returns the parsed data in the same format as ARFF file by creating
-- a pseudo header. The pseudo header is created by parsing the file and inferencing the type of attributes. The function also checks for malformed
-- data by checking that no of elemnts in every row is same. The function also handles any missing attributes by returning Nothing
-- for missing attributes. Any parse errors are displayed with line no. information to help user pinpoint the error quickly.
parseCSV:: String -> String -> IO (Either String (Header, [[Maybe AttributeValue]]) )
parseCSV input filename =
case (parseCSVt input filename) of
Right a -> case output of
Right a -> do
dt <- dataHeader
return (Right dt)
where
header = getHeader (transpose a)
dataHeader = getData a header
Left a -> return (Left a)
where
output= checkIntegrity (removeTrailingSpaces $ removeEmptyLines a) filename
Left a -> return (Left (show a))
-----------------------------------------------------------------------------------------------------------
--Functions for finding out data type of every attribute and generating arff type metadata
-----------------------------------------------------------------------------------------------------------
getData:: [[String]] -> IO Header -> IO (Header, [[Maybe AttributeValue]])
getData x header=
do
pureHeader<-header
let
fdata = toattributeValue x $ map (\x->dataType x) $ attributes pureHeader
return (pureHeader,fdata)
toattributeValue::[[String]] -> [AttributeType] -> [[Maybe AttributeValue]]
toattributeValue (x:xs) dataType = (zipWith toattrVal dataType x):(toattributeValue xs dataType)
toattributeValue [] dataType = []
toattrVal:: AttributeType -> String -> Maybe AttributeValue
toattrVal dataType x =
case dataType of
Numeric -> if x=="?" then Nothing
else
Just (NumericValue ((read x)::Double))
Nominal _ -> if x=="?" then Nothing
else
Just (NominalValue (pack x))
--getAttributes::[[String]]->[Attribute]
transpose:: [[String]]->[[String]]
transpose ([]:_) = []
transpose x = (map head x) : transpose (map tail x)
getHeader::[[String]]->IO Header
getHeader x = do
attrs <- getAttrList x 1 []
return Header{ title = (pack "CSVDATA"), attributes = attrs}
getAttrList:: [[String]] -> Int -> [Attribute] -> IO [Attribute]
getAttrList (x:xs) attrIndex curList=
do
dtype <- getType x
let
curAttr = (Attribute {name= (pack ("attribute"++show(attrIndex))) , dataType = dtype })
(getAttrList xs (attrIndex +1) (curList++[curAttr]))
getAttrList [] attrIndex curList = do
return curList
getType :: [String] -> IO AttributeType
getType x = do
ftype <- examineFeature x
case ftype of
Left a -> return (Nominal (sort (getNominalList x [])))
Right a -> return Numeric
examineFeature :: [String] -> IO (Either Exception.SomeException [a1])
examineFeature (x:xs) =
do
if (x=="?") then
examineFeature xs
else
do
feature <- Exception.try(Exception.evaluate ((read x)::Double))
case feature of
Left a -> return (Left a)
Right a -> examineFeature xs
examineFeature [] = return (Right [])
getNominalList :: [String] -> [BS.ByteString] -> [BS.ByteString]
getNominalList (x:xs) curlist = getNominalList xs (uniqueInsert curlist x)
getNominalList [] curList = curList
uniqueInsert:: [BS.ByteString] -> String -> [BS.ByteString]
uniqueInsert x y = if y=="?" then x
else
if ((ispresent x y) == True) then x
else
(x++ [pack y])
where
ispresent (x:xs) y =
if ((unpack x)==y) then True
else ispresent xs y
ispresent [] y = False
--------------------------------------------------------------------------------------------------------
--Functions for parsing and verifying format of data
--------------------------------------------------------------------------------------------------------
removeEmptyLines :: [[String]] -> [[String]]
removeEmptyLines (x:xs) = case (filter (not.null) x) of
[] -> removeEmptyLines xs
otherwise -> (filter (not.null) x) : (removeEmptyLines xs)
removeEmptyLines [] = []
checkIntegrity :: [[String]] -> String -> (Either String [[String]])
checkIntegrity [] filename = Right []
checkIntegrity (x:xs) filename =
if expLen == foundLen then
Right (x:xs)
else
Left ("Error in file "++filename++"\nNo of features in row "++show(foundLen)++ " do not match no of features in row "++show(foundLen+1))
where
expLen = (length xs) +1
foundLen = (length $ malformedInput xs (length x)) + 1
malformedInput (x:xs) len = if (length x) == len then
x : (malformedInput xs (length x))
else
[]
malformedInput [] len = []
removeTrailingSpaces:: [[String]] ->[[String]]
removeTrailingSpaces (x:xs) = (map (\x-> Dtext.unpack $ Dtext.strip $ Dtext.pack x) x ): (removeTrailingSpaces xs)
removeTrailingSpaces [] =[]
| anirudhhkumarr/ml-lib | src/Parser/CSV.hs | gpl-2.0 | 7,184 | 0 | 18 | 2,643 | 1,851 | 972 | 879 | 108 | 5 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances #-}
module RM.Machine where
-- $Id$
import Machine.Class
import RM.Type
import RM.Memory
import RM.State
import RM.Step
import Autolib.Set
import Autolib.FiniteMap
import Autolib.Reporter
import Autolib.ToDoc
import Control.Monad ( guard )
instance Compute Program State where
next _ = mkSet . step
accepting _ = ( == Nothing ) . program
depth _ = schritt
instance In Program Memory State where
input_reporter p m = return $ State
{ schritt = 0
, program = Just p
, memory = m
, past = []
}
instance Out Program Memory State where
output_reporter _ s = do
let m = memory s
let m0 = memory $ last $ past s
inform $ nest 4 $ text "Sind die Eingabewerte erhalten?"
let ok = and $ do (r,v) <- fmToList m0
return $ lookupFM m r == Just v
when ( not ok ) $ reject $ nest 4 $ text "Nein."
inform $ nest 4 $ text "Ja."
inform $ nest 4 $ text "Sind alle benutzten Register zurückgesetzt?"
let rs = 0 : keysFM m0
let bad = do b@(r,v) <- fmToList m
guard $ not $ elem r rs
guard$ v /= 0
return b
when ( not $ null bad ) $ reject $ nest 4 $ vcat
[ text "Nein. Diese Register enthalten noch Werte:"
, toDoc bad
]
inform $ nest 4 $ text "Ja."
return m
instance Encode Memory where
encode xs = RM.Memory.fromList $ zip [1..] xs
instance Decode Memory where
decode m = get m 0
| Erdwolf/autotool-bonn | src/RM/Machine.hs | gpl-2.0 | 1,543 | 18 | 22 | 481 | 520 | 268 | 252 | 46 | 0 |
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
-- Interface to `makepkg`.
{-
Copyright 2012, 2013, 2014 Colin Woodbury <colingw@gmail.com>
This file is part of Aura.
Aura 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.
Aura is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Aura. If not, see <http://www.gnu.org/licenses/>.
-}
module Aura.MakePkg
( makepkg
, makepkgSource
, makepkgConfFile ) where
import Text.Regex.PCRE ((=~))
import Aura.Monad.Aura
import Aura.Settings.Base (suppressMakepkg,makepkgFlagsOf)
import Aura.Shell (shellCmd, quietShellCmd, quietShellCmd', checkExitCode')
import Shell (pwd, ls)
---
type User = String
makepkgConfFile :: FilePath
makepkgConfFile = "/etc/makepkg.conf"
makepkgCmd :: FilePath
makepkgCmd = "/usr/bin/makepkg"
makepkg :: Aura (String -> Aura [FilePath])
makepkg = asks suppressMakepkg >>= \quiet ->
if quiet then return makepkgQuiet else return makepkgVerbose
-- TODO: Clean this up. Incompatible with `-x` and `--ignorearch`?
-- | Make a source package.
makepkgSource :: User -> Aura [FilePath]
makepkgSource user = do
quietShellCmd cmd opts
filter (=~ "[.]src[.]tar") <$> liftIO (pwd >>= ls)
where (cmd,opts) = runStyle user ["--allsource"]
-- Builds a package with `makepkg`.
-- Some packages create multiple .pkg.tar files. These are all returned.
makepkgGen :: (String -> [String] -> Aura a) -> User -> Aura [FilePath]
makepkgGen make user = asks makepkgFlagsOf >>= \clfs -> do
let (cmd,opts) = runStyle user clfs
make cmd (opts ++ clfs) >> filter (=~ "[.]pkg[.]tar") <$> liftIO (pwd >>= ls)
runStyle :: User -> [String] -> (String,[String])
runStyle "root" opts = (makepkgCmd, "--asroot" : opts)
runStyle user opts = ("sudo",["-u", user, makepkgCmd] ++ opts)
makepkgQuiet :: User -> Aura [FilePath]
makepkgQuiet = makepkgGen quiet
where quiet cmd opts = do
(status,out,err) <- quietShellCmd' cmd opts
let output = err ++ "\n" ++ out
checkExitCode' output status
makepkgVerbose :: User -> Aura [FilePath]
makepkgVerbose = makepkgGen shellCmd
| vigoos/Farrago-OS | aura-master/aura-master/src/Aura/MakePkg.hs | gpl-2.0 | 2,519 | 0 | 13 | 459 | 540 | 297 | 243 | 38 | 2 |
{-# LANGUAGE QuasiQuotes, RecordWildCards, NoCPP #-}
{-|
The @balancesheet@ command prints a simple balance sheet.
-}
module Hledger.Cli.Balancesheet (
balancesheetmode
,balancesheet
,tests_Hledger_Cli_Balancesheet
) where
import Data.String.Here
import System.Console.CmdArgs.Explicit
import Test.HUnit
import Hledger
import Hledger.Cli.CliOptions
import Hledger.Cli.CompoundBalanceCommand
balancesheetSpec = CompoundBalanceCommandSpec {
cbcname = "balancesheet",
cbcaliases = ["bs"],
cbchelp = [here|
This command displays a simple balance sheet, showing historical ending
balances of asset and liability accounts (ignoring any report begin date).
It assumes that these accounts are under a top-level `asset` or `liability`
account (case insensitive, plural forms also allowed).
|],
cbctitle = "Balance Sheet",
cbcqueries = [ ("Assets" , journalAssetAccountQuery),
("Liabilities", journalLiabilityAccountQuery)
],
cbctype = HistoricalBalance
}
balancesheetmode :: Mode RawOpts
balancesheetmode = compoundBalanceCommandMode balancesheetSpec
balancesheet :: CliOpts -> Journal -> IO ()
balancesheet = compoundBalanceCommand balancesheetSpec
tests_Hledger_Cli_Balancesheet :: Test
tests_Hledger_Cli_Balancesheet = TestList
[
]
| mstksg/hledger | hledger/Hledger/Cli/Balancesheet.hs | gpl-3.0 | 1,312 | 0 | 8 | 221 | 178 | 111 | 67 | 26 | 1 |
-- |
-- Copyright : (c) 2011 Simon Meier
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Simon Meier <iridcode@gmail.com>
--
-- Monoids for bounded types.
module Extension.Data.Bounded (
BoundedMax(..)
, BoundedMin(..)
) where
import Data.Monoid
-- | A newtype wrapper for a monoid of the maximum of a bounded type.
newtype BoundedMax a = BoundedMax {getBoundedMax :: a}
deriving( Eq, Ord, Show )
instance (Ord a, Bounded a) => Monoid (BoundedMax a) where
mempty = BoundedMax minBound
(BoundedMax x) `mappend` (BoundedMax y) = BoundedMax (max x y)
-- | A newtype wrapper for a monoid of the minimum of a bounded type.
newtype BoundedMin a = BoundedMin {getBoundedMin :: a}
deriving( Eq, Ord, Show )
instance (Ord a, Bounded a) => Monoid (BoundedMin a) where
mempty = BoundedMin maxBound
(BoundedMin x) `mappend` (BoundedMin y) = BoundedMin (min x y) | ekr/tamarin-prover | lib/utils/src/Extension/Data/Bounded.hs | gpl-3.0 | 965 | 0 | 8 | 253 | 241 | 138 | 103 | 14 | 0 |
{-|
Copyright : (c) Nathan Bloomfield, 2017
License : GPL-3
Maintainer : nbloomf@gmail.com
Stability : experimental
-}
module Hakyll.Shortcode.Types.Letters_Numbers_Hyphens_Underscores (
Letters_Numbers_Hyphens_Underscores()
) where
import Text.Regex.Posix ((=~))
import Hakyll.Shortcode.Validate
-- | Strings consisting only of a-z, A-Z, 0-9, -, and _.
newtype Letters_Numbers_Hyphens_Underscores
= Make { unMake :: String } deriving Eq
instance Validate Letters_Numbers_Hyphens_Underscores where
validate text = case text =~ "^[_a-zA-Z0-9-]+$" of
True -> Right $ Make text
False -> Left "Must be one or more alphanumeric characters, hyphens, or underscores."
instance Show Letters_Numbers_Hyphens_Underscores where
show = unMake
| nbloomf/hakyll-shortcode | src/Hakyll/Shortcode/Types/Letters_Numbers_Hyphens_Underscores.hs | gpl-3.0 | 765 | 0 | 10 | 123 | 112 | 66 | 46 | 14 | 0 |
module Model.Progression
(
module Data.Complex
, FComplex
, FractalProgression(..)
, mandelbrot
) where
import Data.Complex
type FComplex = Complex Double
data FractalProgression = FractalProgression {
progression :: FComplex -> FComplex -> FComplex
, start :: FComplex
}
-- TODO: make FractalProgression an instance of Read
-- mandelbrot progression
mandelbrot :: FractalProgression
mandelbrot = FractalProgression (\z c -> z^2 + c) (fromIntegral 0)
| phaazon/phraskell | src/Model/Progression.hs | gpl-3.0 | 482 | 0 | 10 | 93 | 111 | 66 | 45 | 13 | 1 |
module BabyRays.Scene where
import Core.Constants
import Core.Transform
import Core.Geometry
import BabyRays.Camera
import BabyRays.Types
import BabyRays.Color
import BabyRays.Light
import BabyRays.Shape
import BabyRays.Material
data Scene = Scene {backgroundColor :: Color,
ambientLight :: Color,
lights :: [Light],
shapes :: [Shape],
camera :: Camera,
image :: Image}
defaultScene = Scene {backgroundColor = (0,0,0),
ambientLight = (0.1,0.1,0.1),
-- lights = [Spotlight (Point 100 (-30) 0) nearlywhite,
-- Spotlight (Point 0 0 200) nearlywhite,
-- Spotlight (Point 0 0 200) nearlywhite],
lights = [Spotlight cameraLoc nearlywhite],
shapes = objs,
camera = view,
image = film}
where (view, film) = stdCamera cameraLoc (Vector 0 0 1) (Vector 0 1 0) (Vector 1 0 0)
cameraLoc = Point 0 0 (-200)
-- (view, film) = stdCamera 100 cameraLoc dir up right -- (hat $ up `cross` dir)
-- cameraLoc = Point 0 (-100) 0
-- dir = (Point 0 0 200) .-. cameraLoc
-- up = Vector 0 (1) 0
-- right = Vector 1 0 0
-- dir@(Vector vx vy vz) = Point 50 35 100 .-. cameraLoc
-- wx = -(vy*vy + vz*vz) / (vx*vy)
-- wz = vz/vy
-- up = Vector wx 1 wz
u = Vector 100 0 0
v = Vector 0 100 0
w = Vector 0 0 100
objs = makeBox flatred (Point (-100) 0 100) u v w
-- objs = [Triangle (Point 0 0 100) (Point 100 0 100) (Point 100 100 100) flatgreen,
-- Triangle (Point 0 0 100) (Point 100 100 100) (Point 0 100 100) flatgreen,
-- Triangle (Point 0 100 100) (Point 100 100 100) (Point 100 100 200) flatgreen]
-- objs = [Sphere (Point 0 0 0) 65 flatred]
-- objs = [Triangle (Point 0 0 25) (Point 100 0 25) (Point 0 100 25) flatred]
cornellBox = Scene {backgroundColor = black,
ambientLight = cornellAmbient,
-- lights = [lamp, Spotlight (Point 0 0 (-cl)) nearlywhite],
lights = lamps,
shapes = floor ++ bWall ++ ceil ++ lWall ++ rWall ++ rBox ++ lBox,
camera = camera,
image = image}
where cl = 200
-- w = 100
lh = 90
h = 100
d = 100
(camera, image) = stdCamera (Point 0 0 (-cl)) (Vector 0 0 1) (Vector 0 1 0) (Vector 1 0 0)
-- floor = finitePlane flatred (Point (-50) 25 0) (Vector 100 0 0) (Vector 0 0 100)
-- u = Vector 300 0 0
-- v = Vector 0 1 0
-- w = Vector 0 0 300
wallColor = cornellWhite
floor = [Triangle (Point (-150) 150 100) (Point (-150) 150 400) (Point 150 150 400) wallColor,
Triangle (Point (-150) 150 100) (Point 150 150 400) (Point 150 150 100) wallColor]
bWall = [Triangle (Point (-150) 150 400) (Point (-150) (-150) 400) (Point 150 150 400) wallColor,
Triangle (Point (-150) (-150) 400) (Point 150 (-150) 400) (Point 150 150 400) wallColor]
ceil = [Triangle (Point (-150) (-150) 400) (Point (-150) (-150) 100) (Point 150 (-150) 400) wallColor,
Triangle (Point (-150) (-150) 100) (Point 150 (-150) 100) (Point 150 (-150) 400) wallColor]
lWall = [Triangle (Point (-150) 150 100) (Point (-150) (-150) 100) (Point (-150) 150 400) cornellRed,
Triangle (Point (-150) (-150) 100) (Point (-150) (-150) 400) (Point (-150) 150 400) cornellRed]
rWall = [Triangle (Point 150 150 400) (Point 150 (-150) 100) (Point 150 150 100) cornellGreen,
Triangle (Point 150 150 400) (Point 150 (-150) 400) (Point 150 (-150) 100) cornellGreen]
rRot = rotateY 20
[u,v,w] = map (appTrans rRot) [Vector 90 0 0, Vector 0 (-90) 0, Vector 0 0 90]
rBox = makeBox wallColor (Point (-10) 150 150) u v w
lRot = rotateY (-20)
[u',v',w'] = map (appTrans lRot) [Vector 90 0 0, Vector 0 (-180) 0, Vector 0 0 90]
lBox = makeBox wallColor (Point (-80) 150 210) u' v' w'
entry = Point 0 0 0
-- camera = Camera {location = Point 0 0 0,
-- screenDist = cl,
-- lookingAt = entry,
-- upDir = Vector 0 1 0}
-- film = let sw = entry .+^ Vector (-w/2) (h/2) 0
-- in (sw, sw .+^ Vector 0 (-h) 0, sw .+^ Vector w 0 0)
-- sphere = Sphere (Point (-75) 100 250) 50 flatred
lamps = [Spotlight (Point x (-145) (250+z)) (0.00075,0.00075,0.00075) | x <- [-30,-20..30], z <- [-30,-20..30]]
-- lamps = [Spotlight (Point 0 (-145) 250) (0.125, 0.125, 0.125)]
| dsj36/dropray | src/BabyRays/Scene.hs | gpl-3.0 | 5,055 | 0 | 12 | 1,898 | 1,395 | 774 | 621 | 58 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Storage which contains data about explorers.
module RSCoin.Bank.Storage.Explorers
( ExplorersStorage
, mkExplorersStorage
, Query
, getExplorers
, getExplorersAndPeriods
, Update
, addExplorer
, removeExplorer
, setExplorerPeriod
, suspendExplorer
, restoreExplorers
) where
import Control.Lens (Getter, at, makeLenses, to, use, uses, (%=), (.=),
(<>=))
import Control.Monad.Except (ExceptT, MonadError (throwError))
import Control.Monad.State (State)
import Data.List (find)
import qualified Data.Map as M
import Data.SafeCopy (base, deriveSafeCopy)
import Formatting (int, sformat, string, (%))
import RSCoin.Bank.Error (BankError (BEBadRequest))
import qualified RSCoin.Core as C
data ExplorersStorage = ExplorersStorage
{ -- | All explorers in storage. Explorer is associated with
-- `PeriodId`. This is id of block which Explorer expects to
-- receive.
_esExplorers :: !(M.Map C.Explorer C.PeriodId)
-- | Some explorers may be suspended if something suspicious is
-- detected.
, _esSuspendedExplorers :: !(M.Map C.Explorer C.PeriodId)
}
$(makeLenses ''ExplorersStorage)
$(deriveSafeCopy 0 'base ''ExplorersStorage)
mkExplorersStorage :: ExplorersStorage
mkExplorersStorage =
ExplorersStorage
{ _esExplorers = M.empty
, _esSuspendedExplorers = M.empty
}
type Query a = Getter ExplorersStorage a
-- | Get list of all explorers in storage.
getExplorers :: Query C.Explorers
getExplorers = esExplorers . to M.keys
-- | Get list of all explorers in storage and ids of periods they
-- expect to receive.
getExplorersAndPeriods :: Query [(C.Explorer, C.PeriodId)]
getExplorersAndPeriods = esExplorers . to M.assocs
type Update = State ExplorersStorage
type ExceptUpdate = ExceptT BankError Update
-- | Add given explorer to storage and associate given PeriodId with
-- it. If explorer exists, it is updated.
addExplorer :: C.Explorer -> C.PeriodId -> Update ()
addExplorer e pId = esExplorers . at e .= Just pId
-- | Removes a host that matches host/port, fails if not present
removeExplorer :: String -> Int -> ExceptUpdate ()
removeExplorer host port = do
expls <- uses esExplorers M.keys
let res = find (\C.Explorer{..} -> explorerHost == host &&
explorerPort == port) expls
maybe (throwError $ BEBadRequest $
sformat ("Explorer with host " % string % " and port " % int %
" is not in the storage, can't remove") host port)
(\explorer -> esExplorers %= M.delete explorer)
res
-- | Update expected period id of given explorer. Adds explorer if it
-- doesn't exist.
setExplorerPeriod :: C.Explorer -> C.PeriodId -> Update ()
setExplorerPeriod = addExplorer
-- | Temporarily delete explorer from storage until `restoreExplorers` is called.
suspendExplorer :: C.Explorer -> Update ()
suspendExplorer explorer = do
explorerData <- use $ esExplorers . at explorer
esExplorers . at explorer .= Nothing
esSuspendedExplorers . at explorer .= explorerData
-- | Restore all suspended explorers.
restoreExplorers :: Update [C.Explorer]
restoreExplorers = do
suspended <- use esSuspendedExplorers
esExplorers <>= suspended
esSuspendedExplorers .= mempty
return $ M.keys suspended
| input-output-hk/rscoin-haskell | src/RSCoin/Bank/Storage/Explorers.hs | gpl-3.0 | 3,645 | 0 | 15 | 924 | 748 | 416 | 332 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Logging.Organizations.Logs.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes all the log entries in a log. The log reappears if it receives
-- new entries.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Stackdriver Logging API Reference> for @logging.organizations.logs.delete@.
module Network.Google.Resource.Logging.Organizations.Logs.Delete
(
-- * REST Resource
OrganizationsLogsDeleteResource
-- * Creating a Request
, organizationsLogsDelete
, OrganizationsLogsDelete
-- * Request Lenses
, oldXgafv
, oldUploadProtocol
, oldPp
, oldAccessToken
, oldUploadType
, oldBearerToken
, oldLogName
, oldCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.organizations.logs.delete@ method which the
-- 'OrganizationsLogsDelete' request conforms to.
type OrganizationsLogsDeleteResource =
"v2" :>
Capture "logName" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes all the log entries in a log. The log reappears if it receives
-- new entries.
--
-- /See:/ 'organizationsLogsDelete' smart constructor.
data OrganizationsLogsDelete = OrganizationsLogsDelete'
{ _oldXgafv :: !(Maybe Xgafv)
, _oldUploadProtocol :: !(Maybe Text)
, _oldPp :: !Bool
, _oldAccessToken :: !(Maybe Text)
, _oldUploadType :: !(Maybe Text)
, _oldBearerToken :: !(Maybe Text)
, _oldLogName :: !Text
, _oldCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'OrganizationsLogsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'oldXgafv'
--
-- * 'oldUploadProtocol'
--
-- * 'oldPp'
--
-- * 'oldAccessToken'
--
-- * 'oldUploadType'
--
-- * 'oldBearerToken'
--
-- * 'oldLogName'
--
-- * 'oldCallback'
organizationsLogsDelete
:: Text -- ^ 'oldLogName'
-> OrganizationsLogsDelete
organizationsLogsDelete pOldLogName_ =
OrganizationsLogsDelete'
{ _oldXgafv = Nothing
, _oldUploadProtocol = Nothing
, _oldPp = True
, _oldAccessToken = Nothing
, _oldUploadType = Nothing
, _oldBearerToken = Nothing
, _oldLogName = pOldLogName_
, _oldCallback = Nothing
}
-- | V1 error format.
oldXgafv :: Lens' OrganizationsLogsDelete (Maybe Xgafv)
oldXgafv = lens _oldXgafv (\ s a -> s{_oldXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
oldUploadProtocol :: Lens' OrganizationsLogsDelete (Maybe Text)
oldUploadProtocol
= lens _oldUploadProtocol
(\ s a -> s{_oldUploadProtocol = a})
-- | Pretty-print response.
oldPp :: Lens' OrganizationsLogsDelete Bool
oldPp = lens _oldPp (\ s a -> s{_oldPp = a})
-- | OAuth access token.
oldAccessToken :: Lens' OrganizationsLogsDelete (Maybe Text)
oldAccessToken
= lens _oldAccessToken
(\ s a -> s{_oldAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
oldUploadType :: Lens' OrganizationsLogsDelete (Maybe Text)
oldUploadType
= lens _oldUploadType
(\ s a -> s{_oldUploadType = a})
-- | OAuth bearer token.
oldBearerToken :: Lens' OrganizationsLogsDelete (Maybe Text)
oldBearerToken
= lens _oldBearerToken
(\ s a -> s{_oldBearerToken = a})
-- | Required. The resource name of the log to delete:
-- \"projects\/[PROJECT_ID]\/logs\/[LOG_ID]\"
-- \"organizations\/[ORGANIZATION_ID]\/logs\/[LOG_ID]\" [LOG_ID] must be
-- URL-encoded. For example, \"projects\/my-project-id\/logs\/syslog\",
-- \"organizations\/1234567890\/logs\/cloudresourcemanager.googleapis.com%2Factivity\".
-- For more information about log names, see LogEntry.
oldLogName :: Lens' OrganizationsLogsDelete Text
oldLogName
= lens _oldLogName (\ s a -> s{_oldLogName = a})
-- | JSONP
oldCallback :: Lens' OrganizationsLogsDelete (Maybe Text)
oldCallback
= lens _oldCallback (\ s a -> s{_oldCallback = a})
instance GoogleRequest OrganizationsLogsDelete where
type Rs OrganizationsLogsDelete = Empty
type Scopes OrganizationsLogsDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/logging.admin"]
requestClient OrganizationsLogsDelete'{..}
= go _oldLogName _oldXgafv _oldUploadProtocol
(Just _oldPp)
_oldAccessToken
_oldUploadType
_oldBearerToken
_oldCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy :: Proxy OrganizationsLogsDeleteResource)
mempty
| rueshyna/gogol | gogol-logging/gen/Network/Google/Resource/Logging/Organizations/Logs/Delete.hs | mpl-2.0 | 5,815 | 0 | 17 | 1,334 | 859 | 502 | 357 | 121 | 1 |
module Identity where
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
newtype Identity a = Identity a
deriving (Eq, Ord, Show)
instance Functor Identity where
fmap f (Identity a) = Identity $ f a
instance Foldable Identity where
foldMap f (Identity a) = f a
instance Traversable Identity where
traverse f (Identity a) = fmap Identity (f a)
sequenceA (Identity a) = fmap Identity a
instance Arbitrary a => Arbitrary (Identity a) where
arbitrary = do
a <- arbitrary
return $ Identity a
instance Eq a => EqProp (Identity a) where
(=-=) = eq
data Optional a =
Nada
| Yep a
instance Traversable Optional where
sequenceA Nada = mempty
sequenceA (Yep a) = fmap Yep a
instance Functor Optional where
fmap f (Yep a) = Yep $ f a
fmap _ Nada = Nada
instance Foldable Optional where
foldMap f (Yep a) = f a
foldMap _ Nada = mempty
instance Applicative Optional where
pure = Yep
Nada <*> _ = Nada
_ <*> Nada = Nada
(Yep f) <*> (Yep a) = Yep (f a)
main :: IO ()
main = do
let trigger = undefined :: Identity (Int, Int, [Int])
quickBatch (traversable trigger)
| thewoolleyman/haskellbook | 21/12/haskell-club/ChapterExercises.hs | unlicense | 1,149 | 0 | 12 | 260 | 475 | 240 | 235 | 40 | 1 |
module Git.Command.FormatPatch (run) where
run :: [String] -> IO ()
run args = return () | wereHamster/yag | Git/Command/FormatPatch.hs | unlicense | 89 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
module Data.Tree.Monadic (
MTree(..),
-- * Running trees
-- These functions traverse MTrees and return pure rose trees.
-- Their drawback is that they keep the entire tree in memory.
-- If you are only interested in the monadic effects and not
-- the actual values, it is best to discard the result to save space.
materialize,
materializePar,
-- * Folding, unfolding MTrees
unfoldMTree,
leaves,
justLeaves,
traverseM,
) where
import Control.Concurrent.STM.Utils
import Control.Monad as C
import Data.Collections.Instances()
import Data.Functor.FunctorM
import Data.Tree as T
-- |A monadic rose tree in which the child nodes are wrapped in a monad.
-- @l@ is the type of the keys in the leaf nodes and @n@ the type
-- of the keys in the inner nodes.
data MTree m n = -- |An internal nodes with a value and children
-- wrapped in a monad.
MTree (m (n, [MTree m n]))
instance (Functor m) => Functor (MTree m) where
fmap f (MTree m) = MTree $ fmap (\(x,xs) -> (f x, map (fmap f) xs)) m
instance (Functor m, Monad m) => FunctorM (MTree m) m where
fmapM f (MTree m) = return $ MTree $ do
(x,xs) <- m
liftM2 (,) (f x) (mapM (fmapM f) xs)
-- |Completely unrolls an 'MTree' into a 'Tree' __depth-first__,
-- evaluating all nodes.
--
-- The time is @O(n)@ where @n@ is the number of nodes.
-- The space is @O(n)@ if the result is kept and @O(d)@ if it isn't,
-- with @d@ being the maximal depth of the tree.
materialize :: Monad m => MTree m n -> m (Tree n)
materialize (MTree m) = do
(v, children) <- m
children' <- mapM materialize children
return $ T.Node v children'
-- |Unrolls an 'MTree' into a tree, executing the monadic operations in
-- parallel. 'materializePar' is generalization of 'materialize' and is
-- superior to it if the 'MTree' contains IO-heavy
-- operations like HTTP requests.
--
-- The time @Omega(n/t)@, where @n@ is the number of nodes and @t@ is the
-- size of the thread pool - with optimal parallelism, @t@ nodes can be
-- processed at once (although this depends on the shape of the tree. In
-- the worst case of a list, @t@ makes no difference at all.
-- The space is @O(n)@ if the result is kept and @O(dt)@ if it isn't.
--
-- Note that a node's children may be rearranged, depending
-- on the order in which their processing finishes.
materializePar :: TaskLimit
-- ^The upper limit on simultaneous tasks.
-- For @n=1@, 'materializePar' behaves identically to
-- materialize. For very large @n@, every node gets its own
-- thread. Depending on the IO operations, this value should
-- be kept within reason.
-> MTree IO n
-> IO (Tree n)
materializePar numTasks (MTree m) = do
(v, children) <- withTaskLimit numTasks m
results <- parMapSTM (materializePar numTasks) children
return $ Node v results
-- |Unfolds an 'MTree' from a monadic value.
-- Analogous to 'Data.Tree.unfoldTreeM'
unfoldMTree :: Monad m => (b -> m (a, [b])) -> m b -> MTree m a
unfoldMTree f x = MTree $ do (y, ys) <- x >>= f
return $ (y, map (unfoldMTree f . return) ys)
-- |Leaf function on trees.
leaves :: (s -> n -> a) -- ^Result calculator, applied to the leaves.
-> (s -> n -> s) -- ^State updater, applied on non-leaves.
-> s -- ^Initial state.
-> T.Tree n
-> [a]
leaves f _ seed (Node n []) = [f seed n]
leaves f g seed (Node n xs) = concatMap (leaves f g (g seed n)) xs
traverseM :: Monad m
=> (s -> n -> m (s,a))
-> s
-> MTree m n
-> MTree m a
traverseM f st (MTree m) = MTree $ do
(n, ns) <- m
(st',n') <- f st n
return $ (n', map (traverseM f st') ns)
-- |Collects just the leaves of a tree. Convenience function.
justLeaves :: (n -> a) -> T.Tree n -> [a]
justLeaves f = leaves (const f) undefined undefined
| jtapolczai/Hephaestos | Data/Tree/Monadic.hs | apache-2.0 | 4,099 | 1 | 14 | 1,072 | 921 | 499 | 422 | 57 | 1 |
{-
Copyright 2015 Arun Raghavan <mail@arunraghavan.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE RecordWildCards #-}
module UCM
( Command (..)
, Sequence (..)
, Device (..)
, Modifier (..)
, Verb (..)
, Config (..)
, generateFiles
) where
import Data.List (find)
import Data.Maybe (maybeToList)
-- CSet name value | Exec command
data Command = CSet { csetName :: String,
csetIndex :: Maybe String,
csetValue :: String } |
Exec { execCommand :: String } deriving (Eq, Ord, Show)
-- Sequence ctl commands
data Sequence = Sequence { seqCtl :: String,
seqCommands :: [ Command ] } deriving (Eq, Ord, Show)
-- ice name enable disable conflicts values
data Device = Device { devName :: String,
devDesc :: String,
devPlaybackChannels :: String,
devCaptureChannels :: String,
devPlaybackVolume :: String,
devCaptureVolume :: String,
devEnableSeq :: Sequence,
devDisableSeq :: Sequence,
devConflicts :: [String],
devValues :: [(String, String)] } deriving (Eq, Ord, Show)
-- Modifier name playDev captureDev enable disable supports values
data Modifier = Modifier { modName :: String,
modDesc :: String,
modPlayDevice :: String,
modCaptureDevice :: String,
modEnableSeq :: Sequence,
modDisableSeq :: Sequence,
modSupports :: [String],
modValues :: [(String, String)] } deriving (Eq, Ord, Show)
-- Verb name playDev captureDev enable disable devices modifiers values
data Verb = Verb { verbName :: String,
verbDesc :: String,
verbPlayDevice :: String,
verbCaptureDevice :: String,
verbEnableSeq :: Sequence,
verbDisableSeq :: Sequence,
verbDevices :: [Device],
verbModifiers :: [Modifier],
verbValues :: [(String, String)] } deriving (Eq, Ord, Show)
-- Config cardName verbs
data Config = Config { confCard :: String,
confVerbs :: [Verb],
confDefaults :: Sequence } deriving (Eq, Show, Ord)
-- Write out UCM file
indentInc :: Int
indentInc = 8
quote :: String -> String
quote s =
"\"" ++ s ++ "\""
writeLine :: Int -> String -> String
writeLine indent line = replicate indent ' ' ++ line ++ "\n"
writeStrings :: Int -> [String] -> String
writeStrings i =
concatMap (writeLine i . quote)
writeSection :: Int -> String -> Maybe String -> (Int -> a -> String) -> a -> String
writeSection i section name objToStr obj =
writeLine i (section ++ writeSectionName name ++ " {") ++
objToStr (i + indentInc) obj ++
writeLine i "}" ++
"\n"
where
writeSectionName Nothing = ""
writeSectionName (Just s) = "." ++ quote s
maybeWriteSection :: Int -> String -> Maybe String -> (Int -> [a] -> String) -> [a] -> String
maybeWriteSection _ _ _ _ [] = ""
maybeWriteSection i section name objToStr obj = writeSection i section name objToStr obj
writeList :: Int -> String -> (Int -> a -> String) -> a -> String
writeList i name objToStr obj =
writeLine i (name ++ " [") ++
objToStr (i + indentInc) obj ++
writeLine i "]" ++
"\n"
writeCommand :: Int -> Command -> String
writeCommand i control =
writeLine i (ucmCommandToStr control)
where
ucmCommandToStr (CSet name Nothing value) =
"cset " ++ quote ("name='" ++ name ++ "' " ++ value)
-- FIXME: can we emit a single, collated line instead of one per index?
ucmCommandToStr (CSet name (Just index) value) =
"cset " ++ quote ("name='" ++ name ++ "' " ++ replicate (read index - 1) ',' ++ value)
ucmCommandToStr (Exec cmd) =
"exec " ++ quote cmd
writeSequence :: Int -> Sequence -> String
writeSequence i Sequence{..} =
writeLine i ("cdev " ++ quote seqCtl) ++ "\n" ++
concatMap (writeCommand i) seqCommands
writeValue :: Int -> (String, String) -> String
writeValue i (n, v) =
writeLine i (n ++ " " ++ quote v)
writeValues :: Int -> [(String, String)] -> String
writeValues i =
concatMap (writeValue i)
writeComment :: Int -> String -> String
writeComment _ "" = ""
writeComment i c =
writeLine i ("Comment " ++ quote c ++ "\n")
writeSequences :: Int -> Sequence -> Sequence -> String
writeSequences i en dis =
writeList i "EnableSequence" writeSequence en ++
writeList i "DisableSequence" writeSequence dis
filterEmpty :: [(String, String)] -> [(String, String)]
filterEmpty = filter isEmpty
where
isEmpty (_, "") = False
isEmpty _ = True
-- Gets the disable sequence and adds a volume reset if required
getDisableSeq :: Config -> Device -> Sequence
getDisableSeq (Config _ _ (Sequence _ defaults)) (Device _ _ _ _ pVol cVol _ (Sequence ctl cmds) _ _) =
Sequence ctl (cmds ++ maybeDisableVolume pVol ++ maybeDisableVolume cVol)
where
maybeDisableVolume v = maybeToList $ find (findVolume v) defaults
findVolume v (CSet name _ _) = (v ++ " Volume") == name
findVolume _ _ = False
writeDevice :: Int -> Config -> Device -> String
writeDevice i conf dev@Device{..} =
writeSection i "SectionDevice" (Just devName) writeDevice' dev
where
writeDevice' i' _ =
writeComment i' devDesc ++
writeList i' "ConflictingDevice" writeStrings devConflicts ++
writeSequences i' devEnableSeq (getDisableSeq conf dev) ++
maybeWriteSection i' "Value" Nothing writeValues (devValues ++ genDevValues)
genDevValues =
filterEmpty [("PlaybackChannels", devPlaybackChannels),
("CaptureChannels", devCaptureChannels),
("PlaybackVolume", devPlaybackVolume),
("CaptureVolume", devCaptureVolume)]
writeModifier :: Int -> Modifier -> String
writeModifier i m@Modifier{..} =
writeSection i "SectionModifier" (Just modName) writeModifier' m
where
writeModifier' i' _ =
writeComment i' modDesc ++
writeList i' "SupportedDevice" writeStrings modSupports ++
writeSequences i' modEnableSeq modDisableSeq ++
maybeWriteSection i' "Value" Nothing writeValues (modValues ++ genModValues)
genModValues =
filterEmpty [("PlaybackPCM", modPlayDevice),
("CapturePCM", modCaptureDevice)]
writeVerb :: Int -> Verb -> String
writeVerb i Verb{..} =
writeSequences i verbEnableSeq verbDisableSeq ++
maybeWriteSection i "Value" Nothing writeValues (verbValues ++ genVerbValues)
where
genVerbValues =
filterEmpty [("PlaybackPCM", verbPlayDevice),
("CapturePCM", verbCaptureDevice)]
writeVerbFile :: Config -> Verb -> (String, String)
writeVerbFile conf verb@Verb{..} =
(verbName,
writeSection 0 "SectionVerb" Nothing writeVerb verb ++
concatMap (writeDevice 0 conf) verbDevices ++
concatMap (writeModifier 0) verbModifiers)
writeConfigVerb :: Int -> Verb -> String
writeConfigVerb i Verb{..} =
writeLine i ("File " ++ quote verbName) ++
writeComment i verbDesc
writeConfigUseCase :: Int -> Verb -> String
writeConfigUseCase i verb@Verb{..} =
writeSection i "SectionUseCase" (Just verbName) writeConfigVerb verb
writeConfigFile :: Config -> (String, String)
writeConfigFile Config{..} =
(confCard ++ ".conf",
concatMap (writeConfigUseCase 0) confVerbs ++
writeList 0 "SectionDefaults" writeSequence confDefaults)
generateFiles :: Config -> [(String, String)]
generateFiles conf@Config{..} =
writeConfigFile conf : map (writeVerbFile conf) confVerbs
| ford-prefect/xml2ucm | src/UCM.hs | apache-2.0 | 8,279 | 0 | 15 | 2,152 | 2,254 | 1,217 | 1,037 | 163 | 3 |
module Import
( module Prelude
, module Yesod
, module Foundation
, (<>)
, Text
, unpack
, module Data.Monoid
, module Control.Applicative
) where
import Prelude hiding (writeFile, readFile)
import Yesod hiding (Route(..))
import Foundation
import Data.Monoid (Monoid (mappend, mempty, mconcat))
import Control.Applicative ((<$>), (<*>), pure)
import Data.Text (Text, unpack)
infixr 5 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
| qzchenwl/myweb | Import.hs | bsd-2-clause | 475 | 0 | 7 | 107 | 154 | 103 | 51 | 18 | 1 |
-- 932718654
import Euler(digitUsage, fromDigits, toDigitsBase)
nn = 9
genMult0 _ [] _ = error "genMult0: empty"
genMult0 xs (y:ys) n
| length xs2 == n = fromDigits xs2
| length xs2 > n = 0
| otherwise = genMult0 xs2 ys n
where xs2 = xs ++ toDigitsBase 10 y
genMult n x = genMult0 [] [x,x+x..] n
largestPanMult n = maximum $ filter isPandigital $ map (genMult n) [1..z-1]
where z = 10^(n `div` 2) -- need to generate at least 2 numbers
isPandigital x = digitUsage (fromDigits [1..n]) == digitUsage x
main = putStrLn $ show $ largestPanMult nn
| higgsd/euler | hs/38.hs | bsd-2-clause | 577 | 0 | 11 | 136 | 255 | 128 | 127 | 13 | 1 |
{-# LANGUAGE PatternGuards, CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Convert
-- Copyright : (c) Isaac Dupree 2009,
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Conversion between TyThing and HsDecl. This functionality may be moved into
-- GHC at some point.
-----------------------------------------------------------------------------
module Haddock.Convert where
-- Some other functions turned out to be useful for converting
-- instance heads, which aren't TyThings, so just export everything.
import HsSyn
import TcType ( tcSplitSigmaTy )
import TypeRep
import Type(isStrLitTy)
import Kind ( splitKindFunTys, synTyConResKind, isKind )
import Name
import Var
import Class
import TyCon
import CoAxiom
import ConLike
import DataCon
import PatSyn
import FamInstEnv
import BasicTypes ( TupleSort(..) )
import TysPrim ( alphaTyVars )
import TysWiredIn ( listTyConName, eqTyCon )
import PrelNames (ipClassName)
import Bag ( emptyBag )
import Unique ( getUnique )
import SrcLoc ( Located, noLoc, unLoc )
import Data.List( partition )
import Haddock.Types
-- the main function here! yay!
tyThingToLHsDecl :: TyThing -> LHsDecl Name
tyThingToLHsDecl t = noLoc $ case t of
-- ids (functions and zero-argument a.k.a. CAFs) get a type signature.
-- Including built-in functions like seq.
-- foreign-imported functions could be represented with ForD
-- instead of SigD if we wanted...
--
-- in a future code version we could turn idVarDetails = foreign-call
-- into a ForD instead of a SigD if we wanted. Haddock doesn't
-- need to care.
AnId i -> SigD (synifyIdSig ImplicitizeForAll i)
-- type-constructors (e.g. Maybe) are complicated, put the definition
-- later in the file (also it's used for class associated-types too.)
ATyCon tc
| Just cl <- tyConClass_maybe tc -- classes are just a little tedious
-> let extractFamilyDecl :: TyClDecl a -> LFamilyDecl a
extractFamilyDecl (FamDecl d) = noLoc d
extractFamilyDecl _ =
error "tyThingToLHsDecl: impossible associated tycon"
atTyClDecls = [synifyTyCon Nothing at_tc | (at_tc, _) <- classATItems cl]
atFamDecls = map extractFamilyDecl atTyClDecls in
TyClD $ ClassDecl
{ tcdCtxt = synifyCtx (classSCTheta cl)
, tcdLName = synifyName cl
, tcdTyVars = synifyTyVars (classTyVars cl)
, tcdFDs = map (\ (l,r) -> noLoc
(map getName l, map getName r) ) $
snd $ classTvsFds cl
, tcdSigs = noLoc (MinimalSig . fmap noLoc $ classMinimalDef cl) :
map (noLoc . synifyIdSig DeleteTopLevelQuantification)
(classMethods cl)
, tcdMeths = emptyBag --ignore default method definitions, they don't affect signature
-- class associated-types are a subset of TyCon:
, tcdATs = atFamDecls
, tcdATDefs = [] --ignore associated type defaults
, tcdDocs = [] --we don't have any docs at this point
, tcdFVs = placeHolderNames }
| otherwise
-> TyClD (synifyTyCon Nothing tc)
-- type-constructors (e.g. Maybe) are complicated, put the definition
-- later in the file (also it's used for class associated-types too.)
ACoAxiom ax -> synifyAxiom ax
-- a data-constructor alone just gets rendered as a function:
AConLike (RealDataCon dc) -> SigD (TypeSig [synifyName dc]
(synifyType ImplicitizeForAll (dataConUserType dc)))
AConLike (PatSynCon ps) ->
#if MIN_VERSION_ghc(7,8,3)
let (_, _, req_theta, prov_theta, _, res_ty) = patSynSig ps
#else
let (_, _, (req_theta, prov_theta)) = patSynSig ps
#endif
in SigD $ PatSynSig (synifyName ps)
(fmap (synifyType WithinType) (patSynTyDetails ps))
#if MIN_VERSION_ghc(7,8,3)
(synifyType WithinType res_ty)
#else
(synifyType WithinType (patSynType ps))
#endif
(synifyCtx req_theta)
(synifyCtx prov_theta)
synifyAxBranch :: TyCon -> CoAxBranch -> TyFamInstEqn Name
synifyAxBranch tc (CoAxBranch { cab_tvs = tkvs, cab_lhs = args, cab_rhs = rhs })
= let name = synifyName tc
typats = map (synifyType WithinType) args
hs_rhs = synifyType WithinType rhs
(kvs, tvs) = partition isKindVar tkvs
in TyFamInstEqn { tfie_tycon = name
, tfie_pats = HsWB { hswb_cts = typats
, hswb_kvs = map tyVarName kvs
, hswb_tvs = map tyVarName tvs }
, tfie_rhs = hs_rhs }
synifyAxiom :: CoAxiom br -> HsDecl Name
synifyAxiom ax@(CoAxiom { co_ax_tc = tc })
| isOpenSynFamilyTyCon tc
, Just branch <- coAxiomSingleBranch_maybe ax
= InstD (TyFamInstD (TyFamInstDecl { tfid_eqn = noLoc $ synifyAxBranch tc branch
, tfid_fvs = placeHolderNames }))
| Just ax' <- isClosedSynFamilyTyCon_maybe tc
, getUnique ax' == getUnique ax -- without the getUniques, type error
= TyClD (synifyTyCon (Just ax) tc)
| otherwise
= error "synifyAxiom: closed/open family confusion"
synifyTyCon :: Maybe (CoAxiom br) -> TyCon -> TyClDecl Name
synifyTyCon coax tc
| isFunTyCon tc || isPrimTyCon tc
= DataDecl { tcdLName = synifyName tc
, tcdTyVars = -- tyConTyVars doesn't work on fun/prim, but we can make them up:
let mk_hs_tv realKind fakeTyVar
= noLoc $ KindedTyVar (getName fakeTyVar)
(synifyKindSig realKind)
in HsQTvs { hsq_kvs = [] -- No kind polymorphism
, hsq_tvs = zipWith mk_hs_tv (fst (splitKindFunTys (tyConKind tc)))
alphaTyVars --a, b, c... which are unfortunately all kind *
}
, tcdDataDefn = HsDataDefn { dd_ND = DataType -- arbitrary lie, they are neither
-- algebraic data nor newtype:
, dd_ctxt = noLoc []
, dd_cType = Nothing
, dd_kindSig = Just (synifyKindSig (tyConKind tc))
-- we have their kind accurately:
, dd_cons = [] -- No constructors
, dd_derivs = Nothing }
, tcdFVs = placeHolderNames }
| isSynFamilyTyCon tc
= case synTyConRhs_maybe tc of
Just rhs ->
let info = case rhs of
OpenSynFamilyTyCon -> OpenTypeFamily
ClosedSynFamilyTyCon (CoAxiom { co_ax_branches = branches }) ->
ClosedTypeFamily (brListMap (noLoc . synifyAxBranch tc) branches)
_ -> error "synifyTyCon: type/data family confusion"
in FamDecl (FamilyDecl { fdInfo = info
, fdLName = synifyName tc
, fdTyVars = synifyTyVars (tyConTyVars tc)
, fdKindSig = Just (synifyKindSig (synTyConResKind tc)) })
Nothing -> error "synifyTyCon: impossible open type synonym?"
| isDataFamilyTyCon tc
= --(why no "isOpenAlgTyCon"?)
case algTyConRhs tc of
DataFamilyTyCon ->
FamDecl (FamilyDecl DataFamily (synifyName tc) (synifyTyVars (tyConTyVars tc))
Nothing) --always kind '*'
_ -> error "synifyTyCon: impossible open data type?"
| isSynTyCon tc
= case synTyConRhs_maybe tc of
Just (SynonymTyCon ty) ->
SynDecl { tcdLName = synifyName tc
, tcdTyVars = synifyTyVars (tyConTyVars tc)
, tcdRhs = synifyType WithinType ty
, tcdFVs = placeHolderNames }
_ -> error "synifyTyCon: impossible synTyCon"
| otherwise =
-- (closed) newtype and data
let
alg_nd = if isNewTyCon tc then NewType else DataType
alg_ctx = synifyCtx (tyConStupidTheta tc)
name = case coax of
Just a -> synifyName a -- Data families are named according to their
-- CoAxioms, not their TyCons
_ -> synifyName tc
tyvars = synifyTyVars (tyConTyVars tc)
kindSig = Just (tyConKind tc)
-- The data constructors.
--
-- Any data-constructors not exported from the module that *defines* the
-- type will not (cannot) be included.
--
-- Very simple constructors, Haskell98 with no existentials or anything,
-- probably look nicer in non-GADT syntax. In source code, all constructors
-- must be declared with the same (GADT vs. not) syntax, and it probably
-- is less confusing to follow that principle for the documentation as well.
--
-- There is no sensible infix-representation for GADT-syntax constructor
-- declarations. They cannot be made in source code, but we could end up
-- with some here in the case where some constructors use existentials.
-- That seems like an acceptable compromise (they'll just be documented
-- in prefix position), since, otherwise, the logic (at best) gets much more
-- complicated. (would use dataConIsInfix.)
use_gadt_syntax = any (not . isVanillaDataCon) (tyConDataCons tc)
cons = map (synifyDataCon use_gadt_syntax) (tyConDataCons tc)
-- "deriving" doesn't affect the signature, no need to specify any.
alg_deriv = Nothing
defn = HsDataDefn { dd_ND = alg_nd
, dd_ctxt = alg_ctx
, dd_cType = Nothing
, dd_kindSig = fmap synifyKindSig kindSig
, dd_cons = cons
, dd_derivs = alg_deriv }
in DataDecl { tcdLName = name, tcdTyVars = tyvars, tcdDataDefn = defn
, tcdFVs = placeHolderNames }
-- User beware: it is your responsibility to pass True (use_gadt_syntax)
-- for any constructor that would be misrepresented by omitting its
-- result-type.
-- But you might want pass False in simple enough cases,
-- if you think it looks better.
synifyDataCon :: Bool -> DataCon -> LConDecl Name
synifyDataCon use_gadt_syntax dc = noLoc $
let
-- dataConIsInfix allegedly tells us whether it was declared with
-- infix *syntax*.
use_infix_syntax = dataConIsInfix dc
use_named_field_syntax = not (null field_tys)
name = synifyName dc
-- con_qvars means a different thing depending on gadt-syntax
(univ_tvs, ex_tvs, _eq_spec, theta, arg_tys, res_ty) = dataConFullSig dc
qvars = if use_gadt_syntax
then synifyTyVars (univ_tvs ++ ex_tvs)
else synifyTyVars ex_tvs
-- skip any EqTheta, use 'orig'inal syntax
ctx = synifyCtx theta
linear_tys = zipWith (\ty bang ->
let tySyn = synifyType WithinType ty
src_bang = case bang of
HsUnpack {} -> HsUserBang (Just True) True
HsStrict -> HsUserBang (Just False) True
_ -> bang
in case src_bang of
HsNoBang -> tySyn
_ -> noLoc $ HsBangTy bang tySyn
-- HsNoBang never appears, it's implied instead.
)
arg_tys (dataConStrictMarks dc)
field_tys = zipWith (\field synTy -> ConDeclField
(synifyName field) synTy Nothing)
(dataConFieldLabels dc) linear_tys
hs_arg_tys = case (use_named_field_syntax, use_infix_syntax) of
(True,True) -> error "synifyDataCon: contradiction!"
(True,False) -> RecCon field_tys
(False,False) -> PrefixCon linear_tys
(False,True) -> case linear_tys of
[a,b] -> InfixCon a b
_ -> error "synifyDataCon: infix with non-2 args?"
hs_res_ty = if use_gadt_syntax
then ResTyGADT (synifyType WithinType res_ty)
else ResTyH98
-- finally we get synifyDataCon's result!
in ConDecl name Implicit{-we don't know nor care-}
qvars ctx hs_arg_tys hs_res_ty Nothing
False --we don't want any "deprecated GADT syntax" warnings!
synifyName :: NamedThing n => n -> Located Name
synifyName = noLoc . getName
synifyIdSig :: SynifyTypeState -> Id -> Sig Name
synifyIdSig s i = TypeSig [synifyName i] (synifyType s (varType i))
synifyCtx :: [PredType] -> LHsContext Name
synifyCtx = noLoc . map (synifyType WithinType)
synifyTyVars :: [TyVar] -> LHsTyVarBndrs Name
synifyTyVars ktvs = HsQTvs { hsq_kvs = map tyVarName kvs
, hsq_tvs = map synifyTyVar tvs }
where
(kvs, tvs) = partition isKindVar ktvs
synifyTyVar tv
| isLiftedTypeKind kind = noLoc (UserTyVar name)
| otherwise = noLoc (KindedTyVar name (synifyKindSig kind))
where
kind = tyVarKind tv
name = getName tv
--states of what to do with foralls:
data SynifyTypeState
= WithinType
-- ^ normal situation. This is the safe one to use if you don't
-- quite understand what's going on.
| ImplicitizeForAll
-- ^ beginning of a function definition, in which, to make it look
-- less ugly, those rank-1 foralls are made implicit.
| DeleteTopLevelQuantification
-- ^ because in class methods the context is added to the type
-- (e.g. adding @forall a. Num a =>@ to @(+) :: a -> a -> a@)
-- which is rather sensible,
-- but we want to restore things to the source-syntax situation where
-- the defining class gets to quantify all its functions for free!
synifyType :: SynifyTypeState -> Type -> LHsType Name
synifyType _ (TyVarTy tv) = noLoc $ HsTyVar (getName tv)
synifyType _ (TyConApp tc tys)
-- Use non-prefix tuple syntax where possible, because it looks nicer.
| isTupleTyCon tc, tyConArity tc == length tys =
noLoc $ HsTupleTy (case tupleTyConSort tc of
BoxedTuple -> HsBoxedTuple
ConstraintTuple -> HsConstraintTuple
UnboxedTuple -> HsUnboxedTuple)
(map (synifyType WithinType) tys)
-- ditto for lists
| getName tc == listTyConName, [ty] <- tys =
noLoc $ HsListTy (synifyType WithinType ty)
-- ditto for implicit parameter tycons
| tyConName tc == ipClassName
, [name, ty] <- tys
, Just x <- isStrLitTy name
= noLoc $ HsIParamTy (HsIPName x) (synifyType WithinType ty)
-- and equalities
| tc == eqTyCon
, [ty1, ty2] <- tys
= noLoc $ HsEqTy (synifyType WithinType ty1) (synifyType WithinType ty2)
-- Most TyCons:
| otherwise =
foldl (\t1 t2 -> noLoc (HsAppTy t1 t2))
(noLoc $ HsTyVar (getName tc))
(map (synifyType WithinType) tys)
synifyType _ (AppTy t1 t2) = let
s1 = synifyType WithinType t1
s2 = synifyType WithinType t2
in noLoc $ HsAppTy s1 s2
synifyType _ (FunTy t1 t2) = let
s1 = synifyType WithinType t1
s2 = synifyType WithinType t2
in noLoc $ HsFunTy s1 s2
synifyType s forallty@(ForAllTy _tv _ty) =
let (tvs, ctx, tau) = tcSplitSigmaTy forallty
in case s of
DeleteTopLevelQuantification -> synifyType ImplicitizeForAll tau
_ -> let
forallPlicitness = case s of
WithinType -> Explicit
ImplicitizeForAll -> Implicit
_ -> error "synifyType: impossible case!!!"
sTvs = synifyTyVars tvs
sCtx = synifyCtx ctx
sTau = synifyType WithinType tau
in noLoc $
HsForAllTy forallPlicitness sTvs sCtx sTau
synifyType _ (LitTy t) = noLoc $ HsTyLit $ synifyTyLit t
synifyTyLit :: TyLit -> HsTyLit
synifyTyLit (NumTyLit n) = HsNumTy n
synifyTyLit (StrTyLit s) = HsStrTy s
synifyKindSig :: Kind -> LHsKind Name
synifyKindSig k = synifyType WithinType k
synifyInstHead :: ([TyVar], [PredType], Class, [Type]) -> InstHead Name
synifyInstHead (_, preds, cls, types) =
( getName cls
, map (unLoc . synifyType WithinType) ks
, map (unLoc . synifyType WithinType) ts
, ClassInst $ map (unLoc . synifyType WithinType) preds
)
where (ks,ts) = break (not . isKind) types
-- Convert a family instance, this could be a type family or data family
synifyFamInst :: FamInst -> Bool -> InstHead Name
synifyFamInst fi opaque =
( fi_fam fi
, map (unLoc . synifyType WithinType) ks
, map (unLoc . synifyType WithinType) ts
, case fi_flavor fi of
SynFamilyInst | opaque -> TypeInst Nothing
SynFamilyInst -> TypeInst . Just . unLoc . synifyType WithinType $ fi_rhs fi
DataFamilyInst c -> DataInst $ synifyTyCon (Just $ famInstAxiom fi) c
)
where (ks,ts) = break (not . isKind) $ fi_tys fi
| ghcjs/haddock-internal | src/Haddock/Convert.hs | bsd-2-clause | 16,931 | 53 | 22 | 5,052 | 3,553 | 1,867 | 1,686 | 273 | 10 |
-- {-# LANGUAGE FlexibleInstances #-}
-- {-# LANGUAGE TupleSections #-}
-- {-# LANGUAGE UndecidableInstances #-}
-- {-# LANGUAGE DeriveFunctor #-}
-- {-# LANGUAGE DeriveFoldable #-}
-- {-# LANGUAGE DeriveTraversable #-}
-- {-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE GADTs #-}
{-
- Early parser for TAGs. Fifth preliminary version :-).
-}
module NLP.LTAG.Earley5 where
import Control.Applicative ((<*>), (<$>))
import Control.Arrow (second)
import Control.Monad (guard, void, forever)
import qualified Control.Monad.State.Strict as E
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT (..))
import qualified Control.Monad.RWS.Strict as RWS
import Control.Monad.Identity (Identity(..))
import Data.Function (on)
import Data.Monoid (mappend, mconcat)
import Data.List (intercalate)
-- import Data.Foldable (Foldable)
-- import Data.Traversable (Traversable)
import Data.Maybe ( isJust, isNothing
, listToMaybe, maybeToList)
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Data.PSQueue as Q
import Data.PSQueue (Binding(..))
import qualified Data.Partition as Part
import qualified Pipes as P
-- import qualified Pipes.Prelude as P
import qualified NLP.FeatureStructure.Tree as FT
import qualified NLP.FeatureStructure.Graph as FG
import qualified NLP.FeatureStructure.Join as J
import qualified NLP.FeatureStructure.Unify as U
-- import qualified NLP.FeatureStructure.Reid2 as Reid
import NLP.LTAG.Core
import qualified NLP.LTAG.Rule as R
--------------------------
-- Internal rule
--------------------------
-- | A feature graph identifier, i.e. an identifier used to refer
-- to individual nodes in a FS.
type ID = FT.ID
-- -- | Symbol: a (non-terminal, maybe identifier) pair addorned with
-- -- a feature structure.
-- data Sym n = Sym
-- { nonTerm :: n
-- , ide :: Maybe SymID
-- , fgID :: FID }
-- deriving (Show, Eq, Ord)
--
--
-- -- | A simplified symbol without FID.
-- type SSym n = (n, Maybe SymID)
--
--
-- -- | Simplify symbol.
-- simpSym :: Sym n -> SSym n
-- simpSym Sym{..} = (nonTerm, ide)
--
--
-- -- | Show the symbol.
-- viewSym :: View n => Sym n -> String
-- viewSym (Sym x (Just i) _) = "(" ++ view x ++ ", " ++ show i ++ ")"
-- viewSym (Sym x Nothing _) = "(" ++ view x ++ ", _)"
-- -- | Label: a symbol, a terminal or a generalized foot node.
-- -- Generalized in the sense that it can represent not only a foot
-- -- note of an auxiliary tree, but also a non-terminal on the path
-- -- from the root to the real foot note of an auxiliary tree.
-- data Lab n t
-- = NonT (Sym n)
-- | Term t
-- | Foot (Sym n)
-- deriving (Show, Eq, Ord)
-- | Label represent one of the following:
-- * A non-terminal
-- * A terminal
-- * A root of an auxiliary tree
-- * A foot node of an auxiliary tree
-- * A vertebra of the spine of the auxiliary tree
--
-- It has neither Eq nor Ord instances, because the comparison of
-- feature graph identifiers without context doesn't make much
-- sense.
data Lab n t i
= NonT
{ nonTerm :: n
, labID :: Maybe SymID
, topID :: i
, botID :: i }
| Term t
| AuxRoot
{ nonTerm :: n
, topID :: i
, botID :: i
, footTopID :: i
, footBotID :: i }
| AuxFoot
{ nonTerm :: n }
| AuxVert
{ nonTerm :: n
, symID :: SymID
, topID :: i
, botID :: i }
deriving (Show)
-- | Map IDs given a mapping function.
mapID :: (i -> j) -> Lab n t i -> Lab n t j
mapID f lab = case lab of
NonT{..} -> NonT
{ nonTerm = nonTerm
, labID = labID
, topID = f topID
, botID = f botID }
Term x -> Term x
AuxRoot{..} -> AuxRoot
{ nonTerm = nonTerm
, topID = f topID
, botID = f botID
, footTopID = f footTopID
, footBotID = f footBotID }
AuxFoot x -> AuxFoot x
AuxVert{..} -> AuxVert
{ nonTerm = nonTerm
, symID = symID
, topID = f topID
, botID = f botID }
-- | Label equality within the context of corresponding
-- feature graphs.
--
-- TODO: Reimplement based on `labEq'`
labEq
:: forall n t i j f a
-- We have to use scoped type variables in order to be able
-- to refer to them from the internal functions. The usage
-- of the internal `nodeEq` is most likely responsible for
-- this.
. (Eq n, Eq t, Ord i, Ord j, Eq f, Eq a)
=> Lab n t i -- ^ First label `x`
-> FG.Graph i f a -- ^ Graph corresponding to `x`
-> Lab n t j -- ^ Second label `y`
-> FG.Graph j f a -- ^ Graph corresponding to `y`
-> Bool
labEq p g q h =
eq p q
where
eq x@NonT{} y@NonT{}
= eqOn nonTerm x y
&& eqOn labID x y
&& nodeEqOn topID x y
&& nodeEqOn botID x y
eq (Term x) (Term y)
= x == y
eq x@AuxRoot{} y@AuxRoot{}
= eqOn nonTerm x y
&& nodeEqOn topID x y
&& nodeEqOn botID x y
&& nodeEqOn footTopID x y
&& nodeEqOn footBotID x y
eq (AuxFoot x) (AuxFoot y)
= x == y
eq x@AuxVert{} y@AuxVert{}
= eqOn nonTerm x y
&& eqOn symID x y
&& nodeEqOn topID x y
&& nodeEqOn botID x y
eq _ _ = False
-- if we don't write `forall k.` then compiler tries to match
-- it with both `i` and `j` at the same time.
eqOn :: Eq z => (forall k . Lab n t k -> z)
-> Lab n t i -> Lab n t j -> Bool
eqOn f x y = f x == f y
nodeEqOn :: (forall k . Lab n t k -> k)
-> Lab n t i -> Lab n t j -> Bool
nodeEqOn f x y = nodeEq (f x) (f y)
-- assumption: the first index belongs to the first
-- graph, the second to the second graph.
nodeEq i j = FG.equal g i h j
-- | Label equality within the context of corresponding feature
-- graphs. Concerning the `SymID` values, it is only checked if
-- either both are `Nothing` or both are `Just`.
labEq'
:: forall n t i j f a
-- We have to use scoped type variables in order to be able
-- to refer to them from the internal functions. The usage
-- of the internal `nodeEq` is most likely responsible for
-- this.
. (Eq n, Eq t, Ord i, Ord j, Eq f, Eq a)
=> Lab n t i -- ^ First label `x`
-> FG.Graph i f a -- ^ Graph corresponding to `x`
-> Lab n t j -- ^ Second label `y`
-> FG.Graph j f a -- ^ Graph corresponding to `y`
-> Bool
labEq' p g q h =
eq p q
where
eq x@NonT{} y@NonT{}
= eqOn nonTerm x y
&& eqOn (isJust . labID) x y
&& nodeEqOn topID x y
&& nodeEqOn botID x y
eq (Term x) (Term y)
= x == y
eq x@AuxRoot{} y@AuxRoot{}
= eqOn nonTerm x y
&& nodeEqOn topID x y
&& nodeEqOn botID x y
&& nodeEqOn footTopID x y
&& nodeEqOn footBotID x y
eq (AuxFoot x) (AuxFoot y)
= x == y
eq x@AuxVert{} y@AuxVert{}
= eqOn nonTerm x y
-- && eqOn symID x y
&& nodeEqOn topID x y
&& nodeEqOn botID x y
eq _ _ = False
-- if we don't write `forall k.` then compiler tries to match
-- it with both `i` and `j` at the same time.
eqOn :: Eq z => (forall k . Lab n t k -> z)
-> Lab n t i -> Lab n t j -> Bool
eqOn f x y = f x == f y
nodeEqOn :: (forall k . Lab n t k -> k)
-> Lab n t i -> Lab n t j -> Bool
nodeEqOn f x y = nodeEq (f x) (f y)
-- assumption: the first index belongs to the first
-- graph, the second to the second graph.
nodeEq i j = FG.equal g i h j
-- | Label comparison within the context of corresponding
-- feature graphs.
labCmp
:: forall n t i j f a
. (Ord n, Ord t, Ord i, Ord j, Ord f, Ord a)
=> Lab n t i -- ^ First label `x`
-> FG.Graph i f a -- ^ Graph corresponding to `x`
-> Lab n t j -- ^ Second label `y`
-> FG.Graph j f a -- ^ Graph corresponding to `y`
-> Ordering
labCmp p g q h =
cmp p q
where
cmp x@NonT{} y@NonT{} =
cmpOn nonTerm x y `mappend`
cmpOn labID x y `mappend`
nodeCmpOn topID x y `mappend`
nodeCmpOn botID x y
cmp (Term x) (Term y) =
compare x y
cmp x@AuxRoot{} y@AuxRoot{} =
cmpOn nonTerm x y `mappend`
nodeCmpOn topID x y `mappend`
nodeCmpOn botID x y `mappend`
nodeCmpOn footTopID x y `mappend`
nodeCmpOn footBotID x y
cmp (AuxFoot x) (AuxFoot y) =
compare x y
cmp x@AuxVert{} y@AuxVert{} =
cmpOn nonTerm x y `mappend`
cmpOn symID x y `mappend`
nodeCmpOn topID x y `mappend`
nodeCmpOn botID x y
cmp x y = cmpOn conID x y
cmpOn :: Ord z => (forall k . Lab n t k -> z)
-> Lab n t i -> Lab n t j -> Ordering
cmpOn f x y = compare (f x) (f y)
nodeCmpOn :: (forall k . Lab n t k -> k)
-> Lab n t i -> Lab n t j -> Ordering
nodeCmpOn f x y = nodeCmp (f x) (f y)
-- assumption: the first index belongs to the first
-- graph, the second to the second graph.
nodeCmp i j = FG.compare' g i h j
-- data constructur identifier
conID x = case x of
NonT{} -> 1 :: Int
Term _ -> 2
AuxRoot{} -> 3
AuxFoot{} -> 4
AuxVert{} -> 5
-- | Label comparison within the context of corresponding
-- feature graphs. Concerning the `SymID` values, it is only
-- checked if either both are `Nothing` or both are `Just`.
labCmp'
:: forall n t i j f a
. (Ord n, Ord t, Ord i, Ord j, Ord f, Ord a)
=> Lab n t i -- ^ First label `x`
-> FG.Graph i f a -- ^ Graph corresponding to `x`
-> Lab n t j -- ^ Second label `y`
-> FG.Graph j f a -- ^ Graph corresponding to `y`
-> Ordering
labCmp' p g q h =
cmp p q
where
cmp x@NonT{} y@NonT{} =
cmpOn nonTerm x y `mappend`
cmpOn (isJust . labID) x y `mappend`
nodeCmpOn topID x y `mappend`
nodeCmpOn botID x y
cmp (Term x) (Term y) =
compare x y
cmp x@AuxRoot{} y@AuxRoot{} =
cmpOn nonTerm x y `mappend`
nodeCmpOn topID x y `mappend`
nodeCmpOn botID x y `mappend`
nodeCmpOn footTopID x y `mappend`
nodeCmpOn footBotID x y
cmp (AuxFoot x) (AuxFoot y) =
compare x y
cmp x@AuxVert{} y@AuxVert{} =
cmpOn nonTerm x y `mappend`
-- cmpOn symID x y `mappend`
nodeCmpOn topID x y `mappend`
nodeCmpOn botID x y
cmp x y = cmpOn conID x y
cmpOn :: Ord z => (forall k . Lab n t k -> z)
-> Lab n t i -> Lab n t j -> Ordering
cmpOn f x y = compare (f x) (f y)
nodeCmpOn :: (forall k . Lab n t k -> k)
-> Lab n t i -> Lab n t j -> Ordering
nodeCmpOn f x y = nodeCmp (f x) (f y)
-- assumption: the first index belongs to the first
-- graph, the second to the second graph.
nodeCmp i j = FG.compare' g i h j
-- data constructur identifier
conID x = case x of
NonT{} -> 1 :: Int
Term _ -> 2
AuxRoot{} -> 3
AuxFoot{} -> 4
AuxVert{} -> 5
-- | A simplified label which does not contain any information
-- about FSs. In contrast to `Lab n t`, it provides Eq and Ord
-- instances. TODO: note that we lose the distinction between
-- `AuxRoot` and `AuxFoot` here.
data SLab n t
= SNonT (n, Maybe SymID)
| STerm t
| SAux (n, Maybe SymID)
deriving (Show, Eq, Ord)
-- | Simplify label.
simpLab :: Lab n t i -> SLab n t
simpLab NonT{..} = SNonT (nonTerm, labID)
simpLab (Term t) = STerm t
simpLab AuxRoot{..} = SAux (nonTerm, Nothing)
simpLab AuxFoot{..} = SAux (nonTerm, Nothing)
simpLab AuxVert{..} = SAux (nonTerm, Just symID)
-- | Show the label.
viewLab :: (View n, View t) => Lab n t i -> String
viewLab NonT{..} = "N" ++ viewSym (nonTerm, labID)
viewLab (Term t) = "T(" ++ view t ++ ")"
viewLab AuxRoot{..} = "A" ++ viewSym (nonTerm, Nothing)
viewLab AuxVert{..} = "V" ++ viewSym (nonTerm, Just symID)
viewLab AuxFoot{..} = "F" ++ viewSym (nonTerm, Nothing)
-- | View part of the label. Utility function.
viewSym :: View n => (n, Maybe SymID) -> String
viewSym (x, Just i) = "(" ++ view x ++ ", " ++ show i ++ ")"
viewSym (x, Nothing) = "(" ++ view x ++ ", _)"
-- | Show full info about the label.
viewLabFS
:: (Ord i, View n, View t, View i, View f, View a)
=> Lab n t i
-> FG.Graph i f a
-> String
viewLabFS lab gr = case lab of
NonT{..} -> "N(" ++ view nonTerm
++ ( case labID of
Nothing -> ""
Just i -> ", " ++ view i ) ++ ")"
++ "[t=" ++ FG.showFlat gr topID
++ ",b=" ++ FG.showFlat gr botID ++ "]"
Term t -> "T(" ++ view t ++ ")"
AuxRoot{..} -> "A(" ++ view nonTerm ++ ")"
++ "[t=" ++ FG.showFlat gr topID
++ ",b=" ++ FG.showFlat gr botID
++ ",ft=" ++ FG.showFlat gr footTopID
++ ",fb=" ++ FG.showFlat gr footBotID ++ "]"
AuxFoot x -> "F(" ++ view x ++ ")"
AuxVert{..} -> "V(" ++ view nonTerm ++ ", " ++ view symID ++ ")"
++ "[t=" ++ FG.showFlat gr topID
++ ",b=" ++ FG.showFlat gr botID ++ "]"
-- | A rule for an elementary tree.
data Rule n t i f a = Rule {
-- | The head of the rule. TODO: Should never be a foot or a
-- terminal <- can we enforce this constraint?
headR :: Lab n t i
-- | The body of the rule
, bodyR :: [Lab n t i]
-- | The underlying feature graph.
, graphR :: FG.Graph i f a
} deriving (Show)
--------------------------------------------------
-- Substructure Sharing
--------------------------------------------------
-- | Duplication-removal state serves to share common
-- substructures.
--
-- The idea is to remove redundant rules equivalent to other
-- rules already present in the set of processed rules
-- `rulDepo`(sit).
--
-- Note that rules have to be processed in an appropriate order
-- so that lower-level rules are processed before the
-- higher-level rules from which they are referenced.
data DupS n t i f a = DupS {
-- | A disjoint set for `SymID`s
symDisj :: Part.Partition SymID
-- | Rules already saved
, rulDepo :: S.Set (Rule n t i f a)
}
-- Let us take a rule and let us assume that all identifiers it
-- contains point to rules which have already been processed (for
-- this assumption to be valid we just need to order the set of
-- rules properly). So we have a rule `r`, a set of processed
-- rules `rs` and a clustering (disjoint-set) over `SymID`s
-- present in `rs`.
--
-- Now we want to process `r` and, in particular, check if it is
-- not already in `rs` and update its `SymID`s.
--
-- First we translate the body w.r.t. the existing clustering of
-- `SymID`s (thanks to our assumption, these `SymID`s are already
-- known and processed). The `SymID` in the root of the rule (if
-- present) is the new one and it should not yet have been mentioned
-- in `rs`. Even when `SymID` is not present in the root, we can
-- still try to check if `r` is not present in `rs` -- after all, there
-- may be some duplicates in the input grammar.
--
-- Case 1: we have a rule with a `SymID` in the root. We want to
-- check if there is already a rule in `rs` which:
-- * Has identical body (remember that we have already
-- transformed `SymID`s of the body of the rule in question)
-- * Has the same non-terminal in the root and some `SymID`
--
-- Case 2: the same as case 1 with the difference that we look
-- for the rules which have an empty `SymID` in the root.
--
-- For this to work we just need a specific comparison function
-- which works as specified in the two cases desribed above
-- (i.e. either there are some `SymID`s in the roots, or there
-- are no `SymID`s in both roots.)
--
-- Once we have this comparison, we simply process the set of
-- rules incrementally.
-- | Duplication-removal transformer.
type DupT n t i f a m = E.StateT (DupS n t i f a) m
-- | Duplication-removal monad.
type DupM n t i f a = DupT n t i f a Identity
-- | Run the transformer.
runDupT
:: (Functor m, Monad m)
=> DupT n t i f a m b
-> m (b, S.Set (Rule n t i f a))
runDupT = fmap (second rulDepo) . flip E.runStateT
(DupS Part.empty S.empty)
-- | Update the body of the rule by replacing old `SymID`s with
-- their representatives.
updateBody
:: Rule n t i f a
-> DupM n t i f a (Rule n t i f a)
updateBody r = do
d <- E.gets symDisj
let body' = map (updLab d) (bodyR r)
return $ r { bodyR = body' }
where
updLab d x@NonT{..} = x { labID = updSym d <$> labID }
updLab d x@AuxVert{..} = x { symID = updSym d symID }
updLab _ x = x
updSym = Part.rep
-- | Find a rule if already present.
findRule
:: (Ord n, Ord t, Ord i, Ord f, Ord a)
=> Rule n t i f a
-> DupM n t i f a (Maybe (Rule n t i f a))
findRule x = do
s <- E.gets rulDepo
return $ lookupSet x s
-- | Join two `SymID`s.
joinSym :: SymID -> SymID -> DupM n t i f a ()
joinSym x y = E.modify $ \s@DupS{..} -> s
{ symDisj = Part.joinElems x y symDisj }
-- | Save the rule in the underlying deposit.
keepRule
:: (Ord n, Ord t, Ord i, Ord f, Ord a)
=> Rule n t i f a
-> DupM n t i f a ()
keepRule r = E.modify $ \s@DupS{..} -> s
{ rulDepo = S.insert r rulDepo }
-- | Retrieve the symbol of the head of the rule.
headSym :: Rule n t i f a -> Maybe SymID
headSym r = case headR r of
NonT{..} -> labID
AuxVert{..} -> Just symID
_ -> Nothing
-- | Removing duplicates updating `SymID`s at the same time.
-- WARNING: The pipe assumes that `SymID`s to which the present
-- rule refers have already been processed -- in other words,
-- that rule on which the present rule depends have been
-- processed earlier.
rmDups
:: (Ord n, Ord t, Ord i, Ord f, Ord a)
=> P.Pipe
(Rule n t i f a) -- Input
(Rule n t i f a) -- Output
(DupM n t i f a) -- Underlying state
() -- No result
rmDups = forever $ do
r <- P.await >>= lift . updateBody
lift (findRule r) >>= \mr -> case mr of
Nothing -> do
lift $ keepRule r
P.yield r
Just r' -> case (headSym r, headSym r') of
(Just x, Just y) -> lift $ joinSym x y
_ -> return ()
-- Just r' -> void $ runMaybeT $ joinSym
-- <$> headSymT r
-- <*> headSymT r'
-- where headSymT = maybeT . headSym
instance (Eq n, Eq t, Ord i, Eq f, Eq a) => Eq (Rule n t i f a) where
r == s = (hdEq `on` headR) r s
&& ((==) `on` length.bodyR) r s
&& and [eq x y | (x, y) <- zip (bodyR r) (bodyR s)]
where
eq x y = labEq x (graphR r) y (graphR s)
hdEq x y = labEq' x (graphR r) y (graphR s)
instance (Ord n, Ord t, Ord i, Ord f, Ord a) => Ord (Rule n t i f a) where
r `compare` s = (hdCmp `on` headR) r s `mappend`
(compare `on` length.bodyR) r s `mappend`
mconcat [cmp x y | (x, y) <- zip (bodyR r) (bodyR s)]
where
cmp x y = labCmp x (graphR r) y (graphR s)
hdCmp x y = labCmp' x (graphR r) y (graphR s)
-- | Compile a regular rule to an internal rule.
compile
:: (View n, View t, Ord i, Ord f, Ord a)
=> R.Rule n t i f a -> Rule n t ID f a
compile R.Rule{..} = unJust $ do
((x, xs), J.Res{..}) <- FT.runCon $ (,)
<$> conLab headR
<*> mapM conLab bodyR
return $ Rule
(mapID convID x)
(map (mapID convID) xs)
resGraph
where
conLab R.NonT{..} = NonT nonTerm labID
<$> FT.fromFN rootTopFS
<*> FT.fromFN rootBotFS
conLab (R.Term x) = return $ Term x
conLab R.AuxRoot{..} = AuxRoot nonTerm
<$> FT.fromFN rootTopFS
<*> FT.fromFN rootBotFS
<*> FT.fromFN footTopFS
<*> FT.fromFN footBotFS
conLab (R.AuxFoot x) = return $ AuxFoot x
conLab R.AuxVert{..} = AuxVert nonTerm symID
<$> FT.fromFN rootTopFS
<*> FT.fromFN rootBotFS
-- | Print the state.
printRuleFS
:: ( Ord i, View n, View t
, View i, View f, View a )
=> Rule n t i f a -> IO ()
printRuleFS Rule{..} = do
putStr $ viewl headR
putStr " -> "
putStr $ intercalate " " $ map viewl bodyR
where
viewl x = viewLabFS x graphR
--------------------------------------------------
-- CHART STATE ...
--
-- ... and chart extending operations
--------------------------------------------------
-- | Parsing state: processed initial rule elements and the elements
-- yet to process.
data State n t i f a = State {
-- | The head of the rule represented by the state.
-- TODO: Not a terminal nor a foot.
root :: Lab n t i
-- | The list of processed elements of the rule, stored in an
-- inverse order.
, left :: [Lab n t i]
-- | The list of elements yet to process.
, right :: [Lab n t i]
-- | The starting position.
, beg :: Pos
-- | The ending position (or rather the position of the dot).
, end :: Pos
-- | Coordinates of the gap (if applies)
, gap :: Maybe (Pos, Pos)
-- | The underlying feature graph.
, graph :: FG.Graph i f a
} deriving (Show)
-- | Equality of states.
statEq
:: forall n t i j f a
. (Eq n, Eq t, Ord i, Ord j, Eq f, Eq a)
=> State n t i f a
-> State n t j f a
-> Bool
statEq r s
= eqOn beg r s
&& eqOn end r s
&& eqOn gap r s
&& leq (root r) (root s)
&& eqOn (length.left) r s
&& eqOn (length.right) r s
&& and [leq x y | (x, y) <- zip (left r) (left s)]
&& and [leq x y | (x, y) <- zip (right r) (right s)]
where
leq x y = labEq x (graph r) y (graph s)
eqOn :: Eq z => (forall k . State n t k f a -> z)
-> State n t i f a -> State n t j f a -> Bool
eqOn f x y = f x == f y
instance (Eq n, Eq t, Ord i, Eq f, Eq a) => Eq (State n t i f a) where
(==) = statEq
-- | Equality of states.
statCmp
:: forall n t i j f a
. (Ord n, Ord t, Ord i, Ord j, Ord f, Ord a)
=> State n t i f a
-> State n t j f a
-> Ordering
statCmp r s = cmpOn beg r s
`mappend` cmpOn end r s
`mappend` cmpOn gap r s
`mappend` lcmp (root r) (root s)
`mappend` cmpOn (length.left) r s
`mappend` cmpOn (length.right) r s
`mappend` mconcat [lcmp x y | (x, y) <- zip (left r) (left s)]
`mappend` mconcat [lcmp x y | (x, y) <- zip (right r) (right s)]
where
lcmp x y = labCmp x (graph r) y (graph s)
cmpOn :: Ord z => (forall k . State n t k f a -> z)
-> State n t i f a -> State n t j f a -> Ordering
cmpOn f x y = compare (f x) (f y)
instance (Ord n, Ord t, Ord i, Ord f, Ord a) => Ord (State n t i f a) where
compare = statCmp
-- | Is it a completed (fully-parsed) state?
completed :: State n t i f a -> Bool
completed = null . right
-- | Does it represent a regular rule?
regular :: State n t i f a -> Bool
regular = isNothing . gap
-- | Does it represent an auxiliary rule?
auxiliary :: State n t i f a -> Bool
auxiliary = isJust . gap
-- | Is it top-level? All top-level states (regular or
-- auxiliary) have an underspecified ID in the root symbol.
topLevel :: State n t i f a -> Bool
-- topLevel = isNothing . ide . root
topLevel = not . subLevel
-- | Is it subsidiary (i.e. not top) level?
subLevel :: State n t i f a -> Bool
-- subLevel = isJust . ide . root
subLevel x = case root x of
NonT{..} -> isJust labID
AuxVert{} -> True
Term _ -> True
_ -> False
-- | Deconstruct the right part of the state (i.e. labels yet to
-- process) within the MaybeT monad.
expects
:: Monad m
=> State n t i f a
-> MaybeT m (Lab n t i, [Lab n t i])
expects = maybeT . expects'
-- | Deconstruct the right part of the state (i.e. labels yet to
-- process).
expects'
:: State n t i f a
-> Maybe (Lab n t i, [Lab n t i])
expects' = decoList . right
-- | Print the state.
printStateRaw :: (View n, View i, View t) => State n t i f a -> IO ()
printStateRaw State{..} = do
putStr $ viewLab root
putStr " -> "
putStr $ intercalate " " $
map viewLab (reverse left) ++ ["*"] ++ map viewLab right
putStr " <"
putStr $ show beg
putStr ", "
case gap of
Nothing -> return ()
Just (p, q) -> do
putStr $ show p
putStr ", "
putStr $ show q
putStr ", "
putStr $ show end
putStrLn ">"
-- | Print the state.
printStateFS
:: ( Ord i, View n, View t
, View i, View f, View a )
=> State n t i f a -> IO ()
printStateFS State{..} = do
putStr $ viewl root
putStr " -> "
putStr $ intercalate " " $
map viewl (reverse left) ++ ["*"] ++ map viewl right
putStr " <"
putStr $ show beg
putStr ", "
case gap of
Nothing -> return ()
Just (p, q) -> do
putStr $ show p
putStr ", "
putStr $ show q
putStr ", "
putStr $ show end
putStrLn ">"
where
viewl x = viewLabFS x graph
-- | Print the state.
printState
:: ( Ord i, View n, View t
, View i, View f, View a )
=> State n t i f a -> IO ()
printState = printStateFS
-- | Priority type.
type Prio = Int
-- | Priority of a state. Crucial for the algorithm -- states have
-- to be removed from the queue in a specific order.
prio :: State n t i f a -> Prio
prio p = end p
--------------------------------------------------
-- StateE
--------------------------------------------------
-- | A state existentially quantified over the ID type.
data StateE n t f a where
StateE :: VOrd i => State n t i f a -> StateE n t f a
instance (Eq n, Eq t, Eq f, Eq a) => Eq (StateE n t f a) where
StateE r == StateE s = statEq r s
instance (Ord n, Ord t, Ord f, Ord a) => Ord (StateE n t f a) where
StateE r `compare` StateE s = statCmp r s
-- | Priority of a StateE.
prioE :: StateE n t f a -> Prio
prioE (StateE s) = prio s
--------------------------------------------------
-- Earley monad
--------------------------------------------------
-- | The state of the earley monad.
data EarSt n t f a = EarSt {
-- | Rules which expect a specific label and which end on a
-- specific position.
doneExpEnd :: M.Map (SLab n t, Pos) (S.Set (StateE n t f a))
-- | Rules providing a specific non-terminal in the root
-- and spanning over a given range.
, doneProSpan :: M.Map (n, Pos, Pos) (S.Set (StateE n t f a))
-- | The set of states waiting on the queue to be processed.
-- Invariant: the intersection of `done' and `waiting' states
-- is empty.
, waiting :: Q.PSQ (StateE n t f a) Prio }
-- | Make an initial `EarSt` from a set of states.
mkEarSt
:: (Ord n, Ord t, Ord a, Ord f)
=> S.Set (StateE n t f a)
-> (EarSt n t f a)
mkEarSt s = EarSt
{ doneExpEnd = M.empty
, doneProSpan = M.empty
, waiting = Q.fromList
[ p :-> prioE p
| p <- S.toList s ] }
-- | Earley parser monad. Contains the input sentence (reader)
-- and the state of the computation `EarSt'.
type Earley n t f a = RWS.RWST [t] () (EarSt n t f a) IO
-- | Read word from the given position of the input.
readInput :: Pos -> MaybeT (Earley n t f a) t
readInput i = do
-- ask for the input
xs <- RWS.ask
-- just a safe way to retrieve the i-th element
maybeT $ listToMaybe $ drop i xs
-- | Check if the state is not already processed (i.e. in one of the
-- done-related maps).
isProcessed
:: (Ord n, Ord t, Ord a, Ord f)
=> StateE n t f a
-> EarSt n t f a
-> Bool
isProcessed pE EarSt{..} =
S.member pE $ chooseSet pE
where
chooseSet (StateE p) = case expects' p of
Just (x, _) -> M.findWithDefault S.empty
(simpLab x, end p) doneExpEnd
Nothing -> M.findWithDefault S.empty
(nonTerm $ root p, beg p, end p) doneProSpan
-- | Add the state to the waiting queue. Check first if it is
-- not already in the set of processed (`done') states.
pushState
:: (Ord t, Ord n, Ord a, Ord f)
=> StateE n t f a
-> Earley n t f a ()
pushState p = RWS.state $ \s ->
let waiting' = if isProcessed p s
then waiting s
else Q.insert p (prioE p) (waiting s)
in ((), s {waiting = waiting'})
-- | Remove a state from the queue. In future, the queue
-- will be probably replaced by a priority queue which will allow
-- to order the computations in some smarter way.
popState
:: (Ord t, Ord n, Ord a, Ord f)
=> Earley n t f a (Maybe (StateE n t f a))
popState = RWS.state $ \st -> case Q.minView (waiting st) of
Nothing -> (Nothing, st)
Just (x :-> _, s) -> (Just x, st {waiting = s})
-- | Add the state to the set of processed (`done') states.
saveState
:: (Ord t, Ord n, Ord a, Ord f)
=> StateE n t f a
-> Earley n t f a ()
saveState pE =
RWS.state $ \s -> ((), doit pE s)
where
doit (StateE p) st@EarSt{..} = st
{ doneExpEnd = case expects' p of
Just (x, _) -> M.insertWith S.union (simpLab x, end p)
(S.singleton pE) doneExpEnd
Nothing -> doneExpEnd
, doneProSpan = if completed p
then M.insertWith S.union (nonTerm $ root p, beg p, end p)
(S.singleton pE) doneProSpan
else doneProSpan }
-- | Return all completed states which:
-- * expect a given label,
-- * end on the given position.
expectEnd
:: (Ord n, Ord t) => SLab n t -> Pos
-> P.ListT (Earley n t f a) (StateE n t f a)
expectEnd x i = do
EarSt{..} <- lift RWS.get
listValues (x, i) doneExpEnd
-- | Return all completed states with:
-- * the given root non-terminal value
-- * the given span
rootSpan
:: Ord n => n -> (Pos, Pos)
-> P.ListT (Earley n t f a) (StateE n t f a)
rootSpan x (i, j) = do
EarSt{..} <- lift RWS.get
listValues (x, i, j) doneProSpan
-- | A utility function.
listValues
:: (Monad m, Ord a)
=> a -> M.Map a (S.Set b)
-> P.ListT m b
listValues x m = each $ case M.lookup x m of
Nothing -> []
Just s -> S.toList s
--------------------------------------------------
-- SCAN
--------------------------------------------------
-- | Try to perform SCAN on the given state.
tryScan
:: (VOrd t, VOrd n, VOrd a, VOrd f)
=> StateE n t f a
-> Earley n t f a ()
tryScan (StateE p) = void $ runMaybeT $ do
-- check that the state expects a terminal on the right
(Term t, right') <- expects p
-- read the word immediately following the ending position of
-- the state
c <- readInput $ end p
-- make sure that what the rule expects is consistent with
-- the input
guard $ c == t
-- construct the resultant state
let p' = p
{ end = end p + 1
, left = Term t : left p
, right = right' }
-- print logging information
lift . lift $ do
putStr "[S] " >> printState p
putStr " : " >> printState p'
-- push the resulting state into the waiting queue
lift $ pushState $ StateE p'
--------------------------------------------------
-- SUBST
--------------------------------------------------
-- | Try to use the state (only if fully parsed) to complement
-- (=> substitution) other rules.
trySubst
:: (VOrd t, VOrd n, VOrd a, VOrd f)
=> StateE n t f a
-> Earley n t f a ()
trySubst (StateE p) = void $ P.runListT $ do
-- make sure that `p' is a fully-parsed regular rule
guard $ completed p && regular p
-- find rules which end where `p' begins and which
-- expect the non-terminal provided by `p' (ID included)
StateE q <- expectEnd (simpLab $ root p) (beg p)
(r@NonT{}, _) <- some $ expects' q
-- unify the corresponding feature structures
-- TODO: We assume here that graph IDs are disjoint.
J.Res{..} <- some $ U.unify (graph p) (graph q)
[ (topID $ root p, topID r)
-- in practice, `botID r` should be empty, but
-- it seems that we don't lose anything by taking
-- the other possibility into account.
-- BUT :=> In our case, `botID r` can very well be
-- non-empty. The reason is that trees are broken
-- down into flat rules and therefore intermediary
-- nodes are split.
, (botID $ root p, botID r) ]
-- construct the resultant state
-- Q: Why are we using `Right` here?
let conv = mapID $ convID . Right
q' = q
{ end = end p
, root = conv $ root q
, left = map conv $ r : left q
, right = map conv $ tail $ right q
, graph = resGraph }
-- print logging information
lift . lift $ do
putStr "[U] " >> printState p
putStr " + " >> printState q
putStr " : " >> printState q'
-- push the resulting state into the waiting queue
lift $ pushState $ StateE q'
--------------------------------------------------
-- ADJOIN
--------------------------------------------------
-- | `tryAdjoinInit p q':
-- * `p' is a completed state (regular or auxiliary)
-- * `q' not completed and expects a *real* foot
--
-- No FS unification is taking place here, it is performed at the
-- level of `tryAdjoinTerm(inate)`.
--
tryAdjoinInit
:: (VOrd n, VOrd t, VOrd a, VOrd f)
=> StateE n t f a
-> Earley n t f a ()
tryAdjoinInit (StateE p) = void $ P.runListT $ do
-- make sure that `p' is fully-matched and that it is either
-- a regular rule or an intermediate auxiliary rule ((<=)
-- used as an implication here!); look at `tryAdjoinTerm`
-- for motivations.
guard $ completed p && auxiliary p <= subLevel p
-- before: guard $ completed p
-- find all rules which expect a real foot (with ID == Nothing)
-- and which end where `p' begins.
let u = nonTerm (root p)
StateE q <- expectEnd (SAux (u, Nothing)) (beg p)
-- NOTE: While `SAux (u, Nothing)` can, in theory, represent an
-- auxiliary root as well as a foot, in this context (i.e. as an
-- argument to `expectEnd`) it can only be interpreted as a foot.
(r@AuxFoot{}, _) <- some $ expects' q
-- construct the resultant state
let q' = q
{ gap = Just (beg p, end p)
, end = end p
, left = r : left q
, right = tail (right q) }
-- print logging information
lift . lift $ do
putStr "[A] " >> printState p
putStr " + " >> printState q
putStr " : " >> printState q'
-- push the resulting state into the waiting queue
lift $ pushState $ StateE q'
-- | `tryAdjoinCont p q':
-- * `p' is a completed, auxiliary state
-- * `q' not completed and expects a *dummy* foot
tryAdjoinCont
:: (VOrd n, VOrd t, VOrd f, VOrd a)
=> StateE n t f a
-> Earley n t f a ()
tryAdjoinCont (StateE p) = void $ P.runListT $ do
-- make sure that `p' is a completed, sub-level auxiliary rule
guard $ completed p && subLevel p && auxiliary p
-- find all rules which expect a foot provided by `p'
-- and which end where `p' begins.
StateE q <- expectEnd (simpLab $ root p) (beg p)
(r@AuxVert{}, _) <- some $ expects' q
-- unify the feature structures corresponding to the 'p's
-- root and 'q's foot. TODO: We assume here that graph IDs
-- are disjoint.
J.Res{..} <- some $ U.unify (graph p) (graph q)
[ (topID $ root p, topID r)
, (botID $ root p, botID r) ]
-- construct the resulting state; the span of the gap of the
-- inner state `p' is copied to the outer state based on `q'
let conv = mapID $ convID . Right
q' = q
{ gap = gap p, end = end p
, root = conv $ root q
, left = map conv $ r : left q
, right = map conv $ tail $ right q
-- , left = r : left q
-- , right = tail (right q)
, graph = resGraph }
-- logging info
lift . lift $ do
putStr "[B] " >> printState p
putStr " + " >> printState q
putStr " : " >> printState q'
-- push the resulting state into the waiting queue
lift $ pushState $ StateE q'
-- | Adjoin a fully-parsed auxiliary state `p` to a partially parsed
-- tree represented by a fully parsed rule/state `q`.
tryAdjoinTerm
:: (VOrd t, VOrd n, VOrd a, VOrd f)
=> StateE n t f a
-> Earley n t f a ()
tryAdjoinTerm (StateE p) = void $ P.runListT $ do
-- make sure that `p' is a completed, top-level state ...
guard $ completed p && topLevel p
-- ... and that it is an auxiliary state (by definition only
-- auxiliary states have gaps)
(gapBeg, gapEnd) <- each $ maybeToList $ gap p
-- it is top-level, so we can also make sure that the
-- root is an AuxRoot.
pRoot@AuxRoot{} <- some $ Just $ root p
-- take all completed rules with a given span
-- and a given root non-terminal (IDs irrelevant)
StateE q <- rootSpan (nonTerm $ root p) (gapBeg, gapEnd)
-- make sure that `q' is completed as well and that it is either
-- a regular (perhaps intermediate) rule or an intermediate
-- auxiliary rule (note that (<=) is used as an implication
-- here and can be read as `implies`).
-- NOTE: root auxiliary rules are of no interest to us but they
-- are all the same taken into account in an indirect manner.
-- We can assume here that such rules are already adjoined thus
-- creating either regular or intermediate auxiliary.
-- NOTE: similar reasoning can be used to explain why foot
-- auxiliary rules are likewise ignored.
-- Q: don't get this second remark -- how could a foot node
-- be a root of a state/rule `q`? What `foot auxiliary rules`
-- could actually mean?
guard $ completed q && auxiliary q <= subLevel q
-- TODO: it seems that some of the constraints given above
-- follow from the code below:
qRoot <- some $ case root q of
x@NonT{} -> Just x
x@AuxVert{} -> Just x
_ -> Nothing
J.Res{..} <- some $ U.unify (graph p) (graph q)
[ (topID pRoot, topID qRoot)
, (footBotID pRoot, botID qRoot) ]
let convR = mapID $ convID . Right
convL = convID . Left
newRoot <- some $ case qRoot of
NonT{} -> Just $ NonT
{ nonTerm = nonTerm qRoot
, labID = labID qRoot
, topID = convL $ topID pRoot
, botID = convL $ botID pRoot }
AuxVert{} -> Just $ AuxVert
{ nonTerm = nonTerm qRoot
, symID = symID qRoot
, topID = convL $ topID pRoot
, botID = convL $ botID pRoot }
_ -> Nothing
let q' = q
{ root = newRoot
, left = map convR $ left q
, right = map convR $ right q
, beg = beg p
, end = end p
, graph = resGraph }
lift . lift $ do
putStr "[C] " >> printState p
putStr " + " >> printState q
putStr " : " >> printState q'
lift $ pushState $ StateE q'
--------------------------------------------------
-- EARLEY
--------------------------------------------------
-- | Perform the earley-style computation given the grammar and
-- the input sentence.
earley
:: (VOrd t, VOrd n, VOrd f, VOrd a)
=> S.Set (Rule n t ID f a) -- ^ The grammar (set of rules)
-> [t] -- ^ Input sentence
-> IO (S.Set (StateE n t f a))
-- -> IO ()
earley gram xs =
agregate . doneProSpan . fst <$> RWS.execRWST loop xs st0
-- void $ RWS.execRWST loop xs st0
where
-- Agregate the results from the `doneProSpan` part of the
-- result.
agregate = S.unions . M.elems
-- we put in the initial state all the states with the dot on
-- the left of the body of the rule (-> left = []) on all
-- positions of the input sentence.
st0 = mkEarSt $ S.fromList -- $ Reid.runReid $ mapM reidState
[ StateE $ State
{ root = headR
, left = []
, right = bodyR
, beg = i
, end = i
, gap = Nothing
, graph = graphR }
| Rule{..} <- S.toList gram
, i <- [0 .. length xs - 1] ]
-- the computation is performed as long as the waiting queue
-- is non-empty.
loop = popState >>= \mp -> case mp of
Nothing -> return ()
Just p -> do
-- lift $ case p of
-- (StateE q) -> putStr "POPED: " >> printState q
step p >> loop
-- | Step of the algorithm loop. `p' is the state popped up from
-- the queue.
step
:: (VOrd t, VOrd n, VOrd f, VOrd a)
=> StateE n t f a
-> Earley n t f a ()
step p = do
sequence_ $ map ($p)
[ tryScan, trySubst
, tryAdjoinInit
, tryAdjoinCont
, tryAdjoinTerm ]
saveState p
--------------------------------------------------
-- Utility
--------------------------------------------------
-- | Retrieve the Just value. Error otherwise.
unJust :: Maybe a -> a
unJust (Just x) = x
unJust Nothing = error "unJust: got Nothing!"
-- | Deconstruct list. Utility function. Similar to `unCons`.
decoList :: [a] -> Maybe (a, [a])
decoList [] = Nothing
decoList (y:ys) = Just (y, ys)
-- | MaybeT transformer.
maybeT :: Monad m => Maybe a -> MaybeT m a
maybeT = MaybeT . return
-- | ListT from a list.
each :: Monad m => [a] -> P.ListT m a
each = P.Select . P.each
-- | ListT from a maybe.
some :: Monad m => Maybe a -> P.ListT m a
some = each . maybeToList
-- | Lookup an element in a set.
lookupSet :: Ord a => a -> S.Set a -> Maybe a
lookupSet x s = do
y <- S.lookupLE x s
guard $ x == y
return y
| kawu/ltag | src/NLP/LTAG/Earley5.hs | bsd-2-clause | 42,413 | 0 | 20 | 13,240 | 12,414 | 6,476 | 5,938 | -1 | -1 |
-- 20492570929
mm = [2,3,4]
nn = 50
-- first block is either black or colored
-- a(n) = a(n-1) + a(n-m)
-- ignore all-black result
-- f(n) = a(n) - 1
getCount0 m = (map (getSlowCount m) [0..] !!)
getSlowCount m n = if m > n then 1 else getCount0 m (n-1) + getCount0 m (n-m)
getCount m n = (getCount0 m n) - 1
sumAllCounts ms n = sum $ map (\m -> getCount m n) ms
main = putStrLn $ show $ 20492570929 -- XXX sumAllCounts mm nn
| higgsd/euler | hs/116.hs | bsd-2-clause | 430 | 4 | 9 | 96 | 182 | 92 | 90 | 7 | 2 |
module Drasil.GamePhysics.Changes (likelyChgs, unlikelyChgs) where
--A list of likely and unlikely changes for GamePhysics
import Language.Drasil
import Utils.Drasil
import Data.Drasil.Concepts.Documentation as Doc (library, likeChgDom, unlikeChgDom)
import qualified Data.Drasil.Concepts.Math as CM (ode, constraint)
import Data.Drasil.Concepts.Computation (algorithm)
import qualified Data.Drasil.Concepts.Physics as CP (collision, damping, joint)
import Drasil.GamePhysics.Assumptions (assumpCT, assumpDI, assumpCAJI)
---------------------
-- LIKELY CHANGES --
---------------------
likelyChangesStmt1, likelyChangesStmt2, likelyChangesStmt3,
likelyChangesStmt4 :: Sentence
--these statements look like they could be parametrized
likelyChangesStmt1 = (S "internal" +:+ getAcc CM.ode :+:
S "-solving" +:+ phrase algorithm +:+ S "used by the" +:+
phrase library) `maybeChanged` S "in the future"
likelyChangesStmt2 = chgsStart assumpCT $ phrase library `maybeExpanded`
(S "to deal with edge-to-edge and vertex-to-vertex" +:+
plural CP.collision)
likelyChangesStmt3 = chgsStart assumpDI $ phrase library `maybeExpanded` (
S "to include motion with" +:+ phrase CP.damping)
likelyChangesStmt4 = chgsStart assumpCAJI $ phrase library `maybeExpanded` (
S "to include" +:+ plural CP.joint `sAnd` plural CM.constraint)
lcVODES, lcEC, lcID, lcIJC :: ConceptInstance
lcVODES = cic "lcVODES" likelyChangesStmt1 "Variable-ODE-Solver" likeChgDom
lcEC = cic "lcEC" likelyChangesStmt2 "Expanded-Collisions" likeChgDom
lcID = cic "lcID" likelyChangesStmt3 "Include-Dampening" likeChgDom
lcIJC = cic "lcIJC" likelyChangesStmt4 "Include-Joints-Constraints" likeChgDom
likelyChgs :: [ConceptInstance]
likelyChgs = [lcVODES, lcEC, lcID, lcIJC]
--------------------------------
--UNLIKELY CHANGES --
--------------------------------
unlikelyChangesStmt1, unlikelyChangesStmt2, unlikelyChangesStmt3, unlikelyChangesStmt4 :: Sentence
unlikelyChangesStmt1 = S "The goal of the system is to simulate the interactions of rigid bodies."
unlikelyChangesStmt2 = S "There will always be a source of input data external to the software."
unlikelyChangesStmt3 = S "A Cartesian Coordinate system is used."
unlikelyChangesStmt4 = S "All objects are rigid bodies."
ucSRB, ucEI, ucCCS, ucORB :: ConceptInstance
ucSRB = cic "ucSRB" unlikelyChangesStmt1 "Simulate-Rigid-Bodies" unlikeChgDom
ucEI = cic "ucEI" unlikelyChangesStmt2 "External-Input" unlikeChgDom
ucCCS = cic "ucCCS" unlikelyChangesStmt3 "Cartesian-Coordinate-System" unlikeChgDom
ucORB = cic "ucORB" unlikelyChangesStmt4 "Objects-Rigid-Bodies" unlikeChgDom
unlikelyChgs :: [ConceptInstance]
unlikelyChgs = [ucSRB, ucEI, ucCCS, ucORB]
| JacquesCarette/literate-scientific-software | code/drasil-example/Drasil/GamePhysics/Changes.hs | bsd-2-clause | 2,698 | 0 | 13 | 329 | 535 | 312 | 223 | 39 | 1 |
{-# LANGUAGE TemplateHaskell #-}{-|
Forth word definition.
-}
module Language.Forth.Word (ForthWord(..), WordId(..), WordKind(..),
WordFlags(..), LinkField, wordFlags, hasFlag,
name, wordSymbol, link, doer, wordId, wordKind,
maxNameLen,
exitName, pdoName, ploopName, pploopName,
pleaveName) where
import Control.Lens
import Data.Char
import Translator.Symbol
-- | Unique identifier for words.
newtype WordId = WordId { unWordId :: Int } deriving (Eq, Ord)
instance Show WordId where
show (WordId n) = show n
type LinkField a = Maybe (ForthWord a)
data WordKind = Native | Colon | InterpreterNative deriving Eq
data WordFlags = Immediate | CompileOnly deriving Eq
-- | A Forth word
data ForthWord a = ForthWord
{ _name :: Maybe String
, _wordSymbol :: Maybe Symbol -- ^ Symbol used, valid for target words
, _wordFlags :: [WordFlags]
, _link :: LinkField a
, _wordId :: WordId
, _wordKind :: WordKind
, _doer :: a
}
makeLenses ''ForthWord
instance Eq (ForthWord a) where
a == b = _wordId a == _wordId b
instance Show (ForthWord a) where
show word = case _name word of
Just name -> name
otherwise -> "anonymous" ++ show (_wordId word)
-- | Limit words to this length
maxNameLen :: Int
maxNameLen = 31
-- | Test if a word has a certain flag set
hasFlag flag word = word^.wordFlags & elem flag
exitName, pdoName, ploopName, pploopName, pleaveName :: String
exitName = "EXIT"
pdoName = "(DO)"
ploopName = "(LOOP)"
pploopName = "(+LOOP)"
pleaveName = "(LEAVE)"
| hth313/hthforth | src/Language/Forth/Word.hs | bsd-2-clause | 1,680 | 0 | 12 | 457 | 431 | 253 | 178 | 40 | 1 |
{-# LANGUAGE TypeFamilies, TypeOperators, DataKinds #-}
module Control.Effect.CounterNat where
import Control.Effect
import GHC.TypeLits
import Prelude hiding (Monad(..))
{-| Provides a way to 'count' in the type-level with a monadic interface
to sum up the individual counts of subcomputations. Instead
of using our own inductive natural number typ, this uses the 'Nat' kind from 'GHC.TypeLits' -}
{-| The counter has no semantic meaning -}
data Counter (n :: Nat) a = Counter { forget :: a }
instance Effect Counter where
type Inv Counter n m = ()
{-| Trivial effect annotation is 0 -}
type Unit Counter = 0
{-| Compose effects by addition -}
type Plus Counter n m = n + m
return a = Counter a
(Counter a) >>= k = Counter . forget $ k a
{-| A 'tick' provides a way to increment the counter -}
tick :: a -> Counter 1 a
tick x = Counter x
| dorchard/effect-monad | src/Control/Effect/CounterNat.hs | bsd-2-clause | 886 | 0 | 8 | 200 | 172 | 97 | 75 | 14 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Test.Ganeti.JSON (testJSON) where
import Data.List
import Test.QuickCheck
import qualified Text.JSON as J
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import qualified Ganeti.BasicTypes as BasicTypes
import qualified Ganeti.JSON as JSON
prop_toArray :: [Int] -> Property
prop_toArray intarr =
let arr = map J.showJSON intarr in
case JSON.toArray (J.JSArray arr) of
BasicTypes.Ok arr' -> arr ==? arr'
BasicTypes.Bad err -> failTest $ "Failed to parse array: " ++ err
prop_toArrayFail :: Int -> String -> Bool -> Property
prop_toArrayFail i s b =
-- poor man's instance Arbitrary JSValue
forAll (elements [J.showJSON i, J.showJSON s, J.showJSON b]) $ \item ->
case JSON.toArray item::BasicTypes.Result [J.JSValue] of
BasicTypes.Bad _ -> passTest
BasicTypes.Ok result -> failTest $ "Unexpected parse, got " ++ show result
arrayMaybeToJson :: (J.JSON a) => [Maybe a] -> String -> JSON.JSRecord
arrayMaybeToJson xs k = [(k, J.JSArray $ map sh xs)]
where
sh x = case x of
Just v -> J.showJSON v
Nothing -> J.JSNull
prop_arrayMaybeFromObj :: String -> [Maybe Int] -> String -> Property
prop_arrayMaybeFromObj t xs k =
case JSON.tryArrayMaybeFromObj t (arrayMaybeToJson xs k) k of
BasicTypes.Ok xs' -> xs' ==? xs
BasicTypes.Bad e -> failTest $ "Parsing failing, got: " ++ show e
prop_arrayMaybeFromObjFail :: String -> String -> Property
prop_arrayMaybeFromObjFail t k =
case JSON.tryArrayMaybeFromObj t [] k of
BasicTypes.Ok r -> fail $
"Unexpected result, got: " ++ show (r::[Maybe Int])
BasicTypes.Bad e -> conjoin [ Data.List.isInfixOf t e ==? True
, Data.List.isInfixOf k e ==? True
]
testSuite "JSON"
[ 'prop_toArray
, 'prop_toArrayFail
, 'prop_arrayMaybeFromObj
, 'prop_arrayMaybeFromObjFail
]
| apyrgio/snf-ganeti | test/hs/Test/Ganeti/JSON.hs | bsd-2-clause | 3,352 | 0 | 12 | 684 | 609 | 318 | 291 | 44 | 2 |
-- Header -------------------------------------------------------------- {{{
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Grade.Parse (
SecCallback(..), parseDefns, parseData, commentStart, commentEnd
) where
import Control.Applicative
-- import qualified Control.Lens as L
-- import Control.Monad (guard, when)
import Control.Monad.State
import Data.Text (Text,unpack)
-- import qualified Data.Char as C
import qualified Data.Map as M
-- import qualified Data.Set as S
import Data.String (IsString)
-- import Data.Semigroup ((<>))
import Data.Maybe (isJust)
import qualified Text.Trifecta as T
import qualified Text.Trifecta.Delta as T
import qualified Text.Parser.LookAhead as T
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import Grade.Types
import Grade.ParseUtils
------------------------------------------------------------------------ }}}
-- Common -------------------------------------------------------------- {{{
commentStart, commentEnd :: (IsString s) => s
commentStart = "$BEGIN_COMMENTS"
commentEnd = "$END_COMMENTS"
------------------------------------------------------------------------ }}}
-- Defines ------------------------------------------------------------- {{{
-- | Grab a ByteString that is a wad of text terminated by a dot on a line
-- by itself. This terminating line is not included.
untilDotLine :: (T.DeltaParsing f, T.LookAheadParsing f) => f Text
untilDotLine = toUtf8 (T.sliced (T.manyTill T.anyChar (T.try $ T.lookAhead end)))
<* end <* T.whiteSpace
where
end = T.newline *> T.char '.' *> T.newline
-- | Given a parser for X, parse lines of the form ":name X" preceeded by
-- any number of "# comment" lines and followed by the ding text, terminated
-- by a dot line.
parseDingDefn :: (T.DeltaParsing f, T.LookAheadParsing f)
=> f (sdt,sds) -> f (DingName, sds, DingDefn sdt T.Caret)
parseDingDefn dl = do
(dcs, reuse) <- T.try ((,) <$> many (hashComment) <*> leadchar)
dn T.:^ c <- T.careted (DN <$> word)
(dm, ds) <- dl
-- XXX optional comment here?
dt <- untilDotLine
pure (dn, ds, DingDefn (DingMeta dm dt) c reuse dcs)
where
leadchar = T.choice [ T.char ':' *> pure False
, T.char ';' *> pure True
]
parseSectionDefn :: (T.DeltaParsing f, T.MarkParsing T.Delta f, T.Errable f, T.LookAheadParsing f)
=> f (ExSecCallback f) -> f (SecName, ExSection f T.Caret)
parseSectionDefn fsdap = do
scs <- many hashComment
_ T.:^ c <- T.careted (T.symbolic '@')
sname <- SN <$> word
shidden <- isJust <$> T.optional (T.char '!')
esdp <- fsdap
_ <- T.symbolic '-'
stitle <- toUtf8 (T.sliced (T.manyTill T.anyChar (T.lookAhead T.newline)))
_ <- T.newline
_ <- T.whiteSpace
case esdp of
ExSecCB (SC mfss fsdt sdpo sfn smaxfn) -> do
(sstate, sdingsm, revsdings) <- getDings fsdt M.empty []
_ <- T.whiteSpace
return (sname, ExSec $
Sec (SecMeta stitle (smaxfn sstate) (sfn sstate) (sdpo sstate))
c
shidden
scs
sdingsm
(reverse revsdings)
mfss)
where
getDings fsdt = go mempty
where
go s m l = nextDing s m l <|> return (s,m,l)
nextDing s m l = do
(dn, ds, db) <- parseDingDefn fsdt
case M.lookup dn m of
Nothing -> go (s `mappend` ds) (M.insert dn db m) ((dn,db):l)
Just d -> do
-- XXX this causes an error to be printed out *after* the ding,
-- typically at the beginning of the next line. Argh. It's also
-- really ugly but more informative than it was.
T.raiseErr (T.Err (Just $ "Duplicate ding definition" PP.<+> (PP.pretty $ show $ unDN dn) PP.<+> "original at"
PP.<+> (PP.pretty $ show $ _dingd_loc d)) [] mempty [])
-- | Parse a definitions file
parseDefns :: (T.DeltaParsing f, T.MarkParsing T.Delta f, T.Errable f, T.LookAheadParsing f)
=> f (ExSecCallback f) -> f (Defines f T.Caret)
parseDefns sectys = T.whiteSpace *> go M.empty [] <* T.eof
where
go m l = nextSection m l <|> return (Defs m (reverse l))
nextSection m l = do
(sn, sb) <- parseSectionDefn sectys
case M.lookup sn m of
Nothing -> go (M.insert sn sb m) ((sn,sb):l)
Just _ -> do
T.release (T.delta $ case sb of ExSec s -> _sec_loc s)
T.raiseErr (T.Err (Just "Duplicate section definition") [] mempty [])
------------------------------------------------------------------------ }}}
-- Data ---------------------------------------------------------------- {{{
-- | Parse a grader data file
parseData :: forall f loc . (T.DeltaParsing f, T.LookAheadParsing f)
=> Defines f loc -> f (DataFile T.Caret, [ReportError T.Caret])
parseData defs = do
_ <- T.whiteSpace
(ss, fsm) <- sections defs
_ <- many hashComment
_ <- T.eof
pure (DF ss, (if M.null fsm then id else (REMissingSections (M.keysSet fsm) :)) [])
where
sections (Defs sm0 _) = flip runStateT sm0 $ go M.empty
where
go already = do
_ <- many hashComment
another already <|> pure []
another already = do
(sn,esb) T.:^ sc <- get >>= \sm -> sectionDirective sm
case esb of
ExSec (Sec smeta _ _ _ sdm _ (_,fsat)) -> do
sat <- lift fsat
ds <- sectionDings sdm
mcs <- T.optional $
T.string commentStart *> T.newline *>
toUtf8 (T.sliced (T.manyTill T.anyChar (T.lookAhead cend))) <* cend
_ <- T.whiteSpace
((sn, ExDFS $ DFS smeta sat sc ds (maybe "" id mcs)) :)
<$> (modify (M.delete sn) >> go (M.insert sn () already))
cend = T.string commentEnd *> T.newline
sectionDirective = directiveChoice '@' (unpack . unSN)
sectionDings dm0 = go dm0 M.empty
where
go dm already = do
_ <- many hashComment
another dm already <|> pure []
another dm already = do
((dn,DingDefn dmeta _ dingmany _) T.:^ dc) <- dingDirective dm
((DFD dmeta dc) :) <$> go (if dingmany then dm else M.delete dn dm)
(if dingmany then already else M.insert dn () already)
dingDirective = directiveChoice ':' (unpack . unDN)
directiveChoice lc f m = do
_ T.:^ sc <- T.lookAhead (T.careted $ T.char lc)
(T.:^ sc) <$> parseMapKeys ((lc :) . f) m
{-
-- | Gobble characters until we're looking at something we probably know and
-- love; it's a guess, of course.
recover = T.skipSome (T.notFollowedBy (T.choice (T.try <$> sigil)) *> T.anyChar)
*> T.whiteSpace
where
sigil = [ T.newline *> T.whiteSpace *> T.char '@' *> pure ()
, T.newline *> T.whiteSpace *> T.char ':' *> pure ()
, T.char '#' *> pure ()
, T.symbol commentStart *> pure ()
]
dcErr lc fk falr fnew malr myet = do
_ T.:^ sc <- T.lookAhead (T.careted $ T.char lc)
T.choice [ (Right . (T.:^ sc)) <$> parseMapKeys ((lc :) . fk) myet
, (Left . falr sc . fst) <$> parseMapKeys ((lc :) . fk) malr
, (Left . fnew sc) <$> (T.char lc *> word <* sseof)
]
dcErr' lc fk malr myet = dcErr lc fk (flip SEDuplicateDing) (flip SEUndefinedDing)
-}
------------------------------------------------------------------------ }}}
| nwf/grade | lib/Grade/Parse.hs | bsd-2-clause | 7,714 | 0 | 26 | 2,060 | 2,154 | 1,103 | 1,051 | 120 | 4 |
module Main where
import Network.BitcoinRPC
rpcAuth :: RPCAuth
rpcAuth = RPCAuth "http://127.0.0.1:8332" "rpcuser" "localaccessonly"
main :: IO ()
main = getBlockCountR Nothing rpcAuth >>= print
| javgh/bitcoin-rpc | SampleApp3.hs | bsd-3-clause | 198 | 0 | 6 | 28 | 50 | 27 | 23 | 6 | 1 |
-- Subtyping relation
{-# LANGUAGE BangPatterns #-}
module LambdaQuest.Finter.Subtype where
import LambdaQuest.Finter.Type
import LambdaQuest.SystemFsub.Subtype (primSubType,primMeetType,primJoinType)
import Data.Foldable (foldl')
normalizeType :: [Binding] -> Type -> CCanonicalType
normalizeType ctx (TyPrim p) = [CTyPrim p]
normalizeType ctx (TyArr s t) = do
let !s' = normalizeType ctx s
t' <- normalizeType (AnonymousBind : ctx) t
return (CTyArr s' t')
normalizeType ctx (TyRef i name) = [CTyRef i name]
normalizeType ctx (TyAll name bound t) = do
let !bound' = normalizeType ctx bound
t' <- normalizeType (TyVarBind name bound' : ctx) t
return (CTyAll name bound' t')
normalizeType ctx (TyInter ts) = foldl' (meetTypeC ctx) [] $ map (normalizeType ctx) ts
normalizeType ctx TyTop = []
subTypeC :: [Binding] -> CCanonicalType -> CCanonicalType -> Bool
subTypeC ctx xs ys = all (\y -> any (\x -> subTypeI ctx x y) xs) ys
subTypeI :: [Binding] -> ICanonicalType -> ICanonicalType -> Bool
subTypeI ctx (CTyPrim s) (CTyPrim t) = primSubType s t
subTypeI ctx (CTyArr s0 s1) (CTyArr t0 t1) = subTypeC ctx t0 s0 && subTypeI (AnonymousBind : ctx) s1 t1
subTypeI ctx (CTyRef i _) (CTyRef i' _) | i == i' = True
subTypeI ctx (CTyRef i _) t = let bound = typeShiftC (i + 1) 0 $ getBoundFromCContext ctx i
in subTypeC ctx bound [t]
subTypeI ctx (CTyAll name b s) (CTyAll _ b' t) | b == b' = subTypeI (TyVarBind name b : ctx) s t
subTypeI ctx _ _ = False
meetTypeC :: [Binding] -> CCanonicalType -> CCanonicalType -> CCanonicalType
meetTypeC ctx = rr
where
r :: ICanonicalType -> [ICanonicalType] -> (Bool,[ICanonicalType])
r x [] = (True,[])
r x (y:ys) | subTypeI ctx x y = r x ys -- delete y
| subTypeI ctx y x = (False,y:ys) -- delete x
| otherwise = (y :) <$> r x ys
rr :: [ICanonicalType] -> [ICanonicalType] -> [ICanonicalType]
rr [] ys = ys
rr (x:xs) ys | x' = x : rr xs ys'
| otherwise = rr xs ys'
where (x',ys') = r x ys
joinTypeC :: [Binding] -> CCanonicalType -> CCanonicalType -> CCanonicalType
joinTypeC ctx s t | subTypeC ctx s t = t
| subTypeC ctx t s = s
| otherwise = do s' <- s
t' <- t
joinTypeI ctx s' t'
joinTypeI :: [Binding] -> ICanonicalType -> ICanonicalType -> CCanonicalType
joinTypeI ctx s t | subTypeI ctx s t = [t]
| subTypeI ctx t s = [s]
joinTypeI ctx (CTyPrim s) (CTyPrim t) = case primJoinType s t of
Just u -> [CTyPrim u]
Nothing -> []
joinTypeI ctx (CTyArr s0 s1) (CTyArr t0 t1) = CTyArr (meetTypeC ctx s0 t0) <$> (joinTypeI (AnonymousBind : ctx) s1 t1)
joinTypeI ctx (CTyRef i _) t = joinTypeC ctx (typeShiftC (i + 1) 0 (getBoundFromCContext ctx i)) [t]
joinTypeI ctx s (CTyRef i _) = joinTypeC ctx [s] (typeShiftC (i + 1) 0 (getBoundFromCContext ctx i))
joinTypeI ctx (CTyAll n b s) (CTyAll _ b' t)
| b == b' = CTyAll n b <$> joinTypeI (TyVarBind n b : ctx) s t
joinTypeI _ _ _ = []
subType :: [Binding] -> Type -> Type -> Bool
subType ctx s t = subTypeC ctx (normalizeType ctx s) (normalizeType ctx t)
-- (meetType ctx s t) is a type that is maximal among such u that both (u <: s) and (u <: t) are satisfied.
meetType :: [Binding] -> Type -> Type -> Type
meetType ctx s t = canonicalToOrdinary $ meetTypeC ctx (normalizeType ctx s) (normalizeType ctx t)
-- (joinType ctx s t) is a type that is minimal among such u that both (s <: u) and (t <: u) are satisfied.
joinType :: [Binding] -> Type -> Type -> Type
joinType ctx s t = canonicalToOrdinary $ joinTypeC ctx (normalizeType ctx s) (normalizeType ctx t)
exposeType :: [Binding] -> Type -> [Type]
exposeType = exposeTypeD 0
where
exposeTypeD :: Int -> [Binding] -> Type -> [Type]
exposeTypeD d ctx (TyRef i _) = exposeTypeD (i + 1 + d) (drop (i + 1) ctx) (getBoundFromContext ctx i)
exposeTypeD d ctx (TyInter tys) = concatMap (exposeTypeD d ctx) tys
exposeTypeD d ctx t = [typeShift d 0 t]
| minoki/LambdaQuest | src/LambdaQuest/Finter/Subtype.hs | bsd-3-clause | 4,133 | 0 | 12 | 1,058 | 1,718 | 860 | 858 | 70 | 3 |
module Conversion where
import Types
rawConvertTemp :: TemperatureUOM
-> TemperatureUOM
-> Double
-> Double
rawConvertTemp oldUOM newUOM = fromCelsius newUOM . toCelsius oldUOM
where
toCelsius :: TemperatureUOM -> Double -> Double
toCelsius Celsius x = x
toCelsius Fahrenheit x = (x - 32) / 1.8
toCelsius Kelvin x = x - 273.15
fromCelsius Celsius x = x
fromCelsius Fahrenheit x = 1.8 * x + 32
fromCelsius Kelvin x = x + 273.15
convertTemp :: TemperatureUOM
-> TemperatureUOM
-> Temperature
-> Temperature
convertTemp oldUOM newUOM = round . rawConvertTemp oldUOM newUOM . fromIntegral
rawConvertLen :: LocationUOM
-> LocationUOM
-> Double
-> Double
rawConvertLen oldUOM newUOM = fromMetres newUOM . toMetres oldUOM
where
toMetres :: LocationUOM -> Double -> Double
toMetres Metre x = x
toMetres Kilometre x = x * 1000
toMetres Mile x = x * 1609.344
fromMetres Metre x = x
fromMetres Kilometre x = x / 1000
fromMetres Mile x = x / 1609.344
convertLen :: Integral a
=> LocationUOM
-> LocationUOM
-> a
-> a
convertLen oldUOM newUOM = round . rawConvertLen oldUOM newUOM . fromIntegral
convertLoc :: LocationUOM
-> LocationUOM
-> Location
-> Location
convertLoc oldUOM newUOM (Location x y) =
let f = convertLen oldUOM newUOM
in Location (f x) (f y)
convertLine :: LogLine
-> LocationUOM
-> TemperatureUOM
-> LogLine
convertLine (LogLine ts loc temp obs) newLocUOM newTempUOM =
let oldLocUOM = observatoryLocationUOM obs
oldTempUOM = observatoryTemperatureUOM obs
newLoc = convertLoc oldLocUOM newLocUOM loc
newTemp = convertTemp oldTempUOM newTempUOM temp
in LogLine ts newLoc newTemp obs
statsLine :: LogLine
-> StatsLine
statsLine (LogLine _ (Location x y) temp obs) =
let oldLocUOM = observatoryLocationUOM obs
oldTempUOM = observatoryTemperatureUOM obs
f = rawConvertLen oldLocUOM Metre . fromIntegral
newLoc = (f x, f y)
newTemp = rawConvertTemp oldTempUOM Kelvin $ fromIntegral temp
in StatsLine newLoc newTemp obs
convertMetreKelvinToObservatory :: LogLine
-> LogLine
convertMetreKelvinToObservatory (LogLine ts loc temp obs) =
let newLocUOM = observatoryLocationUOM obs
newTempUOM = observatoryTemperatureUOM obs
newLoc = convertLoc Metre newLocUOM loc
newTemp = convertTemp Kelvin newTempUOM temp
in LogLine ts newLoc newTemp obs
| oswynb/weather | lib/Conversion.hs | bsd-3-clause | 2,796 | 0 | 10 | 901 | 725 | 360 | 365 | 71 | 5 |
{-# LANGUAGE TupleSections #-}
-- | Operations on the 'Actor' type that need the 'State' type,
-- but not the 'Action' type.
-- TODO: Document an export list after it's rewritten according to #17.
module Game.LambdaHack.Common.ActorState
( fidActorNotProjAssocs, fidActorNotProjList
, actorAssocsLvl, actorAssocs, actorList
, actorRegularAssocsLvl, actorRegularAssocs, actorRegularList
, bagAssocs, bagAssocsK, calculateTotal
, mergeItemQuant, sharedAllOwnedFid, findIid
, getCBag, getActorBag, getBodyActorBag, mapActorItems_, getActorAssocs
, nearbyFreePoints, whereTo, getCarriedAssocs, getCarriedIidCStore
, posToActors, getItemBody, memActor, getActorBody
, tryFindHeroK, getLocalTime, itemPrice, regenCalmDelta
, actorInAmbient, actorSkills, dispEnemy, fullAssocs, itemToFull
, goesIntoEqp, goesIntoInv, goesIntoSha, eqpOverfull, eqpFreeN
, storeFromC, lidFromC, aidFromC, hasCharge
, strongestMelee, isMelee, isMeleeEqp
) where
import Control.Applicative
import Control.Exception.Assert.Sugar
import qualified Data.Char as Char
import qualified Data.EnumMap.Strict as EM
import Data.Int (Int64)
import Data.List
import Data.Maybe
import qualified Data.Ord as Ord
import qualified Game.LambdaHack.Common.Ability as Ability
import Game.LambdaHack.Common.Actor
import qualified Game.LambdaHack.Common.Dice as Dice
import Game.LambdaHack.Common.Faction
import Game.LambdaHack.Common.Item
import Game.LambdaHack.Common.ItemStrongest
import qualified Game.LambdaHack.Common.Kind as Kind
import Game.LambdaHack.Common.Level
import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Common.Point
import Game.LambdaHack.Common.State
import qualified Game.LambdaHack.Common.Tile as Tile
import Game.LambdaHack.Common.Time
import Game.LambdaHack.Common.Vector
import qualified Game.LambdaHack.Content.ItemKind as IK
import Game.LambdaHack.Content.ModeKind
import Game.LambdaHack.Content.TileKind (TileKind)
fidActorNotProjAssocs :: FactionId -> State -> [(ActorId, Actor)]
fidActorNotProjAssocs fid s =
let f (_, b) = not (bproj b) && bfid b == fid
in filter f $ EM.assocs $ sactorD s
fidActorNotProjList :: FactionId -> State -> [Actor]
fidActorNotProjList fid s = map snd $ fidActorNotProjAssocs fid s
actorAssocsLvl :: (FactionId -> Bool) -> Level -> ActorDict
-> [(ActorId, Actor)]
actorAssocsLvl p lvl actorD =
mapMaybe (\aid -> let b = actorD EM.! aid
in if p (bfid b)
then Just (aid, b)
else Nothing)
$ concat $ EM.elems $ lprio lvl
actorAssocs :: (FactionId -> Bool) -> LevelId -> State
-> [(ActorId, Actor)]
actorAssocs p lid s =
actorAssocsLvl p (sdungeon s EM.! lid) (sactorD s)
actorList :: (FactionId -> Bool) -> LevelId -> State
-> [Actor]
actorList p lid s = map snd $ actorAssocs p lid s
actorRegularAssocsLvl :: (FactionId -> Bool) -> Level -> ActorDict
-> [(ActorId, Actor)]
actorRegularAssocsLvl p lvl actorD =
mapMaybe (\aid -> let b = actorD EM.! aid
in if not (bproj b) && bhp b > 0 && p (bfid b)
then Just (aid, b)
else Nothing)
$ concat $ EM.elems $ lprio lvl
actorRegularAssocs :: (FactionId -> Bool) -> LevelId -> State
-> [(ActorId, Actor)]
actorRegularAssocs p lid s =
actorRegularAssocsLvl p (sdungeon s EM.! lid) (sactorD s)
actorRegularList :: (FactionId -> Bool) -> LevelId -> State
-> [Actor]
actorRegularList p lid s = map snd $ actorRegularAssocs p lid s
getItemBody :: ItemId -> State -> Item
getItemBody iid s =
let assFail = assert `failure` "item body not found" `twith` (iid, s)
in EM.findWithDefault assFail iid $ sitemD s
bagAssocs :: State -> ItemBag -> [(ItemId, Item)]
bagAssocs s bag =
let iidItem iid = (iid, getItemBody iid s)
in map iidItem $ EM.keys bag
bagAssocsK :: State -> ItemBag -> [(ItemId, (Item, ItemQuant))]
bagAssocsK s bag =
let iidItem (iid, kit) = (iid, (getItemBody iid s, kit))
in map iidItem $ EM.assocs bag
-- | Finds all actors at a position on the current level.
posToActors :: Point -> LevelId -> State -> [(ActorId, Actor)]
posToActors pos lid s =
let as = actorAssocs (const True) lid s
l = filter (\(_, b) -> bpos b == pos) as
in assert (length l <= 1 || all (bproj . snd) l
`blame` "many actors at the same position" `twith` l)
l
nearbyFreePoints :: (Kind.Id TileKind -> Bool) -> Point -> LevelId -> State
-> [Point]
nearbyFreePoints f start lid s =
let Kind.COps{cotile} = scops s
lvl@Level{lxsize, lysize} = sdungeon s EM.! lid
as = actorList (const True) lid s
good p = f (lvl `at` p)
&& Tile.isWalkable cotile (lvl `at` p)
&& unoccupied as p
ps = nub $ start : concatMap (vicinity lxsize lysize) ps
in filter good ps
-- | Calculate loot's worth for a faction of a given actor.
calculateTotal :: Actor -> State -> (ItemBag, Int)
calculateTotal body s =
let bag = sharedAllOwned body s
items = map (\(iid, (k, _)) -> (getItemBody iid s, k)) $ EM.assocs bag
in (bag, sum $ map itemPrice items)
mergeItemQuant :: ItemQuant -> ItemQuant -> ItemQuant
mergeItemQuant (k1, it1) (k2, it2) = (k1 + k2, it1 ++ it2)
sharedInv :: Actor -> State -> ItemBag
sharedInv body s =
let bs = fidActorNotProjList (bfid body) s
in EM.unionsWith mergeItemQuant
$ map binv $ if null bs then [body] else bs
sharedEqp :: Actor -> State -> ItemBag
sharedEqp body s =
let bs = fidActorNotProjList (bfid body) s
in EM.unionsWith mergeItemQuant
$ map beqp $ if null bs then [body] else bs
sharedAllOwned :: Actor -> State -> ItemBag
sharedAllOwned body s =
let shaBag = gsha $ sfactionD s EM.! bfid body
in EM.unionsWith mergeItemQuant [sharedEqp body s, sharedInv body s, shaBag]
sharedAllOwnedFid :: Bool -> FactionId -> State -> ItemBag
sharedAllOwnedFid onlyOrgans fid s =
let shaBag = gsha $ sfactionD s EM.! fid
bs = fidActorNotProjList fid s
in EM.unionsWith mergeItemQuant
$ if onlyOrgans
then map borgan bs
else map binv bs ++ map beqp bs ++ [shaBag]
findIid :: ActorId -> FactionId -> ItemId -> State -> [(Actor, CStore)]
findIid leader fid iid s =
let actors = fidActorNotProjAssocs fid s
itemsOfActor (aid, b) =
let itemsOfCStore store =
let bag = getBodyActorBag b store s
in map (\iid2 -> (iid2, (b, store))) (EM.keys bag)
stores = [CInv, CEqp] ++ [CSha | aid == leader]
in concatMap itemsOfCStore stores
items = concatMap itemsOfActor actors
in map snd $ filter ((== iid) . fst) items
-- | Price an item, taking count into consideration.
itemPrice :: (Item, Int) -> Int
itemPrice (item, jcount) =
case jsymbol item of
'$' -> jcount
'*' -> jcount * 100
_ -> 0
-- * These few operations look at, potentially, all levels of the dungeon.
-- | Tries to finds an actor body satisfying a predicate on any level.
tryFindActor :: State -> (Actor -> Bool) -> Maybe (ActorId, Actor)
tryFindActor s p =
find (p . snd) $ EM.assocs $ sactorD s
tryFindHeroK :: FactionId -> Int -> State -> Maybe (ActorId, Actor)
tryFindHeroK fact k s =
let c | k == 0 = '@'
| k > 0 && k < 10 = Char.intToDigit k
| otherwise = assert `failure` "no digit" `twith` k
in tryFindActor s (\body -> bsymbol body == c
&& not (bproj body)
&& bfid body == fact)
-- | Compute the level identifier and starting position on the level,
-- after a level change.
whereTo :: LevelId -- ^ level of the stairs
-> Point -- ^ position of the stairs
-> Int -- ^ jump up this many levels
-> Dungeon -- ^ current game dungeon
-> (LevelId, Point)
-- ^ target level and the position of its receiving stairs
whereTo lid pos k dungeon = assert (k /= 0) $
let lvl = dungeon EM.! lid
stairs = (if k < 0 then snd else fst) (lstair lvl)
defaultStairs = 0 -- for ascending via, e.g., spells
mindex = elemIndex pos stairs
i = fromMaybe defaultStairs mindex
in case ascendInBranch dungeon k lid of
[] | isNothing mindex -> (lid, pos) -- spell fizzles
[] -> assert `failure` "no dungeon level to go to" `twith` (lid, pos, k)
ln : _ -> let lvlTgt = dungeon EM.! ln
stairsTgt = (if k < 0 then fst else snd) (lstair lvlTgt)
in if length stairsTgt < i + 1
then assert `failure` "no stairs at index"
`twith` (lid, pos, k, ln, stairsTgt, i)
else (ln, stairsTgt !! i)
-- * The operations below disregard levels other than the current.
-- | Gets actor body from the current level. Error if not found.
getActorBody :: ActorId -> State -> Actor
getActorBody aid s =
let assFail = assert `failure` "body not found" `twith` (aid, s)
in EM.findWithDefault assFail aid $ sactorD s
getCarriedAssocs :: Actor -> State -> [(ItemId, Item)]
getCarriedAssocs b s =
bagAssocs s $ EM.unionsWith const [binv b, beqp b, borgan b]
getCarriedIidCStore :: Actor -> [(ItemId, CStore)]
getCarriedIidCStore b =
let bagCarried (cstore, bag) = map (,cstore) $ EM.keys bag
in concatMap bagCarried
[(CInv, binv b), (CEqp, beqp b), (COrgan, borgan b)]
getCBag :: Container -> State -> ItemBag
{-# INLINE getCBag #-}
getCBag c s = case c of
CFloor lid p -> EM.findWithDefault EM.empty p
$ lfloor (sdungeon s EM.! lid)
CEmbed lid p -> EM.findWithDefault EM.empty p
$ lembed (sdungeon s EM.! lid)
CActor aid cstore -> getActorBag aid cstore s
CTrunk{} -> assert `failure` c
getActorBag :: ActorId -> CStore -> State -> ItemBag
{-# INLINE getActorBag #-}
getActorBag aid cstore s =
let b = getActorBody aid s
in getBodyActorBag b cstore s
getBodyActorBag :: Actor -> CStore -> State -> ItemBag
{-# INLINE getBodyActorBag #-}
getBodyActorBag b cstore s =
case cstore of
CGround -> EM.findWithDefault EM.empty (bpos b)
$ lfloor (sdungeon s EM.! blid b)
COrgan -> borgan b
CEqp -> beqp b
CInv -> binv b
CSha -> gsha $ sfactionD s EM.! bfid b
mapActorItems_ :: Monad m
=> (CStore -> ItemId -> ItemQuant -> m a) -> Actor
-> State
-> m ()
mapActorItems_ f b s = do
let notProcessed = [CGround]
sts = [minBound..maxBound] \\ notProcessed
g cstore = do
let bag = getBodyActorBag b cstore s
mapM_ (uncurry $ f cstore) $ EM.assocs bag
mapM_ g sts
getActorAssocs :: ActorId -> CStore -> State -> [(ItemId, Item)]
getActorAssocs aid cstore s = bagAssocs s $ getActorBag aid cstore s
getActorAssocsK :: ActorId -> CStore -> State -> [(ItemId, (Item, ItemQuant))]
getActorAssocsK aid cstore s = bagAssocsK s $ getActorBag aid cstore s
-- | Checks if the actor is present on the current level.
-- The order of argument here and in other functions is set to allow
--
-- > b <- getsState (memActor a)
memActor :: ActorId -> LevelId -> State -> Bool
memActor aid lid s =
maybe False ((== lid) . blid) $ EM.lookup aid $ sactorD s
-- | Get current time from the dungeon data.
getLocalTime :: LevelId -> State -> Time
getLocalTime lid s = ltime $ sdungeon s EM.! lid
regenCalmDelta :: Actor -> [ItemFull] -> State -> Int64
regenCalmDelta b activeItems s =
let calmMax = sumSlotNoFilter IK.EqpSlotAddMaxCalm activeItems
calmIncr = oneM -- normal rate of calm regen
maxDeltaCalm = xM calmMax - bcalm b
-- Worry actor by enemies felt (even if not seen)
-- on the level within 3 steps.
fact = (EM.! bfid b) . sfactionD $ s
allFoes = actorRegularList (isAtWar fact) (blid b) s
isHeard body = not (waitedLastTurn body)
&& chessDist (bpos b) (bpos body) <= 3
noisyFoes = filter isHeard allFoes
in if null noisyFoes
then min calmIncr maxDeltaCalm
else minusM -- even if all calmness spent, keep informing the client
actorInAmbient :: Actor -> State -> Bool
actorInAmbient b s =
let Kind.COps{cotile} = scops s
lvl = (EM.! blid b) . sdungeon $ s
in Tile.isLit cotile (lvl `at` bpos b)
actorSkills :: Maybe ActorId -> ActorId -> [ItemFull] -> State -> Ability.Skills
actorSkills mleader aid activeItems s =
let body = getActorBody aid s
player = gplayer . (EM.! bfid body) . sfactionD $ s
skillsFromTactic = tacticSkills $ ftactic player
factionSkills
| Just aid == mleader = Ability.zeroSkills
| otherwise = fskillsOther player `Ability.addSkills` skillsFromTactic
itemSkills = sumSkills activeItems
in itemSkills `Ability.addSkills` factionSkills
tacticSkills :: Tactic -> Ability.Skills
tacticSkills TExplore = Ability.zeroSkills
tacticSkills TFollow = Ability.zeroSkills
tacticSkills TFollowNoItems = Ability.ignoreItems
tacticSkills TMeleeAndRanged = Ability.meleeAndRanged
tacticSkills TMeleeAdjacent = Ability.meleeAdjacent
tacticSkills TBlock = Ability.blockOnly
tacticSkills TRoam = Ability.zeroSkills
tacticSkills TPatrol = Ability.zeroSkills
-- Check whether an actor can displace an enemy. We assume they are adjacent.
dispEnemy :: ActorId -> ActorId -> [ItemFull] -> State -> Bool
dispEnemy source target activeItems s =
let hasSupport b =
let fact = (EM.! bfid b) . sfactionD $ s
friendlyFid fid = fid == bfid b || isAllied fact fid
sup = actorRegularList friendlyFid (blid b) s
in any (adjacent (bpos b) . bpos) sup
actorMaxSk = sumSkills activeItems
sb = getActorBody source s
tb = getActorBody target s
in bproj tb
|| not (actorDying tb
|| braced tb
|| EM.findWithDefault 0 Ability.AbMove actorMaxSk <= 0
|| hasSupport sb && hasSupport tb) -- solo actors are flexible
fullAssocs :: Kind.COps -> DiscoveryKind -> DiscoveryEffect
-> ActorId -> [CStore] -> State
-> [(ItemId, ItemFull)]
fullAssocs cops disco discoEffect aid cstores s =
let allAssocs = concatMap (\cstore -> getActorAssocsK aid cstore s) cstores
iToFull (iid, (item, kit)) =
(iid, itemToFull cops disco discoEffect iid item kit)
in map iToFull allAssocs
itemToFull :: Kind.COps -> DiscoveryKind -> DiscoveryEffect -> ItemId -> Item
-> ItemQuant
-> ItemFull
itemToFull Kind.COps{coitem=Kind.Ops{okind}}
disco discoEffect iid itemBase (itemK, itemTimer) =
let itemDisco = case EM.lookup (jkindIx itemBase) disco of
Nothing -> Nothing
Just itemKindId -> Just ItemDisco{ itemKindId
, itemKind = okind itemKindId
, itemAE = EM.lookup iid discoEffect }
in ItemFull {..}
-- Non-durable item that hurts doesn't go into equipment by default,
-- but if it is in equipment or among organs, it's used for melee
-- nevertheless, e.g., thorns.
goesIntoEqp :: ItemFull -> Bool
goesIntoEqp itemFull = isJust (strengthEqpSlot $ itemBase itemFull)
-- TODO: not needed if EqpSlotWeapon stays || isMeleeEqp itemFull)
goesIntoInv :: ItemFull -> Bool
goesIntoInv itemFull = IK.Precious `notElem` jfeature (itemBase itemFull)
&& not (goesIntoEqp itemFull)
goesIntoSha :: ItemFull -> Bool
goesIntoSha itemFull = IK.Precious `elem` jfeature (itemBase itemFull)
&& not (goesIntoEqp itemFull)
eqpOverfull :: Actor -> Int -> Bool
eqpOverfull b n = let size = sum $ map fst $ EM.elems $ beqp b
in assert (size <= 10 `blame` (b, n, size))
$ size + n > 10
eqpFreeN :: Actor -> Int
eqpFreeN b = let size = sum $ map fst $ EM.elems $ beqp b
in assert (size <= 10 `blame` (b, size))
$ 10 - size
storeFromC :: Container -> CStore
storeFromC c = case c of
CFloor{} -> CGround
CEmbed{} -> CGround
CActor _ cstore -> cstore
CTrunk{} -> assert `failure` c
-- | Determine the dungeon level of the container. If the item is in a shared
-- stash, the level depends on which actor asks.
lidFromC :: Container -> State -> LevelId
lidFromC (CFloor lid _) _ = lid
lidFromC (CEmbed lid _) _ = lid
lidFromC (CActor aid _) s = blid $ getActorBody aid s
lidFromC c@CTrunk{} _ = assert `failure` c
aidFromC :: Container -> Maybe ActorId
aidFromC CFloor{} = Nothing
aidFromC CEmbed{} = Nothing
aidFromC (CActor aid _) = Just aid
aidFromC c@CTrunk{} = assert `failure` c
hasCharge :: Time -> ItemFull -> Bool
hasCharge localTime itemFull@ItemFull{..} =
let it1 = case strengthFromEqpSlot IK.EqpSlotTimeout itemFull of
Nothing -> [] -- if item not IDed, assume no timeout, to ID by use
Just timeout ->
let timeoutTurns = timeDeltaScale (Delta timeTurn) timeout
charging startT = timeShift startT timeoutTurns > localTime
in filter charging itemTimer
len = length it1
in len < itemK
strMelee :: Bool -> Time -> ItemFull -> Maybe Int
strMelee effectBonus localTime itemFull =
let durable = IK.Durable `elem` jfeature (itemBase itemFull)
recharged = hasCharge localTime itemFull
-- We assume extra weapon effects are useful and so such
-- weapons are preferred over weapons with no effects.
-- If the player doesn't like a particular weapon's extra effect,
-- he has to manage this manually.
p (IK.Hurt d) = [Dice.meanDice d]
p (IK.Burn d) = [Dice.meanDice d]
p IK.NoEffect{} = []
p IK.OnSmash{} = []
-- Hackish extra bonus to force Summon as first effect used
-- before Calm of enemy is depleted.
p (IK.Recharging IK.Summon{}) = [999 | recharged && effectBonus]
-- We assume the weapon is still worth using, even if some effects
-- are charging; in particular, we assume Hurt or Burn are not
-- under Recharging.
p IK.Recharging{} = [100 | recharged && effectBonus]
p IK.Temporary{} = []
p _ = [100 | effectBonus]
psum = sum (strengthEffect p itemFull)
in if not (isMelee itemFull) || psum == 0
then Nothing
else Just $ psum + if durable then 1000 else 0
strongestMelee :: Bool -> Time -> [(ItemId, ItemFull)]
-> [(Int, (ItemId, ItemFull))]
strongestMelee effectBonus localTime is =
let f = strMelee effectBonus localTime
g (iid, itemFull) = (\v -> (v, (iid, itemFull))) <$> f itemFull
in sortBy (flip $ Ord.comparing fst) $ mapMaybe g is
isMelee :: ItemFull -> Bool
isMelee itemFull =
let p IK.Hurt{} = True
p IK.Burn{} = True
p _ = False
in case itemDisco itemFull of
Just ItemDisco{itemAE=Just ItemAspectEffect{jeffects}} ->
any p jeffects
Just ItemDisco{itemKind=IK.ItemKind{IK.ieffects}} ->
any p ieffects
Nothing -> False
-- Melee weapon so good (durable) that goes into equipment by default.
isMeleeEqp :: ItemFull -> Bool
isMeleeEqp itemFull =
let durable = IK.Durable `elem` jfeature (itemBase itemFull)
in isMelee itemFull && durable
| Concomitant/LambdaHack | Game/LambdaHack/Common/ActorState.hs | bsd-3-clause | 19,079 | 0 | 19 | 4,704 | 6,061 | 3,186 | 2,875 | -1 | -1 |
module Maybe(
isJust, isNothing,
fromJust, fromMaybe, listToMaybe, maybeToList,
catMaybes, mapMaybe,
-- ...and what the Prelude exports
Maybe(Nothing, Just),
maybe
) where
instance Eq a => Eq (Maybe a) where
(==) = eqMaybe
eqMaybe x y = case x of
Nothing -> case y of
Nothing -> True
Just _ -> False
Just x -> case y of
Nothing -> False
Just y -> x == y
isJust :: Maybe a -> Bool
isJust x = case x of
(Just a) -> True
Nothing -> False
isNothing :: Maybe a -> Bool
isNothing = not . isJust
fromJust :: Maybe a -> a
fromJust x = case x of
(Just a) -> a
Nothing -> error "Maybe.fromJust: Nothing"
fromMaybe :: a -> Maybe a -> a
fromMaybe d x = case x of
Nothing -> d
Just a -> a
maybeToList :: Maybe a -> [a]
maybeToList x = case x of
Nothing -> []
Just a -> [a]
listToMaybe :: [a] -> Maybe a
listToMaybe = case x of
[] -> Nothing
(a:_) -> Just a
catMaybes :: [Maybe a] -> [a]
catMaybes ms = [ m | Just m <- ms ]
-- concatMap (\x -> case x of Nothing -> []; Just m -> [m]) ms
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
mapMaybe f = catMaybes . map f
| ndmitchell/qed | imports/Maybe.hs | bsd-3-clause | 1,357 | 0 | 11 | 537 | 475 | 249 | 226 | 43 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Validations.Parsers.Fixtures
( localPhoneNumber
, localPhoneNumberWithExtension
, phoneNumberWithAreaCode
, phoneNumberWithAreaCodeAndExtension
, phoneNumberWithAreaCodeAndCountryCode
, phoneNumberWithAreaCodeAndExtendedCountryCode
, phoneNumberWithAreaCodeAndCountryCodeAndExtension
, phoneNumberWithAreaCodeAndCountryCodeAndOneDigitExtension
, sevenDigitNumber
, eightDigitNumber
, nineDigitNumber
, tenDigitNumber
, elevenDigitNumber
, twelveDigitNumber
, thirteenDigitNumber
, fourteenDigitNumber
, fifteenDigitNumber
) where
import Validations.Types
import Data.Monoid(mempty)
localPhoneNumber :: PhoneNumber
localPhoneNumber = mempty {_exchange = "781", _suffix = "4218" }
localPhoneNumberWithExtension :: PhoneNumber
localPhoneNumberWithExtension = mempty {_exchange = "781", _suffix = "4218", _extension = "1111"}
phoneNumberWithAreaCode :: PhoneNumber
phoneNumberWithAreaCode = mempty {_areaCode = "313", _exchange = "781", _suffix = "4218"}
phoneNumberWithAreaCodeAndCountryCode :: PhoneNumber
phoneNumberWithAreaCodeAndCountryCode = mempty {_countryCode = "1", _areaCode = "313", _exchange = "781", _suffix = "4218"}
phoneNumberWithAreaCodeAndExtendedCountryCode :: PhoneNumber
phoneNumberWithAreaCodeAndExtendedCountryCode = mempty {_countryCode = "1212", _areaCode = "313", _exchange = "781", _suffix = "4218"}
phoneNumberWithAreaCodeAndCountryCodeAndExtension :: PhoneNumber
phoneNumberWithAreaCodeAndCountryCodeAndExtension = mempty {_countryCode = "21", _areaCode = "313", _exchange = "781", _suffix = "4218", _extension="1111"}
phoneNumberWithAreaCodeAndCountryCodeAndOneDigitExtension :: PhoneNumber
phoneNumberWithAreaCodeAndCountryCodeAndOneDigitExtension = mempty {_countryCode = "1", _areaCode = "222", _exchange = "222", _suffix = "2222", _extension="1"}
phoneNumberWithAreaCodeAndExtension :: PhoneNumber
phoneNumberWithAreaCodeAndExtension = mempty {_areaCode = "313", _exchange = "781", _suffix = "4218", _extension = "1111"}
--oneDigitNumber :: PhoneNumber
--oneDigitNumber = mempty {_exchange = "1", }
sevenDigitNumber :: PhoneNumber
sevenDigitNumber = mempty {_exchange = "111", _suffix = "1111" }
eightDigitNumber :: PhoneNumber
eightDigitNumber = mempty {_areaCode = "111", _exchange = "111", _suffix = "11"}
nineDigitNumber :: PhoneNumber
nineDigitNumber = mempty {_areaCode = "111", _exchange = "111", _suffix = "111"}
tenDigitNumber :: PhoneNumber
tenDigitNumber = mempty {_areaCode = "111", _exchange = "111", _suffix = "1111"}
elevenDigitNumber :: PhoneNumber
elevenDigitNumber = mempty {_countryCode = "1", _areaCode = "111", _exchange = "111", _suffix = "1111" }
twelveDigitNumber :: PhoneNumber
twelveDigitNumber = mempty {_countryCode = "11", _areaCode = "111", _exchange = "111", _suffix = "1111"}
thirteenDigitNumber :: PhoneNumber
thirteenDigitNumber = mempty {_countryCode = "111", _areaCode = "111", _exchange = "111", _suffix = "1111"}
fourteenDigitNumber :: PhoneNumber
fourteenDigitNumber = mempty {_countryCode = "1111", _areaCode = "111", _exchange = "111", _suffix = "1111"}
fifteenDigitNumber :: PhoneNumber
fifteenDigitNumber = mempty {_countryCode = "1111", _areaCode = "111", _exchange = "111", _suffix = "1111", _extension = "1"}
| mavenraven/validations-checkers | tests/Validations/Parsers/Fixtures.hs | bsd-3-clause | 3,325 | 0 | 6 | 440 | 654 | 419 | 235 | 55 | 1 |
module Lambdiff.Process where
import Data.List (foldl')
import Data.Maybe (fromMaybe)
import Lambdiff.DiffParse (ParseFileResult(..),
ParseChunk(..),
ParseLine(..))
import Lambdiff.Types
import Debug.Trace (trace)
isNotNull = (/= "/dev/null")
processParseFile :: ParseFileResult -> FileDiff
processParseFile (ParseFileResult name1 name2 chunks) =
FileDiff unifiedFilename direction sections
where
unifiedFilename = if name1exists then name1 else name2
name1exists = isNotNull name1
name2exists = isNotNull name2
direction = getDirection name1exists name2exists
getDirection True True = DirectionChanged
getDirection False True = DirectionAdded
getDirection True False = DirectionRemoved
sections = map processChunk chunks
processChunk :: ParseChunk -> DiffSection
processChunk (ParseChunk start1 start2 lines) =
DiffSection plines
where
!plines = (reverse . fst4) $! foldl' processLine
([], start1, start2, Nothing) lines
fst4 (a, b, c, d) = a
processLine :: ([DiffLine], Int, Int, Maybe Int)
-> ParseLine
-> ([DiffLine], Int, Int, Maybe Int)
processLine inp (ParseLineComment s) = inp
processLine (all, l1, l2, _) (ParseLineNone s) =
(newline : all, l1 + 1, l2 + 1, Nothing)
where
newline = DiffLine DirectionNone (Just (l1, s)) (Just (l2, s))
processLine (all, l1, l2, msub) (ParseLineSub s) =
(newline : all, l1 + 1, l2, Just $ (fromMaybe 0 msub) + 1)
where
newline = DiffLine DirectionRemoved (Just (l1, s)) Nothing
-- change case, merge:
processLine (all, l1, l2, Just 1) (ParseLineAdd s) =
(fixed, l1, l2 + 1, Nothing)
where
fixed = mergeChange allsimple
allsimple = simple : all
simple = DiffLine DirectionAdded Nothing (Just (l2, s))
-- non-change case:
processLine (all, l1, l2, msub) (ParseLineAdd s) =
(newline : all, l1, l2 + 1, fmap (subtract 1) msub)
where
newline = DiffLine DirectionAdded Nothing (Just (l2, s))
mergeChange :: [DiffLine] -> [DiffLine]
mergeChange lines =
mergedLines ++ remainingLines
where
(opLines, remainingLines) = span isAddOrSub lines
isAddOrSub (DiffLine DirectionAdded _ _) = True
isAddOrSub (DiffLine DirectionRemoved _ _) = True
isAddOrSub _ = False
mergedLines = uncurry (zipWith mergeLine) $ splitAt (length opLines `div` 2) opLines
mergeLine (DiffLine DirectionAdded Nothing add)
(DiffLine DirectionRemoved sub Nothing) =
DiffLine DirectionChanged sub add
| jamwt/lambdiff | src/Lambdiff/Process.hs | bsd-3-clause | 2,583 | 0 | 11 | 606 | 868 | 478 | 390 | -1 | -1 |
{-# language CPP #-}
-- | = Name
--
-- VK_KHR_display_swapchain - device extension
--
-- == VK_KHR_display_swapchain
--
-- [__Name String__]
-- @VK_KHR_display_swapchain@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 4
--
-- [__Revision__]
-- 10
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_swapchain@
--
-- - Requires @VK_KHR_display@
--
-- [__Contact__]
--
-- - James Jones
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_display_swapchain] @cubanismo%0A<<Here describe the issue or question you have about the VK_KHR_display_swapchain extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2017-03-13
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
-- - James Jones, NVIDIA
--
-- - Jeff Vigil, Qualcomm
--
-- - Jesse Hall, Google
--
-- == Description
--
-- This extension provides an API to create a swapchain directly on a
-- device’s display without any underlying window system.
--
-- == New Commands
--
-- - 'createSharedSwapchainsKHR'
--
-- == New Structures
--
-- - Extending 'Vulkan.Extensions.VK_KHR_swapchain.PresentInfoKHR':
--
-- - 'DisplayPresentInfoKHR'
--
-- == New Enum Constants
--
-- - 'KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME'
--
-- - 'KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.Result.Result':
--
-- - 'Vulkan.Core10.Enums.Result.ERROR_INCOMPATIBLE_DISPLAY_KHR'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR'
--
-- == Issues
--
-- 1) Should swapchains sharing images each hold a reference to the images,
-- or should it be up to the application to destroy the swapchains and
-- images in an order that avoids the need for reference counting?
--
-- __RESOLVED__: Take a reference. The lifetime of presentable images is
-- already complex enough.
--
-- 2) Should the @srcRect@ and @dstRect@ parameters be specified as part of
-- the presentation command, or at swapchain creation time?
--
-- __RESOLVED__: As part of the presentation command. This allows moving
-- and scaling the image on the screen without the need to respecify the
-- mode or create a new swapchain and presentable images.
--
-- 3) Should @srcRect@ and @dstRect@ be specified as rects, or separate
-- offset\/extent values?
--
-- __RESOLVED__: As rects. Specifying them separately might make it easier
-- for hardware to expose support for one but not the other, but in such
-- cases applications must just take care to obey the reported capabilities
-- and not use non-zero offsets or extents that require scaling, as
-- appropriate.
--
-- 4) How can applications create multiple swapchains that use the same
-- images?
--
-- __RESOLVED__: By calling 'createSharedSwapchainsKHR'.
--
-- An earlier resolution used
-- 'Vulkan.Extensions.VK_KHR_swapchain.createSwapchainKHR', chaining
-- multiple 'Vulkan.Extensions.VK_KHR_swapchain.SwapchainCreateInfoKHR'
-- structures through @pNext@. In order to allow each swapchain to also
-- allow other extension structs, a level of indirection was used:
-- 'Vulkan.Extensions.VK_KHR_swapchain.SwapchainCreateInfoKHR'::@pNext@
-- pointed to a different structure, which had both @sType@ and @pNext@
-- members for additional extensions, and also had a pointer to the next
-- 'Vulkan.Extensions.VK_KHR_swapchain.SwapchainCreateInfoKHR' structure.
-- The number of swapchains to be created could only be found by walking
-- this linked list of alternating structures, and the @pSwapchains@ out
-- parameter was reinterpreted to be an array of
-- 'Vulkan.Extensions.Handles.SwapchainKHR' handles.
--
-- Another option considered was a method to specify a “shared” swapchain
-- when creating a new swapchain, such that groups of swapchains using the
-- same images could be built up one at a time. This was deemed unusable
-- because drivers need to know all of the displays an image will be used
-- on when determining which internal formats and layouts to use for that
-- image.
--
-- == Examples
--
-- Note
--
-- The example code for the @VK_KHR_display@ and @VK_KHR_display_swapchain@
-- extensions was removed from the appendix after revision 1.0.43. The
-- display swapchain creation example code was ported to the cube demo that
-- is shipped with the official Khronos SDK, and is being kept up-to-date
-- in that location (see:
-- <https://github.com/KhronosGroup/Vulkan-Tools/blob/master/cube/cube.c>).
--
-- == Version History
--
-- - Revision 1, 2015-07-29 (James Jones)
--
-- - Initial draft
--
-- - Revision 2, 2015-08-21 (Ian Elliott)
--
-- - Renamed this extension and all of its enumerations, types,
-- functions, etc. This makes it compliant with the proposed
-- standard for Vulkan extensions.
--
-- - Switched from “revision” to “version”, including use of the
-- VK_MAKE_VERSION macro in the header file.
--
-- - Revision 3, 2015-09-01 (James Jones)
--
-- - Restore single-field revision number.
--
-- - Revision 4, 2015-09-08 (James Jones)
--
-- - Allow creating multiple swap chains that share the same images
-- using a single call to vkCreateSwapchainKHR().
--
-- - Revision 5, 2015-09-10 (Alon Or-bach)
--
-- - Removed underscores from SWAP_CHAIN in two enums.
--
-- - Revision 6, 2015-10-02 (James Jones)
--
-- - Added support for smart panels\/buffered displays.
--
-- - Revision 7, 2015-10-26 (Ian Elliott)
--
-- - Renamed from VK_EXT_KHR_display_swapchain to
-- VK_KHR_display_swapchain.
--
-- - Revision 8, 2015-11-03 (Daniel Rakos)
--
-- - Updated sample code based on the changes to VK_KHR_swapchain.
--
-- - Revision 9, 2015-11-10 (Jesse Hall)
--
-- - Replaced VkDisplaySwapchainCreateInfoKHR with
-- vkCreateSharedSwapchainsKHR, changing resolution of issue #4.
--
-- - Revision 10, 2017-03-13 (James Jones)
--
-- - Closed all remaining issues. The specification and
-- implementations have been shipping with the proposed resolutions
-- for some time now.
--
-- - Removed the sample code and noted it has been integrated into
-- the official Vulkan SDK cube demo.
--
-- == See Also
--
-- 'DisplayPresentInfoKHR', 'createSharedSwapchainsKHR'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_display_swapchain Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_KHR_display_swapchain ( createSharedSwapchainsKHR
, DisplayPresentInfoKHR(..)
, KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION
, pattern KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION
, KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME
, pattern KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME
, SurfaceKHR(..)
, SwapchainKHR(..)
, SwapchainCreateInfoKHR(..)
, PresentModeKHR(..)
, ColorSpaceKHR(..)
, CompositeAlphaFlagBitsKHR(..)
, CompositeAlphaFlagsKHR
, SurfaceTransformFlagBitsKHR(..)
, SurfaceTransformFlagsKHR
, SwapchainCreateFlagBitsKHR(..)
, SwapchainCreateFlagsKHR
) where
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Exception.Base (bracket)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Alloc (callocBytes)
import Foreign.Marshal.Alloc (free)
import GHC.Base (when)
import GHC.IO (throwIO)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Data.Vector (generateM)
import qualified Data.Vector (imapM_)
import qualified Data.Vector (length)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import Data.Word (Word32)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Data.Vector (Vector)
import Vulkan.CStruct.Utils (advancePtrBytes)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.CStruct.Extends (forgetExtensions)
import Vulkan.CStruct.Extends (pokeSomeCStruct)
import Vulkan.NamedType ((:::))
import Vulkan.Core10.AllocationCallbacks (AllocationCallbacks)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Handles (Device)
import Vulkan.Core10.Handles (Device(..))
import Vulkan.Core10.Handles (Device(Device))
import Vulkan.Dynamic (DeviceCmds(pVkCreateSharedSwapchainsKHR))
import Vulkan.Core10.Handles (Device_T)
import Vulkan.Core10.FundamentalTypes (Rect2D)
import Vulkan.Core10.Enums.Result (Result)
import Vulkan.Core10.Enums.Result (Result(..))
import Vulkan.CStruct.Extends (SomeStruct)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Extensions.VK_KHR_swapchain (SwapchainCreateInfoKHR)
import Vulkan.Extensions.Handles (SwapchainKHR)
import Vulkan.Extensions.Handles (SwapchainKHR(..))
import Vulkan.Exception (VulkanException(..))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR))
import Vulkan.Core10.Enums.Result (Result(SUCCESS))
import Vulkan.Extensions.VK_KHR_surface (ColorSpaceKHR(..))
import Vulkan.Extensions.VK_KHR_surface (CompositeAlphaFlagBitsKHR(..))
import Vulkan.Extensions.VK_KHR_surface (CompositeAlphaFlagsKHR)
import Vulkan.Extensions.VK_KHR_surface (PresentModeKHR(..))
import Vulkan.Extensions.Handles (SurfaceKHR(..))
import Vulkan.Extensions.VK_KHR_surface (SurfaceTransformFlagBitsKHR(..))
import Vulkan.Extensions.VK_KHR_surface (SurfaceTransformFlagsKHR)
import Vulkan.Extensions.VK_KHR_swapchain (SwapchainCreateFlagBitsKHR(..))
import Vulkan.Extensions.VK_KHR_swapchain (SwapchainCreateFlagsKHR)
import Vulkan.Extensions.VK_KHR_swapchain (SwapchainCreateInfoKHR(..))
import Vulkan.Extensions.Handles (SwapchainKHR(..))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCreateSharedSwapchainsKHR
:: FunPtr (Ptr Device_T -> Word32 -> Ptr (SomeStruct SwapchainCreateInfoKHR) -> Ptr AllocationCallbacks -> Ptr SwapchainKHR -> IO Result) -> Ptr Device_T -> Word32 -> Ptr (SomeStruct SwapchainCreateInfoKHR) -> Ptr AllocationCallbacks -> Ptr SwapchainKHR -> IO Result
-- | vkCreateSharedSwapchainsKHR - Create multiple swapchains that share
-- presentable images
--
-- = Description
--
-- 'createSharedSwapchainsKHR' is similar to
-- 'Vulkan.Extensions.VK_KHR_swapchain.createSwapchainKHR', except that it
-- takes an array of
-- 'Vulkan.Extensions.VK_KHR_swapchain.SwapchainCreateInfoKHR' structures,
-- and returns an array of swapchain objects.
--
-- The swapchain creation parameters that affect the properties and number
-- of presentable images /must/ match between all the swapchains. If the
-- displays used by any of the swapchains do not use the same presentable
-- image layout or are incompatible in a way that prevents sharing images,
-- swapchain creation will fail with the result code
-- 'Vulkan.Core10.Enums.Result.ERROR_INCOMPATIBLE_DISPLAY_KHR'. If any
-- error occurs, no swapchains will be created. Images presented to
-- multiple swapchains /must/ be re-acquired from all of them before
-- transitioning away from
-- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PRESENT_SRC_KHR'. After
-- destroying one or more of the swapchains, the remaining swapchains and
-- the presentable images /can/ continue to be used.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkCreateSharedSwapchainsKHR-device-parameter# @device@ /must/
-- be a valid 'Vulkan.Core10.Handles.Device' handle
--
-- - #VUID-vkCreateSharedSwapchainsKHR-pCreateInfos-parameter#
-- @pCreateInfos@ /must/ be a valid pointer to an array of
-- @swapchainCount@ valid
-- 'Vulkan.Extensions.VK_KHR_swapchain.SwapchainCreateInfoKHR'
-- structures
--
-- - #VUID-vkCreateSharedSwapchainsKHR-pAllocator-parameter# If
-- @pAllocator@ is not @NULL@, @pAllocator@ /must/ be a valid pointer
-- to a valid 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks'
-- structure
--
-- - #VUID-vkCreateSharedSwapchainsKHR-pSwapchains-parameter#
-- @pSwapchains@ /must/ be a valid pointer to an array of
-- @swapchainCount@ 'Vulkan.Extensions.Handles.SwapchainKHR' handles
--
-- - #VUID-vkCreateSharedSwapchainsKHR-swapchainCount-arraylength#
-- @swapchainCount@ /must/ be greater than @0@
--
-- == Host Synchronization
--
-- - Host access to @pCreateInfos@[].surface /must/ be externally
-- synchronized
--
-- - Host access to @pCreateInfos@[].oldSwapchain /must/ be externally
-- synchronized
--
-- == Return Codes
--
-- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
-- - 'Vulkan.Core10.Enums.Result.SUCCESS'
--
-- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
-- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY'
--
-- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY'
--
-- - 'Vulkan.Core10.Enums.Result.ERROR_INCOMPATIBLE_DISPLAY_KHR'
--
-- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST'
--
-- - 'Vulkan.Core10.Enums.Result.ERROR_SURFACE_LOST_KHR'
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_display_swapchain VK_KHR_display_swapchain>,
-- 'Vulkan.Core10.AllocationCallbacks.AllocationCallbacks',
-- 'Vulkan.Core10.Handles.Device',
-- 'Vulkan.Extensions.VK_KHR_swapchain.SwapchainCreateInfoKHR',
-- 'Vulkan.Extensions.Handles.SwapchainKHR'
createSharedSwapchainsKHR :: forall io
. (MonadIO io)
=> -- | @device@ is the device to create the swapchains for.
Device
-> -- | @pCreateInfos@ is a pointer to an array of
-- 'Vulkan.Extensions.VK_KHR_swapchain.SwapchainCreateInfoKHR' structures
-- specifying the parameters of the created swapchains.
("createInfos" ::: Vector (SomeStruct SwapchainCreateInfoKHR))
-> -- | @pAllocator@ is the allocator used for host memory allocated for the
-- swapchain objects when there is no more specific allocator available
-- (see
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#memory-allocation Memory Allocation>).
("allocator" ::: Maybe AllocationCallbacks)
-> io (("swapchains" ::: Vector SwapchainKHR))
createSharedSwapchainsKHR device createInfos allocator = liftIO . evalContT $ do
let vkCreateSharedSwapchainsKHRPtr = pVkCreateSharedSwapchainsKHR (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkCreateSharedSwapchainsKHRPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCreateSharedSwapchainsKHR is null" Nothing Nothing
let vkCreateSharedSwapchainsKHR' = mkVkCreateSharedSwapchainsKHR vkCreateSharedSwapchainsKHRPtr
pPCreateInfos <- ContT $ allocaBytes @(SwapchainCreateInfoKHR _) ((Data.Vector.length (createInfos)) * 104)
Data.Vector.imapM_ (\i e -> ContT $ pokeSomeCStruct (forgetExtensions (pPCreateInfos `plusPtr` (104 * (i)) :: Ptr (SwapchainCreateInfoKHR _))) (e) . ($ ())) (createInfos)
pAllocator <- case (allocator) of
Nothing -> pure nullPtr
Just j -> ContT $ withCStruct (j)
pPSwapchains <- ContT $ bracket (callocBytes @SwapchainKHR ((fromIntegral ((fromIntegral (Data.Vector.length $ (createInfos)) :: Word32))) * 8)) free
r <- lift $ traceAroundEvent "vkCreateSharedSwapchainsKHR" (vkCreateSharedSwapchainsKHR' (deviceHandle (device)) ((fromIntegral (Data.Vector.length $ (createInfos)) :: Word32)) (forgetExtensions (pPCreateInfos)) pAllocator (pPSwapchains))
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
pSwapchains <- lift $ generateM (fromIntegral ((fromIntegral (Data.Vector.length $ (createInfos)) :: Word32))) (\i -> peek @SwapchainKHR ((pPSwapchains `advancePtrBytes` (8 * (i)) :: Ptr SwapchainKHR)))
pure $ (pSwapchains)
-- | VkDisplayPresentInfoKHR - Structure describing parameters of a queue
-- presentation to a swapchain
--
-- = Description
--
-- If the extent of the @srcRect@ and @dstRect@ are not equal, the
-- presented pixels will be scaled accordingly.
--
-- == Valid Usage
--
-- - #VUID-VkDisplayPresentInfoKHR-srcRect-01257# @srcRect@ /must/
-- specify a rectangular region that is a subset of the image being
-- presented
--
-- - #VUID-VkDisplayPresentInfoKHR-dstRect-01258# @dstRect@ /must/
-- specify a rectangular region that is a subset of the @visibleRegion@
-- parameter of the display mode the swapchain being presented uses
--
-- - #VUID-VkDisplayPresentInfoKHR-persistentContent-01259# If the
-- @persistentContent@ member of the
-- 'Vulkan.Extensions.VK_KHR_display.DisplayPropertiesKHR' structure
-- returned by
-- 'Vulkan.Extensions.VK_KHR_display.getPhysicalDeviceDisplayPropertiesKHR'
-- for the display the present operation targets is
-- 'Vulkan.Core10.FundamentalTypes.FALSE', then @persistent@ /must/ be
-- 'Vulkan.Core10.FundamentalTypes.FALSE'
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkDisplayPresentInfoKHR-sType-sType# @sType@ /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR'
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_display_swapchain VK_KHR_display_swapchain>,
-- 'Vulkan.Core10.FundamentalTypes.Bool32',
-- 'Vulkan.Core10.FundamentalTypes.Rect2D',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data DisplayPresentInfoKHR = DisplayPresentInfoKHR
{ -- | @srcRect@ is a rectangular region of pixels to present. It /must/ be a
-- subset of the image being presented. If 'DisplayPresentInfoKHR' is not
-- specified, this region will be assumed to be the entire presentable
-- image.
srcRect :: Rect2D
, -- | @dstRect@ is a rectangular region within the visible region of the
-- swapchain’s display mode. If 'DisplayPresentInfoKHR' is not specified,
-- this region will be assumed to be the entire visible region of the
-- swapchain’s mode. If the specified rectangle is a subset of the display
-- mode’s visible region, content from display planes below the swapchain’s
-- plane will be visible outside the rectangle. If there are no planes
-- below the swapchain’s, the area outside the specified rectangle will be
-- black. If portions of the specified rectangle are outside of the
-- display’s visible region, pixels mapping only to those portions of the
-- rectangle will be discarded.
dstRect :: Rect2D
, -- | @persistent@: If this is 'Vulkan.Core10.FundamentalTypes.TRUE', the
-- display engine will enable buffered mode on displays that support it.
-- This allows the display engine to stop sending content to the display
-- until a new image is presented. The display will instead maintain a copy
-- of the last presented image. This allows less power to be used, but
-- /may/ increase presentation latency. If 'DisplayPresentInfoKHR' is not
-- specified, persistent mode will not be used.
persistent :: Bool
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (DisplayPresentInfoKHR)
#endif
deriving instance Show DisplayPresentInfoKHR
instance ToCStruct DisplayPresentInfoKHR where
withCStruct x f = allocaBytes 56 $ \p -> pokeCStruct p x (f p)
pokeCStruct p DisplayPresentInfoKHR{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Rect2D)) (srcRect)
poke ((p `plusPtr` 32 :: Ptr Rect2D)) (dstRect)
poke ((p `plusPtr` 48 :: Ptr Bool32)) (boolToBool32 (persistent))
f
cStructSize = 56
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Rect2D)) (zero)
poke ((p `plusPtr` 32 :: Ptr Rect2D)) (zero)
poke ((p `plusPtr` 48 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct DisplayPresentInfoKHR where
peekCStruct p = do
srcRect <- peekCStruct @Rect2D ((p `plusPtr` 16 :: Ptr Rect2D))
dstRect <- peekCStruct @Rect2D ((p `plusPtr` 32 :: Ptr Rect2D))
persistent <- peek @Bool32 ((p `plusPtr` 48 :: Ptr Bool32))
pure $ DisplayPresentInfoKHR
srcRect dstRect (bool32ToBool persistent)
instance Storable DisplayPresentInfoKHR where
sizeOf ~_ = 56
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero DisplayPresentInfoKHR where
zero = DisplayPresentInfoKHR
zero
zero
zero
type KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION = 10
-- No documentation found for TopLevel "VK_KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION"
pattern KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION = 10
type KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME = "VK_KHR_display_swapchain"
-- No documentation found for TopLevel "VK_KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME"
pattern KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME = "VK_KHR_display_swapchain"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_KHR_display_swapchain.hs | bsd-3-clause | 23,340 | 0 | 22 | 4,472 | 2,806 | 1,761 | 1,045 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.TextureBorderClamp
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the ARB_texture_border_clamp extension, see
-- <http://www.opengl.org/registry/specs/ARB/texture_border_clamp.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.TextureBorderClamp (
-- * Tokens
gl_CLAMP_TO_BORDER
) where
import Graphics.Rendering.OpenGL.Raw.Core32
| mfpi/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/TextureBorderClamp.hs | bsd-3-clause | 715 | 0 | 4 | 86 | 38 | 32 | 6 | 3 | 0 |
module Model where
import Prelude
import Yesod
import Data.Text (Text)
import Database.Persist.Quasi
import Data.Typeable (Typeable)
import Data.Time.Clock (UTCTime)
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [mkPersist sqlOnlySettings, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
| tanakh/icfp2013-clone | Model.hs | bsd-3-clause | 479 | 0 | 8 | 62 | 80 | 47 | 33 | -1 | -1 |
-- mod fclabels: http://hackage.haskell.org/package/fclabels
{-# LANGUAGE TypeOperators, TypeSynonymInstances, TemplateHaskell, PackageImports #-}
module Rika.Data.Record.Label
(
-- * Getter, setter and modifier types.
Getter
, Setter
, Modifier
-- * Label type.
, Point
, (:->) (Label)
, label
, get, set, mod
, fmapL
-- * Bidirectional functor.
, (:<->:) (..)
, (<->)
, Iso (..)
, lmap
, for
-- * State monadic label operations.
, getM, setM, modM, (=:)
-- * Derive labels using Template Haskell.
, module Rika.Data.Record.Label.TH
)
where
import Prelude hiding ((.), id, mod)
import Control.Applicative
import Control.Category
import "mtl" Control.Monad.State hiding (get)
import Rika.Data.Record.Label.TH
type Getter f o = f -> o
type Setter f i = i -> f -> f
type Modifier f i o = (o -> i) -> f -> f
data Point f i o = Point
{ _get :: Getter f o
, _set :: Setter f i
}
_mod :: Point f i o -> (o -> i) -> f -> f
_mod l f a = _set l (f (_get l a)) a
newtype (f :-> a) = Label { unLabel :: Point f a a }
-- Create a label out of a getter and setter.
label :: Getter f a -> Setter f a -> f :-> a
label g s = Label (Point g s)
-- | Get the getter function from a label.
get :: (f :-> a) -> f -> a
get = _get . unLabel
-- | Get the setter function from a label.
set :: (f :-> a) -> a -> f -> f
set = _set . unLabel
-- | Get the modifier function from a label.
mod :: (f :-> a) -> (a -> a) -> f -> f
mod = _mod . unLabel
instance Category (:->) where
id = Label (Point id const)
(Label a) . (Label b) = Label (Point (_get a . _get b) (_mod b . _set a))
instance Functor (Point f i) where
fmap f x = Point (f . _get x) (_set x)
instance Applicative (Point f i) where
pure a = Point (const a) (const id)
a <*> b = Point (_get a <*> _get b) (\r -> _set b r . _set a r)
fmapL :: Applicative f => (a :-> b) -> f a :-> f b
fmapL l = label (fmap (get l)) (\x f -> set l <$> x <*> f)
-- | This isomorphism type class is like a `Functor' but works in two directions.
class Iso f where
iso :: a :<->: b -> f a -> f b
iso (Lens a b) = osi (b <-> a)
osi :: a :<->: b -> f b -> f a
osi (Lens a b) = iso (b <-> a)
-- | The lens datatype, a function that works in two directions. To bad there
-- is no convenient way to do application for this.
data a :<->: b = Lens { fw :: a -> b, bw :: b -> a }
-- | Constructor for lenses.
infixr 7 <->
(<->) :: (a -> b) -> (b -> a) -> a :<->: b
a <-> b = Lens a b
instance Category (:<->:) where
id = Lens id id
(Lens a b) . (Lens c d) = Lens (a . c) (d . b)
instance Iso ((:->) i) where
iso l (Label a) = Label (Point (fw l . _get a) (_set a . bw l))
instance Iso ((:<->:) i) where
iso = (.)
lmap :: Functor f => (a :<->: b) -> f a :<->: f b
lmap l = let (Lens a b) = l in fmap a <-> fmap b
dimap :: (o' -> o) -> (i -> i') -> Point f i' o' -> Point f i o
dimap f g l = Point (f . _get l) (_set l . g)
-- | Combine a partial destructor with a label into something easily used in
-- the applicative instance for the hidden `Point' datatype. Internally uses
-- the covariant in getter, contravariant in setter bi-functioral-map function.
-- (Please refer to the example because this function is just not explainable
-- on its own.)
for :: (i -> o) -> (f :-> o) -> Point f i o
for a b = dimap id a (unLabel b)
-- | Get a value out of state pointed to by the specified label.
getM :: MonadState s m => s :-> b -> m b
getM = gets . get
-- | Set a value somewhere in state pointed to by the specified label.
setM :: MonadState s m => s :-> b -> b -> m ()
setM l = modify . set l
-- | Alias for `setM' that reads like an assignment.
infixr 7 =:
(=:) :: MonadState s m => s :-> b -> b -> m ()
(=:) = setM
-- | Modify a value with a function somewhere in state pointed to by the
-- specified label.
modM :: MonadState s m => s :-> b -> (b -> b) -> m ()
modM l = modify . mod l
| nfjinjing/human-rights-ios | src/Rika/Data/Record/Label.hs | bsd-3-clause | 3,924 | 0 | 11 | 997 | 1,537 | 830 | 707 | 84 | 1 |
--
-- Copyright © 2014-2015 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | Description: Define and operate on data sources.
--
-- /Synchronise/ interacts with external systems and propagates changes to
-- duplicated data between them; these external systems are 'DataSource's.
--
module Synchronise.DataSource
( -- * Definitions
DataSource(..)
, Command
, DataSourceError(..)
, DSMonad
, runDSMonad
-- * Operations
, createDocument
, readDocument
, updateDocument
, deleteDocument
) where
import Control.Applicative
import Control.Exception (Exception)
import Control.Monad
import Control.Monad.Error.Class
import Control.Monad.IO.Class
import Control.Monad.Trans.Except
import Data.Aeson
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.Char
import Data.Monoid
import Data.String ()
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Typeable (Typeable)
import System.Exit
import System.IO
import System.Log.Logger
import System.Process
import Text.Regex
import Synchronise.Configuration
import Synchronise.Document
import Synchronise.Identifier
-- TODO(thsutton): Remove this
{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
logName :: String
logName = "Synchronise.DataSource"
type ErrorMsg = String
data DataSourceError
= DecodeError ErrorMsg
| ForeignError Int Text
| IncompatibleDataSource ErrorMsg
deriving (Eq, Show, Typeable)
instance Exception DataSourceError
newtype DSMonad m a = DSMonad { unDSMonad :: ExceptT DataSourceError m a }
deriving (Applicative, Functor, Monad, MonadIO, MonadError DataSourceError)
runDSMonad :: DSMonad m a -> m (Either DataSourceError a)
runDSMonad = runExceptT . unDSMonad
-- | Replace a named hole in a string.
subNamedHole
:: String -- ^ hole name
-> String -- ^ Input string
-> String -- ^ Replacement text
-> String -- ^ Output string
subNamedHole name = subRegex . mkRegex $ name
-- | Prepare a 'Command' by interpolating
prepareCommand
:: DataSource
-> Maybe ForeignKey
-> Command
-> String
prepareCommand _ds fk cmd =
case fk of
Nothing -> T.unpack . unCommand $ cmd
Just ForeignKey{..} ->
let cmd' = T.unpack . unCommand $ cmd
in subNamedHole "%fk" cmd' (T.unpack fkID)
-- | Check that a 'DataSource' and a 'ForeignKey' are compatible, otherwise
-- raise an error in the monad.
checkCompatibility
:: ( Synchronisable a, Synchronisable b
, Show a, Show b
, MonadIO m)
=> a
-> b
-> DSMonad m ()
checkCompatibility a b
= unless (compatibleSource a b)
$ throwError (IncompatibleDataSource $ show a <> " is not compatible with " <> show b)
-- | Access a 'DataSource' and create a new 'Document' returning the
-- 'ForeignKey' which, in that source, identifies the document.
--
-- It is an error if the 'DataSource' and 'Document' supplied do not agree on
-- the entity and source names.
createDocument
:: (MonadIO m, Functor m)
=> DataSource
-> Document
-> DSMonad m ForeignKey
createDocument src doc = do
-- 1. Check source and key are compatible.
checkCompatibility src doc
-- 2. Spawn process.
let cmd = prepareCommand src Nothing . commandCreate $ src
process = (shell cmd) { std_out = CreatePipe, std_in = CreatePipe }
liftIO .debugM logName $ "CREATE command: " <> show cmd
(Just hin, Just hout, Nothing, hproc) <- liftIO $ createProcess process
-- 3. Write input.
liftIO . BSL.hPutStrLn hin . encode . _documentContent $ doc
liftIO $ hClose hin
-- 4. Read handles
output <- T.filter (not. isSpace) . T.decodeUtf8 <$> (liftIO . BS.hGetContents $ hout)
-- 5. Check return code, raising error if required.
exit <- liftIO $ waitForProcess hproc
liftIO . debugM logName $ "CREATE exit: " <> show exit
case exit of
ExitFailure c -> throwError $ ForeignError c output
ExitSuccess -> return ()
-- 6. Close handles.
liftIO $ hClose hout
-- 7. Parse response.
return $ ForeignKey (sourceEntity src) (sourceName src) output
-- | Access a 'DataSource' and retrieve the 'Document' identified, in that source,
-- by the given 'ForeignKey'.
--
-- It is an error if the 'DataSource' and 'ForeignKey' supplied do not agree on
-- the entity and source names.
readDocument
:: (MonadIO m, Functor m)
=> DataSource
-> ForeignKey
-> DSMonad m Document
readDocument src fk = do
-- 1. Check source and key are compatible.
checkCompatibility src fk
-- 2. Spawn process.
let cmd = prepareCommand src (Just fk) . commandRead $ src
process = (shell cmd) { std_out = CreatePipe }
liftIO . debugM logName $ "READ command: " <> show cmd
(Nothing, Just hout, Nothing, hproc) <- liftIO $ createProcess process
-- 3. Read output.
output <- liftIO $ BS.hGetContents hout
-- 4. Check return code, raising error if required.
exit <- liftIO $ waitForProcess hproc
liftIO . debugM logName $ "READ exit: " <> show exit
case exit of
ExitFailure c -> throwError $ ForeignError c (T.decodeUtf8 output)
ExitSuccess -> return ()
-- 5. Close handles.
liftIO $ hClose hout
-- 6. Parse input and return value.
case eitherDecode' . BSL.fromStrict $ output of
Left e -> throwError $ DecodeError e
Right j -> return $ Document (fkEntity fk) (fkSource fk) j
-- | Access a 'DataSource' and save the 'Document' under the specified
-- 'ForeignKey', returning the 'ForeignKey' to use for the updated document in
-- future.
--
-- It is an error if the 'DataSource' and 'ForeignKey' supplied do not agree on
-- the entity and source names.
updateDocument
:: (MonadIO m, Functor m)
=> DataSource
-> ForeignKey
-> Document
-> DSMonad m ForeignKey -- ^ New (or old) key for this document.
updateDocument src fk doc = do
-- 1. Check source, key, and document are compatible.
checkCompatibility src fk
checkCompatibility src doc
-- 2. Spawn process.
let cmd = prepareCommand src (Just fk) . commandUpdate $ src
process = (shell cmd) { std_out = CreatePipe, std_in = CreatePipe }
liftIO . debugM logName $ "UPDATE command: " <> show cmd
(Just hin, Just hout, Nothing, hproc) <- liftIO $ createProcess process
-- 3. Write input.
liftIO . BSL.hPutStrLn hin . encode . _documentContent $ doc
liftIO $ hClose hin
-- 4. Read handles
output <- T.filter (not. isSpace) . T.decodeUtf8 <$> (liftIO . BS.hGetContents $ hout)
-- 5. Check return code, raising error if required.
exit <- liftIO $ waitForProcess hproc
liftIO . debugM logName $ "UPDATE exit: " <> show exit
case exit of
ExitFailure c -> throwError $ ForeignError c output
ExitSuccess -> return ()
-- 6. Close handles.
liftIO $ hClose hout
-- 7. Parse response.
return $ ForeignKey (fkEntity fk) (fkSource fk) output
-- | Access a 'DataSource' and delete the 'Document' identified in that source
-- by the given 'ForeignKey'.
--
-- It is an error if the 'DataSource' and 'ForeignKey' do not agree on the
-- entity and source names.
deleteDocument
:: (MonadIO m, Functor m)
=> DataSource
-> ForeignKey
-> DSMonad m ()
deleteDocument src fk = do
-- 1. Check source and key are compatible.
checkCompatibility src fk
-- 2. Spawn process.
let cmd = prepareCommand src (Just fk) . commandDelete $ src
process = (shell cmd) { std_out = CreatePipe }
liftIO . debugM logName $ "DELETE command: " <> show cmd
(Nothing, Just hout, Nothing, hproc) <- liftIO $ createProcess process
-- 3. Read output
output <- liftIO $ BS.hGetContents hout
-- 4. Check return code, raising error if required.
exit <- liftIO $ waitForProcess hproc
liftIO . debugM logName $ "DELETE exit: " <> show exit
case exit of
ExitFailure c -> throwError $ ForeignError c (T.decodeUtf8 output)
ExitSuccess -> return ()
-- 5. Close handles.
liftIO $ hClose hout
| anchor/synchronise | lib/Synchronise/DataSource.hs | bsd-3-clause | 8,864 | 1 | 14 | 2,272 | 1,919 | 999 | 920 | 163 | 3 |
{-# LANGUAGE RecordWildCards #-}
module Abstract.Impl.Libs.Queue.Chan.Internal (
QueueChan,
mkQueue'Chan
) where
import Control.Exception
import Control.Concurrent
import Control.Concurrent.Chan
import Abstract.Interfaces.Queue
data QueueChan t = QueueChan {
_conn :: Chan t
}
mkQueue'Chan :: IO (Queue IO t)
mkQueue'Chan = do
mv <- newChan
return $ buildQueue $ QueueChan { _conn = mv }
enqueue' :: QueueChan t -> t -> IO ()
enqueue' QueueChan{..} t = do
writeChan _conn t
enqueueBatch' :: QueueChan t -> [t] -> IO ()
enqueueBatch' QueueChan{..} ts = do
writeList2Chan _conn ts
dequeue' :: QueueChan t -> IO (Maybe t)
dequeue' QueueChan{..} = readChan _conn >>= return . Just
drain' :: QueueChan t -> IO [t]
drain' QueueChan{..} = getChanContents _conn
size' :: QueueChan t -> IO Int
size' QueueChan{..} = return 0
destroy' :: QueueChan t -> IO ()
destroy' QueueChan{..} = return ()
buildQueue :: QueueChan t -> Queue IO t
buildQueue w =
Queue {
_enqueue = enqueue' w,
_enqueueBatch = enqueueBatch' w,
_dequeue = dequeue' w,
_drain = drain' w,
_size = size' w,
_destroy = destroy' w
}
| adarqui/Abstract-Impl-Libs | src/Abstract/Impl/Libs/Queue/Chan/Internal.hs | bsd-3-clause | 1,118 | 0 | 9 | 209 | 430 | 221 | 209 | 37 | 1 |
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE CPP #-}
module CLaSH.Util.CoreHW.TermSubst
( emptySubst
, extendTvSubst
, substTerm
)
where
-- External Modules
import Data.List (mapAccumL)
-- GHC API
import qualified CoreSubst
import Id (maybeModifyIdInfo, idInfo, idName)
import qualified Type
import Var (isTyVar, isLocalId, setVarType, varType)
#if __GLASGOW_HASKELL__ < 702
import Var (isTyCoVar)
#endif
import VarEnv (VarEnv, emptyVarEnv, extendVarEnv, lookupVarEnv, lookupInScope, extendInScopeSet, uniqAway, isEmptyVarEnv, delVarEnv)
import VarSet (VarSet, emptyVarSet, isEmptyVarSet)
-- Internal Modules
import CLaSH.Util (curLoc)
import CLaSH.Util.CoreHW.Syntax (Term(..), Var, Type, TyVar, AltCon(..))
import CLaSH.Util.CoreHW.Types (CoreBinding)
import CLaSH.Util.Pretty
data TermSubst = TermSubst CoreSubst.InScopeSet IdSubstEnv TvSubstEnv
type IdSubstEnv = VarEnv Var
type TvSubstEnv = VarEnv Type
emptyInScopeSet = CoreSubst.substInScope $ CoreSubst.emptySubst
emptySubst = TermSubst emptyInScopeSet emptyVarEnv emptyVarEnv
#if __GLASGOW_HASKELL__ < 702
extendTvSubst (TermSubst inScope ids tvs) var ty | isTyCoVar var = TermSubst inScope ids (extendVarEnv tvs var ty)
#else
extendTvSubst (TermSubst inScope ids tvs) var ty | isTyVar var = TermSubst inScope ids (extendVarEnv tvs var ty)
#endif
| otherwise = error $ $(curLoc) ++ "extendTvSubst called for non tyvar: " ++ show var
substTerm :: TermSubst -> Term -> Term
substTerm subst expr
= go expr
where
go (Var v) = Var (lookupIdSubst subst v)
go (Literal lit) = Literal lit
go (Prim x) = Prim x
go (Data dc) = Data dc
go (App fun arg) = App (go fun) (go arg)
go (TyApp fun ty) = TyApp (go fun) (substTy subst ty)
go (Lambda bndr body) = Lambda bndr' (substTerm subst' body)
where
(subst', bndr') = substBndr subst bndr
go (TyLambda bndr body) = TyLambda bndr' (substTerm subst' body)
where
(subst', bndr') = substBndr subst bndr
go (LetRec binds body) = LetRec binds' (substTerm subst' body)
where
(subst', binds') = substBinds subst binds
go (Case scrut ty alts) = Case (go scrut) (substTy subst ty) (map (goAlt subst) alts)
goAlt subst (DataAlt dc xs, rhs) = (DataAlt dc xs', substTerm subst' rhs)
where
(subst',xs') = substBndrs subst xs
goAlt subst (con, rhs) = (con, substTerm subst rhs)
substBinds :: TermSubst -> [CoreBinding] -> (TermSubst, [CoreBinding])
substBinds subst pairs = (subst', bndrs' `zip` rhss')
where
(bndrs,rhss) = unzip pairs
(subst', bndrs') = substRecBndrs subst bndrs
rhss' = map (substTerm subst') rhss
substRecBndrs :: TermSubst -> [Var] -> (TermSubst,[Var])
substRecBndrs subst bndrs
= (newSubst, newBndrs)
where
(newSubst, newBndrs) = mapAccumL (substIdBndr newSubst) subst bndrs
lookupIdSubst :: TermSubst -> Var -> Var
lookupIdSubst (TermSubst inScope ids _) v
| not (isLocalId v) = v
| Just e <- lookupVarEnv ids v = e
| Just v' <- lookupInScope inScope v = v'
| otherwise = v
substTy :: TermSubst -> Type -> Type
substTy subst ty = Type.substTy (getTvSubst subst) ty
getTvSubst :: TermSubst -> Type.TvSubst
getTvSubst (TermSubst inScope _ tenv) = Type.TvSubst inScope tenv
substBndr :: TermSubst -> Var -> (TermSubst, Var)
substBndr subst bndr
| isTyVar bndr = substTyVarBndr subst bndr
| otherwise = substIdBndr subst subst bndr
substBndrs :: TermSubst -> [Var] -> (TermSubst, [Var])
substBndrs = mapAccumL substBndr
substTyVarBndr :: TermSubst -> TyVar -> (TermSubst, TyVar)
substTyVarBndr (TermSubst inScope idEnv tvEnv) tv
= case Type.substTyVarBndr (Type.TvSubst inScope tvEnv) tv of
(Type.TvSubst inScope' tvEnv', tv') ->
(TermSubst inScope' idEnv tvEnv', tv')
substIdBndr :: TermSubst -> TermSubst -> Var -> (TermSubst, Var)
substIdBndr recSubst subst@(TermSubst inScope env tvs) oldId
= (TermSubst (inScope `extendInScopeSet` id2) newEnv tvs, id2)
where
id1 = uniqAway inScope oldId
id2 | noTypeChange = id1
| otherwise = setVarType id1 (substTy subst oldTy)
oldTy = varType oldId
noTypeChange = isEmptyVarEnv tvs || isEmptyVarSet (Type.tyVarsOfType oldTy)
newEnv | noChange = delVarEnv env oldId
| otherwise = extendVarEnv env oldId id2
noChange = id1 == oldId
| christiaanb/clash-tryout | src/CLaSH/Util/CoreHW/TermSubst.hs | bsd-3-clause | 4,791 | 0 | 11 | 1,317 | 1,485 | 783 | 702 | -1 | -1 |
module Tools (
usage
, version
, success
, failed
, contactLookup
) where
import System.Console.ANSI
import Types
-- | Define some useful functions and wrappers for hpt
-- | Classic usage string when user lauched with wrong arguments
usage :: String
usage = concat [ "Usage : \t-h, --help : display this message.\n"
, "\t\t-v, --version : display hpt's version and stability.\n"
]
-- | Version and stability information about hpt
version :: String
version = concat [ "hpt - Haskell Private Talk version 0.1.0\n"
, "========================================\n"
, "Stability : experimental\n"
, "hpt in under development and no garantee is given that the API will have consistency.\n\
\Please use for development and non-critical applications only.\n"
, "Author : Nicolas Schoemaeker (nschoe) <ns.schoe@gmail.com>\n"
]
-- | Eye-candy terminal formatting to print "success" in green
success :: String -> IO ()
success str = do
setSGR [SetColor Foreground Vivid Green]
putStr str
setSGR [Reset]
-- | Eye-candy terminal formatting to print failed" in red
failed :: String -> IO ()
failed str = do
setSGR [SetColor Foreground Vivid Red]
putStr str
setSGR [Reset]
-- | ContactList version of lookup
contactLookup :: UserName -> ContactList -> Maybe Contact
contactLookup _ [] = Nothing
contactLookup username (x:xs) | username == contactUserName x = Just x
| otherwise = contactLookup username xs
| nschoe/hpt | src/Tools.hs | bsd-3-clause | 1,681 | 0 | 9 | 510 | 264 | 137 | 127 | 31 | 1 |
{-# LANGUAGE FlexibleInstances, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Instances where -- copied (and adapted) from the core library
import XMonad.Hooks.ManageDocks
import XMonad.Layout.LimitWindows
import Test.QuickCheck
import Utils
import XMonad.StackSet
import Control.Monad
import Data.List ( nub )
import Graphics.X11 ( Rectangle(Rectangle) )
arbNat :: Gen Int
arbNat = abs <$> arbitrary
arbPos :: Gen Int
arbPos = (+ 1) . abs <$> arbitrary
instance Arbitrary (Stack Int) where
arbitrary = do
xs <- arbNat
ys <- arbNat
return $ Stack { up = [xs - 1, xs - 2 .. 0]
, focus = xs
, down = [xs + 1 .. xs + ys]
}
instance Arbitrary (Selection a) where
arbitrary = do
nm <- arbNat
st <- arbNat
Sel nm (st + nm) <$> arbPos
--
-- The all important Arbitrary instance for StackSet.
--
instance (Integral i, Integral s, Eq a, Arbitrary a, Arbitrary l, Arbitrary sd)
=> Arbitrary (StackSet i l a s sd) where
arbitrary = do
-- TODO: Fix this to be a reasonable higher number, Possibly use PositiveSized
numWs <- choose (1, 20) -- number of workspaces, there must be at least 1.
numScreens <- choose (1, numWs) -- number of physical screens, there must be at least 1
lay <- arbitrary -- pick any layout
wsIdxInFocus <- choose (1, numWs) -- pick index of WS to be in focus
-- The same screen id's will be present in the list, with high possibility.
screenDims <- replicateM numScreens arbitrary
-- Generate a list of "windows" for each workspace.
wsWindows <- vector numWs :: Gen [[a]]
-- Pick a random window "number" in each workspace, to give focus.
foc <- sequence
[ if null windows
then return Nothing
else Just <$> choose (0, length windows - 1)
| windows <- wsWindows
]
let tags' = [1 .. fromIntegral numWs]
focusWsWindows = zip foc wsWindows
wss = zip tags' focusWsWindows -- tmp representation of a workspace (tag, windows)
initSs = new lay tags' screenDims
return $ view (fromIntegral wsIdxInFocus) $ foldr
(\(tag', (focus', windows)) ss -> -- Fold through all generated (tags,windows).
-- set workspace active by tag and fold through all
-- windows while inserting them. Apply the given number
-- of `focusUp` on the resulting StackSet.
applyN focus' focusUp $ foldr insertUp (view tag' ss) windows
)
initSs
wss
--
-- Just generate StackSets with Char elements.
--
type Tag = Int
type Window = Char
type T = StackSet Tag Int Window Int Int
newtype EmptyStackSet = EmptyStackSet T
deriving Show
instance Arbitrary EmptyStackSet where
arbitrary = do
(NonEmptyNubList ns ) <- arbitrary
(NonEmptyNubList sds) <- arbitrary
l <- arbitrary
-- there cannot be more screens than workspaces:
return . EmptyStackSet . new l ns $ take (min (length ns) (length sds)) sds
newtype NonEmptyWindowsStackSet = NonEmptyWindowsStackSet T
deriving Show
instance Arbitrary NonEmptyWindowsStackSet where
arbitrary =
NonEmptyWindowsStackSet
`fmap` (arbitrary `suchThat` (not . null . allWindows))
instance Arbitrary RectC where
arbitrary = do
(x :: Int, y :: Int) <- arbitrary
NonNegative w <- arbitrary
NonNegative h <- arbitrary
return $ RectC
( fromIntegral x
, fromIntegral y
, fromIntegral $ x + w
, fromIntegral $ y + h
)
instance Arbitrary Rectangle where
arbitrary = Rectangle <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary RationalRect where
arbitrary = RationalRect <$> dim <*> dim <*> dim <*> dim
where
dim = arbitrary `suchThat` liftM2 (&&) (>= 0) (<= 1)
newtype SizedPositive = SizedPositive Int
deriving (Eq, Ord, Show, Read)
instance Arbitrary SizedPositive where
arbitrary = sized $ \s -> do
x <- choose (1, max 1 s)
return $ SizedPositive x
newtype NonEmptyNubList a = NonEmptyNubList [a]
deriving ( Eq, Ord, Show, Read )
instance (Eq a, Arbitrary a) => Arbitrary (NonEmptyNubList a) where
arbitrary =
NonEmptyNubList `fmap` (fmap nub arbitrary `suchThat` (not . null))
-- | Pull out an arbitrary tag from the StackSet. This removes the need for the
-- precondition "n `tagMember x` in many properties and thus reduces the number
-- of discarded tests.
--
-- n <- arbitraryTag x
--
-- We can do the reverse with a simple `suchThat`:
--
-- n <- arbitrary `suchThat` \n' -> not $ n' `tagMember` x
arbitraryTag :: T -> Gen Tag
arbitraryTag x = do
let ts = tags x
-- There must be at least 1 workspace, thus at least 1 tag.
idx <- choose (0, length ts - 1)
return $ ts !! idx
-- | Pull out an arbitrary window from a StackSet that is guaranteed to have a
-- non empty set of windows. This eliminates the precondition "i `member` x" in
-- a few properties.
--
--
-- foo (nex :: NonEmptyWindowsStackSet) = do
-- let NonEmptyWindowsStackSet x = nex
-- w <- arbitraryWindow nex
-- return $ .......
--
-- We can do the reverse with a simple `suchThat`:
--
-- n <- arbitrary `suchThat` \n' -> not $ n `member` x
arbitraryWindow :: NonEmptyWindowsStackSet -> Gen Window
arbitraryWindow (NonEmptyWindowsStackSet x) = do
let ws = allWindows x
-- We know that there are at least 1 window in a NonEmptyWindowsStackSet.
idx <- choose (0, length ws - 1)
return $ ws !! idx
| xmonad/xmonad-contrib | tests/Instances.hs | bsd-3-clause | 5,720 | 0 | 16 | 1,574 | 1,300 | 700 | 600 | 103 | 1 |
-- | Secure generation of random numbers and bytestrings.
module Pos.Crypto.Random
( SecureRandom(..)
, secureRandomBS
, deterministic
, randomNumber
, randomNumberInRange
) where
import Crypto.Number.Basic (numBytes)
import Crypto.Number.Serialize (os2ip)
import Crypto.OpenSSL.Random (randBytes)
import Crypto.Random (ChaChaDRG, MonadPseudoRandom, MonadRandom,
drgNewSeed, getRandomBytes, seedFromInteger, withDRG)
import qualified Data.ByteArray as ByteArray (convert)
import Universum
-- | Generate a cryptographically random 'ByteString' of specific length.
secureRandomBS :: MonadIO m => Int -> m ByteString
secureRandomBS = liftIO . randBytes
-- | You can use 'runSecureRandom' on any 'MonadRandom' computation to make
-- it use a Really Secure™ randomness source (that is, OpenSSL).
newtype SecureRandom a = SecureRandom {runSecureRandom :: IO a}
deriving (Functor, Applicative, Monad)
instance MonadRandom SecureRandom where
getRandomBytes n = SecureRandom (ByteArray.convert <$> secureRandomBS n)
-- | You can use 'deterministic' on any 'MonadRandom' computation to make it
-- use a seed (hopefully produced by a Really Secure™ randomness source). The
-- seed has to have enough entropy to make this function secure.
deterministic :: ByteString -> MonadPseudoRandom ChaChaDRG a -> a
deterministic seed gen = fst $ withDRG chachaSeed gen
where
chachaSeed = drgNewSeed . seedFromInteger . os2ip $ seed
-- | Generate a random number in range [0, n).
--
-- We want to avoid modulo bias, so we use the arc4random_uniform
-- implementation (http://stackoverflow.com/a/20051580/615030). Specifically,
-- we repeatedly generate a random number in range [0, 2^x) until we hit on
-- something outside of [0, 2^x mod n), which means that it'll be in range
-- [2^x mod n, 2^x). The amount of numbers in this interval is guaranteed to
-- be divisible by n, and thus applying 'mod' to it will be safe.
randomNumber :: MonadRandom m => Integer -> m Integer
randomNumber n
| n <= 0 = error "randomNumber: n <= 0"
| otherwise = gen
where
size = max 4 (numBytes n) -- size of integers, in bytes
rangeMod = 2 ^ (size * 8) `rem` n -- 2^x mod n
gen = do
x <- os2ip @ByteString <$> getRandomBytes size
if x < rangeMod then gen else return (x `rem` n)
-- | Generate a random number in range [a, b].
randomNumberInRange :: MonadRandom m => Integer -> Integer -> m Integer
randomNumberInRange a b
| a > b = error "randomNumberInRange: a > b"
| otherwise = (a +) <$> randomNumber (b - a + 1)
| input-output-hk/pos-haskell-prototype | crypto/Pos/Crypto/Random.hs | mit | 2,682 | 0 | 12 | 593 | 487 | 270 | 217 | -1 | -1 |
-----------------------------------------------------------------------------
--
-- Module : Base
-- Copyright :
-- License : MIT
--
-- Maintainer : agocorona@gmail.com
-- Stability :
-- Portability :
--
-- | See http://github.com/agocorona/transient
-- Everything in this module is exported in order to allow extensibility.
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE ConstraintKinds #-}
module Transient.Internals where
import Control.Applicative
import Control.Monad.State
import Data.Dynamic
import qualified Data.Map as M
import System.IO.Unsafe
import Unsafe.Coerce
import Control.Exception hiding (try,onException)
import qualified Control.Exception (try)
import Control.Concurrent
import GHC.Conc(unsafeIOToSTM)
import Control.Concurrent.STM hiding (retry)
import qualified Control.Concurrent.STM as STM (retry)
import System.Mem.StableName
import Data.Maybe
import Data.List
import Data.IORef
import System.Environment
import System.IO
import qualified Data.ByteString.Char8 as BS
import Data.Atomics
#ifdef DEBUG
import Data.Monoid
import Debug.Trace
import System.Exit
{-# INLINE (!>) #-}
(!>) :: Show a => b -> a -> b
(!>) x y = trace (show y) x
infixr 0 !>
#else
{-# INLINE (!>) #-}
(!>) :: a -> b -> a
(!>) = const
#endif
type SData= ()
data LifeCycle = Alive | Parent | Listener | Dead
deriving (Eq, Show)
-- | EventF describes the context of a TransientIO computation:
data EventF = EventF
{ mfData :: M.Map TypeRep SData
-- ^ State data accessed with get or put operations
, mfSequence :: Int
, threadId :: ThreadId
, freeTh :: Bool
-- ^ When 'True', threads are not killed using kill primitives
, parent :: Maybe EventF
-- ^ The parent of this thread
, children :: MVar [EventF]
-- ^ Forked child threads, used only when 'freeTh' is 'False'
, maxThread :: Maybe (IORef Int)
-- ^ Maximum number of threads that are allowed to be created
, labelth :: IORef (LifeCycle, BS.ByteString)
-- ^ Label the thread with its lifecycle state and a label string
} deriving Typeable
newtype Transient r a = Transient { runTransT :: (Maybe a -> StateIO (Maybe r)) -> StateIO (Maybe r) }
type StateIO = StateT EventF IO
type TransIO a= Transient a a
type TransientIO a= TransIO a
--type Transient r a= Transient r a
instance Monad (Transient r) where
return = pure
m >>= k = Transient $ \c -> runTransT m (\a -> runTransT (mayb k a) c)
where
mayb k (Just x)= k x
mayb _ Nothing = empty
instance MonadState EventF (Transient r ) where
get= liftt get -- where lift m = Transient ((Just <$> m) >>=)
put= liftt . put -- where lift m = Transient ((Just <$> m) >>=)
-- instance MonadTrans (Transient r) where
liftt m = Transient ((Just <$> m) >>=)
instance MonadIO (Transient r ) where
liftIO = liftt . liftIO
callCC :: ((a -> Transient r b) -> Transient r a) -> Transient r a
callCC f = Transient $ \ c -> runTransT (f (\ x -> Transient $ \ _ -> c $ Just x)) c
instance Functor (Transient r ) where
fmap f m = Transient $ \c -> runTransT m $ \ mx->
case mx of
Just x -> c $ Just $ f x
Nothing -> return Nothing
instance Monoid a => Monoid (Transient r a) where
mappend x y = mappend <$> x <*> y
mempty = return mempty
instance Applicative (Transient r ) where
pure a = Transient ($ Just a)
-- f <*> v = Transient $ \ k -> runTransT f $ \ g -> runTransT v (k . g)
f <*> v = do
r1 <- liftIO $ newIORef Nothing
r2 <- liftIO $ newIORef Nothing
fparallel r1 r2 <|> vparallel r1 r2
where
fparallel r1 r2= Transient $ \k -> do
runTransT f $ \mg -> do
liftIO $ writeIORef r1 mg !> "f write r1"
case mg of
Nothing -> return Nothing
Just g -> do
mt <- liftIO $ readIORef r2 !> "f read r2"
case mt of
Nothing -> return Nothing
Just t -> k . Just $ g t
vparallel r1 r2= Transient $ \k -> do
runTransT v $ \mt -> do
liftIO $ writeIORef r2 mt !> "v write r2"
mg <- liftIO $ readIORef r1 !> "v read r2"
case mg of
Nothing -> return Nothing
Just g -> do
case mt of
Nothing -> return Nothing
Just t -> k . Just $ g t
instance Alternative (Transient r ) where
empty= Transient ( $ Nothing)
f <|> g= Transient $ \ k ->do
mr <- runTransT f k
case mr of
Nothing -> runTransT g k
justr -> return justr
emptyEventF :: ThreadId -> IORef (LifeCycle, BS.ByteString) -> MVar [EventF] -> EventF
emptyEventF th label childs =
EventF { mfData = mempty
, mfSequence = 0
, threadId = th
, freeTh = False
, parent = Nothing
, children = childs
, maxThread = Nothing
, labelth = label }
-- | Run a transient computation with a default initial state
runTransient :: TransIO a -> IO (Maybe a, EventF)
-- runTransient :: Transient r (StateT EventF IO) r -> IO (Maybe r, EventF)
runTransient t = do
th <- myThreadId
label <- newIORef $ (Alive, BS.pack "top")
childs <- newMVar []
runTransState (emptyEventF th label childs) t
runTransState :: EventF -> TransIO a -> IO (Maybe a, EventF)
runTransState st t= runStateT (runTrans t) st
runTrans :: TransIO a -> StateIO (Maybe a)
runTrans t= ((flip runTransT) (return . id)) t
noTrans :: StateIO a -> TransIO a
noTrans x= Transient $ const $ x >>= return . Just
readWithErr :: (Typeable a, Read a) => String -> IO [(a, String)]
readWithErr line =
(v `seq` return [(v, left)])
`catch` (\(e :: SomeException) ->
error $ "read error trying to read type: \"" ++ show (typeOf v)
++ "\" in: " ++ " <" ++ show line ++ "> ")
where [(v, left)] = readsPrec 0 line
readsPrec' _ = unsafePerformIO . readWithErr
-- | Constraint type synonym for a value that can be logged.
type Loggable a = (Show a, Read a, Typeable a)
-- | Dynamic serializable data for logging.
data IDynamic =
IDyns String
| forall a. Loggable a => IDynamic a
instance Show IDynamic where
show (IDynamic x) = show (show x)
show (IDyns s) = show s
instance Read IDynamic where
readsPrec n str = map (\(x,s) -> (IDyns x,s)) $ readsPrec' n str
type Recover = Bool
type CurrentPointer = [LogElem]
type LogEntries = [LogElem]
data LogElem = Wait | Exec | Var IDynamic
deriving (Read, Show)
data Log = Log Recover CurrentPointer LogEntries
deriving (Typeable, Show)
data RemoteStatus = WasRemote | WasParallel | NoRemote
deriving (Typeable, Eq, Show)
-- | A synonym of 'empty' that can be used in a monadic expression. It stops
-- the computation, which allows the next computation in an 'Alternative'
-- ('<|>') composition to run.
stop :: Alternative m => m stopped
stop = empty
--instance (Num a,Eq a,Fractional a) =>Fractional (Transient r a)where
-- mf / mg = (/) <$> mf <*> mg
-- fromRational (x:%y) = fromInteger x % fromInteger y
instance (Num a, Eq a) => Num (Transient r a) where
fromInteger = return . fromInteger
mf + mg = (+) <$> mf <*> mg
mf * mg = (*) <$> mf <*> mg
negate f = f >>= return . negate
abs f = f >>= return . abs
signum f = f >>= return . signum
class AdditionalOperators m where
-- | Run @m a@ discarding its result before running @m b@.
(**>) :: m a -> m b -> m b
-- | Run @m b@ discarding its result, after the whole task set @m a@ is
-- done.
(<**) :: m a -> m b -> m a
atEnd' :: m a -> m b -> m a
atEnd' = (<**)
-- | Run @m b@ discarding its result, once after each task in @m a@, and
-- once again after the whole task set is done.
(<***) :: m a -> m b -> m a
atEnd :: m a -> m b -> m a
atEnd = (<***)
instance AdditionalOperators (Transient r ) where
-- (**>) :: Transient r a -> Transient r b -> Transient r b
(**>) f g =
Transient $ \k -> runTransT f $ \x -> runTransT g k
-- (<***) :: Transient r a -> Transient r b -> Transient r a
(<***) f g =
Transient $ \k -> runTransT f $ \mx -> do
case mx of
Nothing -> return Nothing
_ -> runTransT g (const $ return Nothing) >> k mx
-- (<**) :: Transient r a -> Transient r b -> Transient r a
(<**) f g =
Transient $ \k -> runTransT f $ \mx -> do
case mx of
Nothing -> return Nothing
_ -> runTransT g (const $ return Nothing) >> k mx
infixr 1 <***, <**, **>
-- * Threads
waitQSemB sem = atomicModifyIORefCAS sem $ \n ->
if n > 0 then(n - 1, True) else (n, False)
signalQSemB sem = atomicModifyIORefCAS sem $ \n -> (n + 1, ())
-- | Sets the maximum number of threads that can be created for the given task
-- set. When set to 0, new tasks start synchronously in the current thread.
-- New threads are created by 'parallel', and APIs that use parallel.
threads :: Int -> Transient r a -> Transient r a
threads n process = do
msem <- gets maxThread
sem <- liftIO $ newIORef n
modify $ \s -> s { maxThread = Just sem }
r <- process <** (modify $ \s -> s { maxThread = msem }) -- restore it
return r
-- | Terminate all the child threads in the given task set and continue
-- execution in the current thread. Useful to reap the children when a task is
-- done.
--
oneThread :: Transient r a -> Transient r a
oneThread comp = do
st <- get
chs <- liftIO $ newMVar []
label <- liftIO $ newIORef (Alive, BS.pack "oneThread")
let st' = st { parent = Just st
, children = chs
, labelth = label }
liftIO $ hangThread st st'
put st'
x <- comp
th <- liftIO myThreadId
-- !> ("FATHER:", threadId st)
chs <- liftIO $ readMVar chs -- children st'
liftIO $ mapM_ (killChildren1 th) chs
return x
where killChildren1 :: ThreadId -> EventF -> IO ()
killChildren1 th state = do
ths' <- modifyMVar (children state) $ \ths -> do
let (inn, ths')= partition (\st -> threadId st == th) ths
return (inn, ths')
mapM_ (killChildren1 th) ths'
mapM_ (killThread . threadId) ths'
-- !> ("KILLEVENT1 ", map threadId ths' )
-- | Add a label to the current passing threads so it can be printed by debugging calls like `showThreads`
labelState :: (MonadIO m,MonadState EventF m) => String -> m ()
labelState l = do
st <- get
liftIO $ atomicModifyIORefCAS (labelth st) $ \(status,_) -> ((status, BS.pack l), ())
printBlock :: MVar ()
printBlock = unsafePerformIO $ newMVar ()
-- | Show the tree of threads hanging from the state.
showThreads :: MonadIO m => EventF -> m ()
showThreads st = liftIO $ withMVar printBlock $ const $ do
mythread <- myThreadId
putStrLn "---------Threads-----------"
let showTree n ch = do
liftIO $ do
putStr $ take n $ repeat ' '
(state, label) <- readIORef $ labelth ch
if BS.null label
then putStr . show $ threadId ch
else do BS.putStr label; putStr . drop 8 . show $ threadId ch
when (state == Dead) $ putStr " dead"
putStrLn $ if mythread == threadId ch then " <--" else ""
chs <- readMVar $ children ch
mapM_ (showTree $ n + 2) $ reverse chs
showTree 0 st
-- | Return the state of the thread that initiated the transient computation
topState :: Transient r EventF
topState = do
st <- get
return $ toplevel st
where toplevel st = case parent st of
Nothing -> st
Just p -> toplevel p
-- | Return the state variable of the type desired with which a thread, identified by his number in the treee was initiated
showState :: (Typeable a, MonadIO m, Alternative m) => String -> EventF -> m (Maybe a)
showState th top = resp
where resp = do
let thstring = drop 9 . show $ threadId top
if thstring == th
then getstate top
else do
sts <- liftIO $ readMVar $ children top
foldl (<|>) empty $ map (showState th) sts
getstate st =
case M.lookup (typeOf $ typeResp resp) $ mfData st of
Just x -> return . Just $ unsafeCoerce x
Nothing -> return Nothing
typeResp :: m (Maybe x) -> x
typeResp = undefined
-- | Add n threads to the limit of threads. If there is no limit, the limit is set.
addThreads' :: Int -> TransIO ()
addThreads' n= noTrans $ do
msem <- gets maxThread
case msem of
Just sem -> liftIO $ modifyIORef sem $ \n' -> n + n'
Nothing -> do
sem <- liftIO (newIORef n)
modify $ \ s -> s { maxThread = Just sem }
-- | Ensure that at least n threads are available for the current task set.
addThreads :: Int -> TransIO ()
addThreads n = noTrans $ do
msem <- gets maxThread
case msem of
Nothing -> return ()
Just sem -> liftIO $ modifyIORef sem $ \n' -> if n' > n then n' else n
--getNonUsedThreads :: Transient r (Maybe Int)
--getNonUsedThreads= Transient $ do
-- msem <- gets maxThread
-- case msem of
-- Just sem -> liftIO $ Just <$> readIORef sem
-- Nothing -> return Nothing
-- | Disable tracking and therefore the ability to terminate the child threads.
-- By default, child threads are terminated automatically when the parent
-- thread dies, or they can be terminated using the kill primitives. Disabling
-- it may improve performance a bit, however, all threads must be well-behaved
-- to exit on their own to avoid a leak.
freeThreads :: Transient r a -> Transient r a
freeThreads process = do
st <- get
put st { freeTh = True }
r <- process
modify $ \s -> s { freeTh = freeTh st }
return r
-- | Enable tracking and therefore the ability to terminate the child threads.
-- This is the default but can be used to re-enable tracking if it was
-- previously disabled with 'freeThreads'.
hookedThreads :: Transient r a -> Transient r a
hookedThreads process = do
st <- get
put st {freeTh = False}
r <- process
modify $ \st -> st { freeTh = freeTh st }
return r
-- | Kill all the child threads of the current thread.
-- killChilds :: Transient r ()
killChilds :: TransIO ()
killChilds = noTrans $ do
cont <- get
liftIO $ do
killChildren $ children cont
writeIORef (labelth cont) (Alive, mempty)
-- !> (threadId cont,"relabeled")
return ()
-- | Kill the current thread and the childs.
killBranch :: TransIO ()
killBranch = noTrans $ do
st <- get
liftIO $ killBranch' st
-- | Kill the childs and the thread of an state
killBranch' :: EventF -> IO ()
killBranch' cont = do
killChildren $ children cont
let thisth = threadId cont
mparent = parent cont
when (isJust mparent) $
modifyMVar_ (children $ fromJust mparent) $ \sts ->
return $ filter (\st -> threadId st /= thisth) sts
killThread $ thisth
-- * Extensible State: Session Data Management
-- | Same as 'getSData' but with a more general type. If the data is found, a
-- 'Just' value is returned. Otherwise, a 'Nothing' value is returned.
getData :: (MonadState EventF m, Typeable a) => m (Maybe a)
getData = resp
where resp = do
list <- gets mfData
case M.lookup (typeOf $ typeResp resp) list of
Just x -> return . Just $ unsafeCoerce x
Nothing -> return Nothing
typeResp :: m (Maybe x) -> x
typeResp = undefined
-- | Retrieve a previously stored data item of the given data type from the
-- monad state. The data type to retrieve is implicitly determined from the
-- requested type context.
-- If the data item is not found, an 'empty' value (a void event) is returned.
-- Remember that an empty value stops the monad computation. If you want to
-- print an error message or a default value in that case, you can use an
-- 'Alternative' composition. For example:
--
-- > getSData <|> error "no data"
-- > getInt = getSData <|> return (0 :: Int)
getSData :: (Typeable r, Typeable a) => Transient r a
getSData = Transient $ const getData
-- | Same as `getSData`
getState :: Typeable a => TransIO a
getState = getSData
-- | 'setData' stores a data item in the monad state which can be retrieved
-- later using 'getData' or 'getSData'. Stored data items are keyed by their
-- data type, and therefore only one item of a given type can be stored. A
-- newtype wrapper can be used to distinguish two data items of the same type.
--
-- @
-- import Control.Monad.IO.Class (liftIO)
-- import Transient.Base
-- import Data.Typeable
--
-- data Person = Person
-- { name :: String
-- , age :: Int
-- } deriving Typeable
--
-- main = keep $ do
-- setData $ Person "Alberto" 55
-- Person name age <- getSData
-- liftIO $ print (name, age)
-- @
setData :: (MonadState EventF m, Typeable a) => a -> m ()
setData x = modify $ \st -> st { mfData = M.insert t (unsafeCoerce x) (mfData st) }
where t = typeOf x
-- | Accepts a function that takes the current value of the stored data type
-- and returns the modified value. If the function returns 'Nothing' the value
-- is deleted otherwise updated.
modifyData :: (MonadState EventF m, Typeable a) => (Maybe a -> Maybe a) -> m ()
modifyData f = modify $ \st -> st { mfData = M.alter alterf t (mfData st) }
where typeResp :: (Maybe a -> b) -> a
typeResp = undefined
t = typeOf (typeResp f)
alterf mx = unsafeCoerce $ f x'
where x' = case mx of
Just x -> Just $ unsafeCoerce x
Nothing -> Nothing
-- | Same as modifyData
modifyState :: (MonadState EventF m, Typeable a) => (Maybe a -> Maybe a) -> m ()
modifyState = modifyData
-- | Same as 'setData'
setState :: (MonadState EventF m, Typeable a) => a -> m ()
setState = setData
-- | Delete the data item of the given type from the monad state.
delData :: (MonadState EventF m, Typeable a) => a -> m ()
delData x = modify $ \st -> st { mfData = M.delete (typeOf x) (mfData st) }
-- | Same as 'delData'
delState :: (MonadState EventF m, Typeable a) => a -> m ()
delState = delData
-- STRefs for the Transient monad
newtype Ref a = Ref (IORef a)
-- | mutable state reference that can be updated (similar to STRef in the state monad)
--
-- Initialized the first time it is set.
setRState:: Typeable a => a -> Transient (Ref a) ()
setRState x= do
Ref ref <- getSData
liftIO $ atomicModifyIORefCAS ref $ const (x,())
<|> do
ref <- liftIO (newIORef x)
setData $ Ref ref
getRState :: Typeable a => Transient (Ref a) a
getRState= do
Ref ref <- getSData
liftIO $ readIORef ref
delRState x= delState (undefined `asTypeOf` ref x)
where ref :: a -> IORef a
ref= undefined
-- | Run an action, if it does not succeed, undo any state changes
-- that it might have caused and allow aternative actions to run with the original state
try :: Transient r a -> Transient r a
try mx = do
sd <- gets mfData
mx <|> (modify (\s -> s { mfData = sd }) >> empty)
-- | Executes the computation and reset the state either if it fails or not.
sandbox :: Transient r a -> Transient r a
sandbox mx = do
sd <- gets mfData
mx <*** modify (\s ->s { mfData = sd})
-- | Generator of identifiers that are unique within the current monadic
-- sequence They are not unique in the whole program.
genId :: MonadState EventF m => m Int
genId = do
st <- get
let n = mfSequence st
put st { mfSequence = n + 1 }
return n
getPrevId :: MonadState EventF m => m Int
getPrevId = gets mfSequence
instance Read SomeException where
readsPrec n str = [(SomeException $ ErrorCall s, r)]
where [(s , r)] = read str
-- | 'StreamData' represents a task in a task stream being generated.
data StreamData a =
SMore a -- ^ More tasks to come
| SLast a -- ^ This is the last task
| SDone -- ^ No more tasks, we are done
| SError SomeException -- ^ An error occurred
deriving (Typeable, Show,Read)
-- | An task stream generator that produces an infinite stream of tasks by
-- running an IO computation in a loop. A task is triggered carrying the output
-- of the computation. See 'parallel' for notes on the return value.
-- waitEvents :: IO a -> Transient r a
waitEvents io = do
mr <- parallel (SMore <$> io)
case mr of
SMore x -> return x
SError e -> back e
-- | Run an IO computation asynchronously and generate a single task carrying
-- the result of the computation when it completes. See 'parallel' for notes on
-- the return value.
-- async :: IO a -> Transient r a
async io = do
mr <- parallel (SLast <$> io)
case mr of
SLast x -> return x
SError e -> back e
-- | Force an async computation to run synchronously. It can be useful in an
-- 'Alternative' composition to run the alternative only after finishing a
-- computation. Note that in Applicatives it might result in an undesired
-- serialization.
sync :: Transient r a -> Transient r a
sync x = do
setData WasRemote
r <- x
delData WasRemote
return r
-- | @spawn = freeThreads . waitEvents@
spawn :: IO a -> Transient r a
spawn = freeThreads . waitEvents
-- | An task stream generator that produces an infinite stream of tasks by
-- running an IO computation periodically at the specified time interval. The
-- task carries the result of the computation. A new task is generated only if
-- the output of the computation is different from the previous one. See
-- 'parallel' for notes on the return value.
-- sample :: Eq a => IO a -> Int -> Transient r a
sample action interval = do
v <- liftIO action
prev <- liftIO $ newIORef v
waitEvents (loop action prev) <|> async (return v)
where loop action prev = loop'
where loop' = do
threadDelay interval
v <- action
v' <- readIORef prev
if v /= v' then writeIORef prev v >> return v else loop'
-- | Run an IO action one or more times to generate a stream of tasks. The IO
-- action returns a 'StreamData'. When it returns an 'SMore' or 'SLast' a new
-- task is triggered with the result value. If the return value is 'SMore', the
-- action is run again to generate the next task, otherwise task creation
-- stops.
--
-- Unless the maximum number of threads (set with 'threads') has been reached,
-- the task is generated in a new thread and the current thread returns a void
-- task.
--parallel :: IO (StreamData b) -> Transient r StateIO (StreamData b)
parallel ioaction = callCC $ \ret -> do
cont <- get
-- !> "PARALLEL"
liftIO $ atomicModifyIORefCAS (labelth cont) $ \(_, lab) -> ((Parent, lab), ())
liftIO $ loop cont ret ioaction
was <- getData `onNothing` return NoRemote
when (was /= WasRemote) $ setData WasParallel
-- th <- liftIO myThreadId
-- return () !> ("finish",th)
empty
-- | Execute the IO action and the continuation
-- loop :: EventF ->(StreamData a -> Transient r (StreamData a)) -> IO (StreamData t) -> IO ()
loop parentc ret rec = forkMaybe parentc $ \cont -> do
-- Execute the IO computation and then the closure-continuation
liftIO $ atomicModifyIORefCAS (labelth cont) $ const ((Listener,BS.pack "wait"),())
let loop'= do
mdat <- rec `catch` \(e :: SomeException) -> return $ SError e
case mdat of
se@(SError _) -> setworker cont >> iocont se cont
SDone -> setworker cont >> iocont SDone cont
last@(SLast _) -> setworker cont >> iocont last cont
more@(SMore _) -> do
forkMaybe cont $ iocont more
loop'
where
setworker cont= liftIO $ atomicModifyIORefCAS (labelth cont) $ const ((Alive,BS.pack "work"),())
iocont dat cont = do
runTransState cont (ret dat )
return ()
loop'
return ()
where
{-# INLINABLE forkMaybe #-}
forkMaybe parent proc = do
case maxThread parent of
Nothing -> forkIt parent proc
Just sem -> do
dofork <- waitQSemB sem
if dofork then forkIt parent proc else proc parent
forkIt parent proc= do
chs <- liftIO $ newMVar []
label <- newIORef (Alive, BS.pack "work")
let cont = parent{parent=Just parent,children= chs, labelth= label}
forkFinally1 (do
th <- myThreadId
let cont'= cont{threadId=th}
when(not $ freeTh parent )$ hangThread parent cont'
-- !> ("thread created: ",th,"in",threadId parent )
proc cont')
$ \me -> do
case me of
Left e -> exceptBack cont e >> return ()
_ -> do
case maxThread cont of
Just sem -> signalQSemB sem -- !> "freed thread"
Nothing -> return ()
when(not $ freeTh parent ) $ do -- if was not a free thread
th <- myThreadId
(can,label) <- atomicModifyIORefCAS (labelth cont) $ \(l@(status,label)) ->
((if status== Alive then Dead else status, label),l)
when (can/= Parent ) $ free th parent
return ()
forkFinally1 :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally1 action and_then =
mask $ \restore -> forkIO $ Control.Exception.try (restore action) >>= and_then
free th env= do
-- return () !> ("freeing",th,"in",threadId env)
let sibling= children env
(sbs',found) <- modifyMVar sibling $ \sbs -> do
let (sbs', found) = drop [] th sbs
return (sbs',(sbs',found))
if found
then do
-- !> ("new list for",threadId env,map threadId sbs')
(typ,_) <- readIORef $ labelth env
if (null sbs' && typ /= Listener && isJust (parent env))
-- free the parent
then free (threadId env) ( fromJust $ parent env)
else return ()
-- return env
else return () -- putMVar sibling sbs
-- !> (th,"orphan")
where
drop processed th []= (processed,False)
drop processed th (ev:evts)| th == threadId ev= (processed ++ evts, True)
| otherwise= drop (ev:processed) th evts
hangThread parentProc child = do
let headpths= children parentProc
modifyMVar_ headpths $ \ths -> return (child:ths)
-- ths <- takeMVar headpths
-- putMVar headpths (child:ths)
-- !> ("hang", threadId child, threadId parentProc,map threadId ths,unsafePerformIO $ readIORef $ labelth parentProc)
-- | kill all the child threads associated with the continuation context
killChildren childs = do
ths <- modifyMVar childs $ \ths -> return ([],ths)
-- ths <- takeMVar childs
-- putMVar childs []
mapM_ (killChildren . children) ths
mapM_ (killThread . threadId) ths -- !> ("KILL", map threadId ths )
-- | Make a transient task generator from an asynchronous callback handler.
--
-- The first parameter is a callback. The second parameter is a value to be
-- returned to the callback; if the callback expects no return value it
-- can just be a @return ()@. The callback expects a setter function taking the
-- @eventdata@ as an argument and returning a value to the callback; this
-- function is supplied by 'react'.
--
-- Callbacks from foreign code can be wrapped into such a handler and hooked
-- into the transient monad using 'react'. Every time the callback is called it
-- generates a new task for the transient monad.
--
react
:: ((eventdata -> IO response) -> IO ())
-> IO response
-> Transient r eventdata
react setHandler iob= callCC $ \ret -> do
st <- get
liftIO $ setHandler $ \x -> (runTransState st $ ret x) >> iob
empty
-- | Runs a computation asynchronously without generating any events. Returns
-- 'empty' in an 'Alternative' composition.
abduce = async $ return ()
-- * non-blocking keyboard input
getLineRef= unsafePerformIO $ newTVarIO Nothing
roption= unsafePerformIO $ newMVar []
-- | Waits on stdin in a loop and triggers a new task every time the input data
-- matches the first parameter. The value contained by the task is the matched
-- value i.e. the first argument itself. The second parameter is a label for
-- the option. The label is displayed on the console when the option is
-- activated.
--
-- Note that if two independent invocations of 'option' are expecting the same
-- input, only one of them gets it and triggers a task. It cannot be
-- predicted which one gets it.
--
option :: (Typeable b, Show b, Read b, Eq b) =>
b -> String -> Transient r b
option ret message= do
let sret= show ret
liftIO $ putStrLn $ "Enter " ++ sret ++ "\tto: " ++ message
liftIO $ modifyMVar_ roption $ \msgs-> return $ sret:msgs
unsafeCoerce $ waitEvents $ getLine' (==ret)
liftIO $ putStr "\noption: " >> putStrLn (show ret)
return ret
-- | Waits on stdin and triggers a task when a console input matches the
-- predicate specified in the first argument. The second parameter is a string
-- to be displayed on the console before waiting.
--
--input :: (Typeable a, Read a,Show a) => (a -> Bool) -> String -> Transient r StateIO a
input cond prompt= input' Nothing cond prompt
--input' :: (Typeable a, Read a,Show a) => Maybe a -> (a -> Bool)
-- -> String -> Transient r StateIO a
input' mv cond prompt= Transient . const $ liftIO $do
putStr prompt >> hFlush stdout
atomically $ do
mr <- readTVar getLineRef
case mr of
Nothing -> STM.retry
Just r ->
case reads2 r of
(s,_):_ -> if cond s !> show (cond s)
then do
unsafeIOToSTM $ print s
writeTVar getLineRef Nothing !>"match"
return $ Just s
else return mv
_ -> return mv !> "return "
where
reads2 s= x where
x= if typeOf(typeOfr x) == typeOf ""
then unsafeCoerce[(s,"")]
else unsafePerformIO $ return (reads s) `catch` \(e :: SomeException) -> (return [])
typeOfr :: [(a,String)] -> a
typeOfr = undefined
-- | Non blocking `getLine` with a validator
getLine' :: (Typeable a,Read a) => (a -> Bool) -> IO a
getLine' cond= do
atomically $ do
mr <- readTVar getLineRef
case mr of
Nothing -> STM.retry
Just r ->
case reads1 r of -- !> ("received " ++ show r ++ show (unsafePerformIO myThreadId)) of
(s,_):_ -> if cond s -- !> show (cond s)
then do
writeTVar getLineRef Nothing -- !>"match"
return s
else STM.retry
_ -> STM.retry
reads1 s=x where
x= if typeOf(typeOfr x) == typeOf "" then unsafeCoerce[(s,"")] else readsPrec' 0 s
typeOfr :: [(a,String)] -> a
typeOfr = undefined
inputLoop :: IO ()
inputLoop= do
r <- getLine
-- XXX hoping that the previous value has been consumed by now.
-- otherwise its just lost by overwriting.
atomically $ writeTVar getLineRef Nothing
processLine r
inputLoop
processLine r= do
let rs = breakSlash [] r
-- XXX this blocks forever if an input is not consumed by any consumer.
-- e.g. try this "xxx/xxx" on the stdin
liftIO $ mapM_ (\ r ->
atomically $ do
-- threadDelay 1000000
t <- readTVar getLineRef
when (isJust t) STM.retry
writeTVar getLineRef $ Just r ) rs
where
breakSlash :: [String] -> String -> [String]
breakSlash [] ""= [""]
breakSlash s ""= s
breakSlash res ('\"':s)=
let (r,rest) = span(/= '\"') s
in breakSlash (res++[r]) $ tail1 rest
breakSlash res s=
let (r,rest) = span(\x -> x /= '/' && x /= ' ') s
in breakSlash (res++[r]) $ tail1 rest
tail1 []=[]
tail1 x= tail x
-- | Wait for the execution of `exit` and return the result or the exhaustion of thread activity
stay rexit= takeMVar rexit
`catch` \(e :: BlockedIndefinitelyOnMVar) -> return Nothing
newtype Exit a= Exit a deriving Typeable
-- | Runs the transient computation in a child thread and keeps the main thread
-- running until all the user threads exit or some thread invokes 'exit'.
--
-- The main thread provides facilities to accept keyboard input in a
-- non-blocking but line-oriented manner. The program reads the standard input
-- and feeds it to all the async input consumers (e.g. 'option' and 'input').
-- All async input consumers contend for each line entered on the standard
-- input and try to read it atomically. When a consumer consumes the input
-- others do not get to see it, otherwise it is left in the buffer for others
-- to consume. If nobody consumes the input, it is discarded.
--
-- A @/@ in the input line is treated as a newline.
--
-- When using asynchronous input, regular synchronous IO APIs like getLine
-- cannot be used as they will contend for the standard input along with the
-- asynchronous input thread. Instead you can use the asynchronous input APIs
-- provided by transient.
--
-- A built-in interactive command handler also reads the stdin asynchronously.
-- All available commands handled by the command handler are displayed when the
-- program is run. The following commands are available:
--
-- 1. @ps@: show threads
-- 2. @log@: inspect the log of a thread
-- 3. @end@, @exit@: terminate the program
--
-- An input not handled by the command handler can be handled by the program.
--
-- The program's command line is scanned for @-p@ or @--path@ command line
-- options. The arguments to these options are injected into the async input
-- channel as keyboard input to the program. Each line of input is separated by
-- a @/@. For example:
--
-- > foo -p ps/end
--
keep :: Typeable a => Transient r a -> IO (Maybe a)
keep mx = do
liftIO $ hSetBuffering stdout LineBuffering
rexit <- newEmptyMVar
forkIO $ do
-- liftIO $ putMVar rexit $ Right Nothing
runTransient $ do
st <- get
setData $ Exit rexit
do abduce
labelState "input"
liftIO inputLoop
<|> do
option "ps" "show threads"
liftIO $ showThreads st
<|> do
option "log" "inspect the log of a thread"
th <- input (const True) "thread number>"
ml <- liftIO $ showState th st
liftIO $ print $ fmap (\(Log _ _ log) -> reverse log) ml
<|> do
option "end" "exit"
killChilds
liftIO $ putMVar rexit Nothing
<|> unsafeCoerce mx
return ()
threadDelay 10000
execCommandLine
stay rexit
where
type1 :: Transient r a -> Either String (Maybe a)
type1= undefined
-- | Same as `keep` but does not read from the standard input, and therefore
-- the async input APIs ('option' and 'input') cannot be used in the monad.
-- However, keyboard input can still be passed via command line arguments as
-- described in 'keep'. Useful for debugging or for creating background tasks,
-- as well as to embed the Transient monad inside another computation. It
-- returns either the value returned by `exit`. or Nothing, when there are no
-- more threads running
--
keep' :: Typeable a => TransIO a -> IO (Maybe a)
keep' mx = do
liftIO $ hSetBuffering stdout LineBuffering
rexit <- newEmptyMVar
forkIO $ do
runTransient $ do
setData $ Exit rexit
mx
return ()
threadDelay 10000
forkIO $ execCommandLine
stay rexit
execCommandLine= do
args <- getArgs
let mindex = findIndex (\o -> o == "-p" || o == "--path" ) args
when (isJust mindex) $ do
let i= fromJust mindex +1
when (length args >= i) $ do
let path= args !! i
putStr "Executing: " >> print path
processLine path
-- | Exit the main thread, and thus all the Transient threads (and the
-- application if there is no more code)
-- exit :: Typeable a => a -> Transient r a
exit x= do
Exit rexit <- getSData <|> error "exit: not the type expected" `asTypeOf` type1 x
liftIO $ putMVar rexit $ Just x
stop
where
type1 :: a -> Transient r (Exit (MVar (Maybe a)))
type1= undefined
-- | If the first parameter is 'Nothing' return the second parameter otherwise
-- return the first parameter..
onNothing :: Monad m => m (Maybe b) -> m b -> m b
onNothing iox iox'= do
mx <- iox
case mx of
Just x -> return x
Nothing -> iox'
----------------------------------backtracking ------------------------
data Backtrack b= forall a r c. Backtrack{backtracking :: Maybe b
,backStack :: [(b ->Transient r c,c -> Transient r a)] }
deriving Typeable
-- | Delete all the undo actions registered till now for the given track id.
-- backCut :: (Typeable b, Show b) => b -> Transient r ()
backCut reason=
delData $ Backtrack (Just reason) []
-- | 'backCut' for the default track; equivalent to @backCut ()@.
undoCut :: Transient r ()
undoCut = backCut ()
-- | Run the action in the first parameter and register the second parameter as
-- the undo action. On undo ('back') the second parameter is called with the
-- undo track id as argument.
--
{-# NOINLINE onBack #-}
onBack :: (Typeable b, Show b) => Transient r a -> ( b -> Transient r a) -> Transient r a
onBack ac back = do
-- Backtrack mreason _ <- getData `onNothing` backStateOf (typeof bac) !> "HANDLER1"
-- r <-ac
-- case mreason !> ("mreason",mreason) of
-- Nothing -> ac
-- Just reason -> bac reason
registerBack ac back
where
typeof :: (b -> Transient r a) -> b
typeof = undefined
-- | 'onBack' for the default track; equivalent to @onBack ()@.
onUndo :: Transient r a -> Transient r a -> Transient r a
onUndo x y= onBack x (\() -> y)
-- | Register an undo action to be executed when backtracking. The first
-- parameter is a "witness" whose data type is used to uniquely identify this
-- backtracking action. The value of the witness parameter is not used.
--
--{-# NOINLINE registerUndo #-}
-- registerBack :: (Typeable a, Show a) => (a -> Transient r a) -> a -> Transient r a
registerBack ac back = callCC $ \k -> do
md <- getData `asTypeOf` (Just <$> (backStateOf $ typeof back)) !> "HANDLER"
case md of
Just (bss@(Backtrack b (bs@((back',_):_)))) ->
-- when (isNothing b) $ do
-- addrx <- addr back'
-- addrx' <- addr back -- to avoid duplicate backtracking points
-- when (addrx /= addrx') $ do return () !> "ADD"; setData $ Backtrack mwit ( (back, k): unsafeCoerce bs)
setData $ Backtrack b ( (back, k): unsafeCoerce bs)
Just (Backtrack b []) -> setData $ Backtrack b [(back , k)]
Nothing -> do
setData $ Backtrack mwit [ (back , k)] -- !> "NOTHING"
ac
where
typeof :: (b -> Transient r a) -> b
typeof = undefined
mwit= Nothing `asTypeOf` (Just $ typeof back)
addr x = liftIO $ return . hashStableName =<< (makeStableName $! x)
-- registerUndo :: Transient r a -> Transient r a
-- registerUndo f= registerBack () f
-- XXX Should we enforce retry of the same track which is being undone? If the
-- user specifies a different track would it make sense?
--
-- | For a given undo track id, stop executing more backtracking actions and
-- resume normal execution in the forward direction. Used inside an undo
-- action.
--
forward :: (Typeable b, Show b) => b -> Transient r ()
forward reason= do
Backtrack _ stack <- getData `onNothing` (backStateOf reason)
setData $ Backtrack(Nothing `asTypeOf` Just reason) stack
-- | To be used with `undo´
retry= forward ()
-- | Start the undo process for the given undo track id. Performs all the undo
-- actions registered till now in reverse order. An undo action can use
-- 'forward' to stop the undo process and resume forward execution. If there
-- are no more undo actions registered execution stops and a 'stop' action is
-- returned.
--
back :: (Typeable b, Show b) => b -> Transient r a
back reason = do
Backtrack _ cs <- getData `onNothing` backStateOf reason
let bs= Backtrack (Just reason) cs
setData bs
goBackt bs
!>"GOBACK"
where
goBackt (Backtrack _ [] )= empty !> "END"
goBackt (Backtrack Nothing _ )= error "goback: no reason"
goBackt (Backtrack (Just reason) ((handler,cont) : bs))= do
-- setData $ Backtrack (Just reason) $ tail stack
-- unsafeCoerce $ first reason !> "GOBACK2"
x <- unsafeCoerce handler reason -- !> ("RUNCLOSURE",length stack)
Backtrack mreason _ <- getData `onNothing` backStateOf reason
-- setData $ Backtrack mreason bs
-- -- !> "END RUNCLOSURE"
-- case mr of
-- Nothing -> return empty -- !> "END EXECUTION"
case mreason of
Nothing -> do
--setData $ Backtrack Nothing bs
unsafeCoerce $ cont x !> "FORWARD EXEC"
justreason -> do
setData $ Backtrack justreason bs
goBackt $ Backtrack justreason bs !> ("BACK AGAIN")
empty
backStateOf :: (Monad m, Show a, Typeable a) => a -> m (Backtrack a)
backStateOf reason= return $ Backtrack (Nothing `asTypeOf` (Just reason)) []
-- | 'back' for the default undo track; equivalent to @back ()@.
--
undo :: Transient r a
undo= back ()
------ finalization
newtype Finish= Finish String deriving Show
instance Exception Finish
-- newtype FinishReason= FinishReason (Maybe SomeException) deriving (Typeable, Show)
-- | Clear all finish actions registered till now.
-- initFinish= backCut (FinishReason Nothing)
-- | Register an action that to be run when 'finish' is called. 'onFinish' can
-- be used multiple times to register multiple actions. Actions are run in
-- reverse order. Used in infix style.
--
onFinish :: (Finish ->TransIO ()) -> TransIO ()
onFinish f= onException' (return ()) f
-- | Run the action specified in the first parameter and register the second
-- parameter as a finish action to be run when 'finish' is called. Used in
-- infix style.
--
onFinish' ::TransIO a ->(Finish ->TransIO a) -> TransIO a
onFinish' proc f= proc `onException'` f
-- | Execute all the finalization actions registered up to the last
-- 'initFinish', in reverse order and continue the execution. Either an exception or 'Nothing' can be
initFinish = cutExceptions
-- passed to 'finish'. The argument passed is made available in the 'onFinish'
-- actions invoked.
--
finish :: String -> Transient r ()
finish reason= (throwt $ Finish reason) <|> return()
noFinish= forward $ Finish ""
-- | trigger finish when the stream of data ends
checkFinalize v=
case v of
SDone -> stop
SLast x -> return x
SError e -> throwt e
SMore x -> return x
------ exceptions ---
--
-- | Install an exception handler. Handlers are executed in reverse (i.e. last in, first out) order when such exception happens in the
-- continuation. Note that multiple handlers can be installed for the same exception type.
--
-- The semantic is thus very different than the one of `Control.Exception.Base.onException`
onException :: Exception e => (e -> TransIO ()) -> TransIO ()
onException exc= return () `onException'` exc
onException' :: Exception e => TransIO a -> (e -> TransIO a) -> TransIO a
onException' mx f= onAnyException mx $ \e ->
case fromException e of
Nothing -> return $ error "do nothing,this should not be evaluated"
Just e' -> f e'
where
--onAnyException :: Transient r a -> (SomeException ->Transient r a) -> Transient r a
onAnyException mx f= ioexp `onBack` f
where
ioexp = callCC $ \cont -> do
st <- get
ioexp' $ runTransState st (mx >>=cont ) `catch` exceptBack st
ioexp' mx= do
(mx,st') <- liftIO mx
put st'
case mx of
Nothing -> empty
Just x -> return x
exceptBack st = \(e ::SomeException) -> do -- recursive catch itself
return () !> "CATCHHHHHHHHHHHHH"
runTransState st (back e )
`catch` exceptBack st
-- | Delete all the exception handlers registered till now.
cutExceptions :: Transient r ()
cutExceptions= backCut (undefined :: SomeException)
-- | Use it inside an exception handler. it stop executing any further exception
-- handlers and resume normal execution from this point on.
continue :: Transient r ()
continue = forward (undefined :: SomeException) !> "CONTINUE"
-- | catch an exception in a Transient block
--
-- The semantic is the same than `catch` but the computation and the exception handler can be multirhreaded
-- catcht1 mx exc= mx' `onBack` exc
-- where
-- mx'= Transient $ const $do
-- st <- get
-- (mx, st) <- liftIO $ runTransState st mx `catch` exceptBack st
-- put st
-- return mx
catcht :: Exception e => TransIO a -> (e -> TransIO a) -> TransIO a
catcht mx exc= do
rpassed <- liftIO $ newIORef False
sandbox $ do
delData $ Backtrack (Just (undefined :: SomeException)) []
r <- onException' mx $ \e -> do
passed <- liftIO $ readIORef rpassed
if not passed then unsafeCoerce continue >> exc e else empty
liftIO $ writeIORef rpassed True
return r
where
sandbox :: Transient r a -> Transient r a
sandbox mx= do
exState <- getData `onNothing` backStateOf (undefined :: SomeException)
mx <*** setState exState
-- | throw an exception in the Transient monad
throwt :: Exception e => e -> Transient r a
throwt= back . toException
| agocorona/transient | src/Transient/Internals.cont.hs | mit | 48,083 | 0 | 27 | 14,168 | 11,239 | 5,746 | 5,493 | 751 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.